@kosdev-code/kos-ui-sdk 2.1.29 → 2.1.31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.cjs CHANGED
@@ -28,7 +28,7 @@ Caused by: ${o.stack}`)}toDetailedString(){const s=[`KosModelError: ${this.messa
28
28
  - Parent Model: ${t.modelTypeName}
29
29
  - Parent Model ID: ${t.modelId}
30
30
  - Provided Options: ${JSON.stringify(n,null,2)}
31
- - Error: ${y}`),o===Ve.FAIL?new Error(`Dependency resolution failed (policy: FAIL) - Model ${t.modelId} cannot resolve dependency ${e.modelType} [${r}]: ${y}`):p}},sl=(t,e=x.READY)=>{var o;const s=((o=t.modelData)==null?void 0:o[F])||{};return Object.keys(s).length===0?(m.debug(`${t.modelId} has no dependencies. Returning`),[]):Object.keys(s).filter(n=>s[n].lifecycle===e).map(n=>{const i=s[n],a=tl(t,i);if(!a.success||!a.dependentModel)return m.debug(`Skipping dependency ${i.modelType} with id ${a.dataModelId} - resolution failed with CONTINUE policy`),t.modelData[n]=void 0,null;const{dependentModel:c,dataModelId:u}=a;t.modelData[n]=c.data,m.debug(`waiting for dependent model ${i.modelType} with id ${u} - waiting for WHENREADY`);const d=async(p,y,w)=>{var E;await((E=p.whenReady)==null?void 0:E.call(p)),m.debug(`dependent model ${y} with id ${w} - READY`)},{promise:h,cancel:f}=Jc(Zc,t,t.status);return Promise.race([d(c.model,i.modelType,u).then(()=>{f()}).catch(p=>{const y=$t(p,{modelType:i.modelType,modelId:u,parentModel:{type:t.modelTypeName,id:t.modelId},lifecycle:e,operation:"dependency whenReady()"});throw m.error(y.toDetailedString()),f(),y}),h])}).filter(n=>!!n)},rl=async(t,e,s,r)=>{if(m.debug(`Execute lifecycle with ${e.length} models`),e.length===0){m.debug(`${t.modelId} has no children. Returning`);return}if(!s){m.error(`${t.modelId} is not transitioning with a valid target ${s}`);return}const o=e.map(a=>{let c;return lr[s]&&a?c=lr[s](a):(a||m.error("model is undefined. This shouldn't happen"),lr[s]||m.error(`There is no promise in the Transition Map for ${s}`)),{promise:c,modelId:a==null?void 0:a.modelId,model:a,type:a==null?void 0:a.modelTypeName,status:a==null?void 0:a.status}}).filter(a=>a.promise?a.model?!0:(m.error(`No model found ${a.modelId}`),!1):(m.error(`No promise found ${a.modelId}`),!1)),n=await Promise.allSettled(o.map(a=>{var d;if(!a.model||!a.status)return Promise.resolve();const{promise:c,cancel:u}=Jc(Zc,a.model,a.status);return Promise.race([(d=a.promise)==null?void 0:d.then(()=>{u()}).catch(h=>{const f=$t(h,{modelType:a.type||"unknown",modelId:a.modelId,parentModel:{type:t.modelTypeName,id:t.modelId},lifecycle:r,operation:`transition to ${s}`});throw m.error(f.toDetailedString()),u(),f}),c])})),i=n.filter(a=>a.status==="rejected");if(i.length>0){const a=i.map(c=>{const u=o[n.indexOf(c)];return{error:c.status==="rejected"?c.reason:new Error("Unknown error"),context:{modelType:u.type||"unknown",modelId:u.modelId,parentModel:{type:t.modelTypeName,id:t.modelId},lifecycle:r,operation:`transition to ${s}`}}});Yp(a,`Model ${t.modelId} had ${i.length} failed child model(s) on ${r}`)}},ol=async(t,e,s)=>{await rl(t,t.getChildren().filter(r=>!!r),e,s)},ts=async(t,e)=>{const r=(await Promise.allSettled(sl(t,e))).filter(o=>o.status==="rejected");r.length&&(m.error(`There were ${r.length} failed dependent models on ${e}`),m.error(r))};function sg(t){const e=`KosModel(${t.modelTypeName}:${t.modelId})`;try{Object.defineProperty(t,Symbol.toStringTag,{value:e,configurable:!0})}catch{t.toString=()=>e}try{Object.defineProperty(t.constructor,"name",{value:`KosModel_${t.modelTypeName}`,configurable:!0})}catch{t.constructor.name=`KosModel_${t.modelTypeName}`}const s=["fsm","effectManager","subscriptionManager","onlineLifecycleManager","companionManager","childResolver","_offlineQueue"];for(const r of s)r in t&&Object.defineProperty(t,r,{enumerable:!1});Object.defineProperty(t,"debugState",{enumerable:!1,configurable:!0,get(){var r,o,n;return{id:t.modelId,type:t.modelTypeName,initialized:t.initialized,loaded:t.loaded,status:t.status,onlineStatus:t.onlineStatus,activeStatus:t.activeStatus,companions:(o=(r=t.companionManager)==null?void 0:r.all())==null?void 0:o.map(i=>i.modelTypeName),children:(n=t.getChildren)==null?void 0:n.call(t).map(i=>i.modelId),effects:!!t.effectManager,subs:!!t.subscriptionManager}}}),rg(t.modelData,t.modelTypeName,t.modelId,t)}function rg(t,e,s,r){Object.defineProperty(t,Symbol.toStringTag,{value:`KosModelData(${e}:${s})`,configurable:!0});try{Object.defineProperty(t.constructor,"name",{value:`${e}ModelData`,configurable:!0})}catch{t.constructor.name=`${e}ModelData`}Object.defineProperty(t,"debugState",{enumerable:!1,configurable:!0,get(){var a,c,u;const o=((a=r.getChildren)==null?void 0:a.call(r))||[],n=((c=r.companionManager)==null?void 0:c.all())||[],i=r.modelData[F]||{};return{id:s,type:e,companions:{count:n.length,data:n.map(d=>({type:d.modelTypeName,id:d.modelId}))},dependencies:{count:Object.keys(i).length,data:Object.values(i).map(d=>({id:d.id||d.modelType,type:d.modelType,options:d.options,lifecycle:d.lifecycle}))},children:{count:o.length,data:o.map(d=>({id:d.modelId,type:d.modelTypeName}))},data:((u=t.toJSON)==null?void 0:u.call(t))||{},subs:!!r.subscriptionManager}}}),Object.defineProperty(t,"toJSON",{configurable:!0,enumerable:!1,writable:!0,value:()=>{const o={};for(const n of Object.keys(t))if(!(n.startsWith("_")||typeof t[n]=="function"))try{const i=t[n];Es(i)?o[`[KOS Model] ${n}`]=typeof i.toJSON=="function"?i.toJSON():{id:i.id,type:i.constructor.name}:In(i)?o[`[KOS Container] ${n}`]=typeof i.toJSON=="function"?i.toJSON():["Container"]:Array.isArray(i)?o[n]=`[Array(${i.length})]`:typeof i=="object"&&i!==null?o[n]=JSON.parse(JSON.stringify(i)):o[n]=i}catch{o[n]="[unreadable]"}return o}})}class og{constructor(e){this.model=e}resolve(){const e=new Set([...this.getResolvedDecoratedChildren(),...this.getAdditionalChildren(),...this.model.companionModels.all()]),s=Array.from(e).map(r=>this.model.modelManager.getModelById(r.id||"")).filter(r=>r&&r.status!==v.FAILED).filter(r=>!!r);return s.forEach(r=>{try{Y.setParentContext(r.modelId,this.model.modelId)}catch(o){console.error(`Failed to set parent context for ${r.modelId} under ${this.model.modelId}`,o)}}),s}getResolvedDecoratedChildren(){var s;const e=((s=this.model.modelData)==null?void 0:s[Ge])||{};return Object.keys(e).map(r=>el(this.model.modelData[r])).filter(r=>!!r).flat()}getAdditionalChildren(){var e,s;return((s=(e=this.model.modelData)==null?void 0:e.getChildren)==null?void 0:s.call(e))||[]}}class ng{constructor(e){l(this,"companions",new M.ObservableMap);this.hostModel=e}add(e){this.companions.set(e.modelTypeName,e)}clear(){this.companions.clear()}get(e){return this.companions.get(e)}all(){return[...this.companions.values()]}get data(){return this.companions}}class ig{constructor(e,s,r,o){l(this,"disposers",[]);this.modelTypeName=e,this.modelId=s,this.modelData=r,this.log=o}setup(){var s;const e=((s=this.modelData)==null?void 0:s[at])||{};for(const r of Object.keys(e)){const{value:o,dependencies:n,options:i}=e[r],a=o.bind(this.modelData),c=()=>{this.log.info(`Running effect ${r} for ${this.modelTypeName} (${this.modelId})`),M.runInAction(()=>a())},u=n?M.reaction(()=>n(this.modelData),c,{fireImmediately:!!(i!=null&&i.fireImmediately)}):M.autorun(c);this.disposers.push(u)}}disposeAll(){for(const e of this.disposers)try{e()}catch(s){this.log.info(`Failed to dispose effect for ${this.modelId}`,s)}this.disposers=[]}}const ag=m.createLogger({name:"model-active-machine"}),cg=t=>{const e=b.createMachine(v.INACTIVE,{[v.FAILED]:b.state(b.transition(L.GO_ACTIVE,v.ACTIVATING)),[v.INACTIVE]:b.state(b.transition(L.GO_ACTIVE,v.ACTIVATING)),[v.ACTIVATING]:b.invoke(()=>(t.activeStatus=v.ACTIVATING,t.activate()),b.transition("done",v.ACTIVE,b.action(()=>{t.activeStatus=v.ACTIVE})),b.transition("error",v.FAILED,b.action(()=>{t.activeStatus=v.FAILED}))),[v.ACTIVE]:b.state(b.transition(L.GO_INACTIVE,v.DEACTIVATING)),[v.DEACTIVATING]:b.invoke(()=>(t.activeStatus=v.DEACTIVATING,t.deactivate()),b.transition("done",v.INACTIVE,b.action(()=>{t.activeStatus=v.INACTIVE})),b.transition("error",v.FAILED,b.action(()=>{t.activeStatus=v.FAILED})))});return{service:b.interpret(e,r=>ag.debug(r.machine.current)),machine:e}},Li=m.createLogger({name:"model-online-machine"}),lg=t=>{const e=b.createMachine(v.OFFLINE,{[v.ONLINE]:b.state(b.transition(L.GO_OFFLINE,v.OFFLINE,b.action(async()=>{await t.offline(),t.onlineStatus=v.OFFLINE}))),[v.OFFLINE]:b.state(b.transition(L.GO_ONLINE,v.ONLINE,b.action(async()=>{Li.debug(`Going online with model ${t.modelId}`),await t.online(),t.onlineStatus=v.ONLINE,await t.fsm.transitionTo(L.INITIALIZE,v.INITIALIZED)})))}),s=b.interpret(e,r=>Li.debug(r.machine.current));return{machine:e,service:s}},ug=t=>{var r;const e=cg(t).service,s=lg(t).service;return b.createMachine(v.CREATING,{[v.CREATING]:b.state(b.transition(L.CREATE,v.CREATED)),[v.CREATED]:b.state(b.immediate(v.INITIALIZING)),[v.INITIALIZING]:b.invoke(()=>(J(()=>{t.status=v.INITIALIZING}),t.init()),b.transition("done",v.INITIALIZED,b.action(()=>{t.status=v.INITIALIZED})),b.transition("error",v.FAILED,b.action(()=>{m.error(`Model ${t.modelId} - ${t.modelTypeName} failed to initialize. Transitioning to FAILED state.`),t.status=v.FAILED}))),[v.INITIALIZED]:b.state(b.immediate(v.LOADING)),[v.LOADING]:b.invoke(()=>(J(()=>{t.status=v.LOADING}),t.load()),b.transition("done",v.LOADED,b.action(()=>{t.status=v.LOADED})),b.transition("error",v.FAILED,b.action(()=>{t.status=v.FAILED}))),[v.LOADED]:b.state(b.immediate(v.READYING),b.transition(L.UNLOAD,v.UNLOADING)),[v.RESETTING]:b.invoke(()=>{var o;return J(()=>{t.status=v.RESETTING}),(o=t.unload)==null||o.call(t),t.load()},b.transition("done",v.LOADED,b.action(()=>{t.status=v.LOADED}))),[v.READYING]:b.invoke(()=>(J(()=>{t.status=v.READYING}),t.ready()),b.transition("done",v.READY,b.action(()=>{J(()=>{t.status=v.READY}),s.send(L.GO_ONLINE)})),b.transition("error",v.FAILED,b.action(()=>{t.status=v.FAILED}))),[v.READY]:b.state(b.transition(L.UNLOAD,v.UNLOADED,b.action((r=t.unload)==null?void 0:r.bind(t))),b.transition(L.RESET,v.RESETTING),b.transition(L.GO_ONLINE,v.READY,b.action(()=>{s.send(L.GO_ONLINE)})),b.transition(L.GO_OFFLINE,v.READY,b.action(()=>{s.send(L.GO_OFFLINE)})),b.transition(L.GO_ACTIVE,v.READY,b.action(()=>{e.send(L.GO_ACTIVE)})),b.transition(L.GO_INACTIVE,v.READY,b.action(()=>{e.send(L.GO_INACTIVE)}))),[v.UNLOADED]:b.state(),[v.FAILED]:b.state()})},dg=m.createLogger({name:"kos-model-lifecycle"}),hg=t=>({service:b.interpret(ug(t),s=>dg.debug(`state machine for model ${t.modelId}: ${s.machine.current});`))});class fg{constructor(e,s){l(this,"disposer");l(this,"service");this.model=e,this.log=s;const r=hg(e);this.service=r.service,this.service.send(L.CREATE)}get current(){return this.service.machine.current}async transitionTo(e,s,r=v.FAILED){return this.getTransitionStatusFor(s)===s?(this.log.debug(`Model ${this.model.modelId} already in state ${s}, skipping transition`),Promise.resolve()):(this.log.debug(`Transitioning model ${this.model.modelId} with event ${e} toward target ${s}`),new Promise((n,i)=>{var a;(a=this.disposer)==null||a.call(this),this.disposer=M.when(()=>{const c=this.getTransitionStatusFor(s);return c===s||c===r},()=>{this.getTransitionStatusFor(s)===r?(this.log.error(`Model ${this.model.modelId} entered error state ${r} during transition`),i(new Error(`FSM transition failed for model ${this.model.modelId} with event ${e}`))):(this.log.debug(`Model ${this.model.modelId} reached target state ${s}`),n())}),this.service.send(e)}).finally(()=>{var n;(n=this.disposer)==null||n.call(this),this.disposer=void 0}))}getTransitionStatusFor(e){return[v.ACTIVE,v.INACTIVE].includes(e)?this.model.activeStatus:this.model.status}}const nl="browser-router-model";class On{constructor(e,s){l(this,"logger");l(this,"model");l(this,"router",null);l(this,"registered",!1);l(this,"registeredRoutes",[]);this.model=e,this.logger=s}registerAll(){var s;if(!mr(this.model))return;let e=this.model.__httpBrowserRouter;if(!e)for(const r of Object.keys(this.model)){const o=this.model[r];if(o&&typeof o=="object"&&"use"in o&&typeof o.use=="function"){e=o;break}}if(e||(e=(s=$e(nl))==null?void 0:s.model),!e)throw this.logger.error("Cannot register HTTP routes: BrowserRouter not found. The HTTP decorators should have auto-injected it, but something went wrong."),new Error("BrowserRouter is required for HTTP route decorators but was not found. This should not happen as HTTP decorators auto-inject the dependency.");this.setRouter(e)}setRouter(e){this.router=e,this.registered||this.registerRoutes()}hasRoutes(){return mr(this.model)}registerRoutes(){if(!this.router){this.logger.warn("Cannot register routes: router not set");return}if(this.registered){this.logger.debug("Routes already registered");return}const e=Dc(this.model);e.length!==0&&(this.logger.debug(`Registering ${e.length} HTTP routes`),e.forEach(s=>{this.registerRoute(s)}),this.registered=!0)}resolvePropKey(e){const s=/\{PROP_([^}]+)\}/g;let r=e;if(r.includes("{MODEL_ID}")){const n=this.model.id||this.model._id||"unknown";r=r.replace(/\{MODEL_ID\}/g,n)}let o;for(;(o=s.exec(e))!==null;){const n=o[1];if(n in this.model){const i=this.model[n];r=r.replace(o[0],String(i))}else this.logger.warn(`Property '${n}' not found on model for PropKey resolution in path: ${e}`)}return r}registerRoute(e){if(!this.router)return;const s=this.model[e.handler];if(!s||typeof s!="function"){this.logger.error(`Handler method '${e.handler}' not found on model`);return}const r=this.resolvePropKey(e.path);this.logger.debug(`Registering ${e.method} ${r} -> ${e.handler}`+(r!==e.path?` (resolved from ${e.path})`:""));const o=async(n,i)=>{var a;try{await s.call(this.model,n,i)}catch(c){this.logger.error(`Error in route handler ${e.method} ${r}:`,c),(a=i.status)==null||a.call(i,500).send({error:"Internal server error",message:c instanceof Error?c.message:String(c)})}};this.checkForDuplicateRoute(e.method,r),this.router.use(e.method,r,o),this.registeredRoutes.push({method:e.method,path:r})}checkForDuplicateRoute(e,s){if(!this.router)return;this.router.getRoutes().find(n=>n.method===e&&n.path===s)&&this.logger.warn(`Duplicate route detected: ${e} ${s}. This route is already registered by another model. The new handler from model '${this.model.id||"unknown"}' will override the existing one. Only the last registered handler will receive requests. Consider using different paths or namespacing to avoid conflicts.`)}dispose(){if(this.router&&this.registeredRoutes.length>0){this.logger.debug(`Removing ${this.registeredRoutes.length} HTTP routes for model ${this.model.id||"unknown"}`);let e=0;for(const s of this.registeredRoutes){const r=this.router.remove(s.method,s.path);e+=r,r>0?this.logger.debug(`Removed route: ${s.method} ${s.path}`):this.logger.warn(`Failed to remove route: ${s.method} ${s.path} (not found)`)}this.logger.debug(`Successfully removed ${e} routes from browser router`)}this.registered=!1,this.registeredRoutes=[],this.router=null}getRegisteredRoutes(){return[...this.registeredRoutes]}}function pg(t,e){if(!mr(t))return;const s=$e(nl);if(!(s!=null&&s.model))throw e.error("Cannot register HTTP routes: BrowserRouter not found. Make sure to include BrowserRouter in your model dependencies or create an instance."),new Error("BrowserRouter is required for HTTP route decorators but was not found. Add it as a dependency using @kosDependency or ensure an instance exists.");new On(t,e).setRouter(s.model)}class gg{constructor(e){l(this,"queue",[]);this.log=e}enqueue(e,s,r){this.queue.push({handler:e,receivedAt:Date.now(),topic:s,payload:r})}flush(){if(this.queue.length!==0){this.log.warn(`Processing ${this.queue.length} offline message(s)`);for(const e of this.queue)try{e.handler()}catch(s){this.log.error("Error while processing offline message:",s)}this.queue=[],this.log.info("Offline queue flushed")}}flushWithStrategy(e,s,r){if(this.queue.length===0)return;const o=this.queue.length,n=this.filterEventsByStrategy(e,s,r),i=o-n.length;this.log.warn(`Processing ${n.length}/${o} offline message(s) with strategy: ${e}`);for(const a of n)try{a.handler()}catch(c){this.log.error(`Error while processing offline message for topic ${a.topic}:`,c)}this.queue=[],this.log.info(`Offline queue flushed with strategy ${e}. Replayed: ${n.length}, Discarded: ${i}`)}filterEventsByStrategy(e,s,r){switch(e){case it.ALL:return[...this.queue];case it.AFTER_REQUEST:return s===void 0?(this.log.warn("AFTER_REQUEST strategy requires baselineRequestedAt, replaying all events"),[...this.queue]):this.queue.filter(o=>o.receivedAt>=s);case it.AFTER_RESPONSE:return r===void 0?(this.log.warn("AFTER_RESPONSE strategy requires baselineReceivedAt, replaying all events"),[...this.queue]):this.queue.filter(o=>o.receivedAt>=r);case it.NONE:return[];default:return this.log.warn(`Unknown replay strategy: ${e}, replaying all`),[...this.queue]}}getStatistics(e,s){if(this.queue.length===0)return{total:0};const r=this.queue.map(n=>n.receivedAt),o={total:this.queue.length,oldestEventAt:Math.min(...r),newestEventAt:Math.max(...r)};return e!==void 0&&(o.afterRequest=this.queue.filter(n=>n.receivedAt>=e).length),s!==void 0&&(o.afterResponse=this.queue.filter(n=>n.receivedAt>=s).length),o}clear(){this.queue=[]}get length(){return this.queue.length}get isEmpty(){return this.queue.length===0}}class mg{constructor(e,s){l(this,"unsubscribers",[]);this.model=e,this.log=s}register(){const e=this.model.modelId,s=C("/kosCore/online",async()=>{this.log.debug(`Online event received for ${e}, waiting for readiness...`),await this.model.whenReady(),this.log.debug(`${e} is ready — sending GO_ONLINE`),await this.model.fsm.transitionTo(L.GO_ONLINE,v.ONLINE)}),r=C("/kosCore/offline",async()=>{this.log.debug(`Offline event received for ${e} — sending GO_OFFLINE`),await this.model.fsm.transitionTo(L.GO_OFFLINE,v.OFFLINE)});this.unsubscribers.push(s.unsubscribe),this.unsubscribers.push(r.unsubscribe)}dispose(){this.unsubscribers.forEach(e=>e()),this.unsubscribers=[]}}const il=()=>({isMock:!1,URL:exports.BASE_URL}),yg=m.createLogger({name:"kos-service-request"}),bg="errUnknown";async function Js(t,e,s,r,o){const n=r!=null&&r.path?Object.keys(r.path).reduce((h,f)=>String(h).replace(`{${f}}`,r==null?void 0:r.path[f]),String(t)):String(t),i=r!=null&&r.query?Object.keys(r.query).map(h=>`${h}=${r.query[h]}`).join("&"):"",a=`${il().URL}${n}${i?`?${encodeURIComponent(i)}`:""}`;yg.debug(`fullUrl: ${a}`);const c={method:String(e).toUpperCase(),body:null,...s};o&&(c.body=JSON.stringify(o));const u=await exports.kosFetch(a,c);return u.status<200||u.status>=400?[`${u.statusText||bg}`,null]:[null,(await u.json()).data]}function Be(){return{get:(t,e,s)=>Js(t,"get",s,e),post:(t,e,s,r)=>Js(t,"post",r,e,s),put:(t,e,s,r)=>Js(t,"put",r,e,s),delete:(t,e,s,r)=>Js(t,"delete",r,e,s)}}const Ae=Be(),al=Object.freeze(Object.defineProperty({__proto__:null,default:Ae},Symbol.toStringTag,{value:"Module"})),st=m.createLogger({name:"kos-service-request-manager",group:"Model"});function vg(t,e){return!t.condition||t.condition(e)}function wg(t,e){return Me({value:t.path,modelId:e.id,modelData:e})}function Eg(t,e){if(t.pathParams)return Me({value:typeof t.pathParams=="function"?t.pathParams(e):t.pathParams,modelId:e.id,modelData:e})}function Mg(t,e){if(t.queryParams)return Me({value:typeof t.queryParams=="function"?t.queryParams(e):t.queryParams,modelId:e.id,modelData:e})}function Tg(t,e){if(t.body)return Me({value:typeof t.body=="function"?t.body(e):t.body,modelId:e.id,modelData:e})}function _g(t){return(t||"get").toLowerCase()}function Fi(t,e){return`${e.toUpperCase()}:${t}`}function cl(t){return t==null}function Sg(t,e,s,r){r&&cl(t)&&st.warn(`Required field '${e}' is missing in response for ${s}`)}function Ig(t,e){return cl(t)&&e!==void 0?e:t}class Og{constructor(e,s){l(this,"model");l(this,"responseStore");l(this,"handlers");this.model=e,this.responseStore=s,this.handlers=new Map,this.discoverHandlers()}discoverHandlers(){const s=Object.getPrototypeOf(this.model)[ct]||{};Object.values(s).forEach(r=>{const o=r.lifecycle;this.handlers.has(o)||this.handlers.set(o,[]),this.handlers.get(o).push(r)}),Object.keys(s).length>0&&st.debug(`Discovered ${Object.keys(s).length} service request handlers for model ${this.model.id}`)}async executeForLifecycle(e){const s=this.handlers.get(e);!s||s.length===0||(st.debug(`Executing ${s.length} service requests for lifecycle ${e}`),await Promise.all(s.map(r=>this.executeHandler(r))))}async executeHandler(e){try{if(!this.shouldProcessRequest(e))return;const s=await this.prepareAndExecuteRequest(e);await this.processAndStoreResponse(s,e)}catch(s){const r=s instanceof Error?s:new Error(String(s));await this.handleError(r,e)}}shouldProcessRequest(e){return vg(e,this.model)?!0:(st.debug(`Skipping request ${e.path} - condition returned false`),!1)}async prepareAndExecuteRequest(e){const s=this.prepareRequest(e),r=this.captureRequestTiming(),[o,n]=await this.performRequest(s),i=this.captureResponseTiming();return{requestContext:s,error:o,response:n,requestedAt:r.requestedAt,receivedAt:i.receivedAt}}captureRequestTiming(){return{requestedAt:Date.now()}}captureResponseTiming(){return{receivedAt:Date.now()}}async processAndStoreResponse(e,s){if(e.error){await this.handleError(new Error(e.error),s);return}const r=await this.processResponse(e.response,s);await this.storeAndInvokeHandler(r,s,e.requestContext.resolvedPath,e.requestedAt,e.receivedAt)}prepareRequest(e){const s=wg(e,this.model),r=Eg(e,this.model),o=Mg(e,this.model),n=Tg(e,this.model),i=_g(e.method);return{resolvedPath:s,method:i,pathParams:r,queryParams:o,body:n}}async performRequest(e){return await this.makeRequest(e.resolvedPath,e.method,{path:e.pathParams,query:e.queryParams},e.body)}async processResponse(e,s){let r=e;return s.transform&&(r=s.transform(e)),s.mappings&&s.mappings.length>0&&(r=this.applyMappings(r,s)),s.iterateOver&&(r=await this.handleIteration(r,s)),r}async storeAndInvokeHandler(e,s,r,o,n){const i=s.cache||{retention:de.SINGLE},a=Fi(r,s.method||"get");this.responseStore.set(a,e,i,o,n),await s.originalHandler.call(this.model,e),this.triggerBaselineQueueFlush(r),this.responseStore.shouldCleanupAfterHandler(a)&&this.responseStore.delete(a)}triggerBaselineQueueFlush(e){const s=this.model.subscriptionManager;!s||!s.flushQueueForBaseline||s.flushQueueForBaseline(e)}async makeRequest(e,s,r,o){const n=Ae;switch(s){case"get":return await n.get(e,r);case"post":return await n.post(e,r,o);case"put":return await n.put(e,r,o);case"delete":return await n.delete(e,r,o);default:return[`Unsupported HTTP method: ${s}`,null]}}applyMappings(e,s){if(!s.mappings||s.mappings.length===0)return e;const r={};return s.mappings.forEach(o=>{const n=this.getNestedValue(e,o.from),i=o.transform?this.applyTransform(n,o.transform):n;Sg(i,o.from,s.path,o.required||!1);const a=Ig(i,o.default);r[o.to]=a}),r}getNestedValue(e,s){return s.split(".").reduce((r,o)=>r==null?void 0:r[o],e)}applyTransform(e,s){if(typeof s=="function")return s(e);switch(s){case"string":return String(e);case"number":return Number(e);case"boolean":return!!e;case"date":return e?new Date(e):void 0;case"json":return typeof e=="string"?JSON.parse(e):e;default:return st.warn(`Unknown transformer: ${s}`),e}}async handleIteration(e,s){if(!s.iterateOver)return e;const r=this.getNestedValue(e,s.iterateOver);return Array.isArray(r)?s.modelFactory?r.map(o=>{const n=s.mappings&&s.mappings.length>0?this.applyMappings(o,s):o,i=s.idExtractor?s.idExtractor(n):n.id;if(!i)throw new Error("Cannot create model instance: no ID found in response data. Provide an 'idExtractor' function or ensure response items have an 'id' field.");const a=s.modelFactory;return typeof a=="function"?a(i)(n):a.instance(i).options(n).build()}):r.map(o=>s.mappings&&s.mappings.length>0?this.applyMappings(o,s):o):(st.warn(`iterateOver path '${s.iterateOver}' did not resolve to an array`),[])}async handleError(e,s){const r=s.errorHandler||{strategy:"throw"};switch(r.onError&&r.onError(e,this.model),r.strategy){case"throw":throw e;case"log":st.error(`Service request failed for ${s.path}:`,e.message);break;case"ignore":break;case"default":if(r.defaultValue!==void 0){const o=Fi(s.path,s.method||"get");this.responseStore.set(o,r.defaultValue,s.cache||{retention:de.SINGLE})}break}}}class $g{constructor(e){l(this,"subscription");l(this,"unsubscribe");l(this,"eventType");this.eventType=e,this.subscription={queue:[],resolvers:[],closed:!1};const s=C(e,r=>{if(!this.subscription.closed&&r!==void 0){const o=this.subscription.resolvers.shift();o?o(r):this.subscription.queue.push(r)}});this.unsubscribe=s.unsubscribe}async next(){return this.subscription.closed&&this.subscription.queue.length===0?{done:!0,value:void 0}:this.subscription.queue.length>0?{done:!1,value:this.subscription.queue.shift()}:new Promise(e=>{this.subscription.closed?e({done:!0,value:void 0}):this.subscription.resolvers.push(s=>{e({done:!1,value:s})})})}async return(){return this.subscription.closed=!0,this.unsubscribe(),this.subscription.resolvers.forEach(e=>{e(void 0)}),this.subscription.resolvers=[],{done:!0,value:void 0}}async throw(e){throw this.subscription.closed=!0,this.unsubscribe(),e}[Symbol.asyncIterator](){return this}}function Ni(t){return new $g(t)}const ll=({path:t,requestId:e,method:s,destinationAddress:r})=>{let o=`${Kr}:${s}
31
+ - Error: ${y}`),o===Ve.FAIL?new Error(`Dependency resolution failed (policy: FAIL) - Model ${t.modelId} cannot resolve dependency ${e.modelType} [${r}]: ${y}`):p}},sl=(t,e=x.READY)=>{var o;const s=((o=t.modelData)==null?void 0:o[F])||{};return Object.keys(s).length===0?(m.debug(`${t.modelId} has no dependencies. Returning`),[]):Object.keys(s).filter(n=>s[n].lifecycle===e).map(n=>{const i=s[n],a=tl(t,i);if(!a.success||!a.dependentModel)return m.debug(`Skipping dependency ${i.modelType} with id ${a.dataModelId} - resolution failed with CONTINUE policy`),t.modelData[n]=void 0,null;const{dependentModel:c,dataModelId:u}=a;t.modelData[n]=c.data,m.debug(`waiting for dependent model ${i.modelType} with id ${u} - waiting for WHENREADY`);const d=async(p,y,w)=>{var E;await((E=p.whenReady)==null?void 0:E.call(p)),m.debug(`dependent model ${y} with id ${w} - READY`)},{promise:h,cancel:f}=Jc(Zc,t,t.status);return Promise.race([d(c.model,i.modelType,u).then(()=>{f()}).catch(p=>{const y=$t(p,{modelType:i.modelType,modelId:u,parentModel:{type:t.modelTypeName,id:t.modelId},lifecycle:e,operation:"dependency whenReady()"});throw m.error(y.toDetailedString()),f(),y}),h])}).filter(n=>!!n)},rl=async(t,e,s,r)=>{if(m.debug(`Execute lifecycle with ${e.length} models`),e.length===0){m.debug(`${t.modelId} has no children. Returning`);return}if(!s){m.error(`${t.modelId} is not transitioning with a valid target ${s}`);return}const o=e.map(a=>{let c;return lr[s]&&a?c=lr[s](a):(a||m.error("model is undefined. This shouldn't happen"),lr[s]||m.error(`There is no promise in the Transition Map for ${s}`)),{promise:c,modelId:a==null?void 0:a.modelId,model:a,type:a==null?void 0:a.modelTypeName,status:a==null?void 0:a.status}}).filter(a=>a.promise?a.model?!0:(m.error(`No model found ${a.modelId}`),!1):(m.error(`No promise found ${a.modelId}`),!1)),n=await Promise.allSettled(o.map(a=>{var d;if(!a.model||!a.status)return Promise.resolve();const{promise:c,cancel:u}=Jc(Zc,a.model,a.status);return Promise.race([(d=a.promise)==null?void 0:d.then(()=>{u()}).catch(h=>{const f=$t(h,{modelType:a.type||"unknown",modelId:a.modelId,parentModel:{type:t.modelTypeName,id:t.modelId},lifecycle:r,operation:`transition to ${s}`});throw m.error(f.toDetailedString()),u(),f}),c])})),i=n.filter(a=>a.status==="rejected");if(i.length>0){const a=i.map(c=>{const u=o[n.indexOf(c)];return{error:c.status==="rejected"?c.reason:new Error("Unknown error"),context:{modelType:u.type||"unknown",modelId:u.modelId,parentModel:{type:t.modelTypeName,id:t.modelId},lifecycle:r,operation:`transition to ${s}`}}});Yp(a,`Model ${t.modelId} had ${i.length} failed child model(s) on ${r}`)}},ol=async(t,e,s)=>{await rl(t,t.getChildren().filter(r=>!!r),e,s)},ts=async(t,e)=>{const r=(await Promise.allSettled(sl(t,e))).filter(o=>o.status==="rejected");r.length&&(m.error(`There were ${r.length} failed dependent models on ${e}`),m.error(r))};function sg(t){const e=`KosModel(${t.modelTypeName}:${t.modelId})`;try{Object.defineProperty(t,Symbol.toStringTag,{value:e,configurable:!0})}catch{t.toString=()=>e}try{Object.defineProperty(t.constructor,"name",{value:`KosModel_${t.modelTypeName}`,configurable:!0})}catch{t.constructor.name=`KosModel_${t.modelTypeName}`}const s=["fsm","effectManager","subscriptionManager","onlineLifecycleManager","companionManager","childResolver","_offlineQueue"];for(const r of s)r in t&&Object.defineProperty(t,r,{enumerable:!1});Object.defineProperty(t,"debugState",{enumerable:!1,configurable:!0,get(){var r,o,n;return{id:t.modelId,type:t.modelTypeName,initialized:t.initialized,loaded:t.loaded,status:t.status,onlineStatus:t.onlineStatus,activeStatus:t.activeStatus,companions:(o=(r=t.companionManager)==null?void 0:r.all())==null?void 0:o.map(i=>i.modelTypeName),children:(n=t.getChildren)==null?void 0:n.call(t).map(i=>i.modelId),effects:!!t.effectManager,subs:!!t.subscriptionManager}}}),rg(t.modelData,t.modelTypeName,t.modelId,t)}function rg(t,e,s,r){Object.defineProperty(t,Symbol.toStringTag,{value:`KosModelData(${e}:${s})`,configurable:!0});try{Object.defineProperty(t.constructor,"name",{value:`${e}ModelData`,configurable:!0})}catch{t.constructor.name=`${e}ModelData`}Object.defineProperty(t,"debugState",{enumerable:!1,configurable:!0,get(){var a,c,u;const o=((a=r.getChildren)==null?void 0:a.call(r))||[],n=((c=r.companionManager)==null?void 0:c.all())||[],i=r.modelData[F]||{};return{id:s,type:e,companions:{count:n.length,data:n.map(d=>({type:d.modelTypeName,id:d.modelId}))},dependencies:{count:Object.keys(i).length,data:Object.values(i).map(d=>({id:d.id||d.modelType,type:d.modelType,options:d.options,lifecycle:d.lifecycle}))},children:{count:o.length,data:o.map(d=>({id:d.modelId,type:d.modelTypeName}))},data:((u=t.toJSON)==null?void 0:u.call(t))||{},subs:!!r.subscriptionManager}}}),Object.defineProperty(t,"toJSON",{configurable:!0,enumerable:!1,writable:!0,value:()=>{const o={};for(const n of Object.keys(t))if(!(n.startsWith("_")||typeof t[n]=="function"))try{const i=t[n];Es(i)?o[`[KOS Model] ${n}`]=typeof i.toJSON=="function"?i.toJSON():{id:i.id,type:i.constructor.name}:In(i)?o[`[KOS Container] ${n}`]=typeof i.toJSON=="function"?i.toJSON():["Container"]:Array.isArray(i)?o[n]=`[Array(${i.length})]`:typeof i=="object"&&i!==null?o[n]=JSON.parse(JSON.stringify(i)):o[n]=i}catch{o[n]="[unreadable]"}return o}})}class og{constructor(e){this.model=e}resolve(){const e=new Set([...this.getResolvedDecoratedChildren(),...this.getAdditionalChildren(),...this.model.companionModels.all()]),s=Array.from(e).map(r=>this.model.modelManager.getModelById(r.id||"")).filter(r=>r&&r.status!==v.FAILED).filter(r=>!!r);return s.forEach(r=>{try{Y.setParentContext(r.modelId,this.model.modelId)}catch(o){console.error(`Failed to set parent context for ${r.modelId} under ${this.model.modelId}`,o)}}),s}getResolvedDecoratedChildren(){var s;const e=((s=this.model.modelData)==null?void 0:s[Ge])||{};return Object.keys(e).map(r=>el(this.model.modelData[r])).filter(r=>!!r).flat()}getAdditionalChildren(){var e,s;return((s=(e=this.model.modelData)==null?void 0:e.getChildren)==null?void 0:s.call(e))||[]}}class ng{constructor(e){l(this,"companions",new M.ObservableMap);this.hostModel=e}add(e){this.companions.set(e.modelTypeName,e)}clear(){this.companions.clear()}get(e){return this.companions.get(e)}all(){return[...this.companions.values()]}get data(){return this.companions}}class ig{constructor(e,s,r,o){l(this,"disposers",[]);this.modelTypeName=e,this.modelId=s,this.modelData=r,this.log=o}setup(){var s;const e=((s=this.modelData)==null?void 0:s[at])||{};for(const r of Object.keys(e)){const{value:o,dependencies:n,options:i}=e[r],a=o.bind(this.modelData),c=()=>{this.log.info(`Running effect ${r} for ${this.modelTypeName} (${this.modelId})`),M.runInAction(()=>a())},u=n?M.reaction(()=>n(this.modelData),c,{fireImmediately:!!(i!=null&&i.fireImmediately)}):M.autorun(c);this.disposers.push(u)}}disposeAll(){for(const e of this.disposers)try{e()}catch(s){this.log.info(`Failed to dispose effect for ${this.modelId}`,s)}this.disposers=[]}}const ag=m.createLogger({name:"model-active-machine"}),cg=t=>{const e=b.createMachine(v.INACTIVE,{[v.FAILED]:b.state(b.transition(L.GO_ACTIVE,v.ACTIVATING)),[v.INACTIVE]:b.state(b.transition(L.GO_ACTIVE,v.ACTIVATING)),[v.ACTIVATING]:b.invoke(()=>(t.activeStatus=v.ACTIVATING,t.activate()),b.transition("done",v.ACTIVE,b.action(()=>{t.activeStatus=v.ACTIVE})),b.transition("error",v.FAILED,b.action(()=>{t.activeStatus=v.FAILED}))),[v.ACTIVE]:b.state(b.transition(L.GO_INACTIVE,v.DEACTIVATING)),[v.DEACTIVATING]:b.invoke(()=>(t.activeStatus=v.DEACTIVATING,t.deactivate()),b.transition("done",v.INACTIVE,b.action(()=>{t.activeStatus=v.INACTIVE})),b.transition("error",v.FAILED,b.action(()=>{t.activeStatus=v.FAILED})))});return{service:b.interpret(e,r=>ag.debug(r.machine.current)),machine:e}},Li=m.createLogger({name:"model-online-machine"}),lg=t=>{const e=b.createMachine(v.OFFLINE,{[v.ONLINE]:b.state(b.transition(L.GO_OFFLINE,v.OFFLINE,b.action(async()=>{await t.offline(),t.onlineStatus=v.OFFLINE}))),[v.OFFLINE]:b.state(b.transition(L.GO_ONLINE,v.ONLINE,b.action(async()=>{Li.debug(`Going online with model ${t.modelId}`),await t.online(),t.onlineStatus=v.ONLINE,await t.fsm.transitionTo(L.INITIALIZE,v.INITIALIZED)})))}),s=b.interpret(e,r=>Li.debug(r.machine.current));return{machine:e,service:s}},ug=t=>{var r;const e=cg(t).service,s=lg(t).service;return b.createMachine(v.CREATING,{[v.CREATING]:b.state(b.transition(L.CREATE,v.CREATED)),[v.CREATED]:b.state(b.immediate(v.INITIALIZING)),[v.INITIALIZING]:b.invoke(()=>(J(()=>{t.status=v.INITIALIZING}),t.init()),b.transition("done",v.INITIALIZED,b.action(()=>{t.status=v.INITIALIZED})),b.transition("error",v.FAILED,b.action(()=>{m.error(`Model ${t.modelId} - ${t.modelTypeName} failed to initialize. Transitioning to FAILED state.`),t.status=v.FAILED}))),[v.INITIALIZED]:b.state(b.immediate(v.LOADING)),[v.LOADING]:b.invoke(()=>(J(()=>{t.status=v.LOADING}),t.load()),b.transition("done",v.LOADED,b.action(()=>{t.status=v.LOADED})),b.transition("error",v.FAILED,b.action(()=>{t.status=v.FAILED}))),[v.LOADED]:b.state(b.immediate(v.READYING),b.transition(L.UNLOAD,v.UNLOADING)),[v.RESETTING]:b.invoke(()=>{var o;return J(()=>{t.status=v.RESETTING}),(o=t.unload)==null||o.call(t),t.load()},b.transition("done",v.LOADED,b.action(()=>{t.status=v.LOADED}))),[v.READYING]:b.invoke(()=>(J(()=>{t.status=v.READYING}),t.ready()),b.transition("done",v.READY,b.action(()=>{J(()=>{t.status=v.READY}),s.send(L.GO_ONLINE)})),b.transition("error",v.FAILED,b.action(()=>{t.status=v.FAILED}))),[v.READY]:b.state(b.transition(L.UNLOAD,v.UNLOADED,b.action((r=t.unload)==null?void 0:r.bind(t))),b.transition(L.RESET,v.RESETTING),b.transition(L.GO_ONLINE,v.READY,b.action(()=>{s.send(L.GO_ONLINE)})),b.transition(L.GO_OFFLINE,v.READY,b.action(()=>{s.send(L.GO_OFFLINE)})),b.transition(L.GO_ACTIVE,v.READY,b.action(()=>{e.send(L.GO_ACTIVE)})),b.transition(L.GO_INACTIVE,v.READY,b.action(()=>{e.send(L.GO_INACTIVE)}))),[v.UNLOADED]:b.state(),[v.FAILED]:b.state()})},dg=m.createLogger({name:"kos-model-lifecycle"}),hg=t=>({service:b.interpret(ug(t),s=>dg.debug(`state machine for model ${t.modelId}: ${s.machine.current});`))});class fg{constructor(e,s){l(this,"disposer");l(this,"service");this.model=e,this.log=s;const r=hg(e);this.service=r.service,this.service.send(L.CREATE)}get current(){return this.service.machine.current}async transitionTo(e,s,r=v.FAILED){return this.getTransitionStatusFor(s)===s?(this.log.debug(`Model ${this.model.modelId} already in state ${s}, skipping transition`),Promise.resolve()):(this.log.debug(`Transitioning model ${this.model.modelId} with event ${e} toward target ${s}`),new Promise((n,i)=>{var a;(a=this.disposer)==null||a.call(this),this.disposer=M.when(()=>{const c=this.getTransitionStatusFor(s);return c===s||c===r},()=>{this.getTransitionStatusFor(s)===r?(this.log.error(`Model ${this.model.modelId} entered error state ${r} during transition`),i(new Error(`FSM transition failed for model ${this.model.modelId} with event ${e}`))):(this.log.debug(`Model ${this.model.modelId} reached target state ${s}`),n())}),this.service.send(e)}).finally(()=>{var n;(n=this.disposer)==null||n.call(this),this.disposer=void 0}))}getTransitionStatusFor(e){return[v.ACTIVE,v.INACTIVE].includes(e)?this.model.activeStatus:this.model.status}}const nl="browser-router-model";class On{constructor(e,s){l(this,"logger");l(this,"model");l(this,"router",null);l(this,"registered",!1);l(this,"registeredRoutes",[]);this.model=e,this.logger=s}registerAll(){var s;if(!mr(this.model))return;let e=this.model.__httpBrowserRouter;if(!e)for(const r of Object.keys(this.model)){const o=this.model[r];if(o&&typeof o=="object"&&"use"in o&&typeof o.use=="function"){e=o;break}}if(e||(e=(s=$e(nl))==null?void 0:s.model),!e)throw this.logger.error("Cannot register HTTP routes: BrowserRouter not found. The HTTP decorators should have auto-injected it, but something went wrong."),new Error("BrowserRouter is required for HTTP route decorators but was not found. This should not happen as HTTP decorators auto-inject the dependency.");this.setRouter(e)}setRouter(e){this.router=e,this.registered||this.registerRoutes()}hasRoutes(){return mr(this.model)}registerRoutes(){if(!this.router){this.logger.warn("Cannot register routes: router not set");return}if(this.registered){this.logger.debug("Routes already registered");return}const e=Dc(this.model);e.length!==0&&(this.logger.debug(`Registering ${e.length} HTTP routes`),e.forEach(s=>{this.registerRoute(s)}),this.registered=!0)}resolvePropKey(e){const s=/\{PROP_([^}]+)\}/g;let r=e;if(r.includes("{MODEL_ID}")){const n=this.model.id||this.model._id||"unknown";r=r.replace(/\{MODEL_ID\}/g,n)}let o;for(;(o=s.exec(e))!==null;){const n=o[1];if(n in this.model){const i=this.model[n];r=r.replace(o[0],String(i))}else this.logger.warn(`Property '${n}' not found on model for PropKey resolution in path: ${e}`)}return r}registerRoute(e){if(!this.router)return;const s=this.model[e.handler];if(!s||typeof s!="function"){this.logger.error(`Handler method '${e.handler}' not found on model`);return}const r=this.resolvePropKey(e.path);this.logger.debug(`Registering ${e.method} ${r} -> ${e.handler}`+(r!==e.path?` (resolved from ${e.path})`:""));const o=async(n,i)=>{var a;try{await s.call(this.model,n,i)}catch(c){this.logger.error(`Error in route handler ${e.method} ${r}:`,c),(a=i.status)==null||a.call(i,500).send({error:"Internal server error",message:c instanceof Error?c.message:String(c)})}};this.checkForDuplicateRoute(e.method,r),this.router.use(e.method,r,o),this.registeredRoutes.push({method:e.method,path:r})}checkForDuplicateRoute(e,s){if(!this.router)return;this.router.getRoutes().find(n=>n.method===e&&n.path===s)&&this.logger.warn(`Duplicate route detected: ${e} ${s}. This route is already registered by another model. The new handler from model '${this.model.id||"unknown"}' will override the existing one. Only the last registered handler will receive requests. Consider using different paths or namespacing to avoid conflicts.`)}dispose(){if(this.router&&this.registeredRoutes.length>0){this.logger.debug(`Removing ${this.registeredRoutes.length} HTTP routes for model ${this.model.id||"unknown"}`);let e=0;for(const s of this.registeredRoutes){const r=this.router.remove(s.method,s.path);e+=r,r>0?this.logger.debug(`Removed route: ${s.method} ${s.path}`):this.logger.warn(`Failed to remove route: ${s.method} ${s.path} (not found)`)}this.logger.debug(`Successfully removed ${e} routes from browser router`)}this.registered=!1,this.registeredRoutes=[],this.router=null}getRegisteredRoutes(){return[...this.registeredRoutes]}}function pg(t,e){if(!mr(t))return;const s=$e(nl);if(!(s!=null&&s.model))throw e.error("Cannot register HTTP routes: BrowserRouter not found. Make sure to include BrowserRouter in your model dependencies or create an instance."),new Error("BrowserRouter is required for HTTP route decorators but was not found. Add it as a dependency using @kosDependency or ensure an instance exists.");new On(t,e).setRouter(s.model)}class gg{constructor(e){l(this,"queue",[]);this.log=e}enqueue(e,s,r){this.queue.push({handler:e,receivedAt:Date.now(),topic:s,payload:r})}flush(){if(this.queue.length!==0){this.log.warn(`Processing ${this.queue.length} offline message(s)`);for(const e of this.queue)try{e.handler()}catch(s){this.log.error("Error while processing offline message:",s)}this.queue=[],this.log.info("Offline queue flushed")}}flushWithStrategy(e,s,r){if(this.queue.length===0)return;const o=this.queue.length,n=this.filterEventsByStrategy(e,s,r),i=o-n.length;this.log.warn(`Processing ${n.length}/${o} offline message(s) with strategy: ${e}`);for(const a of n)try{a.handler()}catch(c){this.log.error(`Error while processing offline message for topic ${a.topic}:`,c)}this.queue=[],this.log.info(`Offline queue flushed with strategy ${e}. Replayed: ${n.length}, Discarded: ${i}`)}filterEventsByStrategy(e,s,r){switch(e){case it.ALL:return[...this.queue];case it.AFTER_REQUEST:return s===void 0?(this.log.warn("AFTER_REQUEST strategy requires baselineRequestedAt, replaying all events"),[...this.queue]):this.queue.filter(o=>o.receivedAt>=s);case it.AFTER_RESPONSE:return r===void 0?(this.log.warn("AFTER_RESPONSE strategy requires baselineReceivedAt, replaying all events"),[...this.queue]):this.queue.filter(o=>o.receivedAt>=r);case it.NONE:return[];default:return this.log.warn(`Unknown replay strategy: ${e}, replaying all`),[...this.queue]}}getStatistics(e,s){if(this.queue.length===0)return{total:0};const r=this.queue.map(n=>n.receivedAt),o={total:this.queue.length,oldestEventAt:Math.min(...r),newestEventAt:Math.max(...r)};return e!==void 0&&(o.afterRequest=this.queue.filter(n=>n.receivedAt>=e).length),s!==void 0&&(o.afterResponse=this.queue.filter(n=>n.receivedAt>=s).length),o}clear(){this.queue=[]}get length(){return this.queue.length}get isEmpty(){return this.queue.length===0}}class mg{constructor(e,s){l(this,"unsubscribers",[]);this.model=e,this.log=s}register(){const e=this.model.modelId,s=C("/kosCore/online",async()=>{this.log.debug(`Online event received for ${e}, waiting for readiness...`),await this.model.whenReady(),this.log.debug(`${e} is ready — sending GO_ONLINE`),await this.model.fsm.transitionTo(L.GO_ONLINE,v.ONLINE)}),r=C("/kosCore/offline",async()=>{this.log.debug(`Offline event received for ${e} — sending GO_OFFLINE`),await this.model.fsm.transitionTo(L.GO_OFFLINE,v.OFFLINE)});this.unsubscribers.push(s.unsubscribe),this.unsubscribers.push(r.unsubscribe)}dispose(){this.unsubscribers.forEach(e=>e()),this.unsubscribers=[]}}const il=()=>({isMock:!1,URL:exports.BASE_URL}),yg=m.createLogger({name:"kos-service-request"}),bg="errUnknown";async function Js(t,e,s,r,o){const n=r!=null&&r.path?Object.keys(r.path).reduce((h,f)=>String(h).replace(`{${f}}`,r==null?void 0:r.path[f]),String(t)):String(t),i=r!=null&&r.query?Object.keys(r.query).map(h=>`${encodeURIComponent(h)}=${encodeURIComponent(r.query[h])}`).join("&"):"",a=`${il().URL}${n}${i?`?${i}`:""}`;yg.debug(`fullUrl: ${a}`);const c={method:String(e).toUpperCase(),body:null,...s};o&&(c.body=JSON.stringify(o));const u=await exports.kosFetch(a,c);return u.status<200||u.status>=400?[`${u.statusText||bg}`,null]:[null,(await u.json()).data]}function Be(){return{get:(t,e,s)=>Js(t,"get",s,e),post:(t,e,s,r)=>Js(t,"post",r,e,s),put:(t,e,s,r)=>Js(t,"put",r,e,s),delete:(t,e,s,r)=>Js(t,"delete",r,e,s)}}const Ae=Be(),al=Object.freeze(Object.defineProperty({__proto__:null,default:Ae},Symbol.toStringTag,{value:"Module"})),st=m.createLogger({name:"kos-service-request-manager",group:"Model"});function vg(t,e){return!t.condition||t.condition(e)}function wg(t,e){return Me({value:t.path,modelId:e.id,modelData:e})}function Eg(t,e){if(t.pathParams)return Me({value:typeof t.pathParams=="function"?t.pathParams(e):t.pathParams,modelId:e.id,modelData:e})}function Mg(t,e){if(t.queryParams)return Me({value:typeof t.queryParams=="function"?t.queryParams(e):t.queryParams,modelId:e.id,modelData:e})}function Tg(t,e){if(t.body)return Me({value:typeof t.body=="function"?t.body(e):t.body,modelId:e.id,modelData:e})}function _g(t){return(t||"get").toLowerCase()}function Fi(t,e){return`${e.toUpperCase()}:${t}`}function cl(t){return t==null}function Sg(t,e,s,r){r&&cl(t)&&st.warn(`Required field '${e}' is missing in response for ${s}`)}function Ig(t,e){return cl(t)&&e!==void 0?e:t}class Og{constructor(e,s){l(this,"model");l(this,"responseStore");l(this,"handlers");this.model=e,this.responseStore=s,this.handlers=new Map,this.discoverHandlers()}discoverHandlers(){const s=Object.getPrototypeOf(this.model)[ct]||{};Object.values(s).forEach(r=>{const o=r.lifecycle;this.handlers.has(o)||this.handlers.set(o,[]),this.handlers.get(o).push(r)}),Object.keys(s).length>0&&st.debug(`Discovered ${Object.keys(s).length} service request handlers for model ${this.model.id}`)}async executeForLifecycle(e){const s=this.handlers.get(e);!s||s.length===0||(st.debug(`Executing ${s.length} service requests for lifecycle ${e}`),await Promise.all(s.map(r=>this.executeHandler(r))))}async executeHandler(e){try{if(!this.shouldProcessRequest(e))return;const s=await this.prepareAndExecuteRequest(e);await this.processAndStoreResponse(s,e)}catch(s){const r=s instanceof Error?s:new Error(String(s));await this.handleError(r,e)}}shouldProcessRequest(e){return vg(e,this.model)?!0:(st.debug(`Skipping request ${e.path} - condition returned false`),!1)}async prepareAndExecuteRequest(e){const s=this.prepareRequest(e),r=this.captureRequestTiming(),[o,n]=await this.performRequest(s),i=this.captureResponseTiming();return{requestContext:s,error:o,response:n,requestedAt:r.requestedAt,receivedAt:i.receivedAt}}captureRequestTiming(){return{requestedAt:Date.now()}}captureResponseTiming(){return{receivedAt:Date.now()}}async processAndStoreResponse(e,s){if(e.error){await this.handleError(new Error(e.error),s);return}const r=await this.processResponse(e.response,s);await this.storeAndInvokeHandler(r,s,e.requestContext.resolvedPath,e.requestedAt,e.receivedAt)}prepareRequest(e){const s=wg(e,this.model),r=Eg(e,this.model),o=Mg(e,this.model),n=Tg(e,this.model),i=_g(e.method);return{resolvedPath:s,method:i,pathParams:r,queryParams:o,body:n}}async performRequest(e){return await this.makeRequest(e.resolvedPath,e.method,{path:e.pathParams,query:e.queryParams},e.body)}async processResponse(e,s){let r=e;return s.transform&&(r=s.transform(e)),s.mappings&&s.mappings.length>0&&(r=this.applyMappings(r,s)),s.iterateOver&&(r=await this.handleIteration(r,s)),r}async storeAndInvokeHandler(e,s,r,o,n){const i=s.cache||{retention:de.SINGLE},a=Fi(r,s.method||"get");this.responseStore.set(a,e,i,o,n),await s.originalHandler.call(this.model,e),this.triggerBaselineQueueFlush(r),this.responseStore.shouldCleanupAfterHandler(a)&&this.responseStore.delete(a)}triggerBaselineQueueFlush(e){const s=this.model.subscriptionManager;!s||!s.flushQueueForBaseline||s.flushQueueForBaseline(e)}async makeRequest(e,s,r,o){const n=Ae;switch(s){case"get":return await n.get(e,r);case"post":return await n.post(e,r,o);case"put":return await n.put(e,r,o);case"delete":return await n.delete(e,r,o);default:return[`Unsupported HTTP method: ${s}`,null]}}applyMappings(e,s){if(!s.mappings||s.mappings.length===0)return e;const r={};return s.mappings.forEach(o=>{const n=this.getNestedValue(e,o.from),i=o.transform?this.applyTransform(n,o.transform):n;Sg(i,o.from,s.path,o.required||!1);const a=Ig(i,o.default);r[o.to]=a}),r}getNestedValue(e,s){return s.split(".").reduce((r,o)=>r==null?void 0:r[o],e)}applyTransform(e,s){if(typeof s=="function")return s(e);switch(s){case"string":return String(e);case"number":return Number(e);case"boolean":return!!e;case"date":return e?new Date(e):void 0;case"json":return typeof e=="string"?JSON.parse(e):e;default:return st.warn(`Unknown transformer: ${s}`),e}}async handleIteration(e,s){if(!s.iterateOver)return e;const r=this.getNestedValue(e,s.iterateOver);return Array.isArray(r)?s.modelFactory?r.map(o=>{const n=s.mappings&&s.mappings.length>0?this.applyMappings(o,s):o,i=s.idExtractor?s.idExtractor(n):n.id;if(!i)throw new Error("Cannot create model instance: no ID found in response data. Provide an 'idExtractor' function or ensure response items have an 'id' field.");const a=s.modelFactory;return typeof a=="function"?a(i)(n):a.instance(i).options(n).build()}):r.map(o=>s.mappings&&s.mappings.length>0?this.applyMappings(o,s):o):(st.warn(`iterateOver path '${s.iterateOver}' did not resolve to an array`),[])}async handleError(e,s){const r=s.errorHandler||{strategy:"throw"};switch(r.onError&&r.onError(e,this.model),r.strategy){case"throw":throw e;case"log":st.error(`Service request failed for ${s.path}:`,e.message);break;case"ignore":break;case"default":if(r.defaultValue!==void 0){const o=Fi(s.path,s.method||"get");this.responseStore.set(o,r.defaultValue,s.cache||{retention:de.SINGLE})}break}}}class $g{constructor(e){l(this,"subscription");l(this,"unsubscribe");l(this,"eventType");this.eventType=e,this.subscription={queue:[],resolvers:[],closed:!1};const s=C(e,r=>{if(!this.subscription.closed&&r!==void 0){const o=this.subscription.resolvers.shift();o?o(r):this.subscription.queue.push(r)}});this.unsubscribe=s.unsubscribe}async next(){return this.subscription.closed&&this.subscription.queue.length===0?{done:!0,value:void 0}:this.subscription.queue.length>0?{done:!1,value:this.subscription.queue.shift()}:new Promise(e=>{this.subscription.closed?e({done:!0,value:void 0}):this.subscription.resolvers.push(s=>{e({done:!1,value:s})})})}async return(){return this.subscription.closed=!0,this.unsubscribe(),this.subscription.resolvers.forEach(e=>{e(void 0)}),this.subscription.resolvers=[],{done:!0,value:void 0}}async throw(e){throw this.subscription.closed=!0,this.unsubscribe(),e}[Symbol.asyncIterator](){return this}}function Ni(t){return new $g(t)}const ll=({path:t,requestId:e,method:s,destinationAddress:r})=>{let o=`${Kr}:${s}
32
32
  `;return o+=`topic:${t}
33
33
  `,o+=`${Kt}:${t}
34
34
  `,o+=`${Ns}:${e}
@@ -104,7 +104,7 @@ cmd:${s}
104
104
  ${u}topics:${e}
105
105
  `:`${u}type:kos.broker.${s}
106
106
 
107
- ["${e}"]`;if(r?(p=this.fosSocket)==null?void 0:p.connectionEstablished:(y=this.socket)==null?void 0:y.connectionEstablished){const E=r?this.fosSocket:this.socket;(w=E==null?void 0:E.socket)==null||w.send(d)}else{et.debug("no connection adding to offline messages");const E=r?this.fosSocket:this.socket;E==null||E.addOfflineMessage(d)}}subscribeTopic({topic:e,callback:s,fos:r,bridge:o,destinationAddress:n}){const{unsubscribe:i,count:a}=C(e,s);return et.debug(`Topic ${e} currently has ${a} subscribers`),this._sendSubscriptionMessage(e,"subscribe",r,o,n),()=>{const{count:c}=i();et.debug(`Topic ${e} currently has ${c} subscribers`),c===0&&this._sendSubscriptionMessage(e,"unsubscribe",r,o,n)}}async whenReady(){const e=this;return this.webSocketSupported?(await M.when(()=>{var s,r;return!!((s=e.socket)!=null&&s.connectionEstablished)&&(!e.useFosTransport||!!((r=e.fosSocket)!=null&&r.connectionEstablished))&&e.authorized}),{status:"success"}):{status:"not supported"}}get token(){return this._token}set token(e){this._token=e,this.init()}static host(e="localhost"){return this.getInstance().host=e,this}static port(e=8080){return this.getInstance().port=e,this}static alias(e){this.getInstance().alias=e}static getInstance(e=8080,s){if(!this._instance){const r=window.kosUseFos?{port:window.kosFosPort||8081}:void 0;this._instance=new this({port:e,token:s,fos:r})}return this._instance}}l(xt,"_instance");class Bg{constructor(e,s,r,o,n){l(this,"disposers",[]);l(this,"activatableDisposers",[]);l(this,"flowControllers",new Map);l(this,"baselineDependencies",new Map);this.model=e,this.modelData=s,this.modelId=r,this.offlineQueue=o,this.log=n}registerAll(e){var o;const s=((o=this.modelData)==null?void 0:o[ee])||{},r=Object.keys(s);this.log.debug(`Found ${r.length} subscriptions in ${this.modelId} (lifecycle: ${e??"any"})`),r.forEach(n=>{const i=s[n],a=i.lifecycle;if(e&&e!==a)return;const c=this.resolvePropKey(n);if(this.log.debug(`Resolved topic: ${n} → ${c}`),i.requiresBaseline&&(this.baselineDependencies.set(c,i.requiresBaseline),this.log.debug(`Registered baseline dependency for ${c}: ${i.requiresBaseline.path}`)),i.flow)this.subscribeWithFlowControl(i,c,a);else{const u=this.createHandler(c,i);this.subscribe(i,c,u,a===x.ACTIVATE)}})}deactivate(){this.log.debug(`Deactivating subscriptions for ${this.modelId}`);for(const e of this.activatableDisposers)try{e()}catch(s){this.log.error("Error during subscription disposal",s)}this.activatableDisposers=[]}disposeAll(){const e=[...this.disposers,...this.activatableDisposers];this.log.debug(`Disposing ${e.length} subscriptions for ${this.modelId}`);for(const[s,r]of this.flowControllers)this.log.debug(`Disposing flow controller for ${s}`);this.flowControllers.clear();for(const s of e)try{s()}catch(r){this.log.error("Error during subscription disposal",r)}this.disposers=[],this.activatableDisposers=[]}subscribe(e,s,r,o){const n=e.destinationAddress?this.resolvePropKey(e.destinationAddress):null;if(e.websocket){this.log.debug(`Subscribing to WebSocket topic: ${s}`);const i=xt.getInstance().subscribeTopic({topic:s,callback:r,fos:e.fos,bridge:e.bridge,destinationAddress:n});this.disposers.push(i)}else{this.log.debug(`Subscribing to EventBus topic: ${s}`);const{unsubscribe:i}=C(s,r);o?this.activatableDisposers.push(i):this.disposers.push(i)}}createHandler(e,s){return async r=>{var o;try{const n=(o=r==null?void 0:r.headers)==null?void 0:o["src-addr"],i=s.destinationAddress&&this.resolvePropKey(s.destinationAddress),a=i?n===i:!0,c=this.extractWildcardCapture(e,r,s),u=this.isBaselineReady(e);if(!this.model.isReady()||!u){u?this.log.warn(`Model ${this.modelId} not ready. Queuing message for ${e}`):this.log.warn(`Baseline not ready for ${e}. Queuing message.`);const d=()=>{const h=Fo(r,s.skipParse),f=s.transform(h);if(a&&s.condition(f,this.modelData,r))return this.callHandlerWithWildcard(s,f,c,r)};this.offlineQueue.enqueue(d,e,r)}else{const d=Fo(r,s.skipParse),h=s.transform(d);if(a&&s.condition(h,this.modelData,r))return this.callHandlerWithWildcard(s,h,c,r)}}catch(n){this.log.error(`Error handling subscription for ${e}`,n)}}}extractWildcardCapture(e,s,r){var n;if(!r.wildcardName||!Vc(e))return null;const o=((n=s==null?void 0:s.headers)==null?void 0:n.topic)||"";return zc(e,o,r.wildcardName)}callHandlerWithWildcard(e,s,r,o){if(r&&Object.keys(r).length>0){const n={...o,wildcardCapture:r};return e.handler.call(this.modelData,s,n,this.modelData)}else return e.handler.call(this.modelData,s,o,this.modelData)}resolvePropKey(e){const s=/.*({PROP_(.+)})/;let r=e.includes("{MODEL_ID}")?e.replace("{MODEL_ID}",this.modelId):e;const o=r.match(s);return o&&o[2]in this.modelData&&(r=r.replace(o[1],this.modelData[o[2]])),r}async subscribeWithFlowControl(e,s,r){this.log.debug(`Setting up flow control for topic: ${s}`);const o=new Rg(e.flow);this.flowControllers.set(s,o);const n=this.createFlowControlHandler(s,e),i=this.startFlowProcessing(e,s,n,o),a=()=>{this.flowControllers.delete(s),i.then(c=>c==null?void 0:c.abort())};r===x.ACTIVATE?this.activatableDisposers.push(a):this.disposers.push(a)}async startFlowProcessing(e,s,r,o){const n=new AbortController;try{let i;if(e.websocket){const a=e.destinationAddress?this.resolvePropKey(e.destinationAddress):null;xt.getInstance().subscribeTopic({topic:s,callback:()=>{},fos:e.fos,bridge:e.bridge,destinationAddress:a}),i=Ni(s)}else i=Ni(s);return(async()=>{try{for await(const a of o.processEvents(i)){if(n.signal.aborted)break;const c=r(a);c instanceof Promise&&await o.trackPromise(c)}}catch(a){this.log.error(`Flow control error for ${s}:`,a)}})(),n}catch(i){return this.log.error(`Failed to start flow processing for ${s}:`,i),null}}createFlowControlHandler(e,s){return async r=>{var o,n,i,a;try{if(s.condition&&!s.condition(r,this.modelData,r))return;if(this.model.isReady())return s.handler.call(this.modelData,r,r,this.modelData);{this.log.warn(`Model ${this.modelId} not ready. Queuing flow-controlled message for ${e}`);const c=()=>s.handler.call(this.modelData,r,r,this.modelData);this.offlineQueue.enqueue(c,e,r)}}catch(c){if(this.log.error(`Error in flow control handler for ${e}:`,c),(n=(o=s.flow)==null?void 0:o.errorHandling)!=null&&n.retry)await this.retryHandler(s,r,c);else if(!((a=(i=s.flow)==null?void 0:i.errorHandling)!=null&&a.continueOnError))throw c}}}async retryHandler(e,s,r){const o=e.flow.errorHandling.retry;let n=r;for(let i=1;i<=o.attempts;i++)try{return this.log.debug(`Retry attempt ${i}/${o.attempts} for handler`),await new Promise(a=>setTimeout(a,o.backoffMs*i)),e.handler.call(this.modelData,s,s,this.modelData)}catch(a){n=a,this.log.warn(`Retry attempt ${i} failed:`,a)}throw this.log.error("All retry attempts failed, throwing last error:",n),n}getFlowControlStats(){const e={};for(const[s,r]of this.flowControllers)e[s]=r.getStats();return e}getResponseStore(){return this.modelData.serviceResponses}isBaselineReady(e){const s=this.baselineDependencies.get(e);if(!s)return!0;const r=this.getResponseStore();if(!r)return this.log.warn(`ServiceResponseStore not found for baseline check on topic: ${e}`),!1;const n=`${(s.method||"get").toUpperCase()}:${s.path}`;return r.has(n)}flushQueueForBaseline(e){const s=this.baselineDependencies.get(e);if(!s){this.log.debug(`No baseline dependency for topic: ${e}`);return}const r=this.getResponseStore();if(!r){this.log.warn("ServiceResponseStore not found, falling back to standard flush"),this.offlineQueue.flush();return}const o=s.method||"get",n=r.getTemporalMetadataByPath(s.path,o);if(!n){this.log.warn(`Baseline temporal metadata not found for ${s.path}, falling back to standard flush`),this.offlineQueue.flush();return}const i=s.replayStrategy||it.AFTER_REQUEST;this.log.info(`Flushing queue with strategy ${i} for topic: ${e}`),this.log.debug(`Baseline timing - requested: ${n.requestedAt}, received: ${n.receivedAt}`),this.offlineQueue.flushWithStrategy(i,n.requestedAt,n.receivedAt)}}function vt(t,e){const s=`[Model:${e}]`;return{debug:(...r)=>t.debug(s,...r),info:(...r)=>t.info(s,...r),warn:(...r)=>t.warn(s,...r),error:(...r)=>t.error(s,...r)}}function Hg(t){return!!(t!=null&&t[at])&&Object.keys(t[at]).length>0}function Kg(t){return!!(t!=null&&t[ee])&&Object.keys(t[ee]).length>0}function qg(t){return!!(t!=null&&t[ke])&&t[ke].length>0}function zg(t){const e=Object.getPrototypeOf(t);return!!(e!=null&&e[ct])&&Object.keys(e[ct]).length>0}function Vg(t){return t.retention===de.TTL&&t.extendOnRefresh===!0&&t.ttl!==void 0}function Gg(t,e){return t.has(e)}function Yg(t){return!t.expiresAt||Date.now()<t.expiresAt}function Bi(t,e,s,r){const o=setTimeout(()=>r(t),e);s.set(t,o)}class Wg{constructor(){l(this,"responses",new Map);l(this,"retentionPolicies",new Map);l(this,"cleanupTimers",new Map)}set(e,s,r={retention:de.SINGLE},o=Date.now(),n=Date.now()){if(this.shouldExtendTTL(e,r))return this.extendExistingTTL(e,r.ttl),!1;const i=this.createCachedResponse(s,e,r,o,n);return this.storeResponse(e,i,r),!0}get(e){const s=this.responses.get(e);if(s){if(s.expiresAt&&Date.now()>s.expiresAt){this.delete(e);return}return s.data}}getByPath(e,s="get"){return this.get(this.makeKey(e,s))}has(e){return this.get(e)!==void 0}delete(e){this.responses.delete(e),this.retentionPolicies.delete(e);const s=this.cleanupTimers.get(e);s&&(clearTimeout(s),this.cleanupTimers.delete(e))}clearPath(e){Array.from(this.responses.keys()).filter(r=>this.extractPath(r)===e).forEach(r=>this.delete(r))}clear(){this.cleanupTimers.forEach(e=>clearTimeout(e)),this.responses.clear(),this.retentionPolicies.clear(),this.cleanupTimers.clear()}get size(){return this.responses.size}shouldCleanupAfterHandler(e){const s=this.retentionPolicies.get(e);return(s==null?void 0:s.retention)===de.IMMEDIATE}shouldExtendTTL(e,s){if(!Vg(s)||!Gg(this.responses,e))return!1;const r=this.responses.get(e);return Yg(r)}extendExistingTTL(e,s){const r=this.responses.get(e);r.expiresAt=Date.now()+s,this.resetCleanupTimer(e,s)}resetCleanupTimer(e,s){this.clearTimerIfExists(e),Bi(e,s,this.cleanupTimers,r=>this.delete(r))}clearTimerIfExists(e){const s=this.cleanupTimers.get(e);s&&(clearTimeout(s),this.cleanupTimers.delete(e))}createCachedResponse(e,s,r,o,n){return{data:e,timestamp:n,requestedAt:o,receivedAt:n,path:this.extractPath(s),method:this.extractMethod(s),expiresAt:this.calculateExpiresAt(r)}}calculateExpiresAt(e){return e.retention===de.TTL&&e.ttl?Date.now()+e.ttl:void 0}storeResponse(e,s,r){this.responses.set(e,s),this.retentionPolicies.set(e,r),this.applyRetentionPolicy(e,r)}applyRetentionPolicy(e,s){switch(s.retention){case de.IMMEDIATE:break;case de.TTL:s.ttl&&Bi(e,s.ttl,this.cleanupTimers,r=>this.delete(r));break;case de.SINGLE:break;case de.PERMANENT:case de.MANUAL:break}}makeKey(e,s){return`${s.toUpperCase()}:${e}`}extractPath(e){return e.split(":",2)[1]||e}extractMethod(e){return e.split(":",2)[0]||"get"}getTemporalMetadata(e){const s=this.responses.get(e);if(s)return{requestedAt:s.requestedAt,receivedAt:s.receivedAt}}getTemporalMetadataByPath(e,s="get"){return this.getTemporalMetadata(this.makeKey(e,s))}cleanup(){const e=Date.now();Array.from(this.responses.entries()).filter(([r,o])=>o.expiresAt&&e>o.expiresAt).map(([r])=>r).forEach(r=>this.delete(r))}}class Qg{static createAll(e){const{modelId:s,modelTypeName:r,modelData:o}=e,n=xc.create({modelId:s,modelTypeName:r}),i=new fg(e,vt(n,"fsm")),a=new gg(vt(n,"offline-queue")),c=new ng(e),u=new og(e),d=new Wg;o.serviceResponses=d;const h={fsm:i,offlineQueue:a,serviceResponseStore:d,companionManager:c,childResolver:u};if(Hg(o)&&(h.effectManager=new ig(r,s,o,vt(n,"effect"))),Kg(o)){const f=vt(n,"subscription");h.subscriptionManager=new Bg(e,o,s,a,f),h.onlineLifecycleManager=new mg(e,vt(n,"online"))}return qg(o)&&(h.httpRouteManager=new On(o,vt(n,"http-routes"))),zg(o)&&(h.serviceRequestManager=new Og(o,d)),h}}const N=D.getLogger("kos-model"),Zg="kos.extension.model.loader";class El{constructor({modelTypeName:e,id:s,modelData:r}){l(this,"_id");l(this,"_status");l(this,"_activeStatus");l(this,"_onlineStatus");l(this,"modelData");l(this,"modelTypeName");l(this,"initialized");l(this,"loaded");l(this,"offlineQueue");l(this,"subscriptionManager");l(this,"effectManager");l(this,"httpRouteManager");l(this,"onlineLifecycleManager");l(this,"serviceResponses");l(this,"serviceRequestManager");l(this,"companionManager");l(this,"childResolver");l(this,"fsm");this._id=typeof s<"u"?`${s}`:e,this.modelTypeName=e,this.initialized=!1,this.loaded=!1,this.modelData=r,this._status=v.CREATED,this._activeStatus=v.INACTIVE,this._onlineStatus=v.OFFLINE;const o=Qg.createAll(this);this.fsm=o.fsm,this.offlineQueue=o.offlineQueue,this.companionManager=o.companionManager,this.childResolver=o.childResolver,this.serviceResponses=o.serviceResponseStore,o.effectManager&&(this.effectManager=o.effectManager),o.subscriptionManager&&(this.subscriptionManager=o.subscriptionManager),o.httpRouteManager&&(this.httpRouteManager=o.httpRouteManager),o.onlineLifecycleManager&&(this.onlineLifecycleManager=o.onlineLifecycleManager),o.serviceRequestManager&&(this.serviceRequestManager=o.serviceRequestManager),M.makeAutoObservable(this,{fsm:!1,effectManager:!1,subscriptionManager:!1,onlineLifecycleManager:!1,serviceRequestManager:!1,serviceResponses:!1,companionManager:!1,childResolver:!1,offlineQueue:!1}),sg(this)}get companionModels(){return this.companionManager}set status(e){this._status=e}get status(){return this._status}get modelId(){return this._id}get id(){return this._id}get activeStatus(){return this._activeStatus}set activeStatus(e){this._activeStatus=e}get onlineStatus(){return this._onlineStatus}set onlineStatus(e){this._onlineStatus=e}get modelManager(){return globalThis.kos.modelManager}isActive(){return this._status===v.ACTIVE}isOnline(){return this._onlineStatus===v.ONLINE}isReady(){return this._status===v.READY}async deactivate(){var e,s,r;N.debug(`deactivating model ${this.modelTypeName} with id ${this.modelId}`);try{const o=Y.getContext(this.modelId);await((s=(e=this.modelData)==null?void 0:e.deactivate)==null?void 0:s.call(e,o)),N.debug(`Model ${this.modelTypeName} with id ${this.modelId} deactivated`),(r=this.subscriptionManager)==null||r.deactivate()}catch(o){throw N.debug(`Model ${this.modelId} failed to deactivated`),o}}async activate(){var e,s,r,o;N.debug(`activating model ${this.modelTypeName} with id ${this.modelId}`),await ts(this,x.ACTIVATE);try{await((e=this.serviceRequestManager)==null?void 0:e.executeForLifecycle(x.ACTIVATE));const n=Y.getContext(this.modelId);await((r=(s=this.modelData)==null?void 0:s.activate)==null?void 0:r.call(s,n)),this.initializeStateMachineForLifecycle(x.ACTIVATE),N.debug(`Model ${this.modelTypeName} with id ${this.modelId} subscribing to all topics`),(o=this.subscriptionManager)==null||o.registerAll(x.ACTIVATE),this.createLifecycleCompanions(x.ACTIVATE),N.debug(`Model ${this.modelTypeName} with id ${this.modelId} activated`)}catch(n){throw N.debug(`Model ${this.modelId} failed to activate`),n}}async whenLoaded(){await To([{condition:()=>this.status===v.FAILED,onMatch:()=>{throw new Error(`Failed to initialize model ${this.modelId}`)}},{condition:()=>this.loaded,onMatch:()=>{N.debug(`Model ${this.modelId} is loaded`)}}])}async whenInitialized(){await To([{condition:()=>this.status===v.FAILED,onMatch:()=>{throw new Error(`Failed to initialize model ${this.modelId}`)}},{condition:()=>this.initialized,onMatch:()=>{N.debug(`Model ${this.modelId} is initialized`)}}])}async whenReady(){await To([{condition:()=>this.status===v.FAILED,onMatch:()=>{throw new Error(`Failed to ready model ${this.modelId}`)}},{condition:()=>this.status===v.READY,onMatch:()=>{N.debug(`Model ${this.modelId} is ready`)}}])}async ready(){var e,s,r,o;if(this.fsm.current===v.READY){N.debug(`already readying model ${this.modelTypeName} with id ${this.modelId} returning`);return}try{N.debug(`readying model ${this.modelTypeName} with id ${this.modelId}`),await ts(this,x.READY),await ol(this,Sn.READY,x.READY),await((e=this.serviceRequestManager)==null?void 0:e.executeForLifecycle(x.READY));const n=Y.getContext(this.modelId);await((r=(s=this.modelData)==null?void 0:s.ready)==null?void 0:r.call(s,n)),this.offlineQueue.flush(),this.initializeStateMachineForLifecycle(x.READY),(o=this.subscriptionManager)==null||o.registerAll(x.READY),this.createLifecycleCompanions(x.READY),N.debug(`Model ${this.modelId} is ready`);const i={modelId:this.modelId,modelType:this.modelTypeName};V(Wc(this.modelTypeName,this.modelId),i),V(Qc(this.modelTypeName),i)}catch(n){throw N.error(n),Error(n)}}async load(){var o,n,i,a,c,u;const e=this[Ye];e&&await e.whenLoaded();const{modelTypeName:s,modelId:r}=this;if(this.fsm.current===v.LOADED||this.fsm.current===v.LOADING){N.debug(`Model ${s} with id ${r} already loaded or loading`);return}N.debug(`Loading model ${s} with id ${r}`),await ts(this,x.LOAD);try{const d=Y.getContext(r),h=`${Zg}.${s}`,f=await $.loader.executeLoader(h,{});f&&(N.info(`Setting loaded context for ${r}, type: ${s}`),d==null||d.set(h,f)),await((o=this.serviceRequestManager)==null?void 0:o.executeForLifecycle(x.LOAD)),await((i=(n=this.modelData)==null?void 0:n.load)==null?void 0:i.call(n,d)),J(()=>{this.loaded=!0}),N.debug(`Model ${s} with id ${r} successfully loaded`),this.initializeStateMachineForLifecycle(x.LOAD),(a=this.subscriptionManager)==null||a.registerAll(x.LOAD),(c=this.httpRouteManager)==null||c.registerAll(),(u=this.effectManager)==null||u.setup(),this.createLifecycleCompanions(x.LOAD)}catch(d){throw N.error(`Model ${r} failed to load`,d),d}}async unload(){var e,s,r,o,n,i,a;N.debug(`unloading model ${this.modelTypeName} with id ${this.modelId}`);try{const c=this.getChildren().map(d=>{var h;return(h=d.unload)==null?void 0:h.call(d)}).filter(d=>!!d);await Promise.allSettled(c);const u=Y.getContext(this.modelId);if(await((s=(e=this.modelData)==null?void 0:e.unload)==null?void 0:s.call(e,u)),this.loaded=!1,(r=this.onlineLifecycleManager)==null||r.dispose(),this.modelData){const d=this.modelData;if(d._fsmInitialized=!1,d._fsmConfig){const h=((o=d._fsmOptions)==null?void 0:o.stateProperty)||"currentState";d[h]=void 0}d.stateHistory&&(d.stateHistory=[])}N.debug(`Model ${this.modelTypeName} with id ${this.modelId} unloaded`),(n=this.effectManager)==null||n.disposeAll(),(i=this.subscriptionManager)==null||i.disposeAll(),(a=this.httpRouteManager)==null||a.dispose()}catch(c){throw N.debug(`Model ${this.modelId} failed to unload`),c}}async init(){var n,i,a,c;const e=this[Ye];e&&await e.whenInitialized();const{modelId:s,modelTypeName:r}=this,o=Y.getContext(s);N.debug(`Initializing model ${r} with id ${s}`),await ts(this,x.INIT);try{await((n=this.serviceRequestManager)==null?void 0:n.executeForLifecycle(x.INIT)),await((a=(i=this.modelData)==null?void 0:i.init)==null?void 0:a.call(i,o)),this.initialized=!0,N.debug(`Model ${r} with id ${s} initialized`),(c=this.onlineLifecycleManager)==null||c.register(),this.initializeStateMachineForLifecycle(x.INIT),this.registerSubscribers(x.INIT),this.createLifecycleCompanions(x.INIT)}catch(u){throw N.error(`Model ${s} failed to initialize`,u),u}}async registerSubscribers(e){var s;N.debug(`registering subscribers in ${this.modelTypeName} with id ${this.modelId}`),(s=this.subscriptionManager)==null||s.registerAll(e)}initializeStateMachineForLifecycle(e){this.modelData&&Ic(this.modelData,e)}createLifecycleCompanions(e){this.modelManager.createLifecycleCompanions(this,{},e)}async online(){var s,r;N.debug(`online model ${this.modelTypeName} with id ${this.modelId}`),this.registerSubscribers();const e=Y.getContext(this.modelId);await((r=(s=this.modelData)==null?void 0:s.online)==null?void 0:r.call(s,e)),this.createLifecycleCompanions(x.ONLINE)}async offline(){var s,r,o;N.debug(`offline model ${this.modelTypeName} with id ${this.modelId}`),(s=this.subscriptionManager)==null||s.disposeAll();const e=Y.getContext(this.modelId);await((o=(r=this.modelData)==null?void 0:r.offline)==null?void 0:o.call(r,e))}accept(e){e.visit(this)}getChildren(){return this.childResolver.resolve()}addCompanionModel(e){this.companionManager.add(e)}clearCompanionModels(){this.companionManager.clear()}}const _o=m.createLogger({name:"kos-model-instantiator"});class Xg{constructor(e,s){l(this,"companionInstantiator");this.registry=e,this.cache=s,this.companionInstantiator=new Wp(e,s,this.createModelInstance.bind(this))}createModelInstance(e,s,r={}){var a;const o=this.registry.models[e];if(!o){const c=`No model registered for type ${e}`;throw _o.error(c,{modelType:e,requestedId:s,providedOptions:r,availableModelTypes:Object.keys(this.registry.models)}),$t(new Error(c),{modelType:e,modelId:s,operation:"model instantiation - registry lookup",options:r,metadata:{availableModelTypes:Object.keys(this.registry.models)}})}const n=o.singleton?e:s;if(this.cache.restoreFromDeleteCache(n),!this.cache.hasModel(n)){_o.debug(`Creating model instance: ${e} [${n}]`);const c=r&&Object.keys(r).length>0,u=o.class||o.create;if(((a=u==null?void 0:u.prototype)==null?void 0:a[Hs])===!0&&!c){const h=new Error(`Model ${e} requires options but none were provided`);throw ki(h,{modelType:e,options:r,registryId:this.registry.alias||"unknown"}),$t(h,{modelType:e,modelId:n,operation:"model instantiation - options validation",options:r,metadata:{requiresOptions:!0,hasOptions:!1}})}try{const h=o.create?o.create({modelTypeId:e,id:n,options:r}):new o.class(n,r),f=new El({modelTypeName:e,id:n,modelData:h});this.cache.addModel(f),this._createCompanionModels(f,r)}catch(h){throw ki(h,{modelType:e,options:r,registryId:this.registry.alias||"unknown"}),$t(h,{modelType:e,modelId:n,operation:"model instantiation",options:r})}}const i=this.cache.getModelById(n);if(!i)throw _o.error(`Model ${e} [${n}] not found in cache`),new Error(`Model ${e} [${n}] not found in cache`);return{model:i,data:i.modelData}}createCompanionModels(e,s,r){this.companionInstantiator.createCompanionModels(e,s,r)}_createCompanionModels(e,s){this.createCompanionModels(e,s)}}let Jg=class{constructor(e){this._registry=e}get registry(){return this._registry}getModelTypeRegistry(e){const s=this.registry.models[e];if(!s)throw new Error(`No registration for model type ${e}`);return s}registerModel(e){const s=e.type;this.registry.models[s]||(this.registry.models={...this.registry.models,...e.registration})}registerCompanionModel(e,s){var r,o;(r=this.registry).companionModels??(r.companionModels={}),(o=this.registry.companionModels)[e]??(o[e]=[]),this.registry.companionModels[e].some(n=>n.type===s)||this.registry.companionModels[e].push({type:s})}getModelSubscriptions(e){var s;return((s=this.getModelTypeRegistry(e))==null?void 0:s.subscriptions)||{}}getDataModelBuilder(e){var r;const s=(r=this.getModelTypeRegistry(e))==null?void 0:r.builder;if(!s)throw new Error(`No builder found for model type ${e}`);return s}getModelFactory(e){return zt(e)}};const Ml=10,Hi=m.createLogger({name:"kos-model-manager"});class Tl{constructor(){l(this,"cache");l(this,"instantiator");l(this,"dependencies");l(this,"_registry");globalThis.kos=globalThis.kos||{},this.dependencies=new Vp,globalThis.kos.modelManager=this,globalThis.kos.resolveKosModel=e=>{const s=this.getModelById(e);if(s)return s.modelData||{}},globalThis.kos.kosModelJson=e=>{var r,o;const s=this.getModelById(e);if(s)return((o=(r=s.modelData).toJSON)==null?void 0:o.call(r))||{}},globalThis.kos.kosModelDebug=e=>{var r;const s=this.getModelById(e);if(s)return((r=s.modelData)==null?void 0:r.debugState)||{}},globalThis.kos.kmd=globalThis.kos.kosModelDebug,globalThis.kos.kmj=globalThis.kos.kosModelJson}static create(e,s){const r=this.getInstance(s);return r._registry=new Jg(e),r.cache=new Gp(e.preloadModels),r.instantiator=new Xg(e,r.cache),r}static getInstance(e){var s,r;return(!((s=globalThis.kos)!=null&&s.modelManager)||e)&&(Hi.debug("Creating new instance of KosModelManager"),new this),(r=globalThis.kos)==null?void 0:r.modelManager}get registry(){return this._registry.registry}get preloadedModels(){return this.cache.preload(e=>(Hi.debug(`preloading ${e}`),typeof e=="string"?this.createModelInstance(e).model:this.createModelInstance(e.modelType,e.modelId,e.options).model))}get models(){return this.cache.models}getModelById(e){return this.cache.getModelById(e)}addModel(e){return this.cache.addModel(e)}removeModel(e){this.cache.removeModel(e.modelId)}hasModel(e){return this.cache.hasModel(e)}getModelsByType(e,s){return Array.from(this.models).filter(r=>r.modelTypeName===e).filter(r=>s?s(r.modelData):!0).map(r=>r.modelData)}getModelSubscriptions(e){return this._registry.getModelSubscriptions(e)}getDataModelBuilder(e){return this._registry.getDataModelBuilder(e)}getModelFactory(e){return zt(e)}addDependency(e,s){this.cache.restoreFromDeleteCache(s),this.dependencies.add(e,s)}removeDependency(e,s){this.dependencies.remove(e,s)}async reloadModel(e){if(e.id){const s=this.getModelById(e.id);s&&await s.fsm.transitionTo(L.RESET,v.RESETTING)}}async initiateDestroyModel(e){if(!e.id)throw new Error("Model ID is required");if(!this.dependencies.canDestroy(e.id))return;const s=this.getModelById(e.id);s&&(this.cache.markForDeletion(s),Gc.addToDeletionQueue(e.id,setTimeout(()=>this.destroyModel(s),Ml)))}async destroyModel(e){var s;e!=null&&e.modelId&&this.dependencies.canDestroy(e.modelId)&&(await((s=e.unload)==null?void 0:s.call(e)),this.removeModel(e))}createModelInstance(e,s,r={}){return this.instantiator.createModelInstance(e,s,r)}createLifecycleCompanions(e,s,r){this.instantiator.createCompanionModels(e,s,r)}registerCompanionModel(e,s){this._registry.registerCompanionModel(e,s)}registerModel(e){this._registry.registerModel(e)}}var ur=(t=>(t.CREATING="creating",t.CREATED="created",t.INITIALIZING="initializing",t.INITIALIZED="initialized",t.LOADING="loading",t.LOADED="loaded",t.ONLINE="online",t.READYING="readying",t.READY="ready",t.OFFLINE="offline",t.UNLOADING="unloading",t.UNLOADED="unloaded",t.RELOADING="reloading",t))(ur||{}),_t=(t=>(t.CREATE="create",t.INITIALIZE="init",t.READY="ready",t.GO_ONLINE="go_online",t.GO_OFFLINE="go_offline",t.UNLOAD="unload",t.RELOAD="reload",t))(_t||{});const em=t=>{const e=b.createMachine("offline",{online:b.state(b.transition("go_offline","offline",b.action(()=>{t.offline(),M.runInAction(()=>{t.isOnline=!1})}))),offline:b.state(b.transition("go_online","online",b.action(()=>{t.online(),M.runInAction(()=>{t.isOnline=!0})})))}),s=b.interpret(e,n=>D.debug(n.machine.current)),r=b.createMachine({creating:b.state(b.transition("create","created")),created:b.state(b.immediate("initializing")),initializing:b.invoke(()=>t.init(),b.transition("done","initialized")),initialized:b.state(b.immediate("loading")),loading:b.invoke(()=>t.load(),b.transition("done","loaded")),loaded:b.state(b.immediate("readying"),b.transition("unload","unloading")),readying:b.invoke(()=>t.ready(),b.transition("done","ready",b.action(()=>{M.runInAction(()=>{t.status="ready"})}))),reloading:b.invoke(()=>t.reload(),b.transition("done","loading")),ready:b.state(b.transition("reload","reloading"),b.transition("unload","unloaded",b.action(t.unload.bind(t))),b.transition("go_online","ready",b.action(()=>{s.send("go_online")})),b.transition("go_offline","ready",b.action(()=>{s.send("go_offline")}))),unloaded:b.state()});return{service:b.interpret(r,n=>D.debug(n.machine.current)),online:s}},Q=m.createLogger({name:"kos-core"}),tm=()=>{const t=ye(),e=t==null?void 0:t.alias,s=process.env.KOS_CONNECTION_ALIAS;return e||s||void 0},sm=()=>{const t=window.location.protocol,e=ye(),s=e==null?void 0:e.host;let r;try{r=new URL(s).protocol==="https:"?"wss://":"ws://"}catch{}return r||(t==="https:"?"wss://":"ws://")},rm=()=>{const t=window.location.hostname,e=process.env.KOS_HOST,s=ye(),r=s==null?void 0:s.host;let o;try{o=new URL(r).hostname}catch{}return o??e??t},om=()=>{const t=window.location.port,e=process.env.KOS_PORT,s=ye(),r=s==null?void 0:s.host;let o;try{o=new URL(r).port}catch{}return o??e??t},nm=(t,e)=>{let s;return{promise:new Promise((n,i)=>{s=setTimeout(()=>{e?m.error(`Model ${e.modelId} - ${e.modelTypeName} preloading - timed out after ${t}ms`):m.error(`KOS Core preloading timed out after ${t}ms`),i(new Error(`Model ${e==null?void 0:e.modelId} - ${e==null?void 0:e.modelTypeName} - timed out after ${t}ms`))},t)}),cancel:()=>{s&&clearTimeout(s)}}},Ki=t=>typeof t.reload=="function",im=t=>typeof t.unload=="function";var _l=(t=>(t.LOGGED_IN="logged_in",t.LOGGED_OUT="logged_out",t))(_l||{});class I{constructor(e){l(this,"fsmService");l(this,"status");l(this,"initialized");l(this,"loaded");l(this,"_transport");l(this,"modelManager");l(this,"authState");l(this,"isOnline");l(this,"_reloading");l(this,"_unloading");l(this,"connectionAlias");this.initialized=!1,this.connectionAlias=e,this.loaded=!1,this.isOnline=!1,this.status=ur.CREATED,this.authState="logged_out",this._reloading=!1,this._unloading=!1,M.makeAutoObservable(this),C("token",a=>{a&&(this.transport.token=a.body)}),C(Ms.CONNECTED,async()=>{await this.whenReady(),this.fsmService.service.send(_t.GO_ONLINE)}),C(Ms.DISCONNECTED,async()=>{this.fsmService.service.send(_t.GO_OFFLINE)}),C("/studioServer/auth/LOGGED_IN",()=>{this.authState="logged_in",this.transport.authorized=!0}),C("/studioServer/auth/LOGIN_REQUIRED",()=>{this.authState="logged_out",this.transport.authorized=!1}),C(Ms.RELOAD,()=>{Q.warn("WebSocket requested reload"),this.fsmService.service.send(_t.RELOAD)}),C("/studio/project/reload",()=>{Q.warn("Project requested reload"),this.fsmService.service.send(_t.RELOAD)});const s=xt.getInstance(),r=rm(),o=om(),n=sm();s.host=r,s.port=Number.parseInt(o),s.protocol=n,process.env.KOS_ALLOW_ANONYMOUS==="true"&&(s.authorized=!0);const i=tm()??e;i&&(s.alias=i.replace("{{TIMESTAMP}}",Date.now().toString())),this._transport=s.init(),this.fsmService=em(this),this.fsmService.service.send(_t.CREATE)}get onlineStatus(){return this.isOnline&&!this._reloading&&!this._unloading}get reloading(){return this._reloading}get unloading(){return this._unloading}async reload(){var o,n,i,a;const e=Date.now();if(this._reloading){Q.info("reload already in progress");return}this._reloading=!0,Q.warn("reloading KOS Core"),Q.warn("reloading preloaded models");const s=this.modelManager;for(const c of s.preloadedModels)Ki(c.modelData)&&(Q.info(`reloading model ${c.modelId}`),(o=c.unload)==null||o.call(c),await c.modelData.reload(),(n=c.registerSubscribers)==null||n.call(c),Q.info(`reloading model ${c.modelId} complete`));for(const c of s.models)!s.preloadedModels.includes(c)&&Ki(c.modelData)&&((i=c.unload)==null||i.call(c),await c.modelData.reload(),(a=c.registerSubscribers)==null||a.call(c));const r=Date.now()-e;setTimeout(()=>{M.runInAction(()=>{Q.warn("reloading KOS Core complete"),this._reloading=!1})},1e3-r)}async online(){Q.debug("KOS Core going online"),await this._transport.whenReady(),Q.debug("KOS Transport Ready. Calling online() for models"),V("/kosCore/online","/kosCore/online"),console.timeEnd("kosCore:startup")}async offline(){Q.debug("KOS Core going offline"),V("/kosCore/offline","/kosCore/offline")}async unload(){var o;Q.debug("Unloading KOS Core");const e=Date.now();this._unloading=!0,Q.debug("unloading KOS Core");const s=this.modelManager;for(const n of s.models)im(n.modelData)&&((o=n.unload)==null||o.call(n));const r=Date.now()-e;setTimeout(()=>{M.runInAction(()=>{this._unloading=!1})},1e3-r)}async whenReady(){await M.when(()=>this.status===ur.READY)}async ready(){Q.debug("Readying KOS Core"),await this._transport.whenReady();const e=this.modelManager.preloadedModels.map(o=>({modelId:o.modelId,model:o,promise:o.whenReady()})),r=(await Promise.allSettled(e.map(o=>{const{promise:n,cancel:i}=nm(5e3,o.model);Promise.race([o.promise.then(()=>{i()}),n])}))).filter(o=>o.status==="rejected");if(r.length)throw Q.error(`There were ${r.length} failed models on model preloading`),Error(`There were ${r.length} failed models on model preloading`);Q.debug("leaving kos-core ready() ")}get isReady(){return this.status===ur.READY}set transport(e){this._transport=e}get transport(){return this._transport}get coreInitialized(){return this.initialized}get modelsLoaded(){return this.loaded}async init(){Q.debug("entering kos-core init()"),console.time("kosCore:startup"),console.time("kosCore:init"),await this._transport.whenReady(),this.initialized=!0,Q.debug("initialized - leaving kos-core init()"),console.timeEnd("kosCore:init")}async load(){Q.debug("entering kos-core load()"),console.time("kosCore:load"),this.loaded=!0,Q.debug("loaded - leaving kos-core load()"),console.timeEnd("kosCore:load")}static create(e,s,r){var i,a,c;const o=this.getInstance({reset:s,connectionAlias:r});(i=e.extensions)!=null&&i.dataMapper&&Object.keys(e.extensions.dataMapper).forEach(u=>{var h,f;const d=(f=(h=e.extensions)==null?void 0:h.dataMapper)==null?void 0:f[u];d&&(Array.isArray(d)?d.forEach(p=>{$.dataMapper.registerDataMapper(u,p)}):$.dataMapper.registerDataMapper(u,d))}),(a=e.extensions)!=null&&a.propertyMapper&&Object.keys(e.extensions.propertyMapper).forEach(u=>{var h,f;const d=(f=(h=e.extensions)==null?void 0:h.propertyMapper)==null?void 0:f[u];d&&$.propertyMapper.registerPropertyMapper(u,d)}),(c=e.extensions)!=null&&c.contextLoader&&Object.keys(e.extensions.contextLoader).forEach(u=>{var h,f;const d=(f=(h=e.extensions)==null?void 0:h.contextLoader)==null?void 0:f[u];d&&$.loader.registerLoader(u,d)}),A.model.getAll().forEach(([,u])=>{e.models={...e.models,...u.registration}}),e.models={...e.models,...A.model.getLegacyModels()},A.companion.getAll().forEach(([u,d])=>{e.companionModels={...e.companionModels},e.companionModels[u]=e.companionModels[u]||[];for(const h of d){let f;if(typeof h=="string"){const p=e.models[h];if(p!=null&&p.class){const y=p.class.prototype[Ye];f=y==null?void 0:y.lifecycle}}e.companionModels[u].push({type:h,lifecycle:f})}}),A.model.getPreloadModels().forEach(u=>{e.preloadModels.includes(u)||e.preloadModels.push(u)});const n=Tl.create(e,s);return o.modelManager=n,o}static getInstance(e){return this._instance=window.KosCore,(!this._instance||e!=null&&e.reset)&&(window.KosCore=new this(e==null?void 0:e.connectionAlias),this._instance=window.KosCore),this._instance}}l(I,"_instance");function Uo(t){const e=new Uint8Array(t);let s="";for(let r=0;r<e.byteLength;r++)s+=String.fromCharCode(e[r]);return btoa(s)}function am(t){const e=atob(t),s=new Uint8Array(e.length);for(let r=0;r<e.length;r++)s[r]=e.charCodeAt(r);return s.buffer}async function cm(t){return await t.arrayBuffer()}function lm(t,e){return new Blob([t],{type:e})}async function um(t){const e={},s=[],r=[];t.forEach((o,n)=>{r.push([n,o])});for(const[o,n]of r)if(n instanceof File){const i=await n.arrayBuffer();s.push({name:o,filename:n.name,type:n.type,data:Uo(i)})}else e[o]=n.toString();return{fields:e,files:s}}function dm(t){return new ReadableStream({async start(){},async pull(e){await t(e)},cancel(){}})}async function hm(t){if(!t)return{data:"",contentType:"text/plain"};if(typeof t=="string")return{data:t,contentType:"text/plain"};if(t instanceof ArrayBuffer||t instanceof Uint8Array){let e;return t instanceof Uint8Array?(e=new ArrayBuffer(t.byteLength),new Uint8Array(e).set(t)):e=t,{data:Uo(e),contentType:"application/octet-stream",encoding:"base64"}}if(t instanceof Blob){const e=await cm(t);return{data:Uo(e),contentType:t.type||"application/octet-stream",encoding:"base64"}}if(t instanceof FormData){const e=await um(t);return{data:JSON.stringify(e),contentType:"multipart/form-data",encoding:"json"}}throw new Error("Unsupported body type")}const er=m.createLogger({name:"kos-fetch"}),fm=process.env.KOS_WS_TIMEOUT?parseInt(process.env.KOS_WS_TIMEOUT):3e4,pm=()=>new Promise(t=>{setTimeout(()=>{t(!0)},0)}),gm=t=>t!=null&&t.studio?ll:t!=null&&t.fos?ul:dl,mm=async(t,e)=>{const s=I.getInstance().transport;await s.whenReady();const r=dt(),o=new URL(t),n=`${o.pathname}${o.search}`;er.debug(`path: ${n}`);const i=(e==null?void 0:e.timeout)||fm,a=gm(e),c=await hm(e==null?void 0:e.body),u={};c.contentType&&(u["content-type"]=c.contentType),c.encoding&&(u["content-encoding"]=c.encoding);const d=Xe(a({path:n,requestId:r,method:(e==null?void 0:e.method)||"GET",destinationAddress:(e==null?void 0:e.destinationAddress)||"",ordered:e==null?void 0:e.ordered,tracker:e==null?void 0:e.tracker,bridge:e==null?void 0:e.bridge,headers:{...e==null?void 0:e.headers,...u}}),c.data);return new Promise(h=>{let f=null,p=null;if(e!=null&&e.signal){if(e.signal.aborted){h({headers:ss({}),status:0,ok:!1,json:async()=>null,body:rs(""),redirected:!1,statusText:"Request aborted",type:"basic",url:"",clone:function(){throw new Error("Function not implemented.")},bodyUsed:!1,arrayBuffer:function(){throw new Error("Function not implemented.")},blob:function(){throw new Error("Function not implemented.")},formData:function(){throw new Error("Function not implemented.")},text:function(){throw new Error("Function not implemented.")}});return}e.signal.addEventListener("abort",()=>{p&&clearTimeout(p),f&&f(),h({headers:ss({}),status:0,ok:!1,json:async()=>null,body:rs(""),redirected:!1,statusText:"Request aborted",type:"basic",url:"",clone:function(){throw new Error("Function not implemented.")},bodyUsed:!1,arrayBuffer:function(){throw new Error("Function not implemented.")},blob:function(){throw new Error("Function not implemented.")},formData:function(){throw new Error("Function not implemented.")},text:function(){throw new Error("Function not implemented.")}})})}p=setTimeout(()=>{er.error(`Timeout occurred - url: ${t}`),f&&f(),h({headers:ss({}),status:404,ok:!1,json:async()=>null,body:rs(""),redirected:!1,statusText:"",type:"basic",url:"",clone:function(){throw new Error("Function not implemented.")},bodyUsed:!1,arrayBuffer:function(){throw new Error("Function not implemented.")},blob:function(){throw new Error("Function not implemented.")},formData:function(){throw new Error("Function not implemented.")},text:function(){throw new Error("Function not implemented.")}})},i);const y=C(r,E=>{p&&clearTimeout(p);const _=(E==null?void 0:E.headers)||{},k=_["content-type"]||"text/plain",U=_["content-encoding"],O=(E==null?void 0:E.body)||"";let S=O;if(U==="base64"&&O)try{S=am(O)}catch(j){er.error("Failed to decode base64 response",j)}const z={headers:ss(_),status:_.status&&parseInt(_.status)||200,ok:_.status==="200",json:async()=>{try{if(typeof S=="string")return S.length?JSON.parse(S):null;{const Z=new TextDecoder().decode(S);return Z.length?JSON.parse(Z):null}}catch{throw Error("Not a JSON response")}},text:async()=>typeof S=="string"?S:new TextDecoder().decode(S),arrayBuffer:async()=>S instanceof ArrayBuffer?S:new TextEncoder().encode(S).buffer,blob:async()=>S instanceof ArrayBuffer?lm(S,k):new Blob([S],{type:k}),formData:async()=>{const j=new FormData;if(k==="multipart/form-data"&&typeof S=="string")try{const Z=JSON.parse(S);Z.fields&&Object.entries(Z.fields).forEach(([Ke,qe])=>{j.append(Ke,qe)}),Z.files&&er.warn("File reconstruction in FormData not fully implemented")}catch{throw new Error("Failed to parse FormData")}return j},body:e!=null&&e.stream?dm(async j=>{if(S instanceof ArrayBuffer)j.enqueue(new Uint8Array(S));else{const Z=new TextEncoder;j.enqueue(Z.encode(S))}j.close()}):rs(typeof S=="string"?S:""),redirected:!1,statusText:"",type:"basic",url:"",clone:function(){return{...this}},bodyUsed:!1};y.unsubscribe(),pm().then(()=>h(z))});f=y.unsubscribe;const w=e!=null&&e.fos?s.fosSocket:s.socket;if(!w)throw Error(`No web socket transport available: ${e}`);w==null||w.send(d)})};exports.BASE_URL="kos:";exports.kosFetch=mm;if(process.env.KOS_MOCK_FETCH==="true"){const t=process.env.KOS_PORT||"9999";exports.kosFetch=fetch,exports.BASE_URL=`http://localhost:${t}`}const ym=m.createLogger({name:"kos-model-visitor",group:"kos-ui-core"});class bm{constructor(){l(this,"visitedModels",new Set);this.visitedModels=new Set}start(e){var r;if(e.id===void 0)throw new Error("rootModel must have an id");const s=I.getInstance().modelManager.getModelById(e.id);if(!s)throw new Error(`Could not find rootModel with id: ${e.id}`);this.visitedModels.clear(),(r=s.accept)==null||r.call(s,this)}visit(e){var r;if(this.visitedModels.has(e.modelId)){ym.info(`model ${e.modelId} already visited`);return}const s=!!this.visitModel(e.modelData,this);this.visitedModels.add(e.modelId),!s&&((r=e.getChildren)==null||r.call(e).forEach(o=>{var n;(n=o.accept)==null||n.call(o,this)}))}}class Sl{constructor(){l(this,"middlewares",[])}use(e){this.middlewares.push(e)}async execute(e){let s=0;const r=async()=>{s++,s<this.middlewares.length&&await this.middlewares[s](e,r)};await this.middlewares[s](e,r)}}const vm=async(t,e)=>{const s=new Sl;e.forEach(o=>s.use(o));const r={data:t,result:{}};return await s.execute(r),r.result},zt=t=>({type:t,build:(e,s)=>I.getInstance().modelManager.createModelInstance(t,e,s).data,buildAsync:async(e,s)=>{const r=I.getInstance().modelManager.createModelInstance(t,e,s);return await r.model.whenInitialized(),r.data}}),wm=t=>{I.getInstance().modelManager.registerModel(t)},Em=(t,e)=>{I.getInstance().modelManager.registerCompanionModel(t,e)},qi="/kos/ui/internal/heartbeat/",Mm=({relationshipId:t,destinationAddress:e,onAbort:s,waitTime:r,beatTime:o})=>{const n=I.getInstance().transport,i=new AbortController;let a=performance.now();const c=n.subscribeTopic({topic:`${qi}${t}`,callback:()=>{a=performance.now()}}),u=r??3e3,d=window.setInterval(()=>{let w=performance.now()-a;w=w/1e3,w>u/1e3&&i.abort()},u),h=o??2e3,f=window.setInterval(()=>{bl({msg:{},options:{topic:`${qi}${t}`,destinationAddress:e}})},h),p=()=>{window.clearInterval(f),window.clearInterval(d),c()},y=()=>{p(),s&&s(),i.signal.removeEventListener("abort",y)};return i.signal.addEventListener("abort",y),{cleanUpHeartbeat:p}},Il=(...t)=>e=>t.reduce((s,r)=>r(s),e),Tm={maxAttempts:5,baseDelayMs:100,backoffFactor:1.5};async function _m(t,e){let s=1;const r={...Tm,...e},{maxAttempts:o,baseDelayMs:n,backoffFactor:i}=r;let a=n;for(;s<=o;)try{return await t()}catch(c){if(m.error(`Attempt ${s} failed: ${c}`),s<o)a=n*Math.pow(i,s),await new Promise(u=>setTimeout(u,a)),s++;else throw c}throw new Error("All attempts failed")}const Sm=m.createLogger({name:"kos-service-request"}),ce=t=>({isMock:!1,URL:exports.BASE_URL}),Im=(t,e,s)=>async({id:r,tracker:o,urlOverride:n,ordered:i,studio:a,fos:c,bridge:u,destinationAddress:d})=>{const h={method:"DELETE"};t&&(h.destinationAddress=t),o&&(h.tracker=o),Vt(h,{ordered:i,studio:a,fos:c,bridge:u,destinationAddress:d});const f=await s(n||`${e}/${r}`,h);if(!f.ok)throw Error(`There was a problem deleting the model; returned status ${f.status}`);return await f.json()},Vt=(t,{ordered:e,studio:s,fos:r,destinationAddress:o,bridge:n,timeout:i})=>(i&&(t.timeout=i),e&&(t.ordered=e),s&&(t.studio=s),r&&(t.fos=r),n&&(t.bridge=n),(o||o==="")&&(t.destinationAddress=o),t),Om=(t,e,s)=>async({urlOverride:r,ordered:o,studio:n,fos:i,bridge:a,timeout:c,destinationAddress:u})=>{const d={method:"GET"};t&&(d.destinationAddress=t),Vt(d,{timeout:c,ordered:o,studio:n,fos:i,bridge:a,destinationAddress:u});const f=await s(r||e,d);if(!f.ok){let y;try{y=await f.json()}catch{}throw new me(`There was a problem retrieving the model; returned status ${f.status}`,y)}return await f.json()},$m=(t,e,s)=>async({urlOverride:r,ordered:o,studio:n,fos:i,bridge:a,tracker:c,timeout:u,destinationAddress:d})=>{const h={method:"GET"};t&&(h.destinationAddress=t),c&&(h.tracker=c),Vt(h,{timeout:u,ordered:o,studio:n,fos:i,bridge:a,destinationAddress:d});const f=r||e;Sm.debug(`resolvedUrl: ${f}`);const p=await s(f,h);if(!p.ok){let w;try{w=await p.json()}catch{}throw new me(`There was a problem retrieving the model; returned status ${p.status}`,w)}return await p.json()},Cm=(t,e,s)=>async({urlOverride:r,id:o,ordered:n,studio:i,fos:a,bridge:c,timeout:u,destinationAddress:d})=>{const h={method:"GET"};t&&(h.destinationAddress=t),Vt(h,{timeout:u,ordered:n,studio:i,fos:a,bridge:c,destinationAddress:d});const f=r||`${e}/${o}`,p=await s(f,h);if(!p.ok){let w;try{w=await p.json()}catch{}throw new me(`There was a problem retrieving the model; returned status ${p.status}`,w)}return await p.json()};class me extends Error{constructor(s,r){super(s);l(this,"payload");this.name="FetchException",this.payload=r}}const zi=(t,e,s)=>async({model:r,urlOverride:o,ordered:n,tracker:i,studio:a,fos:c,bridge:u,timeout:d,destinationAddress:h})=>{const f={method:"POST",body:typeof r=="string"?r:JSON.stringify(r)};t&&(f.destinationAddress=t),i&&(f.tracker=i),Vt(f,{timeout:d,ordered:n,studio:a,fos:c,bridge:u,destinationAddress:h});const p=await s(o||e,f);if(!p.ok){let w;try{w=await p.json()}catch{}throw new me(`There was a problem sending the POST data; returned status ${p.status}`,w)}return await p.json()},Vi=(t="POST",e,s,r)=>async({model:o,id:n,urlOverride:i,ordered:a,studio:c,fos:u,bridge:d,timeout:h,destinationAddress:f})=>{const p={method:t};o&&(p.body=JSON.stringify(o)),e&&(p.destinationAddress=e),Vt(p,{timeout:h,ordered:a,studio:c,fos:u,bridge:d,destinationAddress:f});const y=await r(i||`${s}/${n}`,p);if(!y.ok){let E;try{E=await y.json()}catch{}throw new me(`There was a problem modifying the model; returned status ${y.status}`,E)}return await y.json()},oe={build:({destinationAddress:t="",basePath:e,getAllPath:s,getOnePath:r,deleteModelPath:o,addModelPath:n,modifyModelPath:i,mock:a=!1})=>{const c=a?fetch:exports.kosFetch;return{getAll:Om(t,s||e,c),getModelById:Cm(t,r||e,c),getOne:$m(t,r||e,c),addModel:zi(t,n||e,c),deleteModel:Im(t,o||e,c),modifyModel:Vi("POST",t,i||e,c),putModel:Vi("PUT",t,i||e,c),postModel:zi(t,n||e,c)}}};function Dm(t,e,s="get"){const r=t.serviceResponses;if(r)return r.getByPath(e,s)}function xm(t,e,s="get"){const r=t.serviceResponses;return r?r.has(`${s.toUpperCase()}:${e}`):!1}function Am(t,e,s="get"){const r=t.serviceResponses;r&&r.delete(`${s.toUpperCase()}:${e}`)}function Rm(t,e){const s=t.serviceResponses;s&&s.clearPath(e)}function Pm(t){const e=t.serviceResponses;e&&e.clear()}const km=dt(),Ol=()=>`kos-${km}`,Lm=t=>!!t&&!t.includes("VM_SERVICE")&&t.startsWith(Ol()),Cn=async(t,e=6e4)=>new Promise((s,r)=>{const{unsubscribe:o}=C(t,i=>{D.debug(`recieved response for refId ${t}: ${i}`),o(),clearTimeout(n);try{const a=i!=null&&i.body?JSON.parse(i.body):{};s(a)}catch{const a=(i==null?void 0:i.body)||{};s(a)}}),n=setTimeout(()=>{o(),r(Error(`Request with ID ${t} timed out. Cancelling.`))},e)}),Fm=async(t,e,s)=>{const r=Cn(s),o=await Promise.allSettled([t(e),r]);if(o[0].status==="fulfilled"){if(o[1].status==="rejected")throw Error(o[1].reason);if(o[0].value){if(o[1].value.error)throw Error(o[1].value.error);return o[0].value.data=o[1].value,o[0].value}}else throw Error(o[0].reason)},Nm=async({topic:t,msg:e,requestId:s})=>{const r=s??dt(),o=Cn(r);V(t,e,{sync:r});const n=await o;if(n.error)throw Error(n.error);return n},fe=new Map;class $l{constructor(e){l(this,"_context");l(this,"_parent");l(this,"_id");this._id=e,this._context=new M.ObservableMap({}),this._parent="",M.makeAutoObservable(this)}setParent(e){J(()=>{this._parent=e})}get id(){return this._id}get context(){return this._context}get parentModel(){var e;if(this._parent)return(e=$e(this._parent))==null?void 0:e.model}get companionModels(){const e=$e(this._id);return e!=null&&e.model?Bc(e.model):[]}get(e){var s,r;if(this._context.has(e))return this._context.get(e);if(this.companionModels.length>0){const o=this.companionModels.find(n=>{var i;return!n.id||!fe.has(n.id)?!1:(i=fe.get(n.id))==null?void 0:i.context.has(e)});if(o)return(s=fe.get(o.id))==null?void 0:s.get(e)}if(this._parent)return(r=fe.get(this._parent))==null?void 0:r.get(e)}set(e,s){this._context.set(e,s)}remove(e){this._context.delete(e)}clear(){this._context.clear()}}const Y={createContext:(t,e)=>{const s=fe.get(t)??new $l(t);if(e){if(!fe.has(e))throw new Error(`Parent context ${e} does not exist`);s.setParent(e)}else t!=="root"&&s.setParent("root");return fe.set(t,s),s},getContext:t=>fe.get(t),deleteContext:t=>{fe.delete(t)},setParentContext:(t,e)=>{var s;if(!fe.has(e))throw new Error(`Parent context ${e} does not exist`);(s=fe.get(t))==null||s.setParent(e)},rootContext:()=>fe.get("root")};Y.createContext("root");const Um=t=>Y.getContext(t.id),tt=m.createLogger({name:"kos-data-container"});class Dn{constructor(e){l(this,"_data");l(this,"_sortKey");l(this,"_revision");l(this,"_index");l(this,"_optionsMap");l(this,"_disposerMap",new Map);l(this,"idx");l(this,"_maxCapacity");l(this,"_evictionStrategy");l(this,"_evictionBatchSize");l(this,"_insertionOrder",[]);l(this,"_accessTimes");l(this,"_customEvictionFilter");this._data=M.observable.map(new Map),this._sortKey=e==null?void 0:e.sortKey,this._revision=1,this._optionsMap=(e==null?void 0:e.indexMap)||{};const s=e!=null&&e.indexMap?Object.keys(e.indexMap).reduce((r,o)=>(r[o]=void 0,r),{}):{};this._index=M.observable.map(s),this.idx=Oe(),this._maxCapacity=e==null?void 0:e.maxCapacity,this._evictionStrategy=(e==null?void 0:e.evictionStrategy)||"fifo",this._evictionBatchSize=(e==null?void 0:e.evictionBatchSize)??Math.max(10,Math.ceil(((e==null?void 0:e.maxCapacity)??100)*.1)),this._customEvictionFilter=e==null?void 0:e.customEvictionFilter,this._evictionStrategy==="lru"&&this._maxCapacity&&(this._accessTimes=M.observable.map(new Map)),M.makeAutoObservable(this,{}),this.init()}init(){Object.keys(this._optionsMap).forEach(e=>{const s=this._optionsMap[e],r=new Tn({container:this,key:s});this._index.set(e,r),this.idx[e]=r.data})}[Symbol.iterator](){return this.data[Symbol.iterator]()}get index(){return this._index}get indexKeys(){return Array.from(this.index.keys()).reduce((e,s)=>{var r;return e[s]=(r=this.index.get(s))==null?void 0:r.keys,e},{})}get revision(){return this._revision}addAll(e){M.runInAction(()=>{e.forEach(s=>this.addModel(s))})}removeAll(e){M.runInAction(()=>{e.forEach(s=>this.removeModel(s))})}sortFn(e,s){const r=this._sortKey;return r?String(e[r]).localeCompare(String(s[r]),void 0,{numeric:!0}):0}get data(){const e=Array.from(this._data.values());return this._sortKey&&e.sort(this.sortFn.bind(this)),e}increment(){M.runInAction(()=>{this._revision=this._revision+1})}addModel(e,s){const r=this._ensureObservable(e);this._cleanupExistingDisposer(e.id),this._persistData(r),this._trackDataMetadata(r),this._enforceCapacityLimits(),this._configureDataMonitoring(r),s||this.increment()}_ensureObservable(e){return M.isObservable(e)?e:M.observable.object(e)}_cleanupExistingDisposer(e){if(!e)return;const s=this._disposerMap.get(e);s&&(s(),this._disposerMap.delete(e))}_persistData(e){this._data.set(e.id||"",e)}_trackDataMetadata(e){this._maxCapacity&&(this._insertionOrder.push(e.id||""),this._accessTimes&&this._accessTimes.set(e.id||"",Date.now()))}_enforceCapacityLimits(){this._maxCapacity&&this._data.size>this._maxCapacity&&this._evictModels()}_configureDataMonitoring(e){const s=M.observe(e,r=>{Object.values(this._optionsMap||{}).includes(r.name)&&this.increment()});this._disposerMap.set(e.id||"",s)}removeModel(e){this._data.delete(e);const s=this._insertionOrder.indexOf(e);s!==-1&&this._insertionOrder.splice(s,1),this._accessTimes&&this._accessTimes.delete(e),this.increment();const r=this._disposerMap.get(e);r&&(r(),this._disposerMap.delete(e))}updateModel(e){const s=M.observable.object(e);this._data.set(s.id||"",s),this.increment()}getModel(e){const s=this._data.get(e);return s&&this._accessTimes&&this._accessTimes.set(e,Date.now()),s}getIndexKeys(e){return this.index.has(e)?this.index.get(e).keys??[]:(tt.info(`index ${e} not found in ${Array.from(this.index.keys())}`),[])}getIndexByKey(e,s){if(this.index.has(e)){const r=this.index.get(e);return r.index.has(s)?r.getByKey(s):(tt.info(`key ${s} not found in ${e} index: ${Array.from(r.index.keys())}`),[])}else return tt.info(`index ${e} not found in ${Array.from(this.index.keys())}`),[]}_evictModels(){if(!this._maxCapacity)return;const e=this._data.size-this._maxCapacity;if(e<=0)return;const s=Math.min(this._evictionBatchSize,e);this._logDataCapacityWarning(s);const r=this._selectDataForEviction(s);this._removeEvictedData(r),this._logDataEvictionComplete(r.length)}_logDataCapacityWarning(e){tt.warn(`Data container capacity exceeded (${this._data.size}/${this._maxCapacity}). Evicting ${e} items using ${this._evictionStrategy} strategy. This may indicate missing cleanup handlers or data inconsistency.`)}_selectDataForEviction(e){switch(this._evictionStrategy){case"fifo":return this._selectFifoData(e);case"lru":return this._selectLruData(e);case"custom":return this._selectCustomData(e);default:return this._selectFifoData(e)}}_selectFifoData(e){const s=[];for(let r=0;r<e&&this._insertionOrder.length>0;r++){const o=this._insertionOrder.shift();o&&this._data.has(o)&&s.push(o)}return s}_selectLruData(e){const s=[];return this._accessTimes&&Array.from(this._accessTimes.entries()).sort((o,n)=>o[1]-n[1]).slice(0,e).forEach(([o])=>{this._data.has(o)&&s.push(o)}),s}_selectCustomData(e){return this._customEvictionFilter?this._customEvictionFilter(this.data).slice(0,e).map(r=>r.id):(tt.error("Custom eviction strategy specified but no customEvictionFilter provided. Falling back to FIFO."),this._selectFifoData(e))}_removeEvictedData(e){e.forEach(s=>{var o;const r=this._data.get(s);tt.warn(`Evicting data item: ${s}`,{itemId:s,itemType:r?(o=r.constructor)==null?void 0:o.name:"unknown",strategy:this._evictionStrategy}),this.removeModel(s)})}_logDataEvictionComplete(e){tt.info(`Evicted ${e} data items. Current size: ${this._data.size}/${this._maxCapacity}`)}async clear(){this._data.clear(),this.increment()}filter(e,s){return this.data.filter(e,s)}sort(e){return this.data.sort(e)}map(e,s){return this.data.map(e,s)}forEach(e,s){this.data.forEach(e,s)}toJSON(){return{indexes:this.indexKeys,data:this.data.map(s=>({id:s.id}))}}}class jm{constructor({type:e,model:s,childRegistration:r}){l(this,"type");l(this,"childRegistration");l(this,"model");this.type=e,this.model=s,this.childRegistration=r}get factory(){return ae.Factory.create(this.type)}get registration(){return{[this.type]:{class:this.model,singleton:!1,factory:this.factory},...this.childRegistration}}get predicate(){return _e(this.type)}}class Bm{constructor({type:e,model:s,childRegistration:r}){l(this,"type");l(this,"model");l(this,"childRegistration");this.type=e,this.model=s,this.childRegistration=r}get factory(){return ae.Singleton.create(this.type)}get registration(){return{[this.type]:{class:this.model,singleton:!0,factory:this.factory},...this.childRegistration}}get predicate(){return _e(this.type)}}class Cl{constructor(){l(this,"_token");M.makeAutoObservable(this),C("token",e=>{this.token=e==null?void 0:e.body})}get token(){return this._token}set token(e){this._token=e}}class Dl{constructor(){l(this,"routes",[]);l(this,"openApiRoutes",[])}use(e,s,...r){this.routes.push({method:e,path:s,middlewares:r});const o=this.extractOpenApiParams(s);this.openApiRoutes.push({method:e,path:s,parameters:o})}remove(e,s){const r=this.routes.length;return this.routes=this.routes.filter(o=>!(o.method===e&&o.path===s)),this.openApiRoutes=this.openApiRoutes.filter(o=>!(o.method===e&&o.path===s)),r-this.routes.length}removeAllForPath(e){const s=this.routes.length;return this.routes=this.routes.filter(r=>r.path!==e),this.openApiRoutes=this.openApiRoutes.filter(r=>r.path!==e),s-this.routes.length}getRoutes(){return this.routes.map(e=>({method:e.method,path:e.path}))}async handle(e,s){var a;const{path:r,query:o,params:n}=this.extractPathParams(e.path),i={...e,params:n,query:o};for(const c of this.routes){const u=this.matchRoute(c.path,r);if(c.method===e.method&&u){i.params=u;let d=0;const h=async()=>{if(d<c.middlewares.length){const f=c.middlewares[d++];await f(i,s,h)}};await h();return}}(a=s.status)==null||a.call(s,404).send({error:"Route not found"})}extractOpenApiParams(e){return e.split("/").filter(s=>s.startsWith(":")).map(s=>({name:s.slice(1),in:"path",required:!0,schema:{type:"string"}}))}generateOpenApiSpec(){const e={};for(const s of this.openApiRoutes)e[s.path]||(e[s.path]={}),e[s.path][s.method.toLowerCase()]={summary:s.description||`Handles ${s.method} ${s.path}`,parameters:s.parameters||[],responses:{200:{description:"Successful response"}}};return{openapi:"3.0.0",info:{title:"Kos Router API",version:"1.0.0",description:"Dynamically generated OpenAPI documentation"},paths:e}}extractPathParams(e){const[s,r]=e.split("?"),o=this.parseQueryParams(r);for(const n of this.routes){const i=this.matchRoute(n.path,s);if(i)return{path:s,query:o,params:i}}return{path:s,query:o,params:{}}}matchRoute(e,s){const r=e.split("/").filter(Boolean),o=s.split("/").filter(Boolean);if(r.length!==o.length)return null;const n={};for(let i=0;i<r.length;i++)if(r[i].startsWith(":"))n[r[i].slice(1)]=decodeURIComponent(o[i]);else if(r[i]!==o[i])return null;return n}parseQueryParams(e){return e?e.split("&").reduce((s,r)=>{const[o,n]=r.split("=").map(decodeURIComponent);return s[o]=n??"",s},{}):{}}}const xl=m.createLogger({name:"intent-service"}),Hm=t=>{an(`/kos/intent/${t.type}`)?V(`/kos/intent/${t.type}`,t.options,{"kos.intent.type":t.type}):xl.info(`No subscribers for intent ${t.type}. Intent not sent.`)},Km=async t=>new Promise(e=>{const{type:s,options:r}=t;if(an(`/kos/intent/${t.type}`)){const o=dt(),{unsubscribe:n}=C(o,a=>{clearTimeout(i),n(),a&&(a.headers=a.headers||{},a.headers["kos.intent.type"]=s,a.headers.responseId=o),e([null,{body:a==null?void 0:a.body,payload:a}])}),i=setTimeout(()=>{n(),e([`Intent ${s} timed out after 1 second`,null]),console.warn(`Intent ${s} timed out after 1 second`)},1e3);V(`/kos/intent/${s}`,r,{"kos.intent.type":s,sync:o})}else xl.info(`No subscribers for intent ${t.type}. Intent not sent.`),e([null,{body:void 0,payload:void 0}])}),Pe=m.createLogger({name:"app-startup-service"});async function Al(t,e={}){const{timeout:s=3e4,throwOnTimeout:r=!0,requirePostStarted:o=!1}=e;if(t.length===0)return Pe.warn("No app IDs provided to waitForAppsToStart"),!0;Pe.debug(`Waiting for apps to start: ${t.join(", ")}`);try{const n=t.map(c=>`/kos/app/started/${c}`),i=await un(n,{getCurrentState:async()=>{try{const{default:c}=await Promise.resolve().then(()=>al),[u,d]=await c.get("/api/kos/apps/started");return u?(Pe.error("Error fetching started apps:",u),[]):d}catch(c){Pe.error("Failed to fetch app startup status:",c)}return[]},shouldUseFetchedState:c=>t.every(u=>{const d=c.find(h=>h.appId===u);return!(!d||!d.started||o&&!d.postStarted)}),timeout:s}),a=t.filter(c=>{const u=i.find(d=>d.appId===c);return!!(!u||!u.started||o&&!u.postStarted)});if(a.length>0){const c=`Apps not started: ${a.join(", ")}`;if(Pe.error(c),r)throw new Error(`App startup timeout: ${c}`);return!1}return Pe.info(`All apps started successfully: ${t.join(", ")}`),!0}catch(n){const i=`Failed to wait for apps to start: ${t.join(", ")}`;if(Pe.error(i,n),r)throw new Error(`${i} - ${n instanceof Error?n.message:String(n)}`);return!1}}async function qm(t,e={}){return Al([t],e)}async function zm(t,e=!1){const s={};try{const r=await exports.kosFetch("kos:///api/kos/apps/started");if(!r.ok)return t.forEach(i=>s[i]=!1),s;const o=await r.json(),n=(o==null?void 0:o.data)??[];t.forEach(i=>{const a=n.find(c=>c.appId===i);s[i]=(a==null?void 0:a.started)===!0&&(!e||(a==null?void 0:a.postStarted)===!0)})}catch(r){Pe.error("Failed to check app startup status:",r),t.forEach(o=>s[o]=!1)}return s}async function Vm(){try{const t=await exports.kosFetch("kos:///api/kos/apps/started");if(!t.ok)return[];const e=await t.json();return(e==null?void 0:e.data)??[]}catch(t){return Pe.error("Failed to fetch started apps:",t),[]}}const jo=M.when,xn=M.computed,J=M.runInAction,W=M.autorun,Rl=M.reaction,An=M.observable,Rn="Not Assigned",Gm="kos.trouble.added",Ym="kos.trouble.removed";var we=(t=>(t.TroubleRank="kos.trouble.rank.mapper",t.TroubleColor="kos.trouble.color.mapper",t.TroubleRole="kos.trouble.role.mapper",t))(we||{}),Ts=(t=>(t.TIME_CHANGE="/kos/internal/time/time",t.DAY_CHANGE="/kos/internal/time/day",t.TIMEZONE_CHANGE="/kos/internal/time/timezone",t))(Ts||{});const Pl=m.createLogger({name:"config-bean-service",group:"Services"}),Pn=exports.BASE_URL,kl=t=>(t==null?void 0:t.decimals)!==void 0,{postModel:Wm,getOne:Qm}=oe.build({destinationAddress:"",basePath:`${Pn}/kos/config/`}),Ll=async(t,e,s="/api/kos/config")=>(Pl.debug(`sending modify request for ConfigBean: ${t}`),Wm({model:e,urlOverride:`${Pn}${s}/${t}`})),Fl=async(t,e="/api/kos/config")=>(Pl.debug(`sending get request for ConfigBean: ${t}`),await Qm({urlOverride:`${Pn}${e}/details/${t}/15`})),kn=t=>t.toLowerCase()==="true"||t.toLowerCase()==="false",Xr=t=>{try{const e=Number(t);return!isNaN(e)}catch{return!1}};function Nl(t=[]){return t.reverse().reduce((e,s)=>{const{overrides:r}=s;return r&&(e={...e,...r}),e},{})}function Ul(t,e="",s={}){for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)){const o=e?`${e}.${r}`:r;typeof t[r]=="object"&&t[r]!==null&&!Array.isArray(t[r])?Ul(t[r],o,s):s[o]=t[r]}return s}const jl=(t,e)=>{const s=t.details[0].bean||Nl(t.details[0].scopes),r=Ul(s);M.runInAction(()=>{const o={...r};e.props.setValues(o)})},Bl=(t,e)=>{M.runInAction(()=>{t.changes.forEach(s=>{const r=s.attr;let o=s.currentValue,n=s.previousValue;typeof o=="string"&&kn(o)&&(o=o.toLowerCase()=="true",n=(n==null?void 0:n.toLowerCase())=="true"),typeof o=="string"&&Xr(o)&&(o=Number(o),n=Number(n)),e.props[r]=o,e.prevProps[r]=n})})},Hl=t=>Object.fromEntries(t.props.entries),Zm=t=>e=>s=>t.build(e,s);var Xm=Object.defineProperty,Jm=Object.getOwnPropertyDescriptor,Kl=(t,e,s,r)=>{for(var o=r>1?void 0:r?Jm(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Xm(e,s,o),o};function ey(t,e){for(const s of t)if(new RegExp(`^${s}$`).test(e))return s}const Ln="config-bean-model",tr=m.getLogger(Ln),ty=ht("path");let br=class{constructor(t,e){l(this,"_modifyConfigBean");l(this,"_getConfigBean");l(this,"_schema");l(this,"id");l(this,"path");l(this,"props");l(this,"prevProps");l(this,"serviceBasePath");Object.assign(this,e),this.id=t,this.path=e.path,this.serviceBasePath=e.serviceBasePath;const{modifyConfigBean:s=Ll,getConfigBean:r=Fl}=e;this._modifyConfigBean=s,this._getConfigBean=r,this.props=Oe(),this.prevProps=Oe()}get values(){return this.props.values}async ready(){tr.debug(`readying config bean ${this.path}`),tr.debug(`complete readying config bean ${this.path}`)}async load(){tr.debug(`loading config bean ${this.path}`);const t=await this._getConfigBean(this.path,this.serviceBasePath);if(t!=null&&t.data){const e=t.data;jl(e,this),tr.debug(this.values);const s=t==null?void 0:t.data.details[0].schema;J(()=>{s&&(this._schema=s)})}}get schemaKeys(){var t;return Object.keys(((t=this._schema)==null?void 0:t.schema)||{})}getSchemaForProperty(t){var s,r;if(this.schemaKeys.includes(t))return(s=this._schema)==null?void 0:s.schema[t];const e=ey(this.schemaKeys,t);if(e)return(r=this._schema)==null?void 0:r.schema[e]}async updateProperty(t,e){this.props[t]=e,await this.updateConfigBean()}async updateConfigBean(){const t=Hl(this);await this._modifyConfigBean(this.path,t,this.serviceBasePath)}handleConfigBeanUpdated(t){Bl(t,this)}};Kl([H({topic:`/kos/config/${ty}`,websocket:!0})],br.prototype,"handleConfigBeanUpdated",1);br=Kl([R(Ln)],br);const Is=new be({class:br,type:Ln}),Jr=({path:t,lazy:e,serviceBasePath:s})=>(r,o)=>{r[F]=r[F]||{},r[F][o]={modelType:Is.type,id:`${Is.type}-${t}`,options:{path:t,serviceBasePath:s},lifecycle:x.INIT,lazy:e}},{URL:ql}=ce(),{getOne:sy,getAll:ry}=oe.build({basePath:`${ql}/api/kos/regions/info`}),zl=async()=>{try{return await sy({})}catch{return}},Vl=async()=>{try{return await ry({urlOverride:`${ql}/api/kos/regions`})}catch{return}},oy=Object.freeze(Object.defineProperty({__proto__:null,getRegionInfo:zl,getRegions:Vl},Symbol.toStringTag,{value:"Module"}));var ue=(t=>(t[t.family=0]="family",t[t.scale=1]="scale",t[t.offset=2]="offset",t[t.decimals=3]="decimals",t[t.alias=4]="alias",t[t.system=5]="system",t))(ue||{});const Gl={s:["time",1,0,0],second:["time",1,0,0],m:["time",1/60,0,0],minute:["time",1/60,0,0],h:["time",1/3600,0,0],hour:["time",1/3600,0,0],day:["time",1/86400,0,0],week:["time",1/604800,0,0],month:["time",1/2628e3,0,0],year:["time",1/31536e3,0,0],default:["time",1/.001,0,0],ms:["time",1/.001,0,0],millisecond:["time",1/.001,0,0],microsecond:["time",1/1e-6,0,0],nanosecond:["time",1/1e-9,0,0],picosecond:["time",1/1e-12,0,0]};function ny(t,e){const s=e.id,r=e.units.reduce((o,n)=>{const i=[n.measure,n.scale,n.offset,n.decimals,n.alias,s];return o[n.name]=i,n.alias&&(o[n.alias]=i),o},{...Gl});return{...t,...r}}function iy(t,e){const s=e.id,r=e.units.reduce((o,n)=>{const i=o[n.measure]||{},a=i[s]||{};i[s]=a;const c=[n.measure,n.scale,n.offset,n.decimals,n.alias,s];return a[n.name]=c,Object.hasOwn(n,"default")&&Object.defineProperty(a,"default",{value:c,writable:!0,enumerable:!0,configurable:!0}),o[n.measure]=i,n.alias&&(o[n.alias]=i),o},{time:{[s]:{...Gl}}});return Object.keys(r).forEach(o=>{t[o]={...t[o],...r[o]}}),t}function ay(t,e){const s=e.id,r=e.units.reduce((o,n)=>{const i=o[n.measure]||{};return Object.hasOwn(n,"default")&&(i[s]=n.name),o[n.measure]=i,o},{time:{[s]:"millisecond"}});return Object.keys(r).forEach(o=>{t[o]={...t[o],...r[o]}}),t}var cy=Object.defineProperty,ly=Object.getOwnPropertyDescriptor,Fn=(t,e,s,r)=>{for(var o=r>1?void 0:r?ly(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&cy(e,s,o),o};const dr="region-info-model",es=m.createLogger({name:"region-info-model"});let Os=class{constructor(t){l(this,"id");l(this,"unitSystemMap");l(this,"measureMap");l(this,"defaultMeasureMap");l(this,"regionMap");l(this,"timeFormats");l(this,"dateFormats");l(this,"unitSystems");l(this,"regionSource");l(this,"region");l(this,"regions",[]);l(this,"timeZoneMap",{});this.id=t,this.unitSystems={},this.unitSystemMap={},this.measureMap={},this.defaultMeasureMap={},this.timeFormats={},this.regions=[],this.dateFormats={},this.timeZoneMap={},this.regionMap={}}get availableRegions(){return this.regions}get defaultUnitSystem(){return String(this.regionSource.props.unitSystemId).toLowerCase()||""}get unitSystemId(){return this.defaultUnitSystem}get timeFormatId(){const t=this.regionSource.props.timeFormatId;if(!t)return"";const e=String(t),s=this.timeFormats[e];return s?String(s.id):""}get selectedTimeFormat(){const t=this.timeFormatId;return t?String(this.timeFormats[t].format):"HH:mm:ss"}get is12HourTimeFormat(){const t=this.timeFormatId;return t?this.timeFormats[t].ampm:!0}get dateFormatId(){const t=this.regionSource.props.dateFormatId;if(!t)return"";const e=String(t);return e?this.dateFormats[e].id:""}get selectedDateFormat(){const t=this.dateFormatId;return t?this.dateFormats[t].format:""}get selectedDateOrder(){const t=this.dateFormatId;return t?this.dateFormats[t].order.toLowerCase():"dmy"}get selectedCountry(){return this.regionSource.props.country||"en"}get selectedTimeZone(){return this.regionSource.props.timeZone||""}get timeZones(){return this.regionId?this.timeZoneMap[this.regionId]||[]:[]}get allTimeZones(){return Intl.supportedValuesOf("timeZone")}get regionId(){return this.region.props.regionId||""}get selectedRegion(){return this.regionMap[this.regionId]}get selectedUnitSystem(){return String(this.regionSource.props.unitSystemId)||""}get timeFormatOptions(){return Object.keys(this.timeFormats).map(t=>({id:t,format:this.timeFormats[t].format,ampm:this.timeFormats[t].ampm}))}get dateFormatOptions(){return Object.keys(this.dateFormats).map(t=>({id:t,format:this.dateFormats[t].format,order:this.dateFormats[t].order}))}get unitSystemOptions(){return Object.keys(this.unitSystems).map(t=>({id:t,name:t}))}setSelectedTimeFormat(t){if(!this.timeFormatOptions.find(e=>e.id===t))throw Error(`Invalid time format id. Must be one of ${this.timeFormatOptions.map(e=>e.id).join(", ")}`);this.regionSource.updateProperty("timeFormatId",t)}setSelectedDateFormat(t){if(!this.dateFormatOptions.find(e=>e.id===t))throw Error(`Invalid date format id. Must be one of ${this.dateFormatOptions.map(e=>e.id).join(", ")}`);this.regionSource.updateProperty("dateFormatId",t)}setSelectedUnitSystem(t){if(!this.unitSystemOptions.find(e=>e.id===t))throw Error(`Invalid date format id. Must be one of ${this.unitSystemOptions.map(e=>e.id).join(", ")}`);this.regionSource.updateProperty("unitSystemId",t)}getUnitSystem(t){if(!t)return this.defaultUnitSystem;const e=t==="drt"?"second":t,s=this.unitSystemMap[e];if(!s)throw Error(`No unit found with name: ${e}. Unit should be one of ${Object.keys(this.unitSystemMap).join(", ")}`);return s[ue.system]}getUnitMeasure(t){const e=t==="drt"?"second":t,s=this.unitSystemMap[e];if(!s)throw Error(`No unit found with name: ${e}. Unit should be one of ${Object.keys(this.unitSystemMap).join(", ")}`);return s[ue.family]}getDefaultUnitDecimalPlaces(t,e,s){if(!t||!e)throw Error("Measure and unit system are required");const r=s==="drt"?"second":s,o=this.measureMap[t];if(!o)throw Error(`No unit systems found for measure: ${t}. Measure should come from list of measures: ${Object.keys(this.measureMap).join(", ")}`);const n=o[e.toLowerCase()];if(!n)throw Error(`No unit system found for measure: ${t} and unit system: ${e}. Unit system should come form list of unit systems: ${Object.keys(o).join(", ")}`);const i=n[r||"default"];if(!i)throw Error(`No unit "${r||"default"}" found for measure: ${t} and unit system: ${e}. Unit should come from list of units: ${Object.keys(n).join(", ")}`);return i[ue.decimals]}getDefaultUnitForMeasure(t,e){if(!t||!e)throw Error("Measure and unit system are required");const s=this.defaultMeasureMap[t];if(!s)throw Error(`No unit systems found for measure: ${t}. Measure should come from list of measures: ${Object.keys(this.measureMap).join(", ")}`);const r=s[e.toLowerCase()];if(!r)throw Error(`No unit system found for measure: ${t} and unit system: ${e}. Unit system should come form list of unit systems: ${Object.keys(s).join(", ")}`);return r}convertByUnit(t,e,s){if(e[ue.family]!==s[ue.family])throw new Error(`Cannot convert between units of different families: ${e[ue.family]} and ${s[ue.family]}`);const r=e[ue.offset],o=e[ue.scale],n=s[ue.scale],i=s[ue.offset],a=s[ue.decimals];return((t-r)/(o/n)+i).toFixed(a)}convertByUnitName(t,e,s){const r=this.unitSystemMap[e],o=this.unitSystemMap[s];if(!r||!o)throw new Error(`No unit found with name: ${e} or ${s}. Unit should be one of ${Object.keys(this.unitSystemMap).join(", ")}`);return this.convertByUnit(t,r,o)}convert(t,e,s){var a,c;if(e.unit&&s.unit)return this.convertByUnitName(t,e.unit,s.unit);const r=e.unit||"",o=s.unit||"";let n=this.unitSystemMap[r],i=this.unitSystemMap[o];if(!i&&s.measure&&s.system){const u=this.measureMap[s.measure];if(!u)throw Error(`Could not find measure ${s.measure}. Measure should be one of ${Object.keys(this.measureMap).join(", ")}`);i=(a=u[s.system])==null?void 0:a.default,i||es.info("Could not find default unit for measure",s.measure)}if(!n&&e.measure&&e.system){const u=this.measureMap[e.measure];if(!u)throw Error(`Could not find measure ${s.measure}. Measure should be one of ${Object.keys(this.measureMap).join(", ")}`);n=(c=u[e.system])==null?void 0:c.default,n||es.info("Could not find default unit for measure",e.measure)}return!n||!i?(es.warn("Could not find unit to convert to or from. Return value as is"),String(t)):this.convertByUnit(t,n,i)}async init(){es.debug("initializing region info")}async load(){es.debug("loading region info");const t=await Vl();t&&(this.regions=t.data.map(s=>s.id),this.timeZoneMap=t.data.reduce((s,r)=>({...s,[r.id]:r.timeZones}),this.timeZoneMap),this.regionMap=t.data.reduce((s,r)=>({...s,[r.id]:r}),{}));const e=await zl();e&&(this.unitSystems=e.data.unitSystems.reduce((s,r)=>{const o={id:r.id,name:r.id};return s[r.id]=o,s},this.unitSystems),this.unitSystemMap=e.data.unitSystems.reduce(ny,{}),this.measureMap=e.data.unitSystems.reduce(iy,{}),this.defaultMeasureMap=e.data.unitSystems.reduce(ay,{}),this.timeFormats=e.data.timeFormats.reduce((s,r)=>({...s,[r.id]:r}),{}),this.dateFormats=e.data.dateFormats.reduce((s,r)=>({...s,[r.id]:r}),{}))}async ready(){var t,e;await((e=(t=this.regionSource).ready)==null?void 0:e.call(t))}};Fn([Jr({path:"kos:service:region:settings"})],Os.prototype,"regionSource",2);Fn([Jr({path:"kos:service:region"})],Os.prototype,"region",2);Os=Fn([R(dr)],Os);const re={registration:{[dr]:{class:Os,singleton:!0}},type:dr,factory:ae.Singleton.create(dr)},vr=({source:t,defaultSystem:e="si",defaultMeasure:s})=>{let r={system:e,measure:s};return typeof t=="string"?r={...r,unit:t}:r={...r,...t},r},Nn=(t,e,s)=>{const{model:r}=$e(re.type);if(!r)throw new Error("RegionInfo model not found");if(!yr(r))throw new Error("RegionInfo model not ready");const o={system:r.defaultUnitSystem},n=vr({source:e}),i=vr({source:s||o,defaultMeasure:r.getUnitMeasure(n.unit||"")});return r.convert(t,n,i)};function Gi(t,e,s){const r=e.toLowerCase().replace(/_/g,"-").replace(/s$/,""),o=new Intl.NumberFormat().resolvedOptions().locale??"en-US";try{const n=(s==null?void 0:s.mode)||"long",i=(s==null?void 0:s.maxDecimals)??2,a=(s==null?void 0:s.minDecimals)??0;return new Intl.NumberFormat(o,{style:"unit",unit:r,unitDisplay:n,minimumFractionDigits:a,maximumFractionDigits:i}).format(t)}catch{return e}}const uy=(t,e,s,r)=>{const o=Nn(t,e,s),n=vr({source:e}),{model:i}=$e(re.type);if(!i)throw new Error("RegionInfo model not found");const a=i.getUnitMeasure(n.unit||""),c={system:i.defaultUnitSystem},u=vr({source:s||c,defaultMeasure:i.getUnitMeasure(n.unit||"")}),d=i.getDefaultUnitForMeasure(a,u.system),h=i.getDefaultUnitDecimalPlaces(a,u.system),f={...r,minDecimals:(r==null?void 0:r.minDecimals)??h,maxDecimals:(r==null?void 0:r.maxDecimals)??h};return{value:o,unit:d||n.unit||"",display:Gi(o,d||n.unit||"",{...f,mode:"long"}),shortDisplay:Gi(o,d||n.unit||"",{...f,mode:"short"})}};function Yi({start:t,end:e,count:s,decimals:r=0}){if(typeof t!="number"||typeof e!="number"||typeof s!="number")throw new Error("All input values should be numbers.");if(s<2)throw new Error("Count should be at least 2 for distribution.");if(t>=e)throw new Error("Start should be less than end.");const o=(e-t)/(s-1),n=[];for(let i=0;i<s;i++){const a=Math.round(t+i*o);n.push(a.toFixed(r))}return n}function Wi({start:t,end:e,interval:s,decimals:r=0}){if(typeof t!="number"||typeof e!="number"||typeof s!="number")throw new Error("All input values should be numbers.");if(s<=0)throw new Error("Interval should be a positive number.");if(t>=e)throw new Error("Start should be less than end.");const o=[];let n=t;for(;n<=e;)o.push(n.toFixed(r)),n+=s;return o[o.length-1]!==e.toString()&&o.push(e.toString()),o}const wt=(t,e)=>s=>!t||!e?s:Xr(s)?Nn(Number(s),t,e):s,dy=(t,e,s,r)=>{if((t==null?void 0:t.type)==="enum"||!(t!=null&&t.options))return[];if(t.options.type==="rangeCount")return Yi(t.options).map(wt(s,r));if(t.options.type==="rangeInterval")return Wi(t.options).map(wt(s,r));if(t.options.type==="list"){const{list:o}=t.options;return o.map(wt(s,r))}else{if(t.options.type==="unitSystemRangeCount"&&e)return Yi(t.options.unitSystems[e]).map(wt(s,r));if(t.options.type==="unitSystemRangeInterval"&&e)return Wi(t.options.unitSystems[e]).map(wt(s,r));if(t.options.type==="unitSystemList"&&e){const{list:o}=t.options.unitSystems[e];return o.map(wt(s,r))}}return[]},hy=(t,e)=>{if(!((t==null?void 0:t.type)==="enum"||!(t!=null&&t.options)))return t.options.type==="unitSystemRangeCount"&&e?{type:"rangeCount",...t.options.unitSystems[e]}:t.options.type==="unitSystemRangeInterval"&&e?{type:"rangeInterval",...t.options.unitSystems[e]}:t.options.type==="unitSystemList"&&e?{type:"list",...t.options.unitSystems[e]}:t.options.type==="unitSystemKeypad"&&e?{type:"keypad",...t.options.unitSystems[e]}:t.options};var fy=Object.defineProperty,py=Object.getOwnPropertyDescriptor,Un=(t,e,s,r)=>{for(var o=r>1?void 0:r?py(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&fy(e,s,o),o};function gy(t){return(t==null?void 0:t.type)==="enum"}function my(t){switch(t){case"s":return"second";case"ms":return"millisecond";case"min":return"minute";case"h":return"hour";case"d":return"day";case"w":return"week";case"m":return"month";case"y":return"year";case"ml":return"milliliter";default:return t}}function yy(t,e){const s=new Date;s.setHours(0,0,0,0);const r=new Date(s.getTime()+t*1e3);return ze.format(r,e)}const hr="config-bean-prop-model",Et=m.createLogger({name:"config-bean-prop-model"}),by=ht("path"),vy=ht("serviceBasePath");let $s=class{constructor(t,e){l(this,"id");l(this,"path");l(this,"attribute");l(this,"converter");l(this,"formatter");l(this,"optionsExpander");l(this,"serviceBasePath");l(this,"regionInfo");l(this,"bean");this.id=t,this.path=e.path,this.attribute=e.attribute,this.converter=e.converter,this.formatter=e.formatter,this.serviceBasePath=e.serviceBasePath,this.optionsExpander=e.optionsExpander}getDefaultUnitDecimalPlaces(t,e,s){if(!t)throw new Error("measure is required");if(!e)throw new Error("unitSystem is required");return kl(this.displayOptions)?this.displayOptions.decimals:this.regionInfo.getDefaultUnitDecimalPlaces(t,e,s)}getDefaultUnitForMeasure(t,e){if(!t)throw new Error("measure is required");if(!e)throw new Error("unitSystem is required");return this.regionInfo.getDefaultUnitForMeasure(t,e)}get schemaType(){const t=this.bean.getSchemaForProperty(this.attribute);return t!=null&&t.type?t.type:"String"}get schemaFormat(){const t=this.bean.getSchemaForProperty(this.attribute);return t!=null&&t.format?my(t.format):""}get options(){var i;const t=this.regionInfo.defaultUnitSystem,e=this.getConverter(),s=((i=e==null?void 0:e.to)==null?void 0:i.system)??t,r=this.bean.getSchemaForProperty(this.attribute),o=gy(r)?r.values:dy(r,s,e==null?void 0:e.from,e==null?void 0:e.to),n=o.length>0?o.map(a=>({label:a,value:a})):[];return this.optionsExpander?typeof this.optionsExpander=="function"?this.optionsExpander(s,o):this.optionsExpander:n}convertUnit(t,e,s){const r=(t==null?void 0:t.measure)||s,o=(t==null?void 0:t.system)||e,n=t==null?void 0:t.unit;return{measure:r,system:o,unit:n}}getConverterUnits(){const t=this.regionInfo.defaultUnitSystem,e=this.getConverter();if(!e)throw Error("No converter defined");const s=e.measure,r=this.convertUnit(e.from,"si",s),o=this.convertUnit(e.to,t,s);return{backend:r,display:o}}set value(t){this.updateProperty(t)}get value(){return this.getValue(!0)}get rawValue(){return this.bean.props[this.attribute]}get significantValue(){var o,n;const t=this.value,e=this.regionInfo.defaultUnitSystem,s=this.getConverter(),r=(s==null?void 0:s.measure)||((o=s==null?void 0:s.to)==null?void 0:o.measure);if(!isNaN(t)&&s&&r){const i=this.getDefaultUnitDecimalPlaces(r,e,(n=s==null?void 0:s.to)==null?void 0:n.unit);try{const c=this.getFormatterOptions(s);if(c){let u=String(t);return u=c.formatToParts(Number(t))[0].value,Number(u)}}catch(c){Et.info(`error formatting value ${t}`,c)}return Number(t).toFixed(i)}return t}get previousValue(){return this.getValue(!1)}getValue(t){const e=this.bean[t?"props":"prevProps"][this.attribute];if(typeof e=="boolean")return e;if(this.getConverter()&&!isNaN(e)){const{backend:r,display:o}=this.getConverterUnits();return this.regionInfo.convert(Number(e),r,o)}return e||""}async activate(){Et.debug(`activating config bean ${this.id}`)}get displayValue(){const t=this.value;if(typeof t=="boolean")return String(t);if(this.schemaFormat==="drt"){const s=this.regionInfo.is12HourTimeFormat?"h:mm:ss a":"HH:mm:ss";return yy(t,s)}if(!isNaN(t))try{const e=this.getConverter(),s=this.getFormatterOptions(e);if(s){let r=String(t);return r=s.format(Number(t)),r}}catch(e){Et.error(`error formatting value ${t}`,e)}return String(t)}get unit(){const t=this.getConverter();if(!isNaN(this.value)){const e=this.getFormatterOptions(t);if(e){const r=e.formatToParts(Number(this.value)).find(o=>o.type==="unit");return(r==null?void 0:r.value)??this.getDefaultUnit(t)}}return this.getDefaultUnit(t)}get displayOptions(){var o;const t=this.bean.getSchemaForProperty(this.attribute),e=this.regionInfo.defaultUnitSystem,s=this.getConverter(),r=((o=s==null?void 0:s.to)==null?void 0:o.system)??e;return hy(t,r)}getMeasureFromFormat(){const t=this.schemaFormat;return t?this.regionInfo.getUnitMeasure(t):""}getConverterFromFormat(){const t=this.getMeasureFromFormat();if(t){const e=this.regionInfo.selectedUnitSystem;return{unit:this.schemaFormat||this.regionInfo.getDefaultUnitForMeasure(t,e),measure:t}}return{}}getDefaultUnit(t){var r,o;const e=this.regionInfo.defaultUnitSystem,s=t==null?void 0:t.measure;return s?((r=t==null?void 0:t.to)==null?void 0:r.unit)||this.getDefaultUnitForMeasure(s,((o=t==null?void 0:t.to)==null?void 0:o.system)||e):this.getConverterFromFormat().unit}getFormatterOptions(t){var n,i,a;const e=this.regionInfo.defaultUnitSystem,s=t==null?void 0:t.measure,r=new Intl.NumberFormat().resolvedOptions().locale;let o=null;if(s||this.formatter){const c=s?{style:"unit",unit:this.getDefaultUnit(t)}:null,u=this.formatter||c;if(u){let d=typeof u=="function"?u(((n=t==null?void 0:t.to)==null?void 0:n.system)||e):u;s&&(d={unit:this.getDefaultUnit(t),...d},d.style==="unit"&&(d.maximumFractionDigits=d.maximumFractionDigits??this.getDefaultUnitDecimalPlaces(s,((i=t==null?void 0:t.to)==null?void 0:i.system)||e,(a=t==null?void 0:t.to)==null?void 0:a.unit)));try{o=new Intl.NumberFormat(r,{...d})}catch(h){Et.error(`error creating formatter ${d}. Returning the raw value`,h)}}else Et.debug(`no formatter found for config bean prop ${this.id}. Returning the raw value`)}return o}getConverter(){var r,o,n,i,a,c,u,d,h,f,p;const{unit:t,measure:e}=this.getConverterFromFormat(),s=t==="drt"?"second":t;if(this.converter){const y=(r=this.converter)==null?void 0:r.measure,w=(n=(o=this.converter)==null?void 0:o.to)==null?void 0:n.measure,E=(a=(i=this.converter)==null?void 0:i.from)==null?void 0:a.measure,_=y||w||E||e,k=((u=(c=this.converter)==null?void 0:c.to)==null?void 0:u.unit)||this.regionInfo.getDefaultUnitForMeasure(_,((h=(d=this.converter)==null?void 0:d.to)==null?void 0:h.system)??this.regionInfo.defaultUnitSystem),U=((p=(f=this.converter)==null?void 0:f.to)==null?void 0:p.system)??this.regionInfo.getUnitSystem(k),O=this.schemaFormat==="drt"?"second":this.schemaFormat||s;return{...this.converter,from:{unit:O,...this.converter.from},to:{...this.converter.to,unit:k,system:U},measure:_}}if(s&&e){const y=this.regionInfo.getDefaultUnitForMeasure(e,this.regionInfo.defaultUnitSystem),w=this.regionInfo.getUnitSystem(s),E=this.regionInfo.getUnitSystem(y);return{measure:e,to:{unit:w===E?s:y}}}}async updateProperty(t){Et.debug(`updating property ${this.attribute} with value ${t}`);let e=t;if(this.getConverter()&&!isNaN(e)){const{backend:o,display:n}=this.getConverterUnits();e=this.regionInfo.convert(Number(e),n,o)}const r=Array.isArray(e)?JSON.stringify(e):String(e);await this.bean.updateProperty(this.attribute,r)}};Un([qt({modelType:re.type})],$s.prototype,"regionInfo",2);Un([Jr({path:by,serviceBasePath:vy})],$s.prototype,"bean",2);$s=Un([R(hr)],$s);const pt={registration:{[hr]:{class:$s,singleton:!1}},type:hr,factory:ae.Factory.create(hr)};function wy(t){const{path:e,attribute:s,converter:r,formatter:o,lazy:n,optionsExpander:i,serviceBasePath:a}=t,c=r;return c&&(typeof c!="function"&&typeof c.from=="string"&&(c.from={unit:c.from}),typeof c!="function"&&typeof c.to=="string"&&(c.to={unit:c.to})),(u,d)=>{u[F]=u[F]||{},u[F][d]={modelType:pt.type,id:`${e}-${s}`,options:{path:e,attribute:s,serviceBasePath:a,converter:c,formatter:o,optionsExpander:i},lifecycle:x.INIT,lazy:n}}}const Yl="future-model",Gt=zt(Yl),eo=m.createLogger({name:"future-service",group:"Services"}),{isMock:Ey,URL:qs}=ce();var We=(t=>(t.Success="SUCCESS",t.Fail="FAIL",t.Aborted="ABORT",t.Canceled="CANCEL",t))(We||{});const{getAll:My,modifyModel:Ty,addModel:_y,deleteModel:Sy,postModel:Iy}=oe.build({destinationAddress:"",basePath:`${qs}/api/future`,mock:Ey}),Oy=async()=>await My({}),Wl=async(t,e="/api/kos/future")=>(eo.info(`sending delete request for Future: ${t}`),await Sy({id:t,urlOverride:`${qs}${e}/${t}`})),Ql=async(t,e="/api/kos/future")=>(eo.info("sending add request for Future"),await _y({model:t,urlOverride:`${qs}${e}`})),$y=async(t,e,s="/api/kos/future")=>(eo.info(`sending modify request for Future: ${t}`),Ty({model:e,id:t,urlOverride:`${qs}${s}/${t}`})),Zl=async(t,e="/api/kos/future")=>(eo.info(`sending cancel request for Future: ${t}`),Iy({urlOverride:`${qs}${e}/${t}/cancel`,ordered:!0,model:{}})),jn=t=>({id:String(t.id),progress:t.progress,remainingTimeMs:t.remainingTimeMs,endState:t.endState,reason:t.reason,clientData:t.clientData,reasonData:t.reasonData,note:t.note,tracker:t.tracker}),Bn=(t,e)=>{m.debug(`future dto ${t.id} end state ${t.endState}`),m.debug(`future model ${e.id} end state ${e.endState}`),e.endState?m.debug(`future model ${e.id} is already complete`):(m.debug(`updating future model ${e.id}`),M.runInAction(()=>{const s=jn(t);J(()=>{Object.keys(s).forEach(r=>{r==="id"?(e.futureId=s.id,s.tracker||(e.id=s.id)):r==="tracker"?e.id=s.tracker:e[r]=s[r]})})}))},Xl=t=>e=>s=>t.build(String(e),s),Hn=t=>e=>Il(jn,Xl(t)(e.tracker||e.id))(e);var Cy=Object.defineProperty,Dy=Object.getOwnPropertyDescriptor,Jl=(t,e,s,r)=>{for(var o=r>1?void 0:r?Dy(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Cy(e,s,o),o};const So=m.getLogger(Gt.type);let wr=class{constructor(t,e,s){l(this,"logger");l(this,"_cancelFuture");l(this,"futureId");Object.assign(this,e),this.logger=s.logger,this.id=t,this.futureId=e.id,this.namespace=e.namespace||"kos",this._cancelFuture=Zl,jo(()=>this.status===We.Success||this.status===We.Fail,()=>{So.info(`Future ${this.id} has completed with status ${this.status}`),Ie(this)})}async load(){So.debug(`loading Future ${this.id}`)}unload(){So.info(`unloading Future ${this.id}`)}async cancelFuture(){const t=this.namespace==="studio"?"/api/future":`/api/${this.namespace}/future`;await jo(()=>this.futureId!==Rn),await this._cancelFuture(this.futureId,t)}get status(){return this.endState?this.endState:this.progress>-1?"IN_PROGRESS":"NOT_ACTIVE"}get timeRemaining(){var a,c;const t=this.remainingTimeMs||-1;if(t<0)return"";const e={year:1e3*60*60*24*365,month:1e3*60*60*24*30,day:1e3*60*60*24,hour:1e3*60*60,minute:1e3*60,second:1e3};let s="second",r=0;for(const[u,d]of Object.entries(e))if(Math.abs(t)>=d){s=u,r=Math.round(t/d);break}const n=new Intl.RelativeTimeFormat("en",{numeric:"auto"}).formatToParts(r,s);return n.length===3?`${((a=n[1])==null?void 0:a.value)??0} ${((c=n[2])==null?void 0:c.value)??""}`:"0 seconds"}handleFutureUpdated(t){this.logger.debug(`Future ${this.id} updated. future: ${t.id} endState: ${t.endState} progress: ${t.progress} remainingTimeMs: ${t.remainingTimeMs}`),Bn(t,this)}};Jl([H({topic:`kos.future/${pr}`})],wr.prototype,"handleFutureUpdated",1);wr=Jl([R(Gt.type)],wr);const eu=wr,tu=Be();var xy=Object.defineProperty,Ay=Object.getOwnPropertyDescriptor,su=(t,e,s,r)=>{for(var o=r>1?void 0:r?Ay(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&xy(e,s,o),o};const ru="browser-router-model",Ry="kos.http.request",Py="kos.http.response";let Er=class{constructor(t,e,s){l(this,"_id");l(this,"logger");l(this,"router");this._id=t,this.logger=s.logger,this.router=new Dl}get id(){return this._id}async handleRequest(t,e){const s=e.headers["src-addr"],r=e.headers["dst-addr"],o=e.headers.url,n=e.headers.method,i=e.headers["request-id"],a={id:i,method:n,path:o,body:t};let c=200;const u={send:d=>{this.logger.debug(`sending response to ${r}`),this.logger.debug(d),vl({msg:d,options:{responseId:i,destinationAddress:s,type:Py,sourceAddress:r,status:c}})},status:function(d){return c=d,this}};if(a.path==="/openapi.json"){u.send(this.router.generateOpenApiSpec());return}await this.router.handle(a,u)}use(t,e,...s){this.router.use(t,e,...s)}remove(t,e){return this.router.remove(t,e)}removeAllForPath(t){return this.router.removeAllForPath(t)}getRoutes(){return this.router.getRoutes()}async init(){this.logger.debug(`initializing browser-router ${this.id}`)}async load(){this.logger.debug(`loading browser-router ${this.id}`)}};su([H({topic:Ry})],Er.prototype,"handleRequest",1);Er=su([R(ru)],Er);const Kn=new Se({class:Er,type:ru}),ou="future-container-model",Qe=zt(ou),nu=t=>Hn(Gt)(t),ky=t=>{const e=nu(t);return Qe.build(Qe.type,{}).addFutureModel(e),e},Ly=t=>Qe.build(Qe.type,{}).getFuture(String(t)),lt={buildFutureModel:nu,initiateFuture:ky,getFuture:Ly};var Fy=Object.defineProperty,Ny=Object.getOwnPropertyDescriptor,qn=(t,e,s,r)=>{for(var o=r>1?void 0:r?Ny(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Fy(e,s,o),o};const sr=m.getLogger(Qe.type);let Cs=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_deleteFuture");l(this,"_addFuture");l(this,"_futures");l(this,"createModel");l(this,"deleteModel");const{deleteFuture:r=Wl,addFuture:o=Ql}=e;this.logger=s.logger,this._deleteFuture=r,this._addFuture=o,this.id=t,this._futures=new xe,this.createModel=this.createFuture,this.deleteModel=this.removeFuture}get futures(){return this._futures.data}get models(){return this.futures}getFuture(t){return this._futures.getModel(t)}addFutureModel(t){this._futures.addModel(t)}removeFutureModel(t){this._futures.removeModel(t)}async removeFuture(t){try{await this._deleteFuture(t)}catch(e){sr.error("error deleting a Future"),sr.error(e)}}async createFuture(t){try{const e=await this._addFuture(t),s=e==null?void 0:e.data;if(s){const r=Hn(Gt)(s);return this.addFutureModel(r),r}}catch(e){throw sr.error("error creating a Future"),sr.error(e),e}}handleFutureUpdated(t,e){const s=lt.buildFutureModel(t);this.addFutureModel(s);const r=`kos.future/${t.tracker||t.id}`;this.logger.debug(`publishing future update to ${r}`),V(r,e.body,e.headers)}};qn([De],Cs.prototype,"_futures",2);qn([H({topic:"kos.future"})],Cs.prototype,"handleFutureUpdated",1);Cs=qn([R(Qe.type)],Cs);const iu=Cs,{URL:zs}=ce(),{getOne:Uy,postModel:jy,deleteModel:au}=oe.build({basePath:`${zs}/api/keyVal`}),Bo=m.createLogger({name:"key-value-service",group:"Services"}),cu=async(t,e)=>{await au({urlOverride:`${zs}/api/keyVal/${t}/${e}`,id:e})},lu=async(t,e,s)=>{const r=await jy({urlOverride:`${zs}/api/keyVal/${t}/${e}`,model:s.toString()});if((r==null?void 0:r.status)!==200)throw Bo.error("Failed to update key-value data",r),new Error(`Failed to update key-value data for namespace ${t}`);return r.data},uu=async(t="studio")=>{Bo.debug(`Retrieving all key-value data for namespace: ${t}`);const e=await Uy({urlOverride:`${zs}/api/keyVal/${t}`});if((e==null?void 0:e.status)!==200)throw Bo.error("Failed to retrieve key-value data",e),new Error(`Failed to retrieve key-value data for namespace ${t}`);return e.data},By=async t=>{await au({urlOverride:`${zs}/api/keyVal/${t}`,id:""})},Hy=Object.freeze(Object.defineProperty({__proto__:null,deleteKeyValue:cu,deleteKeyValueNamespace:By,getKeyValue:uu,updateKeyValue:lu},Symbol.toStringTag,{value:"Module"}));var Ky=Object.defineProperty,qy=Object.getOwnPropertyDescriptor,zn=(t,e,s,r)=>{for(var o=r>1?void 0:r?qy(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Ky(e,s,o),o};const du="key-value-model";let Ds=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"namespace");l(this,"data");this.id=t,this.logger=s.logger,this.data=Oe(),this.namespace=e.namespace||"studio"}async init(){this.logger.debug(`initializing studio-state ${this.id}`)}async updateState(t,e){this.logger.debug(`updating studio-state ${t} with value ${e}`),e!==void 0?(await lu(this.namespace,t,e),this.data[t]=e):(await cu(this.namespace,t),this.data[t]=void 0)}async load(){this.logger.debug(`loading studio-state ${this.id}`);const t=await uu(this.namespace);this.data.setValues(t)}handleStateUpdate(t){t.namespace===this.namespace&&(this.data[t.key]=t.value)}handleStateDelete(t){t.namespace===this.namespace&&(this.data[t.key]=void 0)}};zn([H({topic:"/keyVal/set"})],Ds.prototype,"handleStateUpdate",1);zn([H({topic:"/keyVal/remove"})],Ds.prototype,"handleStateDelete",1);Ds=zn([R(du)],Ds);const Vn=new be({class:Ds,type:du});var pe="INUMBER",Yt="IOP1",Wt="IOP2",Qt="IOP3",Le="IVAR",ut="IVARNAME",At="IFUNCALL",to="IFUNDEF",ie="IEXPR",Gn="IEXPREVAL",gt="IMEMBER",so="IENDSTATEMENT",Rt="IARRAY";function P(t,e){this.type=t,this.value=e??0}P.prototype.toString=function(){switch(this.type){case pe:case Yt:case Wt:case Qt:case Le:case ut:case so:return this.value;case At:return"CALL "+this.value;case to:return"DEF "+this.value;case Rt:return"ARRAY "+this.value;case gt:return"."+this.value;default:return"Invalid Instruction"}};function ro(t){return new P(Yt,t)}function He(t){return new P(Wt,t)}function hu(t){return new P(Qt,t)}function Ho(t,e,s,r,o){for(var n=[],i=[],a,c,u,d,h=0;h<t.length;h++){var f=t[h],p=f.type;if(p===pe||p===ut)Array.isArray(f.value)?n.push.apply(n,Ho(f.value.map(function(y){return new P(pe,y)}).concat(new P(Rt,f.value.length)),e,s,r,o)):n.push(f);else if(p===Le&&o.hasOwnProperty(f.value))f=new P(pe,o[f.value]),n.push(f);else if(p===Wt&&n.length>1)c=n.pop(),a=n.pop(),d=s[f.value],f=new P(pe,d(a.value,c.value)),n.push(f);else if(p===Qt&&n.length>2)u=n.pop(),c=n.pop(),a=n.pop(),f.value==="?"?n.push(a.value?c.value:u.value):(d=r[f.value],f=new P(pe,d(a.value,c.value,u.value)),n.push(f));else if(p===Yt&&n.length>0)a=n.pop(),d=e[f.value],f=new P(pe,d(a.value)),n.push(f);else if(p===ie){for(;n.length>0;)i.push(n.shift());i.push(new P(ie,Ho(f.value,e,s,r,o)))}else if(p===gt&&n.length>0)a=n.pop(),n.push(new P(pe,a.value[f.value]));else{for(;n.length>0;)i.push(n.shift());i.push(f)}}for(;n.length>0;)i.push(n.shift());return i}function fu(t,e,s){for(var r=[],o=0;o<t.length;o++){var n=t[o],i=n.type;if(i===Le&&n.value===e)for(var a=0;a<s.tokens.length;a++){var c=s.tokens[a],u;c.type===Yt?u=ro(c.value):c.type===Wt?u=He(c.value):c.type===Qt?u=hu(c.value):u=new P(c.type,c.value),r.push(u)}else i===ie?r.push(new P(ie,fu(n.value,e,s))):r.push(n)}return r}function ot(t,e,s){var r=[],o,n,i,a,c,u;if(Yn(t))return Re(t,s);for(var d=t.length,h=0;h<d;h++){var f=t[h],p=f.type;if(p===pe||p===ut)r.push(f.value);else if(p===Wt)n=r.pop(),o=r.pop(),f.value==="and"?r.push(o?!!ot(n,e,s):!1):f.value==="or"?r.push(o?!0:!!ot(n,e,s)):f.value==="="?(a=e.binaryOps[f.value],r.push(a(o,ot(n,e,s),s))):(a=e.binaryOps[f.value],r.push(a(Re(o,s),Re(n,s))));else if(p===Qt)i=r.pop(),n=r.pop(),o=r.pop(),f.value==="?"?r.push(ot(o?n:i,e,s)):(a=e.ternaryOps[f.value],r.push(a(Re(o,s),Re(n,s),Re(i,s))));else if(p===Le)if(f.value in e.functions)r.push(e.functions[f.value]);else if(f.value in e.unaryOps&&e.parser.isOperatorEnabled(f.value))r.push(e.unaryOps[f.value]);else{var y=s[f.value];if(y!==void 0)r.push(y);else throw new Error("undefined variable: "+f.value)}else if(p===Yt)o=r.pop(),a=e.unaryOps[f.value],r.push(a(Re(o,s)));else if(p===At){for(u=f.value,c=[];u-- >0;)c.unshift(Re(r.pop(),s));if(a=r.pop(),a.apply&&a.call)r.push(a.apply(void 0,c));else throw new Error(a+" is not a function")}else if(p===to)r.push(function(){for(var w=r.pop(),E=[],_=f.value;_-- >0;)E.unshift(r.pop());var k=r.pop(),U=function(){for(var O=Object.assign({},s),S=0,z=E.length;S<z;S++)O[E[S]]=arguments[S];return ot(w,e,O)};return Object.defineProperty(U,"name",{value:k,writable:!1}),s[k]=U,U}());else if(p===ie)r.push(zy(f,e));else if(p===Gn)r.push(f);else if(p===gt)o=r.pop(),r.push(o[f.value]);else if(p===so)r.pop();else if(p===Rt){for(u=f.value,c=[];u-- >0;)c.unshift(r.pop());r.push(c)}else throw new Error("invalid Expression")}if(r.length>1)throw new Error("invalid Expression (parity)");return r[0]===0?0:Re(r[0],s)}function zy(t,e,s){return Yn(t)?t:{type:Gn,value:function(r){return ot(t.value,e,r)}}}function Yn(t){return t&&t.type===Gn}function Re(t,e){return Yn(t)?t.value(e):t}function Wn(t,e){for(var s=[],r,o,n,i,a,c,u=0;u<t.length;u++){var d=t[u],h=d.type;if(h===pe)typeof d.value=="number"&&d.value<0?s.push("("+d.value+")"):Array.isArray(d.value)?s.push("["+d.value.map(Qi).join(", ")+"]"):s.push(Qi(d.value));else if(h===Wt)o=s.pop(),r=s.pop(),i=d.value,e?i==="^"?s.push("Math.pow("+r+", "+o+")"):i==="and"?s.push("(!!"+r+" && !!"+o+")"):i==="or"?s.push("(!!"+r+" || !!"+o+")"):i==="||"?s.push("(function(a,b){ return Array.isArray(a) && Array.isArray(b) ? a.concat(b) : String(a) + String(b); }(("+r+"),("+o+")))"):i==="=="?s.push("("+r+" === "+o+")"):i==="!="?s.push("("+r+" !== "+o+")"):i==="["?s.push(r+"[("+o+") | 0]"):s.push("("+r+" "+i+" "+o+")"):i==="["?s.push(r+"["+o+"]"):s.push("("+r+" "+i+" "+o+")");else if(h===Qt)if(n=s.pop(),o=s.pop(),r=s.pop(),i=d.value,i==="?")s.push("("+r+" ? "+o+" : "+n+")");else throw new Error("invalid Expression");else if(h===Le||h===ut)s.push(d.value);else if(h===Yt)r=s.pop(),i=d.value,i==="-"||i==="+"?s.push("("+i+r+")"):e?i==="not"?s.push("(!"+r+")"):i==="!"?s.push("fac("+r+")"):s.push(i+"("+r+")"):i==="!"?s.push("("+r+"!)"):s.push("("+i+" "+r+")");else if(h===At){for(c=d.value,a=[];c-- >0;)a.unshift(s.pop());i=s.pop(),s.push(i+"("+a.join(", ")+")")}else if(h===to){for(o=s.pop(),c=d.value,a=[];c-- >0;)a.unshift(s.pop());r=s.pop(),e?s.push("("+r+" = function("+a.join(", ")+") { return "+o+" })"):s.push("("+r+"("+a.join(", ")+") = "+o+")")}else if(h===gt)r=s.pop(),s.push(r+"."+d.value);else if(h===Rt){for(c=d.value,a=[];c-- >0;)a.unshift(s.pop());s.push("["+a.join(", ")+"]")}else if(h===ie)s.push("("+Wn(d.value,e)+")");else if(h!==so)throw new Error("invalid Expression")}return s.length>1&&(e?s=[s.join(",")]:s=[s.join(";")]),String(s[0])}function Qi(t){return typeof t=="string"?JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029"):t}function It(t,e){for(var s=0;s<t.length;s++)if(t[s]===e)return!0;return!1}function Qn(t,e,s){s=s||{};for(var r=!!s.withMembers,o=null,n=0;n<t.length;n++){var i=t[n];i.type===Le||i.type===ut?!r&&!It(e,i.value)?e.push(i.value):(o!==null&&(It(e,o)||e.push(o)),o=i.value):i.type===gt&&r&&o!==null?o+="."+i.value:i.type===ie?Qn(i.value,e,s):o!==null&&(It(e,o)||e.push(o),o=null)}o!==null&&!It(e,o)&&e.push(o)}function Ee(t,e){this.tokens=t,this.parser=e,this.unaryOps=e.unaryOps,this.binaryOps=e.binaryOps,this.ternaryOps=e.ternaryOps,this.functions=e.functions}Ee.prototype.simplify=function(t){return t=t||{},new Ee(Ho(this.tokens,this.unaryOps,this.binaryOps,this.ternaryOps,t),this.parser)};Ee.prototype.substitute=function(t,e){return e instanceof Ee||(e=this.parser.parse(String(e))),new Ee(fu(this.tokens,t,e),this.parser)};Ee.prototype.evaluate=function(t){return t=t||{},ot(this.tokens,this,t)};Ee.prototype.toString=function(){return Wn(this.tokens,!1)};Ee.prototype.symbols=function(t){t=t||{};var e=[];return Qn(this.tokens,e,t),e};Ee.prototype.variables=function(t){t=t||{};var e=[];Qn(this.tokens,e,t);var s=this.functions;return e.filter(function(r){return!(r in s)})};Ee.prototype.toJSFunction=function(t,e){var s=this,r=new Function(t,"with(this.functions) with (this.ternaryOps) with (this.binaryOps) with (this.unaryOps) { return "+Wn(this.simplify(e).tokens,!0)+"; }");return function(){return r.apply(s,arguments)}};var xs="TEOF",B="TOP",oo="TNUMBER",pu="TSTRING",Fe="TPAREN",Pt="TBRACKET",no="TCOMMA",Zn="TNAME",Xn="TSEMICOLON";function gu(t,e,s){this.type=t,this.value=e,this.index=s}gu.prototype.toString=function(){return this.type+": "+this.value};function G(t,e){this.pos=0,this.current=null,this.unaryOps=t.unaryOps,this.binaryOps=t.binaryOps,this.ternaryOps=t.ternaryOps,this.consts=t.consts,this.expression=e,this.savedPosition=0,this.savedCurrent=null,this.options=t.options,this.parser=t}G.prototype.newToken=function(t,e,s){return new gu(t,e,s??this.pos)};G.prototype.save=function(){this.savedPosition=this.pos,this.savedCurrent=this.current};G.prototype.restore=function(){this.pos=this.savedPosition,this.current=this.savedCurrent};G.prototype.next=function(){if(this.pos>=this.expression.length)return this.newToken(xs,"EOF");if(this.isWhitespace()||this.isComment())return this.next();if(this.isRadixInteger()||this.isNumber()||this.isOperator()||this.isString()||this.isParen()||this.isBracket()||this.isComma()||this.isSemicolon()||this.isNamedOp()||this.isConst()||this.isName())return this.current;this.parseError('Unknown character "'+this.expression.charAt(this.pos)+'"')};G.prototype.isString=function(){var t=!1,e=this.pos,s=this.expression.charAt(e);if(s==="'"||s==='"')for(var r=this.expression.indexOf(s,e+1);r>=0&&this.pos<this.expression.length;){if(this.pos=r+1,this.expression.charAt(r-1)!=="\\"){var o=this.expression.substring(e+1,r);this.current=this.newToken(pu,this.unescape(o),e),t=!0;break}r=this.expression.indexOf(s,r+1)}return t};G.prototype.isParen=function(){var t=this.expression.charAt(this.pos);return t==="("||t===")"?(this.current=this.newToken(Fe,t),this.pos++,!0):!1};G.prototype.isBracket=function(){var t=this.expression.charAt(this.pos);return(t==="["||t==="]")&&this.isOperatorEnabled("[")?(this.current=this.newToken(Pt,t),this.pos++,!0):!1};G.prototype.isComma=function(){var t=this.expression.charAt(this.pos);return t===","?(this.current=this.newToken(no,","),this.pos++,!0):!1};G.prototype.isSemicolon=function(){var t=this.expression.charAt(this.pos);return t===";"?(this.current=this.newToken(Xn,";"),this.pos++,!0):!1};G.prototype.isConst=function(){for(var t=this.pos,e=t;e<this.expression.length;e++){var s=this.expression.charAt(e);if(s.toUpperCase()===s.toLowerCase()&&(e===this.pos||s!=="_"&&s!=="."&&(s<"0"||s>"9")))break}if(e>t){var r=this.expression.substring(t,e);if(r in this.consts)return this.current=this.newToken(oo,this.consts[r]),this.pos+=r.length,!0}return!1};G.prototype.isNamedOp=function(){for(var t=this.pos,e=t;e<this.expression.length;e++){var s=this.expression.charAt(e);if(s.toUpperCase()===s.toLowerCase()&&(e===this.pos||s!=="_"&&(s<"0"||s>"9")))break}if(e>t){var r=this.expression.substring(t,e);if(this.isOperatorEnabled(r)&&(r in this.binaryOps||r in this.unaryOps||r in this.ternaryOps))return this.current=this.newToken(B,r),this.pos+=r.length,!0}return!1};G.prototype.isName=function(){for(var t=this.pos,e=t,s=!1;e<this.expression.length;e++){var r=this.expression.charAt(e);if(r.toUpperCase()===r.toLowerCase()){if(e===this.pos&&(r==="$"||r==="_")){r==="_"&&(s=!0);continue}else if(e===this.pos||!s||r!=="_"&&(r<"0"||r>"9"))break}else s=!0}if(s){var o=this.expression.substring(t,e);return this.current=this.newToken(Zn,o),this.pos+=o.length,!0}return!1};G.prototype.isWhitespace=function(){for(var t=!1,e=this.expression.charAt(this.pos);(e===" "||e===" "||e===`
107
+ ["${e}"]`;if(r?(p=this.fosSocket)==null?void 0:p.connectionEstablished:(y=this.socket)==null?void 0:y.connectionEstablished){const E=r?this.fosSocket:this.socket;(w=E==null?void 0:E.socket)==null||w.send(d)}else{et.debug("no connection adding to offline messages");const E=r?this.fosSocket:this.socket;E==null||E.addOfflineMessage(d)}}subscribeTopic({topic:e,callback:s,fos:r,bridge:o,destinationAddress:n}){const{unsubscribe:i,count:a}=C(e,s);return et.debug(`Topic ${e} currently has ${a} subscribers`),this._sendSubscriptionMessage(e,"subscribe",r,o,n),()=>{const{count:c}=i();et.debug(`Topic ${e} currently has ${c} subscribers`),c===0&&this._sendSubscriptionMessage(e,"unsubscribe",r,o,n)}}async whenReady(){const e=this;return this.webSocketSupported?(await M.when(()=>{var s,r;return!!((s=e.socket)!=null&&s.connectionEstablished)&&(!e.useFosTransport||!!((r=e.fosSocket)!=null&&r.connectionEstablished))&&e.authorized}),{status:"success"}):{status:"not supported"}}get token(){return this._token}set token(e){this._token=e,this.init()}static host(e="localhost"){return this.getInstance().host=e,this}static port(e=8080){return this.getInstance().port=e,this}static alias(e){this.getInstance().alias=e}static getInstance(e=8080,s){if(!this._instance){const r=window.kosUseFos?{port:window.kosFosPort||8081}:void 0;this._instance=new this({port:e,token:s,fos:r})}return this._instance}}l(xt,"_instance");class Bg{constructor(e,s,r,o,n){l(this,"disposers",[]);l(this,"activatableDisposers",[]);l(this,"flowControllers",new Map);l(this,"baselineDependencies",new Map);this.model=e,this.modelData=s,this.modelId=r,this.offlineQueue=o,this.log=n}registerAll(e){var o;const s=((o=this.modelData)==null?void 0:o[ee])||{},r=Object.keys(s);this.log.debug(`Found ${r.length} subscriptions in ${this.modelId} (lifecycle: ${e??"any"})`),r.forEach(n=>{const i=s[n],a=i.lifecycle;if(e&&e!==a)return;const c=this.resolvePropKey(n);if(this.log.debug(`Resolved topic: ${n} → ${c}`),i.requiresBaseline&&(this.baselineDependencies.set(c,i.requiresBaseline),this.log.debug(`Registered baseline dependency for ${c}: ${i.requiresBaseline.path}`)),i.flow)this.subscribeWithFlowControl(i,c,a);else{const u=this.createHandler(c,i);this.subscribe(i,c,u,a===x.ACTIVATE)}})}deactivate(){this.log.debug(`Deactivating subscriptions for ${this.modelId}`);for(const e of this.activatableDisposers)try{e()}catch(s){this.log.error("Error during subscription disposal",s)}this.activatableDisposers=[]}disposeAll(){const e=[...this.disposers,...this.activatableDisposers];this.log.debug(`Disposing ${e.length} subscriptions for ${this.modelId}`);for(const[s,r]of this.flowControllers)this.log.debug(`Disposing flow controller for ${s}`);this.flowControllers.clear();for(const s of e)try{s()}catch(r){this.log.error("Error during subscription disposal",r)}this.disposers=[],this.activatableDisposers=[]}subscribe(e,s,r,o){const n=e.destinationAddress?this.resolvePropKey(e.destinationAddress):null;if(e.websocket){this.log.debug(`Subscribing to WebSocket topic: ${s}`);const i=xt.getInstance().subscribeTopic({topic:s,callback:r,fos:e.fos,bridge:e.bridge,destinationAddress:n});this.disposers.push(i)}else{this.log.debug(`Subscribing to EventBus topic: ${s}`);const{unsubscribe:i}=C(s,r);o?this.activatableDisposers.push(i):this.disposers.push(i)}}createHandler(e,s){return async r=>{var o;try{const n=(o=r==null?void 0:r.headers)==null?void 0:o["src-addr"],i=s.destinationAddress&&this.resolvePropKey(s.destinationAddress),a=i?n===i:!0,c=this.extractWildcardCapture(e,r,s),u=this.isBaselineReady(e);if(!this.model.isReady()||!u){u?this.log.warn(`Model ${this.modelId} not ready. Queuing message for ${e}`):this.log.warn(`Baseline not ready for ${e}. Queuing message.`);const d=()=>{const h=Fo(r,s.skipParse),f=s.transform(h);if(a&&s.condition(f,this.modelData,r))return this.callHandlerWithWildcard(s,f,c,r)};this.offlineQueue.enqueue(d,e,r)}else{const d=Fo(r,s.skipParse),h=s.transform(d);if(a&&s.condition(h,this.modelData,r))return this.callHandlerWithWildcard(s,h,c,r)}}catch(n){this.log.error(`Error handling subscription for ${e}`,n)}}}extractWildcardCapture(e,s,r){var n;if(!r.wildcardName||!Vc(e))return null;const o=((n=s==null?void 0:s.headers)==null?void 0:n.topic)||"";return zc(e,o,r.wildcardName)}callHandlerWithWildcard(e,s,r,o){if(r&&Object.keys(r).length>0){const n={...o,wildcardCapture:r};return e.handler.call(this.modelData,s,n,this.modelData)}else return e.handler.call(this.modelData,s,o,this.modelData)}resolvePropKey(e){const s=/.*({PROP_(.+)})/;let r=e.includes("{MODEL_ID}")?e.replace("{MODEL_ID}",this.modelId):e;const o=r.match(s);return o&&o[2]in this.modelData&&(r=r.replace(o[1],this.modelData[o[2]])),r}async subscribeWithFlowControl(e,s,r){this.log.debug(`Setting up flow control for topic: ${s}`);const o=new Rg(e.flow);this.flowControllers.set(s,o);const n=this.createFlowControlHandler(s,e),i=this.startFlowProcessing(e,s,n,o),a=()=>{this.flowControllers.delete(s),i.then(c=>c==null?void 0:c.abort())};r===x.ACTIVATE?this.activatableDisposers.push(a):this.disposers.push(a)}async startFlowProcessing(e,s,r,o){const n=new AbortController;try{let i;if(e.websocket){const a=e.destinationAddress?this.resolvePropKey(e.destinationAddress):null;xt.getInstance().subscribeTopic({topic:s,callback:()=>{},fos:e.fos,bridge:e.bridge,destinationAddress:a}),i=Ni(s)}else i=Ni(s);return(async()=>{try{for await(const a of o.processEvents(i)){if(n.signal.aborted)break;const c=r(a);c instanceof Promise&&await o.trackPromise(c)}}catch(a){this.log.error(`Flow control error for ${s}:`,a)}})(),n}catch(i){return this.log.error(`Failed to start flow processing for ${s}:`,i),null}}createFlowControlHandler(e,s){return async r=>{var o,n,i,a;try{if(s.condition&&!s.condition(r,this.modelData,r))return;if(this.model.isReady())return s.handler.call(this.modelData,r,r,this.modelData);{this.log.warn(`Model ${this.modelId} not ready. Queuing flow-controlled message for ${e}`);const c=()=>s.handler.call(this.modelData,r,r,this.modelData);this.offlineQueue.enqueue(c,e,r)}}catch(c){if(this.log.error(`Error in flow control handler for ${e}:`,c),(n=(o=s.flow)==null?void 0:o.errorHandling)!=null&&n.retry)await this.retryHandler(s,r,c);else if(!((a=(i=s.flow)==null?void 0:i.errorHandling)!=null&&a.continueOnError))throw c}}}async retryHandler(e,s,r){const o=e.flow.errorHandling.retry;let n=r;for(let i=1;i<=o.attempts;i++)try{return this.log.debug(`Retry attempt ${i}/${o.attempts} for handler`),await new Promise(a=>setTimeout(a,o.backoffMs*i)),e.handler.call(this.modelData,s,s,this.modelData)}catch(a){n=a,this.log.warn(`Retry attempt ${i} failed:`,a)}throw this.log.error("All retry attempts failed, throwing last error:",n),n}getFlowControlStats(){const e={};for(const[s,r]of this.flowControllers)e[s]=r.getStats();return e}getResponseStore(){return this.modelData.serviceResponses}isBaselineReady(e){const s=this.baselineDependencies.get(e);if(!s)return!0;const r=this.getResponseStore();if(!r)return this.log.warn(`ServiceResponseStore not found for baseline check on topic: ${e}`),!1;const n=`${(s.method||"get").toUpperCase()}:${s.path}`;return r.has(n)}flushQueueForBaseline(e){const s=this.baselineDependencies.get(e);if(!s){this.log.debug(`No baseline dependency for topic: ${e}`);return}const r=this.getResponseStore();if(!r){this.log.warn("ServiceResponseStore not found, falling back to standard flush"),this.offlineQueue.flush();return}const o=s.method||"get",n=r.getTemporalMetadataByPath(s.path,o);if(!n){this.log.warn(`Baseline temporal metadata not found for ${s.path}, falling back to standard flush`),this.offlineQueue.flush();return}const i=s.replayStrategy||it.AFTER_REQUEST;this.log.info(`Flushing queue with strategy ${i} for topic: ${e}`),this.log.debug(`Baseline timing - requested: ${n.requestedAt}, received: ${n.receivedAt}`),this.offlineQueue.flushWithStrategy(i,n.requestedAt,n.receivedAt)}}function vt(t,e){const s=`[Model:${e}]`;return{debug:(...r)=>t.debug(s,...r),info:(...r)=>t.info(s,...r),warn:(...r)=>t.warn(s,...r),error:(...r)=>t.error(s,...r)}}function Hg(t){return!!(t!=null&&t[at])&&Object.keys(t[at]).length>0}function Kg(t){return!!(t!=null&&t[ee])&&Object.keys(t[ee]).length>0}function qg(t){return!!(t!=null&&t[ke])&&t[ke].length>0}function zg(t){const e=Object.getPrototypeOf(t);return!!(e!=null&&e[ct])&&Object.keys(e[ct]).length>0}function Vg(t){return t.retention===de.TTL&&t.extendOnRefresh===!0&&t.ttl!==void 0}function Gg(t,e){return t.has(e)}function Yg(t){return!t.expiresAt||Date.now()<t.expiresAt}function Bi(t,e,s,r){const o=setTimeout(()=>r(t),e);s.set(t,o)}class Wg{constructor(){l(this,"responses",new Map);l(this,"retentionPolicies",new Map);l(this,"cleanupTimers",new Map)}set(e,s,r={retention:de.SINGLE},o=Date.now(),n=Date.now()){if(this.shouldExtendTTL(e,r))return this.extendExistingTTL(e,r.ttl),!1;const i=this.createCachedResponse(s,e,r,o,n);return this.storeResponse(e,i,r),!0}get(e){const s=this.responses.get(e);if(s){if(s.expiresAt&&Date.now()>s.expiresAt){this.delete(e);return}return s.data}}getByPath(e,s="get"){return this.get(this.makeKey(e,s))}has(e){return this.get(e)!==void 0}delete(e){this.responses.delete(e),this.retentionPolicies.delete(e);const s=this.cleanupTimers.get(e);s&&(clearTimeout(s),this.cleanupTimers.delete(e))}clearPath(e){Array.from(this.responses.keys()).filter(r=>this.extractPath(r)===e).forEach(r=>this.delete(r))}clear(){this.cleanupTimers.forEach(e=>clearTimeout(e)),this.responses.clear(),this.retentionPolicies.clear(),this.cleanupTimers.clear()}get size(){return this.responses.size}shouldCleanupAfterHandler(e){const s=this.retentionPolicies.get(e);return(s==null?void 0:s.retention)===de.IMMEDIATE}shouldExtendTTL(e,s){if(!Vg(s)||!Gg(this.responses,e))return!1;const r=this.responses.get(e);return Yg(r)}extendExistingTTL(e,s){const r=this.responses.get(e);r.expiresAt=Date.now()+s,this.resetCleanupTimer(e,s)}resetCleanupTimer(e,s){this.clearTimerIfExists(e),Bi(e,s,this.cleanupTimers,r=>this.delete(r))}clearTimerIfExists(e){const s=this.cleanupTimers.get(e);s&&(clearTimeout(s),this.cleanupTimers.delete(e))}createCachedResponse(e,s,r,o,n){return{data:e,timestamp:n,requestedAt:o,receivedAt:n,path:this.extractPath(s),method:this.extractMethod(s),expiresAt:this.calculateExpiresAt(r)}}calculateExpiresAt(e){return e.retention===de.TTL&&e.ttl?Date.now()+e.ttl:void 0}storeResponse(e,s,r){this.responses.set(e,s),this.retentionPolicies.set(e,r),this.applyRetentionPolicy(e,r)}applyRetentionPolicy(e,s){switch(s.retention){case de.IMMEDIATE:break;case de.TTL:s.ttl&&Bi(e,s.ttl,this.cleanupTimers,r=>this.delete(r));break;case de.SINGLE:break;case de.PERMANENT:case de.MANUAL:break}}makeKey(e,s){return`${s.toUpperCase()}:${e}`}extractPath(e){return e.split(":",2)[1]||e}extractMethod(e){return e.split(":",2)[0]||"get"}getTemporalMetadata(e){const s=this.responses.get(e);if(s)return{requestedAt:s.requestedAt,receivedAt:s.receivedAt}}getTemporalMetadataByPath(e,s="get"){return this.getTemporalMetadata(this.makeKey(e,s))}cleanup(){const e=Date.now();Array.from(this.responses.entries()).filter(([r,o])=>o.expiresAt&&e>o.expiresAt).map(([r])=>r).forEach(r=>this.delete(r))}}class Qg{static createAll(e){const{modelId:s,modelTypeName:r,modelData:o}=e,n=xc.create({modelId:s,modelTypeName:r}),i=new fg(e,vt(n,"fsm")),a=new gg(vt(n,"offline-queue")),c=new ng(e),u=new og(e),d=new Wg;o.serviceResponses=d;const h={fsm:i,offlineQueue:a,serviceResponseStore:d,companionManager:c,childResolver:u};if(Hg(o)&&(h.effectManager=new ig(r,s,o,vt(n,"effect"))),Kg(o)){const f=vt(n,"subscription");h.subscriptionManager=new Bg(e,o,s,a,f),h.onlineLifecycleManager=new mg(e,vt(n,"online"))}return qg(o)&&(h.httpRouteManager=new On(o,vt(n,"http-routes"))),zg(o)&&(h.serviceRequestManager=new Og(o,d)),h}}const N=D.getLogger("kos-model"),Zg="kos.extension.model.loader";class El{constructor({modelTypeName:e,id:s,modelData:r}){l(this,"_id");l(this,"_status");l(this,"_activeStatus");l(this,"_onlineStatus");l(this,"modelData");l(this,"modelTypeName");l(this,"initialized");l(this,"loaded");l(this,"_isLoadExecuting");l(this,"offlineQueue");l(this,"subscriptionManager");l(this,"effectManager");l(this,"httpRouteManager");l(this,"onlineLifecycleManager");l(this,"serviceResponses");l(this,"serviceRequestManager");l(this,"companionManager");l(this,"childResolver");l(this,"fsm");this._id=typeof s<"u"?`${s}`:e,this.modelTypeName=e,this.initialized=!1,this.loaded=!1,this._isLoadExecuting=!1,this.modelData=r,this._status=v.CREATED,this._activeStatus=v.INACTIVE,this._onlineStatus=v.OFFLINE;const o=Qg.createAll(this);this.fsm=o.fsm,this.offlineQueue=o.offlineQueue,this.companionManager=o.companionManager,this.childResolver=o.childResolver,this.serviceResponses=o.serviceResponseStore,o.effectManager&&(this.effectManager=o.effectManager),o.subscriptionManager&&(this.subscriptionManager=o.subscriptionManager),o.httpRouteManager&&(this.httpRouteManager=o.httpRouteManager),o.onlineLifecycleManager&&(this.onlineLifecycleManager=o.onlineLifecycleManager),o.serviceRequestManager&&(this.serviceRequestManager=o.serviceRequestManager),M.makeAutoObservable(this,{fsm:!1,effectManager:!1,subscriptionManager:!1,onlineLifecycleManager:!1,serviceRequestManager:!1,serviceResponses:!1,companionManager:!1,childResolver:!1,offlineQueue:!1}),sg(this)}get companionModels(){return this.companionManager}set status(e){this._status=e}get status(){return this._status}get modelId(){return this._id}get id(){return this._id}get activeStatus(){return this._activeStatus}set activeStatus(e){this._activeStatus=e}get onlineStatus(){return this._onlineStatus}set onlineStatus(e){this._onlineStatus=e}get modelManager(){return globalThis.kos.modelManager}isActive(){return this._status===v.ACTIVE}isOnline(){return this._onlineStatus===v.ONLINE}isReady(){return this._status===v.READY}async deactivate(){var e,s,r;N.debug(`deactivating model ${this.modelTypeName} with id ${this.modelId}`);try{const o=Y.getContext(this.modelId);await((s=(e=this.modelData)==null?void 0:e.deactivate)==null?void 0:s.call(e,o)),N.debug(`Model ${this.modelTypeName} with id ${this.modelId} deactivated`),(r=this.subscriptionManager)==null||r.deactivate()}catch(o){throw N.debug(`Model ${this.modelId} failed to deactivated`),o}}async activate(){var e,s,r,o;N.debug(`activating model ${this.modelTypeName} with id ${this.modelId}`),await ts(this,x.ACTIVATE);try{await((e=this.serviceRequestManager)==null?void 0:e.executeForLifecycle(x.ACTIVATE));const n=Y.getContext(this.modelId);await((r=(s=this.modelData)==null?void 0:s.activate)==null?void 0:r.call(s,n)),this.initializeStateMachineForLifecycle(x.ACTIVATE),N.debug(`Model ${this.modelTypeName} with id ${this.modelId} subscribing to all topics`),(o=this.subscriptionManager)==null||o.registerAll(x.ACTIVATE),this.createLifecycleCompanions(x.ACTIVATE),N.debug(`Model ${this.modelTypeName} with id ${this.modelId} activated`)}catch(n){throw N.debug(`Model ${this.modelId} failed to activate`),n}}async whenLoaded(){await To([{condition:()=>this.status===v.FAILED,onMatch:()=>{throw new Error(`Failed to initialize model ${this.modelId}`)}},{condition:()=>this.loaded,onMatch:()=>{N.debug(`Model ${this.modelId} is loaded`)}}])}async whenInitialized(){await To([{condition:()=>this.status===v.FAILED,onMatch:()=>{throw new Error(`Failed to initialize model ${this.modelId}`)}},{condition:()=>this.initialized,onMatch:()=>{N.debug(`Model ${this.modelId} is initialized`)}}])}async whenReady(){await To([{condition:()=>this.status===v.FAILED,onMatch:()=>{throw new Error(`Failed to ready model ${this.modelId}`)}},{condition:()=>this.status===v.READY,onMatch:()=>{N.debug(`Model ${this.modelId} is ready`)}}])}async ready(){var e,s,r,o;if(this.fsm.current===v.READY){N.debug(`already readying model ${this.modelTypeName} with id ${this.modelId} returning`);return}try{N.debug(`readying model ${this.modelTypeName} with id ${this.modelId}`),await ts(this,x.READY),await ol(this,Sn.READY,x.READY),await((e=this.serviceRequestManager)==null?void 0:e.executeForLifecycle(x.READY));const n=Y.getContext(this.modelId);await((r=(s=this.modelData)==null?void 0:s.ready)==null?void 0:r.call(s,n)),this.offlineQueue.flush(),this.initializeStateMachineForLifecycle(x.READY),(o=this.subscriptionManager)==null||o.registerAll(x.READY),this.createLifecycleCompanions(x.READY),N.debug(`Model ${this.modelId} is ready`);const i={modelId:this.modelId,modelType:this.modelTypeName};V(Wc(this.modelTypeName,this.modelId),i),V(Qc(this.modelTypeName),i)}catch(n){throw N.error(n),Error(n)}}async load(){var o,n,i,a,c,u;const e=this[Ye];e&&await e.whenLoaded();const{modelTypeName:s,modelId:r}=this;if(this.fsm.current===v.LOADED){N.debug(`Model ${s} with id ${r} already loaded`);return}if(this._isLoadExecuting){N.debug(`Model ${s} with id ${r} is currently executing load`);return}this._isLoadExecuting=!0;try{N.debug(`Loading model ${s} with id ${r}`),await ts(this,x.LOAD);const d=Y.getContext(r),h=`${Zg}.${s}`,f=await $.loader.executeLoader(h,{});f&&(N.info(`Setting loaded context for ${r}, type: ${s}`),d==null||d.set(h,f)),await((o=this.serviceRequestManager)==null?void 0:o.executeForLifecycle(x.LOAD)),await((i=(n=this.modelData)==null?void 0:n.load)==null?void 0:i.call(n,d)),J(()=>{this.loaded=!0}),N.debug(`Model ${s} with id ${r} successfully loaded`),this.initializeStateMachineForLifecycle(x.LOAD),(a=this.subscriptionManager)==null||a.registerAll(x.LOAD),(c=this.httpRouteManager)==null||c.registerAll(),(u=this.effectManager)==null||u.setup(),this.createLifecycleCompanions(x.LOAD)}catch(d){throw N.error(`Model ${r} failed to load`,d),d}finally{this._isLoadExecuting=!1}}async unload(){var e,s,r,o,n,i,a;N.debug(`unloading model ${this.modelTypeName} with id ${this.modelId}`);try{const c=this.getChildren().map(d=>{var h;return(h=d.unload)==null?void 0:h.call(d)}).filter(d=>!!d);await Promise.allSettled(c);const u=Y.getContext(this.modelId);if(await((s=(e=this.modelData)==null?void 0:e.unload)==null?void 0:s.call(e,u)),this.loaded=!1,(r=this.onlineLifecycleManager)==null||r.dispose(),this.modelData){const d=this.modelData;if(d._fsmInitialized=!1,d._fsmConfig){const h=((o=d._fsmOptions)==null?void 0:o.stateProperty)||"currentState";d[h]=void 0}d.stateHistory&&(d.stateHistory=[])}N.debug(`Model ${this.modelTypeName} with id ${this.modelId} unloaded`),(n=this.effectManager)==null||n.disposeAll(),(i=this.subscriptionManager)==null||i.disposeAll(),(a=this.httpRouteManager)==null||a.dispose()}catch(c){throw N.debug(`Model ${this.modelId} failed to unload`),c}}async init(){var n,i,a,c;const e=this[Ye];e&&await e.whenInitialized();const{modelId:s,modelTypeName:r}=this,o=Y.getContext(s);N.debug(`Initializing model ${r} with id ${s}`),await ts(this,x.INIT);try{await((n=this.serviceRequestManager)==null?void 0:n.executeForLifecycle(x.INIT)),await((a=(i=this.modelData)==null?void 0:i.init)==null?void 0:a.call(i,o)),this.initialized=!0,N.debug(`Model ${r} with id ${s} initialized`),(c=this.onlineLifecycleManager)==null||c.register(),this.initializeStateMachineForLifecycle(x.INIT),this.registerSubscribers(x.INIT),this.createLifecycleCompanions(x.INIT)}catch(u){throw N.error(`Model ${s} failed to initialize`,u),u}}async registerSubscribers(e){var s;N.debug(`registering subscribers in ${this.modelTypeName} with id ${this.modelId}`),(s=this.subscriptionManager)==null||s.registerAll(e)}initializeStateMachineForLifecycle(e){this.modelData&&Ic(this.modelData,e)}createLifecycleCompanions(e){this.modelManager.createLifecycleCompanions(this,{},e)}async online(){var s,r;N.debug(`online model ${this.modelTypeName} with id ${this.modelId}`),this.registerSubscribers();const e=Y.getContext(this.modelId);await((r=(s=this.modelData)==null?void 0:s.online)==null?void 0:r.call(s,e)),this.createLifecycleCompanions(x.ONLINE)}async offline(){var s,r,o;N.debug(`offline model ${this.modelTypeName} with id ${this.modelId}`),(s=this.subscriptionManager)==null||s.disposeAll();const e=Y.getContext(this.modelId);await((o=(r=this.modelData)==null?void 0:r.offline)==null?void 0:o.call(r,e))}accept(e){e.visit(this)}getChildren(){return this.childResolver.resolve()}addCompanionModel(e){this.companionManager.add(e)}clearCompanionModels(){this.companionManager.clear()}}const _o=m.createLogger({name:"kos-model-instantiator"});class Xg{constructor(e,s){l(this,"companionInstantiator");this.registry=e,this.cache=s,this.companionInstantiator=new Wp(e,s,this.createModelInstance.bind(this))}createModelInstance(e,s,r={}){var a;const o=this.registry.models[e];if(!o){const c=`No model registered for type ${e}`;throw _o.error(c,{modelType:e,requestedId:s,providedOptions:r,availableModelTypes:Object.keys(this.registry.models)}),$t(new Error(c),{modelType:e,modelId:s,operation:"model instantiation - registry lookup",options:r,metadata:{availableModelTypes:Object.keys(this.registry.models)}})}const n=o.singleton?e:s;if(this.cache.restoreFromDeleteCache(n),!this.cache.hasModel(n)){_o.debug(`Creating model instance: ${e} [${n}]`);const c=r&&Object.keys(r).length>0,u=o.class||o.create;if(((a=u==null?void 0:u.prototype)==null?void 0:a[Hs])===!0&&!c){const h=new Error(`Model ${e} requires options but none were provided`);throw ki(h,{modelType:e,options:r,registryId:this.registry.alias||"unknown"}),$t(h,{modelType:e,modelId:n,operation:"model instantiation - options validation",options:r,metadata:{requiresOptions:!0,hasOptions:!1}})}try{const h=o.create?o.create({modelTypeId:e,id:n,options:r}):new o.class(n,r),f=new El({modelTypeName:e,id:n,modelData:h});this.cache.addModel(f),this._createCompanionModels(f,r)}catch(h){throw ki(h,{modelType:e,options:r,registryId:this.registry.alias||"unknown"}),$t(h,{modelType:e,modelId:n,operation:"model instantiation",options:r})}}const i=this.cache.getModelById(n);if(!i)throw _o.error(`Model ${e} [${n}] not found in cache`),new Error(`Model ${e} [${n}] not found in cache`);return{model:i,data:i.modelData}}createCompanionModels(e,s,r){this.companionInstantiator.createCompanionModels(e,s,r)}_createCompanionModels(e,s){this.createCompanionModels(e,s)}}let Jg=class{constructor(e){this._registry=e}get registry(){return this._registry}getModelTypeRegistry(e){const s=this.registry.models[e];if(!s)throw new Error(`No registration for model type ${e}`);return s}registerModel(e){const s=e.type;this.registry.models[s]||(this.registry.models={...this.registry.models,...e.registration})}registerCompanionModel(e,s){var r,o;(r=this.registry).companionModels??(r.companionModels={}),(o=this.registry.companionModels)[e]??(o[e]=[]),this.registry.companionModels[e].some(n=>n.type===s)||this.registry.companionModels[e].push({type:s})}getModelSubscriptions(e){var s;return((s=this.getModelTypeRegistry(e))==null?void 0:s.subscriptions)||{}}getDataModelBuilder(e){var r;const s=(r=this.getModelTypeRegistry(e))==null?void 0:r.builder;if(!s)throw new Error(`No builder found for model type ${e}`);return s}getModelFactory(e){return zt(e)}};const Ml=10,Hi=m.createLogger({name:"kos-model-manager"});class Tl{constructor(){l(this,"cache");l(this,"instantiator");l(this,"dependencies");l(this,"_registry");globalThis.kos=globalThis.kos||{},this.dependencies=new Vp,globalThis.kos.modelManager=this,globalThis.kos.resolveKosModel=e=>{const s=this.getModelById(e);if(s)return s.modelData||{}},globalThis.kos.kosModelJson=e=>{var r,o;const s=this.getModelById(e);if(s)return((o=(r=s.modelData).toJSON)==null?void 0:o.call(r))||{}},globalThis.kos.kosModelDebug=e=>{var r;const s=this.getModelById(e);if(s)return((r=s.modelData)==null?void 0:r.debugState)||{}},globalThis.kos.kmd=globalThis.kos.kosModelDebug,globalThis.kos.kmj=globalThis.kos.kosModelJson}static create(e,s){const r=this.getInstance(s);return r._registry=new Jg(e),r.cache=new Gp(e.preloadModels),r.instantiator=new Xg(e,r.cache),r}static getInstance(e){var s,r;return(!((s=globalThis.kos)!=null&&s.modelManager)||e)&&(Hi.debug("Creating new instance of KosModelManager"),new this),(r=globalThis.kos)==null?void 0:r.modelManager}get registry(){return this._registry.registry}get preloadedModels(){return this.cache.preload(e=>(Hi.debug(`preloading ${e}`),typeof e=="string"?this.createModelInstance(e).model:this.createModelInstance(e.modelType,e.modelId,e.options).model))}get models(){return this.cache.models}getModelById(e){return this.cache.getModelById(e)}addModel(e){return this.cache.addModel(e)}removeModel(e){this.cache.removeModel(e.modelId)}hasModel(e){return this.cache.hasModel(e)}getModelsByType(e,s){return Array.from(this.models).filter(r=>r.modelTypeName===e).filter(r=>s?s(r.modelData):!0).map(r=>r.modelData)}getModelSubscriptions(e){return this._registry.getModelSubscriptions(e)}getDataModelBuilder(e){return this._registry.getDataModelBuilder(e)}getModelFactory(e){return zt(e)}addDependency(e,s){this.cache.restoreFromDeleteCache(s),this.dependencies.add(e,s)}removeDependency(e,s){this.dependencies.remove(e,s)}async reloadModel(e){if(e.id){const s=this.getModelById(e.id);s&&await s.fsm.transitionTo(L.RESET,v.RESETTING)}}async initiateDestroyModel(e){if(!e.id)throw new Error("Model ID is required");if(!this.dependencies.canDestroy(e.id))return;const s=this.getModelById(e.id);s&&(this.cache.markForDeletion(s),Gc.addToDeletionQueue(e.id,setTimeout(()=>this.destroyModel(s),Ml)))}async destroyModel(e){var s;e!=null&&e.modelId&&this.dependencies.canDestroy(e.modelId)&&(await((s=e.unload)==null?void 0:s.call(e)),this.removeModel(e))}createModelInstance(e,s,r={}){return this.instantiator.createModelInstance(e,s,r)}createLifecycleCompanions(e,s,r){this.instantiator.createCompanionModels(e,s,r)}registerCompanionModel(e,s){this._registry.registerCompanionModel(e,s)}registerModel(e){this._registry.registerModel(e)}}var ur=(t=>(t.CREATING="creating",t.CREATED="created",t.INITIALIZING="initializing",t.INITIALIZED="initialized",t.LOADING="loading",t.LOADED="loaded",t.ONLINE="online",t.READYING="readying",t.READY="ready",t.OFFLINE="offline",t.UNLOADING="unloading",t.UNLOADED="unloaded",t.RELOADING="reloading",t))(ur||{}),_t=(t=>(t.CREATE="create",t.INITIALIZE="init",t.READY="ready",t.GO_ONLINE="go_online",t.GO_OFFLINE="go_offline",t.UNLOAD="unload",t.RELOAD="reload",t))(_t||{});const em=t=>{const e=b.createMachine("offline",{online:b.state(b.transition("go_offline","offline",b.action(()=>{t.offline(),M.runInAction(()=>{t.isOnline=!1})}))),offline:b.state(b.transition("go_online","online",b.action(()=>{t.online(),M.runInAction(()=>{t.isOnline=!0})})))}),s=b.interpret(e,n=>D.debug(n.machine.current)),r=b.createMachine({creating:b.state(b.transition("create","created")),created:b.state(b.immediate("initializing")),initializing:b.invoke(()=>t.init(),b.transition("done","initialized")),initialized:b.state(b.immediate("loading")),loading:b.invoke(()=>t.load(),b.transition("done","loaded")),loaded:b.state(b.immediate("readying"),b.transition("unload","unloading")),readying:b.invoke(()=>t.ready(),b.transition("done","ready",b.action(()=>{M.runInAction(()=>{t.status="ready"})}))),reloading:b.invoke(()=>t.reload(),b.transition("done","loading")),ready:b.state(b.transition("reload","reloading"),b.transition("unload","unloaded",b.action(t.unload.bind(t))),b.transition("go_online","ready",b.action(()=>{s.send("go_online")})),b.transition("go_offline","ready",b.action(()=>{s.send("go_offline")}))),unloaded:b.state()});return{service:b.interpret(r,n=>D.debug(n.machine.current)),online:s}},Q=m.createLogger({name:"kos-core"}),tm=()=>{const t=ye(),e=t==null?void 0:t.alias,s=process.env.KOS_CONNECTION_ALIAS;return e||s||void 0},sm=()=>{const t=window.location.protocol,e=ye(),s=e==null?void 0:e.host;let r;try{r=new URL(s).protocol==="https:"?"wss://":"ws://"}catch{}return r||(t==="https:"?"wss://":"ws://")},rm=()=>{const t=window.location.hostname,e=process.env.KOS_HOST,s=ye(),r=s==null?void 0:s.host;let o;try{o=new URL(r).hostname}catch{}return o??e??t},om=()=>{const t=window.location.port,e=process.env.KOS_PORT,s=ye(),r=s==null?void 0:s.host;let o;try{o=new URL(r).port}catch{}return o??e??t},nm=(t,e)=>{let s;return{promise:new Promise((n,i)=>{s=setTimeout(()=>{e?m.error(`Model ${e.modelId} - ${e.modelTypeName} preloading - timed out after ${t}ms`):m.error(`KOS Core preloading timed out after ${t}ms`),i(new Error(`Model ${e==null?void 0:e.modelId} - ${e==null?void 0:e.modelTypeName} - timed out after ${t}ms`))},t)}),cancel:()=>{s&&clearTimeout(s)}}},Ki=t=>typeof t.reload=="function",im=t=>typeof t.unload=="function";var _l=(t=>(t.LOGGED_IN="logged_in",t.LOGGED_OUT="logged_out",t))(_l||{});class I{constructor(e){l(this,"fsmService");l(this,"status");l(this,"initialized");l(this,"loaded");l(this,"_transport");l(this,"modelManager");l(this,"authState");l(this,"isOnline");l(this,"_reloading");l(this,"_unloading");l(this,"connectionAlias");this.initialized=!1,this.connectionAlias=e,this.loaded=!1,this.isOnline=!1,this.status=ur.CREATED,this.authState="logged_out",this._reloading=!1,this._unloading=!1,M.makeAutoObservable(this),C("token",a=>{a&&(this.transport.token=a.body)}),C(Ms.CONNECTED,async()=>{await this.whenReady(),this.fsmService.service.send(_t.GO_ONLINE)}),C(Ms.DISCONNECTED,async()=>{this.fsmService.service.send(_t.GO_OFFLINE)}),C("/studioServer/auth/LOGGED_IN",()=>{this.authState="logged_in",this.transport.authorized=!0}),C("/studioServer/auth/LOGIN_REQUIRED",()=>{this.authState="logged_out",this.transport.authorized=!1}),C(Ms.RELOAD,()=>{Q.warn("WebSocket requested reload"),this.fsmService.service.send(_t.RELOAD)}),C("/studio/project/reload",()=>{Q.warn("Project requested reload"),this.fsmService.service.send(_t.RELOAD)});const s=xt.getInstance(),r=rm(),o=om(),n=sm();s.host=r,s.port=Number.parseInt(o),s.protocol=n,process.env.KOS_ALLOW_ANONYMOUS==="true"&&(s.authorized=!0);const i=tm()??e;i&&(s.alias=i.replace("{{TIMESTAMP}}",Date.now().toString())),this._transport=s.init(),this.fsmService=em(this),this.fsmService.service.send(_t.CREATE)}get onlineStatus(){return this.isOnline&&!this._reloading&&!this._unloading}get reloading(){return this._reloading}get unloading(){return this._unloading}async reload(){var o,n,i,a;const e=Date.now();if(this._reloading){Q.info("reload already in progress");return}this._reloading=!0,Q.warn("reloading KOS Core"),Q.warn("reloading preloaded models");const s=this.modelManager;for(const c of s.preloadedModels)Ki(c.modelData)&&(Q.info(`reloading model ${c.modelId}`),(o=c.unload)==null||o.call(c),await c.modelData.reload(),(n=c.registerSubscribers)==null||n.call(c),Q.info(`reloading model ${c.modelId} complete`));for(const c of s.models)!s.preloadedModels.includes(c)&&Ki(c.modelData)&&((i=c.unload)==null||i.call(c),await c.modelData.reload(),(a=c.registerSubscribers)==null||a.call(c));const r=Date.now()-e;setTimeout(()=>{M.runInAction(()=>{Q.warn("reloading KOS Core complete"),this._reloading=!1})},1e3-r)}async online(){Q.debug("KOS Core going online"),await this._transport.whenReady(),Q.debug("KOS Transport Ready. Calling online() for models"),V("/kosCore/online","/kosCore/online"),console.timeEnd("kosCore:startup")}async offline(){Q.debug("KOS Core going offline"),V("/kosCore/offline","/kosCore/offline")}async unload(){var o;Q.debug("Unloading KOS Core");const e=Date.now();this._unloading=!0,Q.debug("unloading KOS Core");const s=this.modelManager;for(const n of s.models)im(n.modelData)&&((o=n.unload)==null||o.call(n));const r=Date.now()-e;setTimeout(()=>{M.runInAction(()=>{this._unloading=!1})},1e3-r)}async whenReady(){await M.when(()=>this.status===ur.READY)}async ready(){Q.debug("Readying KOS Core"),await this._transport.whenReady();const e=this.modelManager.preloadedModels.map(o=>({modelId:o.modelId,model:o,promise:o.whenReady()})),r=(await Promise.allSettled(e.map(o=>{const{promise:n,cancel:i}=nm(5e3,o.model);Promise.race([o.promise.then(()=>{i()}),n])}))).filter(o=>o.status==="rejected");if(r.length)throw Q.error(`There were ${r.length} failed models on model preloading`),Error(`There were ${r.length} failed models on model preloading`);Q.debug("leaving kos-core ready() ")}get isReady(){return this.status===ur.READY}set transport(e){this._transport=e}get transport(){return this._transport}get coreInitialized(){return this.initialized}get modelsLoaded(){return this.loaded}async init(){Q.debug("entering kos-core init()"),console.time("kosCore:startup"),console.time("kosCore:init"),await this._transport.whenReady(),this.initialized=!0,Q.debug("initialized - leaving kos-core init()"),console.timeEnd("kosCore:init")}async load(){Q.debug("entering kos-core load()"),console.time("kosCore:load"),this.loaded=!0,Q.debug("loaded - leaving kos-core load()"),console.timeEnd("kosCore:load")}static create(e,s,r){var i,a,c;const o=this.getInstance({reset:s,connectionAlias:r});(i=e.extensions)!=null&&i.dataMapper&&Object.keys(e.extensions.dataMapper).forEach(u=>{var h,f;const d=(f=(h=e.extensions)==null?void 0:h.dataMapper)==null?void 0:f[u];d&&(Array.isArray(d)?d.forEach(p=>{$.dataMapper.registerDataMapper(u,p)}):$.dataMapper.registerDataMapper(u,d))}),(a=e.extensions)!=null&&a.propertyMapper&&Object.keys(e.extensions.propertyMapper).forEach(u=>{var h,f;const d=(f=(h=e.extensions)==null?void 0:h.propertyMapper)==null?void 0:f[u];d&&$.propertyMapper.registerPropertyMapper(u,d)}),(c=e.extensions)!=null&&c.contextLoader&&Object.keys(e.extensions.contextLoader).forEach(u=>{var h,f;const d=(f=(h=e.extensions)==null?void 0:h.contextLoader)==null?void 0:f[u];d&&$.loader.registerLoader(u,d)}),A.model.getAll().forEach(([,u])=>{e.models={...e.models,...u.registration}}),e.models={...e.models,...A.model.getLegacyModels()},A.companion.getAll().forEach(([u,d])=>{e.companionModels={...e.companionModels},e.companionModels[u]=e.companionModels[u]||[];for(const h of d){let f;if(typeof h=="string"){const p=e.models[h];if(p!=null&&p.class){const y=p.class.prototype[Ye];f=y==null?void 0:y.lifecycle}}e.companionModels[u].push({type:h,lifecycle:f})}}),A.model.getPreloadModels().forEach(u=>{e.preloadModels.includes(u)||e.preloadModels.push(u)});const n=Tl.create(e,s);return o.modelManager=n,o}static getInstance(e){return this._instance=window.KosCore,(!this._instance||e!=null&&e.reset)&&(window.KosCore=new this(e==null?void 0:e.connectionAlias),this._instance=window.KosCore),this._instance}}l(I,"_instance");function Uo(t){const e=new Uint8Array(t);let s="";for(let r=0;r<e.byteLength;r++)s+=String.fromCharCode(e[r]);return btoa(s)}function am(t){const e=atob(t),s=new Uint8Array(e.length);for(let r=0;r<e.length;r++)s[r]=e.charCodeAt(r);return s.buffer}async function cm(t){return await t.arrayBuffer()}function lm(t,e){return new Blob([t],{type:e})}async function um(t){const e={},s=[],r=[];t.forEach((o,n)=>{r.push([n,o])});for(const[o,n]of r)if(n instanceof File){const i=await n.arrayBuffer();s.push({name:o,filename:n.name,type:n.type,data:Uo(i)})}else e[o]=n.toString();return{fields:e,files:s}}function dm(t){return new ReadableStream({async start(){},async pull(e){await t(e)},cancel(){}})}async function hm(t){if(!t)return{data:"",contentType:"text/plain"};if(typeof t=="string")return{data:t,contentType:"text/plain"};if(t instanceof ArrayBuffer||t instanceof Uint8Array){let e;return t instanceof Uint8Array?(e=new ArrayBuffer(t.byteLength),new Uint8Array(e).set(t)):e=t,{data:Uo(e),contentType:"application/octet-stream",encoding:"base64"}}if(t instanceof Blob){const e=await cm(t);return{data:Uo(e),contentType:t.type||"application/octet-stream",encoding:"base64"}}if(t instanceof FormData){const e=await um(t);return{data:JSON.stringify(e),contentType:"multipart/form-data",encoding:"json"}}throw new Error("Unsupported body type")}const er=m.createLogger({name:"kos-fetch"}),fm=process.env.KOS_WS_TIMEOUT?parseInt(process.env.KOS_WS_TIMEOUT):3e4,pm=()=>new Promise(t=>{setTimeout(()=>{t(!0)},0)}),gm=t=>t!=null&&t.studio?ll:t!=null&&t.fos?ul:dl,mm=async(t,e)=>{const s=I.getInstance().transport;await s.whenReady();const r=dt(),o=new URL(t),n=`${o.pathname}${o.search}`;er.debug(`path: ${n}`);const i=(e==null?void 0:e.timeout)||fm,a=gm(e),c=await hm(e==null?void 0:e.body),u={};c.contentType&&(u["content-type"]=c.contentType),c.encoding&&(u["content-encoding"]=c.encoding);const d=Xe(a({path:n,requestId:r,method:(e==null?void 0:e.method)||"GET",destinationAddress:(e==null?void 0:e.destinationAddress)||"",ordered:e==null?void 0:e.ordered,tracker:e==null?void 0:e.tracker,bridge:e==null?void 0:e.bridge,headers:{...e==null?void 0:e.headers,...u}}),c.data);return new Promise(h=>{let f=null,p=null;if(e!=null&&e.signal){if(e.signal.aborted){h({headers:ss({}),status:0,ok:!1,json:async()=>null,body:rs(""),redirected:!1,statusText:"Request aborted",type:"basic",url:"",clone:function(){throw new Error("Function not implemented.")},bodyUsed:!1,arrayBuffer:function(){throw new Error("Function not implemented.")},blob:function(){throw new Error("Function not implemented.")},formData:function(){throw new Error("Function not implemented.")},text:function(){throw new Error("Function not implemented.")}});return}e.signal.addEventListener("abort",()=>{p&&clearTimeout(p),f&&f(),h({headers:ss({}),status:0,ok:!1,json:async()=>null,body:rs(""),redirected:!1,statusText:"Request aborted",type:"basic",url:"",clone:function(){throw new Error("Function not implemented.")},bodyUsed:!1,arrayBuffer:function(){throw new Error("Function not implemented.")},blob:function(){throw new Error("Function not implemented.")},formData:function(){throw new Error("Function not implemented.")},text:function(){throw new Error("Function not implemented.")}})})}p=setTimeout(()=>{er.error(`Timeout occurred - url: ${t}`),f&&f(),h({headers:ss({}),status:404,ok:!1,json:async()=>null,body:rs(""),redirected:!1,statusText:"",type:"basic",url:"",clone:function(){throw new Error("Function not implemented.")},bodyUsed:!1,arrayBuffer:function(){throw new Error("Function not implemented.")},blob:function(){throw new Error("Function not implemented.")},formData:function(){throw new Error("Function not implemented.")},text:function(){throw new Error("Function not implemented.")}})},i);const y=C(r,E=>{p&&clearTimeout(p);const _=(E==null?void 0:E.headers)||{},k=_["content-type"]||"text/plain",U=_["content-encoding"],O=(E==null?void 0:E.body)||"";let S=O;if(U==="base64"&&O)try{S=am(O)}catch(j){er.error("Failed to decode base64 response",j)}const z={headers:ss(_),status:_.status&&parseInt(_.status)||200,ok:_.status==="200",json:async()=>{try{if(typeof S=="string")return S.length?JSON.parse(S):null;{const Z=new TextDecoder().decode(S);return Z.length?JSON.parse(Z):null}}catch{throw Error("Not a JSON response")}},text:async()=>typeof S=="string"?S:new TextDecoder().decode(S),arrayBuffer:async()=>S instanceof ArrayBuffer?S:new TextEncoder().encode(S).buffer,blob:async()=>S instanceof ArrayBuffer?lm(S,k):new Blob([S],{type:k}),formData:async()=>{const j=new FormData;if(k==="multipart/form-data"&&typeof S=="string")try{const Z=JSON.parse(S);Z.fields&&Object.entries(Z.fields).forEach(([Ke,qe])=>{j.append(Ke,qe)}),Z.files&&er.warn("File reconstruction in FormData not fully implemented")}catch{throw new Error("Failed to parse FormData")}return j},body:e!=null&&e.stream?dm(async j=>{if(S instanceof ArrayBuffer)j.enqueue(new Uint8Array(S));else{const Z=new TextEncoder;j.enqueue(Z.encode(S))}j.close()}):rs(typeof S=="string"?S:""),redirected:!1,statusText:"",type:"basic",url:"",clone:function(){return{...this}},bodyUsed:!1};y.unsubscribe(),pm().then(()=>h(z))});f=y.unsubscribe;const w=e!=null&&e.fos?s.fosSocket:s.socket;if(!w)throw Error(`No web socket transport available: ${e}`);w==null||w.send(d)})};exports.BASE_URL="kos:";exports.kosFetch=mm;if(process.env.KOS_MOCK_FETCH==="true"){const t=process.env.KOS_PORT||"9999";exports.kosFetch=fetch,exports.BASE_URL=`http://localhost:${t}`}const ym=m.createLogger({name:"kos-model-visitor",group:"kos-ui-core"});class bm{constructor(){l(this,"visitedModels",new Set);this.visitedModels=new Set}start(e){var r;if(e.id===void 0)throw new Error("rootModel must have an id");const s=I.getInstance().modelManager.getModelById(e.id);if(!s)throw new Error(`Could not find rootModel with id: ${e.id}`);this.visitedModels.clear(),(r=s.accept)==null||r.call(s,this)}visit(e){var r;if(this.visitedModels.has(e.modelId)){ym.info(`model ${e.modelId} already visited`);return}const s=!!this.visitModel(e.modelData,this);this.visitedModels.add(e.modelId),!s&&((r=e.getChildren)==null||r.call(e).forEach(o=>{var n;(n=o.accept)==null||n.call(o,this)}))}}class Sl{constructor(){l(this,"middlewares",[])}use(e){this.middlewares.push(e)}async execute(e){let s=0;const r=async()=>{s++,s<this.middlewares.length&&await this.middlewares[s](e,r)};await this.middlewares[s](e,r)}}const vm=async(t,e)=>{const s=new Sl;e.forEach(o=>s.use(o));const r={data:t,result:{}};return await s.execute(r),r.result},zt=t=>({type:t,build:(e,s)=>I.getInstance().modelManager.createModelInstance(t,e,s).data,buildAsync:async(e,s)=>{const r=I.getInstance().modelManager.createModelInstance(t,e,s);return await r.model.whenInitialized(),r.data}}),wm=t=>{I.getInstance().modelManager.registerModel(t)},Em=(t,e)=>{I.getInstance().modelManager.registerCompanionModel(t,e)},qi="/kos/ui/internal/heartbeat/",Mm=({relationshipId:t,destinationAddress:e,onAbort:s,waitTime:r,beatTime:o})=>{const n=I.getInstance().transport,i=new AbortController;let a=performance.now();const c=n.subscribeTopic({topic:`${qi}${t}`,callback:()=>{a=performance.now()}}),u=r??3e3,d=window.setInterval(()=>{let w=performance.now()-a;w=w/1e3,w>u/1e3&&i.abort()},u),h=o??2e3,f=window.setInterval(()=>{bl({msg:{},options:{topic:`${qi}${t}`,destinationAddress:e}})},h),p=()=>{window.clearInterval(f),window.clearInterval(d),c()},y=()=>{p(),s&&s(),i.signal.removeEventListener("abort",y)};return i.signal.addEventListener("abort",y),{cleanUpHeartbeat:p}},Il=(...t)=>e=>t.reduce((s,r)=>r(s),e),Tm={maxAttempts:5,baseDelayMs:100,backoffFactor:1.5};async function _m(t,e){let s=1;const r={...Tm,...e},{maxAttempts:o,baseDelayMs:n,backoffFactor:i}=r;let a=n;for(;s<=o;)try{return await t()}catch(c){if(m.error(`Attempt ${s} failed: ${c}`),s<o)a=n*Math.pow(i,s),await new Promise(u=>setTimeout(u,a)),s++;else throw c}throw new Error("All attempts failed")}const Sm=m.createLogger({name:"kos-service-request"}),ce=t=>({isMock:!1,URL:exports.BASE_URL}),Im=(t,e,s)=>async({id:r,tracker:o,urlOverride:n,ordered:i,studio:a,fos:c,bridge:u,destinationAddress:d})=>{const h={method:"DELETE"};t&&(h.destinationAddress=t),o&&(h.tracker=o),Vt(h,{ordered:i,studio:a,fos:c,bridge:u,destinationAddress:d});const f=await s(n||`${e}/${r}`,h);if(!f.ok)throw Error(`There was a problem deleting the model; returned status ${f.status}`);return await f.json()},Vt=(t,{ordered:e,studio:s,fos:r,destinationAddress:o,bridge:n,timeout:i})=>(i&&(t.timeout=i),e&&(t.ordered=e),s&&(t.studio=s),r&&(t.fos=r),n&&(t.bridge=n),(o||o==="")&&(t.destinationAddress=o),t),Om=(t,e,s)=>async({urlOverride:r,ordered:o,studio:n,fos:i,bridge:a,timeout:c,destinationAddress:u})=>{const d={method:"GET"};t&&(d.destinationAddress=t),Vt(d,{timeout:c,ordered:o,studio:n,fos:i,bridge:a,destinationAddress:u});const f=await s(r||e,d);if(!f.ok){let y;try{y=await f.json()}catch{}throw new me(`There was a problem retrieving the model; returned status ${f.status}`,y)}return await f.json()},$m=(t,e,s)=>async({urlOverride:r,ordered:o,studio:n,fos:i,bridge:a,tracker:c,timeout:u,destinationAddress:d})=>{const h={method:"GET"};t&&(h.destinationAddress=t),c&&(h.tracker=c),Vt(h,{timeout:u,ordered:o,studio:n,fos:i,bridge:a,destinationAddress:d});const f=r||e;Sm.debug(`resolvedUrl: ${f}`);const p=await s(f,h);if(!p.ok){let w;try{w=await p.json()}catch{}throw new me(`There was a problem retrieving the model; returned status ${p.status}`,w)}return await p.json()},Cm=(t,e,s)=>async({urlOverride:r,id:o,ordered:n,studio:i,fos:a,bridge:c,timeout:u,destinationAddress:d})=>{const h={method:"GET"};t&&(h.destinationAddress=t),Vt(h,{timeout:u,ordered:n,studio:i,fos:a,bridge:c,destinationAddress:d});const f=r||`${e}/${o}`,p=await s(f,h);if(!p.ok){let w;try{w=await p.json()}catch{}throw new me(`There was a problem retrieving the model; returned status ${p.status}`,w)}return await p.json()};class me extends Error{constructor(s,r){super(s);l(this,"payload");this.name="FetchException",this.payload=r}}const zi=(t,e,s)=>async({model:r,urlOverride:o,ordered:n,tracker:i,studio:a,fos:c,bridge:u,timeout:d,destinationAddress:h})=>{const f={method:"POST",body:typeof r=="string"?r:JSON.stringify(r)};t&&(f.destinationAddress=t),i&&(f.tracker=i),Vt(f,{timeout:d,ordered:n,studio:a,fos:c,bridge:u,destinationAddress:h});const p=await s(o||e,f);if(!p.ok){let w;try{w=await p.json()}catch{}throw new me(`There was a problem sending the POST data; returned status ${p.status}`,w)}return await p.json()},Vi=(t="POST",e,s,r)=>async({model:o,id:n,urlOverride:i,ordered:a,studio:c,fos:u,bridge:d,timeout:h,destinationAddress:f})=>{const p={method:t};o&&(p.body=JSON.stringify(o)),e&&(p.destinationAddress=e),Vt(p,{timeout:h,ordered:a,studio:c,fos:u,bridge:d,destinationAddress:f});const y=await r(i||`${s}/${n}`,p);if(!y.ok){let E;try{E=await y.json()}catch{}throw new me(`There was a problem modifying the model; returned status ${y.status}`,E)}return await y.json()},oe={build:({destinationAddress:t="",basePath:e,getAllPath:s,getOnePath:r,deleteModelPath:o,addModelPath:n,modifyModelPath:i,mock:a=!1})=>{const c=a?fetch:exports.kosFetch;return{getAll:Om(t,s||e,c),getModelById:Cm(t,r||e,c),getOne:$m(t,r||e,c),addModel:zi(t,n||e,c),deleteModel:Im(t,o||e,c),modifyModel:Vi("POST",t,i||e,c),putModel:Vi("PUT",t,i||e,c),postModel:zi(t,n||e,c)}}};function Dm(t,e,s="get"){const r=t.serviceResponses;if(r)return r.getByPath(e,s)}function xm(t,e,s="get"){const r=t.serviceResponses;return r?r.has(`${s.toUpperCase()}:${e}`):!1}function Am(t,e,s="get"){const r=t.serviceResponses;r&&r.delete(`${s.toUpperCase()}:${e}`)}function Rm(t,e){const s=t.serviceResponses;s&&s.clearPath(e)}function Pm(t){const e=t.serviceResponses;e&&e.clear()}const km=dt(),Ol=()=>`kos-${km}`,Lm=t=>!!t&&!t.includes("VM_SERVICE")&&t.startsWith(Ol()),Cn=async(t,e=6e4)=>new Promise((s,r)=>{const{unsubscribe:o}=C(t,i=>{D.debug(`recieved response for refId ${t}: ${i}`),o(),clearTimeout(n);try{const a=i!=null&&i.body?JSON.parse(i.body):{};s(a)}catch{const a=(i==null?void 0:i.body)||{};s(a)}}),n=setTimeout(()=>{o(),r(Error(`Request with ID ${t} timed out. Cancelling.`))},e)}),Fm=async(t,e,s)=>{const r=Cn(s),o=await Promise.allSettled([t(e),r]);if(o[0].status==="fulfilled"){if(o[1].status==="rejected")throw Error(o[1].reason);if(o[0].value){if(o[1].value.error)throw Error(o[1].value.error);return o[0].value.data=o[1].value,o[0].value}}else throw Error(o[0].reason)},Nm=async({topic:t,msg:e,requestId:s})=>{const r=s??dt(),o=Cn(r);V(t,e,{sync:r});const n=await o;if(n.error)throw Error(n.error);return n},fe=new Map;class $l{constructor(e){l(this,"_context");l(this,"_parent");l(this,"_id");this._id=e,this._context=new M.ObservableMap({}),this._parent="",M.makeAutoObservable(this)}setParent(e){J(()=>{this._parent=e})}get id(){return this._id}get context(){return this._context}get parentModel(){var e;if(this._parent)return(e=$e(this._parent))==null?void 0:e.model}get companionModels(){const e=$e(this._id);return e!=null&&e.model?Bc(e.model):[]}get(e){var s,r;if(this._context.has(e))return this._context.get(e);if(this.companionModels.length>0){const o=this.companionModels.find(n=>{var i;return!n.id||!fe.has(n.id)?!1:(i=fe.get(n.id))==null?void 0:i.context.has(e)});if(o)return(s=fe.get(o.id))==null?void 0:s.get(e)}if(this._parent)return(r=fe.get(this._parent))==null?void 0:r.get(e)}set(e,s){this._context.set(e,s)}remove(e){this._context.delete(e)}clear(){this._context.clear()}}const Y={createContext:(t,e)=>{const s=fe.get(t)??new $l(t);if(e){if(!fe.has(e))throw new Error(`Parent context ${e} does not exist`);s.setParent(e)}else t!=="root"&&s.setParent("root");return fe.set(t,s),s},getContext:t=>fe.get(t),deleteContext:t=>{fe.delete(t)},setParentContext:(t,e)=>{var s;if(!fe.has(e))throw new Error(`Parent context ${e} does not exist`);(s=fe.get(t))==null||s.setParent(e)},rootContext:()=>fe.get("root")};Y.createContext("root");const Um=t=>Y.getContext(t.id),tt=m.createLogger({name:"kos-data-container"});class Dn{constructor(e){l(this,"_data");l(this,"_sortKey");l(this,"_revision");l(this,"_index");l(this,"_optionsMap");l(this,"_disposerMap",new Map);l(this,"idx");l(this,"_maxCapacity");l(this,"_evictionStrategy");l(this,"_evictionBatchSize");l(this,"_insertionOrder",[]);l(this,"_accessTimes");l(this,"_customEvictionFilter");this._data=M.observable.map(new Map),this._sortKey=e==null?void 0:e.sortKey,this._revision=1,this._optionsMap=(e==null?void 0:e.indexMap)||{};const s=e!=null&&e.indexMap?Object.keys(e.indexMap).reduce((r,o)=>(r[o]=void 0,r),{}):{};this._index=M.observable.map(s),this.idx=Oe(),this._maxCapacity=e==null?void 0:e.maxCapacity,this._evictionStrategy=(e==null?void 0:e.evictionStrategy)||"fifo",this._evictionBatchSize=(e==null?void 0:e.evictionBatchSize)??Math.max(10,Math.ceil(((e==null?void 0:e.maxCapacity)??100)*.1)),this._customEvictionFilter=e==null?void 0:e.customEvictionFilter,this._evictionStrategy==="lru"&&this._maxCapacity&&(this._accessTimes=M.observable.map(new Map)),M.makeAutoObservable(this,{}),this.init()}init(){Object.keys(this._optionsMap).forEach(e=>{const s=this._optionsMap[e],r=new Tn({container:this,key:s});this._index.set(e,r),this.idx[e]=r.data})}[Symbol.iterator](){return this.data[Symbol.iterator]()}get index(){return this._index}get indexKeys(){return Array.from(this.index.keys()).reduce((e,s)=>{var r;return e[s]=(r=this.index.get(s))==null?void 0:r.keys,e},{})}get revision(){return this._revision}addAll(e){M.runInAction(()=>{e.forEach(s=>this.addModel(s))})}removeAll(e){M.runInAction(()=>{e.forEach(s=>this.removeModel(s))})}sortFn(e,s){const r=this._sortKey;return r?String(e[r]).localeCompare(String(s[r]),void 0,{numeric:!0}):0}get data(){const e=Array.from(this._data.values());return this._sortKey&&e.sort(this.sortFn.bind(this)),e}increment(){M.runInAction(()=>{this._revision=this._revision+1})}addModel(e,s){const r=this._ensureObservable(e);this._cleanupExistingDisposer(e.id),this._persistData(r),this._trackDataMetadata(r),this._enforceCapacityLimits(),this._configureDataMonitoring(r),s||this.increment()}_ensureObservable(e){return M.isObservable(e)?e:M.observable.object(e)}_cleanupExistingDisposer(e){if(!e)return;const s=this._disposerMap.get(e);s&&(s(),this._disposerMap.delete(e))}_persistData(e){this._data.set(e.id||"",e)}_trackDataMetadata(e){this._maxCapacity&&(this._insertionOrder.push(e.id||""),this._accessTimes&&this._accessTimes.set(e.id||"",Date.now()))}_enforceCapacityLimits(){this._maxCapacity&&this._data.size>this._maxCapacity&&this._evictModels()}_configureDataMonitoring(e){const s=M.observe(e,r=>{Object.values(this._optionsMap||{}).includes(r.name)&&this.increment()});this._disposerMap.set(e.id||"",s)}removeModel(e){this._data.delete(e);const s=this._insertionOrder.indexOf(e);s!==-1&&this._insertionOrder.splice(s,1),this._accessTimes&&this._accessTimes.delete(e),this.increment();const r=this._disposerMap.get(e);r&&(r(),this._disposerMap.delete(e))}updateModel(e){const s=M.observable.object(e);this._data.set(s.id||"",s),this.increment()}getModel(e){const s=this._data.get(e);return s&&this._accessTimes&&this._accessTimes.set(e,Date.now()),s}getIndexKeys(e){return this.index.has(e)?this.index.get(e).keys??[]:(tt.info(`index ${e} not found in ${Array.from(this.index.keys())}`),[])}getIndexByKey(e,s){if(this.index.has(e)){const r=this.index.get(e);return r.index.has(s)?r.getByKey(s):(tt.info(`key ${s} not found in ${e} index: ${Array.from(r.index.keys())}`),[])}else return tt.info(`index ${e} not found in ${Array.from(this.index.keys())}`),[]}_evictModels(){if(!this._maxCapacity)return;const e=this._data.size-this._maxCapacity;if(e<=0)return;const s=Math.min(this._evictionBatchSize,e);this._logDataCapacityWarning(s);const r=this._selectDataForEviction(s);this._removeEvictedData(r),this._logDataEvictionComplete(r.length)}_logDataCapacityWarning(e){tt.info(`Data container capacity exceeded (${this._data.size}/${this._maxCapacity}). Evicting ${e} items using ${this._evictionStrategy} strategy. This may indicate missing cleanup handlers or data inconsistency.`)}_selectDataForEviction(e){switch(this._evictionStrategy){case"fifo":return this._selectFifoData(e);case"lru":return this._selectLruData(e);case"custom":return this._selectCustomData(e);default:return this._selectFifoData(e)}}_selectFifoData(e){const s=[];for(let r=0;r<e&&this._insertionOrder.length>0;r++){const o=this._insertionOrder.shift();o&&this._data.has(o)&&s.push(o)}return s}_selectLruData(e){const s=[];return this._accessTimes&&Array.from(this._accessTimes.entries()).sort((o,n)=>o[1]-n[1]).slice(0,e).forEach(([o])=>{this._data.has(o)&&s.push(o)}),s}_selectCustomData(e){return this._customEvictionFilter?this._customEvictionFilter(this.data).slice(0,e).map(r=>r.id):(tt.error("Custom eviction strategy specified but no customEvictionFilter provided. Falling back to FIFO."),this._selectFifoData(e))}_removeEvictedData(e){e.forEach(s=>{var o;const r=this._data.get(s);tt.info(`Evicting data item: ${s}`,{itemId:s,itemType:r?(o=r.constructor)==null?void 0:o.name:"unknown",strategy:this._evictionStrategy}),this.removeModel(s)})}_logDataEvictionComplete(e){tt.info(`Evicted ${e} data items. Current size: ${this._data.size}/${this._maxCapacity}`)}async clear(){this._data.clear(),this.increment()}filter(e,s){return this.data.filter(e,s)}sort(e){return this.data.sort(e)}map(e,s){return this.data.map(e,s)}forEach(e,s){this.data.forEach(e,s)}toJSON(){return{indexes:this.indexKeys,data:this.data.map(s=>({id:s.id}))}}}class jm{constructor({type:e,model:s,childRegistration:r}){l(this,"type");l(this,"childRegistration");l(this,"model");this.type=e,this.model=s,this.childRegistration=r}get factory(){return ae.Factory.create(this.type)}get registration(){return{[this.type]:{class:this.model,singleton:!1,factory:this.factory},...this.childRegistration}}get predicate(){return _e(this.type)}}class Bm{constructor({type:e,model:s,childRegistration:r}){l(this,"type");l(this,"model");l(this,"childRegistration");this.type=e,this.model=s,this.childRegistration=r}get factory(){return ae.Singleton.create(this.type)}get registration(){return{[this.type]:{class:this.model,singleton:!0,factory:this.factory},...this.childRegistration}}get predicate(){return _e(this.type)}}class Cl{constructor(){l(this,"_token");M.makeAutoObservable(this),C("token",e=>{this.token=e==null?void 0:e.body})}get token(){return this._token}set token(e){this._token=e}}class Dl{constructor(){l(this,"routes",[]);l(this,"openApiRoutes",[])}use(e,s,...r){this.routes.push({method:e,path:s,middlewares:r});const o=this.extractOpenApiParams(s);this.openApiRoutes.push({method:e,path:s,parameters:o})}remove(e,s){const r=this.routes.length;return this.routes=this.routes.filter(o=>!(o.method===e&&o.path===s)),this.openApiRoutes=this.openApiRoutes.filter(o=>!(o.method===e&&o.path===s)),r-this.routes.length}removeAllForPath(e){const s=this.routes.length;return this.routes=this.routes.filter(r=>r.path!==e),this.openApiRoutes=this.openApiRoutes.filter(r=>r.path!==e),s-this.routes.length}getRoutes(){return this.routes.map(e=>({method:e.method,path:e.path}))}async handle(e,s){var a;const{path:r,query:o,params:n}=this.extractPathParams(e.path),i={...e,params:n,query:o};for(const c of this.routes){const u=this.matchRoute(c.path,r);if(c.method===e.method&&u){i.params=u;let d=0;const h=async()=>{if(d<c.middlewares.length){const f=c.middlewares[d++];await f(i,s,h)}};await h();return}}(a=s.status)==null||a.call(s,404).send({error:"Route not found"})}extractOpenApiParams(e){return e.split("/").filter(s=>s.startsWith(":")).map(s=>({name:s.slice(1),in:"path",required:!0,schema:{type:"string"}}))}generateOpenApiSpec(){const e={};for(const s of this.openApiRoutes)e[s.path]||(e[s.path]={}),e[s.path][s.method.toLowerCase()]={summary:s.description||`Handles ${s.method} ${s.path}`,parameters:s.parameters||[],responses:{200:{description:"Successful response"}}};return{openapi:"3.0.0",info:{title:"Kos Router API",version:"1.0.0",description:"Dynamically generated OpenAPI documentation"},paths:e}}extractPathParams(e){const[s,r]=e.split("?"),o=this.parseQueryParams(r);for(const n of this.routes){const i=this.matchRoute(n.path,s);if(i)return{path:s,query:o,params:i}}return{path:s,query:o,params:{}}}matchRoute(e,s){const r=e.split("/").filter(Boolean),o=s.split("/").filter(Boolean);if(r.length!==o.length)return null;const n={};for(let i=0;i<r.length;i++)if(r[i].startsWith(":"))n[r[i].slice(1)]=decodeURIComponent(o[i]);else if(r[i]!==o[i])return null;return n}parseQueryParams(e){return e?e.split("&").reduce((s,r)=>{const[o,n]=r.split("=").map(decodeURIComponent);return s[o]=n??"",s},{}):{}}}const xl=m.createLogger({name:"intent-service"}),Hm=t=>{an(`/kos/intent/${t.type}`)?V(`/kos/intent/${t.type}`,t.options,{"kos.intent.type":t.type}):xl.info(`No subscribers for intent ${t.type}. Intent not sent.`)},Km=async t=>new Promise(e=>{const{type:s,options:r}=t;if(an(`/kos/intent/${t.type}`)){const o=dt(),{unsubscribe:n}=C(o,a=>{clearTimeout(i),n(),a&&(a.headers=a.headers||{},a.headers["kos.intent.type"]=s,a.headers.responseId=o),e([null,{body:a==null?void 0:a.body,payload:a}])}),i=setTimeout(()=>{n(),e([`Intent ${s} timed out after 1 second`,null]),console.warn(`Intent ${s} timed out after 1 second`)},1e3);V(`/kos/intent/${s}`,r,{"kos.intent.type":s,sync:o})}else xl.info(`No subscribers for intent ${t.type}. Intent not sent.`),e([null,{body:void 0,payload:void 0}])}),Pe=m.createLogger({name:"app-startup-service"});async function Al(t,e={}){const{timeout:s=3e4,throwOnTimeout:r=!0,requirePostStarted:o=!1}=e;if(t.length===0)return Pe.warn("No app IDs provided to waitForAppsToStart"),!0;Pe.debug(`Waiting for apps to start: ${t.join(", ")}`);try{const n=t.map(c=>`/kos/app/started/${c}`),i=await un(n,{getCurrentState:async()=>{try{const{default:c}=await Promise.resolve().then(()=>al),[u,d]=await c.get("/api/kos/apps/started");return u?(Pe.error("Error fetching started apps:",u),[]):d}catch(c){Pe.error("Failed to fetch app startup status:",c)}return[]},shouldUseFetchedState:c=>t.every(u=>{const d=c.find(h=>h.appId===u);return!(!d||!d.started||o&&!d.postStarted)}),timeout:s}),a=t.filter(c=>{const u=i.find(d=>d.appId===c);return!!(!u||!u.started||o&&!u.postStarted)});if(a.length>0){const c=`Apps not started: ${a.join(", ")}`;if(Pe.error(c),r)throw new Error(`App startup timeout: ${c}`);return!1}return Pe.info(`All apps started successfully: ${t.join(", ")}`),!0}catch(n){const i=`Failed to wait for apps to start: ${t.join(", ")}`;if(Pe.error(i,n),r)throw new Error(`${i} - ${n instanceof Error?n.message:String(n)}`);return!1}}async function qm(t,e={}){return Al([t],e)}async function zm(t,e=!1){const s={};try{const r=await exports.kosFetch("kos:///api/kos/apps/started");if(!r.ok)return t.forEach(i=>s[i]=!1),s;const o=await r.json(),n=(o==null?void 0:o.data)??[];t.forEach(i=>{const a=n.find(c=>c.appId===i);s[i]=(a==null?void 0:a.started)===!0&&(!e||(a==null?void 0:a.postStarted)===!0)})}catch(r){Pe.error("Failed to check app startup status:",r),t.forEach(o=>s[o]=!1)}return s}async function Vm(){try{const t=await exports.kosFetch("kos:///api/kos/apps/started");if(!t.ok)return[];const e=await t.json();return(e==null?void 0:e.data)??[]}catch(t){return Pe.error("Failed to fetch started apps:",t),[]}}const jo=M.when,xn=M.computed,J=M.runInAction,W=M.autorun,Rl=M.reaction,An=M.observable,Rn="Not Assigned",Gm="kos.trouble.added",Ym="kos.trouble.removed";var we=(t=>(t.TroubleRank="kos.trouble.rank.mapper",t.TroubleColor="kos.trouble.color.mapper",t.TroubleRole="kos.trouble.role.mapper",t))(we||{}),Ts=(t=>(t.TIME_CHANGE="/kos/internal/time/time",t.DAY_CHANGE="/kos/internal/time/day",t.TIMEZONE_CHANGE="/kos/internal/time/timezone",t))(Ts||{});const Pl=m.createLogger({name:"config-bean-service",group:"Services"}),Pn=exports.BASE_URL,kl=t=>(t==null?void 0:t.decimals)!==void 0,{postModel:Wm,getOne:Qm}=oe.build({destinationAddress:"",basePath:`${Pn}/kos/config/`}),Ll=async(t,e,s="/api/kos/config")=>(Pl.debug(`sending modify request for ConfigBean: ${t}`),Wm({model:e,urlOverride:`${Pn}${s}/${t}`})),Fl=async(t,e="/api/kos/config")=>(Pl.debug(`sending get request for ConfigBean: ${t}`),await Qm({urlOverride:`${Pn}${e}/details/${t}/15`})),kn=t=>t.toLowerCase()==="true"||t.toLowerCase()==="false",Xr=t=>{try{const e=Number(t);return!isNaN(e)}catch{return!1}};function Nl(t=[]){return t.reverse().reduce((e,s)=>{const{overrides:r}=s;return r&&(e={...e,...r}),e},{})}function Ul(t,e="",s={}){for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)){const o=e?`${e}.${r}`:r;typeof t[r]=="object"&&t[r]!==null&&!Array.isArray(t[r])?Ul(t[r],o,s):s[o]=t[r]}return s}const jl=(t,e)=>{const s=t.details[0].bean||Nl(t.details[0].scopes),r=Ul(s);M.runInAction(()=>{const o={...r};e.props.setValues(o)})},Bl=(t,e)=>{M.runInAction(()=>{t.changes.forEach(s=>{const r=s.attr;let o=s.currentValue,n=s.previousValue;typeof o=="string"&&kn(o)&&(o=o.toLowerCase()=="true",n=(n==null?void 0:n.toLowerCase())=="true"),typeof o=="string"&&Xr(o)&&(o=Number(o),n=Number(n)),e.props[r]=o,e.prevProps[r]=n})})},Hl=t=>Object.fromEntries(t.props.entries),Zm=t=>e=>s=>t.build(e,s);var Xm=Object.defineProperty,Jm=Object.getOwnPropertyDescriptor,Kl=(t,e,s,r)=>{for(var o=r>1?void 0:r?Jm(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Xm(e,s,o),o};function ey(t,e){for(const s of t)if(new RegExp(`^${s}$`).test(e))return s}const Ln="config-bean-model",tr=m.getLogger(Ln),ty=ht("path");let br=class{constructor(t,e){l(this,"_modifyConfigBean");l(this,"_getConfigBean");l(this,"_schema");l(this,"id");l(this,"path");l(this,"props");l(this,"prevProps");l(this,"serviceBasePath");Object.assign(this,e),this.id=t,this.path=e.path,this.serviceBasePath=e.serviceBasePath;const{modifyConfigBean:s=Ll,getConfigBean:r=Fl}=e;this._modifyConfigBean=s,this._getConfigBean=r,this.props=Oe(),this.prevProps=Oe()}get values(){return this.props.values}async ready(){tr.debug(`readying config bean ${this.path}`),tr.debug(`complete readying config bean ${this.path}`)}async load(){tr.debug(`loading config bean ${this.path}`);const t=await this._getConfigBean(this.path,this.serviceBasePath);if(t!=null&&t.data){const e=t.data;jl(e,this),tr.debug(this.values);const s=t==null?void 0:t.data.details[0].schema;J(()=>{s&&(this._schema=s)})}}get schemaKeys(){var t;return Object.keys(((t=this._schema)==null?void 0:t.schema)||{})}getSchemaForProperty(t){var s,r;if(this.schemaKeys.includes(t))return(s=this._schema)==null?void 0:s.schema[t];const e=ey(this.schemaKeys,t);if(e)return(r=this._schema)==null?void 0:r.schema[e]}async updateProperty(t,e){this.props[t]=e,await this.updateConfigBean()}async updateConfigBean(){const t=Hl(this);await this._modifyConfigBean(this.path,t,this.serviceBasePath)}handleConfigBeanUpdated(t){Bl(t,this)}};Kl([H({topic:`/kos/config/${ty}`,websocket:!0})],br.prototype,"handleConfigBeanUpdated",1);br=Kl([R(Ln)],br);const Is=new be({class:br,type:Ln}),Jr=({path:t,lazy:e,serviceBasePath:s})=>(r,o)=>{r[F]=r[F]||{},r[F][o]={modelType:Is.type,id:`${Is.type}-${t}`,options:{path:t,serviceBasePath:s},lifecycle:x.INIT,lazy:e}},{URL:ql}=ce(),{getOne:sy,getAll:ry}=oe.build({basePath:`${ql}/api/kos/regions/info`}),zl=async()=>{try{return await sy({})}catch{return}},Vl=async()=>{try{return await ry({urlOverride:`${ql}/api/kos/regions`})}catch{return}},oy=Object.freeze(Object.defineProperty({__proto__:null,getRegionInfo:zl,getRegions:Vl},Symbol.toStringTag,{value:"Module"}));var ue=(t=>(t[t.family=0]="family",t[t.scale=1]="scale",t[t.offset=2]="offset",t[t.decimals=3]="decimals",t[t.alias=4]="alias",t[t.system=5]="system",t))(ue||{});const Gl={s:["time",1,0,0],second:["time",1,0,0],m:["time",1/60,0,0],minute:["time",1/60,0,0],h:["time",1/3600,0,0],hour:["time",1/3600,0,0],day:["time",1/86400,0,0],week:["time",1/604800,0,0],month:["time",1/2628e3,0,0],year:["time",1/31536e3,0,0],default:["time",1/.001,0,0],ms:["time",1/.001,0,0],millisecond:["time",1/.001,0,0],microsecond:["time",1/1e-6,0,0],nanosecond:["time",1/1e-9,0,0],picosecond:["time",1/1e-12,0,0]};function ny(t,e){const s=e.id,r=e.units.reduce((o,n)=>{const i=[n.measure,n.scale,n.offset,n.decimals,n.alias,s];return o[n.name]=i,n.alias&&(o[n.alias]=i),o},{...Gl});return{...t,...r}}function iy(t,e){const s=e.id,r=e.units.reduce((o,n)=>{const i=o[n.measure]||{},a=i[s]||{};i[s]=a;const c=[n.measure,n.scale,n.offset,n.decimals,n.alias,s];return a[n.name]=c,Object.hasOwn(n,"default")&&Object.defineProperty(a,"default",{value:c,writable:!0,enumerable:!0,configurable:!0}),o[n.measure]=i,n.alias&&(o[n.alias]=i),o},{time:{[s]:{...Gl}}});return Object.keys(r).forEach(o=>{t[o]={...t[o],...r[o]}}),t}function ay(t,e){const s=e.id,r=e.units.reduce((o,n)=>{const i=o[n.measure]||{};return Object.hasOwn(n,"default")&&(i[s]=n.name),o[n.measure]=i,o},{time:{[s]:"millisecond"}});return Object.keys(r).forEach(o=>{t[o]={...t[o],...r[o]}}),t}var cy=Object.defineProperty,ly=Object.getOwnPropertyDescriptor,Fn=(t,e,s,r)=>{for(var o=r>1?void 0:r?ly(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&cy(e,s,o),o};const dr="region-info-model",es=m.createLogger({name:"region-info-model"});let Os=class{constructor(t){l(this,"id");l(this,"unitSystemMap");l(this,"measureMap");l(this,"defaultMeasureMap");l(this,"regionMap");l(this,"timeFormats");l(this,"dateFormats");l(this,"unitSystems");l(this,"regionSource");l(this,"region");l(this,"regions",[]);l(this,"timeZoneMap",{});this.id=t,this.unitSystems={},this.unitSystemMap={},this.measureMap={},this.defaultMeasureMap={},this.timeFormats={},this.regions=[],this.dateFormats={},this.timeZoneMap={},this.regionMap={}}get availableRegions(){return this.regions}get defaultUnitSystem(){return String(this.regionSource.props.unitSystemId).toLowerCase()||""}get unitSystemId(){return this.defaultUnitSystem}get timeFormatId(){const t=this.regionSource.props.timeFormatId;if(!t)return"";const e=String(t),s=this.timeFormats[e];return s?String(s.id):""}get selectedTimeFormat(){const t=this.timeFormatId;return t?String(this.timeFormats[t].format):"HH:mm:ss"}get is12HourTimeFormat(){const t=this.timeFormatId;return t?this.timeFormats[t].ampm:!0}get dateFormatId(){const t=this.regionSource.props.dateFormatId;if(!t)return"";const e=String(t);return e?this.dateFormats[e].id:""}get selectedDateFormat(){const t=this.dateFormatId;return t?this.dateFormats[t].format:""}get selectedDateOrder(){const t=this.dateFormatId;return t?this.dateFormats[t].order.toLowerCase():"dmy"}get selectedCountry(){return this.regionSource.props.country||"en"}get selectedTimeZone(){return this.regionSource.props.timeZone||""}get timeZones(){return this.regionId?this.timeZoneMap[this.regionId]||[]:[]}get allTimeZones(){return Intl.supportedValuesOf("timeZone")}get regionId(){return this.region.props.regionId||""}get selectedRegion(){return this.regionMap[this.regionId]}get selectedUnitSystem(){return String(this.regionSource.props.unitSystemId)||""}get timeFormatOptions(){return Object.keys(this.timeFormats).map(t=>({id:t,format:this.timeFormats[t].format,ampm:this.timeFormats[t].ampm}))}get dateFormatOptions(){return Object.keys(this.dateFormats).map(t=>({id:t,format:this.dateFormats[t].format,order:this.dateFormats[t].order}))}get unitSystemOptions(){return Object.keys(this.unitSystems).map(t=>({id:t,name:t}))}setSelectedTimeFormat(t){if(!this.timeFormatOptions.find(e=>e.id===t))throw Error(`Invalid time format id. Must be one of ${this.timeFormatOptions.map(e=>e.id).join(", ")}`);this.regionSource.updateProperty("timeFormatId",t)}setSelectedDateFormat(t){if(!this.dateFormatOptions.find(e=>e.id===t))throw Error(`Invalid date format id. Must be one of ${this.dateFormatOptions.map(e=>e.id).join(", ")}`);this.regionSource.updateProperty("dateFormatId",t)}setSelectedUnitSystem(t){if(!this.unitSystemOptions.find(e=>e.id===t))throw Error(`Invalid date format id. Must be one of ${this.unitSystemOptions.map(e=>e.id).join(", ")}`);this.regionSource.updateProperty("unitSystemId",t)}getUnitSystem(t){if(!t)return this.defaultUnitSystem;const e=t==="drt"?"second":t,s=this.unitSystemMap[e];if(!s)throw Error(`No unit found with name: ${e}. Unit should be one of ${Object.keys(this.unitSystemMap).join(", ")}`);return s[ue.system]}getUnitMeasure(t){const e=t==="drt"?"second":t,s=this.unitSystemMap[e];if(!s)throw Error(`No unit found with name: ${e}. Unit should be one of ${Object.keys(this.unitSystemMap).join(", ")}`);return s[ue.family]}getDefaultUnitDecimalPlaces(t,e,s){if(!t||!e)throw Error("Measure and unit system are required");const r=s==="drt"?"second":s,o=this.measureMap[t];if(!o)throw Error(`No unit systems found for measure: ${t}. Measure should come from list of measures: ${Object.keys(this.measureMap).join(", ")}`);const n=o[e.toLowerCase()];if(!n)throw Error(`No unit system found for measure: ${t} and unit system: ${e}. Unit system should come form list of unit systems: ${Object.keys(o).join(", ")}`);const i=n[r||"default"];if(!i)throw Error(`No unit "${r||"default"}" found for measure: ${t} and unit system: ${e}. Unit should come from list of units: ${Object.keys(n).join(", ")}`);return i[ue.decimals]}getDefaultUnitForMeasure(t,e){if(!t||!e)throw Error("Measure and unit system are required");const s=this.defaultMeasureMap[t];if(!s)throw Error(`No unit systems found for measure: ${t}. Measure should come from list of measures: ${Object.keys(this.measureMap).join(", ")}`);const r=s[e.toLowerCase()];if(!r)throw Error(`No unit system found for measure: ${t} and unit system: ${e}. Unit system should come form list of unit systems: ${Object.keys(s).join(", ")}`);return r}convertByUnit(t,e,s){if(e[ue.family]!==s[ue.family])throw new Error(`Cannot convert between units of different families: ${e[ue.family]} and ${s[ue.family]}`);const r=e[ue.offset],o=e[ue.scale],n=s[ue.scale],i=s[ue.offset],a=s[ue.decimals];return((t-r)/(o/n)+i).toFixed(a)}convertByUnitName(t,e,s){const r=this.unitSystemMap[e],o=this.unitSystemMap[s];if(!r||!o)throw new Error(`No unit found with name: ${e} or ${s}. Unit should be one of ${Object.keys(this.unitSystemMap).join(", ")}`);return this.convertByUnit(t,r,o)}convert(t,e,s){var a,c;if(e.unit&&s.unit)return this.convertByUnitName(t,e.unit,s.unit);const r=e.unit||"",o=s.unit||"";let n=this.unitSystemMap[r],i=this.unitSystemMap[o];if(!i&&s.measure&&s.system){const u=this.measureMap[s.measure];if(!u)throw Error(`Could not find measure ${s.measure}. Measure should be one of ${Object.keys(this.measureMap).join(", ")}`);i=(a=u[s.system])==null?void 0:a.default,i||es.info("Could not find default unit for measure",s.measure)}if(!n&&e.measure&&e.system){const u=this.measureMap[e.measure];if(!u)throw Error(`Could not find measure ${s.measure}. Measure should be one of ${Object.keys(this.measureMap).join(", ")}`);n=(c=u[e.system])==null?void 0:c.default,n||es.info("Could not find default unit for measure",e.measure)}return!n||!i?(es.warn("Could not find unit to convert to or from. Return value as is"),String(t)):this.convertByUnit(t,n,i)}async init(){es.debug("initializing region info")}async load(){es.debug("loading region info");const t=await Vl();t&&(this.regions=t.data.map(s=>s.id),this.timeZoneMap=t.data.reduce((s,r)=>({...s,[r.id]:r.timeZones}),this.timeZoneMap),this.regionMap=t.data.reduce((s,r)=>({...s,[r.id]:r}),{}));const e=await zl();e&&(this.unitSystems=e.data.unitSystems.reduce((s,r)=>{const o={id:r.id,name:r.id};return s[r.id]=o,s},this.unitSystems),this.unitSystemMap=e.data.unitSystems.reduce(ny,{}),this.measureMap=e.data.unitSystems.reduce(iy,{}),this.defaultMeasureMap=e.data.unitSystems.reduce(ay,{}),this.timeFormats=e.data.timeFormats.reduce((s,r)=>({...s,[r.id]:r}),{}),this.dateFormats=e.data.dateFormats.reduce((s,r)=>({...s,[r.id]:r}),{}))}async ready(){var t,e;await((e=(t=this.regionSource).ready)==null?void 0:e.call(t))}};Fn([Jr({path:"kos:service:region:settings"})],Os.prototype,"regionSource",2);Fn([Jr({path:"kos:service:region"})],Os.prototype,"region",2);Os=Fn([R(dr)],Os);const re={registration:{[dr]:{class:Os,singleton:!0}},type:dr,factory:ae.Singleton.create(dr)},vr=({source:t,defaultSystem:e="si",defaultMeasure:s})=>{let r={system:e,measure:s};return typeof t=="string"?r={...r,unit:t}:r={...r,...t},r},Nn=(t,e,s)=>{const{model:r}=$e(re.type);if(!r)throw new Error("RegionInfo model not found");if(!yr(r))throw new Error("RegionInfo model not ready");const o={system:r.defaultUnitSystem},n=vr({source:e}),i=vr({source:s||o,defaultMeasure:r.getUnitMeasure(n.unit||"")});return r.convert(t,n,i)};function Gi(t,e,s){const r=e.toLowerCase().replace(/_/g,"-").replace(/s$/,""),o=new Intl.NumberFormat().resolvedOptions().locale??"en-US";try{const n=(s==null?void 0:s.mode)||"long",i=(s==null?void 0:s.maxDecimals)??2,a=(s==null?void 0:s.minDecimals)??0;return new Intl.NumberFormat(o,{style:"unit",unit:r,unitDisplay:n,minimumFractionDigits:a,maximumFractionDigits:i}).format(t)}catch{return e}}const uy=(t,e,s,r)=>{const o=Nn(t,e,s),n=vr({source:e}),{model:i}=$e(re.type);if(!i)throw new Error("RegionInfo model not found");const a=i.getUnitMeasure(n.unit||""),c={system:i.defaultUnitSystem},u=vr({source:s||c,defaultMeasure:i.getUnitMeasure(n.unit||"")}),d=i.getDefaultUnitForMeasure(a,u.system),h=i.getDefaultUnitDecimalPlaces(a,u.system),f={...r,minDecimals:(r==null?void 0:r.minDecimals)??h,maxDecimals:(r==null?void 0:r.maxDecimals)??h};return{value:o,unit:d||n.unit||"",display:Gi(o,d||n.unit||"",{...f,mode:"long"}),shortDisplay:Gi(o,d||n.unit||"",{...f,mode:"short"})}};function Yi({start:t,end:e,count:s,decimals:r=0}){if(typeof t!="number"||typeof e!="number"||typeof s!="number")throw new Error("All input values should be numbers.");if(s<2)throw new Error("Count should be at least 2 for distribution.");if(t>=e)throw new Error("Start should be less than end.");const o=(e-t)/(s-1),n=[];for(let i=0;i<s;i++){const a=Math.round(t+i*o);n.push(a.toFixed(r))}return n}function Wi({start:t,end:e,interval:s,decimals:r=0}){if(typeof t!="number"||typeof e!="number"||typeof s!="number")throw new Error("All input values should be numbers.");if(s<=0)throw new Error("Interval should be a positive number.");if(t>=e)throw new Error("Start should be less than end.");const o=[];let n=t;for(;n<=e;)o.push(n.toFixed(r)),n+=s;return o[o.length-1]!==e.toString()&&o.push(e.toString()),o}const wt=(t,e)=>s=>!t||!e?s:Xr(s)?Nn(Number(s),t,e):s,dy=(t,e,s,r)=>{if((t==null?void 0:t.type)==="enum"||!(t!=null&&t.options))return[];if(t.options.type==="rangeCount")return Yi(t.options).map(wt(s,r));if(t.options.type==="rangeInterval")return Wi(t.options).map(wt(s,r));if(t.options.type==="list"){const{list:o}=t.options;return o.map(wt(s,r))}else{if(t.options.type==="unitSystemRangeCount"&&e)return Yi(t.options.unitSystems[e]).map(wt(s,r));if(t.options.type==="unitSystemRangeInterval"&&e)return Wi(t.options.unitSystems[e]).map(wt(s,r));if(t.options.type==="unitSystemList"&&e){const{list:o}=t.options.unitSystems[e];return o.map(wt(s,r))}}return[]},hy=(t,e)=>{if(!((t==null?void 0:t.type)==="enum"||!(t!=null&&t.options)))return t.options.type==="unitSystemRangeCount"&&e?{type:"rangeCount",...t.options.unitSystems[e]}:t.options.type==="unitSystemRangeInterval"&&e?{type:"rangeInterval",...t.options.unitSystems[e]}:t.options.type==="unitSystemList"&&e?{type:"list",...t.options.unitSystems[e]}:t.options.type==="unitSystemKeypad"&&e?{type:"keypad",...t.options.unitSystems[e]}:t.options};var fy=Object.defineProperty,py=Object.getOwnPropertyDescriptor,Un=(t,e,s,r)=>{for(var o=r>1?void 0:r?py(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&fy(e,s,o),o};function gy(t){return(t==null?void 0:t.type)==="enum"}function my(t){switch(t){case"s":return"second";case"ms":return"millisecond";case"min":return"minute";case"h":return"hour";case"d":return"day";case"w":return"week";case"m":return"month";case"y":return"year";case"ml":return"milliliter";default:return t}}function yy(t,e){const s=new Date;s.setHours(0,0,0,0);const r=new Date(s.getTime()+t*1e3);return ze.format(r,e)}const hr="config-bean-prop-model",Et=m.createLogger({name:"config-bean-prop-model"}),by=ht("path"),vy=ht("serviceBasePath");let $s=class{constructor(t,e){l(this,"id");l(this,"path");l(this,"attribute");l(this,"converter");l(this,"formatter");l(this,"optionsExpander");l(this,"serviceBasePath");l(this,"regionInfo");l(this,"bean");this.id=t,this.path=e.path,this.attribute=e.attribute,this.converter=e.converter,this.formatter=e.formatter,this.serviceBasePath=e.serviceBasePath,this.optionsExpander=e.optionsExpander}getDefaultUnitDecimalPlaces(t,e,s){if(!t)throw new Error("measure is required");if(!e)throw new Error("unitSystem is required");return kl(this.displayOptions)?this.displayOptions.decimals:this.regionInfo.getDefaultUnitDecimalPlaces(t,e,s)}getDefaultUnitForMeasure(t,e){if(!t)throw new Error("measure is required");if(!e)throw new Error("unitSystem is required");return this.regionInfo.getDefaultUnitForMeasure(t,e)}get schemaType(){const t=this.bean.getSchemaForProperty(this.attribute);return t!=null&&t.type?t.type:"String"}get schemaFormat(){const t=this.bean.getSchemaForProperty(this.attribute);return t!=null&&t.format?my(t.format):""}get options(){var i;const t=this.regionInfo.defaultUnitSystem,e=this.getConverter(),s=((i=e==null?void 0:e.to)==null?void 0:i.system)??t,r=this.bean.getSchemaForProperty(this.attribute),o=gy(r)?r.values:dy(r,s,e==null?void 0:e.from,e==null?void 0:e.to),n=o.length>0?o.map(a=>({label:a,value:a})):[];return this.optionsExpander?typeof this.optionsExpander=="function"?this.optionsExpander(s,o):this.optionsExpander:n}convertUnit(t,e,s){const r=(t==null?void 0:t.measure)||s,o=(t==null?void 0:t.system)||e,n=t==null?void 0:t.unit;return{measure:r,system:o,unit:n}}getConverterUnits(){const t=this.regionInfo.defaultUnitSystem,e=this.getConverter();if(!e)throw Error("No converter defined");const s=e.measure,r=this.convertUnit(e.from,"si",s),o=this.convertUnit(e.to,t,s);return{backend:r,display:o}}set value(t){this.updateProperty(t)}get value(){return this.getValue(!0)}get rawValue(){return this.bean.props[this.attribute]}get significantValue(){var o,n;const t=this.value,e=this.regionInfo.defaultUnitSystem,s=this.getConverter(),r=(s==null?void 0:s.measure)||((o=s==null?void 0:s.to)==null?void 0:o.measure);if(!isNaN(t)&&s&&r){const i=this.getDefaultUnitDecimalPlaces(r,e,(n=s==null?void 0:s.to)==null?void 0:n.unit);try{const c=this.getFormatterOptions(s);if(c){let u=String(t);return u=c.formatToParts(Number(t))[0].value,Number(u)}}catch(c){Et.info(`error formatting value ${t}`,c)}return Number(t).toFixed(i)}return t}get previousValue(){return this.getValue(!1)}getValue(t){const e=this.bean[t?"props":"prevProps"][this.attribute];if(typeof e=="boolean")return e;if(this.getConverter()&&!isNaN(e)){const{backend:r,display:o}=this.getConverterUnits();return this.regionInfo.convert(Number(e),r,o)}return e||""}async activate(){Et.debug(`activating config bean ${this.id}`)}get displayValue(){const t=this.value;if(typeof t=="boolean")return String(t);if(this.schemaFormat==="drt"){const s=this.regionInfo.is12HourTimeFormat?"h:mm:ss a":"HH:mm:ss";return yy(t,s)}if(!isNaN(t))try{const e=this.getConverter(),s=this.getFormatterOptions(e);if(s){let r=String(t);return r=s.format(Number(t)),r}}catch(e){Et.error(`error formatting value ${t}`,e)}return String(t)}get unit(){const t=this.getConverter();if(!isNaN(this.value)){const e=this.getFormatterOptions(t);if(e){const r=e.formatToParts(Number(this.value)).find(o=>o.type==="unit");return(r==null?void 0:r.value)??this.getDefaultUnit(t)}}return this.getDefaultUnit(t)}get displayOptions(){var o;const t=this.bean.getSchemaForProperty(this.attribute),e=this.regionInfo.defaultUnitSystem,s=this.getConverter(),r=((o=s==null?void 0:s.to)==null?void 0:o.system)??e;return hy(t,r)}getMeasureFromFormat(){const t=this.schemaFormat;return t?this.regionInfo.getUnitMeasure(t):""}getConverterFromFormat(){const t=this.getMeasureFromFormat();if(t){const e=this.regionInfo.selectedUnitSystem;return{unit:this.schemaFormat||this.regionInfo.getDefaultUnitForMeasure(t,e),measure:t}}return{}}getDefaultUnit(t){var r,o;const e=this.regionInfo.defaultUnitSystem,s=t==null?void 0:t.measure;return s?((r=t==null?void 0:t.to)==null?void 0:r.unit)||this.getDefaultUnitForMeasure(s,((o=t==null?void 0:t.to)==null?void 0:o.system)||e):this.getConverterFromFormat().unit}getFormatterOptions(t){var n,i,a;const e=this.regionInfo.defaultUnitSystem,s=t==null?void 0:t.measure,r=new Intl.NumberFormat().resolvedOptions().locale;let o=null;if(s||this.formatter){const c=s?{style:"unit",unit:this.getDefaultUnit(t)}:null,u=this.formatter||c;if(u){let d=typeof u=="function"?u(((n=t==null?void 0:t.to)==null?void 0:n.system)||e):u;s&&(d={unit:this.getDefaultUnit(t),...d},d.style==="unit"&&(d.maximumFractionDigits=d.maximumFractionDigits??this.getDefaultUnitDecimalPlaces(s,((i=t==null?void 0:t.to)==null?void 0:i.system)||e,(a=t==null?void 0:t.to)==null?void 0:a.unit)));try{o=new Intl.NumberFormat(r,{...d})}catch(h){Et.error(`error creating formatter ${d}. Returning the raw value`,h)}}else Et.debug(`no formatter found for config bean prop ${this.id}. Returning the raw value`)}return o}getConverter(){var r,o,n,i,a,c,u,d,h,f,p;const{unit:t,measure:e}=this.getConverterFromFormat(),s=t==="drt"?"second":t;if(this.converter){const y=(r=this.converter)==null?void 0:r.measure,w=(n=(o=this.converter)==null?void 0:o.to)==null?void 0:n.measure,E=(a=(i=this.converter)==null?void 0:i.from)==null?void 0:a.measure,_=y||w||E||e,k=((u=(c=this.converter)==null?void 0:c.to)==null?void 0:u.unit)||this.regionInfo.getDefaultUnitForMeasure(_,((h=(d=this.converter)==null?void 0:d.to)==null?void 0:h.system)??this.regionInfo.defaultUnitSystem),U=((p=(f=this.converter)==null?void 0:f.to)==null?void 0:p.system)??this.regionInfo.getUnitSystem(k),O=this.schemaFormat==="drt"?"second":this.schemaFormat||s;return{...this.converter,from:{unit:O,...this.converter.from},to:{...this.converter.to,unit:k,system:U},measure:_}}if(s&&e){const y=this.regionInfo.getDefaultUnitForMeasure(e,this.regionInfo.defaultUnitSystem),w=this.regionInfo.getUnitSystem(s),E=this.regionInfo.getUnitSystem(y);return{measure:e,to:{unit:w===E?s:y}}}}async updateProperty(t){Et.debug(`updating property ${this.attribute} with value ${t}`);let e=t;if(this.getConverter()&&!isNaN(e)){const{backend:o,display:n}=this.getConverterUnits();e=this.regionInfo.convert(Number(e),n,o)}const r=Array.isArray(e)?JSON.stringify(e):String(e);await this.bean.updateProperty(this.attribute,r)}};Un([qt({modelType:re.type})],$s.prototype,"regionInfo",2);Un([Jr({path:by,serviceBasePath:vy})],$s.prototype,"bean",2);$s=Un([R(hr)],$s);const pt={registration:{[hr]:{class:$s,singleton:!1}},type:hr,factory:ae.Factory.create(hr)};function wy(t){const{path:e,attribute:s,converter:r,formatter:o,lazy:n,optionsExpander:i,serviceBasePath:a}=t,c=r;return c&&(typeof c!="function"&&typeof c.from=="string"&&(c.from={unit:c.from}),typeof c!="function"&&typeof c.to=="string"&&(c.to={unit:c.to})),(u,d)=>{u[F]=u[F]||{},u[F][d]={modelType:pt.type,id:`${e}-${s}`,options:{path:e,attribute:s,serviceBasePath:a,converter:c,formatter:o,optionsExpander:i},lifecycle:x.INIT,lazy:n}}}const Yl="future-model",Gt=zt(Yl),eo=m.createLogger({name:"future-service",group:"Services"}),{isMock:Ey,URL:qs}=ce();var We=(t=>(t.Success="SUCCESS",t.Fail="FAIL",t.Aborted="ABORT",t.Canceled="CANCEL",t))(We||{});const{getAll:My,modifyModel:Ty,addModel:_y,deleteModel:Sy,postModel:Iy}=oe.build({destinationAddress:"",basePath:`${qs}/api/future`,mock:Ey}),Oy=async()=>await My({}),Wl=async(t,e="/api/kos/future")=>(eo.info(`sending delete request for Future: ${t}`),await Sy({id:t,urlOverride:`${qs}${e}/${t}`})),Ql=async(t,e="/api/kos/future")=>(eo.info("sending add request for Future"),await _y({model:t,urlOverride:`${qs}${e}`})),$y=async(t,e,s="/api/kos/future")=>(eo.info(`sending modify request for Future: ${t}`),Ty({model:e,id:t,urlOverride:`${qs}${s}/${t}`})),Zl=async(t,e="/api/kos/future")=>(eo.info(`sending cancel request for Future: ${t}`),Iy({urlOverride:`${qs}${e}/${t}/cancel`,ordered:!0,model:{}})),jn=t=>({id:String(t.id),progress:t.progress,remainingTimeMs:t.remainingTimeMs,endState:t.endState,reason:t.reason,clientData:t.clientData,reasonData:t.reasonData,note:t.note,tracker:t.tracker}),Bn=(t,e)=>{m.debug(`future dto ${t.id} end state ${t.endState}`),m.debug(`future model ${e.id} end state ${e.endState}`),e.endState?m.debug(`future model ${e.id} is already complete`):(m.debug(`updating future model ${e.id}`),M.runInAction(()=>{const s=jn(t);J(()=>{Object.keys(s).forEach(r=>{r==="id"?(e.futureId=s.id,s.tracker||(e.id=s.id)):r==="tracker"?e.id=s.tracker:e[r]=s[r]})})}))},Xl=t=>e=>s=>t.build(String(e),s),Hn=t=>e=>Il(jn,Xl(t)(e.tracker||e.id))(e);var Cy=Object.defineProperty,Dy=Object.getOwnPropertyDescriptor,Jl=(t,e,s,r)=>{for(var o=r>1?void 0:r?Dy(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Cy(e,s,o),o};const So=m.getLogger(Gt.type);let wr=class{constructor(t,e,s){l(this,"logger");l(this,"_cancelFuture");l(this,"futureId");Object.assign(this,e),this.logger=s.logger,this.id=t,this.futureId=e.id,this.namespace=e.namespace||"kos",this._cancelFuture=Zl,jo(()=>this.status===We.Success||this.status===We.Fail,()=>{So.info(`Future ${this.id} has completed with status ${this.status}`),Ie(this)})}async load(){So.debug(`loading Future ${this.id}`)}unload(){So.info(`unloading Future ${this.id}`)}async cancelFuture(){const t=this.namespace==="studio"?"/api/future":`/api/${this.namespace}/future`;await jo(()=>this.futureId!==Rn),await this._cancelFuture(this.futureId,t)}get status(){return this.endState?this.endState:this.progress>-1?"IN_PROGRESS":"NOT_ACTIVE"}get timeRemaining(){var a,c;const t=this.remainingTimeMs||-1;if(t<0)return"";const e={year:1e3*60*60*24*365,month:1e3*60*60*24*30,day:1e3*60*60*24,hour:1e3*60*60,minute:1e3*60,second:1e3};let s="second",r=0;for(const[u,d]of Object.entries(e))if(Math.abs(t)>=d){s=u,r=Math.round(t/d);break}const n=new Intl.RelativeTimeFormat("en",{numeric:"auto"}).formatToParts(r,s);return n.length===3?`${((a=n[1])==null?void 0:a.value)??0} ${((c=n[2])==null?void 0:c.value)??""}`:"0 seconds"}handleFutureUpdated(t){this.logger.debug(`Future ${this.id} updated. future: ${t.id} endState: ${t.endState} progress: ${t.progress} remainingTimeMs: ${t.remainingTimeMs}`),Bn(t,this)}};Jl([H({topic:`kos.future/${pr}`})],wr.prototype,"handleFutureUpdated",1);wr=Jl([R(Gt.type)],wr);const eu=wr,tu=Be();var xy=Object.defineProperty,Ay=Object.getOwnPropertyDescriptor,su=(t,e,s,r)=>{for(var o=r>1?void 0:r?Ay(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&xy(e,s,o),o};const ru="browser-router-model",Ry="kos.http.request",Py="kos.http.response";let Er=class{constructor(t,e,s){l(this,"_id");l(this,"logger");l(this,"router");this._id=t,this.logger=s.logger,this.router=new Dl}get id(){return this._id}async handleRequest(t,e){const s=e.headers["src-addr"],r=e.headers["dst-addr"],o=e.headers.url,n=e.headers.method,i=e.headers["request-id"],a={id:i,method:n,path:o,body:t};let c=200;const u={send:d=>{this.logger.debug(`sending response to ${r}`),this.logger.debug(d),vl({msg:d,options:{responseId:i,destinationAddress:s,type:Py,sourceAddress:r,status:c}})},status:function(d){return c=d,this}};if(a.path==="/openapi.json"){u.send(this.router.generateOpenApiSpec());return}await this.router.handle(a,u)}use(t,e,...s){this.router.use(t,e,...s)}remove(t,e){return this.router.remove(t,e)}removeAllForPath(t){return this.router.removeAllForPath(t)}getRoutes(){return this.router.getRoutes()}async init(){this.logger.debug(`initializing browser-router ${this.id}`)}async load(){this.logger.debug(`loading browser-router ${this.id}`)}};su([H({topic:Ry})],Er.prototype,"handleRequest",1);Er=su([R(ru)],Er);const Kn=new Se({class:Er,type:ru}),ou="future-container-model",Qe=zt(ou),nu=t=>Hn(Gt)(t),ky=t=>{const e=nu(t);return Qe.build(Qe.type,{}).addFutureModel(e),e},Ly=t=>Qe.build(Qe.type,{}).getFuture(String(t)),lt={buildFutureModel:nu,initiateFuture:ky,getFuture:Ly};var Fy=Object.defineProperty,Ny=Object.getOwnPropertyDescriptor,qn=(t,e,s,r)=>{for(var o=r>1?void 0:r?Ny(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Fy(e,s,o),o};const sr=m.getLogger(Qe.type);let Cs=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_deleteFuture");l(this,"_addFuture");l(this,"_futures");l(this,"createModel");l(this,"deleteModel");const{deleteFuture:r=Wl,addFuture:o=Ql}=e;this.logger=s.logger,this._deleteFuture=r,this._addFuture=o,this.id=t,this._futures=new xe,this.createModel=this.createFuture,this.deleteModel=this.removeFuture}get futures(){return this._futures.data}get models(){return this.futures}getFuture(t){return this._futures.getModel(t)}addFutureModel(t){this._futures.addModel(t)}removeFutureModel(t){this._futures.removeModel(t)}async removeFuture(t){try{await this._deleteFuture(t)}catch(e){sr.error("error deleting a Future"),sr.error(e)}}async createFuture(t){try{const e=await this._addFuture(t),s=e==null?void 0:e.data;if(s){const r=Hn(Gt)(s);return this.addFutureModel(r),r}}catch(e){throw sr.error("error creating a Future"),sr.error(e),e}}handleFutureUpdated(t,e){const s=lt.buildFutureModel(t);this.addFutureModel(s);const r=`kos.future/${t.tracker||t.id}`;this.logger.debug(`publishing future update to ${r}`),V(r,e.body,e.headers)}};qn([De],Cs.prototype,"_futures",2);qn([H({topic:"kos.future"})],Cs.prototype,"handleFutureUpdated",1);Cs=qn([R(Qe.type)],Cs);const iu=Cs,{URL:zs}=ce(),{getOne:Uy,postModel:jy,deleteModel:au}=oe.build({basePath:`${zs}/api/keyVal`}),Bo=m.createLogger({name:"key-value-service",group:"Services"}),cu=async(t,e)=>{await au({urlOverride:`${zs}/api/keyVal/${t}/${e}`,id:e})},lu=async(t,e,s)=>{const r=await jy({urlOverride:`${zs}/api/keyVal/${t}/${e}`,model:s.toString()});if((r==null?void 0:r.status)!==200)throw Bo.error("Failed to update key-value data",r),new Error(`Failed to update key-value data for namespace ${t}`);return r.data},uu=async(t="studio")=>{Bo.debug(`Retrieving all key-value data for namespace: ${t}`);const e=await Uy({urlOverride:`${zs}/api/keyVal/${t}`});if((e==null?void 0:e.status)!==200)throw Bo.error("Failed to retrieve key-value data",e),new Error(`Failed to retrieve key-value data for namespace ${t}`);return e.data},By=async t=>{await au({urlOverride:`${zs}/api/keyVal/${t}`,id:""})},Hy=Object.freeze(Object.defineProperty({__proto__:null,deleteKeyValue:cu,deleteKeyValueNamespace:By,getKeyValue:uu,updateKeyValue:lu},Symbol.toStringTag,{value:"Module"}));var Ky=Object.defineProperty,qy=Object.getOwnPropertyDescriptor,zn=(t,e,s,r)=>{for(var o=r>1?void 0:r?qy(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Ky(e,s,o),o};const du="key-value-model";let Ds=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"namespace");l(this,"data");this.id=t,this.logger=s.logger,this.data=Oe(),this.namespace=e.namespace||"studio"}async init(){this.logger.debug(`initializing studio-state ${this.id}`)}async updateState(t,e){this.logger.debug(`updating studio-state ${t} with value ${e}`),e!==void 0?(await lu(this.namespace,t,e),this.data[t]=e):(await cu(this.namespace,t),this.data[t]=void 0)}async load(){this.logger.debug(`loading studio-state ${this.id}`);const t=await uu(this.namespace);this.data.setValues(t)}handleStateUpdate(t){t.namespace===this.namespace&&(this.data[t.key]=t.value)}handleStateDelete(t){t.namespace===this.namespace&&(this.data[t.key]=void 0)}};zn([H({topic:"/keyVal/set"})],Ds.prototype,"handleStateUpdate",1);zn([H({topic:"/keyVal/remove"})],Ds.prototype,"handleStateDelete",1);Ds=zn([R(du)],Ds);const Vn=new be({class:Ds,type:du});var pe="INUMBER",Yt="IOP1",Wt="IOP2",Qt="IOP3",Le="IVAR",ut="IVARNAME",At="IFUNCALL",to="IFUNDEF",ie="IEXPR",Gn="IEXPREVAL",gt="IMEMBER",so="IENDSTATEMENT",Rt="IARRAY";function P(t,e){this.type=t,this.value=e??0}P.prototype.toString=function(){switch(this.type){case pe:case Yt:case Wt:case Qt:case Le:case ut:case so:return this.value;case At:return"CALL "+this.value;case to:return"DEF "+this.value;case Rt:return"ARRAY "+this.value;case gt:return"."+this.value;default:return"Invalid Instruction"}};function ro(t){return new P(Yt,t)}function He(t){return new P(Wt,t)}function hu(t){return new P(Qt,t)}function Ho(t,e,s,r,o){for(var n=[],i=[],a,c,u,d,h=0;h<t.length;h++){var f=t[h],p=f.type;if(p===pe||p===ut)Array.isArray(f.value)?n.push.apply(n,Ho(f.value.map(function(y){return new P(pe,y)}).concat(new P(Rt,f.value.length)),e,s,r,o)):n.push(f);else if(p===Le&&o.hasOwnProperty(f.value))f=new P(pe,o[f.value]),n.push(f);else if(p===Wt&&n.length>1)c=n.pop(),a=n.pop(),d=s[f.value],f=new P(pe,d(a.value,c.value)),n.push(f);else if(p===Qt&&n.length>2)u=n.pop(),c=n.pop(),a=n.pop(),f.value==="?"?n.push(a.value?c.value:u.value):(d=r[f.value],f=new P(pe,d(a.value,c.value,u.value)),n.push(f));else if(p===Yt&&n.length>0)a=n.pop(),d=e[f.value],f=new P(pe,d(a.value)),n.push(f);else if(p===ie){for(;n.length>0;)i.push(n.shift());i.push(new P(ie,Ho(f.value,e,s,r,o)))}else if(p===gt&&n.length>0)a=n.pop(),n.push(new P(pe,a.value[f.value]));else{for(;n.length>0;)i.push(n.shift());i.push(f)}}for(;n.length>0;)i.push(n.shift());return i}function fu(t,e,s){for(var r=[],o=0;o<t.length;o++){var n=t[o],i=n.type;if(i===Le&&n.value===e)for(var a=0;a<s.tokens.length;a++){var c=s.tokens[a],u;c.type===Yt?u=ro(c.value):c.type===Wt?u=He(c.value):c.type===Qt?u=hu(c.value):u=new P(c.type,c.value),r.push(u)}else i===ie?r.push(new P(ie,fu(n.value,e,s))):r.push(n)}return r}function ot(t,e,s){var r=[],o,n,i,a,c,u;if(Yn(t))return Re(t,s);for(var d=t.length,h=0;h<d;h++){var f=t[h],p=f.type;if(p===pe||p===ut)r.push(f.value);else if(p===Wt)n=r.pop(),o=r.pop(),f.value==="and"?r.push(o?!!ot(n,e,s):!1):f.value==="or"?r.push(o?!0:!!ot(n,e,s)):f.value==="="?(a=e.binaryOps[f.value],r.push(a(o,ot(n,e,s),s))):(a=e.binaryOps[f.value],r.push(a(Re(o,s),Re(n,s))));else if(p===Qt)i=r.pop(),n=r.pop(),o=r.pop(),f.value==="?"?r.push(ot(o?n:i,e,s)):(a=e.ternaryOps[f.value],r.push(a(Re(o,s),Re(n,s),Re(i,s))));else if(p===Le)if(f.value in e.functions)r.push(e.functions[f.value]);else if(f.value in e.unaryOps&&e.parser.isOperatorEnabled(f.value))r.push(e.unaryOps[f.value]);else{var y=s[f.value];if(y!==void 0)r.push(y);else throw new Error("undefined variable: "+f.value)}else if(p===Yt)o=r.pop(),a=e.unaryOps[f.value],r.push(a(Re(o,s)));else if(p===At){for(u=f.value,c=[];u-- >0;)c.unshift(Re(r.pop(),s));if(a=r.pop(),a.apply&&a.call)r.push(a.apply(void 0,c));else throw new Error(a+" is not a function")}else if(p===to)r.push(function(){for(var w=r.pop(),E=[],_=f.value;_-- >0;)E.unshift(r.pop());var k=r.pop(),U=function(){for(var O=Object.assign({},s),S=0,z=E.length;S<z;S++)O[E[S]]=arguments[S];return ot(w,e,O)};return Object.defineProperty(U,"name",{value:k,writable:!1}),s[k]=U,U}());else if(p===ie)r.push(zy(f,e));else if(p===Gn)r.push(f);else if(p===gt)o=r.pop(),r.push(o[f.value]);else if(p===so)r.pop();else if(p===Rt){for(u=f.value,c=[];u-- >0;)c.unshift(r.pop());r.push(c)}else throw new Error("invalid Expression")}if(r.length>1)throw new Error("invalid Expression (parity)");return r[0]===0?0:Re(r[0],s)}function zy(t,e,s){return Yn(t)?t:{type:Gn,value:function(r){return ot(t.value,e,r)}}}function Yn(t){return t&&t.type===Gn}function Re(t,e){return Yn(t)?t.value(e):t}function Wn(t,e){for(var s=[],r,o,n,i,a,c,u=0;u<t.length;u++){var d=t[u],h=d.type;if(h===pe)typeof d.value=="number"&&d.value<0?s.push("("+d.value+")"):Array.isArray(d.value)?s.push("["+d.value.map(Qi).join(", ")+"]"):s.push(Qi(d.value));else if(h===Wt)o=s.pop(),r=s.pop(),i=d.value,e?i==="^"?s.push("Math.pow("+r+", "+o+")"):i==="and"?s.push("(!!"+r+" && !!"+o+")"):i==="or"?s.push("(!!"+r+" || !!"+o+")"):i==="||"?s.push("(function(a,b){ return Array.isArray(a) && Array.isArray(b) ? a.concat(b) : String(a) + String(b); }(("+r+"),("+o+")))"):i==="=="?s.push("("+r+" === "+o+")"):i==="!="?s.push("("+r+" !== "+o+")"):i==="["?s.push(r+"[("+o+") | 0]"):s.push("("+r+" "+i+" "+o+")"):i==="["?s.push(r+"["+o+"]"):s.push("("+r+" "+i+" "+o+")");else if(h===Qt)if(n=s.pop(),o=s.pop(),r=s.pop(),i=d.value,i==="?")s.push("("+r+" ? "+o+" : "+n+")");else throw new Error("invalid Expression");else if(h===Le||h===ut)s.push(d.value);else if(h===Yt)r=s.pop(),i=d.value,i==="-"||i==="+"?s.push("("+i+r+")"):e?i==="not"?s.push("(!"+r+")"):i==="!"?s.push("fac("+r+")"):s.push(i+"("+r+")"):i==="!"?s.push("("+r+"!)"):s.push("("+i+" "+r+")");else if(h===At){for(c=d.value,a=[];c-- >0;)a.unshift(s.pop());i=s.pop(),s.push(i+"("+a.join(", ")+")")}else if(h===to){for(o=s.pop(),c=d.value,a=[];c-- >0;)a.unshift(s.pop());r=s.pop(),e?s.push("("+r+" = function("+a.join(", ")+") { return "+o+" })"):s.push("("+r+"("+a.join(", ")+") = "+o+")")}else if(h===gt)r=s.pop(),s.push(r+"."+d.value);else if(h===Rt){for(c=d.value,a=[];c-- >0;)a.unshift(s.pop());s.push("["+a.join(", ")+"]")}else if(h===ie)s.push("("+Wn(d.value,e)+")");else if(h!==so)throw new Error("invalid Expression")}return s.length>1&&(e?s=[s.join(",")]:s=[s.join(";")]),String(s[0])}function Qi(t){return typeof t=="string"?JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029"):t}function It(t,e){for(var s=0;s<t.length;s++)if(t[s]===e)return!0;return!1}function Qn(t,e,s){s=s||{};for(var r=!!s.withMembers,o=null,n=0;n<t.length;n++){var i=t[n];i.type===Le||i.type===ut?!r&&!It(e,i.value)?e.push(i.value):(o!==null&&(It(e,o)||e.push(o)),o=i.value):i.type===gt&&r&&o!==null?o+="."+i.value:i.type===ie?Qn(i.value,e,s):o!==null&&(It(e,o)||e.push(o),o=null)}o!==null&&!It(e,o)&&e.push(o)}function Ee(t,e){this.tokens=t,this.parser=e,this.unaryOps=e.unaryOps,this.binaryOps=e.binaryOps,this.ternaryOps=e.ternaryOps,this.functions=e.functions}Ee.prototype.simplify=function(t){return t=t||{},new Ee(Ho(this.tokens,this.unaryOps,this.binaryOps,this.ternaryOps,t),this.parser)};Ee.prototype.substitute=function(t,e){return e instanceof Ee||(e=this.parser.parse(String(e))),new Ee(fu(this.tokens,t,e),this.parser)};Ee.prototype.evaluate=function(t){return t=t||{},ot(this.tokens,this,t)};Ee.prototype.toString=function(){return Wn(this.tokens,!1)};Ee.prototype.symbols=function(t){t=t||{};var e=[];return Qn(this.tokens,e,t),e};Ee.prototype.variables=function(t){t=t||{};var e=[];Qn(this.tokens,e,t);var s=this.functions;return e.filter(function(r){return!(r in s)})};Ee.prototype.toJSFunction=function(t,e){var s=this,r=new Function(t,"with(this.functions) with (this.ternaryOps) with (this.binaryOps) with (this.unaryOps) { return "+Wn(this.simplify(e).tokens,!0)+"; }");return function(){return r.apply(s,arguments)}};var xs="TEOF",B="TOP",oo="TNUMBER",pu="TSTRING",Fe="TPAREN",Pt="TBRACKET",no="TCOMMA",Zn="TNAME",Xn="TSEMICOLON";function gu(t,e,s){this.type=t,this.value=e,this.index=s}gu.prototype.toString=function(){return this.type+": "+this.value};function G(t,e){this.pos=0,this.current=null,this.unaryOps=t.unaryOps,this.binaryOps=t.binaryOps,this.ternaryOps=t.ternaryOps,this.consts=t.consts,this.expression=e,this.savedPosition=0,this.savedCurrent=null,this.options=t.options,this.parser=t}G.prototype.newToken=function(t,e,s){return new gu(t,e,s??this.pos)};G.prototype.save=function(){this.savedPosition=this.pos,this.savedCurrent=this.current};G.prototype.restore=function(){this.pos=this.savedPosition,this.current=this.savedCurrent};G.prototype.next=function(){if(this.pos>=this.expression.length)return this.newToken(xs,"EOF");if(this.isWhitespace()||this.isComment())return this.next();if(this.isRadixInteger()||this.isNumber()||this.isOperator()||this.isString()||this.isParen()||this.isBracket()||this.isComma()||this.isSemicolon()||this.isNamedOp()||this.isConst()||this.isName())return this.current;this.parseError('Unknown character "'+this.expression.charAt(this.pos)+'"')};G.prototype.isString=function(){var t=!1,e=this.pos,s=this.expression.charAt(e);if(s==="'"||s==='"')for(var r=this.expression.indexOf(s,e+1);r>=0&&this.pos<this.expression.length;){if(this.pos=r+1,this.expression.charAt(r-1)!=="\\"){var o=this.expression.substring(e+1,r);this.current=this.newToken(pu,this.unescape(o),e),t=!0;break}r=this.expression.indexOf(s,r+1)}return t};G.prototype.isParen=function(){var t=this.expression.charAt(this.pos);return t==="("||t===")"?(this.current=this.newToken(Fe,t),this.pos++,!0):!1};G.prototype.isBracket=function(){var t=this.expression.charAt(this.pos);return(t==="["||t==="]")&&this.isOperatorEnabled("[")?(this.current=this.newToken(Pt,t),this.pos++,!0):!1};G.prototype.isComma=function(){var t=this.expression.charAt(this.pos);return t===","?(this.current=this.newToken(no,","),this.pos++,!0):!1};G.prototype.isSemicolon=function(){var t=this.expression.charAt(this.pos);return t===";"?(this.current=this.newToken(Xn,";"),this.pos++,!0):!1};G.prototype.isConst=function(){for(var t=this.pos,e=t;e<this.expression.length;e++){var s=this.expression.charAt(e);if(s.toUpperCase()===s.toLowerCase()&&(e===this.pos||s!=="_"&&s!=="."&&(s<"0"||s>"9")))break}if(e>t){var r=this.expression.substring(t,e);if(r in this.consts)return this.current=this.newToken(oo,this.consts[r]),this.pos+=r.length,!0}return!1};G.prototype.isNamedOp=function(){for(var t=this.pos,e=t;e<this.expression.length;e++){var s=this.expression.charAt(e);if(s.toUpperCase()===s.toLowerCase()&&(e===this.pos||s!=="_"&&(s<"0"||s>"9")))break}if(e>t){var r=this.expression.substring(t,e);if(this.isOperatorEnabled(r)&&(r in this.binaryOps||r in this.unaryOps||r in this.ternaryOps))return this.current=this.newToken(B,r),this.pos+=r.length,!0}return!1};G.prototype.isName=function(){for(var t=this.pos,e=t,s=!1;e<this.expression.length;e++){var r=this.expression.charAt(e);if(r.toUpperCase()===r.toLowerCase()){if(e===this.pos&&(r==="$"||r==="_")){r==="_"&&(s=!0);continue}else if(e===this.pos||!s||r!=="_"&&(r<"0"||r>"9"))break}else s=!0}if(s){var o=this.expression.substring(t,e);return this.current=this.newToken(Zn,o),this.pos+=o.length,!0}return!1};G.prototype.isWhitespace=function(){for(var t=!1,e=this.expression.charAt(this.pos);(e===" "||e===" "||e===`
108
108
  `||e==="\r")&&(t=!0,this.pos++,!(this.pos>=this.expression.length));)e=this.expression.charAt(this.pos);return t};var Vy=/^[0-9a-f]{4}$/i;G.prototype.unescape=function(t){var e=t.indexOf("\\");if(e<0)return t;for(var s=t.substring(0,e);e>=0;){var r=t.charAt(++e);switch(r){case"'":s+="'";break;case'"':s+='"';break;case"\\":s+="\\";break;case"/":s+="/";break;case"b":s+="\b";break;case"f":s+="\f";break;case"n":s+=`
109
109
  `;break;case"r":s+="\r";break;case"t":s+=" ";break;case"u":var o=t.substring(e+1,e+5);Vy.test(o)||this.parseError("Illegal escape sequence: \\u"+o),s+=String.fromCharCode(parseInt(o,16)),e+=4;break;default:throw this.parseError('Illegal escape sequence: "\\'+r+'"')}++e;var n=t.indexOf("\\",e);s+=t.substring(e,n<0?t.length:n),e=n}return s};G.prototype.isComment=function(){var t=this.expression.charAt(this.pos);return t==="/"&&this.expression.charAt(this.pos+1)==="*"?(this.pos=this.expression.indexOf("*/",this.pos)+2,this.pos===1&&(this.pos=this.expression.length),!0):!1};G.prototype.isRadixInteger=function(){var t=this.pos;if(t>=this.expression.length-2||this.expression.charAt(t)!=="0")return!1;++t;var e,s;if(this.expression.charAt(t)==="x")e=16,s=/^[0-9a-f]$/i,++t;else if(this.expression.charAt(t)==="b")e=2,s=/^[01]$/i,++t;else return!1;for(var r=!1,o=t;t<this.expression.length;){var n=this.expression.charAt(t);if(s.test(n))t++,r=!0;else break}return r&&(this.current=this.newToken(oo,parseInt(this.expression.substring(o,t),e)),this.pos=t),r};G.prototype.isNumber=function(){for(var t=!1,e=this.pos,s=e,r=e,o=!1,n=!1,i;e<this.expression.length&&(i=this.expression.charAt(e),i>="0"&&i<="9"||!o&&i===".");)i==="."?o=!0:n=!0,e++,t=n;if(t&&(r=e),i==="e"||i==="E"){e++;for(var a=!0,c=!1;e<this.expression.length;){if(i=this.expression.charAt(e),a&&(i==="+"||i==="-"))a=!1;else if(i>="0"&&i<="9")c=!0,a=!1;else break;e++}c||(e=r)}return t?(this.current=this.newToken(oo,parseFloat(this.expression.substring(s,e))),this.pos=e):this.pos=r,t};G.prototype.isOperator=function(){var t=this.pos,e=this.expression.charAt(this.pos);if(e==="+"||e==="-"||e==="*"||e==="/"||e==="%"||e==="^"||e==="?"||e===":"||e===".")this.current=this.newToken(B,e);else if(e==="∙"||e==="•")this.current=this.newToken(B,"*");else if(e===">")this.expression.charAt(this.pos+1)==="="?(this.current=this.newToken(B,">="),this.pos++):this.current=this.newToken(B,">");else if(e==="<")this.expression.charAt(this.pos+1)==="="?(this.current=this.newToken(B,"<="),this.pos++):this.current=this.newToken(B,"<");else if(e==="|")if(this.expression.charAt(this.pos+1)==="|")this.current=this.newToken(B,"||"),this.pos++;else return!1;else if(e==="=")this.expression.charAt(this.pos+1)==="="?(this.current=this.newToken(B,"=="),this.pos++):this.current=this.newToken(B,e);else if(e==="!")this.expression.charAt(this.pos+1)==="="?(this.current=this.newToken(B,"!="),this.pos++):this.current=this.newToken(B,e);else return!1;return this.pos++,this.isOperatorEnabled(this.current.value)?!0:(this.pos=t,!1)};G.prototype.isOperatorEnabled=function(t){return this.parser.isOperatorEnabled(t)};G.prototype.getCoordinates=function(){var t=0,e,s=-1;do t++,e=this.pos-s,s=this.expression.indexOf(`
110
110
  `,s+1);while(s>=0&&s<this.pos);return{line:t,column:e}};G.prototype.parseError=function(t){var e=this.getCoordinates();throw new Error("parse error ["+e.line+":"+e.column+"]: "+t)};function K(t,e,s){this.parser=t,this.tokens=e,this.current=null,this.nextToken=null,this.next(),this.savedCurrent=null,this.savedNextToken=null,this.allowMemberAccess=s.allowMemberAccess!==!1}K.prototype.next=function(){return this.current=this.nextToken,this.nextToken=this.tokens.next()};K.prototype.tokenMatches=function(t,e){return typeof e>"u"?!0:Array.isArray(e)?It(e,t.value):typeof e=="function"?e(t):t.value===e};K.prototype.save=function(){this.savedCurrent=this.current,this.savedNextToken=this.nextToken,this.tokens.save()};K.prototype.restore=function(){this.tokens.restore(),this.current=this.savedCurrent,this.nextToken=this.savedNextToken};K.prototype.accept=function(t,e){return this.nextToken.type===t&&this.tokenMatches(this.nextToken,e)?(this.next(),!0):!1};K.prototype.expect=function(t,e){if(!this.accept(t,e)){var s=this.tokens.getCoordinates();throw new Error("parse error ["+s.line+":"+s.column+"]: Expected "+(e||t))}};K.prototype.parseAtom=function(t){var e=this.tokens.unaryOps;function s(o){return o.value in e}if(this.accept(Zn)||this.accept(B,s))t.push(new P(Le,this.current.value));else if(this.accept(oo))t.push(new P(pe,this.current.value));else if(this.accept(pu))t.push(new P(pe,this.current.value));else if(this.accept(Fe,"("))this.parseExpression(t),this.expect(Fe,")");else if(this.accept(Pt,"["))if(this.accept(Pt,"]"))t.push(new P(Rt,0));else{var r=this.parseArrayList(t);t.push(new P(Rt,r))}else throw new Error("unexpected "+this.nextToken)};K.prototype.parseExpression=function(t){var e=[];this.parseUntilEndStatement(t,e)||(this.parseVariableAssignmentExpression(e),!this.parseUntilEndStatement(t,e)&&this.pushExpression(t,e))};K.prototype.pushExpression=function(t,e){for(var s=0,r=e.length;s<r;s++)t.push(e[s])};K.prototype.parseUntilEndStatement=function(t,e){return this.accept(Xn)?(this.nextToken&&this.nextToken.type!==xs&&!(this.nextToken.type===Fe&&this.nextToken.value===")")&&e.push(new P(so)),this.nextToken.type!==xs&&this.parseExpression(e),t.push(new P(ie,e)),!0):!1};K.prototype.parseArrayList=function(t){for(var e=0;!this.accept(Pt,"]");)for(this.parseExpression(t),++e;this.accept(no);)this.parseExpression(t),++e;return e};K.prototype.parseVariableAssignmentExpression=function(t){for(this.parseConditionalExpression(t);this.accept(B,"=");){var e=t.pop(),s=[],r=t.length-1;if(e.type===At){if(!this.tokens.isOperatorEnabled("()="))throw new Error("function definition is not permitted");for(var o=0,n=e.value+1;o<n;o++){var i=r-o;t[i].type===Le&&(t[i]=new P(ut,t[i].value))}this.parseVariableAssignmentExpression(s),t.push(new P(ie,s)),t.push(new P(to,e.value));continue}if(e.type!==Le&&e.type!==gt)throw new Error("expected variable for assignment");this.parseVariableAssignmentExpression(s),t.push(new P(ut,e.value)),t.push(new P(ie,s)),t.push(He("="))}};K.prototype.parseConditionalExpression=function(t){for(this.parseOrExpression(t);this.accept(B,"?");){var e=[],s=[];this.parseConditionalExpression(e),this.expect(B,":"),this.parseConditionalExpression(s),t.push(new P(ie,e)),t.push(new P(ie,s)),t.push(hu("?"))}};K.prototype.parseOrExpression=function(t){for(this.parseAndExpression(t);this.accept(B,"or");){var e=[];this.parseAndExpression(e),t.push(new P(ie,e)),t.push(He("or"))}};K.prototype.parseAndExpression=function(t){for(this.parseComparison(t);this.accept(B,"and");){var e=[];this.parseComparison(e),t.push(new P(ie,e)),t.push(He("and"))}};var Gy=["==","!=","<","<=",">=",">","in"];K.prototype.parseComparison=function(t){for(this.parseAddSub(t);this.accept(B,Gy);){var e=this.current;this.parseAddSub(t),t.push(He(e.value))}};var Yy=["+","-","||"];K.prototype.parseAddSub=function(t){for(this.parseTerm(t);this.accept(B,Yy);){var e=this.current;this.parseTerm(t),t.push(He(e.value))}};var Wy=["*","/","%"];K.prototype.parseTerm=function(t){for(this.parseFactor(t);this.accept(B,Wy);){var e=this.current;this.parseFactor(t),t.push(He(e.value))}};K.prototype.parseFactor=function(t){var e=this.tokens.unaryOps;function s(o){return o.value in e}if(this.save(),this.accept(B,s)){if(this.current.value!=="-"&&this.current.value!=="+"){if(this.nextToken.type===Fe&&this.nextToken.value==="("){this.restore(),this.parseExponential(t);return}else if(this.nextToken.type===Xn||this.nextToken.type===no||this.nextToken.type===xs||this.nextToken.type===Fe&&this.nextToken.value===")"){this.restore(),this.parseAtom(t);return}}var r=this.current;this.parseFactor(t),t.push(ro(r.value))}else this.parseExponential(t)};K.prototype.parseExponential=function(t){for(this.parsePostfixExpression(t);this.accept(B,"^");)this.parseFactor(t),t.push(He("^"))};K.prototype.parsePostfixExpression=function(t){for(this.parseFunctionCall(t);this.accept(B,"!");)t.push(ro("!"))};K.prototype.parseFunctionCall=function(t){var e=this.tokens.unaryOps;function s(n){return n.value in e}if(this.accept(B,s)){var r=this.current;this.parseAtom(t),t.push(ro(r.value))}else for(this.parseMemberExpression(t);this.accept(Fe,"(");)if(this.accept(Fe,")"))t.push(new P(At,0));else{var o=this.parseArgumentList(t);t.push(new P(At,o))}};K.prototype.parseArgumentList=function(t){for(var e=0;!this.accept(Fe,")");)for(this.parseExpression(t),++e;this.accept(no);)this.parseExpression(t),++e;return e};K.prototype.parseMemberExpression=function(t){for(this.parseAtom(t);this.accept(B,".")||this.accept(Pt,"[");){var e=this.current;if(e.value==="."){if(!this.allowMemberAccess)throw new Error('unexpected ".", member access is not permitted');this.expect(Zn),t.push(new P(gt,this.current.value))}else if(e.value==="["){if(!this.tokens.isOperatorEnabled("["))throw new Error('unexpected "[]", arrays are disabled');this.parseExpression(t),this.expect(Pt,"]"),t.push(He("["))}else throw new Error("unexpected symbol: "+e.value)}};function Qy(t,e){return Number(t)+Number(e)}function Zy(t,e){return t-e}function Xy(t,e){return t*e}function Jy(t,e){return t/e}function eb(t,e){return t%e}function tb(t,e){return Array.isArray(t)&&Array.isArray(e)?t.concat(e):""+t+e}function sb(t,e){return t===e}function rb(t,e){return t!==e}function ob(t,e){return t>e}function nb(t,e){return t<e}function ib(t,e){return t>=e}function ab(t,e){return t<=e}function cb(t,e){return!!(t&&e)}function lb(t,e){return!!(t||e)}function ub(t,e){return It(e,t)}function db(t){return(Math.exp(t)-Math.exp(-t))/2}function hb(t){return(Math.exp(t)+Math.exp(-t))/2}function fb(t){return t===1/0?1:t===-1/0?-1:(Math.exp(t)-Math.exp(-t))/(Math.exp(t)+Math.exp(-t))}function pb(t){return t===-1/0?t:Math.log(t+Math.sqrt(t*t+1))}function gb(t){return Math.log(t+Math.sqrt(t*t-1))}function mb(t){return Math.log((1+t)/(1-t))/2}function Zi(t){return Math.log(t)*Math.LOG10E}function yb(t){return-t}function bb(t){return!t}function vb(t){return t<0?Math.ceil(t):Math.floor(t)}function wb(t){return Math.random()*(t||1)}function Xi(t){return Jn(t+1)}function Eb(t){return isFinite(t)&&t===Math.round(t)}var Mb=4.7421875,Io=[.9999999999999971,57.15623566586292,-59.59796035547549,14.136097974741746,-.4919138160976202,3399464998481189e-20,4652362892704858e-20,-9837447530487956e-20,.0001580887032249125,-.00021026444172410488,.00021743961811521265,-.0001643181065367639,8441822398385275e-20,-26190838401581408e-21,36899182659531625e-22];function Jn(t){var e,s;if(Eb(t)){if(t<=0)return isFinite(t)?1/0:NaN;if(t>171)return 1/0;for(var r=t-2,o=t-1;r>1;)o*=r,r--;return o===0&&(o=1),o}if(t<.5)return Math.PI/(Math.sin(Math.PI*t)*Jn(1-t));if(t>=171.35)return 1/0;if(t>85){var n=t*t,i=n*t,a=i*t,c=a*t;return Math.sqrt(2*Math.PI/t)*Math.pow(t/Math.E,t)*(1+1/(12*t)+1/(288*n)-139/(51840*i)-571/(2488320*a)+163879/(209018880*c)+5246819/(75246796800*c*t))}--t,s=Io[0];for(var u=1;u<Io.length;++u)s+=Io[u]/(t+u);return e=t+Mb+.5,Math.sqrt(2*Math.PI)*Math.pow(e,t+.5)*Math.exp(-e)*s}function Tb(t){return Array.isArray(t)?t.length:String(t).length}function Ji(){for(var t=0,e=0,s=0;s<arguments.length;s++){var r=Math.abs(arguments[s]),o;e<r?(o=e/r,t=t*o*o+1,e=r):r>0?(o=r/e,t+=o*o):t+=r}return e===1/0?1/0:e*Math.sqrt(t)}function ea(t,e,s){return t?e:s}function _b(t,e){return typeof e>"u"||+e==0?Math.round(t):(t=+t,e=-+e,isNaN(t)||!(typeof e=="number"&&e%1===0)?NaN:(t=t.toString().split("e"),t=Math.round(+(t[0]+"e"+(t[1]?+t[1]-e:-e))),t=t.toString().split("e"),+(t[0]+"e"+(t[1]?+t[1]+e:e))))}function Sb(t,e,s){return s&&(s[t]=e),e}function Ib(t,e){return t[e|0]}function Ob(t){return arguments.length===1&&Array.isArray(t)?Math.max.apply(Math,t):Math.max.apply(Math,arguments)}function $b(t){return arguments.length===1&&Array.isArray(t)?Math.min.apply(Math,t):Math.min.apply(Math,arguments)}function Cb(t,e){if(typeof t!="function")throw new Error("First argument to map is not a function");if(!Array.isArray(e))throw new Error("Second argument to map is not an array");return e.map(function(s,r){return t(s,r)})}function Db(t,e,s){if(typeof t!="function")throw new Error("First argument to fold is not a function");if(!Array.isArray(s))throw new Error("Second argument to fold is not an array");return s.reduce(function(r,o,n){return t(r,o,n)},e)}function xb(t,e){if(typeof t!="function")throw new Error("First argument to filter is not a function");if(!Array.isArray(e))throw new Error("Second argument to filter is not an array");return e.filter(function(s,r){return t(s,r)})}function Ab(t,e){if(!(Array.isArray(e)||typeof e=="string"))throw new Error("Second argument to indexOf is not a string or array");return e.indexOf(t)}function Rb(t,e){if(!Array.isArray(e))throw new Error("Second argument to join is not an array");return e.join(t)}function Pb(t){return(t>0)-(t<0)||+t}var ta=1/3;function kb(t){return t<0?-Math.pow(-t,ta):Math.pow(t,ta)}function Lb(t){return Math.exp(t)-1}function Fb(t){return Math.log(1+t)}function Nb(t){return Math.log(t)/Math.LN2}function mt(t){this.options=t||{},this.unaryOps={sin:Math.sin,cos:Math.cos,tan:Math.tan,asin:Math.asin,acos:Math.acos,atan:Math.atan,sinh:Math.sinh||db,cosh:Math.cosh||hb,tanh:Math.tanh||fb,asinh:Math.asinh||pb,acosh:Math.acosh||gb,atanh:Math.atanh||mb,sqrt:Math.sqrt,cbrt:Math.cbrt||kb,log:Math.log,log2:Math.log2||Nb,ln:Math.log,lg:Math.log10||Zi,log10:Math.log10||Zi,expm1:Math.expm1||Lb,log1p:Math.log1p||Fb,abs:Math.abs,ceil:Math.ceil,floor:Math.floor,round:Math.round,trunc:Math.trunc||vb,"-":yb,"+":Number,exp:Math.exp,not:bb,length:Tb,"!":Xi,sign:Math.sign||Pb},this.binaryOps={"+":Qy,"-":Zy,"*":Xy,"/":Jy,"%":eb,"^":Math.pow,"||":tb,"==":sb,"!=":rb,">":ob,"<":nb,">=":ib,"<=":ab,and:cb,or:lb,in:ub,"=":Sb,"[":Ib},this.ternaryOps={"?":ea},this.functions={random:wb,fac:Xi,min:$b,max:Ob,hypot:Math.hypot||Ji,pyt:Math.hypot||Ji,pow:Math.pow,atan2:Math.atan2,if:ea,gamma:Jn,roundTo:_b,map:Cb,fold:Db,filter:xb,indexOf:Ab,join:Rb},this.consts={E:Math.E,PI:Math.PI,true:!0,false:!1}}mt.prototype.parse=function(t){var e=[],s=new K(this,new G(this,t),{allowMemberAccess:this.options.allowMemberAccess});return s.parseExpression(e),s.expect(xs,"EOF"),new Ee(e,this)};mt.prototype.evaluate=function(t,e){return this.parse(t).evaluate(e)};var mu=new mt;mt.parse=function(t){return mu.parse(t)};mt.evaluate=function(t,e){return mu.parse(t).evaluate(e)};var sa={"+":"add","-":"subtract","*":"multiply","/":"divide","%":"remainder","^":"power","!":"factorial","<":"comparison",">":"comparison","<=":"comparison",">=":"comparison","==":"comparison","!=":"comparison","||":"concatenate",and:"logical",or:"logical",not:"logical","?":"conditional",":":"conditional","=":"assignment","[":"array","()=":"fndef"};function Ub(t){return sa.hasOwnProperty(t)?sa[t]:t}mt.prototype.isOperatorEnabled=function(t){var e=Ub(t),s=this.options.operators||{};return!(e in s)||!!s[e]};var jb=Object.defineProperty,Bb=Object.getOwnPropertyDescriptor,Hb=(t,e,s)=>e in t?jb(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Kb=(t,e,s,r)=>{for(var o=r>1?void 0:r?Bb(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o},qb=(t,e,s)=>(Hb(t,e+"",s),s);const zb="kos-expression-evaluator-model";class Vb{constructor(e,s,r,o){l(this,"name");l(this,"expression");l(this,"expr");l(this,"getContextData",null);l(this,"_lastResult",{value:void 0});this.name=e,this.expression=s,this.expr=r,this.getContextData=o,this._lastResult={value:void 0,error:void 0}}get result(){return this._lastResult}updateResult(e){this._lastResult=e}evaluate(e){try{return{value:this.expr.evaluate(e),error:void 0}}catch(s){return{value:void 0,error:s instanceof Error?s.message:String(s)}}}}let Mr=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"parser");l(this,"_data");l(this,"_expressions",new Map);l(this,"_results");l(this,"_contextRevision",0);this.id=t,this.logger=s.logger,this._data=Oe(),this._results=Oe(),this.parser=new mt}get data(){return this._data}get contextRevision(){return this._contextRevision}setContextData(t){this._data.setValues(t),J(()=>{this._contextRevision++,this.logger.debug("Context revision incremented to:",this._contextRevision)})}updateContextValue(t,e){this._data[t]=e}updateNestedValue(t,e){const s=t.split("."),r=s.pop();if(!r){this.logger.error(`Invalid path "${t}" - cannot be empty`);return}let o=this._data;for(const n of s)(o[n]===void 0||o[n]===null)&&(o[n]={}),o=o[n];o[r]=e,this.logger.debug(`Updated nested context value "${t}" to:`,e)}addModelToContext(t,e){this._data[t]=e}addExpression(t,e){try{const s=this.parser.parse(e),r=new Vb(t,e,s,()=>this.data);this._expressions.set(t,r),this.evaluateExpression(t),this.logger.debug(`Added expression "${t}": ${e}`)}catch(s){throw this.logger.error(`Failed to parse expression "${t}"`,s),s}}removeExpression(t){const e=this._expressions.delete(t);return e?(delete this._results[t],this.logger.debug(`Removed expression "${t}"`)):this.logger.warn(`Attempted to remove non-existent expression "${t}". Available expressions: [${this.expressionNames.join(", ")}]`),e}getExpression(t){const e=this._expressions.get(t);return e||this.logger.warn(`Expression "${t}" not found. Available expressions: [${this.expressionNames.join(", ")}]`),e}getExpressionValue(t){const e=this._expressions.get(t);if(!e){this.logger.warn(`Expression "${t}" not found. Available expressions: [${this.expressionNames.join(", ")}]`);return}return e.result}getCachedExpressionValue(t){const e=this._expressions.get(t);if(e)return e.result}get expressions(){return Array.from(this._expressions.values())}get expressionNames(){return Array.from(this._expressions.keys())}get results(){return this.evaluateAllExpressions(),this._results}evaluateAllExpressions(){Array.from(this._expressions.keys()).forEach(e=>{this._expressions.get(e)&&this.evaluateExpression(e)})}evaluateExpression(t){this.logger.debug(`Evaluating expression: ${String(t)}`);const e=this._expressions.get(t);if(!e){this.logger.warn(`Expression "${String(t)}" not found`);return}const s=e.evaluate(this.data);this.logger.debug(`Expression "${String(t)}" evaluated to:`,s);const r=e.result;(s.value!==r.value||s.error!==r.error)&&(this.logger.debug(`Expression "${String(t)}" result changed from`,r,"to",s),e.updateResult(s),this.updateResult(t,s))}updateResult(t,e){this.logger.debug(`ExpressionEvaluator.updateResult called for "${t}":`,e),J(()=>{this._results[t]=e})}createExpression(t){const e=dt();return this.addExpression(e,t),e}};qb(Mr,"Registration");Mr=Kb([R({modelTypeId:zb,singleton:!1})],Mr);const yu=Mr.Registration,Gb=m.createLogger({name:"kos-log-manager-service",group:"Services"}),Yb="/api/kos/logs/overrides",bu=async()=>(Gb.debug("sending GET for kos-log-manager"),await Ae.get(Yb)),Wb=Object.freeze(Object.defineProperty({__proto__:null,getLogOverrides:bu},Symbol.toStringTag,{value:"Module"}));var Qb=Object.defineProperty,Zb=Object.getOwnPropertyDescriptor,io=(t,e,s,r)=>{for(var o=r>1?void 0:r?Zb(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Qb(e,s,o),o};const vu="kos-log-manager-model",Xb="/kos/logs/override/add/*",Jb="/kos/logs/override/remove/*",ev=t=>{if(typeof t=="string")return t;if(typeof t=="number")switch(t){case 0:return"trace";case 1:return"debug";case 2:return"info";case 3:return"warn";case 4:return"error";default:return"info"}return"info"};let kt=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_overrides");this.id=t,this.logger=s.logger,this._overrides=new Dn}updateModel(t){}resolveLoggers(){const t=m.getLoggers(),s=Object.entries(t).map(([r,o])=>({name:r,level:ev(o.getLevel())})).reduce((r,{name:o,level:n})=>(r[o]={name:o,level:n},r),{});return this.logger.debug("Resolved loggers",s),s}async getAllLoggers(t,e){const s=Object.values(this.resolveLoggers());return e==null||e.send(s),s}setLogLevels(t){Object.values(this.resolveLoggers()).filter(r=>r.name.startsWith(t.name)).forEach(r=>{const o=m.getLoggers()[r.name];if(!o){this.logger.debug(`Logger ${r.name} not found`);return}o.setLevel(t.level)});const s=m.getLoggers()[t.name];if(!s){this.logger.debug(`Logger ${t.name} not found`);return}s.setLevel(t.level),globalThis.kos.logOverrides=this._overrides.data}resetLogLevels(t){Object.values(this.resolveLoggers()).filter(r=>r.name.startsWith(t.name)).forEach(r=>{const o=m.getLoggers()[r.name];o||this.logger.debug(`Logger ${r.name} not found`),o==null||o.resetLevel()});const s=m.getLoggers()[t.name];s||this.logger.debug(`Logger ${t.name} not found`),s==null||s.resetLevel(),globalThis.kos.logOverrides=this._overrides.data}handleOverrideAdded(t,e){var s;this.logger.debug(`Override received for node type ${((s=e.wildcardCapture)==null?void 0:s.nodeType)??"unknown"}`),this._overrides.addModel({...t,id:t.name}),this.setLogLevels(t)}handleOverrideRemoved(t){this._overrides.removeModel(t.name),this.resetLogLevels(t)}async init(){this.logger.debug(`initializing kos-log-manager ${this.id}`)}async load(){this.logger.debug(`loading kos-log-manager ${this.id}`),this.resolveLoggers();const[t,e]=await bu();if(t){this.logger.error("Failed to load log overrides",t);return}const s=(e==null?void 0:e.filter(r=>{var o;return((o=r.type)==null?void 0:o.toUpperCase())==="UI"}).map(r=>({name:r.name??"",type:r.type??"",level:r.level??"info",id:r.name||""})))??[];this._overrides.addAll(s),s.forEach(r=>{this.setLogLevels(r)})}};io([$c("/api/kos/ui/loggers")],kt.prototype,"getAllLoggers",1);io([H({topic:Xb,websocket:!0,wildcardName:"nodeType"})],kt.prototype,"handleOverrideAdded",1);io([H({topic:Jb,websocket:!0,wildcardName:"nodeType"})],kt.prototype,"handleOverrideRemoved",1);kt=io([R(vu)],kt);const wu=new Se({class:kt,type:vu}),{URL:Vs}=ce(),{postModel:ei,getOne:tv}=oe.build({basePath:`${Vs}/api/kos-time`});m.createLogger({name:"kos-time-service",group:"Services"});const Eu=async t=>{const e=await ei({model:t,urlOverride:`${Vs}/api/kos/time/time`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set time");return e.data},Mu=async t=>{const e=await ei({model:t,urlOverride:`${Vs}/api/kos/time/date`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set time");return e.data},Tu=async t=>{const e=await ei({model:{},urlOverride:`${Vs}/api/kos/time/timezone?tz=${t}`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set timezone");return e.data},_u=async()=>{const t=await tv({urlOverride:`${Vs}/api/kos/time/timezone`});if((t==null?void 0:t.status)!==200)throw Error("Failed to set timezone");return t.data.timeZone},sv=Object.freeze(Object.defineProperty({__proto__:null,getTimezone:_u,setDate:Mu,setTime:Eu,setTimezone:Tu},Symbol.toStringTag,{value:"Module"}));var rv=Object.defineProperty,ov=Object.getOwnPropertyDescriptor,ao=(t,e,s,r)=>{for(var o=r>1?void 0:r?ov(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&rv(e,s,o),o};const os="kos-time-model",nv="/kos/time/time",iv="/kos/time/day",av="/kos/time/timezone";let Lt=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"timezone");this.id=t,this.logger=s.logger,this.timezone=""}async updateSystemTime(t){await Eu(t)}async updateSystemDate(t){await Mu(t)}async updateSystemTimezone(t){await Tu(t)}handleTimeChange(){V(Ts.TIME_CHANGE,{})}handleDayChange(){V(Ts.DAY_CHANGE,{})}async handleTimeZoneChange(){await this.retrieveTimezone(),V(Ts.TIMEZONE_CHANGE,{})}async init(){this.logger.debug(`initializing kos-time ${this.id}`)}async retrieveTimezone(){const t=await _u();this.setTimezone(t)}setTimezone(t){this.timezone=t}async load(){this.logger.debug(`loading kos-time ${this.id}`),this.retrieveTimezone()}};ao([H({topic:nv,websocket:!0})],Lt.prototype,"handleTimeChange",1);ao([H({topic:iv,websocket:!0})],Lt.prototype,"handleDayChange",1);ao([H({topic:av,websocket:!0})],Lt.prototype,"handleTimeZoneChange",1);Lt=ao([R(os)],Lt);const Tr={registration:{[os]:{class:Lt,singleton:!0}},type:os,predicate:_e(os),factory:ae.Singleton.create(os)};var cv=Object.defineProperty,lv=Object.getOwnPropertyDescriptor,Su=(t,e,s,r)=>{for(var o=r>1?void 0:r?lv(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&cv(e,s,o),o};const Iu="log-block-container-model";let _r=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_models");this.id=t,this.logger=s.logger,this._models=new xe({parentId:t,sortKey:"blockNum"})}getModel(t){return this._models.getModel(t)}get models(){return this._models}get data(){return this._models.data}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}async init(){this.logger.debug(`initializing log-block-container container ${this.id}`)}async load(){this.logger.debug(`loading log-block-container container ${this.id}`)}};Su([De],_r.prototype,"_models",2);_r=Su([R(Iu)],_r);const uv=m.createLogger({name:"log-stream-container-service",group:"Services"}),Ou=()=>{var r;const t=ye(),s=(t==null?void 0:t.connId)||((r=window==null?void 0:window.kosBridge)==null?void 0:r.call(window,"connId"));return m.error(`getKosConnectionId: ${s}`),s},Zt=Ou(),dv="/api/kos/logs/node/{nodeId}/streams",$u=async()=>(uv.debug("sending GET for log-stream-container"),await Ae.get(dv,{path:{nodeId:"primary"}},{destinationAddress:Zt})),Cu=async(t,e="primary")=>{await Ae.post("/api/kos/logs/node/{nodeId}/{stream}/subscribe",{path:{nodeId:e,stream:t}},void 0,{destinationAddress:Zt})},Du=async t=>{await Ae.post("/api/kos/logs/node/{nodeId}/{stream}/unsubscribe",{path:{nodeId:"primary",stream:t}},void 0,{destinationAddress:Zt})},hv=async()=>{await Ae.post("/api/kos/logs/overrides",{},{level:"WARN",name:"com.example",nodeType:"java",type:"package"},{destinationAddress:Zt})},xu=async t=>await Ae.get("/api/kos/logs/node/{nodeId}/{stream}/blocks",{path:{nodeId:"primary",stream:t}},{destinationAddress:Zt}),Au=async(t,e)=>await Ae.get("/api/kos/logs/node/{nodeId}/{stream}/blocks/{blockId}",{path:{nodeId:"primary",stream:t,blockId:e}},{destinationAddress:Zt}),fv=Object.freeze(Object.defineProperty({__proto__:null,createOverride:hv,getKosConnectionId:Ou,getLogStreamBlock:Au,getLogStreamBlocks:xu,getLogStreams:$u,subscribeToLogStream:Cu,unsubscribeFromLogStream:Du},Symbol.toStringTag,{value:"Module"}));var pv=Object.getOwnPropertyDescriptor,gv=(t,e,s,r)=>{for(var o=r>1?void 0:r?pv(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const Ru="log-block-model";let Ko=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"nodeId");l(this,"stream");l(this,"blockNum");l(this,"startLineNum");l(this,"endLineNum");l(this,"startTime");l(this,"endTime");l(this,"lineCount");l(this,"lines");l(this,"inc");this.id=t,this.logger=s.logger,this.nodeId=e.nodeId,this.stream=e.stream,this.blockNum=e.blockNum,this.startLineNum=e.startLineNum,this.endLineNum=e.endLineNum,this.startTime=e.startTime,this.endTime=e.endTime,this.lineCount=e.lineCount,this.lines=[],this.inc=0}async syncLines(){const[t,e]=await Au(this.stream,this.blockNum);if(t){this.logger.error(`Failed to get log block ${this.blockNum}`);return}e&&this.addLines(e.lines,!0)}updateModel(t){this.startLineNum=t.startLineNum,this.endLineNum=t.endLineNum,this.startTime=t.startTime,this.endTime=t.endTime,this.lineCount=t.lineCount}addLines(t,e){const s=e?[]:this.lines;this.lines=[...s,...t],this.inc+=1}async init(){this.logger.debug(`initializing log-block ${this.id}`)}async load(){this.logger.debug(`loading log-block ${this.id}`)}};Ko=gv([R(Ru)],Ko);const As=new be({class:Ko,type:Ru}),co=new be({class:_r,type:Iu});co.addRelatedModel(As);var mv=Object.defineProperty,yv=Object.getOwnPropertyDescriptor,Pu=(t,e,s,r)=>{for(var o=r>1?void 0:r?yv(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&mv(e,s,o),o};const ku="log-stream-model";let Sr=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"nodeId");l(this,"_blocks");l(this,"name");l(this,"currentBlockId");l(this,"isResetting");l(this,"generatorInstance");l(this,"shouldStop",!1);this.id=t,this.logger=s.logger,this.currentBlockId="",this.name=e.name,this.nodeId=e.nodeId,this.isResetting=!0,this._blocks=co.instance(`${t}-blocks`).options({}).build()}get firstLineNum(){const t=this.populated[0];return t?t.startLineNum:0}get currentBlock(){const t=this.currentBlockId;return this._blocks.getModel(t)}get populated(){return this._blocks.data.filter(t=>t.lines.length>0)}get blocks(){return this._blocks.data}get totalLineCount(){return this.populated.reduce((t,e)=>t+e.lineCount,0)}accept(t){t.visit(this)}updateBlock(t){var r;let e=this._blocks.models.getModel(`${t.stream}-block-${t.blockNum}`);const s={nodeId:t.nodeId,blockNum:t.blockNum,endLineNum:t.endLineNum,lineCount:t.lineCount,startLineNum:t.startLineNum,stream:this.name,endTime:new Date(t.endTime),startTime:new Date(t.startTime)};e||(e=As.instance(`${t.stream}-block-${t.blockNum}`).options(s).build(),this._blocks.addModel(e)),e&&e.updateModel(s),(!this.currentBlock||t.blockNum>=((r=this.currentBlock)==null?void 0:r.blockNum))&&(this.currentBlockId=`${t.stream}-block-${t.blockNum}`)}addBlock(t){var s;const e=As.instance(`${t.stream}-block-${t.blockNum}`).options({nodeId:t.nodeId,blockNum:t.blockNum,endLineNum:t.endLineNum,lineCount:t.lineCount,startLineNum:t.startLineNum,stream:this.name,endTime:new Date(t.endTime),startTime:new Date(t.startTime)}).build();this._blocks.addModel(e),(!this.currentBlock||t.blockNum>=((s=this.currentBlock)==null?void 0:s.blockNum))&&(this.currentBlockId=`${t.stream}-block-${t.blockNum}`)}removeBlock(t){this._blocks.models.removeModel(`${this.name}-block-${t}`)}async subscribe(){await Cu(this.name)}async unsubscribe(){await Du(this.name)}async reset(){if(this.isResetting=!0,this.populated.length>0)return;this.logger.debug(`resetting log-stream ${this.id}`);for(const e of this._blocks.models.data)e.lines=[];const t=this._blocks.data[this._blocks.data.length-1];t&&await t.syncLines(),this.isResetting=!1}async init(){this.logger.debug(`initializing log-stream ${this.id}`)}async load(){this.logger.debug(`loading log-stream ${this.id}`);const[t,e]=await xu(this.name);if(t){this.logger.error(`Error loading log stream: ${t}`);return}if(e)for(const r of e)this.addBlock(r);const s=this._blocks.data[this._blocks.data.length-1];if(s&&await s.syncLines(),this._blocks.data.length>1){const r=this._blocks.data[this._blocks.data.length-2];r&&await r.syncLines()}}start(){return this.shouldStop=!1,this.generatorInstance=this.streamLogs(),this.generatorInstance}stop(){var t;this.shouldStop=!0,(t=this.generatorInstance)==null||t.next(),console.log("Requested generator stop.")}async*streamLogs(){const t=[];let e=null,s=0,r=this.currentBlockId;const o=Rl(()=>{const n=this.currentBlock;return n?{blockId:this.currentBlockId,lineCount:n.lines.length}:null},n=>{const i=this.currentBlock;if(i)if(r!==(n==null?void 0:n.blockId))r=n==null?void 0:n.blockId,s=0,t.push(...i.lines);else{const a=i.lines.slice(s);t.push(...a),s+=a.length}e&&(e(),e=null)},{fireImmediately:!0});try{for(const n of this.populated.filter(i=>i!==this.currentBlock))for(const i of n.lines)yield i;for(;;)for(t.length===0&&await new Promise(n=>e=n);t.length>0;)yield t.shift()}finally{o()}}};Pu([De],Sr.prototype,"_blocks",2);Sr=Pu([R(ku)],Sr);const _s=new be({class:Sr,type:ku});var bv=Object.defineProperty,vv=Object.getOwnPropertyDescriptor,yt=(t,e,s,r)=>{for(var o=r>1?void 0:r?vv(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&bv(e,s,o),o};const Lu="log-stream-container-model",wv="/kos/logs/subscription/addBlock/*",Ev="/kos/logs/subscription/updateBlock/*",Mv="/kos/logs/subscription/removeBlock/*",Tv="/kos/logs/subscription/lines/*",Fu="/kos/logs/streams/add/*";let Ne=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"selectedStream");l(this,"_models");this.id=t,this.logger=s.logger,this._models=new xe({parentId:t}),this.selectedStream=void 0}getModel(t){return this._models.getModel(t)}get models(){return this._models}get data(){return this._models.data}updateModel(t){}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}updateSelectedStream(t){this.selectedStream=t}handleStreamAdded(t){this.logger.debug(`Received topic: ${Fu}`);const e=t.stream,s=_s.instance(e).options({name:e,nodeId:"primary"}).build();this.addModel(s)}handleAddBlock(t,e){this.logger.debug(`Received topic: ${e.headers.topic}`);const s=t.stream,r=this.models.getModel(s);r&&r.addBlock(t)}handleRemoveBlock(t,e){this.logger.debug(`Received topic: ${e.headers.topic}`);const s=t.stream,r=this.models.getModel(s);r&&r.removeBlock(t.blockNum)}handleUpdateBlock(t,e){this.logger.debug(`Received topic: ${e.headers.topic}`);const s=t.stream,r=this.models.getModel(s);r&&r.updateBlock(t)}handleLogLine(t,e){var o;this.logger.debug(`Received topic: ${e.headers.topic}`);const s=t.stream,r=this.models.getModel(s);r&&((o=r.currentBlock)==null||o.addLines(t.lines))}async init(){this.logger.debug(`initializing log-stream-container container ${this.id}`)}async subscribeToLogStream(t){const e=_s.instance(t).options({name:t,nodeId:"primary"}).build();this.addModel(e),await e.subscribe()}async load(){this.logger.debug(`loading log-stream-container container ${this.id}`);const[t,e]=await $u();if(t){this.logger.error(`Error loading log-streams: ${t}`);return}e&&e.forEach(s=>{const r=_s.instance(s).options({name:s,nodeId:"primary"}).build();this.addModel(r)})}};yt([De],Ne.prototype,"_models",2);yt([H({topic:[Fu],websocket:!0})],Ne.prototype,"handleStreamAdded",1);yt([H({topic:[wv],websocket:!0})],Ne.prototype,"handleAddBlock",1);yt([H({topic:[Mv],websocket:!0})],Ne.prototype,"handleRemoveBlock",1);yt([H({topic:[Ev],websocket:!0})],Ne.prototype,"handleUpdateBlock",1);yt([H({topic:[Tv],websocket:!0})],Ne.prototype,"handleLogLine",1);Ne=yt([R(Lu)],Ne);const Gs=new Se({class:Ne,type:Lu});Gs.addRelatedModel(_s);Gs.addRelatedModel(co);Gs.addRelatedModel(As);const _v=t=>t.rank!==void 0,Sv=t=>t.visibleRole!==void 0,Iv=t=>t.color!==void 0,Ov=t=>{const e=t.info;return _v(e)?e.rank:0},$v=t=>{const e=t.info;return Iv(e)?e.color:"orange"},Cv=t=>{const e=t.info;return Sv(e)?e.visibleRole:"TECHNICIAN"},{URL:lo}=ce(),{getAll:Dv,postModel:Nu}=oe.build({basePath:`${lo}/api/kos/troubles`}),Uu=async t=>await Dv({urlOverride:`${lo}${t}`}),ju=async(t,e="/api/kos/troubles",s)=>{try{const r=await Nu({model:{},urlOverride:`${lo}${e}/resolve/${t}`,tracker:s});return r!=null&&r.data&&lt.initiateFuture(r.data),r.data}catch{const o={id:s||"",endState:We.Fail,tracker:s,reason:"Failed to resolve trouble"};return lt.initiateFuture(o),o}},xv=async(t,e="/api/kos/troubles",s)=>{try{const r=await Nu({model:t,urlOverride:`${lo}${e}/resolve/`,tracker:s});return r!=null&&r.data&&lt.initiateFuture(r.data),r.data}catch{const o={id:s||"",endState:We.Fail,tracker:s,reason:"Failed to resolve troubles"};return lt.initiateFuture(o),o}},Av=Object.freeze(Object.defineProperty({__proto__:null,bulkResolveTroubles:xv,getTroubles:Uu,resolveTrouble:ju},Symbol.toStringTag,{value:"Module"})),Ir="troubleDataMapper",rr=new Map;js(Ir,{register:(t,e)=>{var s;rr.has(t)||rr.set(t,[]),(s=rr.get(t))==null||s.push(e)},execute:async(t,e)=>{const s=rr.get(t);if(!s)return{...e.data};const r=s.map(i=>i(e));return(await Promise.allSettled(r)).reduce((i,a)=>(a.status==="fulfilled"?i={...i,...a.value}:m.info(`Trouble mapper ${t} failed: ${a.reason}`),i),{...e.data})}});const Ys="troubleMapper",or=new Map;js(Ys,{register:(t,e)=>{var s;or.has(t)||or.set(t,[]),(s=or.get(t))==null||s.push(e)},execute:async(t,e)=>{const s=or.get(t);if(!s)return[];const r=s.map(i=>i(e)),n=(await Promise.allSettled(r)).map(i=>i.status==="fulfilled"?i.value:(m.info(`Trouble mapper ${t} failed: ${i.reason}`),[])).flat();return Array.from(new Set(n))}});$[Ys].register("nozzle",async t=>[t.data.nozzlePath]);$[Ys].register("path",async t=>[t.data.path]);const Rv=async t=>{const e=new Set,s=t.ifaces,r=s==null?void 0:s.map(n=>$[Ys].execute(n,t));return(await Promise.allSettled(r)).forEach(n=>{n.status==="fulfilled"&&n.value.forEach(i=>e.add(i))}),Array.from(e)},Bu=async t=>{const e=t.ifaces,s=e==null?void 0:e.map(i=>$[Ir].execute(i,t)),r=$[Ir].execute(t.type,t);s.push(r);const n=(await Promise.allSettled(s)).reduce((i,a)=>(a.status==="fulfilled"&&(i={...i,...a.value}),i),{});return{...t.data,...n}};class Pv{constructor(){l(this,"type","ResolvableTrouble");l(this,"title","Resolvable Trouble");l(this,"subtitle","Trouble")}}class kv{constructor(){l(this,"type","BlockPumpTrouble");l(this,"title","Block Pump Trouble");l(this,"subtitle","Trouble")}}class Mt{static getHandler(e){switch(e){case"ResolvableTrouble":return new Pv;case"BlockPumpTrouble":return new kv;default:return}}}var Lv=Object.defineProperty,Fv=Object.getOwnPropertyDescriptor,Hu=(t,e,s,r)=>{for(var o=r>1?void 0:r?Fv(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Lv(e,s,o),o};const ns="trouble-model";function nr(t){return typeof t.shouldDefer=="boolean"}let Or=class{constructor(t,{resolvable:e,tags:s,info:r,id:o,clientData:n,rank:i,ifaces:a,type:c,group:u,createTime:d,role:h,color:f,servicePath:p,...y},w){l(this,"id");l(this,"logger");l(this,"_troubleId");l(this,"_resolvable");l(this,"type");l(this,"futureHandler");l(this,"ifaces");l(this,"clientData");l(this,"info");l(this,"role");l(this,"color");l(this,"tags");l(this,"data");l(this,"rank");l(this,"servicePath");l(this,"group");l(this,"createTime");l(this,"_mapped",{});this.id=t,this.logger=w.logger,this.type=c,this._troubleId=o,this._resolvable=!!e,this.ifaces=a,this.rank=i,this.role=h,this.color=f,this.tags=s,this.info=r,this.group=u,this.servicePath=p??"/api/kos/troubles",this.createTime=d,this.clientData=n,this.data={},Object.assign(this.data,y),this.futureHandler=new Zr(this)}getTitleWithContext(t){var s,r;const e=t?(r=(s=Mt.getHandler(this.type))==null?void 0:s.context)==null?void 0:r[t]:Mt.getHandler(this.type);return(e==null?void 0:e.title)||"Trouble"}getSubtitleWithContext(t){var s,r;const e=t?(r=(s=Mt.getHandler(this.type))==null?void 0:s.context)==null?void 0:r[t]:Mt.getHandler(this.type);return(e==null?void 0:e.subtitle)||"Trouble"}get rawId(){return this._troubleId}get title(){var t;return((t=Mt.getHandler(this.type))==null?void 0:t.title)||"Trouble"}get subtitle(){var t;return((t=Mt.getHandler(this.type))==null?void 0:t.subtitle)||"Trouble"}get troubleId(){return this._troubleId}get resolvable(){return this._resolvable}get future(){return this.futureHandler.future}async resolveMappedData(){return await Bu(this)}get deferredCompanion(){const t=ko(this.id,e=>nr(e));if(t&&nr(t.modelData))return t.modelData}get deferred(){return this.deferredCompanion?this.deferredCompanion.deferred:!1}get shouldDefer(){const t=ko(this.id,e=>nr(e));return t&&nr(t.modelData)?t.modelData.shouldDefer:!1}clearDefer(){var t;(t=this.deferredCompanion)==null||t.clearDefer()}defer(){var t;(t=this.deferredCompanion)==null||t.defer()}getChildren(){return[...this.futureHandler.allFutures]}async resolve(t){var e;if(!this._resolvable)throw this.logger.error(`attempting to resolve an unresolvable trouble with id ${this._troubleId}`),new Error("Trouble is not resolvable");if(this.shouldDefer){(e=this.deferredCompanion)==null||e.defer();return}return await ju(this._troubleId,this.servicePath,t)}};Hu([bi()],Or.prototype,"resolve",1);Or=Hu([R(ns)],Or);const Rs={registration:{[ns]:{class:Or,singleton:!1}},type:ns,predicate:_e(ns),factory:ae.Factory.create(ns)};var Ku=Object.defineProperty,Nv=Object.getOwnPropertyDescriptor,Uv=(t,e,s)=>e in t?Ku(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,ti=(t,e,s,r)=>{for(var o=r>1?void 0:r?Nv(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Ku(e,s,o),o},jv=(t,e,s)=>(Uv(t,e+"",s),s);function ra(t){return $.propertyMapper.hasMapper(we.TroubleRank)?$.propertyMapper.executeMapper(we.TroubleRank,t):Ov(t)}function oa(t){return($.propertyMapper.hasMapper(we.TroubleColor)?$.propertyMapper.executeMapper(we.TroubleColor,t):$v(t)).toLowerCase()}function na(t){return($.propertyMapper.hasMapper(we.TroubleRole)?$.propertyMapper.executeMapper(we.TroubleRole,t):Cv(t)).toLowerCase()}const Bv="trouble-container-model";class ge{}l(ge,"INDEX_TROUBLES_BY_IFACE","byIface"),l(ge,"INDEX_TROUBLES_BY_TYPE","byType"),l(ge,"INDEX_TROUBLES_BY_GROUP","byGroup"),l(ge,"INDEX_TROUBLES_BY_DEFERRED","byDeferred"),l(ge,"SORT_KEY_RANK","rank"),l(ge,"TROUBLES_DEFERRED","true");let Ft=class{constructor(t,e){l(this,"id");l(this,"servicePath","/api/kos/troubles");this.id=t,this.servicePath=e.servicePath??this.servicePath}async load(){this.logger.debug("loading trouble container");const t=await Uu(this.servicePath);try{t==null||t.data.forEach(e=>{const s={...e,servicePath:this.servicePath,rank:ra(e),color:oa(e),role:na(e),id:String(e.id)},r=Rs.factory(`trouble-${e.id}`)(s);this.troubles.addModel(r)})}catch(e){throw this.logger.error(e),e}}handleTroubleRemoved(t){const e=`trouble-${t}`,s=this.troubles.getModel(e);this.troubles.removeModel(e),s&&Ie(s)}handleTroubleAdded(t){const e={...t,servicePath:this.servicePath,rank:ra(t),color:oa(t),role:na(t),id:String(t.id)};if(e.role==="NONE")return;const s=Rs.factory(`trouble-${t.id}`)(e);this.troubles.addModel(s)}};jv(Ft,"Registration");ti([H({topic:"/kos/trouble/remove",websocket:!0,lifecycle:x.INIT})],Ft.prototype,"handleTroubleRemoved",1);ti([H({topic:"/kos/trouble/add",websocket:!0})],Ft.prototype,"handleTroubleAdded",1);Ft=ti([R({modelTypeId:Bv,singleton:!0}),Ac(),Oc({containerProperty:"troubles",containerOptions:{indexMap:{[ge.INDEX_TROUBLES_BY_IFACE]:Rv,[ge.INDEX_TROUBLES_BY_TYPE]:"type",[ge.INDEX_TROUBLES_BY_GROUP]:"group",[ge.INDEX_TROUBLES_BY_DEFERRED]:"deferred"},sortKey:ge.SORT_KEY_RANK}})],Ft);const Nt=Ft.Registration,{URL:qu}=ce(),{getAll:Hv}=oe.build({basePath:`${qu}/api/kos/ota`}),ia=m.createLogger({name:"ota-service",group:"Services"}),Kv=async()=>{ia.debug("sending GET request to /api/kos/ota/artifacts");const t=await Hv({urlOverride:`${qu}/api/kos/ota/artifacts`});return ia.debug("getArtifacts - response:",t),t==null?void 0:t.data};var qv=Object.defineProperty,zv=Object.getOwnPropertyDescriptor,uo=(t,e,s,r)=>{for(var o=r>1?void 0:r?zv(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&qv(e,s,o),o};const zu="ota-model",Vv=t=>{let e=null;for(const s in t){const r=t[s],o=r.lastUpdateTime;(!e||e.lastUpdateTime<o)&&(e=r)}return e},Oo=t=>{const e=t.artifactInfo,s=Vv(t.requests),r=(e==null?void 0:e.identifier)||(s==null?void 0:s.kabId);if(!r)return;let o;switch(t.status){case"INSTALLED":o="ready";break;case"INVALID":o="error";break;case"MISSING":o=((s==null?void 0:s.currentSize)||0)>0?"downloading":"idle";break;case"STAGED":o="pending"}const n=e===void 0;return{id:r,manifest:n,label:e==null?void 0:e.version,name:e==null?void 0:e.name,status:o,error:o==="error"?s==null?void 0:s.lastErrorReason:void 0,errorCount:o==="error"?s==null?void 0:s.errorCount:0,progress:o==="downloading"&&s&&!n?s.currentSize/(e==null?void 0:e.size)*100:void 0,size:e==null?void 0:e.size}};let Ut=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"data",new Dn);l(this,"troubleContainer");this.id=t,this.logger=s.logger}get downloadInProgressTrouble(){var e;return(e=this.troubleContainer.troubles.getIndexByKey("byType","OTADownloadInProgressTrouble"))==null?void 0:e[0]}get updatePendingTrouble(){var e;return(e=this.troubleContainer.troubles.getIndexByKey("byType","OTAUpdatePendingTrouble"))==null?void 0:e[0]}get pausedDueToErrorsTrouble(){var e;return(e=this.troubleContainer.troubles.getIndexByKey("byType","OTAPausedDueToErrorsTrouble"))==null?void 0:e[0]}get updates(){return this.data}get status(){return this.pausedDueToErrorsTrouble?"error":this.downloadInProgressTrouble?"downloading":this.updatePendingTrouble?"pending":"idle"}installAndReboot(){var t;this.updatePendingTrouble||this.logger.error("installAndReboot - OTAUpdatePendingTrouble not present"),this.logger.debug("installAndReboot - resolve OTAUpdatePendingTrouble"),(t=this.updatePendingTrouble)==null||t.resolve()}async init(){this.logger.debug(`initializing ota ${this.id}`)}async load(){this.logger.debug(`loading ota ${this.id}`);try{const t=await Kv();t&&t.forEach(e=>{const s=Oo(e);s&&this.data.addModel(s)})}catch(t){this.logger.error(`loading ota ${this.id} - error:`,t)}}async handleAllArtifacts(t){this.logger.debug("handleAllArtifacts:",t),await this.data.clear();try{t.forEach(e=>{const s=Oo(e);s&&this.data.addModel(s)})}catch(e){this.logger.error(`handleAllArtifacts ${this.id} - error:`,e)}}handleChangedArtifacts(t){this.logger.debug("handleChangedArtifacts:",t);try{t.forEach(e=>{const s=Oo(e);s&&this.data.updateModel(s)})}catch(e){this.logger.error(`handleChangedArtifacts ${this.id} - error:`,e)}}};uo([qt({modelType:Nt.type})],Ut.prototype,"troubleContainer",2);uo([H({topic:"/kos/ota/artifacts/all",websocket:!0})],Ut.prototype,"handleAllArtifacts",1);uo([H({topic:"/kos/ota/artifacts/changed",websocket:!0})],Ut.prototype,"handleChangedArtifacts",1);Ut=uo([R(zu)],Ut);const $r=new Se({class:Ut,type:zu});function Gv(t){let e;const s=async(...r)=>{e&&e.abort(),e=new AbortController;const o=e;try{return await t(...r,o.signal)}finally{e===o&&(e=void 0)}};return s.cancel=()=>{e&&(e.abort(),e=void 0)},s.getController=()=>e,s.isActive=()=>!!e,s}const $o=m.createLogger({name:"software-info-service",group:"Services"}),si=async t=>{$o.debug("sending GET for software-info");const[e,s]=await tu.get("/api/kos/manifest/info",void 0,{signal:t});if(!s)throw t!=null&&t.aborted?($o.debug("Request was aborted"),new me("Request was aborted")):($o.error("Failed to fetch software-info",e),new me("Failed to fetch software-info"));return s},Yv=Gv(si),Wv=Object.freeze(Object.defineProperty({__proto__:null,getSoftwareInfos:si,getSoftwareInfosWithCancel:Yv},Symbol.toStringTag,{value:"Module"}));var Qv=Object.getOwnPropertyDescriptor,Zv=(t,e,s,r)=>{for(var o=r>1?void 0:r?Qv(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const is="software-info-model";let qo=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"nodes");this.id=t,this.logger=s.logger,this.nodes=[]}async init(){this.logger.debug(`initializing software-info ${this.id}`)}groupBy(t,e){return t.reduce((s,r)=>(s[r[e]]=[...s[r[e]]||[],r],s),{})}async load(){this.logger.debug(`loading software-info ${this.id}`);try{const t=await si(),e=(t==null?void 0:t.nodes)||{};J(()=>{const r=Object.keys(e).map(o=>e[o][0]).map(o=>({nodeName:o.nodeType,kosVersion:o.kosVersion,group:this.groupBy(o.artifacts,"group")}));this.nodes=r})}catch(t){t instanceof me&&this.logger.error("Failed to fetch software-info",t)}}};qo=Zv([R(is)],qo);const Cr={registration:{[is]:{class:qo,singleton:!1}},type:is,predicate:_e(is),factory:ae.Factory.create(is)},{URL:Vu}=ce(),{getOne:Xv}=oe.build({basePath:`${Vu}/api/kos/state`}),Jv=m.createLogger({name:"state-bean-service",group:"Services"}),Gu=async({path:t})=>(Jv.debug("sending GET for state-bean"),await Xv({urlOverride:`${Vu}/api/kos/state/${t}`})),ew=Object.freeze(Object.defineProperty({__proto__:null,getStateBeanData:Gu},Symbol.toStringTag,{value:"Module"}));var tw=Object.defineProperty,sw=Object.getOwnPropertyDescriptor,Yu=(t,e,s,r)=>{for(var o=r>1?void 0:r?sw(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&tw(e,s,o),o};const as="state-bean-model",rw=ht("path");let Dr=class{constructor(t,e,s){l(this,"id");l(this,"path");l(this,"props");l(this,"logger");this.id=t,this.logger=s.logger,this.props=An.map(new Map),Po(e,this)}updateModel(t){Po(t,this)}handleConfigBeanUpdated(t){Object.entries(t).forEach(([e,s])=>{let r=s;typeof r=="string"&&kn(r)&&(r=r.toLowerCase()=="true"),typeof r=="string"&&Xr(r)&&(r=Number(r)),this.props.set(e,r)})}async init(){this.logger.debug(`initializing state-bean ${this.id}`)}updateProps(t){Object.entries(t).forEach(([e,s])=>{this.props.set(e,s)})}async load(){this.logger.debug(`loading state-bean ${this.id}`);const t=await Gu({path:this.path});t!=null&&t.data&&this.updateProps(t.data)}};Yu([H({topic:`/kos/state/${rw}`,websocket:!0})],Dr.prototype,"handleConfigBeanUpdated",1);Dr=Yu([R(as)],Dr);const Ps={registration:{[as]:{class:Dr,singleton:!1}},type:as,predicate:_e(as),factory:ae.Factory.create(as)};var ow=Object.defineProperty,nw=Object.getOwnPropertyDescriptor,Wu=(t,e,s,r)=>{for(var o=r>1?void 0:r?nw(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&ow(e,s,o),o};const cs="state-prop-model",aa=ht("path");let xr=class{constructor(t,e,s){l(this,"id");l(this,"path");l(this,"attribute");l(this,"logger");l(this,"stateBean");this.id=t,this.logger=s.logger,this.path=e.path,this.attribute=e.attribute}get value(){return this.stateBean.props.get(this.attribute)}async init(){this.logger.debug(`initializing state-prop ${this.id}`)}async load(){this.logger.debug(`loading state-prop ${this.id}`)}toString(){var t;return((t=this.value)==null?void 0:t.toString())??""}};Wu([qt({modelType:Ps.type,id:`state-bean-${aa}`,options:{path:aa}})],xr.prototype,"stateBean",2);xr=Wu([R(cs)],xr);const ri={registration:{[cs]:{class:xr,singleton:!1}},type:cs,predicate:_e(cs),factory:ae.Factory.create(cs)},{URL:iw}=ce(),{getAll:aw}=oe.build({basePath:`${iw}/api/state-prop`}),cw=m.createLogger({name:"state-prop-service",group:"Services"}),lw=async()=>(cw.debug("sending GET for state-prop"),await aw({})),uw=Object.freeze(Object.defineProperty({__proto__:null,getStateProps:lw},Symbol.toStringTag,{value:"Module"})),{URL:oi}=ce(),{getOne:Qu}=oe.build({basePath:`${oi}/api/translation`}),Ss=m.createLogger({name:"translation-service",group:"Services"}),dw=()=>{const t=window.location.origin,e=ye();return(e==null?void 0:e.host)||t},Zu=async(t,e)=>{Ss.debug(`Loading translations from: ${t}`);const s=e??dw();try{const r=await fetch(`${s}${t}`);return r.status!==200?(Ss.warn(`Failed to fetch translations at ${t}: ${r.status}`),{}):await r.json()}catch(r){throw Ss.error("Error fetching translations",r),r}},hw=async()=>{Ss.debug("Getting system localization descriptor");const t=await Qu({urlOverride:`${oi}/api/system/kos/localization`});if((t==null?void 0:t.status)!==200)throw new Error(`Failed to get localization descriptor ${t==null?void 0:t.status}`);return t.data},Xu=t=>async()=>{Ss.debug(`Getting KOS localization descriptor for context: ${t}`);const e=await Qu({urlOverride:`${oi}/api/kos/localization/contexts`});if((e==null?void 0:e.status)!==200)throw new Error(`Failed to get KOS localization descriptor ${e==null?void 0:e.status}`);return e.data[t]},Ju="langResolver";var fw=Object.getOwnPropertyDescriptor,pw=(t,e,s,r)=>{for(var o=r>1?void 0:r?fw(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const ls="translation-model";function gw(t){const e=typeof t=="string",s=e?!1:!!(t!=null&&t.data)&&typeof(t==null?void 0:t.data)!="string",r=e?t:t==null?void 0:t.defaultValue,o=e||t==null?void 0:t.context,n=e?void 0:s?t==null?void 0:t.data:t;return{isBasicOptions:e,defaultValue:r,context:o,data:n}}function ed(t,e=""){return Object.keys(t).reduce((s,r)=>{const o=e?`${e}.${r}`:r;if(typeof t[r]=="object"&&t[r]!==null&&!Array.isArray(t[r])){const n=ed(t[r],o);return{...s,...n}}else return{...s,[o]:t[r]}},{})}function td(t,e){const s={...t};for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(typeof e[r]=="object"&&e[r]!==null&&typeof t[r]=="object"&&t[r]!==null?s[r]=td(t[r],e[r]):s[r]=e[r]);return s}const zo=(t,e)=>{const s=/__(.*?)__/g,r=t.replace(s,(o,n)=>Object.prototype.hasOwnProperty.call(e||{},n.trim())?e==null?void 0:e[n.trim()]:o);return r===t?r:s.test(r)?zo(r,e):r},ir=(t,e,s)=>{const r=/{{(.*?)}}/g,n=zo(t,e).replace(r,(a,c)=>Object.prototype.hasOwnProperty.call(s||{},c.trim())?s==null?void 0:s[c.trim()]:a);return zo(n,e)},ca=(t,e)=>{if(e.includes(":")){const[s,r]=e.split(":");return{namespace:s,key:r}}else return{namespace:t,key:e}};let Vo=class{constructor(t,e,s){l(this,"id");l(this,"namespace");l(this,"descriptor");l(this,"defaultLocale");l(this,"currentLocale");l(this,"bundleResolver");l(this,"data");l(this,"logger");l(this,"resolver");l(this,"disposer");l(this,"context");l(this,"rootUrl");this.id=t,this.defaultLocale=e.defaultLocale||"en",this.currentLocale=e.currentLocale||"en",this.namespace=e.namespace,this.descriptor=e.descriptor,this.rootUrl=e.rootUrl,this.data={},this.resolver=e.resolver||s.kosContext.get(Ju),this.bundleResolver=e.bundleResolver,this.logger=s.logger,this.context=s.kosContext.parentModel}getTranslationLocales(t){const e=this.descriptor[t];if(!t||!e)return[this.defaultLocale];if(!this.defaultLocale&&!e.fallbacks)return[t];let s=e.fallbacks||[this.defaultLocale];return s.includes(t)||(s=[t,...s]),s}async loadTranslations(){const t=this.getTranslationLocales(this.currentLocale).reverse(),e=t.map(r=>{if(this.bundleResolver){const o=Y.getContext(this.id);return this.bundleResolver(this.namespace,r,o)}try{const o=this.resolver(this.namespace,r);return Zu(o,this.rootUrl)}catch{return Promise.resolve({})}}),s=await Promise.allSettled(e);J(()=>{const r=s.reduce((o,n,i)=>(n.status==="fulfilled"?(this.logger.debug(`resolved ${t[i]}`,n.value),n.value&&(o=td(o,n.value))):this.logger.error(`failed to load translation ${this.id} for ${t[i]}`),o),{});this.data=ed(r)})}async init(){this.logger.debug(`initializing translation ${this.id}`)}exists(t){const{namespace:e,key:s}=ca(this.namespace,t);if(e!==this.namespace){const r=this.context.getModel(e);return r?r.exists(s):!1}return!!this.data[s]}resolveKey(t,e){if(!t)return this.logger.debug("key is empty"),"";const{defaultValue:s,context:r,data:o}=gw(e),{namespace:n,key:i}=ca(this.namespace,t),a=`${i}_${r}`;if(n!==this.namespace){const c=this.context.getModel(n);return c?c.resolveKey(i,e):i}if(r&&this.data[a]){const c=this.data[a];return Array.isArray(c)?c.map(u=>ir(u,this.data,o)):ir(this.data[a],this.data,o)}if(this.data[i]){const c=this.data[i];return Array.isArray(c)?c.map(u=>ir(u,this.data,o)):ir(this.data[i],this.data,o)}return s??i}unload(){this.logger.debug(`unloading translation ${this.id}`),this.disposer&&this.disposer()}async load(){this.logger.debug(`loading translation ${this.id}`),await this.loadTranslations()}async ready(){this.logger.debug(`ready translation ${this.id}`),this.disposer=M.reaction(()=>this.currentLocale,(t,e)=>{this.logger.info(`translation langs for namespace ${this.id} changed from ${e} to ${t}`),this.loadTranslations()})}};Vo=pw([Yr(),R(ls)],Vo);const Ar={registration:{[ls]:{class:Vo,singleton:!1}},type:ls,predicate:_e(ls),factory:ae.Factory.create(ls)};var mw=Object.defineProperty,yw=Object.getOwnPropertyDescriptor,sd=(t,e,s,r)=>{for(var o=r>1?void 0:r?yw(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&mw(e,s,o),o};const us="translation-container-model",bw=(t,e="/")=>t.join(e).replace(new RegExp(e+"{1,}","g"),e);function vw(t,e){const s=this.descriptor.namespaces[t];if(!s)throw new Error("namespace "+t+" not found in descriptor");const r=s.basePath,o=s.locales[e].file;return bw([r,o])}let Rr=class{constructor(t,e,s){l(this,"id");l(this,"lang");l(this,"rootUrl");l(this,"descriptor");l(this,"_defaultNamespace");l(this,"resolver");l(this,"logger");l(this,"descriptorUrl");l(this,"namespaces",[]);l(this,"_models");this.id=t,this.lang=e.lang||"en",this.descriptor=e.descriptor,this._defaultNamespace=e.defaultNamespace,this.descriptorUrl=e.descriptorUrl,this.rootUrl=e.rootUrl,this.resolver=e.resolver||vw.bind(this),s.kosContext.set(Ju,this.resolver),this.logger=s.logger,this._models=new xe({parentId:t})}set currentLocale(t){this.lang=t,this.models.data.forEach(e=>{e.currentLocale=t})}get defaultNamespace(){return this._defaultNamespace?this.getModel("translation-"+this._defaultNamespace):void 0}getModel(t){return this.logger.debug("getting model "+t),this._models.getModel("translation-"+t)}get models(){return this._models}get data(){return this._models.data}async reload(){for(const t of this.namespaces){const e=this.resolveNamespace(t);await he(e)}}resolveNamespace(t){var s;if((s=this.descriptor.namespaces)==null?void 0:s[t]){const r=Object.keys(this.descriptor.namespaces[t].locales)[0],o=this.descriptor.namespaces[t].locales[r].defaultLocale,n=Ar.factory("translation-"+t)({kosParentId:this.id,namespace:t,rootUrl:this.rootUrl,currentLocale:this.lang,defaultLocale:o,descriptor:this.descriptor.namespaces[t].locales,resolver:this.resolver});return this.addModel(n),this.namespaces.includes(t)||J(()=>{this.namespaces.push(t)}),n}else{this.logger.warn("namespace "+t+" not found in descriptor");const r=Ar.factory("translation-"+t)({kosParentId:this.id,namespace:t,rootUrl:this.rootUrl,currentLocale:this.lang,defaultLocale:this.lang,descriptor:{},resolver:this.resolver});return this.addModel(r),r}}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}async init(){this.logger.debug("initializing translation-container container "+this.id)}async load(){this.logger.debug("loading translation-container container "+this.id)}};sd([De],Rr.prototype,"_models",2);Rr=sd([R(us)],Rr);const Ue={registration:{[us]:{class:Rr,singleton:!0}},type:us,predicate:_e(us),factory:ae.Singleton.create(us)},ww={set(t,e){const s=Y.getContext(Ue.type);s&&s.set(t,e)},get(t){const e=Y.getContext(Ue.type);return e==null?void 0:e.get(t)}},rd={async init(t){const e=Ue.factory(t);return await he(e),{translations:e}}};function Ew(t){return(t==null?void 0:t.troubles)!==void 0&&(t==null?void 0:t.troubles)instanceof Array&&(t==null?void 0:t.troublesByType)!==void 0&&typeof(t==null?void 0:t.troublesByType)=="object"}const od="kos-ws-event",ni=zt(od);var Mw=Object.defineProperty,Tw=Object.getOwnPropertyDescriptor,ii=(t,e,s,r)=>{for(var o=r>1?void 0:r?Tw(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Mw(e,s,o),o};const _w=({headers:t,body:e})=>Object.entries(t).map(([r,o])=>`${r}:${o}`).join("\\n")+"\\n\\n"+e;exports.WsEventModel=class{constructor(e){l(this,"id");l(this,"events");l(this,"_topicMap");this.id=e,this.events=M.observable.map(new Map),this._topicMap=new Map}get websocketEvents(){return Array.from(this.events.values())}handleSendEvent(e,s){this.processEvent(s,!0)}handleReceiveEvent(e,s){this.processEvent(s)}processEvent(e,s=!1){m.debug("kos event received");const{body:r,headers:o}=e.body,n=o["request-id"]||o["response-id"],i=o["request-id"]||o["response-id"]||o.topic||o.type;if(i){let a=i;if(n)a=`${a}-${s?"send":"receive"}`;else{const u=this._topicMap.get(i)||0;a=`${a}-${u+1}`,this._topicMap.set(i,u+1)}const c={msgId:a,content:r,headers:o,timestamp:Date.now(),raw:_w({headers:o,body:r}),direction:s?"send":"receive",mocked:!!o.mocked};this.events.set(a,c),m.debug(`logged ${this.events.size} events`)}}};ii([H({topic:[Us.SEND]})],exports.WsEventModel.prototype,"handleSendEvent",1);ii([H({topic:[Us.RECEIVED]})],exports.WsEventModel.prototype,"handleReceiveEvent",1);exports.WsEventModel=ii([R(ni.type)],exports.WsEventModel);const la=ye(),Sw=la.debug==="true"||la.debug===!0,Iw="/api/system/canvas",nd=async(t,e)=>{const s=e||Iw,r=`${exports.BASE_URL}${s}`;await exports.kosFetch(r,{method:"POST",headers:{hide:Sw?"false":"true"},body:t})},Ow=Object.freeze(Object.defineProperty({__proto__:null,sendCanvasData:nd},Symbol.toStringTag,{value:"Module"}));function ua(t,e,s){{const r=t.filter((o,n)=>n%4!==3);return btoa(String.fromCharCode(...r))}}var $w=Object.defineProperty,Cw=Object.getOwnPropertyDescriptor,id=(t,e,s,r)=>{for(var o=r>1?void 0:r?Cw(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&$w(e,s,o),o};const ad="canvas-renderer-model";function Co(t){return typeof t.onDone=="function"}let Pr=class{constructor(t,e,s){l(this,"id");l(this,"router");l(this,"logger");l(this,"_renderer",null);l(this,"_clearOnComplete");l(this,"isStreaming",!1);l(this,"renderLoopId",null);l(this,"sendIntervalId",null);l(this,"timeoutId",null);l(this,"apiPath");l(this,"endpointName");l(this,"width",50);l(this,"height",30);l(this,"fps",10);l(this,"durationMs",null);l(this,"_onFrame",null);this.id=t,this.logger=s.logger,this.width=e.width??50,this.height=e.height??30,this.fps=e.fps??10,this.durationMs=e.durationMs??null,this.apiPath=e.apiPath??"/api/system/canvas",this.endpointName=e.endpoint}set onFrame(t){this._onFrame=t}set renderer(t){var e,s;this._renderer&&(this.stopStreaming(),(s=(e=this._renderer).dispose)==null||s.call(e)),this._renderer=t,this.isStreaming&&this.startStreaming()}setClearOnComplete(t){this._clearOnComplete=t}sendDataFrame(t,e){nd(t,e)}checkStreaming(){if(this.isOneShotDone()||!this.isStreaming){requestAnimationFrame(()=>{const t=this.isOneShotDone();this.stopStreaming(!t)});return}}handleFrame(t){var s;const e=ua(t);this.sendDataFrame(e,this.apiPath),(s=this._onFrame)==null||s.call(this,e)}stopStreaming(t=!0){var e,s;this.logger.debug(`stopStreaming called with clearCanvas=${t}`),this.isStreaming=!1,this.renderLoopId&&cancelAnimationFrame(this.renderLoopId),this.sendIntervalId&&clearInterval(this.sendIntervalId),this.timeoutId&&clearTimeout(this.timeoutId),(s=(e=this._renderer)==null?void 0:e.pause)==null||s.call(e),t&&(this.logger.debug("Clearing canvas..."),this.clearCanvas())}clearCanvas(){var s;const t=this.width>0?this.width:50,e=this.height>0?this.height:30;if(t>0&&e>0){const r=t*e*4,o=new Uint8ClampedArray(r);for(let i=3;i<r;i+=4)o[i]=255;const n=ua(o);this.logger.debug(`Sending clear frame: ${t}x${e}, apiPath: ${this.apiPath}`),this.sendDataFrame(n,this.apiPath),(s=this._onFrame)==null||s.call(this,n)}}isOneShotDone(){var t,e;return Co(this._renderer)&&((e=(t=this._renderer).isOneShot)==null?void 0:e.call(t))===!0&&this._renderer.isOneShotDone}startStreaming(){var t,e,s,r;{if(!this._renderer)return;if(!this.apiPath){this.logger.error(`No endpoint configured for canvas renderer ${this.id}`);return}this.isStreaming=!0,this._renderer.reset(),(e=(t=this._renderer).play)==null||e.call(t);const o=Co(this._renderer);Co(this._renderer)&&this._renderer.onDone(()=>{var c,u,d;this.logger.debug(`Renderer completed for ${this.id}`),V("/canvas/renderer/completed",{endpoint:this.endpointName,rendererId:this.id,rendererType:(c=this._renderer)==null?void 0:c.constructor.name,timestamp:Date.now()});let a=!0;this._clearOnComplete!==void 0?a=this._clearOnComplete:a=!(((d=(u=this._renderer)==null?void 0:u.isOneShot)==null?void 0:d.call(u))??!1),this.stopStreaming(a)}),this._renderer.renderFrame(this.width,this.height);const n=(r=(s=this._renderer).readPixels)==null?void 0:r.call(s,this.width,this.height);if(n&&this._onFrame&&this.handleFrame(n),this.isOneShotDone()){requestAnimationFrame(()=>{this.stopStreaming(!1)});return}const i=()=>{var a;(a=this._renderer)==null||a.renderFrame(this.width,this.height),this.renderLoopId=requestAnimationFrame(i)};this.renderLoopId=requestAnimationFrame(i),this.sendIntervalId=setInterval(()=>{var c,u;const a=(u=(c=this._renderer)==null?void 0:c.readPixels)==null?void 0:u.call(c,this.width,this.height);a&&this._onFrame&&(this.handleFrame(a),this.checkStreaming())},1e3/this.fps),!o&&this.durationMs!=null&&(this.timeoutId=setTimeout(()=>{this.stopStreaming()},this.durationMs))}}async init(){this.logger.debug(`initializing canvas-renderer ${this.id}`)}async load(){this.logger.debug(`loading canvas-renderer ${this.id}`),this.router.use("POST",`/api/ui/canvas/${this.endpointName}/stop`,async(t,e)=>{this.logger.debug(`HTTP stop endpoint called for ${this.endpointName}`),this.stopStreaming(),e.send({status:"OK"})}),this.router.use("POST",`/api/ui/canvas/${this.endpointName}/start`,async(t,e)=>{this.startStreaming(),e.send({status:"OK"})})}};id([qt({modelType:Kn.type})],Pr.prototype,"router",2);Pr=id([R(ad)],Pr);const ai=new be({class:Pr,type:ad});class cd{constructor({src:e}){l(this,"video");l(this,"canvas");l(this,"ctx");l(this,"lastUpdate",0);l(this,"doneCallback",null);this.video=document.createElement("video"),this.video.src=e,this.video.crossOrigin="anonymous",this.video.muted=!0,this.video.loop=!1,this.canvas=document.createElement("canvas");const s=this.canvas.getContext("2d");if(!s)throw new Error("2D canvas not supported");this.ctx=s,this.handleEnded=this.handleEnded.bind(this),this.video.addEventListener("ended",this.handleEnded)}handleEnded(){this.doneCallback&&this.doneCallback()}reset(){this.video.pause(),this.video.currentTime=0,this.lastUpdate=performance.now()}play(){this.video.play().catch(console.warn)}pause(){this.video.pause()}renderFrame(e,s){this.canvas.width=e,this.canvas.height=s,this.video.readyState>=2&&this.ctx.drawImage(this.video,0,0,e,s)}readPixels(e,s){return this.ctx.getImageData(0,0,e,s).data}onDone(e){this.doneCallback=e}dispose(){this.video.pause(),this.video.removeAttribute("src"),this.video.load(),this.video.remove(),this.video.removeEventListener("ended",this.handleEnded),this.doneCallback=null}shouldStep(e){const s=performance.now();return s-this.lastUpdate>=e?(this.lastUpdate=s,!0):!1}}class Dw{constructor(){l(this,"canvas");l(this,"gl");l(this,"lastWidth",0);l(this,"lastHeight",0);l(this,"lastUpdate",0);this.canvas=document.createElement("canvas");const e=this.canvas.getContext("webgl");if(!e)throw new Error("WebGL not supported");this.gl=e}shouldStep(e){const s=performance.now();return s-this.lastUpdate>=e?(this.lastUpdate=s,!0):!1}readPixels(e=this.lastWidth,s=this.lastHeight){const r=new Uint8Array(e*s*4);this.gl.readPixels(0,0,e,s,this.gl.RGBA,this.gl.UNSIGNED_BYTE,r);const o=new Uint8ClampedArray(r.length);for(let n=0;n<s;n++){const i=n*e*4,a=(s-1-n)*e*4;o.set(r.subarray(i,i+e*4),a)}return o}}class xw extends Dw{constructor({speedPx:s=1}={}){super();l(this,"program");l(this,"posBuffer");l(this,"aPosition");l(this,"uMinHue");l(this,"uMaxHue");l(this,"uHueOffset");l(this,"uGridHeight");l(this,"minHue",0);l(this,"maxHue",80);l(this,"hueOffset",0);l(this,"speedPx",1);this.speedPx=s;const r=this.gl,o=`