@kosdev-code/kos-ui-sdk 0.1.0-dev.5638 → 0.1.0-dev.5644
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 +2 -2
- package/index.cjs.map +1 -1
- package/index.js +7 -7
- package/index.js.map +1 -1
- package/models/models/config-bean/config-bean-model-builder.d.ts.map +1 -1
- package/models/services/config-bean/index.d.ts +1 -0
- package/models/services/config-bean/index.d.ts.map +1 -1
- package/package.json +2 -2
package/index.cjs
CHANGED
|
@@ -104,10 +104,10 @@ 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:(g=this.socket)==null?void 0:g.connectionEstablished){const E=r?this.fosSocket:this.socket;(w=E==null?void 0:E.socket)==null||w.send(d)}else{nt.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 nt.debug(`Topic ${e} currently has ${a} subscribers`),this._sendSubscriptionMessage(e,"subscribe",r,o,n),()=>{const{count:c}=i();nt.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(Pt,"_instance");class gm{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===D.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=Pt.getInstance().subscribeTopic({topic:s,callback:r,fos:e.fos,bridge:e.bridge,destinationAddress:n});o?this.activatableDisposers.push(i):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=Ko(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=Ko(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||!Bc(e))return null;const o=((n=s==null?void 0:s.headers)==null?void 0:n.topic)||"";return jc(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 am(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===D.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;Pt.getInstance().subscribeTopic({topic:s,callback:()=>{},fos:e.fos,bridge:e.bridge,destinationAddress:a}),i=Vi(s)}else i=Vi(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||ht.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 _t(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 mm(t){return!!(t!=null&&t[Ue])&&Object.keys(t[Ue]).length>0}function ym(t){return!!(t!=null&&t[ee])&&Object.keys(t[ee]).length>0}function bm(t){return!!(t!=null&&t[je])&&t[je].length>0}function vm(t){const e=Object.getPrototypeOf(t);return!!(e!=null&&e[ft])&&Object.keys(e[ft]).length>0}function wm(t){return t.retention===oe.TTL&&t.extendOnRefresh===!0&&t.ttl!==void 0}function Em(t,e){return t.has(e)}function Mm(t){return!t.expiresAt||Date.now()<t.expiresAt}function Wi(t,e,s,r){const o=setTimeout(()=>r(t),e);s.set(t,o)}class Tm{constructor(){l(this,"responses",new Map);l(this,"retentionPolicies",new Map);l(this,"cleanupTimers",new Map)}set(e,s,r={retention:oe.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)===oe.IMMEDIATE}shouldExtendTTL(e,s){if(!wm(s)||!Em(this.responses,e))return!1;const r=this.responses.get(e);return Mm(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),Wi(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===oe.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 oe.IMMEDIATE:break;case oe.TTL:s.ttl&&Wi(e,s.ttl,this.cleanupTimers,r=>this.delete(r));break;case oe.SINGLE:break;case oe.PERMANENT:case oe.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 _m{static createAll(e){const{modelId:s,modelTypeName:r,modelData:o}=e,n=_c.create({modelId:s,modelTypeName:r}),i=new Dg(e,_t(n,"fsm")),a=new Ag(_t(n,"offline-queue")),c=new Mg(e),u=new Eg(e),d=new Tm;o.serviceResponses=d;const h={fsm:i,offlineQueue:a,serviceResponseStore:d,companionManager:c,childResolver:u};if(mm(o)&&(h.effectManager=new Tg(r,s,o,_t(n,"effect"))),ym(o)){const f=_t(n,"subscription");h.subscriptionManager=new gm(e,o,s,a,f),h.onlineLifecycleManager=new Rg(e,_t(n,"online"))}return bm(o)&&(h.httpRouteManager=new An(o,_t(n,"http-routes"))),vm(o)&&(h.serviceRequestManager=new nm(o,d)),h}}const U=x.getLogger("kos-model"),Sm="kos.extension.model.loader";class vl{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=_m.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}),vg(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;U.debug(`deactivating model ${this.modelTypeName} with id ${this.modelId}`);try{const o=W.getContext(this.modelId);await((s=(e=this.modelData)==null?void 0:e.deactivate)==null?void 0:s.call(e,o)),U.debug(`Model ${this.modelTypeName} with id ${this.modelId} deactivated`),(r=this.subscriptionManager)==null||r.deactivate()}catch(o){throw U.debug(`Model ${this.modelId} failed to deactivated`),o}}async activate(){var e,s,r,o;U.debug(`activating model ${this.modelTypeName} with id ${this.modelId}`),await is(this,D.ACTIVATE);try{await((e=this.serviceRequestManager)==null?void 0:e.executeForLifecycle(D.ACTIVATE));const n=W.getContext(this.modelId);await((r=(s=this.modelData)==null?void 0:s.activate)==null?void 0:r.call(s,n)),this.initializeStateMachineForLifecycle(D.ACTIVATE),U.debug(`Model ${this.modelTypeName} with id ${this.modelId} subscribing to all topics`),(o=this.subscriptionManager)==null||o.registerAll(D.ACTIVATE),this.createLifecycleCompanions(D.ACTIVATE),U.debug(`Model ${this.modelTypeName} with id ${this.modelId} activated`)}catch(n){throw U.debug(`Model ${this.modelId} failed to activate`),n}}async whenLoaded(){await Co([{condition:()=>this.status===v.FAILED,onMatch:()=>{throw new Error(`Failed to initialize model ${this.modelId}`)}},{condition:()=>this.loaded,onMatch:()=>{U.debug(`Model ${this.modelId} is loaded`)}}])}async whenInitialized(){await Co([{condition:()=>this.status===v.FAILED,onMatch:()=>{throw new Error(`Failed to initialize model ${this.modelId}`)}},{condition:()=>this.initialized,onMatch:()=>{U.debug(`Model ${this.modelId} is initialized`)}}])}async whenReady(){await Co([{condition:()=>this.status===v.FAILED,onMatch:()=>{throw new Error(`Failed to ready model ${this.modelId}`)}},{condition:()=>this.status===v.READY,onMatch:()=>{U.debug(`Model ${this.modelId} is ready`)}}])}async ready(){var e,s,r,o;if(this.fsm.current===v.READY){U.debug(`already readying model ${this.modelTypeName} with id ${this.modelId} returning`);return}try{U.debug(`readying model ${this.modelTypeName} with id ${this.modelId}`),await is(this,D.READY),await el(this,Dn.READY,D.READY),await((e=this.serviceRequestManager)==null?void 0:e.executeForLifecycle(D.READY));const n=W.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(D.READY),(o=this.subscriptionManager)==null||o.registerAll(D.READY),this.createLifecycleCompanions(D.READY),U.debug(`Model ${this.modelId} is ready`);const i={modelId:this.modelId,modelType:this.modelTypeName};K(zc(this.modelTypeName,this.modelId),i),K(Vc(this.modelTypeName),i)}catch(n){throw U.error(n),Error(n)}}async load(){var o,n,i,a,c,u;const e=this[Xe];e&&await e.whenLoaded();const{modelTypeName:s,modelId:r}=this;if(this.fsm.current===v.LOADED){U.debug(`Model ${s} with id ${r} already loaded`);return}if(this._isLoadExecuting){U.debug(`Model ${s} with id ${r} is currently executing load`);return}this._isLoadExecuting=!0;try{U.debug(`Loading model ${s} with id ${r}`),await is(this,D.LOAD);const d=W.getContext(r),h=`${Sm}.${s}`,f=await $.loader.executeLoader(h,{});f&&(U.info(`Setting loaded context for ${r}, type: ${s}`),d==null||d.set(h,f)),await((o=this.serviceRequestManager)==null?void 0:o.executeForLifecycle(D.LOAD)),await((i=(n=this.modelData)==null?void 0:n.load)==null?void 0:i.call(n,d)),J(()=>{this.loaded=!0}),U.debug(`Model ${s} with id ${r} successfully loaded`),this.initializeStateMachineForLifecycle(D.LOAD),(a=this.subscriptionManager)==null||a.registerAll(D.LOAD),(c=this.httpRouteManager)==null||c.registerAll(),(u=this.effectManager)==null||u.setup(),this.createLifecycleCompanions(D.LOAD)}catch(d){throw U.error(`Model ${r} failed to load`,d),d}finally{this._isLoadExecuting=!1}}async unload(){var e,s,r,o,n,i,a;U.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=W.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=[])}U.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 U.debug(`Model ${this.modelId} failed to unload`),c}}async init(){var n,i,a,c;const e=this[Xe];e&&await e.whenInitialized();const{modelId:s,modelTypeName:r}=this,o=W.getContext(s);U.debug(`Initializing model ${r} with id ${s}`),await is(this,D.INIT);try{await((n=this.serviceRequestManager)==null?void 0:n.executeForLifecycle(D.INIT)),await((a=(i=this.modelData)==null?void 0:i.init)==null?void 0:a.call(i,o)),this.initialized=!0,U.debug(`Model ${r} with id ${s} initialized`),(c=this.onlineLifecycleManager)==null||c.register(),this.initializeStateMachineForLifecycle(D.INIT),this.registerSubscribers(D.INIT),this.createLifecycleCompanions(D.INIT)}catch(u){throw U.error(`Model ${s} failed to initialize`,u),u}}async registerSubscribers(e){var s;U.debug(`registering subscribers in ${this.modelTypeName} with id ${this.modelId}`),(s=this.subscriptionManager)==null||s.registerAll(e)}initializeStateMachineForLifecycle(e){this.modelData&&vc(this.modelData,e)}createLifecycleCompanions(e){this.modelManager.createLifecycleCompanions(this,{},e)}async online(){var s,r;U.debug(`online model ${this.modelTypeName} with id ${this.modelId}`),this.registerSubscribers();const e=W.getContext(this.modelId);await((r=(s=this.modelData)==null?void 0:s.online)==null?void 0:r.call(s,e)),this.createLifecycleCompanions(D.ONLINE)}async offline(){var s,r,o;U.debug(`offline model ${this.modelTypeName} with id ${this.modelId}`),(s=this.subscriptionManager)==null||s.disposeAll();const e=W.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 Do=m.createLogger({name:"kos-model-instantiator"});class Om{constructor(e,s){l(this,"companionInstantiator");this.registry=e,this.cache=s,this.companionInstantiator=new hg(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 Do.error(c,{modelType:e,requestedId:s,providedOptions:r,availableModelTypes:Object.keys(this.registry.models)}),At(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)){Do.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[Ks])===!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"}),At(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 vl({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"}),At(h,{modelType:e,modelId:n,operation:"model instantiation",options:r})}}const i=this.cache.getModelById(n);if(!i)throw Do.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 Im=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 Qt(e)}};const wl=10,Qi=m.createLogger({name:"kos-model-manager"});class El{constructor(){l(this,"cache");l(this,"instantiator");l(this,"dependencies");l(this,"_registry");globalThis.kos=globalThis.kos||{},this.dependencies=new lg,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 Im(e),r.cache=new ug(e.preloadModels),r.instantiator=new Om(e,r.cache),r}static getInstance(e){var s,r;return(!((s=globalThis.kos)!=null&&s.modelManager)||e)&&(Qi.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=>(Qi.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 Qt(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),Kc.addToDeletionQueue(e.id,setTimeout(()=>this.destroyModel(s),wl)))}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 gr=(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))(gr||{}),ct=(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))(ct||{});const $m=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=>x.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=>x.debug(n.machine.current)),online:s}},Y=m.createLogger({name:"kos-core"}),Cm=()=>{const t=be(),e=t==null?void 0:t.alias,s=process.env.KOS_CONNECTION_ALIAS;return e||s||void 0},Dm=()=>{const t=window.location.protocol,e=be(),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://")},xm=()=>{const t=window.location.hostname,e=process.env.KOS_HOST,s=be(),r=s==null?void 0:s.host;let o;try{o=new URL(r).hostname}catch{}return o??e??t},Am=()=>{const t=window.location.port,e=process.env.KOS_PORT,s=be(),r=s==null?void 0:s.host;let o;try{o=new URL(r).port}catch{}return o??e??t},Rm=(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)}}},Zi=t=>typeof t.reload=="function",Pm=t=>typeof t.unload=="function";var Ml=(t=>(t.LOGGED_IN="logged_in",t.LOGGED_OUT="logged_out",t))(Ml||{});class S{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=gr.CREATED,this.authState="logged_out",this._reloading=!1,this._unloading=!1,M.makeAutoObservable(this),C("token",a=>{a&&(this.transport.token=a.body)}),C(Te.CONNECTED,async()=>{await this.whenReady(),this.fsmService.service.send(ct.GO_ONLINE)}),C(Te.DISCONNECTED,async()=>{this.fsmService.service.send(ct.GO_OFFLINE)}),C("/studioServer/auth/LOGGED_IN",()=>{this.authState="logged_in",this.transport.authorized=!0,this.fsmService.service.send(ct.RELOAD)}),C("/studioServer/auth/LOGIN_REQUIRED",()=>{this.authState="logged_out",this.transport.authorized=!1}),C(Te.RELOAD,()=>{Y.warn("WebSocket requested reload"),this.fsmService.service.send(ct.RELOAD)}),C("/studio/project/reload",()=>{Y.warn("Project requested reload"),this.fsmService.service.send(ct.RELOAD)});const s=Pt.getInstance(),r=xm(),o=Am(),n=Dm();s.host=r,s.port=Number.parseInt(o),s.protocol=n,process.env.KOS_ALLOW_ANONYMOUS==="true"&&(s.authorized=!0);const i=Cm()??e;i&&(s.alias=i.replace("{{TIMESTAMP}}",Date.now().toString())),this._transport=s.init(),this.fsmService=$m(this),this.fsmService.service.send(ct.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){Y.info("reload already in progress");return}this._reloading=!0,Y.warn("reloading KOS Core"),Y.warn("reloading preloaded models");const s=this.modelManager;for(const c of s.preloadedModels)Zi(c.modelData)&&(Y.info(`reloading model ${c.modelId}`),(o=c.unload)==null||o.call(c),await c.modelData.reload(),(n=c.registerSubscribers)==null||n.call(c),Y.info(`reloading model ${c.modelId} complete`));for(const c of s.models)!s.preloadedModels.includes(c)&&Zi(c.modelData)&&(Y.warn(`reloading model ${c.modelId}`),(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(()=>{Y.warn("reloading KOS Core complete"),this._reloading=!1})},1e3-r)}async online(){Y.debug("KOS Core going online"),await this._transport.whenReady(),Y.debug("KOS Transport Ready. Calling online() for models"),K("/kosCore/online","/kosCore/online"),console.timeEnd("kosCore:startup")}async offline(){Y.debug("KOS Core going offline"),K("/kosCore/offline","/kosCore/offline")}async unload(){var o;Y.debug("Unloading KOS Core");const e=Date.now();this._unloading=!0,Y.debug("unloading KOS Core");const s=this.modelManager;for(const n of s.models)Pm(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===gr.READY)}async ready(){Y.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}=Rm(5e3,o.model);Promise.race([o.promise.then(()=>{i()}),n])}))).filter(o=>o.status==="rejected");if(r.length)throw Y.error(`There were ${r.length} failed models on model preloading`),Error(`There were ${r.length} failed models on model preloading`);Y.debug("leaving kos-core ready() ")}get isReady(){return this.status===gr.READY}set transport(e){this._transport=e}get transport(){return this._transport}get coreInitialized(){return this.initialized}get modelsLoaded(){return this.loaded}async init(){Y.debug("entering kos-core init()"),console.time("kosCore:startup"),console.time("kosCore:init"),await this._transport.whenReady(),this.initialized=!0,Y.debug("initialized - leaving kos-core init()"),console.timeEnd("kosCore:init")}async load(){Y.debug("entering kos-core load()"),console.time("kosCore:load"),this.loaded=!0,Y.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 g=p.class.prototype[Xe];f=g==null?void 0:g.lifecycle}}e.companionModels[u].push({type:h,lifecycle:f})}}),A.model.getPreloadModels().forEach(u=>{e.preloadModels.includes(u)||e.preloadModels.push(u)});const n=El.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(S,"_instance");const km=m.createLogger({name:"kos-model-visitor",group:"kos-ui-core"});class Tl{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=S.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)){km.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 Lm extends Tl{constructor(s){super();l(this,"targetId");l(this,"currentPath",[]);l(this,"foundPath",null);this.targetId=s}visit(s){var o;if(this.visitedModels.has(s.modelId))return;this.currentPath.push(s.modelId),this.visitedModels.add(s.modelId),!!this.visitModel(s.modelData)||(o=s.getChildren)==null||o.call(s).forEach(n=>{var i;this.foundPath||(i=n.accept)==null||i.call(n,this)}),this.foundPath||this.currentPath.pop()}visitModel(s){return s.id===this.targetId?(this.foundPath=this.currentPath.slice(0,-1),!0):!1}getAncestorPath(){return this.foundPath??[]}wasFound(){return this.foundPath!==null}}function Fm(t,e){e.forEach(s=>{Object.getOwnPropertyNames(s.prototype).forEach(r=>{const o=Object.getOwnPropertyDescriptor(s.prototype,r);Object.defineProperty(t.prototype,r,o)})})}function Nm(t,e){const s=t??[],r=e??[];return s.length!==r.length?!1:s.every((o,n)=>o===r[n])}const Rn=(t,e)=>{const s=t.map(n=>n.id);return e.map(n=>n.id).filter(n=>!s.includes(n))},_l=t=>t,Pn=t=>t,Um=({container:t,onAddItem:e,onUpdateItem:s,onRemoveItem:r=_l,idMapper:o=Pn})=>n=>{const i=n.map(o),c=Rn(i,t.data).map(r).filter(Boolean);t.removeAll(c);const u=i.map(d=>{const h=t.getModel(d.id);return h&&s?s(d,h):e(d)}).filter(Boolean);t.addAll(u)},jm=({container:t,onAddItem:e,onRemoveItem:s=_l,idMapper:r=Pn})=>o=>{const n=o.map(r);Rn(n,t.models).forEach(s),n.forEach(e)},Bm=({items:t,onAddItem:e,onRemoveItem:s,idMapper:r=Pn})=>o=>{const n=o.map(r);Rn(n,t).forEach(s),n.forEach(e)},Hm=(t,e="parent-")=>{let s=t;return s.startsWith(e)&&(s=s.replace(e,"")),s},Xi=new Intl.RelativeTimeFormat(void 0,{numeric:"auto"}),Ji=[{amount:60,name:"seconds"},{amount:60,name:"minutes"},{amount:24,name:"hours"},{amount:7,name:"days"},{amount:4.34524,name:"weeks"},{amount:12,name:"months"},{amount:Number.POSITIVE_INFINITY,name:"years"}];function Sl(t){let e=(t.getTime()-Date.now())/1e3;for(let s=0;s<=Ji.length;s++){const r=Ji[s];if(Math.abs(e)<r.amount)return Xi.format(Math.round(e),r.name);e/=r.amount}return Xi.format(Math.round(e),"years")}const kn=t=>t%4===0&&t%100!==0||t%400===0,Ln=(t,e)=>[31,kn(t)?29:28,31,30,31,30,31,31,30,31,30,31][e],Ol=(t,e)=>{const s=new Date(t),r=t.getDate();return s.setDate(1),s.setMonth(s.getMonth()+e),s.setDate(Math.min(r,Ln(s.getFullYear(),s.getMonth()))),s},Il=(t,e)=>{const s=new Date(t);return s.setDate(s.getDate()+e),s},kt="en-US",$l={short:{year:"numeric",month:"2-digit",day:"2-digit"},medium:{year:"numeric",month:"short",day:"2-digit"},long:{year:"numeric",month:"long",day:"numeric"},full:{year:"numeric",month:"long",day:"numeric",weekday:"long"}},Cl={short:{hour:"2-digit",minute:"2-digit",hour12:!0},medium:{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!0},long:{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!0,timeZoneName:"short"},full:{hour:"2-digit",minute:"2-digit",hour12:!0,timeZoneName:"long"}},Dl=(t,{dateStyle:e="short",locales:s=kt}={dateStyle:"short",locales:kt})=>{const r=e==="short"?$l.short:{dateStyle:e};return new Intl.DateTimeFormat(s,r).format(t)},xl=(t,{locales:e=kt,timeStyle:s="short"}={locales:kt,timeStyle:"short"})=>{const r=Cl[s];return new Intl.DateTimeFormat(e,r).format(t)},Al=(t,{dateStyle:e="short",locales:s=kt,timeStyle:r="short"}={dateStyle:"short",locales:kt,timeStyle:"short"})=>{const o={...e&&$l[e],...r&&Cl[r]};return new Intl.DateTimeFormat(s,o).format(t)},Km=Object.freeze(Object.defineProperty({__proto__:null,addDaysToDate:Il,addMonthsToDate:Ol,formatDate:Dl,formatDateSince:Sl,formatDateTime:Al,formatTime:xl,getDaysInMonth:Ln,isLeapYear:kn},Symbol.toStringTag,{value:"Module"})),Rl="featureFlagResolver",rr=new Map;zs(Rl,{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[];const r=s.map(a=>a(e)),n=(await Promise.allSettled(r)).map(a=>a.status==="fulfilled"?a.value:(m.info(`Feature flag resolver ${t} failed: ${a.reason}`),[])).flat(),i=Array.from(new Set(n)).reduce((a,c)=>(a[c]=!0,a),{});return kl.updateFlags(i),Object.keys(i)}});const qm="kos.loader.featureFlag";class Pl{constructor(e={}){l(this,"flags",{});this.flags=e}isFeatureEnabled(e){return!!this.flags[e]}enableFeature(e){this.flags[e]=!0}disableFeature(e){this.flags[e]=!1}toggleFeature(e){this.flags[e]=!this.flags[e]}updateFlags(e){this.flags={...this.flags,...e}}}window.KosFeatureFlags=window.KosFeatureFlags??new Pl;const kl=window.KosFeatureFlags,Ll=(t,e,s)=>{s/=100;const r=e*Math.min(s,1-s)/100,o=n=>{const i=(n+t/30)%12,a=s-r*Math.max(Math.min(i-3,9-i,1),-1);return Math.round(255*a).toString(16).padStart(2,"0")};return`#${o(0)}${o(8)}${o(4)}`},Fl=t=>{const s=new RegExp("hsl\\((\\d+),\\s+(\\d+)\\%,\\s+(\\d+)\\%\\)").exec(t);if(!s)throw Error("Invalid HSL string");return Ll(parseInt(s[1]),parseInt(s[2]),parseInt(s[3]))},Nl=(t,e)=>getComputedStyle(t).getPropertyValue(e),zm=(t,e)=>Fl(Nl(t,e)),Vm=(t,e)=>{const s={...t};return s.id&&delete s.id,s},zo=(t,e,s=Vm)=>{const r=s(t,e);M.runInAction(()=>{Object.assign(e,r)})};class Ul{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 Gm=async(t,e)=>{const s=new Ul;e.forEach(o=>s.use(o));const r={data:t,result:{}};return await s.execute(r),r.result},Qt=t=>({type:t,build:(e,s)=>S.getInstance().modelManager.createModelInstance(t,e,s).data,buildAsync:async(e,s)=>{const r=S.getInstance().modelManager.createModelInstance(t,e,s);return await r.model.whenInitialized(),r.data}}),Ym=t=>{S.getInstance().modelManager.registerModel(t)},Wm=(t,e)=>{S.getInstance().modelManager.registerCompanionModel(t,e)},ea="/kos/ui/internal/heartbeat/",Qm=({relationshipId:t,destinationAddress:e,onAbort:s,waitTime:r,beatTime:o})=>{const n=S.getInstance().transport,i=new AbortController;let a=performance.now();const c=n.subscribeTopic({topic:`${ea}${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(()=>{fl({msg:{},options:{topic:`${ea}${t}`,destinationAddress:e}})},h),p=()=>{window.clearInterval(f),window.clearInterval(d),c()},g=()=>{p(),s&&s(),i.signal.removeEventListener("abort",g)};return i.signal.addEventListener("abort",g),{cleanUpHeartbeat:p}},jl=(...t)=>e=>t.reduce((s,r)=>r(s),e),Zm={maxAttempts:5,baseDelayMs:100,backoffFactor:1.5};async function Xm(t,e){let s=1;const r={...Zm,...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 Jm=m.createLogger({name:"kos-service-request"}),ue=t=>({isMock:!1,URL:exports.BASE_URL}),ey=(t,e,s)=>async({id:r,tracker:o,urlOverride:n,ordered:i,studio:a,fos:c,bridge:u,timeout:d,signal:h,destinationAddress:f})=>{const p={method:"DELETE"};t&&(p.destinationAddress=t),o&&(p.tracker=o),Zt(p,{ordered:i,studio:a,fos:c,bridge:u,timeout:d,signal:h,destinationAddress:f});try{const g=await s(n||`${e}/${r}`,p);if(!g.ok)throw Error(`There was a problem deleting the model; returned status ${g.status}`);return await g.json()??void 0}catch(g){if(g instanceof DOMException){if(g.name==="TimeoutError")throw new z("Request timed out while deleting model");if(g.name==="AbortError")throw new z("Request was cancelled while deleting model")}throw g}},Zt=(t,{ordered:e,studio:s,fos:r,destinationAddress:o,bridge:n,timeout:i,signal:a})=>(i&&(t.timeout=i),a&&(t.signal=a),e&&(t.ordered=e),s&&(t.studio=s),r&&(t.fos=r),n&&(t.bridge=n),(o||o==="")&&(t.destinationAddress=o),t),ty=(t,e,s)=>async({urlOverride:r,ordered:o,studio:n,fos:i,bridge:a,timeout:c,signal:u,destinationAddress:d})=>{const h={method:"GET"};t&&(h.destinationAddress=t),Zt(h,{timeout:c,ordered:o,studio:n,fos:i,bridge:a,signal:u,destinationAddress:d});const f=r||e;try{const p=await s(f,h);if(!p.ok){let w;try{w=await p.json()}catch{}throw new z(`There was a problem retrieving the model; returned status ${p.status}`,w??void 0)}return await p.json()??void 0}catch(p){if(p instanceof DOMException){if(p.name==="TimeoutError")throw new z("Request timed out while retrieving models");if(p.name==="AbortError")throw new z("Request was cancelled while retrieving models")}throw p}},sy=(t,e,s)=>async({urlOverride:r,ordered:o,studio:n,fos:i,bridge:a,tracker:c,timeout:u,signal:d,destinationAddress:h})=>{const f={method:"GET"};t&&(f.destinationAddress=t),c&&(f.tracker=c),Zt(f,{timeout:u,ordered:o,studio:n,fos:i,bridge:a,signal:d,destinationAddress:h});const p=r||e;Jm.debug(`resolvedUrl: ${p}`);try{const g=await s(p,f);if(!g.ok){let E;try{E=await g.json()}catch{}throw new z(`There was a problem retrieving the model; returned status ${g.status}`,E??void 0)}return await g.json()??void 0}catch(g){if(g instanceof DOMException){if(g.name==="TimeoutError")throw new z("Request timed out while retrieving model");if(g.name==="AbortError")throw new z("Request was cancelled while retrieving model")}throw g}},ry=(t,e,s)=>async({urlOverride:r,id:o,ordered:n,studio:i,fos:a,bridge:c,timeout:u,signal:d,destinationAddress:h})=>{const f={method:"GET"};t&&(f.destinationAddress=t),Zt(f,{timeout:u,ordered:n,studio:i,fos:a,bridge:c,signal:d,destinationAddress:h});const p=r||`${e}/${o}`;try{const g=await s(p,f);if(!g.ok){let E;try{E=await g.json()}catch{}throw new z(`There was a problem retrieving the model; returned status ${g.status}`,E??void 0)}return await g.json()??void 0}catch(g){if(g instanceof DOMException){if(g.name==="TimeoutError")throw new z("Request timed out while retrieving model by ID");if(g.name==="AbortError")throw new z("Request was cancelled while retrieving model by ID")}throw g}};class z extends Error{constructor(s,r){super(s);l(this,"payload");this.name="FetchException",this.payload=r}}const ta=(t,e,s)=>async({model:r,urlOverride:o,ordered:n,tracker:i,studio:a,fos:c,bridge:u,timeout:d,signal:h,destinationAddress:f})=>{const p={method:"POST",body:typeof r=="string"?r:JSON.stringify(r)};t&&(p.destinationAddress=t),i&&(p.tracker=i),Zt(p,{timeout:d,ordered:n,studio:a,fos:c,bridge:u,signal:h,destinationAddress:f});try{const g=await s(o||e,p);if(!g.ok){let E;try{E=await g.json()}catch{}throw new z(`There was a problem sending the POST data; returned status ${g.status}`,E??void 0)}return await g.json()??void 0}catch(g){if(g instanceof DOMException){if(g.name==="TimeoutError")throw new z("Request timed out while adding model");if(g.name==="AbortError")throw new z("Request was cancelled while adding model")}throw g}},sa=(t="POST",e,s,r)=>async({model:o,id:n,urlOverride:i,ordered:a,studio:c,fos:u,bridge:d,timeout:h,signal:f,destinationAddress:p})=>{const g={method:t};o&&(g.body=JSON.stringify(o)),e&&(g.destinationAddress=e),Zt(g,{timeout:h,ordered:a,studio:c,fos:u,bridge:d,signal:f,destinationAddress:p});try{const w=await r(i||`${s}/${n}`,g);if(!w.ok){let _;try{_=await w.json()}catch{}throw new z(`There was a problem modifying the model; returned status ${w.status}`,_??void 0)}return await w.json()??void 0}catch(w){if(w instanceof DOMException){if(w.name==="TimeoutError")throw new z("Request timed out while modifying model");if(w.name==="AbortError")throw new z("Request was cancelled while modifying model")}throw w}},ie={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:ty(t,s||e,c),getModelById:ry(t,r||e,c),getOne:sy(t,r||e,c),addModel:ta(t,n||e,c),deleteModel:ey(t,o||e,c),modifyModel:sa("POST",t,i||e,c),putModel:sa("PUT",t,i||e,c),postModel:ta(t,n||e,c)}}};function oy(t,e,s="get"){const r=t.serviceResponses;if(r)return r.getByPath(e,s)}function ny(t,e,s="get"){const r=t.serviceResponses;return r?r.has(`${s.toUpperCase()}:${e}`):!1}function iy(t,e,s="get"){const r=t.serviceResponses;r&&r.delete(`${s.toUpperCase()}:${e}`)}function ay(t,e){const s=t.serviceResponses;s&&s.clearPath(e)}function cy(t){const e=t.serviceResponses;e&&e.clear()}const ly=bt(),Bl=()=>`kos-${ly}`,uy=t=>!!t&&!t.includes("VM_SERVICE")&&t.startsWith(Bl()),Fn=async(t,e=6e4)=>new Promise((s,r)=>{const{unsubscribe:o}=C(t,i=>{x.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)}),dy=async(t,e,s)=>{const r=Fn(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)},hy=async({topic:t,msg:e,requestId:s})=>{const r=s??bt(),o=Fn(r);K(t,e,{sync:r});const n=await o;if(n.error)throw Error(n.error);return n},ge=new Map;class Hl{constructor(e){l(this,"_context");l(this,"_parent");l(this,"_id");this._id=e,this._context=new M.ObservableMap({}),this._parent="",M.makeAutoObservable(this)}setParent(e){J(()=>{this._parent=e})}get id(){return this._id}get context(){return this._context}get parentModel(){var e;if(this._parent)return(e=Ae(this._parent))==null?void 0:e.model}get companionModels(){const e=Ae(this._id);return e!=null&&e.model?kc(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||!ge.has(n.id)?!1:(i=ge.get(n.id))==null?void 0:i.context.has(e)});if(o)return(s=ge.get(o.id))==null?void 0:s.get(e)}if(this._parent)return(r=ge.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 W={createContext:(t,e)=>{const s=ge.get(t)??new Hl(t);if(e){if(!ge.has(e))throw new Error(`Parent context ${e} does not exist`);s.setParent(e)}else t!=="root"&&s.setParent("root");return ge.set(t,s),s},getContext:t=>ge.get(t),deleteContext:t=>{ge.delete(t)},setParentContext:(t,e)=>{var s;if(!ge.has(e))throw new Error(`Parent context ${e} does not exist`);(s=ge.get(t))==null||s.setParent(e)},rootContext:()=>ge.get("root")};W.createContext("root");const fy=t=>W.getContext(t.id),it=m.createLogger({name:"kos-data-container"});class Nn{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=xe(),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 $n({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??[]:(it.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):(it.info(`key ${s} not found in ${e} index: ${Array.from(r.index.keys())}`),[])}else return it.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){it.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):(it.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);it.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){it.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 py{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 le.Factory.create(this.type)}get registration(){return{[this.type]:{class:this.model,singleton:!1,factory:this.factory},...this.childRegistration}}get predicate(){return Ie(this.type)}}class gy{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 le.Singleton.create(this.type)}get registration(){return{[this.type]:{class:this.model,singleton:!0,factory:this.factory},...this.childRegistration}}get predicate(){return Ie(this.type)}}class Kl{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 ql{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 zl=m.createLogger({name:"intent-service"}),my=t=>{fn(`/kos/intent/${t.type}`)?K(`/kos/intent/${t.type}`,t.options,{"kos.intent.type":t.type}):zl.info(`No subscribers for intent ${t.type}. Intent not sent.`)},yy=async t=>new Promise(e=>{const{type:s,options:r}=t;if(fn(`/kos/intent/${t.type}`)){const o=bt(),{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);K(`/kos/intent/${s}`,r,{"kos.intent.type":s,sync:o})}else zl.info(`No subscribers for intent ${t.type}. Intent not sent.`),e([null,{body:void 0,payload:void 0}])}),Ne=m.createLogger({name:"app-startup-service"});async function Vl(t,e={}){const{timeout:s=3e4,throwOnTimeout:r=!0,requirePostStarted:o=!1}=e;if(t.length===0)return Ne.warn("No app IDs provided to waitForAppsToStart"),!0;Ne.debug(`Waiting for apps to start: ${t.join(", ")}`);try{const n=t.map(c=>`/kos/app/started/${c}`),i=await mn(n,{getCurrentState:async()=>{try{const{default:c}=await Promise.resolve().then(()=>ml),[u,d]=await c.get("/api/kos/apps/started");return u?(Ne.error("Error fetching started apps:",u),[]):d}catch(c){Ne.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(Ne.error(c),r)throw new Error(`App startup timeout: ${c}`);return!1}return Ne.info(`All apps started successfully: ${t.join(", ")}`),!0}catch(n){const i=`Failed to wait for apps to start: ${t.join(", ")}`;if(Ne.error(i,n),r)throw new Error(`${i} - ${n instanceof Error?n.message:String(n)}`);return!1}}async function by(t,e={}){return Vl([t],e)}async function vy(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){Ne.error("Failed to check app startup status:",r),t.forEach(o=>s[o]=!1)}return s}async function wy(){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 Ne.error("Failed to fetch started apps:",t),[]}}const Vo=M.when,Un=M.computed,J=M.runInAction,Q=M.autorun,Gl=M.reaction,jn=M.observable,Bn="Not Assigned",Ey="kos.trouble.added",My="kos.trouble.removed";var _e=(t=>(t.TroubleRank="kos.trouble.rank.mapper",t.TroubleColor="kos.trouble.color.mapper",t.TroubleRole="kos.trouble.role.mapper",t))(_e||{}),Ss=(t=>(t.TIME_CHANGE="/kos/internal/time/time",t.DAY_CHANGE="/kos/internal/time/day",t.TIMEZONE_CHANGE="/kos/internal/time/timezone",t))(Ss||{});const Yl=m.createLogger({name:"config-bean-service",group:"Services"}),Hn=exports.BASE_URL,Wl=t=>(t==null?void 0:t.decimals)!==void 0,{postModel:Ty,getOne:_y}=ie.build({destinationAddress:"",basePath:`${Hn}/kos/config/`}),Ql=async(t,e,s="/api/kos/config")=>(Yl.debug(`sending modify request for ConfigBean: ${t}`),Ty({model:e,urlOverride:`${Hn}${s}/${t}`})),Zl=async(t,e="/api/kos/config")=>(Yl.debug(`sending get request for ConfigBean: ${t}`),await _y({urlOverride:`${Hn}${e}/details/${t}/15`})),Kn=t=>t.toLowerCase()==="true"||t.toLowerCase()==="false",ro=t=>{try{const e=Number(t);return!isNaN(e)}catch{return!1}};function Xl(t=[]){return t.reverse().reduce((e,s)=>{const{overrides:r}=s;return r&&(e={...e,...r}),e},{})}function Jl(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])?Jl(t[r],o,s):s[o]=t[r]}return s}const eu=(t,e)=>{const s=t.details[0].bean||Xl(t.details[0].scopes),r=Jl(s);M.runInAction(()=>{const o={...r};e.props.setValues(o)})},tu=(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"&&ro(o)&&(o=Number(o),n=Number(n)),e.props[r]=o,e.prevProps[r]=n})})},su=t=>Object.fromEntries(t.props.entries),Sy=t=>e=>s=>t.build(e,s);var Oy=Object.defineProperty,Iy=Object.getOwnPropertyDescriptor,ru=(t,e,s,r)=>{for(var o=r>1?void 0:r?Iy(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&&Oy(e,s,o),o};function $y(t,e){for(const s of t)if(new RegExp(`^${s}$`).test(e))return s}const qn="config-bean-model",or=m.getLogger(qn),Cy=mt("path");let Tr=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=Ql,getConfigBean:r=Zl}=e;this._modifyConfigBean=s,this._getConfigBean=r,this.props=xe(),this.prevProps=xe()}get values(){return this.props.values}async ready(){or.debug(`readying config bean ${this.path}`),or.debug(`complete readying config bean ${this.path}`)}async load(){or.debug(`loading config bean ${this.path}`);const t=await this._getConfigBean(this.path,this.serviceBasePath);if(t!=null&&t.data){const e=t.data;eu(e,this),or.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=$y(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=su(this);await this._modifyConfigBean(this.path,t,this.serviceBasePath)}handleConfigBeanUpdated(t){tu(t,this)}};ru([B({topic:`/kos/config/${Cy}`,websocket:!0})],Tr.prototype,"handleConfigBeanUpdated",1);Tr=ru([R(qn)],Tr);const Cs=new ve({class:Tr,type:qn}),oo=({path:t,lazy:e,serviceBasePath:s})=>(r,o)=>{r[N]=r[N]||{},r[N][o]={modelType:Cs.type,id:`${Cs.type}-${t}`,options:{path:t,serviceBasePath:s},lifecycle:D.INIT,lazy:e}},{URL:ou}=ue(),{getOne:Dy,getAll:xy}=ie.build({basePath:`${ou}/api/kos/regions/info`}),nu=async()=>{try{return await Dy({})}catch{return}},iu=async()=>{try{return await xy({urlOverride:`${ou}/api/kos/regions`})}catch{return}},Ay=Object.freeze(Object.defineProperty({__proto__:null,getRegionInfo:nu,getRegions:iu},Symbol.toStringTag,{value:"Module"}));var he=(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))(he||{});const au={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 Ry(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},{...au});return{...t,...r}}function Py(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,n.alias&&(a[n.alias]=c),Object.hasOwn(n,"default")&&Object.defineProperty(a,"default",{value:c,writable:!0,enumerable:!0,configurable:!0}),o[n.measure]=i,o},{time:{[s]:{...au}}});return Object.keys(r).forEach(o=>{t[o]={...t[o],...r[o]}}),t}function ky(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 Ly=Object.defineProperty,Fy=Object.getOwnPropertyDescriptor,zn=(t,e,s,r)=>{for(var o=r>1?void 0:r?Fy(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&&Ly(e,s,o),o};const mr="region-info-model",ns=m.createLogger({name:"region-info-model"});let Ds=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[he.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[he.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[he.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[he.family]!==s[he.family])throw new Error(`Cannot convert between units of different families: ${e[he.family]} and ${s[he.family]}`);const r=e[he.offset],o=e[he.scale],n=s[he.scale],i=s[he.offset],a=s[he.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||ns.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||ns.info("Could not find default unit for measure",e.measure)}return!n||!i?(ns.warn("Could not find unit to convert to or from. Return value as is"),String(t)):this.convertByUnit(t,n,i)}async init(){ns.debug("initializing region info")}async load(){ns.debug("loading region info");const t=await iu();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 nu();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(Ry,{}),this.measureMap=e.data.unitSystems.reduce(Py,{}),this.defaultMeasureMap=e.data.unitSystems.reduce(ky,{}),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))}};zn([oo({path:"kos:service:region:settings"})],Ds.prototype,"regionSource",2);zn([oo({path:"kos:service:region"})],Ds.prototype,"region",2);Ds=zn([R(mr)],Ds);const ne={registration:{[mr]:{class:Ds,singleton:!0}},type:mr,factory:le.Singleton.create(mr)},_r=({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},Vn=(t,e,s)=>{const{model:r}=Ae(ne.type);if(!r)throw new Error("RegionInfo model not found");if(!Mr(r))throw new Error("RegionInfo model not ready");const o={system:r.defaultUnitSystem},n=_r({source:e}),i=_r({source:s||o,defaultMeasure:r.getUnitMeasure(n.unit||"")});return r.convert(t,n,i)};function ra(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 Ny=(t,e,s,r)=>{const o=Vn(t,e,s),n=_r({source:e}),{model:i}=Ae(ne.type);if(!i)throw new Error("RegionInfo model not found");const a=i.getUnitMeasure(n.unit||""),c={system:i.defaultUnitSystem},u=_r({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:ra(o,d||n.unit||"",{...f,mode:"long"}),shortDisplay:ra(o,d||n.unit||"",{...f,mode:"short"})}};function oa({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 na({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 St=(t,e)=>s=>!t||!e?s:ro(s)?Vn(Number(s),t,e):s,Uy=(t,e,s,r)=>{if((t==null?void 0:t.type)==="enum"||!(t!=null&&t.options))return[];if(t.options.type==="rangeCount")return oa(t.options).map(St(s,r));if(t.options.type==="rangeInterval")return na(t.options).map(St(s,r));if(t.options.type==="list"){const{list:o}=t.options;return o.map(St(s,r))}else{if(t.options.type==="unitSystemRangeCount"&&e)return oa(t.options.unitSystems[e]).map(St(s,r));if(t.options.type==="unitSystemRangeInterval"&&e)return na(t.options.unitSystems[e]).map(St(s,r));if(t.options.type==="unitSystemList"&&e){const{list:o}=t.options.unitSystems[e];return o.map(St(s,r))}}return[]},jy=(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 By=Object.defineProperty,Hy=Object.getOwnPropertyDescriptor,Gn=(t,e,s,r)=>{for(var o=r>1?void 0:r?Hy(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&&By(e,s,o),o};function Ky(t){return(t==null?void 0:t.type)==="enum"}function qy(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 zy(t,e){const s=new Date;s.setHours(0,0,0,0);const r=new Date(s.getTime()+t*1e3);return We.format(r,e)}const yr="config-bean-prop-model",Ot=m.createLogger({name:"config-bean-prop-model"}),Vy=mt("path"),Gy=mt("serviceBasePath");let xs=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 Wl(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?qy(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=Ky(r)?r.values:Uy(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){Ot.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(){Ot.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 zy(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){Ot.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 jy(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){Ot.error(`error creating formatter ${d}. Returning the raw value`,h)}}else Ot.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 g=(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,_=g||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),I=((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:I},measure:_}}if(s&&e){const g=this.regionInfo.getDefaultUnitForMeasure(e,this.regionInfo.defaultUnitSystem),w=this.regionInfo.getUnitSystem(s),E=this.regionInfo.getUnitSystem(g);return{measure:e,to:{unit:w===E?s:g}}}}async updateProperty(t){Ot.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)}};Gn([Wt({modelType:ne.type})],xs.prototype,"regionInfo",2);Gn([oo({path:Vy,serviceBasePath:Gy})],xs.prototype,"bean",2);xs=Gn([R(yr)],xs);const vt={registration:{[yr]:{class:xs,singleton:!1}},type:yr,factory:le.Factory.create(yr)};function Yy(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[N]=u[N]||{},u[N][d]={modelType:vt.type,id:`${e}-${s}`,options:{path:e,attribute:s,serviceBasePath:a,converter:c,formatter:o,optionsExpander:i},lifecycle:D.INIT,lazy:n}}}const cu="future-model",Xt=Qt(cu),no=m.createLogger({name:"future-service",group:"Services"}),{isMock:Wy,URL:Vs}=ue();var Je=(t=>(t.Success="SUCCESS",t.Fail="FAIL",t.Aborted="ABORT",t.Canceled="CANCEL",t))(Je||{});const{getAll:Qy,modifyModel:Zy,addModel:Xy,deleteModel:Jy,postModel:eb}=ie.build({destinationAddress:"",basePath:`${Vs}/api/future`,mock:Wy}),tb=async()=>await Qy({}),lu=async(t,e="/api/kos/future")=>(no.info(`sending delete request for Future: ${t}`),await Jy({id:t,urlOverride:`${Vs}${e}/${t}`})),uu=async(t,e="/api/kos/future")=>(no.info("sending add request for Future"),await Xy({model:t,urlOverride:`${Vs}${e}`})),sb=async(t,e,s="/api/kos/future")=>(no.info(`sending modify request for Future: ${t}`),Zy({model:e,id:t,urlOverride:`${Vs}${s}/${t}`})),du=async(t,e="/api/kos/future")=>(no.info(`sending cancel request for Future: ${t}`),eb({urlOverride:`${Vs}${e}/${t}/cancel`,ordered:!0,model:{}})),Yn=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}),Wn=(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=Yn(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]})})}))},hu=t=>e=>s=>t.build(String(e),s),Qn=t=>e=>jl(Yn,hu(t)(e.tracker||e.id))(e);var rb=Object.defineProperty,ob=Object.getOwnPropertyDescriptor,fu=(t,e,s,r)=>{for(var o=r>1?void 0:r?ob(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&rb(e,s,o),o};const xo=m.getLogger(Xt.type);let Sr=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=du,Vo(()=>this.status===Je.Success||this.status===Je.Fail,()=>{xo.info(`Future ${this.id} has completed with status ${this.status}`),De(this)})}async load(){xo.debug(`loading Future ${this.id}`)}unload(){xo.info(`unloading Future ${this.id}`)}async cancelFuture(){const t=this.namespace==="studio"?"/api/future":`/api/${this.namespace}/future`;await Vo(()=>this.futureId!==Bn),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}`),Wn(t,this)}};fu([B({topic:`kos.future/${vr}`})],Sr.prototype,"handleFutureUpdated",1);Sr=fu([R(Xt.type)],Sr);const pu=Sr,gu=Ve();var nb=Object.defineProperty,ib=Object.getOwnPropertyDescriptor,mu=(t,e,s,r)=>{for(var o=r>1?void 0:r?ib(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&&nb(e,s,o),o};const yu="browser-router-model",ab="kos.http.request",cb="kos.http.response";let Or=class{constructor(t,e,s){l(this,"_id");l(this,"logger");l(this,"router");this._id=t,this.logger=s.logger,this.router=new ql}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),pl({msg:d,options:{responseId:i,destinationAddress:s,type:cb,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}`)}};mu([B({topic:ab})],Or.prototype,"handleRequest",1);Or=mu([R(yu)],Or);const Zn=new $e({class:Or,type:yu}),bu="future-container-model",et=Qt(bu),vu=t=>Qn(Xt)(t),lb=t=>{const e=vu(t);return et.build(et.type,{}).addFutureModel(e),e},ub=t=>et.build(et.type,{}).getFuture(String(t)),pt={buildFutureModel:vu,initiateFuture:lb,getFuture:ub};var db=Object.defineProperty,hb=Object.getOwnPropertyDescriptor,Xn=(t,e,s,r)=>{for(var o=r>1?void 0:r?hb(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&&db(e,s,o),o};const nr=m.getLogger(et.type);let As=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=lu,addFuture:o=uu}=e;this.logger=s.logger,this._deleteFuture=r,this._addFuture=o,this.id=t,this._futures=new ke,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){nr.error("error deleting a Future"),nr.error(e)}}async createFuture(t){try{const e=await this._addFuture(t),s=e==null?void 0:e.data;if(s){const r=Qn(Xt)(s);return this.addFutureModel(r),r}}catch(e){throw nr.error("error creating a Future"),nr.error(e),e}}handleFutureUpdated(t,e){const s=pt.buildFutureModel(t);this.addFutureModel(s);const r=`kos.future/${t.tracker||t.id}`;this.logger.debug(`publishing future update to ${r}`),K(r,e.body,e.headers)}};Xn([Pe],As.prototype,"_futures",2);Xn([B({topic:"kos.future"})],As.prototype,"handleFutureUpdated",1);As=Xn([R(et.type)],As);const wu=As,{URL:Gs}=ue(),{getOne:fb,postModel:pb,deleteModel:Eu}=ie.build({basePath:`${Gs}/api/keyVal`}),Go=m.createLogger({name:"key-value-service",group:"Services"}),Mu=async(t,e)=>{await Eu({urlOverride:`${Gs}/api/keyVal/${t}/${e}`,id:e})},Tu=async(t,e,s)=>{const r=await pb({urlOverride:`${Gs}/api/keyVal/${t}/${e}`,model:s.toString()});if((r==null?void 0:r.status)!==200)throw Go.error("Failed to update key-value data",r),new Error(`Failed to update key-value data for namespace ${t}`);return r.data},_u=async(t="studio")=>{Go.debug(`Retrieving all key-value data for namespace: ${t}`);const e=await fb({urlOverride:`${Gs}/api/keyVal/${t}`});if((e==null?void 0:e.status)!==200)throw Go.error("Failed to retrieve key-value data",e),new Error(`Failed to retrieve key-value data for namespace ${t}`);return e.data},gb=async t=>{await Eu({urlOverride:`${Gs}/api/keyVal/${t}`,id:""})},mb=Object.freeze(Object.defineProperty({__proto__:null,deleteKeyValue:Mu,deleteKeyValueNamespace:gb,getKeyValue:_u,updateKeyValue:Tu},Symbol.toStringTag,{value:"Module"}));var yb=Object.defineProperty,bb=Object.getOwnPropertyDescriptor,Jn=(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=(r?i(e,s,o):i(o))||o);return r&&o&&yb(e,s,o),o};const Su="key-value-model";let Rs=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=xe(),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 Tu(this.namespace,t,e),this.data[t]=e):(await Mu(this.namespace,t),this.data[t]=void 0)}async load(){this.logger.debug(`loading studio-state ${this.id}`);const t=await _u(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)}};Jn([B({topic:"/keyVal/set"})],Rs.prototype,"handleStateUpdate",1);Jn([B({topic:"/keyVal/remove"})],Rs.prototype,"handleStateDelete",1);Rs=Jn([R(Su)],Rs);const ei=new ve({class:Rs,type:Su});var me="INUMBER",Jt="IOP1",es="IOP2",ts="IOP3",Be="IVAR",gt="IVARNAME",Lt="IFUNCALL",io="IFUNDEF",ce="IEXPR",ti="IEXPREVAL",wt="IMEMBER",ao="IENDSTATEMENT",Ft="IARRAY";function P(t,e){this.type=t,this.value=e??0}P.prototype.toString=function(){switch(this.type){case me:case Jt:case es:case ts:case Be:case gt:case ao:return this.value;case Lt:return"CALL "+this.value;case io:return"DEF "+this.value;case Ft:return"ARRAY "+this.value;case wt:return"."+this.value;default:return"Invalid Instruction"}};function co(t){return new P(Jt,t)}function Ge(t){return new P(es,t)}function Ou(t){return new P(ts,t)}function Yo(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===me||p===gt)Array.isArray(f.value)?n.push.apply(n,Yo(f.value.map(function(g){return new P(me,g)}).concat(new P(Ft,f.value.length)),e,s,r,o)):n.push(f);else if(p===Be&&o.hasOwnProperty(f.value))f=new P(me,o[f.value]),n.push(f);else if(p===es&&n.length>1)c=n.pop(),a=n.pop(),d=s[f.value],f=new P(me,d(a.value,c.value)),n.push(f);else if(p===ts&&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(me,d(a.value,c.value,u.value)),n.push(f));else if(p===Jt&&n.length>0)a=n.pop(),d=e[f.value],f=new P(me,d(a.value)),n.push(f);else if(p===ce){for(;n.length>0;)i.push(n.shift());i.push(new P(ce,Yo(f.value,e,s,r,o)))}else if(p===wt&&n.length>0)a=n.pop(),n.push(new P(me,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 Iu(t,e,s){for(var r=[],o=0;o<t.length;o++){var n=t[o],i=n.type;if(i===Be&&n.value===e)for(var a=0;a<s.tokens.length;a++){var c=s.tokens[a],u;c.type===Jt?u=co(c.value):c.type===es?u=Ge(c.value):c.type===ts?u=Ou(c.value):u=new P(c.type,c.value),r.push(u)}else i===ce?r.push(new P(ce,Iu(n.value,e,s))):r.push(n)}return r}function ut(t,e,s){var r=[],o,n,i,a,c,u;if(si(t))return Fe(t,s);for(var d=t.length,h=0;h<d;h++){var f=t[h],p=f.type;if(p===me||p===gt)r.push(f.value);else if(p===es)n=r.pop(),o=r.pop(),f.value==="and"?r.push(o?!!ut(n,e,s):!1):f.value==="or"?r.push(o?!0:!!ut(n,e,s)):f.value==="="?(a=e.binaryOps[f.value],r.push(a(o,ut(n,e,s),s))):(a=e.binaryOps[f.value],r.push(a(Fe(o,s),Fe(n,s))));else if(p===ts)i=r.pop(),n=r.pop(),o=r.pop(),f.value==="?"?r.push(ut(o?n:i,e,s)):(a=e.ternaryOps[f.value],r.push(a(Fe(o,s),Fe(n,s),Fe(i,s))));else if(p===Be)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 g=s[f.value];if(g!==void 0)r.push(g);else throw new Error("undefined variable: "+f.value)}else if(p===Jt)o=r.pop(),a=e.unaryOps[f.value],r.push(a(Fe(o,s)));else if(p===Lt){for(u=f.value,c=[];u-- >0;)c.unshift(Fe(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===io)r.push(function(){for(var w=r.pop(),E=[],_=f.value;_-- >0;)E.unshift(r.pop());var k=r.pop(),I=function(){for(var O=Object.assign({},s),F=0,X=E.length;F<X;F++)O[E[F]]=arguments[F];return ut(w,e,O)};return Object.defineProperty(I,"name",{value:k,writable:!1}),s[k]=I,I}());else if(p===ce)r.push(vb(f,e));else if(p===ti)r.push(f);else if(p===wt)o=r.pop(),r.push(o[f.value]);else if(p===ao)r.pop();else if(p===Ft){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:Fe(r[0],s)}function vb(t,e,s){return si(t)?t:{type:ti,value:function(r){return ut(t.value,e,r)}}}function si(t){return t&&t.type===ti}function Fe(t,e){return si(t)?t.value(e):t}function ri(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===me)typeof d.value=="number"&&d.value<0?s.push("("+d.value+")"):Array.isArray(d.value)?s.push("["+d.value.map(ia).join(", ")+"]"):s.push(ia(d.value));else if(h===es)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===ts)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===Be||h===gt)s.push(d.value);else if(h===Jt)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===Lt){for(c=d.value,a=[];c-- >0;)a.unshift(s.pop());i=s.pop(),s.push(i+"("+a.join(", ")+")")}else if(h===io){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===wt)r=s.pop(),s.push(r+"."+d.value);else if(h===Ft){for(c=d.value,a=[];c-- >0;)a.unshift(s.pop());s.push("["+a.join(", ")+"]")}else if(h===ce)s.push("("+ri(d.value,e)+")");else if(h!==ao)throw new Error("invalid Expression")}return s.length>1&&(e?s=[s.join(",")]:s=[s.join(";")]),String(s[0])}function ia(t){return typeof t=="string"?JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029"):t}function Dt(t,e){for(var s=0;s<t.length;s++)if(t[s]===e)return!0;return!1}function oi(t,e,s){s=s||{};for(var r=!!s.withMembers,o=null,n=0;n<t.length;n++){var i=t[n];i.type===Be||i.type===gt?!r&&!Dt(e,i.value)?e.push(i.value):(o!==null&&(Dt(e,o)||e.push(o)),o=i.value):i.type===wt&&r&&o!==null?o+="."+i.value:i.type===ce?oi(i.value,e,s):o!==null&&(Dt(e,o)||e.push(o),o=null)}o!==null&&!Dt(e,o)&&e.push(o)}function Se(t,e){this.tokens=t,this.parser=e,this.unaryOps=e.unaryOps,this.binaryOps=e.binaryOps,this.ternaryOps=e.ternaryOps,this.functions=e.functions}Se.prototype.simplify=function(t){return t=t||{},new Se(Yo(this.tokens,this.unaryOps,this.binaryOps,this.ternaryOps,t),this.parser)};Se.prototype.substitute=function(t,e){return e instanceof Se||(e=this.parser.parse(String(e))),new Se(Iu(this.tokens,t,e),this.parser)};Se.prototype.evaluate=function(t){return t=t||{},ut(this.tokens,this,t)};Se.prototype.toString=function(){return ri(this.tokens,!1)};Se.prototype.symbols=function(t){t=t||{};var e=[];return oi(this.tokens,e,t),e};Se.prototype.variables=function(t){t=t||{};var e=[];oi(this.tokens,e,t);var s=this.functions;return e.filter(function(r){return!(r in s)})};Se.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 "+ri(this.simplify(e).tokens,!0)+"; }");return function(){return r.apply(s,arguments)}};var Ps="TEOF",j="TOP",lo="TNUMBER",$u="TSTRING",He="TPAREN",Nt="TBRACKET",uo="TCOMMA",ni="TNAME",ii="TSEMICOLON";function Cu(t,e,s){this.type=t,this.value=e,this.index=s}Cu.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 Cu(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(Ps,"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($u,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(He,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(Nt,t),this.pos++,!0):!1};G.prototype.isComma=function(){var t=this.expression.charAt(this.pos);return t===","?(this.current=this.newToken(uo,","),this.pos++,!0):!1};G.prototype.isSemicolon=function(){var t=this.expression.charAt(this.pos);return t===";"?(this.current=this.newToken(ii,";"),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(lo,this.consts[r]),this.pos+=r.length,!0}return!1};G.prototype.isNamedOp=function(){for(var t=this.pos,e=t;e<this.expression.length;e++){var s=this.expression.charAt(e);if(s.toUpperCase()===s.toLowerCase()&&(e===this.pos||s!=="_"&&(s<"0"||s>"9")))break}if(e>t){var r=this.expression.substring(t,e);if(this.isOperatorEnabled(r)&&(r in this.binaryOps||r in this.unaryOps||r in this.ternaryOps))return this.current=this.newToken(j,r),this.pos+=r.length,!0}return!1};G.prototype.isName=function(){for(var t=this.pos,e=t,s=!1;e<this.expression.length;e++){var r=this.expression.charAt(e);if(r.toUpperCase()===r.toLowerCase()){if(e===this.pos&&(r==="$"||r==="_")){r==="_"&&(s=!0);continue}else if(e===this.pos||!s||r!=="_"&&(r<"0"||r>"9"))break}else s=!0}if(s){var o=this.expression.substring(t,e);return this.current=this.newToken(ni,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:(g=this.socket)==null?void 0:g.connectionEstablished){const E=r?this.fosSocket:this.socket;(w=E==null?void 0:E.socket)==null||w.send(d)}else{nt.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 nt.debug(`Topic ${e} currently has ${a} subscribers`),this._sendSubscriptionMessage(e,"subscribe",r,o,n),()=>{const{count:c}=i();nt.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(Pt,"_instance");class gm{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===D.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=Pt.getInstance().subscribeTopic({topic:s,callback:r,fos:e.fos,bridge:e.bridge,destinationAddress:n});o?this.activatableDisposers.push(i):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=Ko(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=Ko(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||!Bc(e))return null;const o=((n=s==null?void 0:s.headers)==null?void 0:n.topic)||"";return jc(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 am(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===D.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;Pt.getInstance().subscribeTopic({topic:s,callback:()=>{},fos:e.fos,bridge:e.bridge,destinationAddress:a}),i=Vi(s)}else i=Vi(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||ht.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 _t(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 mm(t){return!!(t!=null&&t[Ue])&&Object.keys(t[Ue]).length>0}function ym(t){return!!(t!=null&&t[ee])&&Object.keys(t[ee]).length>0}function bm(t){return!!(t!=null&&t[je])&&t[je].length>0}function vm(t){const e=Object.getPrototypeOf(t);return!!(e!=null&&e[ft])&&Object.keys(e[ft]).length>0}function wm(t){return t.retention===oe.TTL&&t.extendOnRefresh===!0&&t.ttl!==void 0}function Em(t,e){return t.has(e)}function Mm(t){return!t.expiresAt||Date.now()<t.expiresAt}function Wi(t,e,s,r){const o=setTimeout(()=>r(t),e);s.set(t,o)}class Tm{constructor(){l(this,"responses",new Map);l(this,"retentionPolicies",new Map);l(this,"cleanupTimers",new Map)}set(e,s,r={retention:oe.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)===oe.IMMEDIATE}shouldExtendTTL(e,s){if(!wm(s)||!Em(this.responses,e))return!1;const r=this.responses.get(e);return Mm(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),Wi(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===oe.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 oe.IMMEDIATE:break;case oe.TTL:s.ttl&&Wi(e,s.ttl,this.cleanupTimers,r=>this.delete(r));break;case oe.SINGLE:break;case oe.PERMANENT:case oe.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 _m{static createAll(e){const{modelId:s,modelTypeName:r,modelData:o}=e,n=_c.create({modelId:s,modelTypeName:r}),i=new Dg(e,_t(n,"fsm")),a=new Ag(_t(n,"offline-queue")),c=new Mg(e),u=new Eg(e),d=new Tm;o.serviceResponses=d;const h={fsm:i,offlineQueue:a,serviceResponseStore:d,companionManager:c,childResolver:u};if(mm(o)&&(h.effectManager=new Tg(r,s,o,_t(n,"effect"))),ym(o)){const f=_t(n,"subscription");h.subscriptionManager=new gm(e,o,s,a,f),h.onlineLifecycleManager=new Rg(e,_t(n,"online"))}return bm(o)&&(h.httpRouteManager=new An(o,_t(n,"http-routes"))),vm(o)&&(h.serviceRequestManager=new nm(o,d)),h}}const U=x.getLogger("kos-model"),Sm="kos.extension.model.loader";class vl{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=_m.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}),vg(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;U.debug(`deactivating model ${this.modelTypeName} with id ${this.modelId}`);try{const o=W.getContext(this.modelId);await((s=(e=this.modelData)==null?void 0:e.deactivate)==null?void 0:s.call(e,o)),U.debug(`Model ${this.modelTypeName} with id ${this.modelId} deactivated`),(r=this.subscriptionManager)==null||r.deactivate()}catch(o){throw U.debug(`Model ${this.modelId} failed to deactivated`),o}}async activate(){var e,s,r,o;U.debug(`activating model ${this.modelTypeName} with id ${this.modelId}`),await is(this,D.ACTIVATE);try{await((e=this.serviceRequestManager)==null?void 0:e.executeForLifecycle(D.ACTIVATE));const n=W.getContext(this.modelId);await((r=(s=this.modelData)==null?void 0:s.activate)==null?void 0:r.call(s,n)),this.initializeStateMachineForLifecycle(D.ACTIVATE),U.debug(`Model ${this.modelTypeName} with id ${this.modelId} subscribing to all topics`),(o=this.subscriptionManager)==null||o.registerAll(D.ACTIVATE),this.createLifecycleCompanions(D.ACTIVATE),U.debug(`Model ${this.modelTypeName} with id ${this.modelId} activated`)}catch(n){throw U.debug(`Model ${this.modelId} failed to activate`),n}}async whenLoaded(){await Co([{condition:()=>this.status===v.FAILED,onMatch:()=>{throw new Error(`Failed to initialize model ${this.modelId}`)}},{condition:()=>this.loaded,onMatch:()=>{U.debug(`Model ${this.modelId} is loaded`)}}])}async whenInitialized(){await Co([{condition:()=>this.status===v.FAILED,onMatch:()=>{throw new Error(`Failed to initialize model ${this.modelId}`)}},{condition:()=>this.initialized,onMatch:()=>{U.debug(`Model ${this.modelId} is initialized`)}}])}async whenReady(){await Co([{condition:()=>this.status===v.FAILED,onMatch:()=>{throw new Error(`Failed to ready model ${this.modelId}`)}},{condition:()=>this.status===v.READY,onMatch:()=>{U.debug(`Model ${this.modelId} is ready`)}}])}async ready(){var e,s,r,o;if(this.fsm.current===v.READY){U.debug(`already readying model ${this.modelTypeName} with id ${this.modelId} returning`);return}try{U.debug(`readying model ${this.modelTypeName} with id ${this.modelId}`),await is(this,D.READY),await el(this,Dn.READY,D.READY),await((e=this.serviceRequestManager)==null?void 0:e.executeForLifecycle(D.READY));const n=W.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(D.READY),(o=this.subscriptionManager)==null||o.registerAll(D.READY),this.createLifecycleCompanions(D.READY),U.debug(`Model ${this.modelId} is ready`);const i={modelId:this.modelId,modelType:this.modelTypeName};K(zc(this.modelTypeName,this.modelId),i),K(Vc(this.modelTypeName),i)}catch(n){throw U.error(n),Error(n)}}async load(){var o,n,i,a,c,u;const e=this[Xe];e&&await e.whenLoaded();const{modelTypeName:s,modelId:r}=this;if(this.fsm.current===v.LOADED){U.debug(`Model ${s} with id ${r} already loaded`);return}if(this._isLoadExecuting){U.debug(`Model ${s} with id ${r} is currently executing load`);return}this._isLoadExecuting=!0;try{U.debug(`Loading model ${s} with id ${r}`),await is(this,D.LOAD);const d=W.getContext(r),h=`${Sm}.${s}`,f=await $.loader.executeLoader(h,{});f&&(U.info(`Setting loaded context for ${r}, type: ${s}`),d==null||d.set(h,f)),await((o=this.serviceRequestManager)==null?void 0:o.executeForLifecycle(D.LOAD)),await((i=(n=this.modelData)==null?void 0:n.load)==null?void 0:i.call(n,d)),J(()=>{this.loaded=!0}),U.debug(`Model ${s} with id ${r} successfully loaded`),this.initializeStateMachineForLifecycle(D.LOAD),(a=this.subscriptionManager)==null||a.registerAll(D.LOAD),(c=this.httpRouteManager)==null||c.registerAll(),(u=this.effectManager)==null||u.setup(),this.createLifecycleCompanions(D.LOAD)}catch(d){throw U.error(`Model ${r} failed to load`,d),d}finally{this._isLoadExecuting=!1}}async unload(){var e,s,r,o,n,i,a;U.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=W.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=[])}U.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 U.debug(`Model ${this.modelId} failed to unload`),c}}async init(){var n,i,a,c;const e=this[Xe];e&&await e.whenInitialized();const{modelId:s,modelTypeName:r}=this,o=W.getContext(s);U.debug(`Initializing model ${r} with id ${s}`),await is(this,D.INIT);try{await((n=this.serviceRequestManager)==null?void 0:n.executeForLifecycle(D.INIT)),await((a=(i=this.modelData)==null?void 0:i.init)==null?void 0:a.call(i,o)),this.initialized=!0,U.debug(`Model ${r} with id ${s} initialized`),(c=this.onlineLifecycleManager)==null||c.register(),this.initializeStateMachineForLifecycle(D.INIT),this.registerSubscribers(D.INIT),this.createLifecycleCompanions(D.INIT)}catch(u){throw U.error(`Model ${s} failed to initialize`,u),u}}async registerSubscribers(e){var s;U.debug(`registering subscribers in ${this.modelTypeName} with id ${this.modelId}`),(s=this.subscriptionManager)==null||s.registerAll(e)}initializeStateMachineForLifecycle(e){this.modelData&&vc(this.modelData,e)}createLifecycleCompanions(e){this.modelManager.createLifecycleCompanions(this,{},e)}async online(){var s,r;U.debug(`online model ${this.modelTypeName} with id ${this.modelId}`),this.registerSubscribers();const e=W.getContext(this.modelId);await((r=(s=this.modelData)==null?void 0:s.online)==null?void 0:r.call(s,e)),this.createLifecycleCompanions(D.ONLINE)}async offline(){var s,r,o;U.debug(`offline model ${this.modelTypeName} with id ${this.modelId}`),(s=this.subscriptionManager)==null||s.disposeAll();const e=W.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 Do=m.createLogger({name:"kos-model-instantiator"});class Om{constructor(e,s){l(this,"companionInstantiator");this.registry=e,this.cache=s,this.companionInstantiator=new hg(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 Do.error(c,{modelType:e,requestedId:s,providedOptions:r,availableModelTypes:Object.keys(this.registry.models)}),At(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)){Do.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[Ks])===!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"}),At(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 vl({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"}),At(h,{modelType:e,modelId:n,operation:"model instantiation",options:r})}}const i=this.cache.getModelById(n);if(!i)throw Do.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 Im=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 Qt(e)}};const wl=10,Qi=m.createLogger({name:"kos-model-manager"});class El{constructor(){l(this,"cache");l(this,"instantiator");l(this,"dependencies");l(this,"_registry");globalThis.kos=globalThis.kos||{},this.dependencies=new lg,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 Im(e),r.cache=new ug(e.preloadModels),r.instantiator=new Om(e,r.cache),r}static getInstance(e){var s,r;return(!((s=globalThis.kos)!=null&&s.modelManager)||e)&&(Qi.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=>(Qi.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 Qt(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),Kc.addToDeletionQueue(e.id,setTimeout(()=>this.destroyModel(s),wl)))}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 gr=(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))(gr||{}),ct=(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))(ct||{});const $m=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=>x.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=>x.debug(n.machine.current)),online:s}},Y=m.createLogger({name:"kos-core"}),Cm=()=>{const t=be(),e=t==null?void 0:t.alias,s=process.env.KOS_CONNECTION_ALIAS;return e||s||void 0},Dm=()=>{const t=window.location.protocol,e=be(),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://")},xm=()=>{const t=window.location.hostname,e=process.env.KOS_HOST,s=be(),r=s==null?void 0:s.host;let o;try{o=new URL(r).hostname}catch{}return o??e??t},Am=()=>{const t=window.location.port,e=process.env.KOS_PORT,s=be(),r=s==null?void 0:s.host;let o;try{o=new URL(r).port}catch{}return o??e??t},Rm=(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)}}},Zi=t=>typeof t.reload=="function",Pm=t=>typeof t.unload=="function";var Ml=(t=>(t.LOGGED_IN="logged_in",t.LOGGED_OUT="logged_out",t))(Ml||{});class S{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=gr.CREATED,this.authState="logged_out",this._reloading=!1,this._unloading=!1,M.makeAutoObservable(this),C("token",a=>{a&&(this.transport.token=a.body)}),C(Te.CONNECTED,async()=>{await this.whenReady(),this.fsmService.service.send(ct.GO_ONLINE)}),C(Te.DISCONNECTED,async()=>{this.fsmService.service.send(ct.GO_OFFLINE)}),C("/studioServer/auth/LOGGED_IN",()=>{this.authState="logged_in",this.transport.authorized=!0,this.fsmService.service.send(ct.RELOAD)}),C("/studioServer/auth/LOGIN_REQUIRED",()=>{this.authState="logged_out",this.transport.authorized=!1}),C(Te.RELOAD,()=>{Y.warn("WebSocket requested reload"),this.fsmService.service.send(ct.RELOAD)}),C("/studio/project/reload",()=>{Y.warn("Project requested reload"),this.fsmService.service.send(ct.RELOAD)});const s=Pt.getInstance(),r=xm(),o=Am(),n=Dm();s.host=r,s.port=Number.parseInt(o),s.protocol=n,process.env.KOS_ALLOW_ANONYMOUS==="true"&&(s.authorized=!0);const i=Cm()??e;i&&(s.alias=i.replace("{{TIMESTAMP}}",Date.now().toString())),this._transport=s.init(),this.fsmService=$m(this),this.fsmService.service.send(ct.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){Y.info("reload already in progress");return}this._reloading=!0,Y.warn("reloading KOS Core"),Y.warn("reloading preloaded models");const s=this.modelManager;for(const c of s.preloadedModels)Zi(c.modelData)&&(Y.info(`reloading model ${c.modelId}`),(o=c.unload)==null||o.call(c),await c.modelData.reload(),(n=c.registerSubscribers)==null||n.call(c),Y.info(`reloading model ${c.modelId} complete`));for(const c of s.models)!s.preloadedModels.includes(c)&&Zi(c.modelData)&&(Y.warn(`reloading model ${c.modelId}`),(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(()=>{Y.warn("reloading KOS Core complete"),this._reloading=!1})},1e3-r)}async online(){Y.debug("KOS Core going online"),await this._transport.whenReady(),Y.debug("KOS Transport Ready. Calling online() for models"),K("/kosCore/online","/kosCore/online"),console.timeEnd("kosCore:startup")}async offline(){Y.debug("KOS Core going offline"),K("/kosCore/offline","/kosCore/offline")}async unload(){var o;Y.debug("Unloading KOS Core");const e=Date.now();this._unloading=!0,Y.debug("unloading KOS Core");const s=this.modelManager;for(const n of s.models)Pm(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===gr.READY)}async ready(){Y.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}=Rm(5e3,o.model);Promise.race([o.promise.then(()=>{i()}),n])}))).filter(o=>o.status==="rejected");if(r.length)throw Y.error(`There were ${r.length} failed models on model preloading`),Error(`There were ${r.length} failed models on model preloading`);Y.debug("leaving kos-core ready() ")}get isReady(){return this.status===gr.READY}set transport(e){this._transport=e}get transport(){return this._transport}get coreInitialized(){return this.initialized}get modelsLoaded(){return this.loaded}async init(){Y.debug("entering kos-core init()"),console.time("kosCore:startup"),console.time("kosCore:init"),await this._transport.whenReady(),this.initialized=!0,Y.debug("initialized - leaving kos-core init()"),console.timeEnd("kosCore:init")}async load(){Y.debug("entering kos-core load()"),console.time("kosCore:load"),this.loaded=!0,Y.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 g=p.class.prototype[Xe];f=g==null?void 0:g.lifecycle}}e.companionModels[u].push({type:h,lifecycle:f})}}),A.model.getPreloadModels().forEach(u=>{e.preloadModels.includes(u)||e.preloadModels.push(u)});const n=El.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(S,"_instance");const km=m.createLogger({name:"kos-model-visitor",group:"kos-ui-core"});class Tl{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=S.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)){km.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 Lm extends Tl{constructor(s){super();l(this,"targetId");l(this,"currentPath",[]);l(this,"foundPath",null);this.targetId=s}visit(s){var o;if(this.visitedModels.has(s.modelId))return;this.currentPath.push(s.modelId),this.visitedModels.add(s.modelId),!!this.visitModel(s.modelData)||(o=s.getChildren)==null||o.call(s).forEach(n=>{var i;this.foundPath||(i=n.accept)==null||i.call(n,this)}),this.foundPath||this.currentPath.pop()}visitModel(s){return s.id===this.targetId?(this.foundPath=this.currentPath.slice(0,-1),!0):!1}getAncestorPath(){return this.foundPath??[]}wasFound(){return this.foundPath!==null}}function Fm(t,e){e.forEach(s=>{Object.getOwnPropertyNames(s.prototype).forEach(r=>{const o=Object.getOwnPropertyDescriptor(s.prototype,r);Object.defineProperty(t.prototype,r,o)})})}function Nm(t,e){const s=t??[],r=e??[];return s.length!==r.length?!1:s.every((o,n)=>o===r[n])}const Rn=(t,e)=>{const s=t.map(n=>n.id);return e.map(n=>n.id).filter(n=>!s.includes(n))},_l=t=>t,Pn=t=>t,Um=({container:t,onAddItem:e,onUpdateItem:s,onRemoveItem:r=_l,idMapper:o=Pn})=>n=>{const i=n.map(o),c=Rn(i,t.data).map(r).filter(Boolean);t.removeAll(c);const u=i.map(d=>{const h=t.getModel(d.id);return h&&s?s(d,h):e(d)}).filter(Boolean);t.addAll(u)},jm=({container:t,onAddItem:e,onRemoveItem:s=_l,idMapper:r=Pn})=>o=>{const n=o.map(r);Rn(n,t.models).forEach(s),n.forEach(e)},Bm=({items:t,onAddItem:e,onRemoveItem:s,idMapper:r=Pn})=>o=>{const n=o.map(r);Rn(n,t).forEach(s),n.forEach(e)},Hm=(t,e="parent-")=>{let s=t;return s.startsWith(e)&&(s=s.replace(e,"")),s},Xi=new Intl.RelativeTimeFormat(void 0,{numeric:"auto"}),Ji=[{amount:60,name:"seconds"},{amount:60,name:"minutes"},{amount:24,name:"hours"},{amount:7,name:"days"},{amount:4.34524,name:"weeks"},{amount:12,name:"months"},{amount:Number.POSITIVE_INFINITY,name:"years"}];function Sl(t){let e=(t.getTime()-Date.now())/1e3;for(let s=0;s<=Ji.length;s++){const r=Ji[s];if(Math.abs(e)<r.amount)return Xi.format(Math.round(e),r.name);e/=r.amount}return Xi.format(Math.round(e),"years")}const kn=t=>t%4===0&&t%100!==0||t%400===0,Ln=(t,e)=>[31,kn(t)?29:28,31,30,31,30,31,31,30,31,30,31][e],Ol=(t,e)=>{const s=new Date(t),r=t.getDate();return s.setDate(1),s.setMonth(s.getMonth()+e),s.setDate(Math.min(r,Ln(s.getFullYear(),s.getMonth()))),s},Il=(t,e)=>{const s=new Date(t);return s.setDate(s.getDate()+e),s},kt="en-US",$l={short:{year:"numeric",month:"2-digit",day:"2-digit"},medium:{year:"numeric",month:"short",day:"2-digit"},long:{year:"numeric",month:"long",day:"numeric"},full:{year:"numeric",month:"long",day:"numeric",weekday:"long"}},Cl={short:{hour:"2-digit",minute:"2-digit",hour12:!0},medium:{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!0},long:{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!0,timeZoneName:"short"},full:{hour:"2-digit",minute:"2-digit",hour12:!0,timeZoneName:"long"}},Dl=(t,{dateStyle:e="short",locales:s=kt}={dateStyle:"short",locales:kt})=>{const r=e==="short"?$l.short:{dateStyle:e};return new Intl.DateTimeFormat(s,r).format(t)},xl=(t,{locales:e=kt,timeStyle:s="short"}={locales:kt,timeStyle:"short"})=>{const r=Cl[s];return new Intl.DateTimeFormat(e,r).format(t)},Al=(t,{dateStyle:e="short",locales:s=kt,timeStyle:r="short"}={dateStyle:"short",locales:kt,timeStyle:"short"})=>{const o={...e&&$l[e],...r&&Cl[r]};return new Intl.DateTimeFormat(s,o).format(t)},Km=Object.freeze(Object.defineProperty({__proto__:null,addDaysToDate:Il,addMonthsToDate:Ol,formatDate:Dl,formatDateSince:Sl,formatDateTime:Al,formatTime:xl,getDaysInMonth:Ln,isLeapYear:kn},Symbol.toStringTag,{value:"Module"})),Rl="featureFlagResolver",rr=new Map;zs(Rl,{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[];const r=s.map(a=>a(e)),n=(await Promise.allSettled(r)).map(a=>a.status==="fulfilled"?a.value:(m.info(`Feature flag resolver ${t} failed: ${a.reason}`),[])).flat(),i=Array.from(new Set(n)).reduce((a,c)=>(a[c]=!0,a),{});return kl.updateFlags(i),Object.keys(i)}});const qm="kos.loader.featureFlag";class Pl{constructor(e={}){l(this,"flags",{});this.flags=e}isFeatureEnabled(e){return!!this.flags[e]}enableFeature(e){this.flags[e]=!0}disableFeature(e){this.flags[e]=!1}toggleFeature(e){this.flags[e]=!this.flags[e]}updateFlags(e){this.flags={...this.flags,...e}}}window.KosFeatureFlags=window.KosFeatureFlags??new Pl;const kl=window.KosFeatureFlags,Ll=(t,e,s)=>{s/=100;const r=e*Math.min(s,1-s)/100,o=n=>{const i=(n+t/30)%12,a=s-r*Math.max(Math.min(i-3,9-i,1),-1);return Math.round(255*a).toString(16).padStart(2,"0")};return`#${o(0)}${o(8)}${o(4)}`},Fl=t=>{const s=new RegExp("hsl\\((\\d+),\\s+(\\d+)\\%,\\s+(\\d+)\\%\\)").exec(t);if(!s)throw Error("Invalid HSL string");return Ll(parseInt(s[1]),parseInt(s[2]),parseInt(s[3]))},Nl=(t,e)=>getComputedStyle(t).getPropertyValue(e),zm=(t,e)=>Fl(Nl(t,e)),Vm=(t,e)=>{const s={...t};return s.id&&delete s.id,s},zo=(t,e,s=Vm)=>{const r=s(t,e);M.runInAction(()=>{Object.assign(e,r)})};class Ul{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 Gm=async(t,e)=>{const s=new Ul;e.forEach(o=>s.use(o));const r={data:t,result:{}};return await s.execute(r),r.result},Qt=t=>({type:t,build:(e,s)=>S.getInstance().modelManager.createModelInstance(t,e,s).data,buildAsync:async(e,s)=>{const r=S.getInstance().modelManager.createModelInstance(t,e,s);return await r.model.whenInitialized(),r.data}}),Ym=t=>{S.getInstance().modelManager.registerModel(t)},Wm=(t,e)=>{S.getInstance().modelManager.registerCompanionModel(t,e)},ea="/kos/ui/internal/heartbeat/",Qm=({relationshipId:t,destinationAddress:e,onAbort:s,waitTime:r,beatTime:o})=>{const n=S.getInstance().transport,i=new AbortController;let a=performance.now();const c=n.subscribeTopic({topic:`${ea}${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(()=>{fl({msg:{},options:{topic:`${ea}${t}`,destinationAddress:e}})},h),p=()=>{window.clearInterval(f),window.clearInterval(d),c()},g=()=>{p(),s&&s(),i.signal.removeEventListener("abort",g)};return i.signal.addEventListener("abort",g),{cleanUpHeartbeat:p}},jl=(...t)=>e=>t.reduce((s,r)=>r(s),e),Zm={maxAttempts:5,baseDelayMs:100,backoffFactor:1.5};async function Xm(t,e){let s=1;const r={...Zm,...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 Jm=m.createLogger({name:"kos-service-request"}),ue=t=>({isMock:!1,URL:exports.BASE_URL}),ey=(t,e,s)=>async({id:r,tracker:o,urlOverride:n,ordered:i,studio:a,fos:c,bridge:u,timeout:d,signal:h,destinationAddress:f})=>{const p={method:"DELETE"};t&&(p.destinationAddress=t),o&&(p.tracker=o),Zt(p,{ordered:i,studio:a,fos:c,bridge:u,timeout:d,signal:h,destinationAddress:f});try{const g=await s(n||`${e}/${r}`,p);if(!g.ok)throw Error(`There was a problem deleting the model; returned status ${g.status}`);return await g.json()??void 0}catch(g){if(g instanceof DOMException){if(g.name==="TimeoutError")throw new z("Request timed out while deleting model");if(g.name==="AbortError")throw new z("Request was cancelled while deleting model")}throw g}},Zt=(t,{ordered:e,studio:s,fos:r,destinationAddress:o,bridge:n,timeout:i,signal:a})=>(i&&(t.timeout=i),a&&(t.signal=a),e&&(t.ordered=e),s&&(t.studio=s),r&&(t.fos=r),n&&(t.bridge=n),(o||o==="")&&(t.destinationAddress=o),t),ty=(t,e,s)=>async({urlOverride:r,ordered:o,studio:n,fos:i,bridge:a,timeout:c,signal:u,destinationAddress:d})=>{const h={method:"GET"};t&&(h.destinationAddress=t),Zt(h,{timeout:c,ordered:o,studio:n,fos:i,bridge:a,signal:u,destinationAddress:d});const f=r||e;try{const p=await s(f,h);if(!p.ok){let w;try{w=await p.json()}catch{}throw new z(`There was a problem retrieving the model; returned status ${p.status}`,w??void 0)}return await p.json()??void 0}catch(p){if(p instanceof DOMException){if(p.name==="TimeoutError")throw new z("Request timed out while retrieving models");if(p.name==="AbortError")throw new z("Request was cancelled while retrieving models")}throw p}},sy=(t,e,s)=>async({urlOverride:r,ordered:o,studio:n,fos:i,bridge:a,tracker:c,timeout:u,signal:d,destinationAddress:h})=>{const f={method:"GET"};t&&(f.destinationAddress=t),c&&(f.tracker=c),Zt(f,{timeout:u,ordered:o,studio:n,fos:i,bridge:a,signal:d,destinationAddress:h});const p=r||e;Jm.debug(`resolvedUrl: ${p}`);try{const g=await s(p,f);if(!g.ok){let E;try{E=await g.json()}catch{}throw new z(`There was a problem retrieving the model; returned status ${g.status}`,E??void 0)}return await g.json()??void 0}catch(g){if(g instanceof DOMException){if(g.name==="TimeoutError")throw new z("Request timed out while retrieving model");if(g.name==="AbortError")throw new z("Request was cancelled while retrieving model")}throw g}},ry=(t,e,s)=>async({urlOverride:r,id:o,ordered:n,studio:i,fos:a,bridge:c,timeout:u,signal:d,destinationAddress:h})=>{const f={method:"GET"};t&&(f.destinationAddress=t),Zt(f,{timeout:u,ordered:n,studio:i,fos:a,bridge:c,signal:d,destinationAddress:h});const p=r||`${e}/${o}`;try{const g=await s(p,f);if(!g.ok){let E;try{E=await g.json()}catch{}throw new z(`There was a problem retrieving the model; returned status ${g.status}`,E??void 0)}return await g.json()??void 0}catch(g){if(g instanceof DOMException){if(g.name==="TimeoutError")throw new z("Request timed out while retrieving model by ID");if(g.name==="AbortError")throw new z("Request was cancelled while retrieving model by ID")}throw g}};class z extends Error{constructor(s,r){super(s);l(this,"payload");this.name="FetchException",this.payload=r}}const ta=(t,e,s)=>async({model:r,urlOverride:o,ordered:n,tracker:i,studio:a,fos:c,bridge:u,timeout:d,signal:h,destinationAddress:f})=>{const p={method:"POST",body:typeof r=="string"?r:JSON.stringify(r)};t&&(p.destinationAddress=t),i&&(p.tracker=i),Zt(p,{timeout:d,ordered:n,studio:a,fos:c,bridge:u,signal:h,destinationAddress:f});try{const g=await s(o||e,p);if(!g.ok){let E;try{E=await g.json()}catch{}throw new z(`There was a problem sending the POST data; returned status ${g.status}`,E??void 0)}return await g.json()??void 0}catch(g){if(g instanceof DOMException){if(g.name==="TimeoutError")throw new z("Request timed out while adding model");if(g.name==="AbortError")throw new z("Request was cancelled while adding model")}throw g}},sa=(t="POST",e,s,r)=>async({model:o,id:n,urlOverride:i,ordered:a,studio:c,fos:u,bridge:d,timeout:h,signal:f,destinationAddress:p})=>{const g={method:t};o&&(g.body=JSON.stringify(o)),e&&(g.destinationAddress=e),Zt(g,{timeout:h,ordered:a,studio:c,fos:u,bridge:d,signal:f,destinationAddress:p});try{const w=await r(i||`${s}/${n}`,g);if(!w.ok){let _;try{_=await w.json()}catch{}throw new z(`There was a problem modifying the model; returned status ${w.status}`,_??void 0)}return await w.json()??void 0}catch(w){if(w instanceof DOMException){if(w.name==="TimeoutError")throw new z("Request timed out while modifying model");if(w.name==="AbortError")throw new z("Request was cancelled while modifying model")}throw w}},ie={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:ty(t,s||e,c),getModelById:ry(t,r||e,c),getOne:sy(t,r||e,c),addModel:ta(t,n||e,c),deleteModel:ey(t,o||e,c),modifyModel:sa("POST",t,i||e,c),putModel:sa("PUT",t,i||e,c),postModel:ta(t,n||e,c)}}};function oy(t,e,s="get"){const r=t.serviceResponses;if(r)return r.getByPath(e,s)}function ny(t,e,s="get"){const r=t.serviceResponses;return r?r.has(`${s.toUpperCase()}:${e}`):!1}function iy(t,e,s="get"){const r=t.serviceResponses;r&&r.delete(`${s.toUpperCase()}:${e}`)}function ay(t,e){const s=t.serviceResponses;s&&s.clearPath(e)}function cy(t){const e=t.serviceResponses;e&&e.clear()}const ly=bt(),Bl=()=>`kos-${ly}`,uy=t=>!!t&&!t.includes("VM_SERVICE")&&t.startsWith(Bl()),Fn=async(t,e=6e4)=>new Promise((s,r)=>{const{unsubscribe:o}=C(t,i=>{x.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)}),dy=async(t,e,s)=>{const r=Fn(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)},hy=async({topic:t,msg:e,requestId:s})=>{const r=s??bt(),o=Fn(r);K(t,e,{sync:r});const n=await o;if(n.error)throw Error(n.error);return n},ge=new Map;class Hl{constructor(e){l(this,"_context");l(this,"_parent");l(this,"_id");this._id=e,this._context=new M.ObservableMap({}),this._parent="",M.makeAutoObservable(this)}setParent(e){J(()=>{this._parent=e})}get id(){return this._id}get context(){return this._context}get parentModel(){var e;if(this._parent)return(e=Ae(this._parent))==null?void 0:e.model}get companionModels(){const e=Ae(this._id);return e!=null&&e.model?kc(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||!ge.has(n.id)?!1:(i=ge.get(n.id))==null?void 0:i.context.has(e)});if(o)return(s=ge.get(o.id))==null?void 0:s.get(e)}if(this._parent)return(r=ge.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 W={createContext:(t,e)=>{const s=ge.get(t)??new Hl(t);if(e){if(!ge.has(e))throw new Error(`Parent context ${e} does not exist`);s.setParent(e)}else t!=="root"&&s.setParent("root");return ge.set(t,s),s},getContext:t=>ge.get(t),deleteContext:t=>{ge.delete(t)},setParentContext:(t,e)=>{var s;if(!ge.has(e))throw new Error(`Parent context ${e} does not exist`);(s=ge.get(t))==null||s.setParent(e)},rootContext:()=>ge.get("root")};W.createContext("root");const fy=t=>W.getContext(t.id),it=m.createLogger({name:"kos-data-container"});class Nn{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=xe(),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 $n({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??[]:(it.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):(it.info(`key ${s} not found in ${e} index: ${Array.from(r.index.keys())}`),[])}else return it.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){it.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):(it.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);it.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){it.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 py{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 le.Factory.create(this.type)}get registration(){return{[this.type]:{class:this.model,singleton:!1,factory:this.factory},...this.childRegistration}}get predicate(){return Ie(this.type)}}class gy{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 le.Singleton.create(this.type)}get registration(){return{[this.type]:{class:this.model,singleton:!0,factory:this.factory},...this.childRegistration}}get predicate(){return Ie(this.type)}}class Kl{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 ql{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 zl=m.createLogger({name:"intent-service"}),my=t=>{fn(`/kos/intent/${t.type}`)?K(`/kos/intent/${t.type}`,t.options,{"kos.intent.type":t.type}):zl.info(`No subscribers for intent ${t.type}. Intent not sent.`)},yy=async t=>new Promise(e=>{const{type:s,options:r}=t;if(fn(`/kos/intent/${t.type}`)){const o=bt(),{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);K(`/kos/intent/${s}`,r,{"kos.intent.type":s,sync:o})}else zl.info(`No subscribers for intent ${t.type}. Intent not sent.`),e([null,{body:void 0,payload:void 0}])}),Ne=m.createLogger({name:"app-startup-service"});async function Vl(t,e={}){const{timeout:s=3e4,throwOnTimeout:r=!0,requirePostStarted:o=!1}=e;if(t.length===0)return Ne.warn("No app IDs provided to waitForAppsToStart"),!0;Ne.debug(`Waiting for apps to start: ${t.join(", ")}`);try{const n=t.map(c=>`/kos/app/started/${c}`),i=await mn(n,{getCurrentState:async()=>{try{const{default:c}=await Promise.resolve().then(()=>ml),[u,d]=await c.get("/api/kos/apps/started");return u?(Ne.error("Error fetching started apps:",u),[]):d}catch(c){Ne.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(Ne.error(c),r)throw new Error(`App startup timeout: ${c}`);return!1}return Ne.info(`All apps started successfully: ${t.join(", ")}`),!0}catch(n){const i=`Failed to wait for apps to start: ${t.join(", ")}`;if(Ne.error(i,n),r)throw new Error(`${i} - ${n instanceof Error?n.message:String(n)}`);return!1}}async function by(t,e={}){return Vl([t],e)}async function vy(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){Ne.error("Failed to check app startup status:",r),t.forEach(o=>s[o]=!1)}return s}async function wy(){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 Ne.error("Failed to fetch started apps:",t),[]}}const Vo=M.when,Un=M.computed,J=M.runInAction,Q=M.autorun,Gl=M.reaction,jn=M.observable,Bn="Not Assigned",Ey="kos.trouble.added",My="kos.trouble.removed";var _e=(t=>(t.TroubleRank="kos.trouble.rank.mapper",t.TroubleColor="kos.trouble.color.mapper",t.TroubleRole="kos.trouble.role.mapper",t))(_e||{}),Ss=(t=>(t.TIME_CHANGE="/kos/internal/time/time",t.DAY_CHANGE="/kos/internal/time/day",t.TIMEZONE_CHANGE="/kos/internal/time/timezone",t))(Ss||{});const Yl=m.createLogger({name:"config-bean-service",group:"Services"}),Hn=exports.BASE_URL,Wl=t=>(t==null?void 0:t.decimals)!==void 0,{postModel:Ty,getOne:_y}=ie.build({destinationAddress:"",basePath:`${Hn}/kos/config/`}),Ql=async(t,e,s="/api/kos/config")=>(Yl.debug(`sending modify request for ConfigBean: ${t}`),Ty({model:e,urlOverride:`${Hn}${s}/${t}`})),Zl=async(t,e="/api/kos/config")=>(Yl.debug(`sending get request for ConfigBean: ${t}`),await _y({urlOverride:`${Hn}${e}/details/${t}/15`})),Kn=t=>t.toLowerCase()==="true"||t.toLowerCase()==="false",ro=t=>{try{const e=Number(t);return!isNaN(e)}catch{return!1}};function Xl(t=[]){return t.reverse().reduce((e,s)=>{const{overrides:r}=s;return r&&(e={...e,...r}),e},{})}function Jl(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])?Jl(t[r],o,s):s[o]=t[r]}return s}const eu=(t,e)=>{const s=t.details[0].bean||Xl(t.details[0].scopes),r=Jl(s);M.runInAction(()=>{const o={...r};e.props.setValues(o)})},tu=(t,e)=>{M.runInAction(()=>{[...t.changes,...t.scopedChanges].forEach(r=>{const o=r.attr;let n=r.currentValue,i=r.previousValue;typeof n=="string"&&Kn(n)&&(n=n.toLowerCase()=="true",i=(i==null?void 0:i.toLowerCase())=="true"),typeof n=="string"&&ro(n)&&(n=Number(n),i=Number(i)),e.props[o]=n,e.prevProps[o]=i})})},su=t=>Object.fromEntries(t.props.entries),Sy=t=>e=>s=>t.build(e,s);var Oy=Object.defineProperty,Iy=Object.getOwnPropertyDescriptor,ru=(t,e,s,r)=>{for(var o=r>1?void 0:r?Iy(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&&Oy(e,s,o),o};function $y(t,e){for(const s of t)if(new RegExp(`^${s}$`).test(e))return s}const qn="config-bean-model",or=m.getLogger(qn),Cy=mt("path");let Tr=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=Ql,getConfigBean:r=Zl}=e;this._modifyConfigBean=s,this._getConfigBean=r,this.props=xe(),this.prevProps=xe()}get values(){return this.props.values}async ready(){or.debug(`readying config bean ${this.path}`),or.debug(`complete readying config bean ${this.path}`)}async load(){or.debug(`loading config bean ${this.path}`);const t=await this._getConfigBean(this.path,this.serviceBasePath);if(t!=null&&t.data){const e=t.data;eu(e,this),or.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=$y(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=su(this);await this._modifyConfigBean(this.path,t,this.serviceBasePath)}handleConfigBeanUpdated(t){tu(t,this)}};ru([B({topic:`/kos/config/${Cy}`,websocket:!0})],Tr.prototype,"handleConfigBeanUpdated",1);Tr=ru([R(qn)],Tr);const Cs=new ve({class:Tr,type:qn}),oo=({path:t,lazy:e,serviceBasePath:s})=>(r,o)=>{r[N]=r[N]||{},r[N][o]={modelType:Cs.type,id:`${Cs.type}-${t}`,options:{path:t,serviceBasePath:s},lifecycle:D.INIT,lazy:e}},{URL:ou}=ue(),{getOne:Dy,getAll:xy}=ie.build({basePath:`${ou}/api/kos/regions/info`}),nu=async()=>{try{return await Dy({})}catch{return}},iu=async()=>{try{return await xy({urlOverride:`${ou}/api/kos/regions`})}catch{return}},Ay=Object.freeze(Object.defineProperty({__proto__:null,getRegionInfo:nu,getRegions:iu},Symbol.toStringTag,{value:"Module"}));var he=(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))(he||{});const au={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 Ry(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},{...au});return{...t,...r}}function Py(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,n.alias&&(a[n.alias]=c),Object.hasOwn(n,"default")&&Object.defineProperty(a,"default",{value:c,writable:!0,enumerable:!0,configurable:!0}),o[n.measure]=i,o},{time:{[s]:{...au}}});return Object.keys(r).forEach(o=>{t[o]={...t[o],...r[o]}}),t}function ky(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 Ly=Object.defineProperty,Fy=Object.getOwnPropertyDescriptor,zn=(t,e,s,r)=>{for(var o=r>1?void 0:r?Fy(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&&Ly(e,s,o),o};const mr="region-info-model",ns=m.createLogger({name:"region-info-model"});let Ds=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[he.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[he.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[he.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[he.family]!==s[he.family])throw new Error(`Cannot convert between units of different families: ${e[he.family]} and ${s[he.family]}`);const r=e[he.offset],o=e[he.scale],n=s[he.scale],i=s[he.offset],a=s[he.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||ns.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||ns.info("Could not find default unit for measure",e.measure)}return!n||!i?(ns.warn("Could not find unit to convert to or from. Return value as is"),String(t)):this.convertByUnit(t,n,i)}async init(){ns.debug("initializing region info")}async load(){ns.debug("loading region info");const t=await iu();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 nu();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(Ry,{}),this.measureMap=e.data.unitSystems.reduce(Py,{}),this.defaultMeasureMap=e.data.unitSystems.reduce(ky,{}),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))}};zn([oo({path:"kos:service:region:settings"})],Ds.prototype,"regionSource",2);zn([oo({path:"kos:service:region"})],Ds.prototype,"region",2);Ds=zn([R(mr)],Ds);const ne={registration:{[mr]:{class:Ds,singleton:!0}},type:mr,factory:le.Singleton.create(mr)},_r=({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},Vn=(t,e,s)=>{const{model:r}=Ae(ne.type);if(!r)throw new Error("RegionInfo model not found");if(!Mr(r))throw new Error("RegionInfo model not ready");const o={system:r.defaultUnitSystem},n=_r({source:e}),i=_r({source:s||o,defaultMeasure:r.getUnitMeasure(n.unit||"")});return r.convert(t,n,i)};function ra(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 Ny=(t,e,s,r)=>{const o=Vn(t,e,s),n=_r({source:e}),{model:i}=Ae(ne.type);if(!i)throw new Error("RegionInfo model not found");const a=i.getUnitMeasure(n.unit||""),c={system:i.defaultUnitSystem},u=_r({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:ra(o,d||n.unit||"",{...f,mode:"long"}),shortDisplay:ra(o,d||n.unit||"",{...f,mode:"short"})}};function oa({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 na({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 St=(t,e)=>s=>!t||!e?s:ro(s)?Vn(Number(s),t,e):s,Uy=(t,e,s,r)=>{if((t==null?void 0:t.type)==="enum"||!(t!=null&&t.options))return[];if(t.options.type==="rangeCount")return oa(t.options).map(St(s,r));if(t.options.type==="rangeInterval")return na(t.options).map(St(s,r));if(t.options.type==="list"){const{list:o}=t.options;return o.map(St(s,r))}else{if(t.options.type==="unitSystemRangeCount"&&e)return oa(t.options.unitSystems[e]).map(St(s,r));if(t.options.type==="unitSystemRangeInterval"&&e)return na(t.options.unitSystems[e]).map(St(s,r));if(t.options.type==="unitSystemList"&&e){const{list:o}=t.options.unitSystems[e];return o.map(St(s,r))}}return[]},jy=(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 By=Object.defineProperty,Hy=Object.getOwnPropertyDescriptor,Gn=(t,e,s,r)=>{for(var o=r>1?void 0:r?Hy(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&&By(e,s,o),o};function Ky(t){return(t==null?void 0:t.type)==="enum"}function qy(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 zy(t,e){const s=new Date;s.setHours(0,0,0,0);const r=new Date(s.getTime()+t*1e3);return We.format(r,e)}const yr="config-bean-prop-model",Ot=m.createLogger({name:"config-bean-prop-model"}),Vy=mt("path"),Gy=mt("serviceBasePath");let xs=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 Wl(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?qy(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=Ky(r)?r.values:Uy(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){Ot.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(){Ot.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 zy(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){Ot.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 jy(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){Ot.error(`error creating formatter ${d}. Returning the raw value`,h)}}else Ot.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 g=(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,_=g||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),I=((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:I},measure:_}}if(s&&e){const g=this.regionInfo.getDefaultUnitForMeasure(e,this.regionInfo.defaultUnitSystem),w=this.regionInfo.getUnitSystem(s),E=this.regionInfo.getUnitSystem(g);return{measure:e,to:{unit:w===E?s:g}}}}async updateProperty(t){Ot.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)}};Gn([Wt({modelType:ne.type})],xs.prototype,"regionInfo",2);Gn([oo({path:Vy,serviceBasePath:Gy})],xs.prototype,"bean",2);xs=Gn([R(yr)],xs);const vt={registration:{[yr]:{class:xs,singleton:!1}},type:yr,factory:le.Factory.create(yr)};function Yy(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[N]=u[N]||{},u[N][d]={modelType:vt.type,id:`${e}-${s}`,options:{path:e,attribute:s,serviceBasePath:a,converter:c,formatter:o,optionsExpander:i},lifecycle:D.INIT,lazy:n}}}const cu="future-model",Xt=Qt(cu),no=m.createLogger({name:"future-service",group:"Services"}),{isMock:Wy,URL:Vs}=ue();var Je=(t=>(t.Success="SUCCESS",t.Fail="FAIL",t.Aborted="ABORT",t.Canceled="CANCEL",t))(Je||{});const{getAll:Qy,modifyModel:Zy,addModel:Xy,deleteModel:Jy,postModel:eb}=ie.build({destinationAddress:"",basePath:`${Vs}/api/future`,mock:Wy}),tb=async()=>await Qy({}),lu=async(t,e="/api/kos/future")=>(no.info(`sending delete request for Future: ${t}`),await Jy({id:t,urlOverride:`${Vs}${e}/${t}`})),uu=async(t,e="/api/kos/future")=>(no.info("sending add request for Future"),await Xy({model:t,urlOverride:`${Vs}${e}`})),sb=async(t,e,s="/api/kos/future")=>(no.info(`sending modify request for Future: ${t}`),Zy({model:e,id:t,urlOverride:`${Vs}${s}/${t}`})),du=async(t,e="/api/kos/future")=>(no.info(`sending cancel request for Future: ${t}`),eb({urlOverride:`${Vs}${e}/${t}/cancel`,ordered:!0,model:{}})),Yn=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}),Wn=(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=Yn(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]})})}))},hu=t=>e=>s=>t.build(String(e),s),Qn=t=>e=>jl(Yn,hu(t)(e.tracker||e.id))(e);var rb=Object.defineProperty,ob=Object.getOwnPropertyDescriptor,fu=(t,e,s,r)=>{for(var o=r>1?void 0:r?ob(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&rb(e,s,o),o};const xo=m.getLogger(Xt.type);let Sr=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=du,Vo(()=>this.status===Je.Success||this.status===Je.Fail,()=>{xo.info(`Future ${this.id} has completed with status ${this.status}`),De(this)})}async load(){xo.debug(`loading Future ${this.id}`)}unload(){xo.info(`unloading Future ${this.id}`)}async cancelFuture(){const t=this.namespace==="studio"?"/api/future":`/api/${this.namespace}/future`;await Vo(()=>this.futureId!==Bn),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}`),Wn(t,this)}};fu([B({topic:`kos.future/${vr}`})],Sr.prototype,"handleFutureUpdated",1);Sr=fu([R(Xt.type)],Sr);const pu=Sr,gu=Ve();var nb=Object.defineProperty,ib=Object.getOwnPropertyDescriptor,mu=(t,e,s,r)=>{for(var o=r>1?void 0:r?ib(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&&nb(e,s,o),o};const yu="browser-router-model",ab="kos.http.request",cb="kos.http.response";let Or=class{constructor(t,e,s){l(this,"_id");l(this,"logger");l(this,"router");this._id=t,this.logger=s.logger,this.router=new ql}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),pl({msg:d,options:{responseId:i,destinationAddress:s,type:cb,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}`)}};mu([B({topic:ab})],Or.prototype,"handleRequest",1);Or=mu([R(yu)],Or);const Zn=new $e({class:Or,type:yu}),bu="future-container-model",et=Qt(bu),vu=t=>Qn(Xt)(t),lb=t=>{const e=vu(t);return et.build(et.type,{}).addFutureModel(e),e},ub=t=>et.build(et.type,{}).getFuture(String(t)),pt={buildFutureModel:vu,initiateFuture:lb,getFuture:ub};var db=Object.defineProperty,hb=Object.getOwnPropertyDescriptor,Xn=(t,e,s,r)=>{for(var o=r>1?void 0:r?hb(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&&db(e,s,o),o};const nr=m.getLogger(et.type);let As=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=lu,addFuture:o=uu}=e;this.logger=s.logger,this._deleteFuture=r,this._addFuture=o,this.id=t,this._futures=new ke,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){nr.error("error deleting a Future"),nr.error(e)}}async createFuture(t){try{const e=await this._addFuture(t),s=e==null?void 0:e.data;if(s){const r=Qn(Xt)(s);return this.addFutureModel(r),r}}catch(e){throw nr.error("error creating a Future"),nr.error(e),e}}handleFutureUpdated(t,e){const s=pt.buildFutureModel(t);this.addFutureModel(s);const r=`kos.future/${t.tracker||t.id}`;this.logger.debug(`publishing future update to ${r}`),K(r,e.body,e.headers)}};Xn([Pe],As.prototype,"_futures",2);Xn([B({topic:"kos.future"})],As.prototype,"handleFutureUpdated",1);As=Xn([R(et.type)],As);const wu=As,{URL:Gs}=ue(),{getOne:fb,postModel:pb,deleteModel:Eu}=ie.build({basePath:`${Gs}/api/keyVal`}),Go=m.createLogger({name:"key-value-service",group:"Services"}),Mu=async(t,e)=>{await Eu({urlOverride:`${Gs}/api/keyVal/${t}/${e}`,id:e})},Tu=async(t,e,s)=>{const r=await pb({urlOverride:`${Gs}/api/keyVal/${t}/${e}`,model:s.toString()});if((r==null?void 0:r.status)!==200)throw Go.error("Failed to update key-value data",r),new Error(`Failed to update key-value data for namespace ${t}`);return r.data},_u=async(t="studio")=>{Go.debug(`Retrieving all key-value data for namespace: ${t}`);const e=await fb({urlOverride:`${Gs}/api/keyVal/${t}`});if((e==null?void 0:e.status)!==200)throw Go.error("Failed to retrieve key-value data",e),new Error(`Failed to retrieve key-value data for namespace ${t}`);return e.data},gb=async t=>{await Eu({urlOverride:`${Gs}/api/keyVal/${t}`,id:""})},mb=Object.freeze(Object.defineProperty({__proto__:null,deleteKeyValue:Mu,deleteKeyValueNamespace:gb,getKeyValue:_u,updateKeyValue:Tu},Symbol.toStringTag,{value:"Module"}));var yb=Object.defineProperty,bb=Object.getOwnPropertyDescriptor,Jn=(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=(r?i(e,s,o):i(o))||o);return r&&o&&yb(e,s,o),o};const Su="key-value-model";let Rs=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=xe(),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 Tu(this.namespace,t,e),this.data[t]=e):(await Mu(this.namespace,t),this.data[t]=void 0)}async load(){this.logger.debug(`loading studio-state ${this.id}`);const t=await _u(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)}};Jn([B({topic:"/keyVal/set"})],Rs.prototype,"handleStateUpdate",1);Jn([B({topic:"/keyVal/remove"})],Rs.prototype,"handleStateDelete",1);Rs=Jn([R(Su)],Rs);const ei=new ve({class:Rs,type:Su});var me="INUMBER",Jt="IOP1",es="IOP2",ts="IOP3",Be="IVAR",gt="IVARNAME",Lt="IFUNCALL",io="IFUNDEF",ce="IEXPR",ti="IEXPREVAL",wt="IMEMBER",ao="IENDSTATEMENT",Ft="IARRAY";function P(t,e){this.type=t,this.value=e??0}P.prototype.toString=function(){switch(this.type){case me:case Jt:case es:case ts:case Be:case gt:case ao:return this.value;case Lt:return"CALL "+this.value;case io:return"DEF "+this.value;case Ft:return"ARRAY "+this.value;case wt:return"."+this.value;default:return"Invalid Instruction"}};function co(t){return new P(Jt,t)}function Ge(t){return new P(es,t)}function Ou(t){return new P(ts,t)}function Yo(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===me||p===gt)Array.isArray(f.value)?n.push.apply(n,Yo(f.value.map(function(g){return new P(me,g)}).concat(new P(Ft,f.value.length)),e,s,r,o)):n.push(f);else if(p===Be&&o.hasOwnProperty(f.value))f=new P(me,o[f.value]),n.push(f);else if(p===es&&n.length>1)c=n.pop(),a=n.pop(),d=s[f.value],f=new P(me,d(a.value,c.value)),n.push(f);else if(p===ts&&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(me,d(a.value,c.value,u.value)),n.push(f));else if(p===Jt&&n.length>0)a=n.pop(),d=e[f.value],f=new P(me,d(a.value)),n.push(f);else if(p===ce){for(;n.length>0;)i.push(n.shift());i.push(new P(ce,Yo(f.value,e,s,r,o)))}else if(p===wt&&n.length>0)a=n.pop(),n.push(new P(me,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 Iu(t,e,s){for(var r=[],o=0;o<t.length;o++){var n=t[o],i=n.type;if(i===Be&&n.value===e)for(var a=0;a<s.tokens.length;a++){var c=s.tokens[a],u;c.type===Jt?u=co(c.value):c.type===es?u=Ge(c.value):c.type===ts?u=Ou(c.value):u=new P(c.type,c.value),r.push(u)}else i===ce?r.push(new P(ce,Iu(n.value,e,s))):r.push(n)}return r}function ut(t,e,s){var r=[],o,n,i,a,c,u;if(si(t))return Fe(t,s);for(var d=t.length,h=0;h<d;h++){var f=t[h],p=f.type;if(p===me||p===gt)r.push(f.value);else if(p===es)n=r.pop(),o=r.pop(),f.value==="and"?r.push(o?!!ut(n,e,s):!1):f.value==="or"?r.push(o?!0:!!ut(n,e,s)):f.value==="="?(a=e.binaryOps[f.value],r.push(a(o,ut(n,e,s),s))):(a=e.binaryOps[f.value],r.push(a(Fe(o,s),Fe(n,s))));else if(p===ts)i=r.pop(),n=r.pop(),o=r.pop(),f.value==="?"?r.push(ut(o?n:i,e,s)):(a=e.ternaryOps[f.value],r.push(a(Fe(o,s),Fe(n,s),Fe(i,s))));else if(p===Be)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 g=s[f.value];if(g!==void 0)r.push(g);else throw new Error("undefined variable: "+f.value)}else if(p===Jt)o=r.pop(),a=e.unaryOps[f.value],r.push(a(Fe(o,s)));else if(p===Lt){for(u=f.value,c=[];u-- >0;)c.unshift(Fe(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===io)r.push(function(){for(var w=r.pop(),E=[],_=f.value;_-- >0;)E.unshift(r.pop());var k=r.pop(),I=function(){for(var O=Object.assign({},s),F=0,X=E.length;F<X;F++)O[E[F]]=arguments[F];return ut(w,e,O)};return Object.defineProperty(I,"name",{value:k,writable:!1}),s[k]=I,I}());else if(p===ce)r.push(vb(f,e));else if(p===ti)r.push(f);else if(p===wt)o=r.pop(),r.push(o[f.value]);else if(p===ao)r.pop();else if(p===Ft){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:Fe(r[0],s)}function vb(t,e,s){return si(t)?t:{type:ti,value:function(r){return ut(t.value,e,r)}}}function si(t){return t&&t.type===ti}function Fe(t,e){return si(t)?t.value(e):t}function ri(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===me)typeof d.value=="number"&&d.value<0?s.push("("+d.value+")"):Array.isArray(d.value)?s.push("["+d.value.map(ia).join(", ")+"]"):s.push(ia(d.value));else if(h===es)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===ts)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===Be||h===gt)s.push(d.value);else if(h===Jt)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===Lt){for(c=d.value,a=[];c-- >0;)a.unshift(s.pop());i=s.pop(),s.push(i+"("+a.join(", ")+")")}else if(h===io){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===wt)r=s.pop(),s.push(r+"."+d.value);else if(h===Ft){for(c=d.value,a=[];c-- >0;)a.unshift(s.pop());s.push("["+a.join(", ")+"]")}else if(h===ce)s.push("("+ri(d.value,e)+")");else if(h!==ao)throw new Error("invalid Expression")}return s.length>1&&(e?s=[s.join(",")]:s=[s.join(";")]),String(s[0])}function ia(t){return typeof t=="string"?JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029"):t}function Dt(t,e){for(var s=0;s<t.length;s++)if(t[s]===e)return!0;return!1}function oi(t,e,s){s=s||{};for(var r=!!s.withMembers,o=null,n=0;n<t.length;n++){var i=t[n];i.type===Be||i.type===gt?!r&&!Dt(e,i.value)?e.push(i.value):(o!==null&&(Dt(e,o)||e.push(o)),o=i.value):i.type===wt&&r&&o!==null?o+="."+i.value:i.type===ce?oi(i.value,e,s):o!==null&&(Dt(e,o)||e.push(o),o=null)}o!==null&&!Dt(e,o)&&e.push(o)}function Se(t,e){this.tokens=t,this.parser=e,this.unaryOps=e.unaryOps,this.binaryOps=e.binaryOps,this.ternaryOps=e.ternaryOps,this.functions=e.functions}Se.prototype.simplify=function(t){return t=t||{},new Se(Yo(this.tokens,this.unaryOps,this.binaryOps,this.ternaryOps,t),this.parser)};Se.prototype.substitute=function(t,e){return e instanceof Se||(e=this.parser.parse(String(e))),new Se(Iu(this.tokens,t,e),this.parser)};Se.prototype.evaluate=function(t){return t=t||{},ut(this.tokens,this,t)};Se.prototype.toString=function(){return ri(this.tokens,!1)};Se.prototype.symbols=function(t){t=t||{};var e=[];return oi(this.tokens,e,t),e};Se.prototype.variables=function(t){t=t||{};var e=[];oi(this.tokens,e,t);var s=this.functions;return e.filter(function(r){return!(r in s)})};Se.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 "+ri(this.simplify(e).tokens,!0)+"; }");return function(){return r.apply(s,arguments)}};var Ps="TEOF",j="TOP",lo="TNUMBER",$u="TSTRING",He="TPAREN",Nt="TBRACKET",uo="TCOMMA",ni="TNAME",ii="TSEMICOLON";function Cu(t,e,s){this.type=t,this.value=e,this.index=s}Cu.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 Cu(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(Ps,"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($u,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(He,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(Nt,t),this.pos++,!0):!1};G.prototype.isComma=function(){var t=this.expression.charAt(this.pos);return t===","?(this.current=this.newToken(uo,","),this.pos++,!0):!1};G.prototype.isSemicolon=function(){var t=this.expression.charAt(this.pos);return t===";"?(this.current=this.newToken(ii,";"),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(lo,this.consts[r]),this.pos+=r.length,!0}return!1};G.prototype.isNamedOp=function(){for(var t=this.pos,e=t;e<this.expression.length;e++){var s=this.expression.charAt(e);if(s.toUpperCase()===s.toLowerCase()&&(e===this.pos||s!=="_"&&(s<"0"||s>"9")))break}if(e>t){var r=this.expression.substring(t,e);if(this.isOperatorEnabled(r)&&(r in this.binaryOps||r in this.unaryOps||r in this.ternaryOps))return this.current=this.newToken(j,r),this.pos+=r.length,!0}return!1};G.prototype.isName=function(){for(var t=this.pos,e=t,s=!1;e<this.expression.length;e++){var r=this.expression.charAt(e);if(r.toUpperCase()===r.toLowerCase()){if(e===this.pos&&(r==="$"||r==="_")){r==="_"&&(s=!0);continue}else if(e===this.pos||!s||r!=="_"&&(r<"0"||r>"9"))break}else s=!0}if(s){var o=this.expression.substring(t,e);return this.current=this.newToken(ni,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 wb=/^[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);wb.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(lo,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(lo,parseFloat(this.expression.substring(s,e))),this.pos=e):this.pos=r,t};G.prototype.isOperator=function(){var t=this.pos,e=this.expression.charAt(this.pos);if(e==="+"||e==="-"||e==="*"||e==="/"||e==="%"||e==="^"||e==="?"||e===":"||e===".")this.current=this.newToken(j,e);else if(e==="∙"||e==="•")this.current=this.newToken(j,"*");else if(e===">")this.expression.charAt(this.pos+1)==="="?(this.current=this.newToken(j,">="),this.pos++):this.current=this.newToken(j,">");else if(e==="<")this.expression.charAt(this.pos+1)==="="?(this.current=this.newToken(j,"<="),this.pos++):this.current=this.newToken(j,"<");else if(e==="|")if(this.expression.charAt(this.pos+1)==="|")this.current=this.newToken(j,"||"),this.pos++;else return!1;else if(e==="=")this.expression.charAt(this.pos+1)==="="?(this.current=this.newToken(j,"=="),this.pos++):this.current=this.newToken(j,e);else if(e==="!")this.expression.charAt(this.pos+1)==="="?(this.current=this.newToken(j,"!="),this.pos++):this.current=this.newToken(j,e);else return!1;return this.pos++,this.isOperatorEnabled(this.current.value)?!0:(this.pos=t,!1)};G.prototype.isOperatorEnabled=function(t){return this.parser.isOperatorEnabled(t)};G.prototype.getCoordinates=function(){var t=0,e,s=-1;do t++,e=this.pos-s,s=this.expression.indexOf(`
|
|
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 q(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}q.prototype.next=function(){return this.current=this.nextToken,this.nextToken=this.tokens.next()};q.prototype.tokenMatches=function(t,e){return typeof e>"u"?!0:Array.isArray(e)?Dt(e,t.value):typeof e=="function"?e(t):t.value===e};q.prototype.save=function(){this.savedCurrent=this.current,this.savedNextToken=this.nextToken,this.tokens.save()};q.prototype.restore=function(){this.tokens.restore(),this.current=this.savedCurrent,this.nextToken=this.savedNextToken};q.prototype.accept=function(t,e){return this.nextToken.type===t&&this.tokenMatches(this.nextToken,e)?(this.next(),!0):!1};q.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))}};q.prototype.parseAtom=function(t){var e=this.tokens.unaryOps;function s(o){return o.value in e}if(this.accept(ni)||this.accept(j,s))t.push(new P(Be,this.current.value));else if(this.accept(lo))t.push(new P(me,this.current.value));else if(this.accept($u))t.push(new P(me,this.current.value));else if(this.accept(He,"("))this.parseExpression(t),this.expect(He,")");else if(this.accept(Nt,"["))if(this.accept(Nt,"]"))t.push(new P(Ft,0));else{var r=this.parseArrayList(t);t.push(new P(Ft,r))}else throw new Error("unexpected "+this.nextToken)};q.prototype.parseExpression=function(t){var e=[];this.parseUntilEndStatement(t,e)||(this.parseVariableAssignmentExpression(e),!this.parseUntilEndStatement(t,e)&&this.pushExpression(t,e))};q.prototype.pushExpression=function(t,e){for(var s=0,r=e.length;s<r;s++)t.push(e[s])};q.prototype.parseUntilEndStatement=function(t,e){return this.accept(ii)?(this.nextToken&&this.nextToken.type!==Ps&&!(this.nextToken.type===He&&this.nextToken.value===")")&&e.push(new P(ao)),this.nextToken.type!==Ps&&this.parseExpression(e),t.push(new P(ce,e)),!0):!1};q.prototype.parseArrayList=function(t){for(var e=0;!this.accept(Nt,"]");)for(this.parseExpression(t),++e;this.accept(uo);)this.parseExpression(t),++e;return e};q.prototype.parseVariableAssignmentExpression=function(t){for(this.parseConditionalExpression(t);this.accept(j,"=");){var e=t.pop(),s=[],r=t.length-1;if(e.type===Lt){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===Be&&(t[i]=new P(gt,t[i].value))}this.parseVariableAssignmentExpression(s),t.push(new P(ce,s)),t.push(new P(io,e.value));continue}if(e.type!==Be&&e.type!==wt)throw new Error("expected variable for assignment");this.parseVariableAssignmentExpression(s),t.push(new P(gt,e.value)),t.push(new P(ce,s)),t.push(Ge("="))}};q.prototype.parseConditionalExpression=function(t){for(this.parseOrExpression(t);this.accept(j,"?");){var e=[],s=[];this.parseConditionalExpression(e),this.expect(j,":"),this.parseConditionalExpression(s),t.push(new P(ce,e)),t.push(new P(ce,s)),t.push(Ou("?"))}};q.prototype.parseOrExpression=function(t){for(this.parseAndExpression(t);this.accept(j,"or");){var e=[];this.parseAndExpression(e),t.push(new P(ce,e)),t.push(Ge("or"))}};q.prototype.parseAndExpression=function(t){for(this.parseComparison(t);this.accept(j,"and");){var e=[];this.parseComparison(e),t.push(new P(ce,e)),t.push(Ge("and"))}};var Eb=["==","!=","<","<=",">=",">","in"];q.prototype.parseComparison=function(t){for(this.parseAddSub(t);this.accept(j,Eb);){var e=this.current;this.parseAddSub(t),t.push(Ge(e.value))}};var Mb=["+","-","||"];q.prototype.parseAddSub=function(t){for(this.parseTerm(t);this.accept(j,Mb);){var e=this.current;this.parseTerm(t),t.push(Ge(e.value))}};var Tb=["*","/","%"];q.prototype.parseTerm=function(t){for(this.parseFactor(t);this.accept(j,Tb);){var e=this.current;this.parseFactor(t),t.push(Ge(e.value))}};q.prototype.parseFactor=function(t){var e=this.tokens.unaryOps;function s(o){return o.value in e}if(this.save(),this.accept(j,s)){if(this.current.value!=="-"&&this.current.value!=="+"){if(this.nextToken.type===He&&this.nextToken.value==="("){this.restore(),this.parseExponential(t);return}else if(this.nextToken.type===ii||this.nextToken.type===uo||this.nextToken.type===Ps||this.nextToken.type===He&&this.nextToken.value===")"){this.restore(),this.parseAtom(t);return}}var r=this.current;this.parseFactor(t),t.push(co(r.value))}else this.parseExponential(t)};q.prototype.parseExponential=function(t){for(this.parsePostfixExpression(t);this.accept(j,"^");)this.parseFactor(t),t.push(Ge("^"))};q.prototype.parsePostfixExpression=function(t){for(this.parseFunctionCall(t);this.accept(j,"!");)t.push(co("!"))};q.prototype.parseFunctionCall=function(t){var e=this.tokens.unaryOps;function s(n){return n.value in e}if(this.accept(j,s)){var r=this.current;this.parseAtom(t),t.push(co(r.value))}else for(this.parseMemberExpression(t);this.accept(He,"(");)if(this.accept(He,")"))t.push(new P(Lt,0));else{var o=this.parseArgumentList(t);t.push(new P(Lt,o))}};q.prototype.parseArgumentList=function(t){for(var e=0;!this.accept(He,")");)for(this.parseExpression(t),++e;this.accept(uo);)this.parseExpression(t),++e;return e};q.prototype.parseMemberExpression=function(t){for(this.parseAtom(t);this.accept(j,".")||this.accept(Nt,"[");){var e=this.current;if(e.value==="."){if(!this.allowMemberAccess)throw new Error('unexpected ".", member access is not permitted');this.expect(ni),t.push(new P(wt,this.current.value))}else if(e.value==="["){if(!this.tokens.isOperatorEnabled("["))throw new Error('unexpected "[]", arrays are disabled');this.parseExpression(t),this.expect(Nt,"]"),t.push(Ge("["))}else throw new Error("unexpected symbol: "+e.value)}};function _b(t,e){return Number(t)+Number(e)}function Sb(t,e){return t-e}function Ob(t,e){return t*e}function Ib(t,e){return t/e}function $b(t,e){return t%e}function Cb(t,e){return Array.isArray(t)&&Array.isArray(e)?t.concat(e):""+t+e}function Db(t,e){return t===e}function xb(t,e){return t!==e}function Ab(t,e){return t>e}function Rb(t,e){return t<e}function Pb(t,e){return t>=e}function kb(t,e){return t<=e}function Lb(t,e){return!!(t&&e)}function Fb(t,e){return!!(t||e)}function Nb(t,e){return Dt(e,t)}function Ub(t){return(Math.exp(t)-Math.exp(-t))/2}function jb(t){return(Math.exp(t)+Math.exp(-t))/2}function Bb(t){return t===1/0?1:t===-1/0?-1:(Math.exp(t)-Math.exp(-t))/(Math.exp(t)+Math.exp(-t))}function Hb(t){return t===-1/0?t:Math.log(t+Math.sqrt(t*t+1))}function Kb(t){return Math.log(t+Math.sqrt(t*t-1))}function qb(t){return Math.log((1+t)/(1-t))/2}function aa(t){return Math.log(t)*Math.LOG10E}function zb(t){return-t}function Vb(t){return!t}function Gb(t){return t<0?Math.ceil(t):Math.floor(t)}function Yb(t){return Math.random()*(t||1)}function ca(t){return ai(t+1)}function Wb(t){return isFinite(t)&&t===Math.round(t)}var Qb=4.7421875,Ao=[.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 ai(t){var e,s;if(Wb(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)*ai(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=Ao[0];for(var u=1;u<Ao.length;++u)s+=Ao[u]/(t+u);return e=t+Qb+.5,Math.sqrt(2*Math.PI)*Math.pow(e,t+.5)*Math.exp(-e)*s}function Zb(t){return Array.isArray(t)?t.length:String(t).length}function la(){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 ua(t,e,s){return t?e:s}function Xb(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 Jb(t,e,s){return s&&(s[t]=e),e}function ev(t,e){return t[e|0]}function tv(t){return arguments.length===1&&Array.isArray(t)?Math.max.apply(Math,t):Math.max.apply(Math,arguments)}function sv(t){return arguments.length===1&&Array.isArray(t)?Math.min.apply(Math,t):Math.min.apply(Math,arguments)}function rv(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 ov(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 nv(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 iv(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 av(t,e){if(!Array.isArray(e))throw new Error("Second argument to join is not an array");return e.join(t)}function cv(t){return(t>0)-(t<0)||+t}var da=1/3;function lv(t){return t<0?-Math.pow(-t,da):Math.pow(t,da)}function uv(t){return Math.exp(t)-1}function dv(t){return Math.log(1+t)}function hv(t){return Math.log(t)/Math.LN2}function Et(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||Ub,cosh:Math.cosh||jb,tanh:Math.tanh||Bb,asinh:Math.asinh||Hb,acosh:Math.acosh||Kb,atanh:Math.atanh||qb,sqrt:Math.sqrt,cbrt:Math.cbrt||lv,log:Math.log,log2:Math.log2||hv,ln:Math.log,lg:Math.log10||aa,log10:Math.log10||aa,expm1:Math.expm1||uv,log1p:Math.log1p||dv,abs:Math.abs,ceil:Math.ceil,floor:Math.floor,round:Math.round,trunc:Math.trunc||Gb,"-":zb,"+":Number,exp:Math.exp,not:Vb,length:Zb,"!":ca,sign:Math.sign||cv},this.binaryOps={"+":_b,"-":Sb,"*":Ob,"/":Ib,"%":$b,"^":Math.pow,"||":Cb,"==":Db,"!=":xb,">":Ab,"<":Rb,">=":Pb,"<=":kb,and:Lb,or:Fb,in:Nb,"=":Jb,"[":ev},this.ternaryOps={"?":ua},this.functions={random:Yb,fac:ca,min:sv,max:tv,hypot:Math.hypot||la,pyt:Math.hypot||la,pow:Math.pow,atan2:Math.atan2,if:ua,gamma:ai,roundTo:Xb,map:rv,fold:ov,filter:nv,indexOf:iv,join:av},this.consts={E:Math.E,PI:Math.PI,true:!0,false:!1}}Et.prototype.parse=function(t){var e=[],s=new q(this,new G(this,t),{allowMemberAccess:this.options.allowMemberAccess});return s.parseExpression(e),s.expect(Ps,"EOF"),new Se(e,this)};Et.prototype.evaluate=function(t,e){return this.parse(t).evaluate(e)};var Du=new Et;Et.parse=function(t){return Du.parse(t)};Et.evaluate=function(t,e){return Du.parse(t).evaluate(e)};var ha={"+":"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 fv(t){return ha.hasOwnProperty(t)?ha[t]:t}Et.prototype.isOperatorEnabled=function(t){var e=fv(t),s=this.options.operators||{};return!(e in s)||!!s[e]};var pv=Object.defineProperty,gv=Object.getOwnPropertyDescriptor,mv=(t,e,s)=>e in t?pv(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,yv=(t,e,s,r)=>{for(var o=r>1?void 0:r?gv(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o},bv=(t,e,s)=>(mv(t,e+"",s),s);const vv="kos-expression-evaluator-model";class wv{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 Ir=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=xe(),this._results=xe(),this.parser=new Et,this.parser.functions.exists=r=>r!=null,this.parser.functions.isEmpty=r=>r==null?!0:typeof r=="string"||Array.isArray(r)?r.length===0:typeof r=="object"?Object.keys(r).length===0:!1}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 wv(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=bt();return this.addExpression(e,t),e}};bv(Ir,"Registration");Ir=yv([R({modelTypeId:vv,singleton:!1})],Ir);const xu=Ir.Registration,Ev=m.createLogger({name:"kos-log-manager-service",group:"Services"}),Mv="/api/kos/logs/overrides",Au=async()=>(Ev.debug("sending GET for kos-log-manager"),await Le.get(Mv)),Tv=Object.freeze(Object.defineProperty({__proto__:null,getLogOverrides:Au},Symbol.toStringTag,{value:"Module"}));var _v=Object.defineProperty,Sv=Object.getOwnPropertyDescriptor,ho=(t,e,s,r)=>{for(var o=r>1?void 0:r?Sv(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&&_v(e,s,o),o};const Ru="kos-log-manager-model",Ov="/kos/logs/override/add/*",Iv="/kos/logs/override/remove/*",$v=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 Ut=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_overrides");this.id=t,this.logger=s.logger,this._overrides=new Nn}updateModel(t){}resolveLoggers(){const t=m.getLoggers(),s=Object.entries(t).map(([r,o])=>({name:r,level:$v(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 Au();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)})}};ho([Ec("/api/kos/ui/loggers")],Ut.prototype,"getAllLoggers",1);ho([B({topic:Ov,websocket:!0,wildcardName:"nodeType"})],Ut.prototype,"handleOverrideAdded",1);ho([B({topic:Iv,websocket:!0,wildcardName:"nodeType"})],Ut.prototype,"handleOverrideRemoved",1);Ut=ho([R(Ru)],Ut);const Pu=new $e({class:Ut,type:Ru}),{URL:Ys}=ue(),{postModel:ci,getOne:Cv}=ie.build({basePath:`${Ys}/api/kos-time`});m.createLogger({name:"kos-time-service",group:"Services"});const ku=async t=>{const e=await ci({model:t,urlOverride:`${Ys}/api/kos/time/time`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set time");return e.data},Lu=async t=>{const e=await ci({model:t,urlOverride:`${Ys}/api/kos/time/date`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set time");return e.data},Fu=async t=>{const e=await ci({model:{},urlOverride:`${Ys}/api/kos/time/timezone?tz=${t}`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set timezone");return e.data},Nu=async()=>{const t=await Cv({urlOverride:`${Ys}/api/kos/time/timezone`});if((t==null?void 0:t.status)!==200)throw Error("Failed to set timezone");return t.data.timeZone},Dv=Object.freeze(Object.defineProperty({__proto__:null,getTimezone:Nu,setDate:Lu,setTime:ku,setTimezone:Fu},Symbol.toStringTag,{value:"Module"}));var xv=Object.defineProperty,Av=Object.getOwnPropertyDescriptor,fo=(t,e,s,r)=>{for(var o=r>1?void 0:r?Av(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&&xv(e,s,o),o};const as="kos-time-model",Rv="/kos/time/time",Pv="/kos/time/day",kv="/kos/time/timezone";let jt=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 ku(t)}async updateSystemDate(t){await Lu(t)}async updateSystemTimezone(t){await Fu(t)}handleTimeChange(){K(Ss.TIME_CHANGE,{})}handleDayChange(){K(Ss.DAY_CHANGE,{})}async handleTimeZoneChange(){await this.retrieveTimezone(),K(Ss.TIMEZONE_CHANGE,{})}async init(){this.logger.debug(`initializing kos-time ${this.id}`)}async retrieveTimezone(){const t=await Nu();this.setTimezone(t)}setTimezone(t){this.timezone=t}async load(){this.logger.debug(`loading kos-time ${this.id}`),this.retrieveTimezone()}};fo([B({topic:Rv,websocket:!0})],jt.prototype,"handleTimeChange",1);fo([B({topic:Pv,websocket:!0})],jt.prototype,"handleDayChange",1);fo([B({topic:kv,websocket:!0})],jt.prototype,"handleTimeZoneChange",1);jt=fo([R(as)],jt);const $r={registration:{[as]:{class:jt,singleton:!0}},type:as,predicate:Ie(as),factory:le.Singleton.create(as)};var Lv=Object.defineProperty,Fv=Object.getOwnPropertyDescriptor,Uu=(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 ju="log-block-container-model";let Cr=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_models");this.id=t,this.logger=s.logger,this._models=new ke({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}`)}};Uu([Pe],Cr.prototype,"_models",2);Cr=Uu([R(ju)],Cr);const Nv=m.createLogger({name:"log-stream-container-service",group:"Services"}),Bu=()=>{var r;const t=be(),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},ss=Bu(),Uv="/api/kos/logs/node/{nodeId}/streams",Hu=async()=>(Nv.debug("sending GET for log-stream-container"),await Le.get(Uv,{path:{nodeId:"primary"}},{destinationAddress:ss})),Ku=async(t,e="primary")=>{await Le.post("/api/kos/logs/node/{nodeId}/{stream}/subscribe",{path:{nodeId:e,stream:t}},void 0,{destinationAddress:ss})},qu=async t=>{await Le.post("/api/kos/logs/node/{nodeId}/{stream}/unsubscribe",{path:{nodeId:"primary",stream:t}},void 0,{destinationAddress:ss})},jv=async()=>{await Le.post("/api/kos/logs/overrides",{},{level:"WARN",name:"com.example",nodeType:"java",type:"package"},{destinationAddress:ss})},zu=async t=>await Le.get("/api/kos/logs/node/{nodeId}/{stream}/blocks",{path:{nodeId:"primary",stream:t}},{destinationAddress:ss}),Vu=async(t,e)=>await Le.get("/api/kos/logs/node/{nodeId}/{stream}/blocks/{blockId}",{path:{nodeId:"primary",stream:t,blockId:e}},{destinationAddress:ss}),Bv=Object.freeze(Object.defineProperty({__proto__:null,createOverride:jv,getKosConnectionId:Bu,getLogStreamBlock:Vu,getLogStreamBlocks:zu,getLogStreams:Hu,subscribeToLogStream:Ku,unsubscribeFromLogStream:qu},Symbol.toStringTag,{value:"Module"}));var Hv=Object.getOwnPropertyDescriptor,Kv=(t,e,s,r)=>{for(var o=r>1?void 0:r?Hv(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const Gu="log-block-model";let Wo=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 Vu(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}`)}};Wo=Kv([R(Gu)],Wo);const ks=new ve({class:Wo,type:Gu}),po=new ve({class:Cr,type:ju});po.addRelatedModel(ks);var qv=Object.defineProperty,zv=Object.getOwnPropertyDescriptor,Yu=(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 Wu="log-stream-model";let Dr=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=po.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=ks.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=ks.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 Ku(this.name)}async unsubscribe(){await qu(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 zu(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=Gl(()=>{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()}}};Yu([Pe],Dr.prototype,"_blocks",2);Dr=Yu([R(Wu)],Dr);const Os=new ve({class:Dr,type:Wu});var Vv=Object.defineProperty,Gv=Object.getOwnPropertyDescriptor,Mt=(t,e,s,r)=>{for(var o=r>1?void 0:r?Gv(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&&Vv(e,s,o),o};const Qu="log-stream-container-model",Yv="/kos/logs/subscription/addBlock/*",Wv="/kos/logs/subscription/updateBlock/*",Qv="/kos/logs/subscription/removeBlock/*",Zv="/kos/logs/subscription/lines/*",Zu="/kos/logs/streams/add/*";let Ke=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 ke({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: ${Zu}`);const e=t.stream,s=Os.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=Os.instance(t).options({name:t,nodeId:"primary"}).build();this.addModel(e),await e.subscribe()}async load(){this.logger.debug(`loading log-stream-container container ${this.id}`);const[t,e]=await Hu();if(t){this.logger.error(`Error loading log-streams: ${t}`);return}e&&e.forEach(s=>{const r=Os.instance(s).options({name:s,nodeId:"primary"}).build();this.addModel(r)})}};Mt([Pe],Ke.prototype,"_models",2);Mt([B({topic:[Zu],websocket:!0})],Ke.prototype,"handleStreamAdded",1);Mt([B({topic:[Yv],websocket:!0})],Ke.prototype,"handleAddBlock",1);Mt([B({topic:[Qv],websocket:!0})],Ke.prototype,"handleRemoveBlock",1);Mt([B({topic:[Wv],websocket:!0})],Ke.prototype,"handleUpdateBlock",1);Mt([B({topic:[Zv],websocket:!0})],Ke.prototype,"handleLogLine",1);Ke=Mt([R(Qu)],Ke);const Ws=new $e({class:Ke,type:Qu});Ws.addRelatedModel(Os);Ws.addRelatedModel(po);Ws.addRelatedModel(ks);const Xv=t=>t.rank!==void 0,Jv=t=>t.visibleRole!==void 0,ew=t=>t.color!==void 0,tw=t=>{const e=t.info;return Xv(e)?e.rank:0},sw=t=>{const e=t.info;return ew(e)?e.color:"orange"},rw=t=>{const e=t.info;return Jv(e)?e.visibleRole:"TECHNICIAN"},{URL:go}=ue(),{getAll:ow,postModel:Xu}=ie.build({basePath:`${go}/api/kos/troubles`}),Ju=async t=>await ow({urlOverride:`${go}${t}`}),ed=async(t,e="/api/kos/troubles",s)=>{try{const r=await Xu({model:{},urlOverride:`${go}${e}/resolve/${t}`,tracker:s});return r!=null&&r.data&&pt.initiateFuture(r.data),r.data}catch{const o={id:s||"",endState:Je.Fail,tracker:s,reason:"Failed to resolve trouble"};return pt.initiateFuture(o),o}},nw=async(t,e="/api/kos/troubles",s)=>{try{const r=await Xu({model:t,urlOverride:`${go}${e}/resolve/`,tracker:s});return r!=null&&r.data&&pt.initiateFuture(r.data),r.data}catch{const o={id:s||"",endState:Je.Fail,tracker:s,reason:"Failed to resolve troubles"};return pt.initiateFuture(o),o}},iw=Object.freeze(Object.defineProperty({__proto__:null,bulkResolveTroubles:nw,getTroubles:Ju,resolveTrouble:ed},Symbol.toStringTag,{value:"Module"})),xr="troubleDataMapper",ir=new Map;zs(xr,{register:(t,e)=>{var s;ir.has(t)||ir.set(t,[]),(s=ir.get(t))==null||s.push(e)},execute:async(t,e)=>{const s=ir.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 Qs="troubleMapper",ar=new Map;zs(Qs,{register:(t,e)=>{var s;ar.has(t)||ar.set(t,[]),(s=ar.get(t))==null||s.push(e)},execute:async(t,e)=>{const s=ar.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))}});$[Qs].register("nozzle",async t=>[t.data.nozzlePath]);$[Qs].register("path",async t=>[t.data.path]);const aw=async t=>{const e=new Set,s=t.ifaces,r=s==null?void 0:s.map(n=>$[Qs].execute(n,t));return(await Promise.allSettled(r)).forEach(n=>{n.status==="fulfilled"&&n.value.forEach(i=>e.add(i))}),Array.from(e)},td=async t=>{const e=t.ifaces,s=e==null?void 0:e.map(i=>$[xr].execute(i,t)),r=$[xr].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 cw{constructor(){l(this,"type","ResolvableTrouble");l(this,"title","Resolvable Trouble");l(this,"subtitle","Trouble")}}class lw{constructor(){l(this,"type","BlockPumpTrouble");l(this,"title","Block Pump Trouble");l(this,"subtitle","Trouble")}}class It{static getHandler(e){switch(e){case"ResolvableTrouble":return new cw;case"BlockPumpTrouble":return new lw;default:return}}}var uw=Object.defineProperty,dw=Object.getOwnPropertyDescriptor,sd=(t,e,s,r)=>{for(var o=r>1?void 0:r?dw(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&&uw(e,s,o),o};const cs="trouble-model";function cr(t){return typeof t.shouldDefer=="boolean"}let Ar=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,...g},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,g),this.futureHandler=new so(this)}getTitleWithContext(t){var s,r;const e=t?(r=(s=It.getHandler(this.type))==null?void 0:s.context)==null?void 0:r[t]:It.getHandler(this.type);return(e==null?void 0:e.title)||"Trouble"}getSubtitleWithContext(t){var s,r;const e=t?(r=(s=It.getHandler(this.type))==null?void 0:s.context)==null?void 0:r[t]:It.getHandler(this.type);return(e==null?void 0:e.subtitle)||"Trouble"}get rawId(){return this._troubleId}get title(){var t;return((t=It.getHandler(this.type))==null?void 0:t.title)||"Trouble"}get subtitle(){var t;return((t=It.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 td(this)}get deferredCompanion(){const t=jo(this.id,e=>cr(e));if(t&&cr(t.modelData))return t.modelData}get deferred(){return this.deferredCompanion?this.deferredCompanion.deferred:!1}get shouldDefer(){const t=jo(this.id,e=>cr(e));return t&&cr(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 ed(this._troubleId,this.servicePath,t)}};sd([Oi()],Ar.prototype,"resolve",1);Ar=sd([R(cs)],Ar);const Ls={registration:{[cs]:{class:Ar,singleton:!1}},type:cs,predicate:Ie(cs),factory:le.Factory.create(cs)};var rd=Object.defineProperty,hw=Object.getOwnPropertyDescriptor,fw=(t,e,s)=>e in t?rd(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,li=(t,e,s,r)=>{for(var o=r>1?void 0:r?hw(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&&rd(e,s,o),o},pw=(t,e,s)=>(fw(t,e+"",s),s);function fa(t){return $.propertyMapper.hasMapper(_e.TroubleRank)?$.propertyMapper.executeMapper(_e.TroubleRank,t):tw(t)}function pa(t){return($.propertyMapper.hasMapper(_e.TroubleColor)?$.propertyMapper.executeMapper(_e.TroubleColor,t):sw(t)).toLowerCase()}function ga(t){return($.propertyMapper.hasMapper(_e.TroubleRole)?$.propertyMapper.executeMapper(_e.TroubleRole,t):rw(t)).toLowerCase()}const gw="trouble-container-model";class ye{}l(ye,"INDEX_TROUBLES_BY_IFACE","byIface"),l(ye,"INDEX_TROUBLES_BY_TYPE","byType"),l(ye,"INDEX_TROUBLES_BY_GROUP","byGroup"),l(ye,"INDEX_TROUBLES_BY_DEFERRED","byDeferred"),l(ye,"SORT_KEY_RANK","rank"),l(ye,"TROUBLES_DEFERRED","true");let Bt=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 Ju(this.servicePath);try{t==null||t.data.forEach(e=>{const s={...e,servicePath:this.servicePath,rank:fa(e),color:pa(e),role:ga(e),id:String(e.id)},r=Ls.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&&De(s)}handleTroubleAdded(t){const e={...t,servicePath:this.servicePath,rank:fa(t),color:pa(t),role:ga(t),id:String(t.id)};if(e.role==="NONE")return;const s=Ls.factory(`trouble-${t.id}`)(e);this.troubles.addModel(s)}};pw(Bt,"Registration");li([B({topic:"/kos/trouble/remove",websocket:!0,lifecycle:D.INIT})],Bt.prototype,"handleTroubleRemoved",1);li([B({topic:"/kos/trouble/add",websocket:!0})],Bt.prototype,"handleTroubleAdded",1);Bt=li([R({modelTypeId:gw,singleton:!0}),Sc(),wc({containerProperty:"troubles",containerOptions:{indexMap:{[ye.INDEX_TROUBLES_BY_IFACE]:aw,[ye.INDEX_TROUBLES_BY_TYPE]:"type",[ye.INDEX_TROUBLES_BY_GROUP]:"group",[ye.INDEX_TROUBLES_BY_DEFERRED]:"deferred"},sortKey:ye.SORT_KEY_RANK}})],Bt);const Ht=Bt.Registration,{URL:od}=ue(),{getAll:mw}=ie.build({basePath:`${od}/api/kos/ota`}),ma=m.createLogger({name:"ota-service",group:"Services"}),yw=async()=>{ma.debug("sending GET request to /api/kos/ota/artifacts");const t=await mw({urlOverride:`${od}/api/kos/ota/artifacts`});return ma.debug("getArtifacts - response:",t),t==null?void 0:t.data};var bw=Object.defineProperty,vw=Object.getOwnPropertyDescriptor,mo=(t,e,s,r)=>{for(var o=r>1?void 0:r?vw(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&&bw(e,s,o),o};const nd="ota-model",ww=t=>{let e=null;for(const s in t){const r=t[s],o=r.lastUpdateTime;(!e||e.lastUpdateTime<o)&&(e=r)}return e},Ro=t=>{const e=t.artifactInfo,s=ww(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 Kt=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"data",new Nn);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 yw();t&&t.forEach(e=>{const s=Ro(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=Ro(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=Ro(e);s&&this.data.updateModel(s)})}catch(e){this.logger.error(`handleChangedArtifacts ${this.id} - error:`,e)}}};mo([Wt({modelType:Ht.type})],Kt.prototype,"troubleContainer",2);mo([B({topic:"/kos/ota/artifacts/all",websocket:!0})],Kt.prototype,"handleAllArtifacts",1);mo([B({topic:"/kos/ota/artifacts/changed",websocket:!0})],Kt.prototype,"handleChangedArtifacts",1);Kt=mo([R(nd)],Kt);const Rr=new $e({class:Kt,type:nd});function Ew(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 Po=m.createLogger({name:"software-info-service",group:"Services"}),ui=async t=>{Po.debug("sending GET for software-info");const[e,s]=await gu.get("/api/kos/manifest/info",void 0,{signal:t});if(!s)throw t!=null&&t.aborted?(Po.debug("Request was aborted"),new z("Request was aborted")):(Po.error("Failed to fetch software-info",e),new z("Failed to fetch software-info"));return s},Mw=Ew(ui),Tw=Object.freeze(Object.defineProperty({__proto__:null,getSoftwareInfos:ui,getSoftwareInfosWithCancel:Mw},Symbol.toStringTag,{value:"Module"}));var _w=Object.getOwnPropertyDescriptor,Sw=(t,e,s,r)=>{for(var o=r>1?void 0:r?_w(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const ls="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 ui(),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 z&&this.logger.error("Failed to fetch software-info",t)}}};Qo=Sw([R(ls)],Qo);const Pr={registration:{[ls]:{class:Qo,singleton:!1}},type:ls,predicate:Ie(ls),factory:le.Factory.create(ls)},{URL:id}=ue(),{getOne:Ow}=ie.build({basePath:`${id}/api/kos/state`}),Iw=m.createLogger({name:"state-bean-service",group:"Services"}),ad=async({path:t})=>(Iw.debug("sending GET for state-bean"),await Ow({urlOverride:`${id}/api/kos/state/${t}`})),$w=Object.freeze(Object.defineProperty({__proto__:null,getStateBeanData:ad},Symbol.toStringTag,{value:"Module"}));var Cw=Object.defineProperty,Dw=Object.getOwnPropertyDescriptor,cd=(t,e,s,r)=>{for(var o=r>1?void 0:r?Dw(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&&Cw(e,s,o),o};const us="state-bean-model",xw=mt("path");let kr=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=jn.map(new Map),zo(e,this)}updateModel(t){zo(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"&&ro(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 ad({path:this.path});t!=null&&t.data&&this.updateProps(t.data)}};cd([B({topic:`/kos/state/${xw}`,websocket:!0})],kr.prototype,"handleConfigBeanUpdated",1);kr=cd([R(us)],kr);const Fs={registration:{[us]:{class:kr,singleton:!1}},type:us,predicate:Ie(us),factory:le.Factory.create(us)};var Aw=Object.defineProperty,Rw=Object.getOwnPropertyDescriptor,ld=(t,e,s,r)=>{for(var o=r>1?void 0:r?Rw(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&&Aw(e,s,o),o};const ds="state-prop-model",ya=mt("path");let Lr=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())??""}};ld([Wt({modelType:Fs.type,id:`state-bean-${ya}`,options:{path:ya}})],Lr.prototype,"stateBean",2);Lr=ld([R(ds)],Lr);const di={registration:{[ds]:{class:Lr,singleton:!1}},type:ds,predicate:Ie(ds),factory:le.Factory.create(ds)},{URL:Pw}=ue(),{getAll:kw}=ie.build({basePath:`${Pw}/api/state-prop`}),Lw=m.createLogger({name:"state-prop-service",group:"Services"}),Fw=async()=>(Lw.debug("sending GET for state-prop"),await kw({})),Nw=Object.freeze(Object.defineProperty({__proto__:null,getStateProps:Fw},Symbol.toStringTag,{value:"Module"})),{URL:hi}=ue(),{getOne:ud}=ie.build({basePath:`${hi}/api/translation`}),Is=m.createLogger({name:"translation-service",group:"Services"}),Uw=()=>{const t=window.location.origin,e=be();return(e==null?void 0:e.host)||t},dd=async(t,e)=>{Is.debug(`Loading translations from: ${t}`);const s=e??Uw();try{const r=await fetch(`${s}${t}`);return r.status!==200?(Is.warn(`Failed to fetch translations at ${t}: ${r.status}`),{}):await r.json()}catch(r){throw Is.error("Error fetching translations",r),r}},jw=async()=>{Is.debug("Getting system localization descriptor");const t=await ud({urlOverride:`${hi}/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},hd=t=>async()=>{Is.debug(`Getting KOS localization descriptor for context: ${t}`);const e=await ud({urlOverride:`${hi}/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]},fd="langResolver";var Bw=Object.getOwnPropertyDescriptor,Hw=(t,e,s,r)=>{for(var o=r>1?void 0:r?Bw(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const hs="translation-model";function Kw(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 pd(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=pd(t[r],o);return{...s,...n}}else return{...s,[o]:t[r]}},{})}function gd(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]=gd(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},lr=(t,e,s)=>{const r=/{{(.*?)}}/g,n=Zo(t,e).replace(r,(a,c)=>{const u=c.trim();if(Object.prototype.hasOwnProperty.call(s||{},u))return s==null?void 0:s[u];if(u.includes(".")){const d=u.split(".");let h=s;for(const f of d)if(h&&typeof h=="object"&&Object.prototype.hasOwnProperty.call(h,f))h=h[f];else return a;return h}return a});return Zo(n,e)},ba=(t,e)=>{if(e.includes(":")){const[s,r]=e.split(":");return{namespace:s,key:r}}else return{namespace:t,key:e}};let Xo=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(fd),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=W.getContext(this.id);return this.bundleResolver(this.namespace,r,o)}try{const o=this.resolver(this.namespace,r);return dd(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=gd(o,n.value))):this.logger.error(`failed to load translation ${this.id} for ${t[i]}`),o),{});this.data=pd(r)})}async init(){this.logger.debug(`initializing translation ${this.id}`)}exists(t){const{namespace:e,key:s}=ba(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}=Kw(e),{namespace:n,key:i}=ba(this.namespace,t),a=`${i}_${r}`;if(n!==this.namespace){const c=this.context.getModel(n);return c?c.resolveKey(i,e):s??i}if(r&&this.data[a]){const c=this.data[a];return Array.isArray(c)?c.map(u=>lr(u,this.data,o)):lr(this.data[a],this.data,o)}if(this.data[i]){const c=this.data[i];return Array.isArray(c)?c.map(u=>lr(u,this.data,o)):lr(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()})}};Xo=Hw([Jr(),R(hs)],Xo);const Fr={registration:{[hs]:{class:Xo,singleton:!1}},type:hs,predicate:Ie(hs),factory:le.Factory.create(hs)};var qw=Object.defineProperty,zw=Object.getOwnPropertyDescriptor,md=(t,e,s,r)=>{for(var o=r>1?void 0:r?zw(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&&qw(e,s,o),o};const fs="translation-container-model",Vw=(t,e="/")=>t.join(e).replace(new RegExp(e+"{1,}","g"),e);function Gw(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 Vw([r,o])}let Nr=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||Gw.bind(this),s.kosContext.set(fd,this.resolver),this.logger=s.logger,this._models=new ke({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 pe(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=Fr.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=Fr.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)}};md([Pe],Nr.prototype,"_models",2);Nr=md([R(fs)],Nr);const qe={registration:{[fs]:{class:Nr,singleton:!0}},type:fs,predicate:Ie(fs),factory:le.Singleton.create(fs)},Yw={set(t,e){const s=W.getContext(qe.type);s&&s.set(t,e)},get(t){const e=W.getContext(qe.type);return e==null?void 0:e.get(t)}},yd={async init(t){const e=qe.factory(t);return await pe(e),{translations:e}}};function Ww(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 bd="kos-ws-event",fi=Qt(bd);var Qw=Object.defineProperty,Zw=Object.getOwnPropertyDescriptor,pi=(t,e,s,r)=>{for(var o=r>1?void 0:r?Zw(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&&Qw(e,s,o),o};const Xw=({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:Xw({headers:o,body:r}),direction:s?"send":"receive",mocked:!!o.mocked};this.events.set(a,c),m.debug(`logged ${this.events.size} events`)}}};pi([B({topic:[Hs.SEND]})],exports.WsEventModel.prototype,"handleSendEvent",1);pi([B({topic:[Hs.RECEIVED]})],exports.WsEventModel.prototype,"handleReceiveEvent",1);exports.WsEventModel=pi([R(fi.type)],exports.WsEventModel);const va=be(),Jw=va.debug==="true"||va.debug===!0,eE="/api/system/canvas",vd=async(t,e)=>{const s=e||eE,r=`${exports.BASE_URL}${s}`;await exports.kosFetch(r,{method:"POST",headers:{hide:Jw?"false":"true"},body:t})},tE=Object.freeze(Object.defineProperty({__proto__:null,sendCanvasData:vd},Symbol.toStringTag,{value:"Module"}));function wa(t,e,s){{const r=t.filter((o,n)=>n%4!==3);return btoa(String.fromCharCode(...r))}}var sE=Object.defineProperty,rE=Object.getOwnPropertyDescriptor,wd=(t,e,s,r)=>{for(var o=r>1?void 0:r?rE(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&&sE(e,s,o),o};const Ed="canvas-renderer-model";function ko(t){return typeof t.onDone=="function"}let Ur=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){vd(t,e)}checkStreaming(){if(this.isOneShotDone()||!this.isStreaming){requestAnimationFrame(()=>{const t=this.isOneShotDone();this.stopStreaming(!t)});return}}handleFrame(t){var s;const e=wa(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=wa(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 ko(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=ko(this._renderer);ko(this._renderer)&&this._renderer.onDone(()=>{var c,u,d;this.logger.debug(`Renderer completed for ${this.id}`),K("/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"})})}};wd([Wt({modelType:Zn.type})],Ur.prototype,"router",2);Ur=wd([R(Ed)],Ur);const gi=new ve({class:Ur,type:Ed});class Md{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 oE{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 nE extends oE{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=`
|
|
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 q(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}q.prototype.next=function(){return this.current=this.nextToken,this.nextToken=this.tokens.next()};q.prototype.tokenMatches=function(t,e){return typeof e>"u"?!0:Array.isArray(e)?Dt(e,t.value):typeof e=="function"?e(t):t.value===e};q.prototype.save=function(){this.savedCurrent=this.current,this.savedNextToken=this.nextToken,this.tokens.save()};q.prototype.restore=function(){this.tokens.restore(),this.current=this.savedCurrent,this.nextToken=this.savedNextToken};q.prototype.accept=function(t,e){return this.nextToken.type===t&&this.tokenMatches(this.nextToken,e)?(this.next(),!0):!1};q.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))}};q.prototype.parseAtom=function(t){var e=this.tokens.unaryOps;function s(o){return o.value in e}if(this.accept(ni)||this.accept(j,s))t.push(new P(Be,this.current.value));else if(this.accept(lo))t.push(new P(me,this.current.value));else if(this.accept($u))t.push(new P(me,this.current.value));else if(this.accept(He,"("))this.parseExpression(t),this.expect(He,")");else if(this.accept(Nt,"["))if(this.accept(Nt,"]"))t.push(new P(Ft,0));else{var r=this.parseArrayList(t);t.push(new P(Ft,r))}else throw new Error("unexpected "+this.nextToken)};q.prototype.parseExpression=function(t){var e=[];this.parseUntilEndStatement(t,e)||(this.parseVariableAssignmentExpression(e),!this.parseUntilEndStatement(t,e)&&this.pushExpression(t,e))};q.prototype.pushExpression=function(t,e){for(var s=0,r=e.length;s<r;s++)t.push(e[s])};q.prototype.parseUntilEndStatement=function(t,e){return this.accept(ii)?(this.nextToken&&this.nextToken.type!==Ps&&!(this.nextToken.type===He&&this.nextToken.value===")")&&e.push(new P(ao)),this.nextToken.type!==Ps&&this.parseExpression(e),t.push(new P(ce,e)),!0):!1};q.prototype.parseArrayList=function(t){for(var e=0;!this.accept(Nt,"]");)for(this.parseExpression(t),++e;this.accept(uo);)this.parseExpression(t),++e;return e};q.prototype.parseVariableAssignmentExpression=function(t){for(this.parseConditionalExpression(t);this.accept(j,"=");){var e=t.pop(),s=[],r=t.length-1;if(e.type===Lt){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===Be&&(t[i]=new P(gt,t[i].value))}this.parseVariableAssignmentExpression(s),t.push(new P(ce,s)),t.push(new P(io,e.value));continue}if(e.type!==Be&&e.type!==wt)throw new Error("expected variable for assignment");this.parseVariableAssignmentExpression(s),t.push(new P(gt,e.value)),t.push(new P(ce,s)),t.push(Ge("="))}};q.prototype.parseConditionalExpression=function(t){for(this.parseOrExpression(t);this.accept(j,"?");){var e=[],s=[];this.parseConditionalExpression(e),this.expect(j,":"),this.parseConditionalExpression(s),t.push(new P(ce,e)),t.push(new P(ce,s)),t.push(Ou("?"))}};q.prototype.parseOrExpression=function(t){for(this.parseAndExpression(t);this.accept(j,"or");){var e=[];this.parseAndExpression(e),t.push(new P(ce,e)),t.push(Ge("or"))}};q.prototype.parseAndExpression=function(t){for(this.parseComparison(t);this.accept(j,"and");){var e=[];this.parseComparison(e),t.push(new P(ce,e)),t.push(Ge("and"))}};var Eb=["==","!=","<","<=",">=",">","in"];q.prototype.parseComparison=function(t){for(this.parseAddSub(t);this.accept(j,Eb);){var e=this.current;this.parseAddSub(t),t.push(Ge(e.value))}};var Mb=["+","-","||"];q.prototype.parseAddSub=function(t){for(this.parseTerm(t);this.accept(j,Mb);){var e=this.current;this.parseTerm(t),t.push(Ge(e.value))}};var Tb=["*","/","%"];q.prototype.parseTerm=function(t){for(this.parseFactor(t);this.accept(j,Tb);){var e=this.current;this.parseFactor(t),t.push(Ge(e.value))}};q.prototype.parseFactor=function(t){var e=this.tokens.unaryOps;function s(o){return o.value in e}if(this.save(),this.accept(j,s)){if(this.current.value!=="-"&&this.current.value!=="+"){if(this.nextToken.type===He&&this.nextToken.value==="("){this.restore(),this.parseExponential(t);return}else if(this.nextToken.type===ii||this.nextToken.type===uo||this.nextToken.type===Ps||this.nextToken.type===He&&this.nextToken.value===")"){this.restore(),this.parseAtom(t);return}}var r=this.current;this.parseFactor(t),t.push(co(r.value))}else this.parseExponential(t)};q.prototype.parseExponential=function(t){for(this.parsePostfixExpression(t);this.accept(j,"^");)this.parseFactor(t),t.push(Ge("^"))};q.prototype.parsePostfixExpression=function(t){for(this.parseFunctionCall(t);this.accept(j,"!");)t.push(co("!"))};q.prototype.parseFunctionCall=function(t){var e=this.tokens.unaryOps;function s(n){return n.value in e}if(this.accept(j,s)){var r=this.current;this.parseAtom(t),t.push(co(r.value))}else for(this.parseMemberExpression(t);this.accept(He,"(");)if(this.accept(He,")"))t.push(new P(Lt,0));else{var o=this.parseArgumentList(t);t.push(new P(Lt,o))}};q.prototype.parseArgumentList=function(t){for(var e=0;!this.accept(He,")");)for(this.parseExpression(t),++e;this.accept(uo);)this.parseExpression(t),++e;return e};q.prototype.parseMemberExpression=function(t){for(this.parseAtom(t);this.accept(j,".")||this.accept(Nt,"[");){var e=this.current;if(e.value==="."){if(!this.allowMemberAccess)throw new Error('unexpected ".", member access is not permitted');this.expect(ni),t.push(new P(wt,this.current.value))}else if(e.value==="["){if(!this.tokens.isOperatorEnabled("["))throw new Error('unexpected "[]", arrays are disabled');this.parseExpression(t),this.expect(Nt,"]"),t.push(Ge("["))}else throw new Error("unexpected symbol: "+e.value)}};function _b(t,e){return Number(t)+Number(e)}function Sb(t,e){return t-e}function Ob(t,e){return t*e}function Ib(t,e){return t/e}function $b(t,e){return t%e}function Cb(t,e){return Array.isArray(t)&&Array.isArray(e)?t.concat(e):""+t+e}function Db(t,e){return t===e}function xb(t,e){return t!==e}function Ab(t,e){return t>e}function Rb(t,e){return t<e}function Pb(t,e){return t>=e}function kb(t,e){return t<=e}function Lb(t,e){return!!(t&&e)}function Fb(t,e){return!!(t||e)}function Nb(t,e){return Dt(e,t)}function Ub(t){return(Math.exp(t)-Math.exp(-t))/2}function jb(t){return(Math.exp(t)+Math.exp(-t))/2}function Bb(t){return t===1/0?1:t===-1/0?-1:(Math.exp(t)-Math.exp(-t))/(Math.exp(t)+Math.exp(-t))}function Hb(t){return t===-1/0?t:Math.log(t+Math.sqrt(t*t+1))}function Kb(t){return Math.log(t+Math.sqrt(t*t-1))}function qb(t){return Math.log((1+t)/(1-t))/2}function aa(t){return Math.log(t)*Math.LOG10E}function zb(t){return-t}function Vb(t){return!t}function Gb(t){return t<0?Math.ceil(t):Math.floor(t)}function Yb(t){return Math.random()*(t||1)}function ca(t){return ai(t+1)}function Wb(t){return isFinite(t)&&t===Math.round(t)}var Qb=4.7421875,Ao=[.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 ai(t){var e,s;if(Wb(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)*ai(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=Ao[0];for(var u=1;u<Ao.length;++u)s+=Ao[u]/(t+u);return e=t+Qb+.5,Math.sqrt(2*Math.PI)*Math.pow(e,t+.5)*Math.exp(-e)*s}function Zb(t){return Array.isArray(t)?t.length:String(t).length}function la(){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 ua(t,e,s){return t?e:s}function Xb(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 Jb(t,e,s){return s&&(s[t]=e),e}function ev(t,e){return t[e|0]}function tv(t){return arguments.length===1&&Array.isArray(t)?Math.max.apply(Math,t):Math.max.apply(Math,arguments)}function sv(t){return arguments.length===1&&Array.isArray(t)?Math.min.apply(Math,t):Math.min.apply(Math,arguments)}function rv(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 ov(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 nv(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 iv(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 av(t,e){if(!Array.isArray(e))throw new Error("Second argument to join is not an array");return e.join(t)}function cv(t){return(t>0)-(t<0)||+t}var da=1/3;function lv(t){return t<0?-Math.pow(-t,da):Math.pow(t,da)}function uv(t){return Math.exp(t)-1}function dv(t){return Math.log(1+t)}function hv(t){return Math.log(t)/Math.LN2}function Et(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||Ub,cosh:Math.cosh||jb,tanh:Math.tanh||Bb,asinh:Math.asinh||Hb,acosh:Math.acosh||Kb,atanh:Math.atanh||qb,sqrt:Math.sqrt,cbrt:Math.cbrt||lv,log:Math.log,log2:Math.log2||hv,ln:Math.log,lg:Math.log10||aa,log10:Math.log10||aa,expm1:Math.expm1||uv,log1p:Math.log1p||dv,abs:Math.abs,ceil:Math.ceil,floor:Math.floor,round:Math.round,trunc:Math.trunc||Gb,"-":zb,"+":Number,exp:Math.exp,not:Vb,length:Zb,"!":ca,sign:Math.sign||cv},this.binaryOps={"+":_b,"-":Sb,"*":Ob,"/":Ib,"%":$b,"^":Math.pow,"||":Cb,"==":Db,"!=":xb,">":Ab,"<":Rb,">=":Pb,"<=":kb,and:Lb,or:Fb,in:Nb,"=":Jb,"[":ev},this.ternaryOps={"?":ua},this.functions={random:Yb,fac:ca,min:sv,max:tv,hypot:Math.hypot||la,pyt:Math.hypot||la,pow:Math.pow,atan2:Math.atan2,if:ua,gamma:ai,roundTo:Xb,map:rv,fold:ov,filter:nv,indexOf:iv,join:av},this.consts={E:Math.E,PI:Math.PI,true:!0,false:!1}}Et.prototype.parse=function(t){var e=[],s=new q(this,new G(this,t),{allowMemberAccess:this.options.allowMemberAccess});return s.parseExpression(e),s.expect(Ps,"EOF"),new Se(e,this)};Et.prototype.evaluate=function(t,e){return this.parse(t).evaluate(e)};var Du=new Et;Et.parse=function(t){return Du.parse(t)};Et.evaluate=function(t,e){return Du.parse(t).evaluate(e)};var ha={"+":"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 fv(t){return ha.hasOwnProperty(t)?ha[t]:t}Et.prototype.isOperatorEnabled=function(t){var e=fv(t),s=this.options.operators||{};return!(e in s)||!!s[e]};var pv=Object.defineProperty,gv=Object.getOwnPropertyDescriptor,mv=(t,e,s)=>e in t?pv(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,yv=(t,e,s,r)=>{for(var o=r>1?void 0:r?gv(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o},bv=(t,e,s)=>(mv(t,e+"",s),s);const vv="kos-expression-evaluator-model";class wv{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 Ir=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=xe(),this._results=xe(),this.parser=new Et,this.parser.functions.exists=r=>r!=null,this.parser.functions.isEmpty=r=>r==null?!0:typeof r=="string"||Array.isArray(r)?r.length===0:typeof r=="object"?Object.keys(r).length===0:!1}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 wv(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=bt();return this.addExpression(e,t),e}};bv(Ir,"Registration");Ir=yv([R({modelTypeId:vv,singleton:!1})],Ir);const xu=Ir.Registration,Ev=m.createLogger({name:"kos-log-manager-service",group:"Services"}),Mv="/api/kos/logs/overrides",Au=async()=>(Ev.debug("sending GET for kos-log-manager"),await Le.get(Mv)),Tv=Object.freeze(Object.defineProperty({__proto__:null,getLogOverrides:Au},Symbol.toStringTag,{value:"Module"}));var _v=Object.defineProperty,Sv=Object.getOwnPropertyDescriptor,ho=(t,e,s,r)=>{for(var o=r>1?void 0:r?Sv(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&&_v(e,s,o),o};const Ru="kos-log-manager-model",Ov="/kos/logs/override/add/*",Iv="/kos/logs/override/remove/*",$v=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 Ut=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_overrides");this.id=t,this.logger=s.logger,this._overrides=new Nn}updateModel(t){}resolveLoggers(){const t=m.getLoggers(),s=Object.entries(t).map(([r,o])=>({name:r,level:$v(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 Au();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)})}};ho([Ec("/api/kos/ui/loggers")],Ut.prototype,"getAllLoggers",1);ho([B({topic:Ov,websocket:!0,wildcardName:"nodeType"})],Ut.prototype,"handleOverrideAdded",1);ho([B({topic:Iv,websocket:!0,wildcardName:"nodeType"})],Ut.prototype,"handleOverrideRemoved",1);Ut=ho([R(Ru)],Ut);const Pu=new $e({class:Ut,type:Ru}),{URL:Ys}=ue(),{postModel:ci,getOne:Cv}=ie.build({basePath:`${Ys}/api/kos-time`});m.createLogger({name:"kos-time-service",group:"Services"});const ku=async t=>{const e=await ci({model:t,urlOverride:`${Ys}/api/kos/time/time`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set time");return e.data},Lu=async t=>{const e=await ci({model:t,urlOverride:`${Ys}/api/kos/time/date`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set time");return e.data},Fu=async t=>{const e=await ci({model:{},urlOverride:`${Ys}/api/kos/time/timezone?tz=${t}`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set timezone");return e.data},Nu=async()=>{const t=await Cv({urlOverride:`${Ys}/api/kos/time/timezone`});if((t==null?void 0:t.status)!==200)throw Error("Failed to set timezone");return t.data.timeZone},Dv=Object.freeze(Object.defineProperty({__proto__:null,getTimezone:Nu,setDate:Lu,setTime:ku,setTimezone:Fu},Symbol.toStringTag,{value:"Module"}));var xv=Object.defineProperty,Av=Object.getOwnPropertyDescriptor,fo=(t,e,s,r)=>{for(var o=r>1?void 0:r?Av(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&&xv(e,s,o),o};const as="kos-time-model",Rv="/kos/time/time",Pv="/kos/time/day",kv="/kos/time/timezone";let jt=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 ku(t)}async updateSystemDate(t){await Lu(t)}async updateSystemTimezone(t){await Fu(t)}handleTimeChange(){K(Ss.TIME_CHANGE,{})}handleDayChange(){K(Ss.DAY_CHANGE,{})}async handleTimeZoneChange(){await this.retrieveTimezone(),K(Ss.TIMEZONE_CHANGE,{})}async init(){this.logger.debug(`initializing kos-time ${this.id}`)}async retrieveTimezone(){const t=await Nu();this.setTimezone(t)}setTimezone(t){this.timezone=t}async load(){this.logger.debug(`loading kos-time ${this.id}`),this.retrieveTimezone()}};fo([B({topic:Rv,websocket:!0})],jt.prototype,"handleTimeChange",1);fo([B({topic:Pv,websocket:!0})],jt.prototype,"handleDayChange",1);fo([B({topic:kv,websocket:!0})],jt.prototype,"handleTimeZoneChange",1);jt=fo([R(as)],jt);const $r={registration:{[as]:{class:jt,singleton:!0}},type:as,predicate:Ie(as),factory:le.Singleton.create(as)};var Lv=Object.defineProperty,Fv=Object.getOwnPropertyDescriptor,Uu=(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 ju="log-block-container-model";let Cr=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_models");this.id=t,this.logger=s.logger,this._models=new ke({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}`)}};Uu([Pe],Cr.prototype,"_models",2);Cr=Uu([R(ju)],Cr);const Nv=m.createLogger({name:"log-stream-container-service",group:"Services"}),Bu=()=>{var r;const t=be(),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},ss=Bu(),Uv="/api/kos/logs/node/{nodeId}/streams",Hu=async()=>(Nv.debug("sending GET for log-stream-container"),await Le.get(Uv,{path:{nodeId:"primary"}},{destinationAddress:ss})),Ku=async(t,e="primary")=>{await Le.post("/api/kos/logs/node/{nodeId}/{stream}/subscribe",{path:{nodeId:e,stream:t}},void 0,{destinationAddress:ss})},qu=async t=>{await Le.post("/api/kos/logs/node/{nodeId}/{stream}/unsubscribe",{path:{nodeId:"primary",stream:t}},void 0,{destinationAddress:ss})},jv=async()=>{await Le.post("/api/kos/logs/overrides",{},{level:"WARN",name:"com.example",nodeType:"java",type:"package"},{destinationAddress:ss})},zu=async t=>await Le.get("/api/kos/logs/node/{nodeId}/{stream}/blocks",{path:{nodeId:"primary",stream:t}},{destinationAddress:ss}),Vu=async(t,e)=>await Le.get("/api/kos/logs/node/{nodeId}/{stream}/blocks/{blockId}",{path:{nodeId:"primary",stream:t,blockId:e}},{destinationAddress:ss}),Bv=Object.freeze(Object.defineProperty({__proto__:null,createOverride:jv,getKosConnectionId:Bu,getLogStreamBlock:Vu,getLogStreamBlocks:zu,getLogStreams:Hu,subscribeToLogStream:Ku,unsubscribeFromLogStream:qu},Symbol.toStringTag,{value:"Module"}));var Hv=Object.getOwnPropertyDescriptor,Kv=(t,e,s,r)=>{for(var o=r>1?void 0:r?Hv(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const Gu="log-block-model";let Wo=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 Vu(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}`)}};Wo=Kv([R(Gu)],Wo);const ks=new ve({class:Wo,type:Gu}),po=new ve({class:Cr,type:ju});po.addRelatedModel(ks);var qv=Object.defineProperty,zv=Object.getOwnPropertyDescriptor,Yu=(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 Wu="log-stream-model";let Dr=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=po.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=ks.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=ks.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 Ku(this.name)}async unsubscribe(){await qu(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 zu(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=Gl(()=>{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()}}};Yu([Pe],Dr.prototype,"_blocks",2);Dr=Yu([R(Wu)],Dr);const Os=new ve({class:Dr,type:Wu});var Vv=Object.defineProperty,Gv=Object.getOwnPropertyDescriptor,Mt=(t,e,s,r)=>{for(var o=r>1?void 0:r?Gv(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&&Vv(e,s,o),o};const Qu="log-stream-container-model",Yv="/kos/logs/subscription/addBlock/*",Wv="/kos/logs/subscription/updateBlock/*",Qv="/kos/logs/subscription/removeBlock/*",Zv="/kos/logs/subscription/lines/*",Zu="/kos/logs/streams/add/*";let Ke=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 ke({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: ${Zu}`);const e=t.stream,s=Os.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=Os.instance(t).options({name:t,nodeId:"primary"}).build();this.addModel(e),await e.subscribe()}async load(){this.logger.debug(`loading log-stream-container container ${this.id}`);const[t,e]=await Hu();if(t){this.logger.error(`Error loading log-streams: ${t}`);return}e&&e.forEach(s=>{const r=Os.instance(s).options({name:s,nodeId:"primary"}).build();this.addModel(r)})}};Mt([Pe],Ke.prototype,"_models",2);Mt([B({topic:[Zu],websocket:!0})],Ke.prototype,"handleStreamAdded",1);Mt([B({topic:[Yv],websocket:!0})],Ke.prototype,"handleAddBlock",1);Mt([B({topic:[Qv],websocket:!0})],Ke.prototype,"handleRemoveBlock",1);Mt([B({topic:[Wv],websocket:!0})],Ke.prototype,"handleUpdateBlock",1);Mt([B({topic:[Zv],websocket:!0})],Ke.prototype,"handleLogLine",1);Ke=Mt([R(Qu)],Ke);const Ws=new $e({class:Ke,type:Qu});Ws.addRelatedModel(Os);Ws.addRelatedModel(po);Ws.addRelatedModel(ks);const Xv=t=>t.rank!==void 0,Jv=t=>t.visibleRole!==void 0,ew=t=>t.color!==void 0,tw=t=>{const e=t.info??{};return Xv(e)?e.rank:0},sw=t=>{const e=t.info??{};return ew(e)?e.color:"orange"},rw=t=>{const e=t.info??{};return Jv(e)?e.visibleRole:"TECHNICIAN"},{URL:go}=ue(),{getAll:ow,postModel:Xu}=ie.build({basePath:`${go}/api/kos/troubles`}),Ju=async t=>await ow({urlOverride:`${go}${t}`}),ed=async(t,e="/api/kos/troubles",s)=>{try{const r=await Xu({model:{},urlOverride:`${go}${e}/resolve/${t}`,tracker:s});return r!=null&&r.data&&pt.initiateFuture(r.data),r.data}catch{const o={id:s||"",endState:Je.Fail,tracker:s,reason:"Failed to resolve trouble"};return pt.initiateFuture(o),o}},nw=async(t,e="/api/kos/troubles",s)=>{try{const r=await Xu({model:t,urlOverride:`${go}${e}/resolve/`,tracker:s});return r!=null&&r.data&&pt.initiateFuture(r.data),r.data}catch{const o={id:s||"",endState:Je.Fail,tracker:s,reason:"Failed to resolve troubles"};return pt.initiateFuture(o),o}},iw=Object.freeze(Object.defineProperty({__proto__:null,bulkResolveTroubles:nw,getTroubles:Ju,resolveTrouble:ed},Symbol.toStringTag,{value:"Module"})),xr="troubleDataMapper",ir=new Map;zs(xr,{register:(t,e)=>{var s;ir.has(t)||ir.set(t,[]),(s=ir.get(t))==null||s.push(e)},execute:async(t,e)=>{const s=ir.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 Qs="troubleMapper",ar=new Map;zs(Qs,{register:(t,e)=>{var s;ar.has(t)||ar.set(t,[]),(s=ar.get(t))==null||s.push(e)},execute:async(t,e)=>{const s=ar.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))}});$[Qs].register("nozzle",async t=>[t.data.nozzlePath]);$[Qs].register("path",async t=>[t.data.path]);const aw=async t=>{const e=new Set,s=t.ifaces,r=s==null?void 0:s.map(n=>$[Qs].execute(n,t));return(await Promise.allSettled(r)).forEach(n=>{n.status==="fulfilled"&&n.value.forEach(i=>e.add(i))}),Array.from(e)},td=async t=>{const e=t.ifaces,s=e==null?void 0:e.map(i=>$[xr].execute(i,t)),r=$[xr].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 cw{constructor(){l(this,"type","ResolvableTrouble");l(this,"title","Resolvable Trouble");l(this,"subtitle","Trouble")}}class lw{constructor(){l(this,"type","BlockPumpTrouble");l(this,"title","Block Pump Trouble");l(this,"subtitle","Trouble")}}class It{static getHandler(e){switch(e){case"ResolvableTrouble":return new cw;case"BlockPumpTrouble":return new lw;default:return}}}var uw=Object.defineProperty,dw=Object.getOwnPropertyDescriptor,sd=(t,e,s,r)=>{for(var o=r>1?void 0:r?dw(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&&uw(e,s,o),o};const cs="trouble-model";function cr(t){return typeof t.shouldDefer=="boolean"}let Ar=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,...g},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,g),this.futureHandler=new so(this)}getTitleWithContext(t){var s,r;const e=t?(r=(s=It.getHandler(this.type))==null?void 0:s.context)==null?void 0:r[t]:It.getHandler(this.type);return(e==null?void 0:e.title)||"Trouble"}getSubtitleWithContext(t){var s,r;const e=t?(r=(s=It.getHandler(this.type))==null?void 0:s.context)==null?void 0:r[t]:It.getHandler(this.type);return(e==null?void 0:e.subtitle)||"Trouble"}get rawId(){return this._troubleId}get title(){var t;return((t=It.getHandler(this.type))==null?void 0:t.title)||"Trouble"}get subtitle(){var t;return((t=It.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 td(this)}get deferredCompanion(){const t=jo(this.id,e=>cr(e));if(t&&cr(t.modelData))return t.modelData}get deferred(){return this.deferredCompanion?this.deferredCompanion.deferred:!1}get shouldDefer(){const t=jo(this.id,e=>cr(e));return t&&cr(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 ed(this._troubleId,this.servicePath,t)}};sd([Oi()],Ar.prototype,"resolve",1);Ar=sd([R(cs)],Ar);const Ls={registration:{[cs]:{class:Ar,singleton:!1}},type:cs,predicate:Ie(cs),factory:le.Factory.create(cs)};var rd=Object.defineProperty,hw=Object.getOwnPropertyDescriptor,fw=(t,e,s)=>e in t?rd(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,li=(t,e,s,r)=>{for(var o=r>1?void 0:r?hw(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&&rd(e,s,o),o},pw=(t,e,s)=>(fw(t,e+"",s),s);function fa(t){return $.propertyMapper.hasMapper(_e.TroubleRank)?$.propertyMapper.executeMapper(_e.TroubleRank,t):tw(t)}function pa(t){return($.propertyMapper.hasMapper(_e.TroubleColor)?$.propertyMapper.executeMapper(_e.TroubleColor,t):sw(t)).toLowerCase()}function ga(t){return($.propertyMapper.hasMapper(_e.TroubleRole)?$.propertyMapper.executeMapper(_e.TroubleRole,t):rw(t)).toLowerCase()}const gw="trouble-container-model";class ye{}l(ye,"INDEX_TROUBLES_BY_IFACE","byIface"),l(ye,"INDEX_TROUBLES_BY_TYPE","byType"),l(ye,"INDEX_TROUBLES_BY_GROUP","byGroup"),l(ye,"INDEX_TROUBLES_BY_DEFERRED","byDeferred"),l(ye,"SORT_KEY_RANK","rank"),l(ye,"TROUBLES_DEFERRED","true");let Bt=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 Ju(this.servicePath);try{t==null||t.data.forEach(e=>{const s={...e,servicePath:this.servicePath,rank:fa(e),color:pa(e),role:ga(e),id:String(e.id)},r=Ls.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&&De(s)}handleTroubleAdded(t){const e={...t,servicePath:this.servicePath,rank:fa(t),color:pa(t),role:ga(t),id:String(t.id)};if(e.role==="NONE")return;const s=Ls.factory(`trouble-${t.id}`)(e);this.troubles.addModel(s)}};pw(Bt,"Registration");li([B({topic:"/kos/trouble/remove",websocket:!0,lifecycle:D.INIT})],Bt.prototype,"handleTroubleRemoved",1);li([B({topic:"/kos/trouble/add",websocket:!0})],Bt.prototype,"handleTroubleAdded",1);Bt=li([R({modelTypeId:gw,singleton:!0}),Sc(),wc({containerProperty:"troubles",containerOptions:{indexMap:{[ye.INDEX_TROUBLES_BY_IFACE]:aw,[ye.INDEX_TROUBLES_BY_TYPE]:"type",[ye.INDEX_TROUBLES_BY_GROUP]:"group",[ye.INDEX_TROUBLES_BY_DEFERRED]:"deferred"},sortKey:ye.SORT_KEY_RANK}})],Bt);const Ht=Bt.Registration,{URL:od}=ue(),{getAll:mw}=ie.build({basePath:`${od}/api/kos/ota`}),ma=m.createLogger({name:"ota-service",group:"Services"}),yw=async()=>{ma.debug("sending GET request to /api/kos/ota/artifacts");const t=await mw({urlOverride:`${od}/api/kos/ota/artifacts`});return ma.debug("getArtifacts - response:",t),t==null?void 0:t.data};var bw=Object.defineProperty,vw=Object.getOwnPropertyDescriptor,mo=(t,e,s,r)=>{for(var o=r>1?void 0:r?vw(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&&bw(e,s,o),o};const nd="ota-model",ww=t=>{let e=null;for(const s in t){const r=t[s],o=r.lastUpdateTime;(!e||e.lastUpdateTime<o)&&(e=r)}return e},Ro=t=>{const e=t.artifactInfo,s=ww(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 Kt=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"data",new Nn);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 yw();t&&t.forEach(e=>{const s=Ro(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=Ro(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=Ro(e);s&&this.data.updateModel(s)})}catch(e){this.logger.error(`handleChangedArtifacts ${this.id} - error:`,e)}}};mo([Wt({modelType:Ht.type})],Kt.prototype,"troubleContainer",2);mo([B({topic:"/kos/ota/artifacts/all",websocket:!0})],Kt.prototype,"handleAllArtifacts",1);mo([B({topic:"/kos/ota/artifacts/changed",websocket:!0})],Kt.prototype,"handleChangedArtifacts",1);Kt=mo([R(nd)],Kt);const Rr=new $e({class:Kt,type:nd});function Ew(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 Po=m.createLogger({name:"software-info-service",group:"Services"}),ui=async t=>{Po.debug("sending GET for software-info");const[e,s]=await gu.get("/api/kos/manifest/info",void 0,{signal:t});if(!s)throw t!=null&&t.aborted?(Po.debug("Request was aborted"),new z("Request was aborted")):(Po.error("Failed to fetch software-info",e),new z("Failed to fetch software-info"));return s},Mw=Ew(ui),Tw=Object.freeze(Object.defineProperty({__proto__:null,getSoftwareInfos:ui,getSoftwareInfosWithCancel:Mw},Symbol.toStringTag,{value:"Module"}));var _w=Object.getOwnPropertyDescriptor,Sw=(t,e,s,r)=>{for(var o=r>1?void 0:r?_w(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const ls="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 ui(),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 z&&this.logger.error("Failed to fetch software-info",t)}}};Qo=Sw([R(ls)],Qo);const Pr={registration:{[ls]:{class:Qo,singleton:!1}},type:ls,predicate:Ie(ls),factory:le.Factory.create(ls)},{URL:id}=ue(),{getOne:Ow}=ie.build({basePath:`${id}/api/kos/state`}),Iw=m.createLogger({name:"state-bean-service",group:"Services"}),ad=async({path:t})=>(Iw.debug("sending GET for state-bean"),await Ow({urlOverride:`${id}/api/kos/state/${t}`})),$w=Object.freeze(Object.defineProperty({__proto__:null,getStateBeanData:ad},Symbol.toStringTag,{value:"Module"}));var Cw=Object.defineProperty,Dw=Object.getOwnPropertyDescriptor,cd=(t,e,s,r)=>{for(var o=r>1?void 0:r?Dw(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&&Cw(e,s,o),o};const us="state-bean-model",xw=mt("path");let kr=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=jn.map(new Map),zo(e,this)}updateModel(t){zo(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"&&ro(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 ad({path:this.path});t!=null&&t.data&&this.updateProps(t.data)}};cd([B({topic:`/kos/state/${xw}`,websocket:!0})],kr.prototype,"handleConfigBeanUpdated",1);kr=cd([R(us)],kr);const Fs={registration:{[us]:{class:kr,singleton:!1}},type:us,predicate:Ie(us),factory:le.Factory.create(us)};var Aw=Object.defineProperty,Rw=Object.getOwnPropertyDescriptor,ld=(t,e,s,r)=>{for(var o=r>1?void 0:r?Rw(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&&Aw(e,s,o),o};const ds="state-prop-model",ya=mt("path");let Lr=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())??""}};ld([Wt({modelType:Fs.type,id:`state-bean-${ya}`,options:{path:ya}})],Lr.prototype,"stateBean",2);Lr=ld([R(ds)],Lr);const di={registration:{[ds]:{class:Lr,singleton:!1}},type:ds,predicate:Ie(ds),factory:le.Factory.create(ds)},{URL:Pw}=ue(),{getAll:kw}=ie.build({basePath:`${Pw}/api/state-prop`}),Lw=m.createLogger({name:"state-prop-service",group:"Services"}),Fw=async()=>(Lw.debug("sending GET for state-prop"),await kw({})),Nw=Object.freeze(Object.defineProperty({__proto__:null,getStateProps:Fw},Symbol.toStringTag,{value:"Module"})),{URL:hi}=ue(),{getOne:ud}=ie.build({basePath:`${hi}/api/translation`}),Is=m.createLogger({name:"translation-service",group:"Services"}),Uw=()=>{const t=window.location.origin,e=be();return(e==null?void 0:e.host)||t},dd=async(t,e)=>{Is.debug(`Loading translations from: ${t}`);const s=e??Uw();try{const r=await fetch(`${s}${t}`);return r.status!==200?(Is.warn(`Failed to fetch translations at ${t}: ${r.status}`),{}):await r.json()}catch(r){throw Is.error("Error fetching translations",r),r}},jw=async()=>{Is.debug("Getting system localization descriptor");const t=await ud({urlOverride:`${hi}/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},hd=t=>async()=>{Is.debug(`Getting KOS localization descriptor for context: ${t}`);const e=await ud({urlOverride:`${hi}/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]},fd="langResolver";var Bw=Object.getOwnPropertyDescriptor,Hw=(t,e,s,r)=>{for(var o=r>1?void 0:r?Bw(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const hs="translation-model";function Kw(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 pd(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=pd(t[r],o);return{...s,...n}}else return{...s,[o]:t[r]}},{})}function gd(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]=gd(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},lr=(t,e,s)=>{const r=/{{(.*?)}}/g,n=Zo(t,e).replace(r,(a,c)=>{const u=c.trim();if(Object.prototype.hasOwnProperty.call(s||{},u))return s==null?void 0:s[u];if(u.includes(".")){const d=u.split(".");let h=s;for(const f of d)if(h&&typeof h=="object"&&Object.prototype.hasOwnProperty.call(h,f))h=h[f];else return a;return h}return a});return Zo(n,e)},ba=(t,e)=>{if(e.includes(":")){const[s,r]=e.split(":");return{namespace:s,key:r}}else return{namespace:t,key:e}};let Xo=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(fd),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=W.getContext(this.id);return this.bundleResolver(this.namespace,r,o)}try{const o=this.resolver(this.namespace,r);return dd(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=gd(o,n.value))):this.logger.error(`failed to load translation ${this.id} for ${t[i]}`),o),{});this.data=pd(r)})}async init(){this.logger.debug(`initializing translation ${this.id}`)}exists(t){const{namespace:e,key:s}=ba(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}=Kw(e),{namespace:n,key:i}=ba(this.namespace,t),a=`${i}_${r}`;if(n!==this.namespace){const c=this.context.getModel(n);return c?c.resolveKey(i,e):s??i}if(r&&this.data[a]){const c=this.data[a];return Array.isArray(c)?c.map(u=>lr(u,this.data,o)):lr(this.data[a],this.data,o)}if(this.data[i]){const c=this.data[i];return Array.isArray(c)?c.map(u=>lr(u,this.data,o)):lr(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()})}};Xo=Hw([Jr(),R(hs)],Xo);const Fr={registration:{[hs]:{class:Xo,singleton:!1}},type:hs,predicate:Ie(hs),factory:le.Factory.create(hs)};var qw=Object.defineProperty,zw=Object.getOwnPropertyDescriptor,md=(t,e,s,r)=>{for(var o=r>1?void 0:r?zw(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&&qw(e,s,o),o};const fs="translation-container-model",Vw=(t,e="/")=>t.join(e).replace(new RegExp(e+"{1,}","g"),e);function Gw(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 Vw([r,o])}let Nr=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||Gw.bind(this),s.kosContext.set(fd,this.resolver),this.logger=s.logger,this._models=new ke({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 pe(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=Fr.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=Fr.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)}};md([Pe],Nr.prototype,"_models",2);Nr=md([R(fs)],Nr);const qe={registration:{[fs]:{class:Nr,singleton:!0}},type:fs,predicate:Ie(fs),factory:le.Singleton.create(fs)},Yw={set(t,e){const s=W.getContext(qe.type);s&&s.set(t,e)},get(t){const e=W.getContext(qe.type);return e==null?void 0:e.get(t)}},yd={async init(t){const e=qe.factory(t);return await pe(e),{translations:e}}};function Ww(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 bd="kos-ws-event",fi=Qt(bd);var Qw=Object.defineProperty,Zw=Object.getOwnPropertyDescriptor,pi=(t,e,s,r)=>{for(var o=r>1?void 0:r?Zw(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&&Qw(e,s,o),o};const Xw=({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:Xw({headers:o,body:r}),direction:s?"send":"receive",mocked:!!o.mocked};this.events.set(a,c),m.debug(`logged ${this.events.size} events`)}}};pi([B({topic:[Hs.SEND]})],exports.WsEventModel.prototype,"handleSendEvent",1);pi([B({topic:[Hs.RECEIVED]})],exports.WsEventModel.prototype,"handleReceiveEvent",1);exports.WsEventModel=pi([R(fi.type)],exports.WsEventModel);const va=be(),Jw=va.debug==="true"||va.debug===!0,eE="/api/system/canvas",vd=async(t,e)=>{const s=e||eE,r=`${exports.BASE_URL}${s}`;await exports.kosFetch(r,{method:"POST",headers:{hide:Jw?"false":"true"},body:t})},tE=Object.freeze(Object.defineProperty({__proto__:null,sendCanvasData:vd},Symbol.toStringTag,{value:"Module"}));function wa(t,e,s){{const r=t.filter((o,n)=>n%4!==3);return btoa(String.fromCharCode(...r))}}var sE=Object.defineProperty,rE=Object.getOwnPropertyDescriptor,wd=(t,e,s,r)=>{for(var o=r>1?void 0:r?rE(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&&sE(e,s,o),o};const Ed="canvas-renderer-model";function ko(t){return typeof t.onDone=="function"}let Ur=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){vd(t,e)}checkStreaming(){if(this.isOneShotDone()||!this.isStreaming){requestAnimationFrame(()=>{const t=this.isOneShotDone();this.stopStreaming(!t)});return}}handleFrame(t){var s;const e=wa(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=wa(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 ko(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=ko(this._renderer);ko(this._renderer)&&this._renderer.onDone(()=>{var c,u,d;this.logger.debug(`Renderer completed for ${this.id}`),K("/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"})})}};wd([Wt({modelType:Zn.type})],Ur.prototype,"router",2);Ur=wd([R(Ed)],Ur);const gi=new ve({class:Ur,type:Ed});class Md{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 oE{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 nE extends oE{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=`
|
|
111
111
|
attribute vec2 a_position;
|
|
112
112
|
void main() {
|
|
113
113
|
gl_Position = vec4(a_position, 0, 1);
|