@kosdev-code/kos-ui-sdk 2.0.31 → 2.0.32
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/common/events/eventBus.d.ts +16 -0
- package/common/events/eventBus.d.ts.map +1 -1
- package/common/events/eventBus.functional.d.ts +150 -0
- package/common/events/eventBus.functional.d.ts.map +1 -0
- package/common/events/eventBus.state.d.ts +118 -0
- package/common/events/eventBus.state.d.ts.map +1 -0
- package/common/events/index.d.ts +5 -2
- package/common/events/index.d.ts.map +1 -1
- package/core/core/decorators/kosTopicHandler.d.ts +61 -14
- package/core/core/decorators/kosTopicHandler.d.ts.map +1 -1
- package/core/core/log/log.d.ts +1 -1
- package/core/core/services/app-startup-service.d.ts +74 -0
- package/core/core/services/app-startup-service.d.ts.map +1 -0
- package/core/core/services/index.d.ts +1 -0
- package/core/core/services/index.d.ts.map +1 -1
- package/core/types/utils/kos-fetch.d.ts +10 -2
- package/core/types/utils/kos-fetch.d.ts.map +1 -1
- package/core/util/binary-utils.d.ts +44 -0
- package/core/util/binary-utils.d.ts.map +1 -0
- package/core/util/kos-fetch.d.ts.map +1 -1
- package/index.cjs +76 -76
- package/index.cjs.map +1 -1
- package/index.js +6431 -5370
- package/index.js.map +1 -1
- package/models/decorators/future-service.d.ts +7 -0
- package/models/decorators/future-service.d.ts.map +1 -1
- package/models/index.d.ts +1 -0
- package/models/index.d.ts.map +1 -1
- package/models/models/canvas-dispatcher/utils/renderers/base/video-base-renderer.d.ts +3 -1
- package/models/models/canvas-dispatcher/utils/renderers/base/video-base-renderer.d.ts.map +1 -1
- package/models/models/canvas-dispatcher/utils/renderers/image-renderer.d.ts +3 -1
- package/models/models/canvas-dispatcher/utils/renderers/image-renderer.d.ts.map +1 -1
- package/models/models/software-info/services/software-info-services.d.ts +23 -1
- package/models/models/software-info/services/software-info-services.d.ts.map +1 -1
- package/models/types/cancellable-promise.d.ts +49 -0
- package/models/types/cancellable-promise.d.ts.map +1 -0
- package/models/types/future-interfaces.d.ts +55 -0
- package/models/types/future-interfaces.d.ts.map +1 -0
- package/models/types/index.d.ts +3 -0
- package/models/types/index.d.ts.map +1 -0
- package/models/utils/cancellable-future-call.d.ts +54 -0
- package/models/utils/cancellable-future-call.d.ts.map +1 -0
- package/models/utils/cancellable-service.d.ts +79 -0
- package/models/utils/cancellable-service.d.ts.map +1 -0
- package/models/utils/client.d.ts +15 -7
- package/models/utils/client.d.ts.map +1 -1
- package/models/utils/index.d.ts +2 -0
- package/models/utils/index.d.ts.map +1 -1
- package/models/utils/kosmodel-compatible-future-mixin.d.ts +142 -0
- package/models/utils/kosmodel-compatible-future-mixin.d.ts.map +1 -0
- package/models/utils/kosmodel-interface-companion-mixin.d.ts +83 -0
- package/models/utils/kosmodel-interface-companion-mixin.d.ts.map +1 -0
- package/models/utils/openapi.d.ts +9304 -3999
- package/models/utils/service.d.ts +15 -7
- package/models/utils/service.d.ts.map +1 -1
- package/package.json +2 -2
package/index.cjs
CHANGED
|
@@ -1,80 +1,80 @@
|
|
|
1
|
-
"use strict";var sd=Object.defineProperty;var od=(e,t,s)=>t in e?sd(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var a=(e,t,s)=>(od(e,typeof t!="symbol"?t+"":t,s),s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const T=require("loglevel"),w=require("mobx"),p=require("robot3"),ye=require("date-fns"),M=require("@emotion/react/jsx-runtime"),No=require("@emotion/styled"),An=require("react-dom"),Te=require("@emotion/react"),g=require("react"),Uo=require("mobx-react-lite"),rd=require("@use-gesture/react"),Us="method",Cn="topic",Qe="url",Ht="request-id",js="response-id",jo="status",me="dst-addr",Rn="src-addr",de="type",Bo="ordered",Ko="tracker",Pn="Content-Type",Ln="Cache-Control",xn="requestId",kn=process.env.KOS_LOGIN_URL||"http://localhost",Fn=process.env.KOS_APP_PORT||"8080",nd=`${kn}:${Fn}`,fs="{MODEL_ID}";var Gt=(e=>(e.SEND="/ws/log/msg/send",e.RECEIVED="/ws/log/msg/receive",e))(Gt||{}),Nn=(e=>(e.MSG_RECEIVE="/mock/msg/receive",e))(Nn||{});const Ho="/kos/model/ready/";T.info("Initializing event bus");globalThis.kos=globalThis.kos||{};globalThis.kos.subscriptions=globalThis.kos.subscriptions||{};const P=globalThis.kos.subscriptions,id=()=>Symbol("eventKey");function Go(e){return P[e]&&Object.getOwnPropertySymbols(P[e]).length>0}function U(e,t){const s=id();return P[e]||(T.debug(`Initializing subscription for ${e}`),P[e]={}),T.debug(`Subscribing to ${e} with id ${s.toString()}`),P[e][s]=t,{count:P[e]?Object.getOwnPropertySymbols(P[e]).length:0,unsubscribe:()=>(T.debug(`Unsubscribing from ${e} with id ${s.toString()}`),P[e]&&P[e][s]&&delete P[e][s],P[e]&&Object.getOwnPropertySymbols(P[e]).length===0&&delete P[e],{count:P[e]?Object.getOwnPropertySymbols(P[e]).length:0})}}function F(e,t,s={}){if(!P[e]||Object.getOwnPropertySymbols(P[e]).length===0)return T.debug(`No subscriptions for ${e}. Not publishing.`),{eventType:e,subscribers:0};const o=Object.getOwnPropertySymbols(P[e]).length;return Object.getOwnPropertySymbols(P[e]).forEach(r=>{if(s.sync){const n=s.sync;T.debug(`Performing sync publish for ${e} with sync id ${n}`),P[e][r]({body:t,headers:s}).then(i=>{T.debug(`Response recieved for ${n}, publishing back to source.`),F(n,i)})}else T.debug(`Performing async publish for ${e}`),P[e][r]({body:t,headers:s})}),{eventType:e,subscribers:o}}function ad(){T.warn("Resetting event bus"),Object.keys(P).forEach(e=>delete P[e])}const cd=Object.freeze(Object.defineProperty({__proto__:null,hasEventSubscriptions:Go,publish:F,reset:ad,subscribe:U},Symbol.toStringTag,{value:"Module"})),ld=(e,t=0)=>{if(!+e)return{value:0,scale:"bytes",toString:()=>"0 bytes"};const s=1024,o=t<0?0:t,r=["bytes","KB","MB","GB","TB"],n=Math.floor(Math.log(e)/Math.log(s)),i=parseFloat((e/Math.pow(s,n)).toFixed(o)),c=r[n];return{value:i,scale:c,toString:()=>`${i} ${c}`}};function Vo(e){let t="pending",s;const o=e.then(n=>{t="success",s=n},n=>{t="error",s=n});return{read:()=>{switch(t){case"pending":throw o;case"error":throw s;default:return s}}}}function et(){return"xxxxxxxx-xxxx-4xxx-2xxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){const t=Math.random()*16|0;return(e=="x"?t:t&3|8).toString(16)})}function dd(e,t){t.forEach(s=>{Object.getOwnPropertyNames(s.prototype).forEach(o=>{const r=Object.getOwnPropertyDescriptor(s.prototype,o);Object.defineProperty(e.prototype,o,r)})})}function ud(e,t){const s=e??[],o=t??[];return s.length!==o.length?!1:s.every((r,n)=>r===o[n])}const Yo=(e,t)=>{const s=e.map(n=>n.id);return t.map(n=>n.id).filter(n=>!s.includes(n))},hd=({container:e,onAddItem:t,onRemoveItem:s,idMapper:o=r=>r})=>r=>{const n=r.map(o),c=Yo(n,e.data).map(s).filter(Boolean);e.removeAll(c);const l=n.map(t).filter(Boolean);e.addAll(l)},gd=({container:e,onAddItem:t,onRemoveItem:s,idMapper:o=r=>r})=>r=>{const n=r.map(o);Yo(n,e.models).forEach(s),n.forEach(t)},fd=({items:e,onAddItem:t,onRemoveItem:s,idMapper:o=r=>r})=>r=>{const n=r.map(o);Yo(n,e).forEach(s),n.forEach(t)},md=(e,t="parent-")=>{let s=e;return s.startsWith(t)&&(s=s.replace(t,"")),s},Yr=new Intl.RelativeTimeFormat(void 0,{numeric:"auto"}),zr=[{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 Un(e){let t=(e.getTime()-Date.now())/1e3;for(let s=0;s<=zr.length;s++){const o=zr[s];if(Math.abs(t)<o.amount)return Yr.format(Math.round(t),o.name);t/=o.amount}return Yr.format(Math.round(t),"years")}const zo=e=>e%4===0&&e%100!==0||e%400===0,qo=(e,t)=>[31,zo(e)?29:28,31,30,31,30,31,31,30,31,30,31][t],jn=(e,t)=>{const s=new Date(e),o=e.getDate();return s.setDate(1),s.setMonth(s.getMonth()+t),s.setDate(Math.min(o,qo(s.getFullYear(),s.getMonth()))),s},Bn=(e,t)=>{const s=new Date(e);return s.setDate(s.getDate()+t),s},He="en-US",Kn={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"}},Hn={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"}},Gn=(e,{dateStyle:t="short",locales:s=He}={dateStyle:"short",locales:He})=>{const o=t==="short"?Kn.short:{dateStyle:t};return new Intl.DateTimeFormat(s,o).format(e)},Vn=(e,{locales:t=He,timeStyle:s="short"}={locales:He,timeStyle:"short"})=>{const o=Hn[s];return new Intl.DateTimeFormat(t,o).format(e)},Yn=(e,{dateStyle:t="short",locales:s=He,timeStyle:o="short"}={dateStyle:"short",locales:He,timeStyle:"short"})=>{const r={...t&&Kn[t],...o&&Hn[o]};return new Intl.DateTimeFormat(s,r).format(e)},pd=Object.freeze(Object.defineProperty({__proto__:null,addDaysToDate:Bn,addMonthsToDate:jn,formatDate:Gn,formatDateSince:Un,formatDateTime:Yn,formatTime:Vn,getDaysInMonth:qo,isLeapYear:zo},Symbol.toStringTag,{value:"Module"}));function zn(e,t,s=300){let o;return(...r)=>{clearTimeout(o),o=setTimeout(()=>{t.apply(e,r)},s)}}class qn{constructor(t={}){a(this,"flags",{});this.flags=t}isFeatureEnabled(t){return!!this.flags[t]}enableFeature(t){this.flags[t]=!0}disableFeature(t){this.flags[t]=!1}toggleFeature(t){this.flags[t]=!this.flags[t]}updateFlags(t){this.flags={...this.flags,...t}}}window.KosFeatureFlags=window.KosFeatureFlags??new qn;const yd=window.KosFeatureFlags,ee=(e=null)=>(e||window.location.search.replace("?","")).split("&").map(t=>{const[s,o]=t.split("=");return[s,decodeURIComponent(o||"")]}).reduce((t,[s,o])=>(t[s]=o,t),{}),Wn=(e,t,s)=>{s/=100;const o=t*Math.min(s,1-s)/100,r=n=>{const i=(n+e/30)%12,c=s-o*Math.max(Math.min(i-3,9-i,1),-1);return Math.round(255*c).toString(16).padStart(2,"0")};return`#${r(0)}${r(8)}${r(4)}`},Zn=e=>{const s=new RegExp("hsl\\((\\d+),\\s+(\\d+)\\%,\\s+(\\d+)\\%\\)").exec(e);if(!s)throw Error("Invalid HSL string");return Wn(parseInt(s[1]),parseInt(s[2]),parseInt(s[3]))},Jn=(e,t)=>getComputedStyle(e).getPropertyValue(t),bd=(e,t)=>Zn(Jn(e,t)),Xn="studio.tools.preview",vd="studio.relax.store.validation",Qn="studio.log.debug",ei="studio.log.info",wd={profiles:[Xn]};var Dn;const Md=((Dn=globalThis.getKosConfig)==null?void 0:Dn.call(globalThis))||JSON.stringify(wd),ti=JSON.parse(Md);globalThis.kosConfig=ti;const Wo=ti,si=()=>Wo.profiles||[],bo=e=>si().includes(e),_d=()=>Wo.logging||!1,Ed=(e,t)=>{const s={...e};return s.id&&delete s.id,s},vo=(e,t,s=Ed)=>{const o=s(e,t);w.runInAction(()=>{Object.assign(t,o)})},ro=new Map,oi={addToDeletionQueue:(e,t)=>{const s=ro.get(e)||[];s.push(t),ro.set(e,s)},cancelDeletion:e=>{const t=ro.get(e);t&&t.forEach(s=>{clearTimeout(s)})}},Id=()=>{const e=bo(Qn),t=bo(ei);return e?"DEBUG":t?"INFO":void 0},ri=()=>{const e=ee(),t=Id(),o=e.kosLogLevel??t??window.kosLogLevel??process.env.KOS_LOG_LEVEL;return o||"WARN"},ni=()=>window.kosMessageLogging||process.env.KOS_MESSAGE_LOGGING==="true",ii=()=>window.kosMessageStudioLogging||process.env.KOS_MESSAGE_STUDIO_LOGGING==="true",ai="ws-log",Td=T.methodFactory,ci=ni(),$d=ii();T.methodFactory=function(e,t,s){const o=Td(e,t,s);return function(r,n){var l;const i=s?String(s):"",c=i?`[${String(i).substring(i.lastIndexOf(":")+1)}] | `:"[root] | ";o(`${c}${r}`,n||""),(l=globalThis==null?void 0:globalThis.kosConfig)!=null&&l.logging&&globalThis.kosLog&&(s!==ai||ci&&$d)&&globalThis.kosLog(`UI: ${c}${r}`)}};let li=ri();T.setLevel(li);window.setKosLogLevel=e=>{li=e,T.setLevel(e)};const ms=T.getLogger(ai);window.enableKosMessageLog=()=>{ms.setLevel(T.levels.INFO)};window.disableKosMessageLog=()=>{ms.setLevel(T.levels.ERROR)};ci?window.enableKosMessageLog():window.disableKosMessageLog();const Od=["color: black","display: block","background-color: lightgreen","padding: 4px","margin: 0","text-shadow: 0 1px 0 rgba(0, 0, 0, 0.3)","box-shadow: 0 1px 0 rgba(255, 255, 255, 0.4) inset, 0 5px 3px -5px rgba(0, 0, 0, 0.5), 0 -13px 5px -10px rgba(255, 255, 255, 0.4) inset","font-weight: bold"].join(";"),Sd=["color: black","display: block","padding: 4px","background-color: yellow","margin: 0","text-shadow: 0 1px 0 rgba(0, 0, 0, 0.3)","box-shadow: 0 1px 0 rgba(255, 255, 255, 0.4) inset, 0 5px 3px -5px rgba(0, 0, 0, 0.5), 0 -13px 5px -10px rgba(255, 255, 255, 0.4) inset","font-weight: bold"].join(";"),Xt=e=>t=>{T.getLevel()<=e&&t()},m={...T,ifDebug:Xt(T.levels.DEBUG),ifInfo:Xt(T.levels.INFO),ifWarn:Xt(T.levels.WARN),ifError:Xt(T.levels.ERROR),getLogger:e=>T.getLogger(`kos::${e}`),createLogger:({name:e,group:t})=>T.getLogger(`${t?`${t}:`:"kos"}::${e}`),wsSend:(...e)=>{const t=String(e).replace(/\n/g,"\\n");ms.info(`%c⬆ ${t}`,Od)},wsReceive:(...e)=>{const t=String(e).replace(/\n/g,"\\n");ms.info(`%c⬇ ${t}`,Sd)}},Dd=m.createLogger({name:"kos-dependency-manager"});class Ad{constructor(){a(this,"_usedByCache",new Map);a(this,"_usesCache",new Map)}add(t,s){oi.cancelDeletion(s);const o=this._usedByCache.get(s)||[];o.includes(t)||o.push(t),this._usedByCache.set(s,o);const r=this._usesCache.get(t)||[];r.includes(s)||r.push(s),this._usesCache.set(t,r)}remove(t,s){const o=this._usedByCache.get(s)||[];this._usedByCache.set(s,o.filter(n=>n!==t));const r=this._usesCache.get(t)||[];this._usesCache.set(t,r.filter(n=>n!==s))}canDestroy(t){const s=this._usedByCache.get(t);return s!=null&&s.length?(Dd.info(`Model ${t} is still used by: ${s.join(", ")}`),!1):!0}clear(){this._usedByCache.clear(),this._usesCache.clear()}}var y=(e=>(e.CREATING="creating",e.CREATED="created",e.INITIALIZING="initializing",e.INITIALIZED="initialized",e.LOADING="loading",e.LOADED="loaded",e.ONLINE="online",e.READYING="readying",e.READY="ready",e.READY_FAILED="ready_failed",e.RESETTING="resetting",e.RESET="reset",e.OFFLINE="offline",e.UNLOADING="unloading",e.UNLOADED="unloaded",e.FAILED="failed",e.INACTIVE="inactive",e.ACTIVE="active",e.ACTIVATING="activating",e.DEACTIVATING="deactivating",e))(y||{}),D=(e=>(e.CREATE="create",e.INITIALIZE="init",e.LOAD="load",e.READY="ready",e.GO_ONLINE="go_online",e.GO_OFFLINE="go_offline",e.RESET="go_offline",e.UNLOAD="unload",e.FAILED="failed",e.GO_ACTIVE="go_active",e.GO_INACTIVE="go_inactive",e.TIMEOUT="timeout",e))(D||{});const qr=m.createLogger({name:"kos-model-cache"});class Cd{constructor(t=[]){a(this,"_modelsById",w.observable.map(new Map));a(this,"_toDelete",new Map);a(this,"_preloaded",[]);a(this,"_isPreloaded",!1);this.preloadKeys=t}get models(){return Array.from(this._modelsById.values()).filter(t=>!this._toDelete.has(t.modelId))}getModelById(t){if(t&&!this._toDelete.has(t))return this._modelsById.get(t)}addModel(t){const s=this.getModelById(t.modelId)||t;return this._modelsById.set(s.modelId,s),s}removeModel(t){this._modelsById.delete(t),this._toDelete.delete(t)}hasModel(t){return!!t&&this._modelsById.has(t)&&!this._toDelete.has(t)}restoreFromDeleteCache(t){if(t&&this._toDelete.has(t)){const s=this._toDelete.get(t);this._toDelete.delete(t),this._modelsById.set(t,s)}}markForDeletion(t){this._modelsById.delete(t.modelId),this._toDelete.set(t.modelId,t)}preload(t){return this._isPreloaded?(qr.debug("Returning cached preloaded models"),this._preloaded):(this._preloaded=this.preloadKeys.map(s=>(qr.debug(`Preloading model: ${typeof s=="string"?s:s.modelType}`),t(s))).filter(s=>!!s),this._isPreloaded=!0,this._preloaded)}}const ne="canvas-renderer",no=new Map,Wr=new Map,io=new Map,ao=new Map,Bs=(e,t)=>{di[e]=t},di={indexExtension:{registerIndexExtension:(e,t)=>{const s=ao.get(e)||{};Object.assign(s,t),ao.set(e,t)},loadIndexExtensions:e=>ao.get(e)||{}},loader:{registerLoader:(e,t)=>{Wr.set(e,t)},executeLoader:async(e,t)=>{const s=Wr.get(e);if(s)return await s(t)}},propertyMapper:{registerPropertyMapper:(e,t)=>{io.set(e,t)},hasMapper:e=>io.has(e),executeMapper:(e,t,s)=>{const o=io.get(e);return o?o(t,s):""}},dataMapper:{registerDataMapper:(e,t)=>{const s=no.get(e)||[];s.push(t),no.set(e,s)},executeMapper:async(e,t,s)=>{const o=no.get(e);if(!o)return{};const r={};for(const n of o){const i=await n(t,s);Object.assign(r,i)}return r}},canvas:{registerRenderer:(e,t)=>{if(!$[ne]){console.warn(`Canvas renderer extension point is not registered. Cannot register renderer "${e}".`);return}$[ne].register(e,t)}}},$=di;function ui(e,t){return`${Ho}${e}${t?`/${t}`:`/${e}`}`}function hi(e){return`${Ho}${e}`}var k=(e=>(e.INIT="init",e.LOAD="load",e.READY="ready",e.ACTIVATE="activate",e.ONLINE="online",e))(k||{});const Rd=Object.freeze(Object.defineProperty({__proto__:null,DependencyLifecycle:k},Symbol.toStringTag,{value:"Module"}));function Zr(e){const t=[];return new Promise((s,o)=>{for(const{condition:r,onMatch:n}of e){const i=w.when(r,()=>{t.forEach(c=>c());try{n==null||n(),s()}catch(c){o(c)}});t.push(i)}})}const H=Symbol("SubscriptionHandlers"),L=Symbol("DependencyModels"),Mt=Symbol("FutureService"),_t=Symbol("ChildModels"),Et=Symbol("ParentModel"),It=Symbol("LogConfig"),cs=Symbol("ReferenceConfig"),gi=Symbol("KosModelSymbol"),Oe=Symbol("ModelEffects"),ae=(e,t)=>{e[_t]=e[_t]||{},e[_t][t]=!0},Ae=e=>`{PROP_${String(e)}}`,Pd=e=>`{PROP_${String(e)}}`,Ld=Ae("kosParentId"),Ks=e=>t=>{t[Et]=t[Et]||{};const s=(e==null?void 0:e.parentId)||Ld;t[Et]={parentId:s}},Ge=({value:e,modelId:t,modelData:s})=>{let o=e;if(Array.isArray(o))return[...e];if(typeof o!="string"&&typeof o!="object")return o;if(typeof o=="object")o=Object.keys(o).reduce((r,n)=>(r[n]=Ge({value:o[n],modelId:t,modelData:s}),r),{});else if(typeof o=="string"){const r=new RegExp(".*({PROP_(.+)})");let n=o!=null&&o.includes(fs)?o.replace(fs,t):o;const i=n.match(r);if(i&&s&&(Object.getOwnPropertyNames(s).includes(i[2])||Object.getOwnPropertyNames(Object.getPrototypeOf(s)).includes(i[2]))){const c=s[i[2]];n=c?n.replace(i[1],c):void 0}return n}else return o;return o},xd=m.createLogger({name:"kos-model"});function kd(e,t,s){var n;const o=(n=e[Et])==null?void 0:n.parentId;if(!o)return;const r=Ge({value:o,modelData:s,modelId:t});r&&typeof r=="string"&&x.setParentContext(t,r)}function Fd(e){const t=e[Mt];t&&Object.entries(t).forEach(([s,{handler:o}])=>{e[s]=o})}function Nd(e,t){const s=e[L]||{};Object.entries(s).forEach(([o,r])=>{const n=Ge({value:r.id||r.modelType,modelData:e,modelId:t}),i=Object.entries((r==null?void 0:r.options)||{}).reduce((c,[l,d])=>(c[l]=Ge({value:d,modelData:e,modelId:t}),c),{});if(typeof n=="string"){if(!r.lazy){const c=E.getInstance().modelManager.createModelInstance(r.modelType,n,i);e[o]=c.data}E.getInstance().modelManager.addDependency(t,n)}})}function Ud(e){try{return w.makeAutoObservable(e)}catch(t){return xd.error("Failed to make observable:",t),e}}const jd={construct(e,t){var c;const[s,o={}]=t,r=x.createContext(s);kd(e,s,o);const n=m.createLogger({name:e.prototype.modelTypeId,group:((c=e[It])==null?void 0:c.group)??"kos-model"}),i=new e(s,o,{logger:n,kosContext:r});return Fd(i),Nd(i,s),Ud(i)}};function S(e){return t=>{var o,r;const s=t;return s.prototype.modelTypeId=e,s.prototype[gi]=!0,(o=s.prototype)[H]??(o[H]={}),(r=s.prototype)[L]??(r[L]={}),m.ifDebug(()=>{m.debug(`Registering model with id ${e}`)}),new Proxy(s,jd)}}const Bd=({modelType:e})=>t=>{Ks()(t),S(e)(t)};function Kd(e,t,s){const o=s.value;s.value=function(...r){const n=x.getContext(this.id);return r.push(n),o.apply(this,r)}}const Hd=({group:e}={group:""})=>t=>{t[It]=t[It]||{},t[It]={group:e}};function fi(e){return(t,s,o)=>{t[Oe]=t[Oe]||{},t[Oe][s]={dependencies:e==null?void 0:e.dependencies,value:o.value},o.value=function(){throw new Error(`Method ${s} cannot be called directly.`)}}}const Gd=e=>(t,s)=>{t[cs]=t[cs]||{},t[cs][s]=e},Ce=({modelType:e,id:t,options:s,lifecycle:o})=>(r,n)=>{r[L]=r[L]||{},r[L][n]={modelType:e,id:t,options:s,lifecycle:o||k.INIT}},Vd=({topic:e,handler:t,websocket:s=!1,condition:o=()=>!0})=>r=>{r[H]=r[H]||{},Array.isArray(e)?e.forEach(n=>{r[H][n]={websocket:s,handler:t,condition:o}}):r[H][e]={websocket:s,handler:zn(r,w.action(t),200),condition:o}};function R({topic:e,condition:t=(d,u)=>!0,transform:s=d=>d,websocket:o=!1,fos:r=!1,bridge:n=!1,skipParse:i=!1,lifecycle:c,destinationAddress:l}){return(d,u,h)=>{d[H]=d[H]||{},Array.isArray(e)?e.forEach(f=>{d[H][f]={websocket:o,fos:r,bridge:n,handler:h.value,condition:t,transform:s,lifecycle:c,skipParse:i,destinationAddress:l}}):d[H][e]={websocket:o,fos:r,bridge:n,handler:h.value,condition:t,transform:s,lifecycle:c,skipParse:i,destinationAddress:l}}}const mi=5e3;class Yd extends Error{constructor(s,o){super(s);a(this,"model");this.model=o}}const pi=(e,t,s)=>{let o;return{promise:new Promise((i,c)=>{o=setTimeout(()=>{m.error(`Model ${t.modelId} - ${t.modelTypeName} - ${s} timed out after ${e}ms`),c(new Yd(`${t.modelId} - ${t.modelTypeName} - ${s}`,t))},e)}),cancel:()=>{o&&clearTimeout(o)}}},yi=e=>e.fsm.transitionTo(D.GO_ACTIVE,y.ACTIVE),bi=e=>e.whenReady(),vi=e=>e.fsm.transitionTo(D.LOAD,y.LOADED),zd=e=>e.fsm.transitionTo(D.UNLOAD,y.UNLOADED),wi=e=>e.fsm.transitionTo(D.INITIALIZE,y.INITIALIZED);var Zo=(e=>(e.ACTIVE="active",e.READY="ready",e.LOAD="load",e.UNLOAD="unload",e.INIT="init",e))(Zo||{});const ls={active:yi,ready:bi,load:vi,init:wi},Mi=(e,t)=>{const s=t.id||t.modelType,o=Ge({value:s,modelData:e.modelData,modelId:e.modelId});m.debug(`activating dependent model ${t.modelType} with id ${o}`);const r=Object.keys((t==null?void 0:t.options)||{}).reduce((i,c)=>{const l=t.options[c];return i[c]=Ge({value:l,modelData:e.modelData,modelId:e.modelId}),i},{});return{dependentModel:E.getInstance().modelManager.createModelInstance(t.modelType,o,r),dataModelId:o}},_i=(e,t=k.READY)=>{var r;const s=((r=e.modelData)==null?void 0:r[L])||{};return Object.keys(s).length===0?(m.debug(`${e.modelId} has no dependencies. Returning`),[]):Object.keys(s).filter(n=>s[n].lifecycle===t).map(n=>{const i=s[n],{dependentModel:c,dataModelId:l}=Mi(e,i);e.modelData[n]=c.data,m.debug(`waiting for dependent model ${i.modelType} with id ${l} - waiting for WHENREADY`);const d=async(f,v,b)=>{var _;await((_=f.whenReady)==null?void 0:_.call(f)),m.debug(`dependent model ${v} with id ${b} - READY`)},{promise:u,cancel:h}=pi(mi,e,e.status);return Promise.race([d(c.model,i.modelType,l).then(()=>{h()}).catch(f=>{console.error(`Error waiting for dependent model ${i.modelType} with id ${l}:`,f),h()}),u])}).filter(n=>!!n)},Ei=async(e,t,s,o)=>{if(m.debug(`Execute lifecycle with ${t.length} models`),t.length===0){m.debug(`${e.modelId} has no children. Returning`);return}if(!s){m.error(`${e.modelId} is not transitioning with a valid target ${s}`);return}const r=t.map(c=>{let l;return ls[s]&&c?l=ls[s](c):(c||m.error("model is undefined. This shouldn't happen"),ls[s]||m.error(`There is no promise in the Transition Map for ${s}`)),{promise:l,modelId:c==null?void 0:c.modelId,model:c,type:c==null?void 0:c.modelTypeName,status:c==null?void 0:c.status}}).filter(c=>c.promise?c.model?!0:(m.error(`No model found ${c.modelId}`),!1):(m.error(`No promise found ${c.modelId}`),!1)),i=(await Promise.allSettled(r.map(c=>{var u;const{promise:l,cancel:d}=pi(mi,c.model,c.status);return Promise.race([(u=c.promise)==null?void 0:u.then(()=>{d()}).catch(h=>{m.error(`Model ${c.modelId} - ${c.type} failed to transition to ${s}: ${h.message}`),d()}),l])}))).filter(c=>c.status==="rejected");i.length>0&&m.error(`Model ${e.modelId} had ${i.length} failed child models on ${o}`)},Ii=async(e,t,s)=>{await Ei(e,e.getChildren().filter(o=>!!o),t,s)},lt=async(e,t)=>{const o=(await Promise.allSettled(_i(e,t))).filter(r=>r.status==="rejected");o.length&&(m.error(`There were ${o.length} failed dependent models on ${t}`),m.error(o))},qd=e=>typeof e.toJSON=="function",Tt=e=>e[L]!==void 0,Jo=e=>e.revision!==void 0&&e.index!==void 0,Ti=e=>{if(e){if(Tt(e))return e;if(Jo(e))return e.data;if(e instanceof Map||e instanceof w.ObservableMap||e instanceof Set)return Array.from(e.values()).filter(Tt);if(Array.isArray(e))return e.filter(Tt)}};function Wd(e){const t=`KosModel(${e.modelTypeName}:${e.modelId})`;try{Object.defineProperty(e,Symbol.toStringTag,{value:t,configurable:!0})}catch{e.toString=()=>t}try{Object.defineProperty(e.constructor,"name",{value:`KosModel_${e.modelTypeName}`,configurable:!0})}catch{e.constructor.name=`KosModel_${e.modelTypeName}`}const s=["fsm","effectManager","subscriptionManager","onlineLifecycleManager","companionManager","childResolver","_offlineQueue"];for(const o of s)o in e&&Object.defineProperty(e,o,{enumerable:!1});Object.defineProperty(e,"debugState",{enumerable:!1,configurable:!0,get(){var o,r,n;return{id:e.modelId,type:e.modelTypeName,initialized:e.initialized,loaded:e.loaded,status:e.status,onlineStatus:e.onlineStatus,activeStatus:e.activeStatus,companions:(r=(o=e.companionManager)==null?void 0:o.all())==null?void 0:r.map(i=>i.modelTypeName),children:(n=e.getChildren)==null?void 0:n.call(e).map(i=>i.modelId),effects:!!e.effectManager,subs:!!e.subscriptionManager}}}),Zd(e.modelData,e.modelTypeName,e.modelId,e)}function Zd(e,t,s,o){Object.defineProperty(e,Symbol.toStringTag,{value:`KosModelData(${t}:${s})`,configurable:!0});try{Object.defineProperty(e.constructor,"name",{value:`${t}ModelData`,configurable:!0})}catch{e.constructor.name=`${t}ModelData`}Object.defineProperty(e,"debugState",{enumerable:!1,configurable:!0,get(){var c,l,d;const r=((c=o.getChildren)==null?void 0:c.call(o))||[],n=((l=o.companionManager)==null?void 0:l.all())||[],i=o.modelData[L]||{};return{id:s,type:t,companions:{count:n.length,data:n.map(u=>({type:u.modelTypeName,id:u.modelId}))},dependencies:{count:Object.keys(i).length,data:Object.values(i).map(u=>({id:u.id||u.modelType,type:u.modelType,options:u.options,lifecycle:u.lifecycle}))},children:{count:r.length,data:r.map(u=>({id:u.modelId,type:u.modelTypeName}))},data:((d=e.toJSON)==null?void 0:d.call(e))||{},subs:!!o.subscriptionManager}}}),Object.defineProperty(e,"toJSON",{configurable:!0,enumerable:!1,writable:!0,value:()=>{const r={};for(const n of Object.keys(e))if(!(n.startsWith("_")||typeof e[n]=="function"))try{const i=e[n];Tt(i)?r[`[KOS Model] ${n}`]=typeof i.toJSON=="function"?i.toJSON():{id:i.id,type:i.constructor.name}:Jo(i)?r[`[KOS Container] ${n}`]=typeof i.toJSON=="function"?i.toJSON():["Container"]:Array.isArray(i)?r[n]=`[Array(${i.length})]`:typeof i=="object"&&i!==null?r[n]=JSON.parse(JSON.stringify(i)):r[n]=i}catch{r[n]="[unreadable]"}return r}})}class Jd{constructor(t){this.model=t}resolve(){const t=new Set([...this.getResolvedDecoratedChildren(),...this.getAdditionalChildren(),...this.model.companionModels.all()]),s=Array.from(t).map(o=>this.model.modelManager.getModelById(o.id||"")).filter(o=>o&&o.status!==y.FAILED).filter(o=>!!o);return s.forEach(o=>{try{x.setParentContext(o.modelId,this.model.modelId)}catch(r){console.error(`Failed to set parent context for ${o.modelId} under ${this.model.modelId}`,r)}}),s}getResolvedDecoratedChildren(){var s;const t=((s=this.model.modelData)==null?void 0:s[_t])||{};return Object.keys(t).map(o=>Ti(this.model.modelData[o])).filter(o=>!!o).flat()}getAdditionalChildren(){var t,s;return((s=(t=this.model.modelData)==null?void 0:t.getChildren)==null?void 0:s.call(t))||[]}}class Xd{constructor(t){a(this,"companions",new w.ObservableMap);this.hostModel=t}add(t){this.companions.set(t.modelTypeName,t)}clear(){this.companions.clear()}get(t){return this.companions.get(t)}all(){return[...this.companions.values()]}get data(){return this.companions}}class Qd{constructor(t,s,o,r){a(this,"disposers",[]);this.modelTypeName=t,this.modelId=s,this.modelData=o,this.log=r}setup(){var s;const t=((s=this.modelData)==null?void 0:s[Oe])||{};for(const o of Object.keys(t)){const{value:r,dependencies:n,options:i}=t[o],c=r.bind(this.modelData),l=()=>{this.log.info(`Running effect ${o} for ${this.modelTypeName} (${this.modelId})`),w.runInAction(()=>c())},d=n?w.reaction(()=>n(this.modelData),l,{fireImmediately:!!(i!=null&&i.fireImmediately)}):w.autorun(l);this.disposers.push(d)}}disposeAll(){for(const t of this.disposers)try{t()}catch(s){this.log.info(`Failed to dispose effect for ${this.modelId}`,s)}this.disposers=[]}}const eu=m.createLogger({name:"model-active-machine"}),tu=e=>{const t=p.createMachine(y.INACTIVE,{[y.FAILED]:p.state(p.transition(D.GO_ACTIVE,y.ACTIVATING)),[y.INACTIVE]:p.state(p.transition(D.GO_ACTIVE,y.ACTIVATING)),[y.ACTIVATING]:p.invoke(()=>(e.activeStatus=y.ACTIVATING,e.activate()),p.transition("done",y.ACTIVE,p.action(()=>{e.activeStatus=y.ACTIVE})),p.transition("error",y.FAILED,p.action(()=>{e.activeStatus=y.FAILED}))),[y.ACTIVE]:p.state(p.transition(D.GO_INACTIVE,y.DEACTIVATING)),[y.DEACTIVATING]:p.invoke(()=>(e.activeStatus=y.DEACTIVATING,e.deactivate()),p.transition("done",y.INACTIVE,p.action(()=>{e.activeStatus=y.INACTIVE})),p.transition("error",y.FAILED,p.action(()=>{e.activeStatus=y.FAILED})))});return{service:p.interpret(t,o=>eu.debug(o.machine.current)),machine:t}},Jr=m.createLogger({name:"model-online-machine"}),su=e=>{const t=p.createMachine(y.OFFLINE,{[y.ONLINE]:p.state(p.transition(D.GO_OFFLINE,y.OFFLINE,p.action(async()=>{await e.offline(),e.onlineStatus=y.OFFLINE}))),[y.OFFLINE]:p.state(p.transition(D.GO_ONLINE,y.ONLINE,p.action(async()=>{Jr.debug(`Going online with model ${e.modelId}`),await e.online(),e.onlineStatus=y.ONLINE,await e.fsm.transitionTo(D.INITIALIZE,y.INITIALIZED)})))}),s=p.interpret(t,o=>Jr.debug(o.machine.current));return{machine:t,service:s}},ou=e=>{var o;const t=tu(e).service,s=su(e).service;return p.createMachine(y.CREATING,{[y.CREATING]:p.state(p.transition(D.CREATE,y.CREATED)),[y.CREATED]:p.state(p.immediate(y.INITIALIZING)),[y.INITIALIZING]:p.invoke(()=>(z(()=>{e.status=y.INITIALIZING}),e.init()),p.transition("done",y.INITIALIZED,p.action(()=>{e.status=y.INITIALIZED})),p.transition("error",y.FAILED,p.action(()=>{m.error(`Model ${e.modelId} - ${e.modelTypeName} failed to initialize. Transitioning to FAILED state.`),e.status=y.FAILED}))),[y.INITIALIZED]:p.state(p.immediate(y.LOADING)),[y.LOADING]:p.invoke(()=>(z(()=>{e.status=y.LOADING}),e.load()),p.transition("done",y.LOADED,p.action(()=>{e.status=y.LOADED})),p.transition("error",y.FAILED,p.action(()=>{e.status=y.FAILED}))),[y.LOADED]:p.state(p.immediate(y.READYING),p.transition(D.UNLOAD,y.UNLOADING)),[y.RESETTING]:p.invoke(()=>{var r;return z(()=>{e.status=y.RESETTING}),(r=e.unload)==null||r.call(e),e.load()},p.transition("done",y.LOADED,p.action(()=>{e.status=y.LOADED}))),[y.READYING]:p.invoke(()=>(z(()=>{e.status=y.READYING}),e.ready()),p.transition("done",y.READY,p.action(()=>{z(()=>{e.status=y.READY}),s.send(D.GO_ONLINE)})),p.transition("error",y.FAILED,p.action(()=>{e.status=y.FAILED}))),[y.READY]:p.state(p.transition(D.UNLOAD,y.UNLOADED,p.action((o=e.unload)==null?void 0:o.bind(e))),p.transition(D.RESET,y.RESETTING),p.transition(D.GO_ONLINE,y.READY,p.action(()=>{s.send(D.GO_ONLINE)})),p.transition(D.GO_OFFLINE,y.READY,p.action(()=>{s.send(D.GO_OFFLINE)})),p.transition(D.GO_ACTIVE,y.READY,p.action(()=>{t.send(D.GO_ACTIVE)})),p.transition(D.GO_INACTIVE,y.READY,p.action(()=>{t.send(D.GO_INACTIVE)}))),[y.UNLOADED]:p.state(),[y.FAILED]:p.state()})},ru=m.createLogger({name:"kos-model-lifecycle"}),nu=e=>({service:p.interpret(ou(e),s=>ru.debug(`state machine for model ${e.modelId}: ${s.machine.current});`))});class iu{constructor(t,s){a(this,"disposer");a(this,"service");this.model=t,this.log=s;const o=nu(t);this.service=o.service,this.service.send(D.CREATE)}get current(){return this.service.machine.current}async transitionTo(t,s,o=y.FAILED){return this.getTransitionStatusFor(s)===s?(this.log.debug(`Model ${this.model.modelId} already in state ${s}, skipping transition`),Promise.resolve()):(this.log.debug(`Transitioning model ${this.model.modelId} with event ${t} toward target ${s}`),new Promise((n,i)=>{var c;(c=this.disposer)==null||c.call(this),this.disposer=w.when(()=>{const l=this.getTransitionStatusFor(s);return l===s||l===o},()=>{this.getTransitionStatusFor(s)===o?(this.log.error(`Model ${this.model.modelId} entered error state ${o} during transition`),i(new Error(`FSM transition failed for model ${this.model.modelId} with event ${t}`))):(this.log.debug(`Model ${this.model.modelId} reached target state ${s}`),n())}),this.service.send(t)}).finally(()=>{var n;(n=this.disposer)==null||n.call(this),this.disposer=void 0}))}getTransitionStatusFor(t){return[y.ACTIVE,y.INACTIVE].includes(t)?this.model.activeStatus:this.model.status}}class au{static create({modelId:t,modelTypeName:s,component:o}){const r=[o??"kos",s,t].filter(Boolean).join(".");return m.createLogger({name:r})}}class cu{constructor(t){a(this,"queue",[]);this.log=t}enqueue(t){this.queue.push(t)}flush(){if(this.queue.length!==0){this.log.warn(`Processing ${this.queue.length} offline message(s)`);for(const t of this.queue)try{t()}catch(s){this.log.error("Error while processing offline message:",s)}this.queue=[],this.log.info("Offline queue flushed")}}clear(){this.queue=[]}get length(){return this.queue.length}get isEmpty(){return this.queue.length===0}}class lu{constructor(t,s){a(this,"unsubscribers",[]);this.model=t,this.log=s}register(){const t=this.model.modelId,s=U("/kosCore/online",async()=>{this.log.debug(`Online event received for ${t}, waiting for readiness...`),await this.model.whenReady(),this.log.debug(`${t} is ready — sending GO_ONLINE`),await this.model.fsm.transitionTo(D.GO_ONLINE,y.ONLINE)}),o=U("/kosCore/offline",async()=>{this.log.debug(`Offline event received for ${t} — sending GO_OFFLINE`),await this.model.fsm.transitionTo(D.GO_OFFLINE,y.OFFLINE)});this.unsubscribers.push(s.unsubscribe),this.unsubscribers.push(o.unsubscribe)}dispose(){this.unsubscribers.forEach(t=>t()),this.unsubscribers=[]}}var $i=(e=>(e.GET="GET",e.PUT="PUT",e.POST="POST",e.DELETE="DELETE",e))($i||{});const Oi=({path:e,requestId:t,method:s,destinationAddress:o})=>{let r=`${Us}:${s}
|
|
2
|
-
`;return
|
|
3
|
-
`,
|
|
4
|
-
`,
|
|
5
|
-
`,
|
|
6
|
-
`),
|
|
7
|
-
`,r+=`
|
|
8
|
-
`,r},Si=({path:e,requestId:t,method:s,destinationAddress:o,ordered:r,tracker:n})=>{let i=`${Cn}:/http${e}
|
|
9
|
-
`;return i+=`${Us}:${s}
|
|
10
|
-
`,i+=`${Qe}:${e}
|
|
11
|
-
`,i+=`${xn}:${t}
|
|
12
|
-
`,o&&(i+=`${me}:${o}
|
|
13
|
-
`),r&&(i+=`${Bo}:true
|
|
14
|
-
`),n&&(i+=`${Ko}:${n}
|
|
15
|
-
`),i+=`${de}:fos.http.request
|
|
16
|
-
`,i+=`
|
|
17
|
-
`,i},Di=({path:e,requestId:t,method:s,destinationAddress:o,ordered:r,tracker:n,bridge:i,headers:c})=>{let l=`${Us}:${s}
|
|
18
|
-
`;return l+=`${Qe}:${e}
|
|
19
|
-
`,l+=`${Ht}:${t}
|
|
20
|
-
`,o&&(l+=`${me}:${o}
|
|
21
|
-
`),r&&(l+=`${Bo}:true
|
|
22
|
-
`),n&&(l+=`${Ko}:${n}
|
|
23
|
-
`),c&&Object.keys(c).forEach(d=>{l+=`${d}:${c[d]}
|
|
24
|
-
`}),l+=`${de}:${i?"fos":"kos"}.http.request
|
|
25
|
-
`,l+=`
|
|
26
|
-
`,l},we=(e,t)=>{let s=e;return t&&(s+=t),s};function wo(e){const t={...e};return{append(s,o){t[s]=o},delete(s){delete t[s]},get(s){return t[s]},forEach(s){Object.keys(t).forEach(o=>s(t[o],o,this))},has(s){return Object.hasOwn(t,s)},set(s,o){t[s]=o},keys(){return Object.keys(t)},values(){return Object.values(t)},entries(){return Object.entries(t)}}}function Mo(e){let t=!1;return window.ReadableStream?new ReadableStream({start(o){function r(){return Promise.resolve({done:t,value:e}).then(({done:n,value:i})=>{if(n){o.close();return}o.enqueue(i),t=!0,r()})}r()}}):e}const Ai=({path:e,requestId:t,destinationAddress:s})=>{let o=`topic:${e}
|
|
27
|
-
`;return o+=`${Qe}:${e}
|
|
28
|
-
`,o+=`${Ht}:${t}
|
|
29
|
-
`,o+=`${me}:${s}
|
|
30
|
-
`,o+=`${de}:kos.studio.request
|
|
1
|
+
"use strict";var Rd=Object.defineProperty;var Pd=(e,t,s)=>t in e?Rd(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var l=(e,t,s)=>(Pd(e,typeof t!="symbol"?t+"":t,s),s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const S=require("loglevel"),M=require("mobx"),y=require("robot3"),Ie=require("date-fns"),_=require("@emotion/react/jsx-runtime"),Vr=require("@emotion/styled"),jn=require("react-dom"),Re=require("@emotion/react"),f=require("react"),Yr=require("mobx-react-lite"),xd=require("@use-gesture/react"),qs="method",Bn="topic",ot="url",Zt="request-id",Ws="response-id",qr="status",Me="dst-addr",Kn="src-addr",pe="type",Wr="ordered",Zr="tracker",Hn="Content-Type",Gn="Cache-Control",zn="requestId",Vn=process.env.KOS_LOGIN_URL||"http://localhost",Yn=process.env.KOS_APP_PORT||"8080",Ld=`${Vn}:${Yn}`,_s="{MODEL_ID}";var Jt=(e=>(e.SEND="/ws/log/msg/send",e.RECEIVED="/ws/log/msg/receive",e))(Jt||{}),qn=(e=>(e.MSG_RECEIVE="/mock/msg/receive",e))(qn||{});const Jr="/kos/model/ready/";S.info("Initializing event bus");globalThis.kos=globalThis.kos||{};globalThis.kos.subscriptions=globalThis.kos.subscriptions||{};const L=globalThis.kos.subscriptions,Fd=()=>Symbol("eventKey");function Xr(e){return L[e]&&Object.getOwnPropertySymbols(L[e]).length>0}function O(e,t){const s=Fd();return L[e]||(S.debug(`Initializing subscription for ${e}`),L[e]={}),S.debug(`Subscribing to ${e} with id ${s.toString()}`),L[e][s]=t,{count:L[e]?Object.getOwnPropertySymbols(L[e]).length:0,unsubscribe:()=>(S.debug(`Unsubscribing from ${e} with id ${s.toString()}`),L[e]&&L[e][s]&&delete L[e][s],L[e]&&Object.getOwnPropertySymbols(L[e]).length===0&&delete L[e],{count:L[e]?Object.getOwnPropertySymbols(L[e]).length:0})}}function U(e,t,s={}){if(!L[e]||Object.getOwnPropertySymbols(L[e]).length===0)return S.debug(`No subscriptions for ${e}. Not publishing.`),{eventType:e,subscribers:0};const r=Object.getOwnPropertySymbols(L[e]).length;return Object.getOwnPropertySymbols(L[e]).forEach(o=>{if(s.sync){const n=s.sync;S.debug(`Performing sync publish for ${e} with sync id ${n}`),L[e][o]({body:t,headers:s}).then(i=>{S.debug(`Response recieved for ${n}, publishing back to source.`),U(n,i)})}else S.debug(`Performing async publish for ${e}`),L[e][o]({body:t,headers:s})}),{eventType:e,subscribers:r}}function kd(){S.warn("Resetting event bus"),Object.keys(L).forEach(e=>delete L[e])}function Wn(e,t){const s=O(e,r=>{s.unsubscribe(),t(r)});return s.unsubscribe}function Qr(e,t){return new Promise((s,r)=>{let o=null;const n=Wn(e,i=>{o&&clearTimeout(o),s(i)});t&&(o=setTimeout(()=>{n(),r(new Error(`Timeout waiting for event: ${e}`))},t))})}const Nd=Object.freeze(Object.defineProperty({__proto__:null,hasEventSubscriptions:Xr,once:Wn,publish:U,reset:kd,subscribe:O,waitFor:Qr},Symbol.toStringTag,{value:"Module"}));function Zs(e,t){const s=O(e,r=>{s.unsubscribe(),t(r)});return s.unsubscribe}function Js(e,t){return new Promise((s,r)=>{let o=null;const n=Zs(e,i=>{o&&clearTimeout(o),s(i)});t&&(o=setTimeout(()=>{n(),r(new Error(`Timeout waiting for event: ${e}`))},t))})}function Zn(e,t){const s=e.map(r=>Js(r,t));return Promise.all(s)}function Jn(e,t){return new Promise((s,r)=>{const o=[];let n=null,i=!1;const a=()=>{o.forEach(c=>c()),n&&clearTimeout(n)};e.forEach(c=>{const d=Zs(c,u=>{i||(i=!0,a(),s({eventType:c,data:u}))});o.push(d)}),t&&(n=setTimeout(()=>{i||(i=!0,a(),r(new Error(`Timeout waiting for any event: ${e.join(", ")}`)))},t))})}function Xn(e,t,s){return O(e,o=>{o&&t(o)&&s(o)}).unsubscribe}function Qn(e,t,s){return O(e,o=>{if(o){const n=t(o);s(n)}}).unsubscribe}function ei(e,t,s){let r=null;const o=O(e,n=>{r&&clearTimeout(r),r=setTimeout(()=>{s(n)},t)});return()=>{r&&clearTimeout(r),o.unsubscribe()}}function ti(e,t,s){let r=0,o=null;const n=O(e,i=>{const a=Date.now(),c=a-r;c>=t?(r=a,s(i)):o||(o=setTimeout(()=>{r=Date.now(),s(i),o=null},t-c))});return()=>{o&&clearTimeout(o),n.unsubscribe()}}function si(e,t,s){let r=[],o=null;const n=()=>{r.length>0&&(s([...r]),r=[])},i=O(e,a=>{a&&(r.push(a),o||(o=setTimeout(()=>{n(),o=null},t)))});return()=>{o&&(clearTimeout(o),n()),i.unsubscribe()}}function eo(e,t=1){const s=[];return O(e,r=>{r&&(s.push(r),s.length>t&&s.shift())}),{subscribe:r=>(s.forEach(o=>r(o)),O(e,r))}}function ri(e,t){const s=e.map(r=>O(r,o=>{o&&t(r,o)}));return()=>{s.forEach(r=>r.unsubscribe())}}function oi(e,t){let s=e;const r=[],o=new Set;return Object.values(t).forEach(n=>{Object.keys(n).forEach(i=>{o.add(i)})}),o.forEach(n=>{const{unsubscribe:i}=O(n,a=>{const c=t[s];c&&c[n]&&(s=c[n](a))});r.push(i)}),{get state(){return s},unsubscribe:()=>{r.forEach(n=>n())}}}function ni(e,t,s,r){const o=Js(t,r);return U(e,s),o}async function*ii(e){const t=[],s=[],r=O(e,o=>{o&&(s.length>0?s.shift()(o):t.push(o))});try{for(;;)t.length>0?yield t.shift():yield await new Promise(o=>{s.push(o)})}finally{r.unsubscribe()}}const Ud={once:Zs,waitFor:Js,waitForAll:Zn,race:Jn,filter:Xn,map:Qn,debounce:ei,throttle:ti,buffer:si,replay:eo,merge:ri,stateMachine:oi,request:ni,eventIterator:ii},jd=Object.freeze(Object.defineProperty({__proto__:null,EventBusFunctional:Ud,buffer:si,debounce:ei,eventIterator:ii,filter:Xn,map:Qn,merge:ri,once:Zs,race:Jn,replay:eo,request:ni,stateMachine:oi,throttle:ti,waitFor:Js,waitForAll:Zn},Symbol.toStringTag,{value:"Module"}));async function Xs(e,t){const{getCurrentState:s,transformState:r,shouldUseFetchedState:o,timeout:n}=t,i=Qr(e,n),a=await s(),c=r?r(a):a;return o&&o(c)?(i.catch(()=>{}),c):await Promise.race([i,new Promise(u=>{setTimeout(()=>u(c),100)})])}function ai(e,t,s){const{getCurrentState:r,transformState:o}=s;let n=!1;const i=O(e,a=>{a&&(n=!0,t(a))});return Promise.resolve(r()).then(a=>{const c=o?o(a):a;n||t(c)}).catch(a=>{console.error("Failed to fetch initial state:",a)}),i.unsubscribe}function ci(e,t){let s;const r=new Set,o=async()=>{try{typeof t=="string"?s=await(await fetch(t)).json():s=await t(),r.forEach(a=>a(s))}catch(a){throw console.error("Failed to fetch initial state:",a),a}};O(e,a=>{a!=null&&a.body&&(s=a.body,r.forEach(c=>c(s)))});let n=!1;const i=()=>{n||(n=!0,o())};return{get state(){return s},async getState(){return i(),s===void 0&&await new Promise(a=>{const c=()=>{s!==void 0?a():setTimeout(c,10)};c()}),s},subscribe(a){return i(),r.add(a),s!==void 0&&a(s),()=>{r.delete(a)}},async refresh(){return await o(),s}}}async function to(e,t){if(typeof e=="string")return Xs(e,t);const s=e,{getCurrentState:r,shouldUseFetchedState:o,timeout:n}=t,i=await r(),a=t.transformState?t.transformState(i):i;if(o&&o(a))return a;const c=s.map(u=>Qr(u,n)),d=await Promise.all(c);return d[d.length-1]}function li(e,t,s){const{fetchMissedEvents:r,checkInterval:o=3e4,deduplicateById:n}=s,i=new Set,a=O(e,async d=>{if(d){if(n){const u=n(d);if(i.has(u))return;i.add(u),i.size>1e3&&Array.from(i).slice(0,500).forEach(g=>i.delete(g))}await t(d)}}),c=setInterval(async()=>{try{const d=await r(),u=Array.isArray(d)?d:[d];for(const h of u)if(n){const g=n(h);i.has(g)||(i.add(g),await t(h))}else await t(h)}catch(d){console.error("Failed to fetch missed events:",d)}},o);return()=>{a.unsubscribe(),clearInterval(c)}}function di(e){const{connectEvent:t,disconnectEvent:s,errorEvent:r,dataEvent:o,fetchInitialState:n,reconnectDelay:i=5e3}=e,a={state:"disconnected",data:void 0,async waitForConnection(u){if(a.state==="connected"&&a.data)return a.data;const h=await Xs(t,{getCurrentState:n,shouldUseFetchedState:g=>!!g,timeout:u});return a.state="connected",a.data=h,d(),h},subscribe(u){return c.add(u),u(a),()=>{c.delete(u)}},async reconnect(){a.state="connecting",d();try{const u=await n();a.state="connected",a.data=u,d()}catch{a.state="error",d(),setTimeout(()=>{a.state==="error"&&a.reconnect()},i)}}},c=new Set,d=()=>{c.forEach(u=>u(a))};return O(t,u=>{a.state="connected",u!=null&&u.body&&(a.data=u.body),d()}),O(s,()=>{a.state="disconnected",d(),setTimeout(()=>{a.state==="disconnected"&&a.reconnect()},i)}),r&&O(r,()=>{a.state="error",d()}),o&&O(o,u=>{u!=null&&u.body&&a.state==="connected"&&(a.data=u.body,d())}),a.reconnect(),a}const Bd={waitForOrGetState:Xs,subscribeWithInitialState:ai,createStatefulEventStream:ci,waitForAllWithState:to,createResilientEventHandler:li,createConnectionStateManager:di},Kd=Object.freeze(Object.defineProperty({__proto__:null,EventBusState:Bd,createConnectionStateManager:di,createResilientEventHandler:li,createStatefulEventStream:ci,subscribeWithInitialState:ai,waitForAllWithState:to,waitForOrGetState:Xs},Symbol.toStringTag,{value:"Module"})),Hd=(e,t=0)=>{if(!+e)return{value:0,scale:"bytes",toString:()=>"0 bytes"};const s=1024,r=t<0?0:t,o=["bytes","KB","MB","GB","TB"],n=Math.floor(Math.log(e)/Math.log(s)),i=parseFloat((e/Math.pow(s,n)).toFixed(r)),a=o[n];return{value:i,scale:a,toString:()=>`${i} ${a}`}};function so(e){let t="pending",s;const r=e.then(n=>{t="success",s=n},n=>{t="error",s=n});return{read:()=>{switch(t){case"pending":throw r;case"error":throw s;default:return s}}}}function nt(){return"xxxxxxxx-xxxx-4xxx-2xxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){const t=Math.random()*16|0;return(e=="x"?t:t&3|8).toString(16)})}function Gd(e,t){t.forEach(s=>{Object.getOwnPropertyNames(s.prototype).forEach(r=>{const o=Object.getOwnPropertyDescriptor(s.prototype,r);Object.defineProperty(e.prototype,r,o)})})}function zd(e,t){const s=e??[],r=t??[];return s.length!==r.length?!1:s.every((o,n)=>o===r[n])}const ro=(e,t)=>{const s=e.map(n=>n.id);return t.map(n=>n.id).filter(n=>!s.includes(n))},Vd=({container:e,onAddItem:t,onRemoveItem:s,idMapper:r=o=>o})=>o=>{const n=o.map(r),a=ro(n,e.data).map(s).filter(Boolean);e.removeAll(a);const c=n.map(t).filter(Boolean);e.addAll(c)},Yd=({container:e,onAddItem:t,onRemoveItem:s,idMapper:r=o=>o})=>o=>{const n=o.map(r);ro(n,e.models).forEach(s),n.forEach(t)},qd=({items:e,onAddItem:t,onRemoveItem:s,idMapper:r=o=>o})=>o=>{const n=o.map(r);ro(n,e).forEach(s),n.forEach(t)},Wd=(e,t="parent-")=>{let s=e;return s.startsWith(t)&&(s=s.replace(t,"")),s},on=new Intl.RelativeTimeFormat(void 0,{numeric:"auto"}),nn=[{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 ui(e){let t=(e.getTime()-Date.now())/1e3;for(let s=0;s<=nn.length;s++){const r=nn[s];if(Math.abs(t)<r.amount)return on.format(Math.round(t),r.name);t/=r.amount}return on.format(Math.round(t),"years")}const oo=e=>e%4===0&&e%100!==0||e%400===0,no=(e,t)=>[31,oo(e)?29:28,31,30,31,30,31,31,30,31,30,31][t],hi=(e,t)=>{const s=new Date(e),r=e.getDate();return s.setDate(1),s.setMonth(s.getMonth()+t),s.setDate(Math.min(r,no(s.getFullYear(),s.getMonth()))),s},fi=(e,t)=>{const s=new Date(e);return s.setDate(s.getDate()+t),s},We="en-US",gi={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"}},pi={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"}},mi=(e,{dateStyle:t="short",locales:s=We}={dateStyle:"short",locales:We})=>{const r=t==="short"?gi.short:{dateStyle:t};return new Intl.DateTimeFormat(s,r).format(e)},yi=(e,{locales:t=We,timeStyle:s="short"}={locales:We,timeStyle:"short"})=>{const r=pi[s];return new Intl.DateTimeFormat(t,r).format(e)},bi=(e,{dateStyle:t="short",locales:s=We,timeStyle:r="short"}={dateStyle:"short",locales:We,timeStyle:"short"})=>{const o={...t&&gi[t],...r&&pi[r]};return new Intl.DateTimeFormat(s,o).format(e)},Zd=Object.freeze(Object.defineProperty({__proto__:null,addDaysToDate:fi,addMonthsToDate:hi,formatDate:mi,formatDateSince:ui,formatDateTime:bi,formatTime:yi,getDaysInMonth:no,isLeapYear:oo},Symbol.toStringTag,{value:"Module"}));function wi(e,t,s=300){let r;return(...o)=>{clearTimeout(r),r=setTimeout(()=>{t.apply(e,o)},s)}}class vi{constructor(t={}){l(this,"flags",{});this.flags=t}isFeatureEnabled(t){return!!this.flags[t]}enableFeature(t){this.flags[t]=!0}disableFeature(t){this.flags[t]=!1}toggleFeature(t){this.flags[t]=!this.flags[t]}updateFlags(t){this.flags={...this.flags,...t}}}window.KosFeatureFlags=window.KosFeatureFlags??new vi;const Jd=window.KosFeatureFlags,ie=(e=null)=>(e||window.location.search.replace("?","")).split("&").map(t=>{const[s,r]=t.split("=");return[s,decodeURIComponent(r||"")]}).reduce((t,[s,r])=>(t[s]=r,t),{}),Mi=(e,t,s)=>{s/=100;const r=t*Math.min(s,1-s)/100,o=n=>{const i=(n+e/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)}`},Ei=e=>{const s=new RegExp("hsl\\((\\d+),\\s+(\\d+)\\%,\\s+(\\d+)\\%\\)").exec(e);if(!s)throw Error("Invalid HSL string");return Mi(parseInt(s[1]),parseInt(s[2]),parseInt(s[3]))},_i=(e,t)=>getComputedStyle(e).getPropertyValue(t),Xd=(e,t)=>Ei(_i(e,t)),Ii="studio.tools.preview",Qd="studio.relax.store.validation",Ti="studio.log.debug",Oi="studio.log.info",eu={profiles:[Ii]};var Un;const tu=((Un=globalThis.getKosConfig)==null?void 0:Un.call(globalThis))||JSON.stringify(eu),Si=JSON.parse(tu);globalThis.kosConfig=Si;const io=Si,$i=()=>io.profiles||[],Sr=e=>$i().includes(e),su=()=>io.logging||!1,ru=(e,t)=>{const s={...e};return s.id&&delete s.id,s},$r=(e,t,s=ru)=>{const r=s(e,t);M.runInAction(()=>{Object.assign(t,r)})},fr=new Map,Di={addToDeletionQueue:(e,t)=>{const s=fr.get(e)||[];s.push(t),fr.set(e,s)},cancelDeletion:e=>{const t=fr.get(e);t&&t.forEach(s=>{clearTimeout(s)})}},ou=()=>{const e=Sr(Ti),t=Sr(Oi);return e?"DEBUG":t?"INFO":void 0},Ci=()=>{const e=ie(),t=ou(),r=e.kosLogLevel??t??window.kosLogLevel??process.env.KOS_LOG_LEVEL;return r||"WARN"},Ai=()=>window.kosMessageLogging||process.env.KOS_MESSAGE_LOGGING==="true",Ri=()=>window.kosMessageStudioLogging||process.env.KOS_MESSAGE_STUDIO_LOGGING==="true",Pi="ws-log",nu=S.methodFactory,xi=Ai(),iu=Ri();S.methodFactory=function(e,t,s){const r=nu(e,t,s);return function(o,n){var c;const i=s?String(s):"",a=i?`[${String(i).substring(i.lastIndexOf(":")+1)}] | `:"[root] | ";r(`${a}${o}`,n||""),(c=globalThis==null?void 0:globalThis.kosConfig)!=null&&c.logging&&globalThis.kosLog&&(s!==Pi||xi&&iu)&&globalThis.kosLog(`UI: ${a}${o}`)}};let Li=Ci();S.setLevel(Li);window.setKosLogLevel=e=>{Li=e,S.setLevel(e)};const Is=S.getLogger(Pi);window.enableKosMessageLog=()=>{Is.setLevel(S.levels.INFO)};window.disableKosMessageLog=()=>{Is.setLevel(S.levels.ERROR)};xi?window.enableKosMessageLog():window.disableKosMessageLog();const au=["color: black","display: block","background-color: lightgreen","padding: 4px","margin: 0","text-shadow: 0 1px 0 rgba(0, 0, 0, 0.3)","box-shadow: 0 1px 0 rgba(255, 255, 255, 0.4) inset, 0 5px 3px -5px rgba(0, 0, 0, 0.5), 0 -13px 5px -10px rgba(255, 255, 255, 0.4) inset","font-weight: bold"].join(";"),cu=["color: black","display: block","padding: 4px","background-color: yellow","margin: 0","text-shadow: 0 1px 0 rgba(0, 0, 0, 0.3)","box-shadow: 0 1px 0 rgba(255, 255, 255, 0.4) inset, 0 5px 3px -5px rgba(0, 0, 0, 0.5), 0 -13px 5px -10px rgba(255, 255, 255, 0.4) inset","font-weight: bold"].join(";"),is=e=>t=>{S.getLevel()<=e&&t()},p={...S,ifDebug:is(S.levels.DEBUG),ifInfo:is(S.levels.INFO),ifWarn:is(S.levels.WARN),ifError:is(S.levels.ERROR),getLogger:e=>S.getLogger(`kos::${e}`),createLogger:({name:e,group:t})=>S.getLogger(`${t?`${t}:`:"kos"}::${e}`),wsSend:(...e)=>{const t=String(e).replace(/\n/g,"\\n");Is.info(`%c⬆ ${t}`,au)},wsReceive:(...e)=>{const t=String(e).replace(/\n/g,"\\n");Is.info(`%c⬇ ${t}`,cu)}},lu=p.createLogger({name:"kos-dependency-manager"});class du{constructor(){l(this,"_usedByCache",new Map);l(this,"_usesCache",new Map)}add(t,s){Di.cancelDeletion(s);const r=this._usedByCache.get(s)||[];r.includes(t)||r.push(t),this._usedByCache.set(s,r);const o=this._usesCache.get(t)||[];o.includes(s)||o.push(s),this._usesCache.set(t,o)}remove(t,s){const r=this._usedByCache.get(s)||[];this._usedByCache.set(s,r.filter(n=>n!==t));const o=this._usesCache.get(t)||[];this._usesCache.set(t,o.filter(n=>n!==s))}canDestroy(t){const s=this._usedByCache.get(t);return s!=null&&s.length?(lu.info(`Model ${t} is still used by: ${s.join(", ")}`),!1):!0}clear(){this._usedByCache.clear(),this._usesCache.clear()}}var b=(e=>(e.CREATING="creating",e.CREATED="created",e.INITIALIZING="initializing",e.INITIALIZED="initialized",e.LOADING="loading",e.LOADED="loaded",e.ONLINE="online",e.READYING="readying",e.READY="ready",e.READY_FAILED="ready_failed",e.RESETTING="resetting",e.RESET="reset",e.OFFLINE="offline",e.UNLOADING="unloading",e.UNLOADED="unloaded",e.FAILED="failed",e.INACTIVE="inactive",e.ACTIVE="active",e.ACTIVATING="activating",e.DEACTIVATING="deactivating",e))(b||{}),A=(e=>(e.CREATE="create",e.INITIALIZE="init",e.LOAD="load",e.READY="ready",e.GO_ONLINE="go_online",e.GO_OFFLINE="go_offline",e.RESET="go_offline",e.UNLOAD="unload",e.FAILED="failed",e.GO_ACTIVE="go_active",e.GO_INACTIVE="go_inactive",e.TIMEOUT="timeout",e))(A||{});const an=p.createLogger({name:"kos-model-cache"});class uu{constructor(t=[]){l(this,"_modelsById",M.observable.map(new Map));l(this,"_toDelete",new Map);l(this,"_preloaded",[]);l(this,"_isPreloaded",!1);this.preloadKeys=t}get models(){return Array.from(this._modelsById.values()).filter(t=>!this._toDelete.has(t.modelId))}getModelById(t){if(t&&!this._toDelete.has(t))return this._modelsById.get(t)}addModel(t){const s=this.getModelById(t.modelId)||t;return this._modelsById.set(s.modelId,s),s}removeModel(t){this._modelsById.delete(t),this._toDelete.delete(t)}hasModel(t){return!!t&&this._modelsById.has(t)&&!this._toDelete.has(t)}restoreFromDeleteCache(t){if(t&&this._toDelete.has(t)){const s=this._toDelete.get(t);this._toDelete.delete(t),this._modelsById.set(t,s)}}markForDeletion(t){this._modelsById.delete(t.modelId),this._toDelete.set(t.modelId,t)}preload(t){return this._isPreloaded?(an.debug("Returning cached preloaded models"),this._preloaded):(this._preloaded=this.preloadKeys.map(s=>(an.debug(`Preloading model: ${typeof s=="string"?s:s.modelType}`),t(s))).filter(s=>!!s),this._isPreloaded=!0,this._preloaded)}}const ue="canvas-renderer",gr=new Map,cn=new Map,pr=new Map,mr=new Map,Qs=(e,t)=>{Fi[e]=t},Fi={indexExtension:{registerIndexExtension:(e,t)=>{const s=mr.get(e)||{};Object.assign(s,t),mr.set(e,t)},loadIndexExtensions:e=>mr.get(e)||{}},loader:{registerLoader:(e,t)=>{cn.set(e,t)},executeLoader:async(e,t)=>{const s=cn.get(e);if(s)return await s(t)}},propertyMapper:{registerPropertyMapper:(e,t)=>{pr.set(e,t)},hasMapper:e=>pr.has(e),executeMapper:(e,t,s)=>{const r=pr.get(e);return r?r(t,s):""}},dataMapper:{registerDataMapper:(e,t)=>{const s=gr.get(e)||[];s.push(t),gr.set(e,s)},executeMapper:async(e,t,s)=>{const r=gr.get(e);if(!r)return{};const o={};for(const n of r){const i=await n(t,s);Object.assign(o,i)}return o}},canvas:{registerRenderer:(e,t)=>{if(!$[ue]){console.warn(`Canvas renderer extension point is not registered. Cannot register renderer "${e}".`);return}$[ue].register(e,t)}}},$=Fi;function ki(e,t){return`${Jr}${e}${t?`/${t}`:`/${e}`}`}function Ni(e){return`${Jr}${e}`}var B=(e=>(e.INIT="init",e.LOAD="load",e.READY="ready",e.ACTIVATE="activate",e.ONLINE="online",e))(B||{});const hu=Object.freeze(Object.defineProperty({__proto__:null,DependencyLifecycle:B},Symbol.toStringTag,{value:"Module"}));function ln(e){const t=[];return new Promise((s,r)=>{for(const{condition:o,onMatch:n}of e){const i=M.when(o,()=>{t.forEach(a=>a());try{n==null||n(),s()}catch(a){r(a)}});t.push(i)}})}const W=Symbol("SubscriptionHandlers"),F=Symbol("DependencyModels"),$t=Symbol("FutureService"),Dt=Symbol("ChildModels"),Ct=Symbol("ParentModel"),At=Symbol("LogConfig"),ys=Symbol("ReferenceConfig"),Ui=Symbol("KosModelSymbol"),xe=Symbol("ModelEffects"),fe=(e,t)=>{e[Dt]=e[Dt]||{},e[Dt][t]=!0},ke=e=>`{PROP_${String(e)}}`,fu=e=>`{PROP_${String(e)}}`,gu=ke("kosParentId"),er=e=>t=>{t[Ct]=t[Ct]||{};const s=(e==null?void 0:e.parentId)||gu;t[Ct]={parentId:s}},Ze=({value:e,modelId:t,modelData:s})=>{let r=e;if(Array.isArray(r))return[...e];if(typeof r!="string"&&typeof r!="object")return r;if(typeof r=="object")r=Object.keys(r).reduce((o,n)=>(o[n]=Ze({value:r[n],modelId:t,modelData:s}),o),{});else if(typeof r=="string"){const o=new RegExp(".*({PROP_(.+)})");let n=r!=null&&r.includes(_s)?r.replace(_s,t):r;const i=n.match(o);if(i&&s&&(Object.getOwnPropertyNames(s).includes(i[2])||Object.getOwnPropertyNames(Object.getPrototypeOf(s)).includes(i[2]))){const a=s[i[2]];n=a?n.replace(i[1],a):void 0}return n}else return r;return r},pu=p.createLogger({name:"kos-model"});function mu(e,t,s){var n;const r=(n=e[Ct])==null?void 0:n.parentId;if(!r)return;const o=Ze({value:r,modelData:s,modelId:t});o&&typeof o=="string"&&N.setParentContext(t,o)}function yu(e){const t=e[$t];t&&Object.entries(t).forEach(([s,{handler:r}])=>{e[s]=r})}function bu(e,t){const s=e[F]||{};Object.entries(s).forEach(([r,o])=>{const n=Ze({value:o.id||o.modelType,modelData:e,modelId:t}),i=Object.entries((o==null?void 0:o.options)||{}).reduce((a,[c,d])=>(a[c]=Ze({value:d,modelData:e,modelId:t}),a),{});if(typeof n=="string"){if(!o.lazy){const a=I.getInstance().modelManager.createModelInstance(o.modelType,n,i);e[r]=a.data}I.getInstance().modelManager.addDependency(t,n)}})}function wu(e){try{return M.makeAutoObservable(e)}catch(t){return pu.error("Failed to make observable:",t),e}}const vu={construct(e,t){var a;const[s,r={}]=t,o=N.createContext(s);mu(e,s,r);const n=p.createLogger({name:e.prototype.modelTypeId,group:((a=e[At])==null?void 0:a.group)??"kos-model"}),i=new e(s,r,{logger:n,kosContext:o});return yu(i),bu(i,s),wu(i)}};function C(e){return t=>{var r,o;const s=t;return s.prototype.modelTypeId=e,s.prototype[Ui]=!0,(r=s.prototype)[W]??(r[W]={}),(o=s.prototype)[F]??(o[F]={}),p.ifDebug(()=>{p.debug(`Registering model with id ${e}`)}),new Proxy(s,vu)}}const Mu=({modelType:e})=>t=>{er()(t),C(e)(t)};function Eu(e,t,s){const r=s.value;s.value=function(...o){const n=N.getContext(this.id);return o.push(n),r.apply(this,o)}}const _u=({group:e}={group:""})=>t=>{t[At]=t[At]||{},t[At]={group:e}};function ji(e){return(t,s,r)=>{t[xe]=t[xe]||{},t[xe][s]={dependencies:e==null?void 0:e.dependencies,value:r.value},r.value=function(){throw new Error(`Method ${s} cannot be called directly.`)}}}const Iu=e=>(t,s)=>{t[ys]=t[ys]||{},t[ys][s]=e},Ne=({modelType:e,id:t,options:s,lifecycle:r})=>(o,n)=>{o[F]=o[F]||{},o[F][n]={modelType:e,id:t,options:s,lifecycle:r||B.INIT}},Tu=({topic:e,handler:t,websocket:s=!1,condition:r=()=>!0})=>o=>{o[W]=o[W]||{},Array.isArray(e)?e.forEach(n=>{o[W][n]={websocket:s,handler:t,condition:r}}):o[W][e]={websocket:s,handler:wi(o,M.action(t),200),condition:r}};function x({topic:e,condition:t=(w,E)=>!0,transform:s=w=>w,websocket:r=!1,fos:o=!1,bridge:n=!1,skipParse:i=!1,lifecycle:a,destinationAddress:c,debounce:d,throttle:u,buffer:h,filter:g,once:m,replay:v}){return(w,E,T)=>{w[W]=w[W]||{};let H=T.value;d&&d>0?H=Ou(H,d):u&&u>0?H=Su(H,u):h?H=$u(H,h):m&&(H=Du(H));let ce=t;if(g){const G=t;ce=(k,Y,_e)=>g(_e)?G(k,Y,_e):!1}const R={websocket:r,fos:o,bridge:n,handler:H,condition:ce,transform:s,lifecycle:a,skipParse:i,destinationAddress:c};Array.isArray(e)?e.forEach(G=>{w[W][G]=R}):w[W][e]=R,v&&Cu(e,v.bufferSize)}}function Ou(e,t){let s=null;return function(r){s&&clearTimeout(s),s=setTimeout(()=>{e.call(this,r)},t)}}function Su(e,t){let s=0,r=null;return function(o){const n=Date.now(),i=n-s;i>=t?(s=n,e.call(this,o)):r||(r=setTimeout(()=>{s=Date.now(),e.call(this,o),r=null},t-i))}}function $u(e,t){const s=[];let r=null;const o=t.maxSize||1e3,n=i=>{s.length>0&&(e.call(i,[...s]),s.length=0)};return function(i){if(s.push(i),s.length>=o){r&&(clearTimeout(r),r=null),n(this);return}r||(r=setTimeout(()=>{n(this),r=null},t.time))}}function Du(e){let t=!1;return function(s){t||(t=!0,e.call(this,s))}}function Cu(e,t){(Array.isArray(e)?e:[e]).forEach(r=>{eo(r,t)})}const Bi=5e3;class Au extends Error{constructor(s,r){super(s);l(this,"model");this.model=r}}const Ki=(e,t,s)=>{let r;return{promise:new Promise((i,a)=>{r=setTimeout(()=>{p.error(`Model ${t.modelId} - ${t.modelTypeName} - ${s} timed out after ${e}ms`),a(new Au(`${t.modelId} - ${t.modelTypeName} - ${s}`,t))},e)}),cancel:()=>{r&&clearTimeout(r)}}},Hi=e=>e.fsm.transitionTo(A.GO_ACTIVE,b.ACTIVE),Gi=e=>e.whenReady(),zi=e=>e.fsm.transitionTo(A.LOAD,b.LOADED),Ru=e=>e.fsm.transitionTo(A.UNLOAD,b.UNLOADED),Vi=e=>e.fsm.transitionTo(A.INITIALIZE,b.INITIALIZED);var ao=(e=>(e.ACTIVE="active",e.READY="ready",e.LOAD="load",e.UNLOAD="unload",e.INIT="init",e))(ao||{});const bs={active:Hi,ready:Gi,load:zi,init:Vi},Yi=(e,t)=>{const s=t.id||t.modelType,r=Ze({value:s,modelData:e.modelData,modelId:e.modelId});p.debug(`activating dependent model ${t.modelType} with id ${r}`);const o=Object.keys((t==null?void 0:t.options)||{}).reduce((i,a)=>{const c=t.options[a];return i[a]=Ze({value:c,modelData:e.modelData,modelId:e.modelId}),i},{});return{dependentModel:I.getInstance().modelManager.createModelInstance(t.modelType,r,o),dataModelId:r}},qi=(e,t=B.READY)=>{var o;const s=((o=e.modelData)==null?void 0:o[F])||{};return Object.keys(s).length===0?(p.debug(`${e.modelId} has no dependencies. Returning`),[]):Object.keys(s).filter(n=>s[n].lifecycle===t).map(n=>{const i=s[n],{dependentModel:a,dataModelId:c}=Yi(e,i);e.modelData[n]=a.data,p.debug(`waiting for dependent model ${i.modelType} with id ${c} - waiting for WHENREADY`);const d=async(g,m,v)=>{var w;await((w=g.whenReady)==null?void 0:w.call(g)),p.debug(`dependent model ${m} with id ${v} - READY`)},{promise:u,cancel:h}=Ki(Bi,e,e.status);return Promise.race([d(a.model,i.modelType,c).then(()=>{h()}).catch(g=>{console.error(`Error waiting for dependent model ${i.modelType} with id ${c}:`,g),h()}),u])}).filter(n=>!!n)},Wi=async(e,t,s,r)=>{if(p.debug(`Execute lifecycle with ${t.length} models`),t.length===0){p.debug(`${e.modelId} has no children. Returning`);return}if(!s){p.error(`${e.modelId} is not transitioning with a valid target ${s}`);return}const o=t.map(a=>{let c;return bs[s]&&a?c=bs[s](a):(a||p.error("model is undefined. This shouldn't happen"),bs[s]||p.error(`There is no promise in the Transition Map for ${s}`)),{promise:c,modelId:a==null?void 0:a.modelId,model:a,type:a==null?void 0:a.modelTypeName,status:a==null?void 0:a.status}}).filter(a=>a.promise?a.model?!0:(p.error(`No model found ${a.modelId}`),!1):(p.error(`No promise found ${a.modelId}`),!1)),i=(await Promise.allSettled(o.map(a=>{var u;const{promise:c,cancel:d}=Ki(Bi,a.model,a.status);return Promise.race([(u=a.promise)==null?void 0:u.then(()=>{d()}).catch(h=>{p.error(`Model ${a.modelId} - ${a.type} failed to transition to ${s}: ${h.message}`),d()}),c])}))).filter(a=>a.status==="rejected");i.length>0&&p.error(`Model ${e.modelId} had ${i.length} failed child models on ${r}`)},Zi=async(e,t,s)=>{await Wi(e,e.getChildren().filter(r=>!!r),t,s)},gt=async(e,t)=>{const r=(await Promise.allSettled(qi(e,t))).filter(o=>o.status==="rejected");r.length&&(p.error(`There were ${r.length} failed dependent models on ${t}`),p.error(r))},Pu=e=>typeof e.toJSON=="function",Rt=e=>e[F]!==void 0,co=e=>e.revision!==void 0&&e.index!==void 0,Ji=e=>{if(e){if(Rt(e))return e;if(co(e))return e.data;if(e instanceof Map||e instanceof M.ObservableMap||e instanceof Set)return Array.from(e.values()).filter(Rt);if(Array.isArray(e))return e.filter(Rt)}};function xu(e){const t=`KosModel(${e.modelTypeName}:${e.modelId})`;try{Object.defineProperty(e,Symbol.toStringTag,{value:t,configurable:!0})}catch{e.toString=()=>t}try{Object.defineProperty(e.constructor,"name",{value:`KosModel_${e.modelTypeName}`,configurable:!0})}catch{e.constructor.name=`KosModel_${e.modelTypeName}`}const s=["fsm","effectManager","subscriptionManager","onlineLifecycleManager","companionManager","childResolver","_offlineQueue"];for(const r of s)r in e&&Object.defineProperty(e,r,{enumerable:!1});Object.defineProperty(e,"debugState",{enumerable:!1,configurable:!0,get(){var r,o,n;return{id:e.modelId,type:e.modelTypeName,initialized:e.initialized,loaded:e.loaded,status:e.status,onlineStatus:e.onlineStatus,activeStatus:e.activeStatus,companions:(o=(r=e.companionManager)==null?void 0:r.all())==null?void 0:o.map(i=>i.modelTypeName),children:(n=e.getChildren)==null?void 0:n.call(e).map(i=>i.modelId),effects:!!e.effectManager,subs:!!e.subscriptionManager}}}),Lu(e.modelData,e.modelTypeName,e.modelId,e)}function Lu(e,t,s,r){Object.defineProperty(e,Symbol.toStringTag,{value:`KosModelData(${t}:${s})`,configurable:!0});try{Object.defineProperty(e.constructor,"name",{value:`${t}ModelData`,configurable:!0})}catch{e.constructor.name=`${t}ModelData`}Object.defineProperty(e,"debugState",{enumerable:!1,configurable:!0,get(){var a,c,d;const o=((a=r.getChildren)==null?void 0:a.call(r))||[],n=((c=r.companionManager)==null?void 0:c.all())||[],i=r.modelData[F]||{};return{id:s,type:t,companions:{count:n.length,data:n.map(u=>({type:u.modelTypeName,id:u.modelId}))},dependencies:{count:Object.keys(i).length,data:Object.values(i).map(u=>({id:u.id||u.modelType,type:u.modelType,options:u.options,lifecycle:u.lifecycle}))},children:{count:o.length,data:o.map(u=>({id:u.modelId,type:u.modelTypeName}))},data:((d=e.toJSON)==null?void 0:d.call(e))||{},subs:!!r.subscriptionManager}}}),Object.defineProperty(e,"toJSON",{configurable:!0,enumerable:!1,writable:!0,value:()=>{const o={};for(const n of Object.keys(e))if(!(n.startsWith("_")||typeof e[n]=="function"))try{const i=e[n];Rt(i)?o[`[KOS Model] ${n}`]=typeof i.toJSON=="function"?i.toJSON():{id:i.id,type:i.constructor.name}:co(i)?o[`[KOS Container] ${n}`]=typeof i.toJSON=="function"?i.toJSON():["Container"]:Array.isArray(i)?o[n]=`[Array(${i.length})]`:typeof i=="object"&&i!==null?o[n]=JSON.parse(JSON.stringify(i)):o[n]=i}catch{o[n]="[unreadable]"}return o}})}class Fu{constructor(t){this.model=t}resolve(){const t=new Set([...this.getResolvedDecoratedChildren(),...this.getAdditionalChildren(),...this.model.companionModels.all()]),s=Array.from(t).map(r=>this.model.modelManager.getModelById(r.id||"")).filter(r=>r&&r.status!==b.FAILED).filter(r=>!!r);return s.forEach(r=>{try{N.setParentContext(r.modelId,this.model.modelId)}catch(o){console.error(`Failed to set parent context for ${r.modelId} under ${this.model.modelId}`,o)}}),s}getResolvedDecoratedChildren(){var s;const t=((s=this.model.modelData)==null?void 0:s[Dt])||{};return Object.keys(t).map(r=>Ji(this.model.modelData[r])).filter(r=>!!r).flat()}getAdditionalChildren(){var t,s;return((s=(t=this.model.modelData)==null?void 0:t.getChildren)==null?void 0:s.call(t))||[]}}class ku{constructor(t){l(this,"companions",new M.ObservableMap);this.hostModel=t}add(t){this.companions.set(t.modelTypeName,t)}clear(){this.companions.clear()}get(t){return this.companions.get(t)}all(){return[...this.companions.values()]}get data(){return this.companions}}class Nu{constructor(t,s,r,o){l(this,"disposers",[]);this.modelTypeName=t,this.modelId=s,this.modelData=r,this.log=o}setup(){var s;const t=((s=this.modelData)==null?void 0:s[xe])||{};for(const r of Object.keys(t)){const{value:o,dependencies:n,options:i}=t[r],a=o.bind(this.modelData),c=()=>{this.log.info(`Running effect ${r} for ${this.modelTypeName} (${this.modelId})`),M.runInAction(()=>a())},d=n?M.reaction(()=>n(this.modelData),c,{fireImmediately:!!(i!=null&&i.fireImmediately)}):M.autorun(c);this.disposers.push(d)}}disposeAll(){for(const t of this.disposers)try{t()}catch(s){this.log.info(`Failed to dispose effect for ${this.modelId}`,s)}this.disposers=[]}}const Uu=p.createLogger({name:"model-active-machine"}),ju=e=>{const t=y.createMachine(b.INACTIVE,{[b.FAILED]:y.state(y.transition(A.GO_ACTIVE,b.ACTIVATING)),[b.INACTIVE]:y.state(y.transition(A.GO_ACTIVE,b.ACTIVATING)),[b.ACTIVATING]:y.invoke(()=>(e.activeStatus=b.ACTIVATING,e.activate()),y.transition("done",b.ACTIVE,y.action(()=>{e.activeStatus=b.ACTIVE})),y.transition("error",b.FAILED,y.action(()=>{e.activeStatus=b.FAILED}))),[b.ACTIVE]:y.state(y.transition(A.GO_INACTIVE,b.DEACTIVATING)),[b.DEACTIVATING]:y.invoke(()=>(e.activeStatus=b.DEACTIVATING,e.deactivate()),y.transition("done",b.INACTIVE,y.action(()=>{e.activeStatus=b.INACTIVE})),y.transition("error",b.FAILED,y.action(()=>{e.activeStatus=b.FAILED})))});return{service:y.interpret(t,r=>Uu.debug(r.machine.current)),machine:t}},dn=p.createLogger({name:"model-online-machine"}),Bu=e=>{const t=y.createMachine(b.OFFLINE,{[b.ONLINE]:y.state(y.transition(A.GO_OFFLINE,b.OFFLINE,y.action(async()=>{await e.offline(),e.onlineStatus=b.OFFLINE}))),[b.OFFLINE]:y.state(y.transition(A.GO_ONLINE,b.ONLINE,y.action(async()=>{dn.debug(`Going online with model ${e.modelId}`),await e.online(),e.onlineStatus=b.ONLINE,await e.fsm.transitionTo(A.INITIALIZE,b.INITIALIZED)})))}),s=y.interpret(t,r=>dn.debug(r.machine.current));return{machine:t,service:s}},Ku=e=>{var r;const t=ju(e).service,s=Bu(e).service;return y.createMachine(b.CREATING,{[b.CREATING]:y.state(y.transition(A.CREATE,b.CREATED)),[b.CREATED]:y.state(y.immediate(b.INITIALIZING)),[b.INITIALIZING]:y.invoke(()=>(Q(()=>{e.status=b.INITIALIZING}),e.init()),y.transition("done",b.INITIALIZED,y.action(()=>{e.status=b.INITIALIZED})),y.transition("error",b.FAILED,y.action(()=>{p.error(`Model ${e.modelId} - ${e.modelTypeName} failed to initialize. Transitioning to FAILED state.`),e.status=b.FAILED}))),[b.INITIALIZED]:y.state(y.immediate(b.LOADING)),[b.LOADING]:y.invoke(()=>(Q(()=>{e.status=b.LOADING}),e.load()),y.transition("done",b.LOADED,y.action(()=>{e.status=b.LOADED})),y.transition("error",b.FAILED,y.action(()=>{e.status=b.FAILED}))),[b.LOADED]:y.state(y.immediate(b.READYING),y.transition(A.UNLOAD,b.UNLOADING)),[b.RESETTING]:y.invoke(()=>{var o;return Q(()=>{e.status=b.RESETTING}),(o=e.unload)==null||o.call(e),e.load()},y.transition("done",b.LOADED,y.action(()=>{e.status=b.LOADED}))),[b.READYING]:y.invoke(()=>(Q(()=>{e.status=b.READYING}),e.ready()),y.transition("done",b.READY,y.action(()=>{Q(()=>{e.status=b.READY}),s.send(A.GO_ONLINE)})),y.transition("error",b.FAILED,y.action(()=>{e.status=b.FAILED}))),[b.READY]:y.state(y.transition(A.UNLOAD,b.UNLOADED,y.action((r=e.unload)==null?void 0:r.bind(e))),y.transition(A.RESET,b.RESETTING),y.transition(A.GO_ONLINE,b.READY,y.action(()=>{s.send(A.GO_ONLINE)})),y.transition(A.GO_OFFLINE,b.READY,y.action(()=>{s.send(A.GO_OFFLINE)})),y.transition(A.GO_ACTIVE,b.READY,y.action(()=>{t.send(A.GO_ACTIVE)})),y.transition(A.GO_INACTIVE,b.READY,y.action(()=>{t.send(A.GO_INACTIVE)}))),[b.UNLOADED]:y.state(),[b.FAILED]:y.state()})},Hu=p.createLogger({name:"kos-model-lifecycle"}),Gu=e=>({service:y.interpret(Ku(e),s=>Hu.debug(`state machine for model ${e.modelId}: ${s.machine.current});`))});class zu{constructor(t,s){l(this,"disposer");l(this,"service");this.model=t,this.log=s;const r=Gu(t);this.service=r.service,this.service.send(A.CREATE)}get current(){return this.service.machine.current}async transitionTo(t,s,r=b.FAILED){return this.getTransitionStatusFor(s)===s?(this.log.debug(`Model ${this.model.modelId} already in state ${s}, skipping transition`),Promise.resolve()):(this.log.debug(`Transitioning model ${this.model.modelId} with event ${t} toward target ${s}`),new Promise((n,i)=>{var a;(a=this.disposer)==null||a.call(this),this.disposer=M.when(()=>{const c=this.getTransitionStatusFor(s);return c===s||c===r},()=>{this.getTransitionStatusFor(s)===r?(this.log.error(`Model ${this.model.modelId} entered error state ${r} during transition`),i(new Error(`FSM transition failed for model ${this.model.modelId} with event ${t}`))):(this.log.debug(`Model ${this.model.modelId} reached target state ${s}`),n())}),this.service.send(t)}).finally(()=>{var n;(n=this.disposer)==null||n.call(this),this.disposer=void 0}))}getTransitionStatusFor(t){return[b.ACTIVE,b.INACTIVE].includes(t)?this.model.activeStatus:this.model.status}}class Vu{static create({modelId:t,modelTypeName:s,component:r}){const o=[r??"kos",s,t].filter(Boolean).join(".");return p.createLogger({name:o})}}class Yu{constructor(t){l(this,"queue",[]);this.log=t}enqueue(t){this.queue.push(t)}flush(){if(this.queue.length!==0){this.log.warn(`Processing ${this.queue.length} offline message(s)`);for(const t of this.queue)try{t()}catch(s){this.log.error("Error while processing offline message:",s)}this.queue=[],this.log.info("Offline queue flushed")}}clear(){this.queue=[]}get length(){return this.queue.length}get isEmpty(){return this.queue.length===0}}class qu{constructor(t,s){l(this,"unsubscribers",[]);this.model=t,this.log=s}register(){const t=this.model.modelId,s=O("/kosCore/online",async()=>{this.log.debug(`Online event received for ${t}, waiting for readiness...`),await this.model.whenReady(),this.log.debug(`${t} is ready — sending GO_ONLINE`),await this.model.fsm.transitionTo(A.GO_ONLINE,b.ONLINE)}),r=O("/kosCore/offline",async()=>{this.log.debug(`Offline event received for ${t} — sending GO_OFFLINE`),await this.model.fsm.transitionTo(A.GO_OFFLINE,b.OFFLINE)});this.unsubscribers.push(s.unsubscribe),this.unsubscribers.push(r.unsubscribe)}dispose(){this.unsubscribers.forEach(t=>t()),this.unsubscribers=[]}}var Xi=(e=>(e.GET="GET",e.PUT="PUT",e.POST="POST",e.DELETE="DELETE",e))(Xi||{});const Qi=({path:e,requestId:t,method:s,destinationAddress:r})=>{let o=`${qs}:${s}
|
|
2
|
+
`;return o+=`topic:${e}
|
|
3
|
+
`,o+=`${ot}:${e}
|
|
4
|
+
`,o+=`${Zt}:${t}
|
|
5
|
+
`,r&&(o+=`${Me}:${r}
|
|
6
|
+
`),o+=`${pe}:kos.studio.request
|
|
31
7
|
`,o+=`
|
|
32
|
-
`,o},
|
|
33
|
-
`;return
|
|
34
|
-
`,
|
|
35
|
-
`,
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
`,r
|
|
42
|
-
|
|
8
|
+
`,o},ea=({path:e,requestId:t,method:s,destinationAddress:r,ordered:o,tracker:n})=>{let i=`${Bn}:/http${e}
|
|
9
|
+
`;return i+=`${qs}:${s}
|
|
10
|
+
`,i+=`${ot}:${e}
|
|
11
|
+
`,i+=`${zn}:${t}
|
|
12
|
+
`,r&&(i+=`${Me}:${r}
|
|
13
|
+
`),o&&(i+=`${Wr}:true
|
|
14
|
+
`),n&&(i+=`${Zr}:${n}
|
|
15
|
+
`),i+=`${pe}:fos.http.request
|
|
16
|
+
`,i+=`
|
|
17
|
+
`,i},ta=({path:e,requestId:t,method:s,destinationAddress:r,ordered:o,tracker:n,bridge:i,headers:a})=>{let c=`${qs}:${s}
|
|
18
|
+
`;return c+=`${ot}:${e}
|
|
19
|
+
`,c+=`${Zt}:${t}
|
|
20
|
+
`,r&&(c+=`${Me}:${r}
|
|
21
|
+
`),o&&(c+=`${Wr}:true
|
|
22
|
+
`),n&&(c+=`${Zr}:${n}
|
|
23
|
+
`),a&&Object.keys(a).forEach(d=>{c+=`${d}:${a[d]}
|
|
24
|
+
`}),c+=`${pe}:${i?"fos":"kos"}.http.request
|
|
25
|
+
`,c+=`
|
|
26
|
+
`,c},$e=(e,t)=>{let s=e;return t&&(s+=t),s};function pt(e){const t={...e};return{append(s,r){t[s]=r},delete(s){delete t[s]},get(s){return t[s]},forEach(s){Object.keys(t).forEach(r=>s(t[r],r,this))},has(s){return Object.hasOwn(t,s)},set(s,r){t[s]=r},keys(){return Object.keys(t)},values(){return Object.values(t)},entries(){return Object.entries(t)}}}function mt(e){let t=!1;return window.ReadableStream?new ReadableStream({start(r){function o(){return Promise.resolve({done:t,value:e}).then(({done:n,value:i})=>{if(n){r.close();return}r.enqueue(i),t=!0,o()})}o()}}):e}const sa=({path:e,requestId:t,destinationAddress:s})=>{let r=`topic:${e}
|
|
27
|
+
`;return r+=`${ot}:${e}
|
|
28
|
+
`,r+=`${Zt}:${t}
|
|
29
|
+
`,r+=`${Me}:${s}
|
|
30
|
+
`,r+=`${pe}:kos.studio.request
|
|
43
31
|
`,r+=`
|
|
44
|
-
`,r},
|
|
45
|
-
`;return
|
|
32
|
+
`,r},ra=({requestId:e,destinationAddress:t,requestType:s,headers:r})=>{let o=`${Zt}:${e}
|
|
33
|
+
`;return o+=`${Me}:${t}
|
|
34
|
+
`,o+=`${pe}:${s}
|
|
35
|
+
`,r&&Object.keys(r).forEach(n=>{o+=`${n}:${r[n]}
|
|
36
|
+
`}),o+=`
|
|
37
|
+
`,o},Wu=(e,t)=>{const s=e,r=$e(ra(t),typeof s=="string"?s:JSON.stringify(s)),o=I.getInstance().transport.socket;o?(p.debug("Sending message",r),o.socket.send(r)):p.error("socket transport is not initialized")},oa=({path:e,responseId:t,status:s,destinationAddress:r})=>{let o=`topic:${e}
|
|
38
|
+
`;return o+=`${ot}:${e}
|
|
39
|
+
`,t&&(o+=`${Ws}:${t}
|
|
40
|
+
`),o+=`${qr}:${s}
|
|
41
|
+
`,o+=`${Me}:${r}
|
|
42
|
+
`,o+=`${pe}:kos.studio.response
|
|
43
|
+
`,o+=`
|
|
44
|
+
`,o},Zu=(e,t)=>{const s=e,r=$e(sa(t),JSON.stringify(s)),o=I.getInstance().transport.socket;o?o.socket.send(r):p.error("socket transport is not initialized")},Ju=(e,t)=>{const s=t.responseId?{status:t.status,data:e}:e,r=$e(oa(t),JSON.stringify(s)),o=I.getInstance().transport.socket;o?o.socket.send(r):p.error("socket transport is not initialized")},na=({topic:e})=>{let t=`topic:${e}
|
|
45
|
+
`;return t+=`${pe}:kos.broker.send
|
|
46
46
|
`,t+=`
|
|
47
|
-
`,t},
|
|
48
|
-
`;return n+=`${
|
|
49
|
-
`,n+=`${
|
|
50
|
-
`,n+=`${
|
|
51
|
-
`,n+=`${
|
|
52
|
-
`,n+=`${
|
|
53
|
-
`,n+=`${
|
|
47
|
+
`,t},ia=({responseId:e,destinationAddress:t,type:s,sourceAddress:r,status:o})=>{let n=`${Ws}:${e}
|
|
48
|
+
`;return n+=`${Me}:${t}
|
|
49
|
+
`,n+=`${Kn}:${r}
|
|
50
|
+
`,n+=`${pe}:${s??"kos.message.request"}
|
|
51
|
+
`,n+=`${qr}:${o}
|
|
52
|
+
`,n+=`${Hn}:application/json
|
|
53
|
+
`,n+=`${Gn}:no-cache
|
|
54
54
|
`,n+=`
|
|
55
|
-
`,n},
|
|
56
|
-
`;return t&&(
|
|
57
|
-
`),
|
|
58
|
-
`,
|
|
59
|
-
`,
|
|
60
|
-
`,
|
|
55
|
+
`,n},aa=({topic:e,responseId:t,destinationAddress:s,type:r})=>{let o=`topic:${e}
|
|
56
|
+
`;return t&&(o+=`${Ws}:${t}
|
|
57
|
+
`),o+=`${Me}:${s}
|
|
58
|
+
`,o+=`${pe}:${r??"kos.message.request"}
|
|
59
|
+
`,o+=`
|
|
60
|
+
`,o},Xu=({msg:e,options:t})=>{const s=e,r=$e(na(t),JSON.stringify(s)),o=I.getInstance().transport.socket;o?o.socket.send(r):p.error("socket transport is not initialized")},ca=({msg:e,options:t})=>{const s=e,r=$e(aa(t),JSON.stringify(s)),o=I.getInstance().transport.socket;o?o.socket.send(r):p.error("socket transport is not initialized")},la=({msg:e,options:t})=>{const s=e,r=$e(ia(t),JSON.stringify(s)),o=I.getInstance().transport.socket;o?o.socket.send(r):p.error("socket transport is not initialized")},Dr=(e,t)=>{try{return t?e.body??e:JSON.parse(e.body)}catch{return e.body||e}};class Qu extends WebSocket{constructor(t){super(t)}}function un(e){const t=`
|
|
61
61
|
|
|
62
62
|
`,s=`
|
|
63
|
-
`,
|
|
63
|
+
`,r=/:(.*)/s,[o,n]=e.split(t).map(a=>a.trim());return{headers:o.split(s).reduce((a,c)=>{const[d,u]=c.split(r).map(h=>h.trim());return d&&u&&(a[d]=u),a},{}),body:n}}function eh(e){const t=`
|
|
64
64
|
|
|
65
65
|
`,s=`
|
|
66
|
-
`,
|
|
66
|
+
`,r=/:(.*)/s,[,o,n]=e.split(t).map(a=>a.trim());return{headers:o.split(s).reduce((a,c)=>{const[d,u]=c.split(r).map(h=>h.trim());return d&&u&&(a[d]=u),a},{}),body:n}}class lo{constructor({host:t,port:s,protocol:r,alias:o,onConnectionEstablished:n,onConnectionLost:i,Transport:a=Qu}){l(this,"host");l(this,"port");l(this,"protocol");l(this,"socket");l(this,"connectionEstablished");l(this,"alias");l(this,"onConnectionEstablished");l(this,"onConnectionLost");l(this,"offlineMessages",[]);l(this,"oldSend");this.host=t,this.port=s,this.protocol=r,this.onConnectionEstablished=n,this.onConnectionLost=i,this.alias=o,this.socket=new a(`${this.protocol}${this.host}:${this.port}/events`),this.socket.onmessage=this.onMessage.bind(this),this.socket.onopen=this.onOpen.bind(this),this.socket.onclose=this.onClose.bind(this),this.oldSend=this.socket.send,this.connectionEstablished=!1,O("/mock/msg/receive",c=>{var d,u;if(c!=null&&c.body){p.wsReceive(c==null?void 0:c.body);const h={data:c.body};(u=(d=this.socket)==null?void 0:d.onmessage)==null||u.call(d,h)}}),M.makeObservable(this,{connectionEstablished:M.observable})}addOfflineMessage(t){this.offlineMessages.push({msg:t})}processMessageEvent(t){const{data:s}=t;return un(s)}onMessage(t){try{p.debug("webSocketTransport: onMessage received");const{headers:s,body:r}=this.processMessageEvent(t);p.wsReceive(t.data);const o=s.subscription||s[this.RESPONSE_ID_HEADER]||s.topic||s.type;if(o){let n=r,i=s;if(o==="kos.sniffer.msg"){const{headers:a,body:c}=eh(t.data);n=c,i={...s,...a}}U(o,n,i)}}catch(s){p.error("onMessage exception",s.message,s.stack)}}onOpen(t){p.info("websocket connection opened"),this.socket=t.currentTarget,M.runInAction(()=>{var s;this.connectionEstablished=!0,this.alias&&this.socket.send(`type:kos.addr.alias
|
|
67
67
|
alias:${this.alias}
|
|
68
68
|
|
|
69
|
-
`),
|
|
70
|
-
${t}`;const
|
|
71
|
-
${
|
|
72
|
-
`:"",u=
|
|
69
|
+
`),p.debug(`sending ${this.offlineMessages.length} offline FOS messages`),this.offlineMessages.forEach(r=>{var o;p.debug(`sending offline message ${r.msg}`),(o=this.socket)==null||o.send(r.msg)}),this.offlineMessages=[],(s=this.onConnectionEstablished)==null||s.call(this)})}onClose(){this.socket&&this.socket.close(),M.runInAction(()=>{this.connectionEstablished=!1}),p.debug("websocket disconnected. Attempting calling callback"),this.onConnectionLost&&setTimeout(this.onConnectionLost,2500)}send(t){var s,r;if(p.wsSend(t),window.kosLogEvents){const{headers:o,body:n}=un(String(t));U(Jt.SEND,{headers:o,body:n})}if(window.kosTopicIntercept&&window.kosEnableMocks){const{handler:o,requestId:n}=window.kosTopicIntercept(t);if(o){t=`mocked:true
|
|
70
|
+
${t}`;const a={data:`mocked:true
|
|
71
|
+
${o(n)}`};(r=(s=this.socket)==null?void 0:s.onmessage)==null||r.call(s,a)}else this.oldSend.call(this.socket,t)}else this.oldSend.call(this.socket,t)}}class th{constructor(t){l(this,"addEventListener");l(this,"dispatchEvent");l(this,"removeEventListener");l(this,"_onclose");l(this,"_onerror");l(this,"_onmessage");l(this,"_onopen");l(this,"messageQueue",[]);l(this,"isSending",!1);S.debug(`called Bridge Transport with addr ${t}`);const s=this;globalThis.kosWindowWebsocketRecv=r=>{if(s.onmessage){const o={data:r};s.onmessage(o)}},S.debug("Opening bridge transport"),globalThis.kosWindowWebsocketOpen(),S.debug("Opened bridge transport"),this._onclose=null,this._onerror=null,this._onmessage=null,this._onopen=null,this.addEventListener=()=>S.debug("not implemented"),this.dispatchEvent=()=>S.debug("not implemented"),this.removeEventListener=()=>S.debug("not implemented")}close(){S.debug("closing")}sendNextMessage(){if(this.messageQueue.length>0){const t=this.messageQueue.shift();globalThis.kosWindowWebsocketSend(t),setTimeout(()=>this.sendNextMessage(),1)}else this.isSending=!1}enqueueMessage(t){this.messageQueue.push(t),this.isSending||(this.isSending=!0,this.sendNextMessage())}send(t){globalThis.kosWindowWebsocketSend(t)}get onmessage(){return this._onmessage}set onmessage(t){this._onmessage=t}get onopen(){return this._onopen}set onopen(t){this._onopen=t}get onclose(){return this._onclose}set onclose(t){this._onclose=t}get onerror(){return this._onerror}set onerror(t){this._onopen=t}}class sh extends lo{constructor({host:s,port:r,alias:o}){super({host:s,port:r,Transport:th,alias:o,protocol:"kos://"});l(this,"RESPONSE_ID_HEADER");this.RESPONSE_ID_HEADER="response-id"}}class rh extends lo{constructor({host:s,port:r}){super({host:s,port:r,protocol:"ws://"});l(this,"RESPONSE_ID_HEADER");this.RESPONSE_ID_HEADER="requestId"}}class oh extends lo{constructor({host:s,port:r,protocol:o,onConnectionEstablished:n,onConnectionLost:i,alias:a}){super({host:s,port:r,onConnectionEstablished:n,onConnectionLost:i,alias:a,protocol:o});l(this,"RESPONSE_ID_HEADER");this.RESPONSE_ID_HEADER="response-id"}}window.kosEnableMocks=process.env.KOS_MOCK_WS==="true";window.kosLogEvents=process.env.KOS_LOG_WS==="true";class Cr{static build({host:t,port:s,protocol:r,fos:o,alias:n,onConnectionEstablished:i,onConnectionLost:a}){return p.debug("initializing websocket connection"),p.warn(`kosWindowWebsocketOpen: ${globalThis.kosWindowWebsocketOpen?"true":"false"}`),p.warn(`fos: ${o?"true":"false"}`),window.kosMockWs||globalThis.kosWindowWebsocketOpen&&!o?(p.warn("Using bridged message transport"),new sh({host:t,port:s,protocol:r,onConnectionEstablished:i,onConnectionLost:a,alias:n})):o?new rh({host:t,port:s,protocol:r,alias:n,onConnectionEstablished:i,onConnectionLost:a}):new oh({host:t,port:s,protocol:r,alias:n,onConnectionEstablished:i,onConnectionLost:a})}}const nh=ie();nh.fos&&(window.kosUseFos=!0);const hn=process.env.KOS_FOS_PORT;window.kosUseFos=!!(window.kosUseFos||process.env.KOS_USE_FOS==="true");window.kosFosPort=hn?parseInt(hn):0;const Ae=S.getLogger("web-socket-transport");var da=(e=>(e.NOT_INITIALIZED="not_initialized",e.INITIALIZED="initialized",e.OFFLINE="OFFLINE",e.ONLINE="ONLINE",e))(da||{}),Pt=(e=>(e.CONNECTED="websocket.connected",e.DISCONNECTED="websocket.disconnected",e.RELOAD="websocket.reload",e))(Pt||{});class Xt{constructor({host:t="localhost",port:s=8080,protocol:r="ws://",token:o,initialize:n,alias:i,fos:a}){l(this,"host");l(this,"port");l(this,"protocol");l(this,"_token");l(this,"webSocketSupported",!!globalThis.WebSocket);l(this,"authorized");l(this,"alias");l(this,"socket");l(this,"fosSocket");l(this,"fosPort");l(this,"useFosTransport");this.host=t,this.port=s,this.protocol=r,this._token=o,this.alias=i,this.authorized=process.env.KOS_ALLOW_ANONYMOUS==="true",this.useFosTransport=!!a,this.fosPort=a==null?void 0:a.port,this.socket=void 0,this.fosSocket=void 0;let c=!1;M.makeObservable(this,{authorized:M.observable,socket:M.observable,fosSocket:M.observable,init:M.action,connectionEstablished:M.computed}),M.reaction(()=>this.connectionEstablished,d=>{d&&(Ae.warn("Connection Established"),U("websocket.connected","websocket.connected"),c&&U("websocket.reload","websocket.reload"),c=!0)}),n&&this.init()}get connectionEstablished(){return!this.webSocketSupported||!this.socket||this.useFosTransport&&!this.fosSocket?!1:this.useFosTransport&&this.fosSocket?this.socket.connectionEstablished&&this.fosSocket.connectionEstablished:!this.useFosTransport&&this.socket?this.socket.connectionEstablished:!1}init(){var t,s;if(p.warn(`Initializing WebSocketTransport on ${this.host}:${this.port}`),this.useFosTransport&&(this.fosSocket=Cr.build({host:this.host,port:this.fosPort||9854,protocol:this.protocol,fos:!0})),this.socket=Cr.build({host:this.host,port:this.port,protocol:this.protocol,alias:this.alias,onConnectionLost:()=>{Ae.error("Connection Lost"),U("websocket.disconnected","websocket.disconnected"),this.init()}}),globalThis.kosWindowWebsocketOpen){const r={currentTarget:this.socket.socket};(s=(t=this.socket.socket)==null?void 0:t.onopen)==null||s.call(t,r)}return this}_sendSubscriptionMessage(t,s,r=!1,o=!1,n){var g,m,v,w;Ae.debug(`${s} to topic ${t}`);const i=ie(),a=i==null?void 0:i.connId,c=n??a??((g=window==null?void 0:window.kosBridge)==null?void 0:g.call(window,"connId"));Ae.debug(`subscribing with connId ${c}`);const d=c?`dst-addr:${c}
|
|
72
|
+
`:"",u=r?`subscribe:${t}`:o?`type:fos.broker
|
|
73
73
|
cmd:${s}
|
|
74
74
|
${d}topics:${t}
|
|
75
75
|
`:`${d}type:kos.broker.${s}
|
|
76
76
|
|
|
77
|
-
["${t}"]`;if(o?(v=this.fosSocket)==null?void 0:v.connectionEstablished:(b=this.socket)==null?void 0:b.connectionEstablished){const I=o?this.fosSocket:this.socket;(_=I==null?void 0:I.socket)==null||_.send(u)}else{Ie.debug("no connection adding to offline messages");const I=o?this.fosSocket:this.socket;I==null||I.addOfflineMessage(u)}}subscribeTopic({topic:t,callback:s,fos:o,bridge:r,destinationAddress:n}){const{unsubscribe:i,count:c}=U(t,s);return Ie.debug(`Topic ${t} currently has ${c} subscribers`),this._sendSubscriptionMessage(t,"subscribe",o,r,n),()=>{const{count:l}=i();Ie.debug(`Topic ${t} currently has ${l} subscribers`),l===0&&this._sendSubscriptionMessage(t,"unsubscribe",o,r,n)}}async whenReady(){const t=this;return this.webSocketSupported?(await w.when(()=>{var s,o;return!!((s=t.socket)!=null&&s.connectionEstablished)&&(!t.useFosTransport||!!((o=t.fosSocket)!=null&&o.connectionEstablished))&&t.authorized}),{status:"success"}):{status:"not supported"}}get token(){return this._token}set token(t){this._token=t,this.init()}static host(t="localhost"){return this.getInstance().host=t,this}static port(t=8080){return this.getInstance().port=t,this}static alias(t){this.getInstance().alias=t}static getInstance(t=8080,s){if(!this._instance){const o=window.kosUseFos?{port:window.kosFosPort||8081}:void 0;this._instance=new this({port:t,token:s,fos:o})}return this._instance}}a(Vt,"_instance");class Mu{constructor(t,s,o,r,n){a(this,"disposers",[]);a(this,"activatableDisposers",[]);this.model=t,this.modelData=s,this.modelId=o,this.offlineQueue=r,this.log=n}registerAll(t){var r;const s=((r=this.modelData)==null?void 0:r[H])||{},o=Object.keys(s);this.log.debug(`Found ${o.length} subscriptions in ${this.modelId} (lifecycle: ${t??"any"})`),o.forEach(n=>{const i=s[n],c=i.lifecycle;if(t&&t!==c)return;const l=this.resolvePropKey(n);this.log.debug(`Resolved topic: ${n} → ${l}`);const d=this.createHandler(l,i);this.subscribe(i,l,d,c===k.ACTIVATE)})}deactivate(){this.log.debug(`Deactivating subscriptions for ${this.modelId}`);for(const t of this.activatableDisposers)try{t()}catch(s){this.log.error("Error during subscription disposal",s)}this.activatableDisposers=[]}disposeAll(){const t=[...this.disposers,...this.activatableDisposers];this.log.debug(`Disposing ${t.length} subscriptions for ${this.modelId}`);for(const s of t)try{s()}catch(o){this.log.error("Error during subscription disposal",o)}this.disposers=[],this.activatableDisposers=[]}subscribe(t,s,o,r){const n=t.destinationAddress?this.resolvePropKey(t.destinationAddress):null;if(t.websocket){this.log.debug(`Subscribing to WebSocket topic: ${s}`);const i=Vt.getInstance().subscribeTopic({topic:s,callback:o,fos:t.fos,bridge:t.bridge,destinationAddress:n});this.disposers.push(i)}else{this.log.debug(`Subscribing to EventBus topic: ${s}`);const{unsubscribe:i}=U(s,o);r?this.activatableDisposers.push(i):this.disposers.push(i)}}createHandler(t,s){return async o=>{var r;try{const n=(r=o==null?void 0:o.headers)==null?void 0:r["src-addr"],i=s.destinationAddress&&this.resolvePropKey(s.destinationAddress),c=i?n===i:!0;if(this.model.isReady()){const l=_o(o,s.skipParse),d=s.transform(l);if(c&&s.condition(d,this.modelData,o))return s.handler.call(this.modelData,d,o,this.modelData)}else{this.log.warn(`Model ${this.modelId} not ready. Queuing message for ${t}`);const l=()=>{const d=_o(o,s.skipParse),u=s.transform(d);if(c&&s.condition(u,this.modelData,o))return s.handler.call(this.modelData,u,o,this.modelData)};this.offlineQueue.enqueue(l)}}catch(n){this.log.error(`Error handling subscription for ${t}`,n)}}}resolvePropKey(t){const s=/.*({PROP_(.+)})/;let o=t.includes("{MODEL_ID}")?t.replace("{MODEL_ID}",this.modelId):t;const r=o.match(s);return r&&r[2]in this.modelData&&(o=o.replace(r[1],this.modelData[r[2]])),o}}function it(e,t){const s=`[Model:${t}]`;return{debug:(...o)=>e.debug(s,...o),info:(...o)=>e.info(s,...o),warn:(...o)=>e.warn(s,...o),error:(...o)=>e.error(s,...o)}}function _u(e){return!!(e!=null&&e[Oe])&&Object.keys(e[Oe]).length>0}function Eu(e){return!!(e!=null&&e[H])&&Object.keys(e[H]).length>0}class Iu{static createAll(t){const{modelId:s,modelTypeName:o,modelData:r}=t,n=au.create({modelId:s,modelTypeName:o}),i=new iu(t,it(n,"fsm")),c=new cu(it(n,"offline-queue")),l=new Xd(t),d=new Jd(t),u={fsm:i,offlineQueue:c,companionManager:l,childResolver:d};if(_u(r)&&(u.effectManager=new Qd(o,s,r,it(n,"effect"))),Eu(r)){const h=it(n,"subscription");u.subscriptionManager=new Mu(t,r,s,c,h),u.onlineLifecycleManager=new lu(t,it(n,"online"))}return u}}const A=T.getLogger("kos-model"),Tu="kos.extension.model.loader";class Ui{constructor({modelTypeName:t,id:s,modelData:o}){a(this,"_id");a(this,"_status");a(this,"_activeStatus");a(this,"_onlineStatus");a(this,"modelData");a(this,"modelTypeName");a(this,"initialized");a(this,"loaded");a(this,"offlineQueue");a(this,"subscriptionManager");a(this,"effectManager");a(this,"onlineLifecycleManager");a(this,"companionManager");a(this,"childResolver");a(this,"fsm");this._id=typeof s<"u"?`${s}`:t,this.modelTypeName=t,this.initialized=!1,this.loaded=!1,this.modelData=o,this._status=y.CREATED,this._activeStatus=y.INACTIVE,this._onlineStatus=y.OFFLINE;const r=Iu.createAll(this);this.fsm=r.fsm,this.offlineQueue=r.offlineQueue,this.companionManager=r.companionManager,this.childResolver=r.childResolver,r.effectManager&&(this.effectManager=r.effectManager),r.subscriptionManager&&(this.subscriptionManager=r.subscriptionManager),r.onlineLifecycleManager&&(this.onlineLifecycleManager=r.onlineLifecycleManager),w.makeAutoObservable(this,{fsm:!1,effectManager:!1,subscriptionManager:!1,onlineLifecycleManager:!1,companionManager:!1,childResolver:!1,offlineQueue:!1}),Wd(this)}get companionModels(){return this.companionManager}set status(t){this._status=t}get status(){return this._status}get modelId(){return this._id}get id(){return this._id}get activeStatus(){return this._activeStatus}set activeStatus(t){this._activeStatus=t}get onlineStatus(){return this._onlineStatus}set onlineStatus(t){this._onlineStatus=t}get modelManager(){return globalThis.kos.modelManager}isActive(){return this._status===y.ACTIVE}isOnline(){return this._onlineStatus===y.ONLINE}isReady(){return this._status===y.READY}async deactivate(){var t,s,o;A.debug(`deactivating model ${this.modelTypeName} with id ${this.modelId}`);try{const r=x.getContext(this.modelId);await((s=(t=this.modelData)==null?void 0:t.deactivate)==null?void 0:s.call(t,r)),A.debug(`Model ${this.modelTypeName} with id ${this.modelId} deactivated`),(o=this.subscriptionManager)==null||o.deactivate()}catch(r){throw A.debug(`Model ${this.modelId} failed to deactivated`),r}}async activate(){var t,s,o;A.debug(`activating model ${this.modelTypeName} with id ${this.modelId}`),await lt(this,k.ACTIVATE);try{const r=x.getContext(this.modelId);await((s=(t=this.modelData)==null?void 0:t.activate)==null?void 0:s.call(t,r)),A.debug(`Model ${this.modelTypeName} with id ${this.modelId} subscribing to all topics`),(o=this.subscriptionManager)==null||o.registerAll(k.ACTIVATE),A.debug(`Model ${this.modelTypeName} with id ${this.modelId} activated`)}catch(r){throw A.debug(`Model ${this.modelId} failed to activate`),r}}async whenInitialized(){await Zr([{condition:()=>this.status===y.FAILED,onMatch:()=>{throw new Error(`Failed to initialize model ${this.modelId}`)}},{condition:()=>this.initialized,onMatch:()=>{A.debug(`Model ${this.modelId} is initialized`)}}])}async whenReady(){await Zr([{condition:()=>this.status===y.FAILED,onMatch:()=>{throw new Error(`Failed to ready model ${this.modelId}`)}},{condition:()=>this.status===y.READY,onMatch:()=>{A.debug(`Model ${this.modelId} is ready`)}}])}async ready(){var t,s,o;if(this.fsm.current===y.READY){A.debug(`already readying model ${this.modelTypeName} with id ${this.modelId} returning`);return}try{A.debug(`readying model ${this.modelTypeName} with id ${this.modelId}`),await lt(this,k.READY),await Ii(this,Zo.READY,k.READY);const r=x.getContext(this.modelId);await((s=(t=this.modelData)==null?void 0:t.ready)==null?void 0:s.call(t,r)),this.offlineQueue.flush(),(o=this.subscriptionManager)==null||o.registerAll(k.READY),A.debug(`Model ${this.modelId} is ready`);const n={modelId:this.modelId,modelType:this.modelTypeName};F(ui(this.modelTypeName,this.modelId),n),F(hi(this.modelTypeName),n)}catch(r){throw A.error(r),Error(r)}}async load(){var o,r,n,i;const{modelTypeName:t,modelId:s}=this;if(this.fsm.current===y.LOADED||this.fsm.current===y.LOADING){A.debug(`Model ${t} with id ${s} already loaded or loading`);return}A.debug(`Loading model ${t} with id ${s}`),await lt(this,k.LOAD);try{const c=x.getContext(s),l=`${Tu}.${t}`,d=await $.loader.executeLoader(l,{});d&&(A.info(`Setting loaded context for ${s}, type: ${t}`),c==null||c.set(l,d)),await((r=(o=this.modelData)==null?void 0:o.load)==null?void 0:r.call(o,c)),this.loaded=!0,A.debug(`Model ${t} with id ${s} successfully loaded`),(n=this.subscriptionManager)==null||n.registerAll(k.LOAD),(i=this.effectManager)==null||i.setup()}catch(c){throw A.error(`Model ${s} failed to load`,c),c}}async unload(){var t,s,o,r,n;A.debug(`unloading model ${this.modelTypeName} with id ${this.modelId}`);try{const i=this.getChildren().map(l=>{var d;return(d=l.unload)==null?void 0:d.call(l)}).filter(l=>!!l);await Promise.allSettled(i);const c=x.getContext(this.modelId);await((s=(t=this.modelData)==null?void 0:t.unload)==null?void 0:s.call(t,c)),this.loaded=!1,(o=this.onlineLifecycleManager)==null||o.dispose(),A.debug(`Model ${this.modelTypeName} with id ${this.modelId} unloaded`),(r=this.effectManager)==null||r.disposeAll(),(n=this.subscriptionManager)==null||n.disposeAll()}catch(i){throw A.debug(`Model ${this.modelId} failed to unload`),i}}async init(){var r,n,i;const{modelId:t,modelTypeName:s}=this,o=x.getContext(t);A.debug(`Initializing model ${s} with id ${t}`),await lt(this,k.INIT);try{await((n=(r=this.modelData)==null?void 0:r.init)==null?void 0:n.call(r,o)),this.initialized=!0,A.debug(`Model ${s} with id ${t} initialized`),(i=this.onlineLifecycleManager)==null||i.register(),this.registerSubscribers(k.INIT)}catch(c){throw A.error(`Model ${t} failed to initialize`,c),c}}async registerSubscribers(t){var s;A.debug(`registering subscribers in ${this.modelTypeName} with id ${this.modelId}`),(s=this.subscriptionManager)==null||s.registerAll(t)}async online(){var s,o;A.debug(`online model ${this.modelTypeName} with id ${this.modelId}`),this.registerSubscribers();const t=x.getContext(this.modelId);await((o=(s=this.modelData)==null?void 0:s.online)==null?void 0:o.call(s,t))}async offline(){var s,o,r;A.debug(`offline model ${this.modelTypeName} with id ${this.modelId}`),(s=this.subscriptionManager)==null||s.disposeAll();const t=x.getContext(this.modelId);await((r=(o=this.modelData)==null?void 0:o.offline)==null?void 0:r.call(o,t))}accept(t){t.visit(this)}getChildren(){return this.childResolver.resolve()}addCompanionModel(t){this.companionManager.add(t)}clearCompanionModels(){this.companionManager.clear()}}const ji=e=>typeof e=="function",en=m.createLogger({name:"kos-model-instantiator"});class $u{constructor(t,s){this.registry=t,this.cache=s}createModelInstance(t,s,o={}){const r=this.registry.models[t];if(!r)throw new Error(`No model registered for type ${t}`);const n=r.singleton?t:s;if(this.cache.restoreFromDeleteCache(n),!this.cache.hasModel(n)){en.debug(`Creating model instance: ${t} [${n}]`);const c=r.create?r.create({modelTypeId:t,id:n,options:o}):new r.class(n,o),l=new Ui({modelTypeName:t,id:n,modelData:c});this.cache.addModel(l),this._createCompanionModels(l,o)}const i=this.cache.getModelById(n);if(!i)throw en.error(`Model ${t} [${n}] not found in cache`),new Error(`Model ${t} [${n}] not found in cache`);return{model:i,data:i.modelData}}_createCompanionModels(t,s){var n;const o=t.modelTypeName,r=((n=this.registry.companionModels)==null?void 0:n[o])||[];for(const{type:i}of r){const c=ji(i)?i(t.modelData,s):i;if(!c)continue;const l=`${c}-${t.modelId}`,d=this.createModelInstance(c,l,{data:s,companionParent:t.modelData,kosParentId:t.modelId});d!=null&&d.model&&t.addCompanionModel(d.model)}}}let Ou=class{constructor(t){this._registry=t}get registry(){return this._registry}getModelTypeRegistry(t){const s=this.registry.models[t];if(!s)throw new Error(`No registration for model type ${t}`);return s}registerModel(t){const s=t.type;this.registry.models[s]||(this.registry.models={...this.registry.models,...t.registration})}registerCompanionModel(t,s){var o,r;(o=this.registry).companionModels??(o.companionModels={}),(r=this.registry.companionModels)[t]??(r[t]=[]),this.registry.companionModels[t].some(n=>n.type===s)||this.registry.companionModels[t].push({type:s})}getModelSubscriptions(t){var s;return((s=this.getModelTypeRegistry(t))==null?void 0:s.subscriptions)||{}}getDataModelBuilder(t){var o;const s=(o=this.getModelTypeRegistry(t))==null?void 0:o.builder;if(!s)throw new Error(`No builder found for model type ${t}`);return s}getModelFactory(t){return tt(t)}};const Bi=10,tn=m.createLogger({name:"kos-model-manager"});class Ki{constructor(){a(this,"cache");a(this,"instantiator");a(this,"dependencies");a(this,"_registry");globalThis.kos=globalThis.kos||{},this.dependencies=new Ad,globalThis.kos.modelManager=this,globalThis.kos.resolveKosModel=t=>{const s=this.getModelById(t);if(s)return s.modelData||{}},globalThis.kos.kosModelJson=t=>{var o,r;const s=this.getModelById(t);if(s)return((r=(o=s.modelData).toJSON)==null?void 0:r.call(o))||{}},globalThis.kos.kosModelDebug=t=>{var o;const s=this.getModelById(t);if(s)return((o=s.modelData)==null?void 0:o.debugState)||{}},globalThis.kos.kmd=globalThis.kos.kosModelDebug,globalThis.kos.kmj=globalThis.kos.kosModelJson}static create(t,s){const o=this.getInstance(s);return o._registry=new Ou(t),o.cache=new Cd(t.preloadModels),o.instantiator=new $u(t,o.cache),o}static getInstance(t){var s,o;return(!((s=globalThis.kos)!=null&&s.modelManager)||t)&&(tn.debug("Creating new instance of KosModelManager"),new this),(o=globalThis.kos)==null?void 0:o.modelManager}get registry(){return this._registry.registry}get preloadedModels(){return this.cache.preload(t=>(tn.debug(`preloading ${t}`),typeof t=="string"?this.createModelInstance(t).model:this.createModelInstance(t.modelType,t.modelId,t.options).model))}get models(){return this.cache.models}getModelById(t){return this.cache.getModelById(t)}addModel(t){return this.cache.addModel(t)}removeModel(t){this.cache.removeModel(t.modelId)}hasModel(t){return this.cache.hasModel(t)}getModelsByType(t,s){return Array.from(this.models).filter(o=>o.modelTypeName===t).filter(o=>s?s(o.modelData):!0).map(o=>o.modelData)}getModelSubscriptions(t){return this._registry.getModelSubscriptions(t)}getDataModelBuilder(t){return this._registry.getDataModelBuilder(t)}getModelFactory(t){return tt(t)}addDependency(t,s){this.cache.restoreFromDeleteCache(s),this.dependencies.add(t,s)}removeDependency(t,s){this.dependencies.remove(t,s)}async reloadModel(t){if(t.id){const s=this.getModelById(t.id);s&&await s.fsm.transitionTo(D.RESET,y.RESETTING)}}async initiateDestroyModel(t){if(!t.id)throw new Error("Model ID is required");if(!this.dependencies.canDestroy(t.id))return;const s=this.getModelById(t.id);s&&(this.cache.markForDeletion(s),oi.addToDeletionQueue(t.id,setTimeout(()=>this.destroyModel(s),Bi)))}async destroyModel(t){var s;t!=null&&t.modelId&&this.dependencies.canDestroy(t.modelId)&&(await((s=t.unload)==null?void 0:s.call(t)),this.removeModel(t))}createModelInstance(t,s,o={}){return this.instantiator.createModelInstance(t,s,o)}registerCompanionModel(t,s){this._registry.registerCompanionModel(t,s)}registerModel(t){this._registry.registerModel(t)}}const Su=async({context:e,extension:t})=>{const s=await $.loader.executeLoader(t,{});return e==null||e.set(t,s),s},Du=async({extension:e,contextData:t,data:s})=>await $.dataMapper.executeMapper(e,s,t),Au=async({extension:e,contextData:t,data:s})=>await $.propertyMapper.executeMapper(e,s,t),Cu=Object.freeze(Object.defineProperty({__proto__:null,executeDataMapperExtension:Du,executeLoaderExtension:Su,executePropertyMapperExtension:Au},Symbol.toStringTag,{value:"Module"})),Ru="Extensions";class Pu{constructor(){a(this,"extensions");this.extensions={}}register(t,s,o){this.extensions[t]={},this.extensions[t][s]={component:o}}get(t,s){if(!this.extensions[t])throw new Error(`Extension point ${t} not found`);return this.extensions[t][s]}get allExtensions(){return this.extensions}}var ds=(e=>(e.CREATING="creating",e.CREATED="created",e.INITIALIZING="initializing",e.INITIALIZED="initialized",e.LOADING="loading",e.LOADED="loaded",e.ONLINE="online",e.READYING="readying",e.READY="ready",e.OFFLINE="offline",e.UNLOADING="unloading",e.UNLOADED="unloaded",e.RELOADING="reloading",e))(ds||{}),je=(e=>(e.CREATE="create",e.INITIALIZE="init",e.READY="ready",e.GO_ONLINE="go_online",e.GO_OFFLINE="go_offline",e.UNLOAD="unload",e.RELOAD="reload",e))(je||{});const Lu=e=>{const t=p.createMachine("offline",{online:p.state(p.transition("go_offline","offline",p.action(()=>{e.offline(),w.runInAction(()=>{e.isOnline=!1})}))),offline:p.state(p.transition("go_online","online",p.action(()=>{e.online(),w.runInAction(()=>{e.isOnline=!0})})))}),s=p.interpret(t,n=>T.debug(n.machine.current)),o=p.createMachine({creating:p.state(p.transition("create","created")),created:p.state(p.immediate("initializing")),initializing:p.invoke(()=>e.init(),p.transition("done","initialized")),initialized:p.state(p.immediate("loading")),loading:p.invoke(()=>e.load(),p.transition("done","loaded")),loaded:p.state(p.immediate("readying"),p.transition("unload","unloading")),readying:p.invoke(()=>e.ready(),p.transition("done","ready",p.action(()=>{w.runInAction(()=>{e.status="ready"})}))),reloading:p.invoke(()=>e.reload(),p.transition("done","loading")),ready:p.state(p.transition("reload","reloading"),p.transition("unload","unloaded",p.action(e.unload.bind(e))),p.transition("go_online","ready",p.action(()=>{s.send("go_online")})),p.transition("go_offline","ready",p.action(()=>{s.send("go_offline")}))),unloaded:p.state()});return{service:p.interpret(o,n=>T.debug(n.machine.current)),online:s}},J=async e=>{if(e.id){const t=E.getInstance().modelManager.getModelById(e.id);if(!t)throw new Error(`Model with ID ${e.id} not found`);await(t==null?void 0:t.whenReady())}else throw new Error("Data model must have a valid ID");return e},Se=async e=>{await E.getInstance().whenReady(),await E.getInstance().modelManager.initiateDestroyModel(e)},xu=async e=>{if(await E.getInstance().whenReady(),!e.id)throw new Error("Model ID is required");const t=E.getInstance().modelManager.getModelById(e.id);t&&await t.fsm.transitionTo(D.UNLOAD,y.UNLOADED)},Hi=async e=>{await E.getInstance().whenReady(),await E.getInstance().modelManager.reloadModel(e),m.debug(`reload model initiated for model ${e.id}, model ready: ${ps(e)} - ${Date.now()} `),await J(e),m.debug(`reload model complete for model ${e.id}, model ready: ${ps(e)} - ${Date.now()} `)},ku=async e=>{if(await E.getInstance().whenReady(),!e)throw new Error("Model ID is required");const t=E.getInstance().modelManager.getModelById(e);return t==null?void 0:t.modelTypeName},Gi=async e=>{if(await E.getInstance().whenReady(),!e)throw new Error("Model ID is required");const t=E.getInstance().modelManager.getModelById(e);return{model:t==null?void 0:t.modelData,type:t==null?void 0:t.modelTypeName}},Re=e=>{if(!e)throw new Error("Model ID is required");const t=E.getInstance().modelManager.getModelById(e);return{model:t==null?void 0:t.modelData,type:t==null?void 0:t.modelTypeName}},Vi=(e,t)=>{if(!e)throw new Error("Model type is required");return E.getInstance().modelManager.getModelsByType(e).filter(r=>Object.keys(t).every(n=>r[n]===t[n]))},Fu=(e,t)=>Vi(e,t)[0],Nu=(e,t)=>{if(!e.id)throw new Error("Model ID is required");const s=E.getInstance().modelManager.getModelById(e.id);if(!s)throw new Error("Model not found");const o=s.companionModels.get(t);return o==null?void 0:o.modelData},Uu=e=>{if(!e.id)throw new Error("Model ID is required");const t=E.getInstance().modelManager.getModelById(e.id);if(!t)throw new Error("Model not found");return Array.from(t.companionModels.all()).map(o=>o.modelData)},ju=e=>{if(!e)throw new Error("Model ID is required");const t=E.getInstance().modelManager.getModelById(e);if(!t)throw new Error("Model not found");return t.companionModels.data},Io=(e,t)=>{const s=E.getInstance().modelManager.getModelById(e);if(!s){m.info(`Model not found for id ${e}`);return}return Array.from(s.companionModels.all()).find(r=>t(r.modelData))},te=e=>t=>Object.getPrototypeOf(t).modelTypeId===e,ps=e=>{const t=E.getInstance().modelManager.getModelById(e.id);if(!t)throw new Error("Model not found");return t.isReady()},Bu=m.createLogger({name:"kos-model-factory"}),Ot={byModelType:e=>E.getInstance().modelManager.getModelFactory(e),getModelInstance:(e,t,s)=>{const o=Ot.byModelType(t);if(!o)throw Bu.error(`No registered factory found for model type ${t}. Please register a factory for this model type. `),Error(`No factory found for model type ${t}`);return o.build(e,s)}},V={Factory:{create:e=>t=>(s,o)=>(o&&x.setParentContext(t,o),Ot.getModelInstance(t,e,s))},Singleton:{create:e=>(t,s)=>(s&&x.setParentContext(e,s),Ot.getModelInstance(e,e,t))},Model:{instance:e=>t=>Ot.getModelInstance(t,e)}};window.KosRegistry=window.KosRegistry||{coreModels:new Map,preloadModels:[],companionModels:new Map,models:new Map};const sn=window.KosRegistry.coreModels,co=window.KosRegistry.preloadModels,lo=window.KosRegistry.companionModels,Qt=window.KosRegistry.models,O={model:{registerLegacyModel:e=>(t,s)=>(sn.set(t,s),{preload:O.model.preloadModel(e),model:O.model.register(e),companion:O.companion.register(e),legacy:O.model.registerLegacyModel(e),root:e}),preloadModel:e=>t=>(co.includes(t)||co.push(t),{preload:O.model.preloadModel(e),model:O.model.register(e),companion:O.companion.register(e),legacy:O.model.registerLegacyModel(e),root:e}),register:e=>(t,s)=>{const o=uo(t)?t.registration():t;return Qt.set(o.type,o),uo(t)&&t.relatedModels.forEach(r=>Qt.set(r.type,r.registration())),E.getInstance().isReady&&(E.getInstance().modelManager.registry.models[o.type]||(console.info(`Model with type ${o.type} doesn't exist. Adding new registration`),E.getInstance().modelManager.registry.models[o.type]=o.registration[o.type],uo(t)&&t.relatedModels.forEach(r=>E.getInstance().modelManager.registry.models[r.type]=r.registration().registration))),s&&O.model.preloadModel(e)(o.type),{preload:O.model.preloadModel(e),model:O.model.register(e),companion:O.companion.register(e),legacy:O.model.registerLegacyModel(e),root:e}},get:e=>Qt.get(e),getAll:()=>Array.from(Qt.entries()),getPreloadModels:()=>co,getLegacyModels:()=>Array.from(sn.entries()).reduce((e,[t,s])=>(e[t]=s,e),{})},companion:{register:e=>(t,s)=>{const o=lo.get(t)||[];return o.push(s),lo.set(t,o),{preload:O.model.preloadModel(e),model:O.model.register(e),companion:O.companion.register(e),legacy:O.model.registerLegacyModel(e),root:e}},getAll:()=>Array.from(lo.entries())}},Yi=O.model.registerLegacyModel,zi=O.model.register,Ku=O.companion.register,Hu=O.model.preloadModel,qi=e=>typeof e.updateModel=="function",uo=e=>e.registration!==void 0&&typeof e.registration=="function";class Wi{constructor(t){a(this,"singleton");a(this,"type");a(this,"loader");a(this,"class");a(this,"guard");a(this,"factory");a(this,"relatedModels",[]);this.singleton=t.singleton,this.guard=te(t.type),this.type=t.type,this.loader=`kos.extension.model.loader.${t.type}`,this.factory=t.factory,this.class=t.class}addRelatedModel(t){this.relatedModels.push(t)}registerRelatedModels(){this.relatedModels.forEach(t=>t.register())}register(){O.model.register({})(this.registration()),this.registerRelatedModels()}}class ce extends Wi{constructor(t){super({...t,singleton:!1,factory:V.Factory.create(t.type)})}instance(t){const s=this.factory(t);return{get:()=>{const o=Re(t);if(!o)throw new Error("Model not found with id "+t);if(this.guard(o))return o;throw new Error("Model is not of type "+this.type)},forceUpdate:{options:o=>({build:()=>{const r=s(o);if(this.guard(r)){if(qi(r))r.updateModel(o);else throw new Error(`Model ${this.type} is not updateable. Please implement UpdateAware interface`);return r}else throw new Error("Model is not of type "+this.type)}})},options:o=>({build:()=>{const r=s(o);if(this.guard(r))return r;throw new Error("Model is not of type "+this.type)}})}}registration(){return{type:this.type,predicate:this.guard,registration:{[this.type]:{class:this.class,singleton:!1}},factory:this.factory}}}class pe extends Wi{constructor(t){super({...t,singleton:!0,factory:V.Singleton.create(t.type)})}instance(){const t=this.factory;return{get:()=>{const o=Re(this.type);if(!o)throw new Error("Model not found with id "+this.type);if(this.guard(o))return o;throw new Error(`Model is not of type ${this.type}. Received type ${Object.getPrototypeOf(o).modelTypeId}`)},forceUpdate:{options:o=>({build:()=>{const r=t(o);if(this.guard(r)){if(qi(r))r.updateModel(o);else throw new Error(`Model ${this.type} is not updateable. Please implement UpdateAware interface`);return r}else throw new Error(`Model is not of type ${this.type}. Received type ${Object.getPrototypeOf(r).modelTypeId}`)}})},options:o=>({build:()=>{const r=t(o);if(this.guard(r))return r;throw new Error(`Model is not of type ${this.type}. Received type ${Object.getPrototypeOf(r).modelTypeId}`)}})}}registration(){return{type:this.type,predicate:this.guard,registration:{[this.type]:{class:this.class,singleton:!0}},factory:this.factory}}}const j=m.createLogger({name:"kos-core"}),Gu=()=>{const e=ee(),t=e==null?void 0:e.alias,s=process.env.KOS_CONNECTION_ALIAS;return t||s||void 0},Vu=()=>{const e=window.location.protocol,t=ee(),s=t==null?void 0:t.host;let o;try{o=new URL(s).protocol==="https:"?"wss://":"ws://"}catch{}return o||(e==="https:"?"wss://":"ws://")},Yu=()=>{const e=window.location.hostname,t=process.env.KOS_HOST,s=ee(),o=s==null?void 0:s.host;let r;try{r=new URL(o).hostname}catch{}return r??t??e},zu=()=>{const e=window.location.port,t=process.env.KOS_PORT,s=ee(),o=s==null?void 0:s.host;let r;try{r=new URL(o).port}catch{}return r??t??e},qu=(e,t)=>{let s;return{promise:new Promise((n,i)=>{s=setTimeout(()=>{t?m.error(`Model ${t.modelId} - ${t.modelTypeName} preloading - timed out after ${e}ms`):m.error(`KOS Core preloading timed out after ${e}ms`),i(new Error(`Model ${t==null?void 0:t.modelId} - ${t==null?void 0:t.modelTypeName} - timed out after ${e}ms`))},e)}),cancel:()=>{s&&clearTimeout(s)}}},on=e=>typeof e.reload=="function",Wu=e=>typeof e.unload=="function";var Zi=(e=>(e.LOGGED_IN="logged_in",e.LOGGED_OUT="logged_out",e))(Zi||{});class E{constructor(t){a(this,"fsmService");a(this,"status");a(this,"initialized");a(this,"loaded");a(this,"_transport");a(this,"modelManager");a(this,"authState");a(this,"isOnline");a(this,"_reloading");a(this,"_unloading");a(this,"connectionAlias");this.initialized=!1,this.connectionAlias=t,this.loaded=!1,this.isOnline=!1,this.status=ds.CREATED,this.authState="logged_out",this._reloading=!1,this._unloading=!1,w.makeAutoObservable(this),U("token",c=>{c&&(this.transport.token=c.body)}),U($t.CONNECTED,async()=>{await this.whenReady(),this.fsmService.service.send(je.GO_ONLINE)}),U($t.DISCONNECTED,async()=>{this.fsmService.service.send(je.GO_OFFLINE)}),U("/studioServer/auth/LOGGED_IN",()=>{this.authState="logged_in",this.transport.authorized=!0}),U("/studioServer/auth/LOGIN_REQUIRED",()=>{this.authState="logged_out",this.transport.authorized=!1}),U($t.RELOAD,()=>{this.fsmService.service.send(je.RELOAD)}),U("/studio/project/reload",()=>{this.fsmService.service.send(je.RELOAD)});const s=Vt.getInstance(),o=Yu(),r=zu(),n=Vu();s.host=o,s.port=Number.parseInt(r),s.protocol=n,process.env.KOS_ALLOW_ANONYMOUS==="true"&&(s.authorized=!0);const i=Gu()??t;i&&(s.alias=i.replace("{{TIMESTAMP}}",Date.now().toString())),this._transport=s.init(),this.fsmService=Lu(this),this.fsmService.service.send(je.CREATE)}get onlineStatus(){return this.isOnline&&!this._reloading&&!this._unloading}get reloading(){return this._reloading}get unloading(){return this._unloading}async reload(){var r,n,i,c;const t=Date.now();if(this._reloading){j.info("reload already in progress");return}this._reloading=!0,j.warn("reloading KOS Core"),j.warn("reloading preloaded models");const s=this.modelManager;for(const l of s.preloadedModels)on(l.modelData)&&(j.info(`reloading model ${l.modelId}`),(r=l.unload)==null||r.call(l),await l.modelData.reload(),(n=l.registerSubscribers)==null||n.call(l),j.info(`reloading model ${l.modelId} complete`));for(const l of s.models)!s.preloadedModels.includes(l)&&on(l.modelData)&&((i=l.unload)==null||i.call(l),await l.modelData.reload(),(c=l.registerSubscribers)==null||c.call(l));const o=Date.now()-t;setTimeout(()=>{w.runInAction(()=>{j.warn("reloading KOS Core complete"),this._reloading=!1})},1e3-o)}async online(){j.debug("KOS Core going online"),await this._transport.whenReady(),j.debug("KOS Transport Ready. Calling online() for models"),F("/kosCore/online","/kosCore/online"),console.timeEnd("kosCore:startup")}async offline(){j.debug("KOS Core going offline"),F("/kosCore/offline","/kosCore/offline")}async unload(){var r;j.debug("Unloading KOS Core");const t=Date.now();this._unloading=!0,j.debug("unloading KOS Core");const s=this.modelManager;for(const n of s.models)Wu(n.modelData)&&((r=n.unload)==null||r.call(n));const o=Date.now()-t;setTimeout(()=>{w.runInAction(()=>{this._unloading=!1})},1e3-o)}async whenReady(){await w.when(()=>this.status===ds.READY)}async ready(){j.debug("Readying KOS Core"),await this._transport.whenReady();const t=this.modelManager.preloadedModels.map(r=>({modelId:r.modelId,model:r,promise:r.whenReady()})),o=(await Promise.allSettled(t.map(r=>{const{promise:n,cancel:i}=qu(5e3,r.model);Promise.race([r.promise.then(()=>{i()}),n])}))).filter(r=>r.status==="rejected");if(o.length)throw j.error(`There were ${o.length} failed models on model preloading`),Error(`There were ${o.length} failed models on model preloading`);j.debug("leaving kos-core ready() ")}get isReady(){return this.status===ds.READY}set transport(t){this._transport=t}get transport(){return this._transport}get coreInitialized(){return this.initialized}get modelsLoaded(){return this.loaded}async init(){j.debug("entering kos-core init()"),console.time("kosCore:startup"),console.time("kosCore:init"),await this._transport.whenReady(),this.initialized=!0,j.debug("initialized - leaving kos-core init()"),console.timeEnd("kosCore:init")}async load(){j.debug("entering kos-core load()"),console.time("kosCore:load"),this.loaded=!0,j.debug("loaded - leaving kos-core load()"),console.timeEnd("kosCore:load")}static create(t,s,o){var i,c,l;const r=this.getInstance({reset:s,connectionAlias:o});(i=t.extensions)!=null&&i.dataMapper&&Object.keys(t.extensions.dataMapper).forEach(d=>{var h,f;const u=(f=(h=t.extensions)==null?void 0:h.dataMapper)==null?void 0:f[d];u&&(Array.isArray(u)?u.forEach(v=>{$.dataMapper.registerDataMapper(d,v)}):$.dataMapper.registerDataMapper(d,u))}),(c=t.extensions)!=null&&c.propertyMapper&&Object.keys(t.extensions.propertyMapper).forEach(d=>{var h,f;const u=(f=(h=t.extensions)==null?void 0:h.propertyMapper)==null?void 0:f[d];u&&$.propertyMapper.registerPropertyMapper(d,u)}),(l=t.extensions)!=null&&l.contextLoader&&Object.keys(t.extensions.contextLoader).forEach(d=>{var h,f;const u=(f=(h=t.extensions)==null?void 0:h.contextLoader)==null?void 0:f[d];u&&$.loader.registerLoader(d,u)}),O.model.getAll().forEach(([,d])=>{t.models={...t.models,...d.registration}}),t.models={...t.models,...O.model.getLegacyModels()},O.companion.getAll().forEach(([d,u])=>{t.companionModels={...t.companionModels},t.companionModels[d]=t.companionModels[d]||[];for(const h of u)t.companionModels[d].push({type:h})}),O.model.getPreloadModels().forEach(d=>{t.preloadModels.includes(d)||t.preloadModels.push(d)});const n=Ki.create(t,s);return r.modelManager=n,r}static getInstance(t){return this._instance=window.KosCore,(!this._instance||t!=null&&t.reset)&&(window.KosCore=new this(t==null?void 0:t.connectionAlias),this._instance=window.KosCore),this._instance}}a(E,"_instance");const rn=m.createLogger({name:"kos-fetch"}),Zu=process.env.KOS_WS_TIMEOUT?parseInt(process.env.KOS_WS_TIMEOUT):3e4,Ju=()=>new Promise(e=>{setTimeout(()=>{e(!0)},0)}),Xu=e=>e!=null&&e.studio?Oi:e!=null&&e.fos?Si:Di,Qu=async(e,t)=>{const s=E.getInstance().transport;await s.whenReady();const o=et(),r=new URL(e),n=`${r.pathname}${r.search}`;rn.debug(`path: ${n}`);const i=(t==null?void 0:t.timeout)||Zu,c=Xu(t),l=we(c({path:n,requestId:o,method:(t==null?void 0:t.method)||"GET",destinationAddress:(t==null?void 0:t.destinationAddress)||"",ordered:t==null?void 0:t.ordered,tracker:t==null?void 0:t.tracker,bridge:t==null?void 0:t.bridge}),t==null?void 0:t.body);return new Promise(d=>{const u=new AbortController,h=setTimeout(()=>{rn.error(`Timeout occurred - url: ${e}`),u.abort(),d({headers:wo({}),status:404,ok:!1,json:async()=>null,body:Mo(""),redirected:!1,statusText:"",type:"basic",url:"",clone:function(){throw new Error("Function not implemented.")},bodyUsed:!1,arrayBuffer:function(){throw new Error("Function not implemented.")},blob:function(){throw new Error("Function not implemented.")},formData:function(){throw new Error("Function not implemented.")},text:function(){throw new Error("Function not implemented.")}})},i),{unsubscribe:f}=U(o,b=>{var I,C,se;clearTimeout(h);const _={headers:wo((b==null?void 0:b.headers)||{}),status:((I=b==null?void 0:b.headers)==null?void 0:I.status)&&parseInt((C=b==null?void 0:b.headers)==null?void 0:C.status)||200,ok:((se=b==null?void 0:b.headers)==null?void 0:se.status)==="200",json:async()=>{var Me;try{return(Me=b==null?void 0:b.body)!=null&&Me.length?JSON.parse(b.body):null}catch{throw Error("Not a JSON response")}},text:async()=>(b==null?void 0:b.body)||"",body:Mo((b==null?void 0:b.body)||""),redirected:!1,statusText:"",type:"basic",url:"",clone:function(){throw new Error("Function not implemented.")},bodyUsed:!1,arrayBuffer:function(){throw new Error("Function not implemented.")},blob:function(){throw new Error("Function not implemented.")},formData:function(){throw new Error("Function not implemented.")}};f(),Ju().then(()=>d(_))}),v=t!=null&&t.fos?s.fosSocket:s.socket;if(!v)throw Error(`No web socket transport available: ${t}`);v==null||v.send(l)})};exports.BASE_URL="kos:";exports.kosFetch=Qu;if(process.env.KOS_MOCK_FETCH==="true"){const e=process.env.KOS_PORT||"9999";exports.kosFetch=fetch,exports.BASE_URL=`http://localhost:${e}`}const eh=m.createLogger({name:"kos-model-visitor",group:"kos-ui-core"});class th{constructor(){a(this,"visitedModels",new Set);this.visitedModels=new Set}start(t){var o;if(t.id===void 0)throw new Error("rootModel must have an id");const s=E.getInstance().modelManager.getModelById(t.id);if(!s)throw new Error(`Could not find rootModel with id: ${t.id}`);this.visitedModels.clear(),(o=s.accept)==null||o.call(s,this)}visit(t){var o;if(this.visitedModels.has(t.modelId)){eh.info(`model ${t.modelId} already visited`);return}const s=!!this.visitModel(t.modelData,this);this.visitedModels.add(t.modelId),!s&&((o=t.getChildren)==null||o.call(t).forEach(r=>{var n;(n=r.accept)==null||n.call(r,this)}))}}const Ji=()=>({isMock:!1,URL:exports.BASE_URL}),sh=m.createLogger({name:"kos-service-request"}),oh="errUnknown";async function es(e,t,s,o,r){const n=o!=null&&o.path?Object.keys(o.path).reduce((h,f)=>String(h).replace(`{${f}}`,o==null?void 0:o.path[f]),String(e)):String(e),i=o!=null&&o.query?Object.keys(o.query).map(h=>`${h}=${o.query[h]}`).join("&"):"",c=`${Ji().URL}${n}${i?`?${encodeURIComponent(i)}`:""}`;sh.debug(`fullUrl: ${c}`);const l={method:String(t).toUpperCase(),body:null,...s};r&&(l.body=JSON.stringify(r));const d=await exports.kosFetch(c,l);return d.status<200||d.status>=400?[`${d.statusText||oh}`,null]:[null,(await d.json()).data]}function Qo(){return{get:(e,t,s)=>es(e,"get",s,t),post:(e,t,s,o)=>es(e,"post",o,t,s),put:(e,t,s,o)=>es(e,"put",o,t,s),delete:(e,t,s)=>es(e,"delete",s,t)}}class Xi{constructor(){a(this,"middlewares",[])}use(t){this.middlewares.push(t)}async execute(t){let s=0;const o=async()=>{s++,s<this.middlewares.length&&await this.middlewares[s](t,o)};await this.middlewares[s](t,o)}}const rh=async(e,t)=>{const s=new Xi;t.forEach(r=>s.use(r));const o={data:e,result:{}};return await s.execute(o),o.result},tt=e=>({type:e,build:(t,s)=>E.getInstance().modelManager.createModelInstance(e,t,s).data,buildAsync:async(t,s)=>{const o=E.getInstance().modelManager.createModelInstance(e,t,s);return await o.model.whenInitialized(),o.data}}),nh=e=>{E.getInstance().modelManager.registerModel(e)},ih=(e,t)=>{E.getInstance().modelManager.registerCompanionModel(e,t)},Qi=Symbol("KosObservableData");class ea{constructor(){a(this,"map");a(this,"atomMap",new Map);a(this,"proxyHandler",{get:(t,s)=>{var o;return t[s]!==void 0?t[s]:this.atomMap.has(s)&&(o=this.atomMap.get(s))!=null&&o.reportObserved()?this.getValue(s):this.getValue(s)},set:(t,s,o)=>{var r;return this.setValue(s,o),this.atomMap.has(s)||this.atomMap.set(s,w.createAtom(s.toString())),(r=this.atomMap.get(s))==null||r.reportChanged(),!0},ownKeys:()=>Array.from(this.map.keys())});this.map=w.observable.map(new Map)}setValue(t,s){this.map.set(t,s)}getValue(t){return this.map.get(t)}has(t){return this.map.has(t)}get entries(){return Array.from(this.map.entries())}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}setValues(t){t&&Object.keys(t).forEach(s=>{this.setValue(s,t[s])})}get proxy(){return new Proxy(this,this.proxyHandler)}}ea.prototype[Qi]=!0;function ah(e,t){return new Proxy(e,{construct:(s,o)=>{const r=new e(...o);return r.setValues(t),r.proxy}})}const be=e=>{const t=ah(ea,e);return new t(e)},nn="/kos/ui/internal/heartbeat/",ch=({relationshipId:e,destinationAddress:t,onAbort:s,waitTime:o,beatTime:r})=>{const n=E.getInstance().transport,i=new AbortController;let c=performance.now();const l=n.subscribeTopic({topic:`${nn}${e}`,callback:()=>{c=performance.now()}}),d=o??3e3,u=window.setInterval(()=>{let _=performance.now()-c;_=_/1e3,_>d/1e3&&i.abort()},d),h=r??2e3,f=window.setInterval(()=>{ki({msg:{},options:{topic:`${nn}${e}`,destinationAddress:t}})},h),v=()=>{window.clearInterval(f),window.clearInterval(u),l()},b=()=>{v(),s&&s(),i.signal.removeEventListener("abort",b)};return i.signal.addEventListener("abort",b),{cleanUpHeartbeat:v}},ta=(...e)=>t=>e.reduce((s,o)=>o(s),t),lh={maxAttempts:5,baseDelayMs:100,backoffFactor:1.5};async function dh(e,t){let s=1;const o={...lh,...t},{maxAttempts:r,baseDelayMs:n,backoffFactor:i}=o;let c=n;for(;s<=r;)try{return await e()}catch(l){if(m.error(`Attempt ${s} failed: ${l}`),s<r)c=n*Math.pow(i,s),await new Promise(d=>setTimeout(d,c)),s++;else throw l}throw new Error("All attempts failed")}const uh=m.createLogger({name:"kos-service-request"}),q=e=>({isMock:!1,URL:exports.BASE_URL}),hh=(e,t,s)=>async({id:o,tracker:r,urlOverride:n,ordered:i,studio:c,fos:l,bridge:d,destinationAddress:u})=>{const h={method:"DELETE"};e&&(h.destinationAddress=e),r&&(h.tracker=r),st(h,{ordered:i,studio:c,fos:l,bridge:d,destinationAddress:u});const f=await s(n||`${t}/${o}`,h);if(!f.ok)throw Error(`There was a problem deleting the model; returned status ${f.status}`);return await f.json()},st=(e,{ordered:t,studio:s,fos:o,destinationAddress:r,bridge:n,timeout:i})=>(i&&(e.timeout=i),t&&(e.ordered=t),s&&(e.studio=s),o&&(e.fos=o),n&&(e.bridge=n),(r||r==="")&&(e.destinationAddress=r),e),gh=(e,t,s)=>async({urlOverride:o,ordered:r,studio:n,fos:i,bridge:c,timeout:l,destinationAddress:d})=>{const u={method:"GET"};e&&(u.destinationAddress=e),st(u,{timeout:l,ordered:r,studio:n,fos:i,bridge:c,destinationAddress:d});const f=await s(o||t,u);if(!f.ok){let b;try{b=await f.json()}catch{}throw new le(`There was a problem retrieving the model; returned status ${f.status}`,b)}return await f.json()},fh=(e,t,s)=>async({urlOverride:o,ordered:r,studio:n,fos:i,bridge:c,tracker:l,timeout:d,destinationAddress:u})=>{const h={method:"GET"};e&&(h.destinationAddress=e),l&&(h.tracker=l),st(h,{timeout:d,ordered:r,studio:n,fos:i,bridge:c,destinationAddress:u});const f=o||t;uh.debug(`resolvedUrl: ${f}`);const v=await s(f,h);if(!v.ok){let _;try{_=await v.json()}catch{}throw new le(`There was a problem retrieving the model; returned status ${v.status}`,_)}return await v.json()},mh=(e,t,s)=>async({urlOverride:o,id:r,ordered:n,studio:i,fos:c,bridge:l,timeout:d,destinationAddress:u})=>{const h={method:"GET"};e&&(h.destinationAddress=e),st(h,{timeout:d,ordered:n,studio:i,fos:c,bridge:l,destinationAddress:u});const f=o||`${t}/${r}`,v=await s(f,h);if(!v.ok){let _;try{_=await v.json()}catch{}throw new le(`There was a problem retrieving the model; returned status ${v.status}`,_)}return await v.json()};class le extends Error{constructor(s,o){super(s);a(this,"payload");this.name="FetchException",this.payload=o}}const an=(e,t,s)=>async({model:o,urlOverride:r,ordered:n,tracker:i,studio:c,fos:l,bridge:d,timeout:u,destinationAddress:h})=>{const f={method:"POST",body:typeof o=="string"?o:JSON.stringify(o)};e&&(f.destinationAddress=e),i&&(f.tracker=i),st(f,{timeout:u,ordered:n,studio:c,fos:l,bridge:d,destinationAddress:h});const v=await s(r||t,f);if(!v.ok){let _;try{_=await v.json()}catch{}throw new le(`There was a problem sending the POST data; returned status ${v.status}`,_)}return await v.json()},cn=(e="POST",t,s,o)=>async({model:r,id:n,urlOverride:i,ordered:c,studio:l,fos:d,bridge:u,timeout:h,destinationAddress:f})=>{const v={method:e};r&&(v.body=JSON.stringify(r)),t&&(v.destinationAddress=t),st(v,{timeout:h,ordered:c,studio:l,fos:d,bridge:u,destinationAddress:f});const b=await o(i||`${s}/${n}`,v);if(!b.ok){let I;try{I=await b.json()}catch{}throw new le(`There was a problem modifying the model; returned status ${b.status}`,I)}return await b.json()},Y={build:({destinationAddress:e="",basePath:t,getAllPath:s,getOnePath:o,deleteModelPath:r,addModelPath:n,modifyModelPath:i,mock:c=!1})=>{const l=c?fetch:exports.kosFetch;return{getAll:gh(e,s||t,l),getModelById:mh(e,o||t,l),getOne:fh(e,o||t,l),addModel:an(e,n||t,l),deleteModel:hh(e,r||t,l),modifyModel:cn("POST",e,i||t,l),putModel:cn("PUT",e,i||t,l),postModel:an(e,n||t,l)}}},ph=et(),sa=()=>`kos-${ph}`,yh=e=>!!e&&!e.includes("VM_SERVICE")&&e.startsWith(sa()),er=async(e,t=6e4)=>new Promise((s,o)=>{const{unsubscribe:r}=U(e,i=>{T.debug(`recieved response for refId ${e}: ${i}`),r(),clearTimeout(n);try{const c=i!=null&&i.body?JSON.parse(i.body):{};s(c)}catch{const c=(i==null?void 0:i.body)||{};s(c)}}),n=setTimeout(()=>{r(),o(Error(`Request with ID ${e} timed out. Cancelling.`))},t)}),bh=async(e,t,s)=>{const o=er(s),r=await Promise.allSettled([e(t),o]);if(r[0].status==="fulfilled"){if(r[1].status==="rejected")throw Error(r[1].reason);if(r[0].value){if(r[1].value.error)throw Error(r[1].value.error);return r[0].value.data=r[1].value,r[0].value}}else throw Error(r[0].reason)},vh=async({topic:e,msg:t,requestId:s})=>{const o=s??et(),r=er(o);F(e,t,{sync:o});const n=await r;if(n.error)throw Error(n.error);return n},he=new Map;class oa{constructor(t){a(this,"_context");a(this,"_parent");a(this,"_id");this._id=t,this._context=new w.ObservableMap({}),this._parent="",w.makeAutoObservable(this)}setParent(t){z(()=>{this._parent=t})}get id(){return this._id}get context(){return this._context}get parentModel(){var t;if(this._parent)return(t=Re(this._parent))==null?void 0:t.model}get(t){var s;if(this._context.has(t))return this._context.get(t);if(this._parent)return(s=he.get(this._parent))==null?void 0:s.get(t)}set(t,s){this._context.set(t,s)}remove(t){this._context.delete(t)}clear(){this._context.clear()}}const x={createContext:(e,t)=>{const s=he.get(e)??new oa(e);if(t){if(!he.has(t))throw new Error(`Parent context ${t} does not exist`);s.setParent(t)}else e!=="root"&&s.setParent("root");return he.set(e,s),s},getContext:e=>he.get(e),deleteContext:e=>{he.delete(e)},setParentContext:(e,t)=>{var s;if(!he.has(t))throw new Error(`Parent context ${t} does not exist`);(s=he.get(e))==null||s.setParent(t)},rootContext:()=>he.get("root")};x.createContext("root");const wh=e=>x.getContext(e.id);function Mh(e,t){return e.length!==t.length?!1:e.every(s=>t.includes(s))}class tr{constructor({container:t,key:s}){a(this,"_container");a(this,"_map");a(this,"_key");a(this,"data");this._container=t,this._map=w.observable.map(new Map),this._key=s,this.data=be(),this.generateIndex(),w.autorun(()=>{this._container.revision&&this.generateIndex()}),w.makeAutoObservable(this)}refresh(){this.generateIndex()}addItemToIndex(t,s,o=this._map,r=this.data){const n=o.get(t)||new Set;n.add(s),o.set(t,n),r[t]=Array.from(n)}resolveIndex(t,s){this.data.keys.filter(r=>!Object.keys(s).includes(r)).forEach(r=>{delete this.data[r],this._map.delete(r)}),Object.keys(s).forEach(r=>{const n=s[r],i=this.data[r]||[];if(Mh(n,i))m.debug(`KosContainerIndex - Index ${r} is the same`);else{this.data[r]=n;const c=t.get(r)||new Set;this._map.set(r,c)}})}generateIndex(){w.runInAction(async()=>{const t=new Map,s={};for(const o of this._container.data){const r=typeof this._key=="function"?await this._key(o):o[this._key];Array.isArray(r)?r.forEach(n=>{this.addItemToIndex(n,o,t,s)}):typeof r=="string"||typeof r=="number"?this.addItemToIndex(String(r),o,t,s):typeof r=="boolean"&&this.addItemToIndex(String(r),o,t,s)}this.resolveIndex(t,s)})}get keys(){return Array.from(this._map.keys())}get index(){return this._map}getByKey(t){const s=this._map.get(t);return s?Array.from(s):[]}}function _h(e,t,s=[]){const o=Object.getOwnPropertyDescriptors(e);return Object.keys(o).filter(i=>w.isComputedProp(e,i)).filter(i=>s.includes(i)).map(i=>w.reaction(()=>e[i],(c,l)=>{t({name:i,newValue:c,oldValue:l})}))}const at=m.createLogger({name:"kos-container-model"});class ue{constructor(t){a(this,"_data");a(this,"_sortKey");a(this,"_revision");a(this,"_index");a(this,"_optionsMap");a(this,"_disposerMap",new Map);a(this,"_parentId");a(this,"idx");this._data=w.observable.map(new Map),this._sortKey=t==null?void 0:t.sortKey,this._revision=1;const s=t!=null&&t.extensionId?$.indexExtension.loadIndexExtensions(t.extensionId):{},o=(t==null?void 0:t.indexMap)||{};this._optionsMap={...o,...s};const r=t!=null&&t.indexMap?Object.keys(t.indexMap).reduce((n,i)=>(n[i]=void 0,n),{}):{};this._index=w.observable.map(r),this.idx=be(),this._parentId=t==null?void 0:t.parentId,w.makeAutoObservable(this),this.init()}init(){Object.keys(this._optionsMap).forEach(t=>{const s=this._optionsMap[t],o=new tr({container:this,key:s});this._index.set(t,o),this.idx[t]=o.data})}[Symbol.iterator](){return this.data[Symbol.iterator]()}get index(){return this._index}get revision(){return this._revision}get indexKeys(){return Array.from(this.index.keys()).reduce((t,s)=>{var o;return t[s]=(o=this.index.get(s))==null?void 0:o.keys,t},{})}sortFn(t,s){const o=this._sortKey;return o?String(t[o]).localeCompare(String(s[o]),void 0,{numeric:!0}):0}get data(){const t=Array.from(this._data.values());return this._sortKey&&t.sort(this.sortFn.bind(this)),t}increment(){w.runInAction(()=>{this._revision=this._revision+1})}addAll(t){w.runInAction(()=>{t.forEach(s=>this.addModel(s,!0))}),this.increment()}removeAll(t){w.runInAction(()=>{t.forEach(s=>this.removeModel(s,!0)),this.increment()})}addModel(t,s){this._data.set(t.id||"",t),t.id&&this._parentId&&x.setParentContext(t.id,this._parentId),s||this.increment();const o=this._disposerMap.get(t.id);o&&(o(),this._disposerMap.delete(t.id));const r=Object.entries(this._optionsMap||{}),n=Object.values(this._optionsMap||{}),i=new Map(r.map(([u,h])=>[h,u])),c=u=>{var f,v;n.includes(u.name)&&((f=this.index.get(i.get(u.name)))==null||f.refresh());const h=r.filter(([,b])=>typeof b=="function");for(const[b]of h)(v=this.index.get(b))==null||v.refresh()},l=_h(t,c,n.filter(u=>typeof u=="string")),d=w.observe(t,c);this._disposerMap.set(t.id||"",()=>[d,...l].forEach(u=>u()))}removeModel(t,s){this._data.delete(t),s||this.increment();const o=this._disposerMap.get(t);o&&(o(),this._disposerMap.delete(t))}updateModel(t){this._data.set(t.id||"",t),this.increment()}getModel(t){return this._data.get(t)}getIndexKeys(t){return this.index.has(t)?this.index.get(t).keys??[]:(at.info(`index ${t} not found in ${Array.from(this.index.keys())}`),[])}getIndexByKey(t,s){if(this.index.has(t)){const o=this.index.get(t);return o.index.has(s)?o.getByKey(s):(at.info(`key ${s} not found in ${t} index: ${Array.from(o.index.keys())}`),[])}else return at.info(`index ${t} not found in ${Array.from(this.index.keys())}`),[]}async clear(){this._data.forEach(t=>{const s=t.id;Se(t).then(()=>{at.debug(`${s} destroyed, removing from map`),this.removeModel(s,!0)}).catch(o=>at.error(o))}),this.increment()}filter(t,s){return this.data.filter(t,s)}sort(t){return this.data.sort(t)}map(t,s){return this.data.map(t,s)}forEach(t,s){this.data.forEach(t,s)}toJSON(){return{indexes:this.indexKeys,data:this.data.map(s=>({id:s.id,type:s.constructor.name}))}}}const ho=m.createLogger({name:"kos-data-container"});class ra{constructor(t){a(this,"_data");a(this,"_sortKey");a(this,"_revision");a(this,"_index");a(this,"_optionsMap");a(this,"_disposerMap",new Map);a(this,"idx");this._data=w.observable.map(new Map),this._sortKey=t==null?void 0:t.sortKey,this._revision=1,this._optionsMap=(t==null?void 0:t.indexMap)||{};const s=t!=null&&t.indexMap?Object.keys(t.indexMap).reduce((o,r)=>(o[r]=void 0,o),{}):{};this._index=w.observable.map(s),this.idx=be(),w.makeAutoObservable(this,{}),this.init()}init(){Object.keys(this._optionsMap).forEach(t=>{const s=this._optionsMap[t],o=new tr({container:this,key:s});this._index.set(t,o),this.idx[t]=o.data})}[Symbol.iterator](){return this.data[Symbol.iterator]()}get index(){return this._index}get indexKeys(){return Array.from(this.index.keys()).reduce((t,s)=>{var o;return t[s]=(o=this.index.get(s))==null?void 0:o.keys,t},{})}get revision(){return this._revision}addAll(t){w.runInAction(()=>{t.forEach(s=>this.addModel(s))})}removeAll(t){w.runInAction(()=>{t.forEach(s=>this.removeModel(s))})}sortFn(t,s){const o=this._sortKey;return o?String(t[o]).localeCompare(String(s[o]),void 0,{numeric:!0}):0}get data(){const t=Array.from(this._data.values());return this._sortKey&&t.sort(this.sortFn.bind(this)),t}increment(){w.runInAction(()=>{this._revision=this._revision+1})}addModel(t,s){const o=w.isObservable(t)?t:w.observable.object(t),r=this._disposerMap.get(t.id);r&&(r(),this._disposerMap.delete(t.id)),this._data.set(o.id||"",o),s||this.increment();const n=w.observe(o,i=>{Object.values(this._optionsMap||{}).includes(i.name)&&this.increment()});this._disposerMap.set(o.id||"",n)}removeModel(t){this._data.delete(t),this.increment();const s=this._disposerMap.get(t);s&&(s(),this._disposerMap.delete(t))}updateModel(t){const s=w.observable.object(t);this._data.set(s.id||"",s),this.increment()}getModel(t){return this._data.get(t)}getIndexKeys(t){return this.index.has(t)?this.index.get(t).keys??[]:(ho.info(`index ${t} not found in ${Array.from(this.index.keys())}`),[])}getIndexByKey(t,s){if(this.index.has(t)){const o=this.index.get(t);return o.index.has(s)?o.getByKey(s):(ho.info(`key ${s} not found in ${t} index: ${Array.from(o.index.keys())}`),[])}else return ho.info(`index ${t} not found in ${Array.from(this.index.keys())}`),[]}async clear(){this._data.clear(),this.increment()}filter(t,s){return this.data.filter(t,s)}sort(t){return this.data.sort(t)}map(t,s){return this.data.map(t,s)}forEach(t,s){this.data.forEach(t,s)}toJSON(){return{indexes:this.indexKeys,data:this.data.map(s=>({id:s.id}))}}}class Eh{constructor({type:t,model:s,childRegistration:o}){a(this,"type");a(this,"childRegistration");a(this,"model");this.type=t,this.model=s,this.childRegistration=o}get factory(){return V.Factory.create(this.type)}get registration(){return{[this.type]:{class:this.model,singleton:!1,factory:this.factory},...this.childRegistration}}get predicate(){return te(this.type)}}class Ih{constructor({type:t,model:s,childRegistration:o}){a(this,"type");a(this,"model");a(this,"childRegistration");this.type=t,this.model=s,this.childRegistration=o}get factory(){return V.Singleton.create(this.type)}get registration(){return{[this.type]:{class:this.model,singleton:!0,factory:this.factory},...this.childRegistration}}get predicate(){return te(this.type)}}class na{constructor(){a(this,"_token");w.makeAutoObservable(this),U("token",t=>{this.token=t==null?void 0:t.body})}get token(){return this._token}set token(t){this._token=t}}class ia{constructor(){a(this,"routes",[]);a(this,"openApiRoutes",[])}use(t,s,...o){this.routes.push({method:t,path:s,middlewares:o});const r=this.extractOpenApiParams(s);this.openApiRoutes.push({method:t,path:s,parameters:r})}async handle(t,s){var c;const{path:o,query:r,params:n}=this.extractPathParams(t.path),i={...t,params:n,query:r};for(const l of this.routes){const d=this.matchRoute(l.path,o);if(l.method===t.method&&d){i.params=d;let u=0;const h=async()=>{if(u<l.middlewares.length){const f=l.middlewares[u++];await f(i,s,h)}};await h();return}}(c=s.status)==null||c.call(s,404).send({error:"Route not found"})}extractOpenApiParams(t){return t.split("/").filter(s=>s.startsWith(":")).map(s=>({name:s.slice(1),in:"path",required:!0,schema:{type:"string"}}))}generateOpenApiSpec(){const t={};for(const s of this.openApiRoutes)t[s.path]||(t[s.path]={}),t[s.path][s.method.toLowerCase()]={summary:s.description||`Handles ${s.method} ${s.path}`,parameters:s.parameters||[],responses:{200:{description:"Successful response"}}};return{openapi:"3.0.0",info:{title:"Kos Router API",version:"1.0.0",description:"Dynamically generated OpenAPI documentation"},paths:t}}extractPathParams(t){const[s,o]=t.split("?"),r=this.parseQueryParams(o);for(const n of this.routes){const i=this.matchRoute(n.path,s);if(i)return{path:s,query:r,params:i}}return{path:s,query:r,params:{}}}matchRoute(t,s){const o=t.split("/").filter(Boolean),r=s.split("/").filter(Boolean);if(o.length!==r.length)return null;const n={};for(let i=0;i<o.length;i++)if(o[i].startsWith(":"))n[o[i].slice(1)]=decodeURIComponent(r[i]);else if(o[i]!==r[i])return null;return n}parseQueryParams(t){return t?t.split("&").reduce((s,o)=>{const[r,n]=o.split("=").map(decodeURIComponent);return s[r]=n??"",s},{}):{}}}const aa=m.createLogger({name:"intent-service"}),Th=e=>{Go(`/kos/intent/${e.type}`)?F(`/kos/intent/${e.type}`,e.options,{"kos.intent.type":e.type}):aa.info(`No subscribers for intent ${e.type}. Intent not sent.`)},$h=async e=>new Promise(t=>{const{type:s,options:o}=e;if(Go(`/kos/intent/${e.type}`)){const r=et(),{unsubscribe:n}=U(r,c=>{clearTimeout(i),n(),c&&(c.headers=c.headers||{},c.headers["kos.intent.type"]=s,c.headers.responseId=r),t([null,{body:c==null?void 0:c.body,payload:c}])}),i=setTimeout(()=>{n(),t([`Intent ${s} timed out after 1 second`,null]),console.warn(`Intent ${s} timed out after 1 second`)},1e3);F(`/kos/intent/${s}`,o,{"kos.intent.type":s,sync:r})}else aa.info(`No subscribers for intent ${e.type}. Intent not sent.`),t([null,{body:void 0,payload:void 0}])}),To=w.when,sr=w.computed,z=w.runInAction,N=w.autorun,ca=w.reaction,or=w.observable,rr="Not Assigned",Oh="kos.trouble.added",Sh="kos.trouble.removed";var re=(e=>(e.TroubleRank="kos.trouble.rank.mapper",e.TroubleColor="kos.trouble.color.mapper",e.TroubleRole="kos.trouble.role.mapper",e))(re||{}),St=(e=>(e.TIME_CHANGE="/kos/internal/time/time",e.DAY_CHANGE="/kos/internal/time/day",e.TIMEZONE_CHANGE="/kos/internal/time/timezone",e))(St||{});const la=m.createLogger({name:"config-bean-service",group:"Services"}),nr=exports.BASE_URL,da=e=>(e==null?void 0:e.decimals)!==void 0,{postModel:Dh,getOne:Ah}=Y.build({destinationAddress:"",basePath:`${nr}/kos/config/`}),ua=async(e,t,s="/api/kos/config")=>(la.debug(`sending modify request for ConfigBean: ${e}`),Dh({model:t,urlOverride:`${nr}${s}/${e}`})),ha=async(e,t="/api/kos/config")=>(la.debug(`sending get request for ConfigBean: ${e}`),await Ah({urlOverride:`${nr}${t}/details/${e}/15`})),ir=e=>e.toLowerCase()==="true"||e.toLowerCase()==="false",Hs=e=>{try{const t=Number(e);return!isNaN(t)}catch{return!1}};function ga(e=[]){return e.reverse().reduce((t,s)=>{const{overrides:o}=s;return o&&(t={...t,...o}),t},{})}function fa(e,t="",s={}){for(const o in e)if(Object.prototype.hasOwnProperty.call(e,o)){const r=t?`${t}.${o}`:o;typeof e[o]=="object"&&e[o]!==null&&!Array.isArray(e[o])?fa(e[o],r,s):s[r]=e[o]}return s}const ma=(e,t)=>{const s=e.details[0].bean||ga(e.details[0].scopes),o=fa(s);w.runInAction(()=>{const r={...o};t.props.setValues(r)})},pa=(e,t)=>{w.runInAction(()=>{e.changes.forEach(s=>{const o=s.attr;let r=s.currentValue,n=s.previousValue;typeof r=="string"&&ir(r)&&(r=r.toLowerCase()=="true",n=(n==null?void 0:n.toLowerCase())=="true"),typeof r=="string"&&Hs(r)&&(r=Number(r),n=Number(n)),t.props[o]=r,t.prevProps[o]=n})})},ya=e=>Object.fromEntries(e.props.entries),Ch=e=>t=>s=>e.build(t,s);var Rh=Object.defineProperty,Ph=Object.getOwnPropertyDescriptor,ba=(e,t,s,o)=>{for(var r=o>1?void 0:o?Ph(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Rh(t,s,r),r};function Lh(e,t){for(const s of e)if(new RegExp(`^${s}$`).test(t))return s}const ar="config-bean-model",ts=m.getLogger(ar),xh=Ae("path");let ys=class{constructor(e,t){a(this,"_modifyConfigBean");a(this,"_getConfigBean");a(this,"_schema");a(this,"id");a(this,"path");a(this,"props");a(this,"prevProps");a(this,"serviceBasePath");Object.assign(this,t),this.id=e,this.path=t.path,this.serviceBasePath=t.serviceBasePath;const{modifyConfigBean:s=ua,getConfigBean:o=ha}=t;this._modifyConfigBean=s,this._getConfigBean=o,this.props=be(),this.prevProps=be()}get values(){return this.props.values}async ready(){ts.debug(`readying config bean ${this.path}`),ts.debug(`complete readying config bean ${this.path}`)}async load(){ts.debug(`loading config bean ${this.path}`);const e=await this._getConfigBean(this.path,this.serviceBasePath);if(e!=null&&e.data){const t=e.data;ma(t,this),ts.debug(this.values);const s=e==null?void 0:e.data.details[0].schema;z(()=>{s&&(this._schema=s)})}}get schemaKeys(){var e;return Object.keys(((e=this._schema)==null?void 0:e.schema)||{})}getSchemaForProperty(e){var s,o;if(this.schemaKeys.includes(e))return(s=this._schema)==null?void 0:s.schema[e];const t=Lh(this.schemaKeys,e);if(t)return(o=this._schema)==null?void 0:o.schema[t]}async updateProperty(e,t){this.props[e]=t,await this.updateConfigBean()}async updateConfigBean(){const e=ya(this);await this._modifyConfigBean(this.path,e,this.serviceBasePath)}handleConfigBeanUpdated(e){pa(e,this)}};ba([R({topic:`/kos/config/${xh}`,websocket:!0})],ys.prototype,"handleConfigBeanUpdated",1);ys=ba([S(ar)],ys);const Ct=new ce({class:ys,type:ar}),Gs=({path:e,lazy:t,serviceBasePath:s})=>(o,r)=>{o[L]=o[L]||{},o[L][r]={modelType:Ct.type,id:`${Ct.type}-${e}`,options:{path:e,serviceBasePath:s},lifecycle:k.INIT,lazy:t}},{URL:va}=q(),{getOne:kh,getAll:Fh}=Y.build({basePath:`${va}/api/kos/regions/info`}),wa=async()=>await kh({}),Ma=async()=>await Fh({urlOverride:`${va}/api/kos/regions`}),Nh=Object.freeze(Object.defineProperty({__proto__:null,getRegionInfo:wa,getRegions:Ma},Symbol.toStringTag,{value:"Module"}));var Z=(e=>(e[e.family=0]="family",e[e.scale=1]="scale",e[e.offset=2]="offset",e[e.decimals=3]="decimals",e[e.alias=4]="alias",e[e.system=5]="system",e))(Z||{});const _a={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 Uh(e,t){const s=t.id,o=t.units.reduce((r,n)=>{const i=[n.measure,n.scale,n.offset,n.decimals,n.alias,s];return r[n.name]=i,n.alias&&(r[n.alias]=i),r},{..._a});return{...e,...o}}function jh(e,t){const s=t.id,o=t.units.reduce((r,n)=>{const i=r[n.measure]||{},c=i[s]||{};i[s]=c;const l=[n.measure,n.scale,n.offset,n.decimals,n.alias,s];return c[n.name]=l,Object.hasOwn(n,"default")&&Object.defineProperty(c,"default",{value:l,writable:!0,enumerable:!0,configurable:!0}),r[n.measure]=i,n.alias&&(r[n.alias]=i),r},{time:{[s]:{..._a}}});return Object.keys(o).forEach(r=>{e[r]={...e[r],...o[r]}}),e}function Bh(e,t){const s=t.id,o=t.units.reduce((r,n)=>{const i=r[n.measure]||{};return Object.hasOwn(n,"default")&&(i[s]=n.name),r[n.measure]=i,r},{time:{[s]:"millisecond"}});return Object.keys(o).forEach(r=>{e[r]={...e[r],...o[r]}}),e}var Kh=Object.defineProperty,Hh=Object.getOwnPropertyDescriptor,cr=(e,t,s,o)=>{for(var r=o>1?void 0:o?Hh(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Kh(t,s,r),r};const us="region-info-model",ct=m.createLogger({name:"region-info-model"});let Rt=class{constructor(e){a(this,"id");a(this,"unitSystemMap");a(this,"measureMap");a(this,"defaultMeasureMap");a(this,"regionMap");a(this,"timeFormats");a(this,"dateFormats");a(this,"unitSystems");a(this,"regionSource");a(this,"region");a(this,"regions",[]);a(this,"timeZoneMap",{});this.id=e,this.unitSystems={},this.unitSystemMap={},this.measureMap={},this.defaultMeasureMap={},this.timeFormats={},this.regions=[],this.dateFormats={},this.timeZoneMap={},this.regionMap={}}get availableRegions(){return this.regions}get defaultUnitSystem(){return String(this.regionSource.props.unitSystemId).toLowerCase()||""}get unitSystemId(){return this.defaultUnitSystem}get timeFormatId(){const e=this.regionSource.props.timeFormatId;if(!e)return"";const t=String(e),s=this.timeFormats[t];return s?String(s.id):""}get selectedTimeFormat(){const e=this.timeFormatId;return e?String(this.timeFormats[e].format):"HH:mm:ss"}get is12HourTimeFormat(){const e=this.timeFormatId;return e?this.timeFormats[e].ampm:!0}get dateFormatId(){const e=this.regionSource.props.dateFormatId;if(!e)return"";const t=String(e);return t?this.dateFormats[t].id:""}get selectedDateFormat(){const e=this.dateFormatId;return e?this.dateFormats[e].format:""}get selectedDateOrder(){const e=this.dateFormatId;return e?this.dateFormats[e].order.toLowerCase():"dmy"}get selectedCountry(){return this.regionSource.props.country||"en"}get selectedTimeZone(){return this.regionSource.props.timeZone||""}get timeZones(){return this.regionId?this.timeZoneMap[this.regionId]||[]:[]}get allTimeZones(){return Intl.supportedValuesOf("timeZone")}get regionId(){return this.region.props.regionId||""}get selectedRegion(){return this.regionMap[this.regionId]}get selectedUnitSystem(){return String(this.regionSource.props.unitSystemId)||""}get timeFormatOptions(){return Object.keys(this.timeFormats).map(e=>({id:e,format:this.timeFormats[e].format,ampm:this.timeFormats[e].ampm}))}get dateFormatOptions(){return Object.keys(this.dateFormats).map(e=>({id:e,format:this.dateFormats[e].format,order:this.dateFormats[e].order}))}get unitSystemOptions(){return Object.keys(this.unitSystems).map(e=>({id:e,name:e}))}setSelectedTimeFormat(e){if(!this.timeFormatOptions.find(t=>t.id===e))throw Error(`Invalid time format id. Must be one of ${this.timeFormatOptions.map(t=>t.id).join(", ")}`);this.regionSource.updateProperty("timeFormatId",e)}setSelectedDateFormat(e){if(!this.dateFormatOptions.find(t=>t.id===e))throw Error(`Invalid date format id. Must be one of ${this.dateFormatOptions.map(t=>t.id).join(", ")}`);this.regionSource.updateProperty("dateFormatId",e)}setSelectedUnitSystem(e){if(!this.unitSystemOptions.find(t=>t.id===e))throw Error(`Invalid date format id. Must be one of ${this.unitSystemOptions.map(t=>t.id).join(", ")}`);this.regionSource.updateProperty("unitSystemId",e)}getUnitSystem(e){if(!e)return this.defaultUnitSystem;const t=e==="drt"?"second":e,s=this.unitSystemMap[t];if(!s)throw Error(`No unit found with name: ${t}. Unit should be one of ${Object.keys(this.unitSystemMap).join(", ")}`);return s[Z.system]}getUnitMeasure(e){const t=e==="drt"?"second":e,s=this.unitSystemMap[t];if(!s)throw Error(`No unit found with name: ${t}. Unit should be one of ${Object.keys(this.unitSystemMap).join(", ")}`);return s[Z.family]}getDefaultUnitDecimalPlaces(e,t,s){if(!e||!t)throw Error("Measure and unit system are required");const o=s==="drt"?"second":s,r=this.measureMap[e];if(!r)throw Error(`No unit systems found for measure: ${e}. Measure should come from list of measures: ${Object.keys(this.measureMap).join(", ")}`);const n=r[t.toLowerCase()];if(!n)throw Error(`No unit system found for measure: ${e} and unit system: ${t}. Unit system should come form list of unit systems: ${Object.keys(r).join(", ")}`);const i=n[o||"default"];if(!i)throw Error(`No unit "${o||"default"}" found for measure: ${e} and unit system: ${t}. Unit should come from list of units: ${Object.keys(n).join(", ")}`);return i[Z.decimals]}getDefaultUnitForMeasure(e,t){if(!e||!t)throw Error("Measure and unit system are required");const s=this.defaultMeasureMap[e];if(!s)throw Error(`No unit systems found for measure: ${e}. Measure should come from list of measures: ${Object.keys(this.measureMap).join(", ")}`);const o=s[t.toLowerCase()];if(!o)throw Error(`No unit system found for measure: ${e} and unit system: ${t}. Unit system should come form list of unit systems: ${Object.keys(s).join(", ")}`);return o}convertByUnit(e,t,s){if(t[Z.family]!==s[Z.family])throw new Error(`Cannot convert between units of different families: ${t[Z.family]} and ${s[Z.family]}`);const o=t[Z.offset],r=t[Z.scale],n=s[Z.scale],i=s[Z.offset],c=s[Z.decimals];return((e-o)/(r/n)+i).toFixed(c)}convertByUnitName(e,t,s){const o=this.unitSystemMap[t],r=this.unitSystemMap[s];if(!o||!r)throw new Error(`No unit found with name: ${t} or ${s}. Unit should be one of ${Object.keys(this.unitSystemMap).join(", ")}`);return this.convertByUnit(e,o,r)}convert(e,t,s){var c,l;if(t.unit&&s.unit)return this.convertByUnitName(e,t.unit,s.unit);const o=t.unit||"",r=s.unit||"";let n=this.unitSystemMap[o],i=this.unitSystemMap[r];if(!i&&s.measure&&s.system){const d=this.measureMap[s.measure];if(!d)throw Error(`Could not find measure ${s.measure}. Measure should be one of ${Object.keys(this.measureMap).join(", ")}`);i=(c=d[s.system])==null?void 0:c.default,i||ct.info("Could not find default unit for measure",s.measure)}if(!n&&t.measure&&t.system){const d=this.measureMap[t.measure];if(!d)throw Error(`Could not find measure ${s.measure}. Measure should be one of ${Object.keys(this.measureMap).join(", ")}`);n=(l=d[t.system])==null?void 0:l.default,n||ct.info("Could not find default unit for measure",t.measure)}return!n||!i?(ct.warn("Could not find unit to convert to or from. Return value as is"),String(e)):this.convertByUnit(e,n,i)}async init(){ct.debug("initializing region info")}async load(){ct.debug("loading region info");const e=await Ma();e&&(this.regions=e.data.map(s=>s.id),this.timeZoneMap=e.data.reduce((s,o)=>({...s,[o.id]:o.timeZones}),this.timeZoneMap),this.regionMap=e.data.reduce((s,o)=>({...s,[o.id]:o}),{}));const t=await wa();t&&(this.unitSystems=t.data.unitSystems.reduce((s,o)=>{const r={id:o.id,name:o.id};return s[o.id]=r,s},this.unitSystems),this.unitSystemMap=t.data.unitSystems.reduce(Uh,{}),this.measureMap=t.data.unitSystems.reduce(jh,{}),this.defaultMeasureMap=t.data.unitSystems.reduce(Bh,{}),this.timeFormats=t.data.timeFormats.reduce((s,o)=>({...s,[o.id]:o}),{}),this.dateFormats=t.data.dateFormats.reduce((s,o)=>({...s,[o.id]:o}),{}))}async ready(){var e,t;await((t=(e=this.regionSource).ready)==null?void 0:t.call(e))}};cr([Gs({path:"kos:service:region:settings"})],Rt.prototype,"regionSource",2);cr([Gs({path:"kos:service:region"})],Rt.prototype,"region",2);Rt=cr([S(us)],Rt);const G={registration:{[us]:{class:Rt,singleton:!0}},type:us,factory:V.Singleton.create(us)},bs=({source:e,defaultSystem:t="si",defaultMeasure:s})=>{let o={system:t,measure:s};return typeof e=="string"?o={...o,unit:e}:o={...o,...e},o},lr=(e,t,s)=>{const{model:o}=Re(G.type);if(!o)throw new Error("RegionInfo model not found");if(!ps(o))throw new Error("RegionInfo model not ready");const r={system:o.defaultUnitSystem},n=bs({source:t}),i=bs({source:s||r,defaultMeasure:o.getUnitMeasure(n.unit||"")});return o.convert(e,n,i)};function ln(e,t,s){const o=t.toLowerCase().replace(/_/g,"-").replace(/s$/,""),r=new Intl.NumberFormat().resolvedOptions().locale??"en-US";try{const n=(s==null?void 0:s.mode)||"long",i=(s==null?void 0:s.maxDecimals)??2,c=(s==null?void 0:s.minDecimals)??0;return new Intl.NumberFormat(r,{style:"unit",unit:o,unitDisplay:n,minimumFractionDigits:c,maximumFractionDigits:i}).format(e)}catch{return t}}const Gh=(e,t,s,o)=>{const r=lr(e,t,s),n=bs({source:t}),{model:i}=Re(G.type);if(!i)throw new Error("RegionInfo model not found");const c=i.getUnitMeasure(n.unit||""),l={system:i.defaultUnitSystem},d=bs({source:s||l,defaultMeasure:i.getUnitMeasure(n.unit||"")}),u=i.getDefaultUnitForMeasure(c,d.system),h=i.getDefaultUnitDecimalPlaces(c,d.system),f={...o,minDecimals:(o==null?void 0:o.minDecimals)??h,maxDecimals:(o==null?void 0:o.maxDecimals)??h};return{value:r,unit:u||n.unit||"",display:ln(r,u||n.unit||"",{...f,mode:"long"}),shortDisplay:ln(r,u||n.unit||"",{...f,mode:"short"})}};function dn({start:e,end:t,count:s,decimals:o=0}){if(typeof e!="number"||typeof t!="number"||typeof s!="number")throw new Error("All input values should be numbers.");if(s<2)throw new Error("Count should be at least 2 for distribution.");if(e>=t)throw new Error("Start should be less than end.");const r=(t-e)/(s-1),n=[];for(let i=0;i<s;i++){const c=Math.round(e+i*r);n.push(c.toFixed(o))}return n}function un({start:e,end:t,interval:s,decimals:o=0}){if(typeof e!="number"||typeof t!="number"||typeof s!="number")throw new Error("All input values should be numbers.");if(s<=0)throw new Error("Interval should be a positive number.");if(e>=t)throw new Error("Start should be less than end.");const r=[];let n=e;for(;n<=t;)r.push(n.toFixed(o)),n+=s;return r[r.length-1]!==t.toString()&&r.push(t.toString()),r}const ke=(e,t)=>s=>!e||!t?s:Hs(s)?lr(Number(s),e,t):s,Vh=(e,t,s,o)=>{if((e==null?void 0:e.type)==="enum"||!(e!=null&&e.options))return[];if(e.options.type==="rangeCount")return dn(e.options).map(ke(s,o));if(e.options.type==="rangeInterval")return un(e.options).map(ke(s,o));if(e.options.type==="list"){const{list:r}=e.options;return r.map(ke(s,o))}else{if(e.options.type==="unitSystemRangeCount"&&t)return dn(e.options.unitSystems[t]).map(ke(s,o));if(e.options.type==="unitSystemRangeInterval"&&t)return un(e.options.unitSystems[t]).map(ke(s,o));if(e.options.type==="unitSystemList"&&t){const{list:r}=e.options.unitSystems[t];return r.map(ke(s,o))}}return[]},Yh=(e,t)=>{if(!((e==null?void 0:e.type)==="enum"||!(e!=null&&e.options)))return e.options.type==="unitSystemRangeCount"&&t?{type:"rangeCount",...e.options.unitSystems[t]}:e.options.type==="unitSystemRangeInterval"&&t?{type:"rangeInterval",...e.options.unitSystems[t]}:e.options.type==="unitSystemList"&&t?{type:"list",...e.options.unitSystems[t]}:e.options.type==="unitSystemKeypad"&&t?{type:"keypad",...e.options.unitSystems[t]}:e.options};var zh=Object.defineProperty,qh=Object.getOwnPropertyDescriptor,dr=(e,t,s,o)=>{for(var r=o>1?void 0:o?qh(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&zh(t,s,r),r};function Wh(e){return(e==null?void 0:e.type)==="enum"}function Zh(e){switch(e){case"s":return"second";case"ms":return"millisecond";case"min":return"minute";case"h":return"hour";case"d":return"day";case"w":return"week";case"m":return"month";case"y":return"year";case"ml":return"milliliter";default:return e}}function Jh(e,t){const s=new Date;s.setHours(0,0,0,0);const o=new Date(s.getTime()+e*1e3);return ye.format(o,t)}const hs="config-bean-prop-model",Fe=m.createLogger({name:"config-bean-prop-model"}),Xh=Ae("path"),Qh=Ae("serviceBasePath");let Pt=class{constructor(e,t){a(this,"id");a(this,"path");a(this,"attribute");a(this,"converter");a(this,"formatter");a(this,"optionsExpander");a(this,"serviceBasePath");a(this,"regionInfo");a(this,"bean");this.id=e,this.path=t.path,this.attribute=t.attribute,this.converter=t.converter,this.formatter=t.formatter,this.serviceBasePath=t.serviceBasePath,this.optionsExpander=t.optionsExpander}getDefaultUnitDecimalPlaces(e,t,s){if(!e)throw new Error("measure is required");if(!t)throw new Error("unitSystem is required");return da(this.displayOptions)?this.displayOptions.decimals:this.regionInfo.getDefaultUnitDecimalPlaces(e,t,s)}getDefaultUnitForMeasure(e,t){if(!e)throw new Error("measure is required");if(!t)throw new Error("unitSystem is required");return this.regionInfo.getDefaultUnitForMeasure(e,t)}get schemaType(){const e=this.bean.getSchemaForProperty(this.attribute);return e!=null&&e.type?e.type:"String"}get schemaFormat(){const e=this.bean.getSchemaForProperty(this.attribute);return e!=null&&e.format?Zh(e.format):""}get options(){var i;const e=this.regionInfo.defaultUnitSystem,t=this.getConverter(),s=((i=t==null?void 0:t.to)==null?void 0:i.system)??e,o=this.bean.getSchemaForProperty(this.attribute),r=Wh(o)?o.values:Vh(o,s,t==null?void 0:t.from,t==null?void 0:t.to),n=r.length>0?r.map(c=>({label:c,value:c})):[];return this.optionsExpander?typeof this.optionsExpander=="function"?this.optionsExpander(s,r):this.optionsExpander:n}convertUnit(e,t,s){const o=(e==null?void 0:e.measure)||s,r=(e==null?void 0:e.system)||t,n=e==null?void 0:e.unit;return{measure:o,system:r,unit:n}}getConverterUnits(){const e=this.regionInfo.defaultUnitSystem,t=this.getConverter();if(!t)throw Error("No converter defined");const s=t.measure,o=this.convertUnit(t.from,"si",s),r=this.convertUnit(t.to,e,s);return{backend:o,display:r}}set value(e){this.updateProperty(e)}get value(){return this.getValue(!0)}get rawValue(){return this.bean.props[this.attribute]}get significantValue(){var r,n;const e=this.value,t=this.regionInfo.defaultUnitSystem,s=this.getConverter(),o=(s==null?void 0:s.measure)||((r=s==null?void 0:s.to)==null?void 0:r.measure);if(!isNaN(e)&&s&&o){const i=this.getDefaultUnitDecimalPlaces(o,t,(n=s==null?void 0:s.to)==null?void 0:n.unit);try{const l=this.getFormatterOptions(s);if(l){let d=String(e);return d=l.formatToParts(Number(e))[0].value,Number(d)}}catch(l){Fe.info(`error formatting value ${e}`,l)}return Number(e).toFixed(i)}return e}get previousValue(){return this.getValue(!1)}getValue(e){const t=this.bean[e?"props":"prevProps"][this.attribute];if(typeof t=="boolean")return t;if(this.getConverter()&&!isNaN(t)){const{backend:o,display:r}=this.getConverterUnits();return this.regionInfo.convert(Number(t),o,r)}return t||""}async activate(){Fe.debug(`activating config bean ${this.id}`)}get displayValue(){const e=this.value;if(typeof e=="boolean")return String(e);if(this.schemaFormat==="drt"){const s=this.regionInfo.is12HourTimeFormat?"h:mm:ss a":"HH:mm:ss";return Jh(e,s)}if(!isNaN(e))try{const t=this.getConverter(),s=this.getFormatterOptions(t);if(s){let o=String(e);return o=s.format(Number(e)),o}}catch(t){Fe.error(`error formatting value ${e}`,t)}return String(e)}get unit(){const e=this.getConverter();if(!isNaN(this.value)){const t=this.getFormatterOptions(e);if(t){const o=t.formatToParts(Number(this.value)).find(r=>r.type==="unit");return(o==null?void 0:o.value)??this.getDefaultUnit(e)}}return this.getDefaultUnit(e)}get displayOptions(){var r;const e=this.bean.getSchemaForProperty(this.attribute),t=this.regionInfo.defaultUnitSystem,s=this.getConverter(),o=((r=s==null?void 0:s.to)==null?void 0:r.system)??t;return Yh(e,o)}getMeasureFromFormat(){const e=this.schemaFormat;return e?this.regionInfo.getUnitMeasure(e):""}getConverterFromFormat(){const e=this.getMeasureFromFormat();if(e){const t=this.regionInfo.selectedUnitSystem;return{unit:this.schemaFormat||this.regionInfo.getDefaultUnitForMeasure(e,t),measure:e}}return{}}getDefaultUnit(e){var o,r;const t=this.regionInfo.defaultUnitSystem,s=e==null?void 0:e.measure;return s?((o=e==null?void 0:e.to)==null?void 0:o.unit)||this.getDefaultUnitForMeasure(s,((r=e==null?void 0:e.to)==null?void 0:r.system)||t):this.getConverterFromFormat().unit}getFormatterOptions(e){var n,i,c;const t=this.regionInfo.defaultUnitSystem,s=e==null?void 0:e.measure,o=new Intl.NumberFormat().resolvedOptions().locale;let r=null;if(s||this.formatter){const l=s?{style:"unit",unit:this.getDefaultUnit(e)}:null,d=this.formatter||l;if(d){let u=typeof d=="function"?d(((n=e==null?void 0:e.to)==null?void 0:n.system)||t):d;s&&(u={unit:this.getDefaultUnit(e),...u},u.style==="unit"&&(u.maximumFractionDigits=u.maximumFractionDigits??this.getDefaultUnitDecimalPlaces(s,((i=e==null?void 0:e.to)==null?void 0:i.system)||t,(c=e==null?void 0:e.to)==null?void 0:c.unit)));try{r=new Intl.NumberFormat(o,{...u})}catch(h){Fe.error(`error creating formatter ${u}. Returning the raw value`,h)}}else Fe.debug(`no formatter found for config bean prop ${this.id}. Returning the raw value`)}return r}getConverter(){var o,r,n,i,c,l,d,u,h,f,v;const{unit:e,measure:t}=this.getConverterFromFormat(),s=e==="drt"?"second":e;if(this.converter){const b=(o=this.converter)==null?void 0:o.measure,_=(n=(r=this.converter)==null?void 0:r.to)==null?void 0:n.measure,I=(c=(i=this.converter)==null?void 0:i.from)==null?void 0:c.measure,C=b||_||I||t,se=((d=(l=this.converter)==null?void 0:l.to)==null?void 0:d.unit)||this.regionInfo.getDefaultUnitForMeasure(C,((h=(u=this.converter)==null?void 0:u.to)==null?void 0:h.system)??this.regionInfo.defaultUnitSystem),Me=((v=(f=this.converter)==null?void 0:f.to)==null?void 0:v.system)??this.regionInfo.getUnitSystem(se),nt=this.schemaFormat==="drt"?"second":this.schemaFormat||s;return{...this.converter,from:{unit:nt,...this.converter.from},to:{...this.converter.to,unit:se,system:Me},measure:C}}if(s&&t){const b=this.regionInfo.getDefaultUnitForMeasure(t,this.regionInfo.defaultUnitSystem),_=this.regionInfo.getUnitSystem(s),I=this.regionInfo.getUnitSystem(b);return{measure:t,to:{unit:_===I?s:b}}}}async updateProperty(e){Fe.debug(`updating property ${this.attribute} with value ${e}`);let t=e;if(this.getConverter()&&!isNaN(t)){const{backend:r,display:n}=this.getConverterUnits();t=this.regionInfo.convert(Number(t),n,r)}const o=Array.isArray(t)?JSON.stringify(t):String(t);await this.bean.updateProperty(this.attribute,o)}};dr([Ce({modelType:G.type})],Pt.prototype,"regionInfo",2);dr([Gs({path:Xh,serviceBasePath:Qh})],Pt.prototype,"bean",2);Pt=dr([S(hs)],Pt);const Pe={registration:{[hs]:{class:Pt,singleton:!1}},type:hs,factory:V.Factory.create(hs)};function eg(e){const{path:t,attribute:s,converter:o,formatter:r,lazy:n,optionsExpander:i,serviceBasePath:c}=e,l=o;return l&&(typeof l!="function"&&typeof l.from=="string"&&(l.from={unit:l.from}),typeof l!="function"&&typeof l.to=="string"&&(l.to={unit:l.to})),(d,u)=>{d[L]=d[L]||{},d[L][u]={modelType:Pe.type,id:`${t}-${s}`,options:{path:t,attribute:s,serviceBasePath:c,converter:l,formatter:r,optionsExpander:i},lifecycle:k.INIT,lazy:n}}}class tg{constructor(t,s){a(this,"futures");a(this,"defaultContext");a(this,"context");a(this,"disposers",new Map);a(this,"container");this.futures=or.map(new Map),this.context="",this.defaultContext=s||"",this.container=t,w.makeAutoObservable(this)}get allFutures(){return Array.from(this.futures.values())}get future(){return this.futures.get(this.defaultContext)}addFuture(t,s){this.futures.set(s||t.id,t),this.context=s||t.id;const o=N(()=>{var r,n;(t.endState||t.progress)&&((n=(r=this.container)==null?void 0:r.onFutureUpdate)==null||n.call(r,t))});this.disposers.set(s||t.id,o)}removeFuture(t){var s;this.futures.delete(t||this.context),(s=this.disposers.get(t||this.context))==null||s(),this.disposers.delete(t||this.context)}getFuture(t){return this.futures.get(t||this.context)}get futureMap(){return this.futures}}class ur{constructor(t){a(this,"disposer");a(this,"_future");a(this,"container");a(this,"onFutureUpdate");this._future=void 0,this.container=t,w.makeAutoObservable(this)}removeFuture(){var t;this._future=void 0,(t=this.disposer)==null||t.call(this),this.disposer=void 0}get future(){return this._future}getFuture(){return this._future}addFuture(t){this._future=t;const s=N(()=>{var o,r;(t.endState||t.progress)&&((r=(o=this.container)==null?void 0:o.onFutureUpdate)==null||r.call(o,t))});this.disposer=s}get allFutures(){return this._future?[this._future]:[]}get timeRemaining(){var t;return((t=this._future)==null?void 0:t.timeRemaining)||""}get status(){var t;return((t=this._future)==null?void 0:t.status)||"NOT_RESOLVED"}get progress(){var t;return((t=this._future)==null?void 0:t.progress)||-1}async cancel(){if(this._future)try{await this._future.cancelFuture()}catch(t){throw m.error(t),t}}}const Ea="future-model",ot=tt(Ea),Vs=m.createLogger({name:"future-service",group:"Services"}),{isMock:sg,URL:Yt}=q();var Ve=(e=>(e.Success="SUCCESS",e.Fail="FAIL",e.Aborted="ABORT",e.Canceled="CANCEL",e))(Ve||{});const{getAll:og,modifyModel:rg,addModel:ng,deleteModel:ig,postModel:ag}=Y.build({destinationAddress:"",basePath:`${Yt}/api/future`,mock:sg}),cg=async()=>await og({}),Ia=async(e,t="/api/kos/future")=>(Vs.info(`sending delete request for Future: ${e}`),await ig({id:e,urlOverride:`${Yt}${t}/${e}`})),Ta=async(e,t="/api/kos/future")=>(Vs.info("sending add request for Future"),await ng({model:e,urlOverride:`${Yt}${t}`})),lg=async(e,t,s="/api/kos/future")=>(Vs.info(`sending modify request for Future: ${e}`),rg({model:t,id:e,urlOverride:`${Yt}${s}/${e}`})),$a=async(e,t="/api/kos/future")=>(Vs.info(`sending cancel request for Future: ${e}`),ag({urlOverride:`${Yt}${t}/${e}/cancel`,ordered:!0,model:{}})),hr=e=>({id:String(e.id),progress:e.progress,remainingTimeMs:e.remainingTimeMs,endState:e.endState,reason:e.reason,clientData:e.clientData,reasonData:e.reasonData,note:e.note,tracker:e.tracker}),gr=(e,t)=>{m.debug(`future dto ${e.id} end state ${e.endState}`),m.debug(`future model ${t.id} end state ${t.endState}`),t.endState?m.debug(`future model ${t.id} is already complete`):(m.debug(`updating future model ${t.id}`),w.runInAction(()=>{const s=hr(e);z(()=>{Object.keys(s).forEach(o=>{o==="id"?(t.futureId=s.id,s.tracker||(t.id=s.id)):o==="tracker"?t.id=s.tracker:t[o]=s[o]})})}))},Oa=e=>t=>s=>e.build(String(t),s),fr=e=>t=>ta(hr,Oa(e)(t.tracker||t.id))(t);var dg=Object.defineProperty,ug=Object.getOwnPropertyDescriptor,Sa=(e,t,s,o)=>{for(var r=o>1?void 0:o?ug(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&dg(t,s,r),r};const go=m.getLogger(ot.type);let vs=class{constructor(e,t,s){a(this,"logger");a(this,"_cancelFuture");a(this,"futureId");Object.assign(this,t),this.logger=s.logger,this.id=e,this.futureId=t.id,this.namespace=t.namespace||"kos",this._cancelFuture=$a,To(()=>this.status===Ve.Success||this.status===Ve.Fail,()=>{go.info(`Future ${this.id} has completed with status ${this.status}`),Se(this)})}async load(){go.debug(`loading Future ${this.id}`)}unload(){go.info(`unloading Future ${this.id}`)}async cancelFuture(){const e=this.namespace==="studio"?"/api/future":`/api/${this.namespace}/future`;await To(()=>this.futureId!==rr),await this._cancelFuture(this.futureId,e)}get status(){return this.endState?this.endState:this.progress>-1?"IN_PROGRESS":"NOT_ACTIVE"}get timeRemaining(){var c,l;const e=this.remainingTimeMs||-1;if(e<0)return"";const t={year:1e3*60*60*24*365,month:1e3*60*60*24*30,day:1e3*60*60*24,hour:1e3*60*60,minute:1e3*60,second:1e3};let s="second",o=0;for(const[d,u]of Object.entries(t))if(Math.abs(e)>=u){s=d,o=Math.round(e/u);break}const n=new Intl.RelativeTimeFormat("en",{numeric:"auto"}).formatToParts(o,s);return n.length===3?`${((c=n[1])==null?void 0:c.value)??0} ${((l=n[2])==null?void 0:l.value)??""}`:"0 seconds"}handleFutureUpdated(e){this.logger.debug(`Future ${this.id} updated. future: ${e.id} endState: ${e.endState} progress: ${e.progress} remainingTimeMs: ${e.remainingTimeMs}`),gr(e,this)}};Sa([R({topic:`kos.future/${fs}`})],vs.prototype,"handleFutureUpdated",1);vs=Sa([S(ot.type)],vs);const Da=vs,Aa=Qo();var hg=Object.defineProperty,gg=Object.getOwnPropertyDescriptor,Ca=(e,t,s,o)=>{for(var r=o>1?void 0:o?gg(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&hg(t,s,r),r};const Ra="browser-router-model",fg="kos.http.request",mg="kos.http.response";let ws=class{constructor(e,t,s){a(this,"_id");a(this,"logger");a(this,"router");this._id=e,this.logger=s.logger,this.router=new ia}get id(){return this._id}async handleRequest(e,t){const s=t.headers["src-addr"],o=t.headers["dst-addr"],r=t.headers.url,n=t.headers.method,i=t.headers["request-id"],c={id:i,method:n,path:r,body:e};let l=200;const d={send:u=>{this.logger.debug(`sending response to ${o}`),this.logger.debug(u),Fi({msg:u,options:{responseId:i,destinationAddress:s,type:mg,sourceAddress:o,status:l}})},status:function(u){return l=u,this}};if(c.path==="/openapi.json"){d.send(this.router.generateOpenApiSpec());return}await this.router.handle(c,d)}use(e,t,...s){this.router.use(e,t,...s)}async init(){this.logger.debug(`initializing browser-router ${this.id}`)}async load(){this.logger.debug(`loading browser-router ${this.id}`)}};Ca([R({topic:fg})],ws.prototype,"handleRequest",1);ws=Ca([S(Ra)],ws);const Ys=new pe({class:ws,type:Ra}),Pa="future-container-model",ve=tt(Pa),La=e=>fr(ot)(e),pg=e=>{const t=La(e);return ve.build(ve.type,{}).addFutureModel(t),t},yg=e=>ve.build(ve.type,{}).getFuture(String(e)),De={buildFutureModel:La,initiateFuture:pg,getFuture:yg};var bg=Object.defineProperty,vg=Object.getOwnPropertyDescriptor,mr=(e,t,s,o)=>{for(var r=o>1?void 0:o?vg(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&bg(t,s,r),r};const ss=m.getLogger(ve.type);let Lt=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(this,"_deleteFuture");a(this,"_addFuture");a(this,"_futures");a(this,"createModel");a(this,"deleteModel");const{deleteFuture:o=Ia,addFuture:r=Ta}=t;this.logger=s.logger,this._deleteFuture=o,this._addFuture=r,this.id=e,this._futures=new ue,this.createModel=this.createFuture,this.deleteModel=this.removeFuture}get futures(){return this._futures.data}get models(){return this.futures}getFuture(e){return this._futures.getModel(e)}addFutureModel(e){this._futures.addModel(e)}removeFutureModel(e){this._futures.removeModel(e)}async removeFuture(e){try{await this._deleteFuture(e)}catch(t){ss.error("error deleting a Future"),ss.error(t)}}async createFuture(e){try{const t=await this._addFuture(e),s=t==null?void 0:t.data;if(s){const o=fr(ot)(s);return this.addFutureModel(o),o}}catch(t){throw ss.error("error creating a Future"),ss.error(t),t}}handleFutureUpdated(e,t){const s=De.buildFutureModel(e);this.addFutureModel(s);const o=`kos.future/${e.tracker||e.id}`;this.logger.debug(`publishing future update to ${o}`),F(o,t.body,t.headers)}};mr([ae],Lt.prototype,"_futures",2);mr([R({topic:"kos.future"})],Lt.prototype,"handleFutureUpdated",1);Lt=mr([S(ve.type)],Lt);const xa=Lt,{URL:zt}=q(),{getOne:wg,postModel:Mg,deleteModel:ka}=Y.build({basePath:`${zt}/api/keyVal`}),$o=m.createLogger({name:"key-value-service",group:"Services"}),Fa=async(e,t)=>{await ka({urlOverride:`${zt}/api/keyVal/${e}/${t}`,id:t})},Na=async(e,t,s)=>{const o=await Mg({urlOverride:`${zt}/api/keyVal/${e}/${t}`,model:s.toString()});if((o==null?void 0:o.status)!==200)throw $o.error("Failed to update studio-state data",o),new Error(`Failed to update studio-state data for namespace ${e}`);return o.data},Ua=async(e="studio")=>{$o.debug("sending GET for studio-state");const t=await wg({urlOverride:`${zt}/api/keyVal/${e}`});if((t==null?void 0:t.status)!==200)throw $o.error("Failed to retrieve studio-state data",t),new Error(`Failed to retrieve studio-state data for namespace ${e}`);return t.data},_g=async e=>{await ka({urlOverride:`${zt}/api/keyVal/${e}}`,id:""})},Eg=Object.freeze(Object.defineProperty({__proto__:null,deleteKeyValue:Fa,deleteKeyValueNamespace:_g,getKeyValue:Ua,updateKeyValue:Na},Symbol.toStringTag,{value:"Module"}));var Ig=Object.defineProperty,Tg=Object.getOwnPropertyDescriptor,pr=(e,t,s,o)=>{for(var r=o>1?void 0:o?Tg(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Ig(t,s,r),r};const ja="key-value-model";let xt=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(this,"namespace");a(this,"data");this.id=e,this.logger=s.logger,this.data=be(),this.namespace=t.namespace||"studio"}async init(){this.logger.debug(`initializing studio-state ${this.id}`)}async updateState(e,t){this.logger.debug(`updating studio-state ${e} with value ${t}`),t!==void 0?(await Na(this.namespace,e,t),this.data[e]=t):(await Fa(this.namespace,e),this.data[e]=void 0)}async load(){this.logger.debug(`loading studio-state ${this.id}`);const e=await Ua(this.namespace);this.data.setValues(e)}handleStateUpdate(e){e.namespace===this.namespace&&(this.data[e.key]=e.value)}handleStateDelete(e){e.namespace===this.namespace&&(this.data[e.key]=void 0)}};pr([R({topic:"/keyVal/set"})],xt.prototype,"handleStateUpdate",1);pr([R({topic:"/keyVal/remove"})],xt.prototype,"handleStateDelete",1);xt=pr([S(ja)],xt);const yr=new ce({class:xt,type:ja}),{URL:qt}=q(),{postModel:br,getOne:$g}=Y.build({basePath:`${qt}/api/kos-time`});m.createLogger({name:"kos-time-service",group:"Services"});const Ba=async e=>{const t=await br({model:e,urlOverride:`${qt}/api/kos/time/time`});if((t==null?void 0:t.status)!==200)throw Error("Failed to set time");return t.data},Ka=async e=>{const t=await br({model:e,urlOverride:`${qt}/api/kos/time/date`});if((t==null?void 0:t.status)!==200)throw Error("Failed to set time");return t.data},Ha=async e=>{const t=await br({model:{},urlOverride:`${qt}/api/kos/time/timezone?tz=${e}`});if((t==null?void 0:t.status)!==200)throw Error("Failed to set timezone");return t.data},Ga=async()=>{const e=await $g({urlOverride:`${qt}/api/kos/time/timezone`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set timezone");return e.data.timeZone},Og=Object.freeze(Object.defineProperty({__proto__:null,getTimezone:Ga,setDate:Ka,setTime:Ba,setTimezone:Ha},Symbol.toStringTag,{value:"Module"}));var Sg=Object.defineProperty,Dg=Object.getOwnPropertyDescriptor,zs=(e,t,s,o)=>{for(var r=o>1?void 0:o?Dg(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Sg(t,s,r),r};const dt="kos-time-model",Ag="/kos/time/time",Cg="/kos/time/day",Rg="/kos/time/timezone";let Ye=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(this,"timezone");this.id=e,this.logger=s.logger,this.timezone=""}async updateSystemTime(e){await Ba(e)}async updateSystemDate(e){await Ka(e)}async updateSystemTimezone(e){await Ha(e)}handleTimeChange(){F(St.TIME_CHANGE,{})}handleDayChange(){F(St.DAY_CHANGE,{})}async handleTimeZoneChange(){await this.retrieveTimezone(),F(St.TIMEZONE_CHANGE,{})}async init(){this.logger.debug(`initializing kos-time ${this.id}`)}async retrieveTimezone(){const e=await Ga();this.setTimezone(e)}setTimezone(e){this.timezone=e}async load(){this.logger.debug(`loading kos-time ${this.id}`),this.retrieveTimezone()}};zs([R({topic:Ag,websocket:!0})],Ye.prototype,"handleTimeChange",1);zs([R({topic:Cg,websocket:!0})],Ye.prototype,"handleDayChange",1);zs([R({topic:Rg,websocket:!0})],Ye.prototype,"handleTimeZoneChange",1);Ye=zs([S(dt)],Ye);const Ms={registration:{[dt]:{class:Ye,singleton:!0}},type:dt,predicate:te(dt),factory:V.Singleton.create(dt)};var Pg=Object.defineProperty,Lg=Object.getOwnPropertyDescriptor,Va=(e,t,s,o)=>{for(var r=o>1?void 0:o?Lg(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Pg(t,s,r),r};const Ya="log-block-container-model";let _s=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(this,"_models");this.id=e,this.logger=s.logger,this._models=new ue({parentId:e,sortKey:"blockNum"})}getModel(e){return this._models.getModel(e)}get models(){return this._models}get data(){return this._models.data}addModel(e){this._models.addModel(e)}removeModel(e){this._models.removeModel(e)}async init(){this.logger.debug(`initializing log-block-container container ${this.id}`)}async load(){this.logger.debug(`loading log-block-container container ${this.id}`)}};Va([ae],_s.prototype,"_models",2);_s=Va([S(Ya)],_s);const Le=Qo(),xg=m.createLogger({name:"log-stream-container-service",group:"Services"}),za=()=>{var o;const e=ee(),s=(e==null?void 0:e.connId)||((o=window==null?void 0:window.kosBridge)==null?void 0:o.call(window,"connId"));return m.error(`getKosConnectionId: ${s}`),s},rt=za(),kg="/api/kos/logs/node/{nodeId}/streams",qa=async()=>(xg.debug("sending GET for log-stream-container"),await Le.get(kg,{path:{nodeId:"primary"}},{destinationAddress:rt})),Wa=async(e,t="primary")=>{await Le.post("/api/kos/logs/node/{nodeId}/{stream}/subscribe",{path:{nodeId:t,stream:e}},void 0,{destinationAddress:rt})},Za=async e=>{await Le.post("/api/kos/logs/node/{nodeId}/{stream}/unsubscribe",{path:{nodeId:"primary",stream:e}},void 0,{destinationAddress:rt})},Fg=async()=>{await Le.post("/api/kos/logs/overrides",{},{level:"WARN",name:"com.example",nodeType:"java",type:"package"},{destinationAddress:rt})},Ja=async e=>await Le.get("/api/kos/logs/node/{nodeId}/{stream}/blocks",{path:{nodeId:"primary",stream:e}},{destinationAddress:rt}),Xa=async(e,t)=>await Le.get("/api/kos/logs/node/{nodeId}/{stream}/blocks/{blockId}",{path:{nodeId:"primary",stream:e,blockId:t}},{destinationAddress:rt}),Ng=Object.freeze(Object.defineProperty({__proto__:null,createOverride:Fg,getKosConnectionId:za,getLogStreamBlock:Xa,getLogStreamBlocks:Ja,getLogStreams:qa,subscribeToLogStream:Wa,unsubscribeFromLogStream:Za},Symbol.toStringTag,{value:"Module"}));var Ug=Object.defineProperty,jg=Object.getOwnPropertyDescriptor,Bg=(e,t,s,o)=>{for(var r=o>1?void 0:o?jg(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Ug(t,s,r),r};const Qa="log-block-model";let Oo=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(this,"nodeId");a(this,"stream");a(this,"blockNum");a(this,"startLineNum");a(this,"endLineNum");a(this,"startTime");a(this,"endTime");a(this,"lineCount");a(this,"lines");a(this,"inc");this.id=e,this.logger=s.logger,this.nodeId=t.nodeId,this.stream=t.stream,this.blockNum=t.blockNum,this.startLineNum=t.startLineNum,this.endLineNum=t.endLineNum,this.startTime=t.startTime,this.endTime=t.endTime,this.lineCount=t.lineCount,this.lines=[],this.inc=0}async syncLines(){const[e,t]=await Xa(this.stream,this.blockNum);if(e){this.logger.error(`Failed to get log block ${this.blockNum}`);return}t&&this.addLines(t.lines,!0)}updateModel(e){this.startLineNum=e.startLineNum,this.endLineNum=e.endLineNum,this.startTime=e.startTime,this.endTime=e.endTime,this.lineCount=e.lineCount}addLines(e,t){const s=t?[]:this.lines;this.lines=[...s,...e],this.inc+=1}async init(){this.logger.debug(`initializing log-block ${this.id}`)}async load(){this.logger.debug(`loading log-block ${this.id}`)}};Oo=Bg([S(Qa)],Oo);const kt=new ce({class:Oo,type:Qa}),qs=new ce({class:_s,type:Ya});qs.addRelatedModel(kt);var Kg=Object.defineProperty,Hg=Object.getOwnPropertyDescriptor,ec=(e,t,s,o)=>{for(var r=o>1?void 0:o?Hg(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Kg(t,s,r),r};const tc="log-stream-model";let Es=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(this,"nodeId");a(this,"_blocks");a(this,"name");a(this,"currentBlockId");a(this,"isResetting");a(this,"generatorInstance");a(this,"shouldStop",!1);this.id=e,this.logger=s.logger,this.currentBlockId="",this.name=t.name,this.nodeId=t.nodeId,this.isResetting=!0,this._blocks=qs.instance(`${e}-blocks`).options({}).build()}get firstLineNum(){const e=this.populated[0];return e?e.startLineNum:0}get currentBlock(){const e=this.currentBlockId;return this._blocks.getModel(e)}get populated(){return this._blocks.data.filter(e=>e.lines.length>0)}get blocks(){return this._blocks.data}get totalLineCount(){return this.populated.reduce((e,t)=>e+t.lineCount,0)}accept(e){e.visit(this)}updateBlock(e){var o;let t=this._blocks.models.getModel(`${e.stream}-block-${e.blockNum}`);const s={nodeId:e.nodeId,blockNum:e.blockNum,endLineNum:e.endLineNum,lineCount:e.lineCount,startLineNum:e.startLineNum,stream:this.name,endTime:new Date(e.endTime),startTime:new Date(e.startTime)};t||(t=kt.instance(`${e.stream}-block-${e.blockNum}`).options(s).build(),this._blocks.addModel(t)),t&&t.updateModel(s),(!this.currentBlock||e.blockNum>=((o=this.currentBlock)==null?void 0:o.blockNum))&&(this.currentBlockId=`${e.stream}-block-${e.blockNum}`)}addBlock(e){var s;const t=kt.instance(`${e.stream}-block-${e.blockNum}`).options({nodeId:e.nodeId,blockNum:e.blockNum,endLineNum:e.endLineNum,lineCount:e.lineCount,startLineNum:e.startLineNum,stream:this.name,endTime:new Date(e.endTime),startTime:new Date(e.startTime)}).build();this._blocks.addModel(t),(!this.currentBlock||e.blockNum>=((s=this.currentBlock)==null?void 0:s.blockNum))&&(this.currentBlockId=`${e.stream}-block-${e.blockNum}`)}removeBlock(e){this._blocks.models.removeModel(`${this.name}-block-${e}`)}async subscribe(){await Wa(this.name)}async unsubscribe(){await Za(this.name)}async reset(){if(this.isResetting=!0,this.populated.length>0)return;this.logger.debug(`resetting log-stream ${this.id}`);for(const t of this._blocks.models.data)t.lines=[];const e=this._blocks.data[this._blocks.data.length-1];e&&await e.syncLines(),this.isResetting=!1}async init(){this.logger.debug(`initializing log-stream ${this.id}`)}async load(){this.logger.debug(`loading log-stream ${this.id}`);const[e,t]=await Ja(this.name);if(e){this.logger.error(`Error loading log stream: ${e}`);return}if(t)for(const o of t)this.addBlock(o);const s=this._blocks.data[this._blocks.data.length-1];if(s&&await s.syncLines(),this._blocks.data.length>1){const o=this._blocks.data[this._blocks.data.length-2];o&&await o.syncLines()}}start(){return this.shouldStop=!1,this.generatorInstance=this.streamLogs(),this.generatorInstance}stop(){var e;this.shouldStop=!0,(e=this.generatorInstance)==null||e.next(),console.log("Requested generator stop.")}async*streamLogs(){const e=[];let t=null,s=0,o=this.currentBlockId;const r=ca(()=>{const n=this.currentBlock;return n?{blockId:this.currentBlockId,lineCount:n.lines.length}:null},n=>{const i=this.currentBlock;if(i)if(o!==(n==null?void 0:n.blockId))o=n==null?void 0:n.blockId,s=0,e.push(...i.lines);else{const c=i.lines.slice(s);e.push(...c),s+=c.length}t&&(t(),t=null)},{fireImmediately:!0});try{for(const n of this.populated.filter(i=>i!==this.currentBlock))for(const i of n.lines)yield i;for(;;)for(e.length===0&&await new Promise(n=>t=n);e.length>0;)yield e.shift()}finally{r()}}};ec([ae],Es.prototype,"_blocks",2);Es=ec([S(tc)],Es);const Dt=new ce({class:Es,type:tc});var Gg=Object.defineProperty,Vg=Object.getOwnPropertyDescriptor,xe=(e,t,s,o)=>{for(var r=o>1?void 0:o?Vg(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Gg(t,s,r),r};const sc="log-stream-container-model",Yg="/kos/logs/subscription/addBlock/*",zg="/kos/logs/subscription/updateBlock/*",qg="/kos/logs/subscription/removeBlock/*",Wg="/kos/logs/subscription/lines/*",oc="/kos/logs/streams/add/*";let ge=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(this,"selectedStream");a(this,"_models");this.id=e,this.logger=s.logger,this._models=new ue({parentId:e}),this.selectedStream=void 0}getModel(e){return this._models.getModel(e)}get models(){return this._models}get data(){return this._models.data}updateModel(e){}addModel(e){this._models.addModel(e)}removeModel(e){this._models.removeModel(e)}updateSelectedStream(e){this.selectedStream=e}handleStreamAdded(e){this.logger.debug(`Received topic: ${oc}`);const t=e.stream,s=Dt.instance(t).options({name:t,nodeId:"primary"}).build();this.addModel(s)}handleAddBlock(e,t){this.logger.debug(`Received topic: ${t.headers.topic}`);const s=e.stream,o=this.models.getModel(s);o&&o.addBlock(e)}handleRemoveBlock(e,t){this.logger.debug(`Received topic: ${t.headers.topic}`);const s=e.stream,o=this.models.getModel(s);o&&o.removeBlock(e.blockNum)}handleUpdateBlock(e,t){this.logger.debug(`Received topic: ${t.headers.topic}`);const s=e.stream,o=this.models.getModel(s);o&&o.updateBlock(e)}handleLogLine(e,t){var r;this.logger.debug(`Received topic: ${t.headers.topic}`);const s=e.stream,o=this.models.getModel(s);o&&((r=o.currentBlock)==null||r.addLines(e.lines))}async init(){this.logger.debug(`initializing log-stream-container container ${this.id}`)}async subscribeToLogStream(e){const t=Dt.instance(e).options({name:e,nodeId:"primary"}).build();this.addModel(t),await t.subscribe()}async load(){this.logger.debug(`loading log-stream-container container ${this.id}`);const[e,t]=await qa();if(e){this.logger.error(`Error loading log-streams: ${e}`);return}t&&t.forEach(s=>{const o=Dt.instance(s).options({name:s,nodeId:"primary"}).build();this.addModel(o)})}};xe([ae],ge.prototype,"_models",2);xe([R({topic:[oc],websocket:!0})],ge.prototype,"handleStreamAdded",1);xe([R({topic:[Yg],websocket:!0})],ge.prototype,"handleAddBlock",1);xe([R({topic:[qg],websocket:!0})],ge.prototype,"handleRemoveBlock",1);xe([R({topic:[zg],websocket:!0})],ge.prototype,"handleUpdateBlock",1);xe([R({topic:[Wg],websocket:!0})],ge.prototype,"handleLogLine",1);ge=xe([S(sc)],ge);const Wt=new pe({class:ge,type:sc});Wt.addRelatedModel(Dt);Wt.addRelatedModel(qs);Wt.addRelatedModel(kt);const Zg=e=>e.rank!==void 0,Jg=e=>e.visibleRole!==void 0,Xg=e=>e.color!==void 0,Qg=e=>{const t=e.info;return Zg(t)?t.rank:0},ef=e=>{const t=e.info;return Xg(t)?t.color:"orange"},tf=e=>{const t=e.info;return Jg(t)?t.visibleRole:"TECHNICIAN"},{URL:vr}=q(),{getAll:sf,postModel:rc}=Y.build({basePath:`${vr}/api/kos/troubles`}),nc=async()=>await sf({}),ic=async(e,t)=>{try{const s=await rc({model:{},urlOverride:`${vr}/api/kos/troubles/resolve/${e}`,tracker:t});return s!=null&&s.data&&De.initiateFuture(s.data),s.data}catch{const o={id:t||"",endState:Ve.Fail,tracker:t,reason:"Failed to resolve trouble"};return De.initiateFuture(o),o}},of=async(e,t)=>{try{const s=await rc({model:e,urlOverride:`${vr}/api/kos/troubles/resolve/`,tracker:t});return s!=null&&s.data&&De.initiateFuture(s.data),s.data}catch{const o={id:t||"",endState:Ve.Fail,tracker:t,reason:"Failed to resolve troubles"};return De.initiateFuture(o),o}},rf=Object.freeze(Object.defineProperty({__proto__:null,bulkResolveTroubles:of,getTroubles:nc,resolveTrouble:ic},Symbol.toStringTag,{value:"Module"})),Is="troubleDataMapper",os=new Map;Bs(Is,{register:(e,t)=>{var s;os.has(e)||os.set(e,[]),(s=os.get(e))==null||s.push(t)},execute:async(e,t)=>{const s=os.get(e);if(!s)return{...t.data};const o=s.map(i=>i(t));return(await Promise.allSettled(o)).reduce((i,c)=>(c.status==="fulfilled"?i={...i,...c.value}:m.info(`Trouble mapper ${e} failed: ${c.reason}`),i),{...t.data})}});const Zt="troubleMapper",rs=new Map;Bs(Zt,{register:(e,t)=>{var s;rs.has(e)||rs.set(e,[]),(s=rs.get(e))==null||s.push(t)},execute:async(e,t)=>{const s=rs.get(e);if(!s)return[];const o=s.map(i=>i(t)),n=(await Promise.allSettled(o)).map(i=>i.status==="fulfilled"?i.value:(m.info(`Trouble mapper ${e} failed: ${i.reason}`),[])).flat();return Array.from(new Set(n))}});$[Zt].register("nozzle",async e=>[e.data.nozzlePath]);$[Zt].register("path",async e=>[e.data.path]);const nf=async e=>{const t=new Set,s=e.ifaces,o=s==null?void 0:s.map(n=>$[Zt].execute(n,e));return(await Promise.allSettled(o)).forEach(n=>{n.status==="fulfilled"&&n.value.forEach(i=>t.add(i))}),Array.from(t)},ac=async e=>{const t=e.ifaces,s=t==null?void 0:t.map(i=>$[Is].execute(i,e)),o=$[Is].execute(e.type,e);s.push(o);const n=(await Promise.allSettled(s)).reduce((i,c)=>(c.status==="fulfilled"&&(i={...i,...c.value}),i),{});return{...e.data,...n}};class af{constructor(){a(this,"type","ResolvableTrouble");a(this,"title","Resolvable Trouble");a(this,"subtitle","Trouble")}}class cf{constructor(){a(this,"type","BlockPumpTrouble");a(this,"title","Block Pump Trouble");a(this,"subtitle","Trouble")}}class Ne{static getHandler(t){switch(t){case"ResolvableTrouble":return new af;case"BlockPumpTrouble":return new cf;default:return}}}var lf=Object.defineProperty,df=Object.getOwnPropertyDescriptor,cc=(e,t,s,o)=>{for(var r=o>1?void 0:o?df(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&lf(t,s,r),r};const ut="trouble-model";function ns(e){return typeof e.shouldDefer=="boolean"}let Ts=class{constructor(e,{resolvable:t,tags:s,info:o,id:r,clientData:n,rank:i,ifaces:c,type:l,group:d,createTime:u,role:h,color:f,...v},b){a(this,"id");a(this,"logger");a(this,"_troubleId");a(this,"_resolvable");a(this,"type");a(this,"futureHandler");a(this,"ifaces");a(this,"clientData");a(this,"info");a(this,"role");a(this,"color");a(this,"tags");a(this,"data");a(this,"rank");a(this,"group");a(this,"createTime");a(this,"_mapped",{});this.id=e,this.logger=b.logger,this.type=l,this._troubleId=r,this._resolvable=!!t,this.ifaces=c,this.rank=i,this.role=h,this.color=f,this.tags=s,this.info=o,this.group=d,this.createTime=u,this.clientData=n,this.data={},Object.assign(this.data,v),this.futureHandler=new ur(this)}getTitleWithContext(e){var s,o;const t=e?(o=(s=Ne.getHandler(this.type))==null?void 0:s.context)==null?void 0:o[e]:Ne.getHandler(this.type);return(t==null?void 0:t.title)||"Trouble"}getSubtitleWithContext(e){var s,o;const t=e?(o=(s=Ne.getHandler(this.type))==null?void 0:s.context)==null?void 0:o[e]:Ne.getHandler(this.type);return(t==null?void 0:t.subtitle)||"Trouble"}get rawId(){return this._troubleId}get title(){var e;return((e=Ne.getHandler(this.type))==null?void 0:e.title)||"Trouble"}get subtitle(){var e;return((e=Ne.getHandler(this.type))==null?void 0:e.subtitle)||"Trouble"}get troubleId(){return this._troubleId}get resolvable(){return this._resolvable}get future(){return this.futureHandler.future}async resolveMappedData(){return await ac(this)}get deferredCompanion(){const e=Io(this.id,t=>ns(t));if(e&&ns(e.modelData))return e.modelData}get deferred(){return this.deferredCompanion?this.deferredCompanion.deferred:!1}get shouldDefer(){const e=Io(this.id,t=>ns(t));return e&&ns(e.modelData)?e.modelData.shouldDefer:!1}clearDefer(){var e;(e=this.deferredCompanion)==null||e.clearDefer()}defer(){var e;(e=this.deferredCompanion)==null||e.defer()}getChildren(){return[...this.futureHandler.allFutures]}async resolve(e){var t;if(!this._resolvable)throw this.logger.error(`attempting to resolve an unresolvable trouble with id ${this._troubleId}`),new Error("Trouble is not resolvable");if(this.shouldDefer){(t=this.deferredCompanion)==null||t.defer();return}return await ic(this._troubleId,e)}};cc([kr()],Ts.prototype,"resolve",1);Ts=cc([S(ut)],Ts);const Ft={registration:{[ut]:{class:Ts,singleton:!1}},type:ut,predicate:te(ut),factory:V.Factory.create(ut)};var uf=Object.defineProperty,hf=Object.getOwnPropertyDescriptor,Ws=(e,t,s,o)=>{for(var r=o>1?void 0:o?hf(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&uf(t,s,r),r};const hn=m.createLogger({name:"trouble-container-model"});function gn(e){return $.propertyMapper.hasMapper(re.TroubleRank)?$.propertyMapper.executeMapper(re.TroubleRank,e):Qg(e)}function fn(e){return($.propertyMapper.hasMapper(re.TroubleColor)?$.propertyMapper.executeMapper(re.TroubleColor,e):ef(e)).toLowerCase()}function mn(e){return($.propertyMapper.hasMapper(re.TroubleRole)?$.propertyMapper.executeMapper(re.TroubleRole,e):tf(e)).toLowerCase()}const gf="trouble-container-model";class Q{}a(Q,"INDEX_TROUBLES_BY_IFACE","byIface"),a(Q,"INDEX_TROUBLES_BY_TYPE","byType"),a(Q,"INDEX_TROUBLES_BY_GROUP","byGroup"),a(Q,"INDEX_TROUBLES_BY_DEFERRED","byDeferred"),a(Q,"SORT_KEY_RANK","rank"),a(Q,"TROUBLES_DEFERRED","true");let ze=class{constructor(e){a(this,"id");a(this,"troubles");this.id=e,this.troubles=new ue({indexMap:{[Q.INDEX_TROUBLES_BY_IFACE]:nf,[Q.INDEX_TROUBLES_BY_TYPE]:"type",[Q.INDEX_TROUBLES_BY_GROUP]:"group",[Q.INDEX_TROUBLES_BY_DEFERRED]:"deferred"},sortKey:Q.SORT_KEY_RANK,parentId:e})}async load(){hn.debug("loading trouble container");const e=await nc();try{e==null||e.data.forEach(t=>{const s={...t,rank:gn(t),color:fn(t),role:mn(t),id:String(t.id)},o=Ft.factory(`trouble-${t.id}`)(s);this.troubles.addModel(o)})}catch(t){throw hn.error(t),t}}handleTroubleRemoved(e){const t=`trouble-${e}`,s=this.troubles.getModel(t);this.troubles.removeModel(t),s&&Se(s)}handleTroubleAdded(e){const t={...e,rank:gn(e),color:fn(e),role:mn(e),id:String(e.id)};if(t.role==="NONE")return;const s=Ft.factory(`trouble-${e.id}`)(t);this.troubles.addModel(s)}};Ws([ae],ze.prototype,"troubles",2);Ws([R({topic:"/kos/trouble/remove",websocket:!0,lifecycle:k.INIT})],ze.prototype,"handleTroubleRemoved",1);Ws([R({topic:"/kos/trouble/add",websocket:!0})],ze.prototype,"handleTroubleAdded",1);ze=Ws([S(gf)],ze);const is="trouble-container-model",qe={registration:{[is]:{class:ze,singleton:!0}},type:is,predicate:te(is),factory:V.Singleton.create(is)},{URL:lc}=q(),{getAll:ff}=Y.build({basePath:`${lc}/api/kos/ota`}),pn=m.createLogger({name:"ota-service",group:"Services"}),mf=async()=>{pn.debug("sending GET request to /api/kos/ota/artifacts");const e=await ff({urlOverride:`${lc}/api/kos/ota/artifacts`});return pn.debug("getArtifacts - response:",e),e==null?void 0:e.data};var pf=Object.defineProperty,yf=Object.getOwnPropertyDescriptor,Zs=(e,t,s,o)=>{for(var r=o>1?void 0:o?yf(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&pf(t,s,r),r};const dc="ota-model",bf=e=>{let t=null;for(const s in e){const o=e[s],r=o.lastUpdateTime;(!t||t.lastUpdateTime<r)&&(t=o)}return t},fo=e=>{const t=e.artifactInfo,s=bf(e.requests),o=(t==null?void 0:t.identifier)||(s==null?void 0:s.kabId);if(!o)return;let r;switch(e.status){case"INSTALLED":r="ready";break;case"INVALID":r="error";break;case"MISSING":r=((s==null?void 0:s.currentSize)||0)>0?"downloading":"idle";break;case"STAGED":r="pending"}const n=t===void 0;return{id:o,manifest:n,label:t==null?void 0:t.version,name:t==null?void 0:t.name,status:r,error:r==="error"?s==null?void 0:s.lastErrorReason:void 0,errorCount:r==="error"?s==null?void 0:s.errorCount:0,progress:r==="downloading"&&s&&!n?s.currentSize/(t==null?void 0:t.size)*100:void 0,size:t==null?void 0:t.size}};let We=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(this,"data",new ra);a(this,"troubleContainer");this.id=e,this.logger=s.logger}get downloadInProgressTrouble(){var t;return(t=this.troubleContainer.troubles.getIndexByKey("byType","OTADownloadInProgressTrouble"))==null?void 0:t[0]}get updatePendingTrouble(){var t;return(t=this.troubleContainer.troubles.getIndexByKey("byType","OTAUpdatePendingTrouble"))==null?void 0:t[0]}get pausedDueToErrorsTrouble(){var t;return(t=this.troubleContainer.troubles.getIndexByKey("byType","OTAPausedDueToErrorsTrouble"))==null?void 0:t[0]}get updates(){return this.data}get status(){return this.pausedDueToErrorsTrouble?"error":this.downloadInProgressTrouble?"downloading":this.updatePendingTrouble?"pending":"idle"}installAndReboot(){var e;this.updatePendingTrouble||this.logger.error("installAndReboot - OTAUpdatePendingTrouble not present"),this.logger.debug("installAndReboot - resolve OTAUpdatePendingTrouble"),(e=this.updatePendingTrouble)==null||e.resolve()}async init(){this.logger.debug(`initializing ota ${this.id}`)}async load(){this.logger.debug(`loading ota ${this.id}`);try{const e=await mf();e&&e.forEach(t=>{const s=fo(t);s&&this.data.addModel(s)})}catch(e){this.logger.error(`loading ota ${this.id} - error:`,e)}}async handleAllArtifacts(e){this.logger.debug("handleAllArtifacts:",e),await this.data.clear();try{e.forEach(t=>{const s=fo(t);s&&this.data.addModel(s)})}catch(t){this.logger.error(`handleAllArtifacts ${this.id} - error:`,t)}}handleChangedArtifacts(e){this.logger.debug("handleChangedArtifacts:",e);try{e.forEach(t=>{const s=fo(t);s&&this.data.updateModel(s)})}catch(t){this.logger.error(`handleChangedArtifacts ${this.id} - error:`,t)}}};Zs([Ce({modelType:qe.type})],We.prototype,"troubleContainer",2);Zs([R({topic:"/kos/ota/artifacts/all",websocket:!0})],We.prototype,"handleAllArtifacts",1);Zs([R({topic:"/kos/ota/artifacts/changed",websocket:!0})],We.prototype,"handleChangedArtifacts",1);We=Zs([S(dc)],We);const $s=new pe({class:We,type:dc}),yn=m.createLogger({name:"software-info-service",group:"Services"}),uc=async()=>{yn.debug("sending GET for software-info");const[e,t]=await Aa.get("/api/kos/manifest/info");if(!t)throw yn.error("Failed to fetch software-info",e),new le("Failed to fetch software-info");return t},vf=Object.freeze(Object.defineProperty({__proto__:null,getSoftwareInfos:uc},Symbol.toStringTag,{value:"Module"}));var wf=Object.defineProperty,Mf=Object.getOwnPropertyDescriptor,_f=(e,t,s,o)=>{for(var r=o>1?void 0:o?Mf(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&wf(t,s,r),r};const ht="software-info-model";let So=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(this,"nodes");this.id=e,this.logger=s.logger,this.nodes=[]}async init(){this.logger.debug(`initializing software-info ${this.id}`)}groupBy(e,t){return e.reduce((s,o)=>(s[o[t]]=[...s[o[t]]||[],o],s),{})}async load(){this.logger.debug(`loading software-info ${this.id}`);try{const e=await uc(),t=(e==null?void 0:e.nodes)||{};z(()=>{const o=Object.keys(t).map(r=>t[r][0]).map(r=>({nodeName:r.nodeType,kosVersion:r.kosVersion,group:this.groupBy(r.artifacts,"group")}));this.nodes=o})}catch(e){e instanceof le&&this.logger.error("Failed to fetch software-info",e)}}};So=_f([S(ht)],So);const Os={registration:{[ht]:{class:So,singleton:!1}},type:ht,predicate:te(ht),factory:V.Factory.create(ht)},{URL:hc}=q(),{getOne:Ef}=Y.build({basePath:`${hc}/api/kos/state`}),If=m.createLogger({name:"state-bean-service",group:"Services"}),gc=async({path:e})=>(If.debug("sending GET for state-bean"),await Ef({urlOverride:`${hc}/api/kos/state/${e}`})),Tf=Object.freeze(Object.defineProperty({__proto__:null,getStateBeanData:gc},Symbol.toStringTag,{value:"Module"}));var $f=Object.defineProperty,Of=Object.getOwnPropertyDescriptor,fc=(e,t,s,o)=>{for(var r=o>1?void 0:o?Of(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&$f(t,s,r),r};const gt="state-bean-model",Sf=Ae("path");let Ss=class{constructor(e,t,s){a(this,"id");a(this,"path");a(this,"props");a(this,"logger");this.id=e,this.logger=s.logger,this.props=or.map(new Map),vo(t,this)}updateModel(e){vo(e,this)}handleConfigBeanUpdated(e){Object.entries(e).forEach(([t,s])=>{let o=s;typeof o=="string"&&ir(o)&&(o=o.toLowerCase()=="true"),typeof o=="string"&&Hs(o)&&(o=Number(o)),this.props.set(t,o)})}async init(){this.logger.debug(`initializing state-bean ${this.id}`)}updateProps(e){Object.entries(e).forEach(([t,s])=>{this.props.set(t,s)})}async load(){this.logger.debug(`loading state-bean ${this.id}`);const e=await gc({path:this.path});e!=null&&e.data&&this.updateProps(e.data)}};fc([R({topic:`/kos/state/${Sf}`,websocket:!0})],Ss.prototype,"handleConfigBeanUpdated",1);Ss=fc([S(gt)],Ss);const Nt={registration:{[gt]:{class:Ss,singleton:!1}},type:gt,predicate:te(gt),factory:V.Factory.create(gt)};var Df=Object.defineProperty,Af=Object.getOwnPropertyDescriptor,mc=(e,t,s,o)=>{for(var r=o>1?void 0:o?Af(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Df(t,s,r),r};const ft="state-prop-model",bn=Ae("path");let Ds=class{constructor(e,t,s){a(this,"id");a(this,"path");a(this,"attribute");a(this,"logger");a(this,"stateBean");this.id=e,this.logger=s.logger,this.path=t.path,this.attribute=t.attribute}get value(){return this.stateBean.props.get(this.attribute)}async init(){this.logger.debug(`initializing state-prop ${this.id}`)}async load(){this.logger.debug(`loading state-prop ${this.id}`)}toString(){var e;return((e=this.value)==null?void 0:e.toString())??""}};mc([Ce({modelType:Nt.type,id:`state-bean-${bn}`,options:{path:bn}})],Ds.prototype,"stateBean",2);Ds=mc([S(ft)],Ds);const wr={registration:{[ft]:{class:Ds,singleton:!1}},type:ft,predicate:te(ft),factory:V.Factory.create(ft)},{URL:Cf}=q(),{getAll:Rf}=Y.build({basePath:`${Cf}/api/state-prop`}),Pf=m.createLogger({name:"state-prop-service",group:"Services"}),Lf=async()=>(Pf.debug("sending GET for state-prop"),await Rf({})),xf=Object.freeze(Object.defineProperty({__proto__:null,getStateProps:Lf},Symbol.toStringTag,{value:"Module"})),{URL:Mr}=q(),{getOne:pc}=Y.build({basePath:`${Mr}/api/translation`}),At=m.createLogger({name:"translation-service",group:"Services"}),kf=()=>{const e=window.location.origin,t=ee();return(t==null?void 0:t.host)||e},yc=async(e,t)=>{At.debug("sending GET for translation");const s=t??kf();try{const o=await fetch(`${s}${e}`);return o.status!==200?(At.warn(`Failed to fetch translations at ${e}: ${o.status}`),{}):await o.json()}catch(o){throw At.error("Error fetching translations",o),o}},Ff=async()=>{At.debug("getting localization descriptor");const e=await pc({urlOverride:`${Mr}/api/system/kos/localization`});if((e==null?void 0:e.status)!==200)throw new Error(`Failed to get tool localization descriptor ${e==null?void 0:e.status}`);return e.data},bc=e=>async()=>{At.debug("getting kos localization descriptor");const t=await pc({urlOverride:`${Mr}/api/kos/localization/contexts`});if((t==null?void 0:t.status)!==200)throw new Error(`Failed to get tool localization descriptor ${t==null?void 0:t.status}`);return t.data[e]},vc="langResolver";var Nf=Object.defineProperty,Uf=Object.getOwnPropertyDescriptor,jf=(e,t,s,o)=>{for(var r=o>1?void 0:o?Uf(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Nf(t,s,r),r};const mt="translation-model";function Bf(e){const t=typeof e=="string",s=t?!1:!!(e!=null&&e.data)&&typeof(e==null?void 0:e.data)!="string",o=t?e:e==null?void 0:e.defaultValue,r=t||e==null?void 0:e.context,n=t?void 0:s?e==null?void 0:e.data:e;return{isBasicOptions:t,defaultValue:o,context:r,data:n}}function wc(e,t=""){return Object.keys(e).reduce((s,o)=>{const r=t?`${t}.${o}`:o;if(typeof e[o]=="object"&&e[o]!==null){const n=wc(e[o],r);return{...s,...n}}else return{...s,[r]:e[o]}},{})}function Mc(e,t){const s={...e};for(const o in t)Object.prototype.hasOwnProperty.call(t,o)&&(typeof t[o]=="object"&&t[o]!==null&&typeof e[o]=="object"&&e[o]!==null?s[o]=Mc(e[o],t[o]):s[o]=t[o]);return s}const Do=(e,t)=>{const s=/__(.*?)__/g,o=e.replace(s,(r,n)=>Object.prototype.hasOwnProperty.call(t||{},n.trim())?t==null?void 0:t[n.trim()]:r);return o===e?o:s.test(o)?Do(o,t):o},as=(e,t,s)=>{const o=/{{(.*?)}}/g,n=Do(e,t).replace(o,(c,l)=>Object.prototype.hasOwnProperty.call(s||{},l.trim())?s==null?void 0:s[l.trim()]:c);return Do(n,t)},vn=(e,t)=>{if(t.includes(":")){const[s,o]=t.split(":");return{namespace:s,key:o}}else return{namespace:e,key:t}};let Ao=class{constructor(e,t,s){a(this,"id");a(this,"namespace");a(this,"descriptor");a(this,"defaultLocale");a(this,"currentLocale");a(this,"bundleResolver");a(this,"data");a(this,"logger");a(this,"resolver");a(this,"disposer");a(this,"context");a(this,"rootUrl");this.id=e,this.defaultLocale=t.defaultLocale||"en",this.currentLocale=t.currentLocale||"en",this.namespace=t.namespace,this.descriptor=t.descriptor,this.rootUrl=t.rootUrl,this.data={},this.resolver=t.resolver||s.kosContext.get(vc),this.bundleResolver=t.bundleResolver,this.logger=s.logger,this.context=s.kosContext.parentModel}getTranslationLocales(e){const t=this.descriptor[e];if(!e||!t)return[this.defaultLocale];if(!this.defaultLocale&&!t.fallbacks)return[e];let s=t.fallbacks||[this.defaultLocale];return s.includes(e)||(s=[e,...s]),s}async loadTranslations(){const e=this.getTranslationLocales(this.currentLocale).reverse(),t=e.map(o=>{if(this.bundleResolver){const r=x.getContext(this.id);return this.bundleResolver(this.namespace,o,r)}try{const r=this.resolver(this.namespace,o);return yc(r,this.rootUrl)}catch{return Promise.resolve({})}}),s=await Promise.allSettled(t);z(()=>{const o=s.reduce((r,n,i)=>(n.status==="fulfilled"?(this.logger.debug(`resolved ${e[i]}`,n.value),n.value&&(r=Mc(r,n.value))):this.logger.error(`failed to load translation ${this.id} for ${e[i]}`),r),{});this.data=wc(o)})}async init(){this.logger.debug(`initializing translation ${this.id}`)}exists(e){const{namespace:t,key:s}=vn(this.namespace,e);if(t!==this.namespace){const o=this.context.getModel(t);return o?o.exists(s):!1}return!!this.data[s]}resolveKey(e,t){if(!e)return this.logger.debug("key is empty"),"";const{defaultValue:s,context:o,data:r}=Bf(t),{namespace:n,key:i}=vn(this.namespace,e),c=`${i}_${o}`;if(n!==this.namespace){const l=this.context.getModel(n);return l?l.resolveKey(i,t):i}if(o&&this.data[c]){const l=this.data[c];return Array.isArray(l)?l.map(d=>as(d,this.data,r)):as(this.data[c],this.data,r)}if(this.data[i]){const l=this.data[c];return Array.isArray(l)?l.map(d=>as(d,this.data,r)):as(this.data[i],this.data,r)}return s??i}unload(){this.logger.debug(`unloading translation ${this.id}`),this.disposer&&this.disposer()}async load(){this.logger.debug(`loading translation ${this.id}`),await this.loadTranslations()}async ready(){this.logger.debug(`ready translation ${this.id}`),this.disposer=w.reaction(()=>this.currentLocale,(e,t)=>{this.logger.info(`translation langs for namespace ${this.id} changed from ${t} to ${e}`),this.loadTranslations()})}};Ao=jf([Ks(),S(mt)],Ao);const As={registration:{[mt]:{class:Ao,singleton:!1}},type:mt,predicate:te(mt),factory:V.Factory.create(mt)};var Kf=Object.defineProperty,Hf=Object.getOwnPropertyDescriptor,_c=(e,t,s,o)=>{for(var r=o>1?void 0:o?Hf(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Kf(t,s,r),r};const pt="translation-container-model",Gf=(e,t="/")=>e.join(t).replace(new RegExp(t+"{1,}","g"),t);function Vf(e,t){const s=this.descriptor.namespaces[e];if(!s)throw new Error(`namespace ${e} not found in descriptor`);const o=s.basePath,r=s.locales[t].file;return Gf([o,r])}let Cs=class{constructor(e,t,s){a(this,"id");a(this,"lang");a(this,"rootUrl");a(this,"descriptor");a(this,"_defaultNamespace");a(this,"resolver");a(this,"logger");a(this,"descriptorUrl");a(this,"namespaces",[]);a(this,"_models");this.id=e,this.lang=t.lang||"en",this.descriptor=t.descriptor,this._defaultNamespace=t.defaultNamespace,this.descriptorUrl=t.descriptorUrl,this.rootUrl=t.rootUrl,this.resolver=t.resolver||Vf.bind(this),s.kosContext.set(vc,this.resolver),this.logger=s.logger,this._models=new ue({parentId:e})}set currentLocale(e){this.lang=e,this.models.data.forEach(t=>{t.currentLocale=e})}get defaultNamespace(){return this._defaultNamespace?this.getModel(`translation-${this._defaultNamespace}`):void 0}getModel(e){return this.logger.debug(`getting model ${e}`),this._models.getModel(`translation-${e}`)}get models(){return this._models}get data(){return this._models.data}async reload(){this._models.clear(),await Hi(this);for(const e of this.namespaces){const t=this.resolveNamespace(e);await J(t)}}resolveNamespace(e){var s;if((s=this.descriptor.namespaces)==null?void 0:s[e]){const o=Object.keys(this.descriptor.namespaces[e].locales)[0],r=this.descriptor.namespaces[e].locales[o].defaultLocale,n=As.factory(`translation-${e}`)({kosParentId:this.id,namespace:e,rootUrl:this.rootUrl,currentLocale:this.lang,defaultLocale:r,descriptor:this.descriptor.namespaces[e].locales,resolver:this.resolver});return this.addModel(n),this.namespaces.includes(e)||z(()=>{this.namespaces.push(e)}),n}else{this.logger.warn(`namespace ${e} not found in descriptor`);const o=As.factory(`translation-${e}`)({kosParentId:this.id,namespace:e,rootUrl:this.rootUrl,currentLocale:this.lang,defaultLocale:this.lang,descriptor:{},resolver:this.resolver});return this.addModel(o),o}}addModel(e){this._models.addModel(e)}removeModel(e){this._models.removeModel(e)}async init(){this.logger.debug(`initializing translation-container container ${this.id}`)}async load(){this.logger.debug(`loading translation-container container ${this.id}`)}};_c([ae],Cs.prototype,"_models",2);Cs=_c([S(pt)],Cs);const fe={registration:{[pt]:{class:Cs,singleton:!0}},type:pt,predicate:te(pt),factory:V.Singleton.create(pt)},Yf={set(e,t){const s=x.getContext(fe.type);s&&s.set(e,t)},get(e){const t=x.getContext(fe.type);return t==null?void 0:t.get(e)}},Ec={async init(e){const t=fe.factory(e);return await J(t),{translations:t}}},zf=(e,t)=>{const s=t.type;return e[s]||(e[s]=[]),e[s].push(t),e},Ic="kos-ws-event",_r=tt(Ic);var qf=Object.defineProperty,Wf=Object.getOwnPropertyDescriptor,Er=(e,t,s,o)=>{for(var r=o>1?void 0:o?Wf(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&qf(t,s,r),r};const Zf=({headers:e,body:t})=>Object.entries(e).map(([o,r])=>`${o}:${r}`).join("\\n")+"\\n\\n"+t;exports.WsEventModel=class{constructor(t){a(this,"id");a(this,"events");a(this,"_topicMap");this.id=t,this.events=w.observable.map(new Map),this._topicMap=new Map}get websocketEvents(){return Array.from(this.events.values())}handleSendEvent(t,s){this.processEvent(s,!0)}handleReceiveEvent(t,s){this.processEvent(s)}processEvent(t,s=!1){m.debug("kos event received");const{body:o,headers:r}=t.body,n=r["request-id"]||r["response-id"],i=r["request-id"]||r["response-id"]||r.topic||r.type;if(i){let c=i;if(n)c=`${c}-${s?"send":"receive"}`;else{const d=this._topicMap.get(i)||0;c=`${c}-${d+1}`,this._topicMap.set(i,d+1)}const l={msgId:c,content:o,headers:r,timestamp:Date.now(),raw:Zf({headers:r,body:o}),direction:s?"send":"receive",mocked:!!r.mocked};this.events.set(c,l),m.debug(`logged ${this.events.size} events`)}}};Er([R({topic:[Gt.SEND]})],exports.WsEventModel.prototype,"handleSendEvent",1);Er([R({topic:[Gt.RECEIVED]})],exports.WsEventModel.prototype,"handleReceiveEvent",1);exports.WsEventModel=Er([S(_r.type)],exports.WsEventModel);const wn=ee(),Jf=wn.debug==="true"||wn.debug===!0,Xf="/api/system/canvas",Tc=async(e,t)=>{const s=t||Xf,o=`${exports.BASE_URL}${s}`;await exports.kosFetch(o,{method:"POST",headers:{hide:Jf?"true":"false"},body:e})},Qf=Object.freeze(Object.defineProperty({__proto__:null,sendCanvasData:Tc},Symbol.toStringTag,{value:"Module"})),em=(e,t,s)=>e>>5<<5|t>>5<<2|s>>6;function tm(e,t,s){if(t==="base64"){const o=s?e.filter((r,n)=>n%4!==3):Array.from(e);return btoa(String.fromCharCode(...o))}else{const o=[];for(let r=0;r<e.length;r+=4)o.push(em(e[r],e[r+1],e[r+2]));return String.fromCharCode(...o)}}var sm=Object.defineProperty,om=Object.getOwnPropertyDescriptor,$c=(e,t,s,o)=>{for(var r=o>1?void 0:o?om(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&sm(t,s,r),r};const Oc="canvas-renderer-model";function Mn(e){return typeof e.onDone=="function"}let Rs=class{constructor(e,t,s){a(this,"id");a(this,"router");a(this,"logger");a(this,"_renderer",null);a(this,"isStreaming",!1);a(this,"renderLoopId",null);a(this,"sendIntervalId",null);a(this,"timeoutId",null);a(this,"apiPath");a(this,"endpointName");a(this,"width",50);a(this,"height",30);a(this,"fps",10);a(this,"durationMs",null);a(this,"_onFrame",null);this.id=e,this.logger=s.logger,this.width=t.width??50,this.height=t.height??30,this.fps=t.fps??10,this.durationMs=t.durationMs??null,this.apiPath=t.apiPath??"/api/system/canvas",this.endpointName=t.endpoint}set onFrame(e){this._onFrame=e}set renderer(e){var t,s;this._renderer&&(this.stopStreaming(),(s=(t=this._renderer).dispose)==null||s.call(t)),this._renderer=e,this.isStreaming&&this.startStreaming()}sendDataFrame(e,t){Tc(e,t)}checkStreaming(){if(this.isOneShotDone()||!this.isStreaming){requestAnimationFrame(()=>{this.stopStreaming()});return}}handleFrame(e){var s;const t=tm(e,"base64",!0);this.sendDataFrame(t,this.apiPath),(s=this._onFrame)==null||s.call(this,t)}stopStreaming(){var e,t;this.isStreaming=!1,this.renderLoopId&&cancelAnimationFrame(this.renderLoopId),this.sendIntervalId&&clearInterval(this.sendIntervalId),this.timeoutId&&clearTimeout(this.timeoutId),(t=(e=this._renderer)==null?void 0:e.pause)==null||t.call(e)}isOneShotDone(){var e,t;return Mn(this._renderer)&&((t=(e=this._renderer).isOneShot)==null?void 0:t.call(e))===!0&&this._renderer.isOneShotDone}startStreaming(){var e,t,s,o;{if(!this._renderer)return;if(!this.apiPath){this.logger.error(`No endpoint configured for canvas renderer ${this.id}`);return}this.isStreaming=!0,this._renderer.reset(),(t=(e=this._renderer).play)==null||t.call(e);const r=Mn(this._renderer);this._renderer.renderFrame(this.width,this.height);const n=(o=(s=this._renderer).readPixels)==null?void 0:o.call(s,this.width,this.height);if(n&&this._onFrame&&this.handleFrame(n),this.isOneShotDone()){requestAnimationFrame(()=>{this.stopStreaming()});return}const i=()=>{var c;(c=this._renderer)==null||c.renderFrame(this.width,this.height),this.renderLoopId=requestAnimationFrame(i)};this.renderLoopId=requestAnimationFrame(i),this.sendIntervalId=setInterval(()=>{var l,d;const c=(d=(l=this._renderer)==null?void 0:l.readPixels)==null?void 0:d.call(l,this.width,this.height);c&&this._onFrame&&(this.handleFrame(c),this.checkStreaming())},1e3/this.fps),!r&&this.durationMs!=null&&(this.timeoutId=setTimeout(()=>{this.stopStreaming()},this.durationMs))}}async init(){this.logger.debug(`initializing canvas-renderer ${this.id}`)}async load(){this.logger.debug(`loading canvas-renderer ${this.id}`),this.router.use("POST",`/api/ui/canvas/${this.endpointName}/stop`,async(e,t)=>{this.stopStreaming(),t.send({status:"OK"})}),this.router.use("POST",`/api/ui/canvas/${this.endpointName}/start`,async(e,t)=>{this.startStreaming(),t.send({status:"OK"})})}};$c([Ce({modelType:Ys.type})],Rs.prototype,"router",2);Rs=$c([S(Oc)],Rs);const Ir=new ce({class:Rs,type:Oc});class rm{constructor(t){a(this,"video");a(this,"canvas");a(this,"ctx");a(this,"lastUpdate",0);a(this,"doneCallback",null);this.video=document.createElement("video"),this.video.src=t,this.video.crossOrigin="anonymous",this.video.muted=!0,this.video.loop=!1,this.canvas=document.createElement("canvas");const s=this.canvas.getContext("2d");if(!s)throw new Error("2D canvas not supported");this.ctx=s,this.handleEnded=this.handleEnded.bind(this),this.video.addEventListener("ended",this.handleEnded)}handleEnded(){this.doneCallback&&this.doneCallback()}reset(){this.video.pause(),this.video.currentTime=0,this.lastUpdate=performance.now()}play(){this.video.play().catch(console.warn)}pause(){this.video.pause()}renderFrame(t,s){this.canvas.width=t,this.canvas.height=s,this.video.readyState>=2&&this.ctx.drawImage(this.video,0,0,t,s)}readPixels(t,s){return this.ctx.getImageData(0,0,t,s).data}onDone(t){this.doneCallback=t}dispose(){this.video.pause(),this.video.removeAttribute("src"),this.video.load(),this.video.remove(),this.video.removeEventListener("ended",this.handleEnded),this.doneCallback=null}shouldStep(t){const s=performance.now();return s-this.lastUpdate>=t?(this.lastUpdate=s,!0):!1}}class nm{constructor(){a(this,"canvas");a(this,"gl");a(this,"lastWidth",0);a(this,"lastHeight",0);a(this,"lastUpdate",0);this.canvas=document.createElement("canvas");const t=this.canvas.getContext("webgl");if(!t)throw new Error("WebGL not supported");this.gl=t}shouldStep(t){const s=performance.now();return s-this.lastUpdate>=t?(this.lastUpdate=s,!0):!1}readPixels(t=this.lastWidth,s=this.lastHeight){const o=new Uint8Array(t*s*4);this.gl.readPixels(0,0,t,s,this.gl.RGBA,this.gl.UNSIGNED_BYTE,o);const r=new Uint8ClampedArray(o.length);for(let n=0;n<s;n++){const i=n*t*4,c=(s-1-n)*t*4;r.set(o.subarray(i,i+t*4),c)}return r}}class im extends nm{constructor({speedPx:s=1}={}){super();a(this,"program");a(this,"posBuffer");a(this,"aPosition");a(this,"uMinHue");a(this,"uMaxHue");a(this,"uHueOffset");a(this,"uGridHeight");a(this,"minHue",0);a(this,"maxHue",80);a(this,"hueOffset",0);a(this,"speedPx",1);this.speedPx=s;const o=this.gl,r=`
|
|
77
|
+
["${t}"]`;if(r?(m=this.fosSocket)==null?void 0:m.connectionEstablished:(v=this.socket)==null?void 0:v.connectionEstablished){const E=r?this.fosSocket:this.socket;(w=E==null?void 0:E.socket)==null||w.send(u)}else{Ae.debug("no connection adding to offline messages");const E=r?this.fosSocket:this.socket;E==null||E.addOfflineMessage(u)}}subscribeTopic({topic:t,callback:s,fos:r,bridge:o,destinationAddress:n}){const{unsubscribe:i,count:a}=O(t,s);return Ae.debug(`Topic ${t} currently has ${a} subscribers`),this._sendSubscriptionMessage(t,"subscribe",r,o,n),()=>{const{count:c}=i();Ae.debug(`Topic ${t} currently has ${c} subscribers`),c===0&&this._sendSubscriptionMessage(t,"unsubscribe",r,o,n)}}async whenReady(){const t=this;return this.webSocketSupported?(await M.when(()=>{var s,r;return!!((s=t.socket)!=null&&s.connectionEstablished)&&(!t.useFosTransport||!!((r=t.fosSocket)!=null&&r.connectionEstablished))&&t.authorized}),{status:"success"}):{status:"not supported"}}get token(){return this._token}set token(t){this._token=t,this.init()}static host(t="localhost"){return this.getInstance().host=t,this}static port(t=8080){return this.getInstance().port=t,this}static alias(t){this.getInstance().alias=t}static getInstance(t=8080,s){if(!this._instance){const r=window.kosUseFos?{port:window.kosFosPort||8081}:void 0;this._instance=new this({port:t,token:s,fos:r})}return this._instance}}l(Xt,"_instance");class ih{constructor(t,s,r,o,n){l(this,"disposers",[]);l(this,"activatableDisposers",[]);this.model=t,this.modelData=s,this.modelId=r,this.offlineQueue=o,this.log=n}registerAll(t){var o;const s=((o=this.modelData)==null?void 0:o[W])||{},r=Object.keys(s);this.log.debug(`Found ${r.length} subscriptions in ${this.modelId} (lifecycle: ${t??"any"})`),r.forEach(n=>{const i=s[n],a=i.lifecycle;if(t&&t!==a)return;const c=this.resolvePropKey(n);this.log.debug(`Resolved topic: ${n} → ${c}`);const d=this.createHandler(c,i);this.subscribe(i,c,d,a===B.ACTIVATE)})}deactivate(){this.log.debug(`Deactivating subscriptions for ${this.modelId}`);for(const t of this.activatableDisposers)try{t()}catch(s){this.log.error("Error during subscription disposal",s)}this.activatableDisposers=[]}disposeAll(){const t=[...this.disposers,...this.activatableDisposers];this.log.debug(`Disposing ${t.length} subscriptions for ${this.modelId}`);for(const s of t)try{s()}catch(r){this.log.error("Error during subscription disposal",r)}this.disposers=[],this.activatableDisposers=[]}subscribe(t,s,r,o){const n=t.destinationAddress?this.resolvePropKey(t.destinationAddress):null;if(t.websocket){this.log.debug(`Subscribing to WebSocket topic: ${s}`);const i=Xt.getInstance().subscribeTopic({topic:s,callback:r,fos:t.fos,bridge:t.bridge,destinationAddress:n});this.disposers.push(i)}else{this.log.debug(`Subscribing to EventBus topic: ${s}`);const{unsubscribe:i}=O(s,r);o?this.activatableDisposers.push(i):this.disposers.push(i)}}createHandler(t,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;if(this.model.isReady()){const c=Dr(r,s.skipParse),d=s.transform(c);if(a&&s.condition(d,this.modelData,r))return s.handler.call(this.modelData,d,r,this.modelData)}else{this.log.warn(`Model ${this.modelId} not ready. Queuing message for ${t}`);const c=()=>{const d=Dr(r,s.skipParse),u=s.transform(d);if(a&&s.condition(u,this.modelData,r))return s.handler.call(this.modelData,u,r,this.modelData)};this.offlineQueue.enqueue(c)}}catch(n){this.log.error(`Error handling subscription for ${t}`,n)}}}resolvePropKey(t){const s=/.*({PROP_(.+)})/;let r=t.includes("{MODEL_ID}")?t.replace("{MODEL_ID}",this.modelId):t;const o=r.match(s);return o&&o[2]in this.modelData&&(r=r.replace(o[1],this.modelData[o[2]])),r}}function ut(e,t){const s=`[Model:${t}]`;return{debug:(...r)=>e.debug(s,...r),info:(...r)=>e.info(s,...r),warn:(...r)=>e.warn(s,...r),error:(...r)=>e.error(s,...r)}}function ah(e){return!!(e!=null&&e[xe])&&Object.keys(e[xe]).length>0}function ch(e){return!!(e!=null&&e[W])&&Object.keys(e[W]).length>0}class lh{static createAll(t){const{modelId:s,modelTypeName:r,modelData:o}=t,n=Vu.create({modelId:s,modelTypeName:r}),i=new zu(t,ut(n,"fsm")),a=new Yu(ut(n,"offline-queue")),c=new ku(t),d=new Fu(t),u={fsm:i,offlineQueue:a,companionManager:c,childResolver:d};if(ah(o)&&(u.effectManager=new Nu(r,s,o,ut(n,"effect"))),ch(o)){const h=ut(n,"subscription");u.subscriptionManager=new ih(t,o,s,a,h),u.onlineLifecycleManager=new qu(t,ut(n,"online"))}return u}}const P=S.getLogger("kos-model"),dh="kos.extension.model.loader";class ua{constructor({modelTypeName:t,id:s,modelData:r}){l(this,"_id");l(this,"_status");l(this,"_activeStatus");l(this,"_onlineStatus");l(this,"modelData");l(this,"modelTypeName");l(this,"initialized");l(this,"loaded");l(this,"offlineQueue");l(this,"subscriptionManager");l(this,"effectManager");l(this,"onlineLifecycleManager");l(this,"companionManager");l(this,"childResolver");l(this,"fsm");this._id=typeof s<"u"?`${s}`:t,this.modelTypeName=t,this.initialized=!1,this.loaded=!1,this.modelData=r,this._status=b.CREATED,this._activeStatus=b.INACTIVE,this._onlineStatus=b.OFFLINE;const o=lh.createAll(this);this.fsm=o.fsm,this.offlineQueue=o.offlineQueue,this.companionManager=o.companionManager,this.childResolver=o.childResolver,o.effectManager&&(this.effectManager=o.effectManager),o.subscriptionManager&&(this.subscriptionManager=o.subscriptionManager),o.onlineLifecycleManager&&(this.onlineLifecycleManager=o.onlineLifecycleManager),M.makeAutoObservable(this,{fsm:!1,effectManager:!1,subscriptionManager:!1,onlineLifecycleManager:!1,companionManager:!1,childResolver:!1,offlineQueue:!1}),xu(this)}get companionModels(){return this.companionManager}set status(t){this._status=t}get status(){return this._status}get modelId(){return this._id}get id(){return this._id}get activeStatus(){return this._activeStatus}set activeStatus(t){this._activeStatus=t}get onlineStatus(){return this._onlineStatus}set onlineStatus(t){this._onlineStatus=t}get modelManager(){return globalThis.kos.modelManager}isActive(){return this._status===b.ACTIVE}isOnline(){return this._onlineStatus===b.ONLINE}isReady(){return this._status===b.READY}async deactivate(){var t,s,r;P.debug(`deactivating model ${this.modelTypeName} with id ${this.modelId}`);try{const o=N.getContext(this.modelId);await((s=(t=this.modelData)==null?void 0:t.deactivate)==null?void 0:s.call(t,o)),P.debug(`Model ${this.modelTypeName} with id ${this.modelId} deactivated`),(r=this.subscriptionManager)==null||r.deactivate()}catch(o){throw P.debug(`Model ${this.modelId} failed to deactivated`),o}}async activate(){var t,s,r;P.debug(`activating model ${this.modelTypeName} with id ${this.modelId}`),await gt(this,B.ACTIVATE);try{const o=N.getContext(this.modelId);await((s=(t=this.modelData)==null?void 0:t.activate)==null?void 0:s.call(t,o)),P.debug(`Model ${this.modelTypeName} with id ${this.modelId} subscribing to all topics`),(r=this.subscriptionManager)==null||r.registerAll(B.ACTIVATE),P.debug(`Model ${this.modelTypeName} with id ${this.modelId} activated`)}catch(o){throw P.debug(`Model ${this.modelId} failed to activate`),o}}async whenInitialized(){await ln([{condition:()=>this.status===b.FAILED,onMatch:()=>{throw new Error(`Failed to initialize model ${this.modelId}`)}},{condition:()=>this.initialized,onMatch:()=>{P.debug(`Model ${this.modelId} is initialized`)}}])}async whenReady(){await ln([{condition:()=>this.status===b.FAILED,onMatch:()=>{throw new Error(`Failed to ready model ${this.modelId}`)}},{condition:()=>this.status===b.READY,onMatch:()=>{P.debug(`Model ${this.modelId} is ready`)}}])}async ready(){var t,s,r;if(this.fsm.current===b.READY){P.debug(`already readying model ${this.modelTypeName} with id ${this.modelId} returning`);return}try{P.debug(`readying model ${this.modelTypeName} with id ${this.modelId}`),await gt(this,B.READY),await Zi(this,ao.READY,B.READY);const o=N.getContext(this.modelId);await((s=(t=this.modelData)==null?void 0:t.ready)==null?void 0:s.call(t,o)),this.offlineQueue.flush(),(r=this.subscriptionManager)==null||r.registerAll(B.READY),P.debug(`Model ${this.modelId} is ready`);const n={modelId:this.modelId,modelType:this.modelTypeName};U(ki(this.modelTypeName,this.modelId),n),U(Ni(this.modelTypeName),n)}catch(o){throw P.error(o),Error(o)}}async load(){var r,o,n,i;const{modelTypeName:t,modelId:s}=this;if(this.fsm.current===b.LOADED||this.fsm.current===b.LOADING){P.debug(`Model ${t} with id ${s} already loaded or loading`);return}P.debug(`Loading model ${t} with id ${s}`),await gt(this,B.LOAD);try{const a=N.getContext(s),c=`${dh}.${t}`,d=await $.loader.executeLoader(c,{});d&&(P.info(`Setting loaded context for ${s}, type: ${t}`),a==null||a.set(c,d)),await((o=(r=this.modelData)==null?void 0:r.load)==null?void 0:o.call(r,a)),this.loaded=!0,P.debug(`Model ${t} with id ${s} successfully loaded`),(n=this.subscriptionManager)==null||n.registerAll(B.LOAD),(i=this.effectManager)==null||i.setup()}catch(a){throw P.error(`Model ${s} failed to load`,a),a}}async unload(){var t,s,r,o,n;P.debug(`unloading model ${this.modelTypeName} with id ${this.modelId}`);try{const i=this.getChildren().map(c=>{var d;return(d=c.unload)==null?void 0:d.call(c)}).filter(c=>!!c);await Promise.allSettled(i);const a=N.getContext(this.modelId);await((s=(t=this.modelData)==null?void 0:t.unload)==null?void 0:s.call(t,a)),this.loaded=!1,(r=this.onlineLifecycleManager)==null||r.dispose(),P.debug(`Model ${this.modelTypeName} with id ${this.modelId} unloaded`),(o=this.effectManager)==null||o.disposeAll(),(n=this.subscriptionManager)==null||n.disposeAll()}catch(i){throw P.debug(`Model ${this.modelId} failed to unload`),i}}async init(){var o,n,i;const{modelId:t,modelTypeName:s}=this,r=N.getContext(t);P.debug(`Initializing model ${s} with id ${t}`),await gt(this,B.INIT);try{await((n=(o=this.modelData)==null?void 0:o.init)==null?void 0:n.call(o,r)),this.initialized=!0,P.debug(`Model ${s} with id ${t} initialized`),(i=this.onlineLifecycleManager)==null||i.register(),this.registerSubscribers(B.INIT)}catch(a){throw P.error(`Model ${t} failed to initialize`,a),a}}async registerSubscribers(t){var s;P.debug(`registering subscribers in ${this.modelTypeName} with id ${this.modelId}`),(s=this.subscriptionManager)==null||s.registerAll(t)}async online(){var s,r;P.debug(`online model ${this.modelTypeName} with id ${this.modelId}`),this.registerSubscribers();const t=N.getContext(this.modelId);await((r=(s=this.modelData)==null?void 0:s.online)==null?void 0:r.call(s,t))}async offline(){var s,r,o;P.debug(`offline model ${this.modelTypeName} with id ${this.modelId}`),(s=this.subscriptionManager)==null||s.disposeAll();const t=N.getContext(this.modelId);await((o=(r=this.modelData)==null?void 0:r.offline)==null?void 0:o.call(r,t))}accept(t){t.visit(this)}getChildren(){return this.childResolver.resolve()}addCompanionModel(t){this.companionManager.add(t)}clearCompanionModels(){this.companionManager.clear()}}const ha=e=>typeof e=="function",fn=p.createLogger({name:"kos-model-instantiator"});class uh{constructor(t,s){this.registry=t,this.cache=s}createModelInstance(t,s,r={}){const o=this.registry.models[t];if(!o)throw new Error(`No model registered for type ${t}`);const n=o.singleton?t:s;if(this.cache.restoreFromDeleteCache(n),!this.cache.hasModel(n)){fn.debug(`Creating model instance: ${t} [${n}]`);const a=o.create?o.create({modelTypeId:t,id:n,options:r}):new o.class(n,r),c=new ua({modelTypeName:t,id:n,modelData:a});this.cache.addModel(c),this._createCompanionModels(c,r)}const i=this.cache.getModelById(n);if(!i)throw fn.error(`Model ${t} [${n}] not found in cache`),new Error(`Model ${t} [${n}] not found in cache`);return{model:i,data:i.modelData}}_createCompanionModels(t,s){var n;const r=t.modelTypeName,o=((n=this.registry.companionModels)==null?void 0:n[r])||[];for(const{type:i}of o){const a=ha(i)?i(t.modelData,s):i;if(!a)continue;const c=`${a}-${t.modelId}`,d=this.createModelInstance(a,c,{data:s,companionParent:t.modelData,kosParentId:t.modelId});d!=null&&d.model&&t.addCompanionModel(d.model)}}}let hh=class{constructor(t){this._registry=t}get registry(){return this._registry}getModelTypeRegistry(t){const s=this.registry.models[t];if(!s)throw new Error(`No registration for model type ${t}`);return s}registerModel(t){const s=t.type;this.registry.models[s]||(this.registry.models={...this.registry.models,...t.registration})}registerCompanionModel(t,s){var r,o;(r=this.registry).companionModels??(r.companionModels={}),(o=this.registry.companionModels)[t]??(o[t]=[]),this.registry.companionModels[t].some(n=>n.type===s)||this.registry.companionModels[t].push({type:s})}getModelSubscriptions(t){var s;return((s=this.getModelTypeRegistry(t))==null?void 0:s.subscriptions)||{}}getDataModelBuilder(t){var r;const s=(r=this.getModelTypeRegistry(t))==null?void 0:r.builder;if(!s)throw new Error(`No builder found for model type ${t}`);return s}getModelFactory(t){return it(t)}};const fa=10,gn=p.createLogger({name:"kos-model-manager"});class ga{constructor(){l(this,"cache");l(this,"instantiator");l(this,"dependencies");l(this,"_registry");globalThis.kos=globalThis.kos||{},this.dependencies=new du,globalThis.kos.modelManager=this,globalThis.kos.resolveKosModel=t=>{const s=this.getModelById(t);if(s)return s.modelData||{}},globalThis.kos.kosModelJson=t=>{var r,o;const s=this.getModelById(t);if(s)return((o=(r=s.modelData).toJSON)==null?void 0:o.call(r))||{}},globalThis.kos.kosModelDebug=t=>{var r;const s=this.getModelById(t);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(t,s){const r=this.getInstance(s);return r._registry=new hh(t),r.cache=new uu(t.preloadModels),r.instantiator=new uh(t,r.cache),r}static getInstance(t){var s,r;return(!((s=globalThis.kos)!=null&&s.modelManager)||t)&&(gn.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(t=>(gn.debug(`preloading ${t}`),typeof t=="string"?this.createModelInstance(t).model:this.createModelInstance(t.modelType,t.modelId,t.options).model))}get models(){return this.cache.models}getModelById(t){return this.cache.getModelById(t)}addModel(t){return this.cache.addModel(t)}removeModel(t){this.cache.removeModel(t.modelId)}hasModel(t){return this.cache.hasModel(t)}getModelsByType(t,s){return Array.from(this.models).filter(r=>r.modelTypeName===t).filter(r=>s?s(r.modelData):!0).map(r=>r.modelData)}getModelSubscriptions(t){return this._registry.getModelSubscriptions(t)}getDataModelBuilder(t){return this._registry.getDataModelBuilder(t)}getModelFactory(t){return it(t)}addDependency(t,s){this.cache.restoreFromDeleteCache(s),this.dependencies.add(t,s)}removeDependency(t,s){this.dependencies.remove(t,s)}async reloadModel(t){if(t.id){const s=this.getModelById(t.id);s&&await s.fsm.transitionTo(A.RESET,b.RESETTING)}}async initiateDestroyModel(t){if(!t.id)throw new Error("Model ID is required");if(!this.dependencies.canDestroy(t.id))return;const s=this.getModelById(t.id);s&&(this.cache.markForDeletion(s),Di.addToDeletionQueue(t.id,setTimeout(()=>this.destroyModel(s),fa)))}async destroyModel(t){var s;t!=null&&t.modelId&&this.dependencies.canDestroy(t.modelId)&&(await((s=t.unload)==null?void 0:s.call(t)),this.removeModel(t))}createModelInstance(t,s,r={}){return this.instantiator.createModelInstance(t,s,r)}registerCompanionModel(t,s){this._registry.registerCompanionModel(t,s)}registerModel(t){this._registry.registerModel(t)}}const fh=async({context:e,extension:t})=>{const s=await $.loader.executeLoader(t,{});return e==null||e.set(t,s),s},gh=async({extension:e,contextData:t,data:s})=>await $.dataMapper.executeMapper(e,s,t),ph=async({extension:e,contextData:t,data:s})=>await $.propertyMapper.executeMapper(e,s,t),mh=Object.freeze(Object.defineProperty({__proto__:null,executeDataMapperExtension:gh,executeLoaderExtension:fh,executePropertyMapperExtension:ph},Symbol.toStringTag,{value:"Module"})),yh="Extensions";class bh{constructor(){l(this,"extensions");this.extensions={}}register(t,s,r){this.extensions[t]={},this.extensions[t][s]={component:r}}get(t,s){if(!this.extensions[t])throw new Error(`Extension point ${t} not found`);return this.extensions[t][s]}get allExtensions(){return this.extensions}}var ws=(e=>(e.CREATING="creating",e.CREATED="created",e.INITIALIZING="initializing",e.INITIALIZED="initialized",e.LOADING="loading",e.LOADED="loaded",e.ONLINE="online",e.READYING="readying",e.READY="ready",e.OFFLINE="offline",e.UNLOADING="unloading",e.UNLOADED="unloaded",e.RELOADING="reloading",e))(ws||{}),Ve=(e=>(e.CREATE="create",e.INITIALIZE="init",e.READY="ready",e.GO_ONLINE="go_online",e.GO_OFFLINE="go_offline",e.UNLOAD="unload",e.RELOAD="reload",e))(Ve||{});const wh=e=>{const t=y.createMachine("offline",{online:y.state(y.transition("go_offline","offline",y.action(()=>{e.offline(),M.runInAction(()=>{e.isOnline=!1})}))),offline:y.state(y.transition("go_online","online",y.action(()=>{e.online(),M.runInAction(()=>{e.isOnline=!0})})))}),s=y.interpret(t,n=>S.debug(n.machine.current)),r=y.createMachine({creating:y.state(y.transition("create","created")),created:y.state(y.immediate("initializing")),initializing:y.invoke(()=>e.init(),y.transition("done","initialized")),initialized:y.state(y.immediate("loading")),loading:y.invoke(()=>e.load(),y.transition("done","loaded")),loaded:y.state(y.immediate("readying"),y.transition("unload","unloading")),readying:y.invoke(()=>e.ready(),y.transition("done","ready",y.action(()=>{M.runInAction(()=>{e.status="ready"})}))),reloading:y.invoke(()=>e.reload(),y.transition("done","loading")),ready:y.state(y.transition("reload","reloading"),y.transition("unload","unloaded",y.action(e.unload.bind(e))),y.transition("go_online","ready",y.action(()=>{s.send("go_online")})),y.transition("go_offline","ready",y.action(()=>{s.send("go_offline")}))),unloaded:y.state()});return{service:y.interpret(r,n=>S.debug(n.machine.current)),online:s}},re=async e=>{if(e.id){const t=I.getInstance().modelManager.getModelById(e.id);if(!t)throw new Error(`Model with ID ${e.id} not found`);await(t==null?void 0:t.whenReady())}else throw new Error("Data model must have a valid ID");return e},Le=async e=>{await I.getInstance().whenReady(),await I.getInstance().modelManager.initiateDestroyModel(e)},vh=async e=>{if(await I.getInstance().whenReady(),!e.id)throw new Error("Model ID is required");const t=I.getInstance().modelManager.getModelById(e.id);t&&await t.fsm.transitionTo(A.UNLOAD,b.UNLOADED)},pa=async e=>{await I.getInstance().whenReady(),await I.getInstance().modelManager.reloadModel(e),p.debug(`reload model initiated for model ${e.id}, model ready: ${Ts(e)} - ${Date.now()} `),await re(e),p.debug(`reload model complete for model ${e.id}, model ready: ${Ts(e)} - ${Date.now()} `)},Mh=async e=>{if(await I.getInstance().whenReady(),!e)throw new Error("Model ID is required");const t=I.getInstance().modelManager.getModelById(e);return t==null?void 0:t.modelTypeName},ma=async e=>{if(await I.getInstance().whenReady(),!e)throw new Error("Model ID is required");const t=I.getInstance().modelManager.getModelById(e);return{model:t==null?void 0:t.modelData,type:t==null?void 0:t.modelTypeName}},Ue=e=>{if(!e)throw new Error("Model ID is required");const t=I.getInstance().modelManager.getModelById(e);return{model:t==null?void 0:t.modelData,type:t==null?void 0:t.modelTypeName}},ya=(e,t)=>{if(!e)throw new Error("Model type is required");return I.getInstance().modelManager.getModelsByType(e).filter(o=>Object.keys(t).every(n=>o[n]===t[n]))},Eh=(e,t)=>ya(e,t)[0],_h=(e,t)=>{if(!e.id)throw new Error("Model ID is required");const s=I.getInstance().modelManager.getModelById(e.id);if(!s)throw new Error("Model not found");const r=s.companionModels.get(t);return r==null?void 0:r.modelData},Ih=e=>{if(!e.id)throw new Error("Model ID is required");const t=I.getInstance().modelManager.getModelById(e.id);if(!t)throw new Error("Model not found");return Array.from(t.companionModels.all()).map(r=>r.modelData)},Th=e=>{if(!e)throw new Error("Model ID is required");const t=I.getInstance().modelManager.getModelById(e);if(!t)throw new Error("Model not found");return t.companionModels.data},Ar=(e,t)=>{const s=I.getInstance().modelManager.getModelById(e);if(!s){p.info(`Model not found for id ${e}`);return}return Array.from(s.companionModels.all()).find(o=>t(o.modelData))},ae=e=>t=>Object.getPrototypeOf(t).modelTypeId===e,Ts=e=>{const t=I.getInstance().modelManager.getModelById(e.id);if(!t)throw new Error("Model not found");return t.isReady()},Oh=p.createLogger({name:"kos-model-factory"}),xt={byModelType:e=>I.getInstance().modelManager.getModelFactory(e),getModelInstance:(e,t,s)=>{const r=xt.byModelType(t);if(!r)throw Oh.error(`No registered factory found for model type ${t}. Please register a factory for this model type. `),Error(`No factory found for model type ${t}`);return r.build(e,s)}},J={Factory:{create:e=>t=>(s,r)=>(r&&N.setParentContext(t,r),xt.getModelInstance(t,e,s))},Singleton:{create:e=>(t,s)=>(s&&N.setParentContext(e,s),xt.getModelInstance(e,e,t))},Model:{instance:e=>t=>xt.getModelInstance(t,e)}};window.KosRegistry=window.KosRegistry||{coreModels:new Map,preloadModels:[],companionModels:new Map,models:new Map};const pn=window.KosRegistry.coreModels,yr=window.KosRegistry.preloadModels,br=window.KosRegistry.companionModels,as=window.KosRegistry.models,D={model:{registerLegacyModel:e=>(t,s)=>(pn.set(t,s),{preload:D.model.preloadModel(e),model:D.model.register(e),companion:D.companion.register(e),legacy:D.model.registerLegacyModel(e),root:e}),preloadModel:e=>t=>(yr.includes(t)||yr.push(t),{preload:D.model.preloadModel(e),model:D.model.register(e),companion:D.companion.register(e),legacy:D.model.registerLegacyModel(e),root:e}),register:e=>(t,s)=>{const r=wr(t)?t.registration():t;return as.set(r.type,r),wr(t)&&t.relatedModels.forEach(o=>as.set(o.type,o.registration())),I.getInstance().isReady&&(I.getInstance().modelManager.registry.models[r.type]||(console.info(`Model with type ${r.type} doesn't exist. Adding new registration`),I.getInstance().modelManager.registry.models[r.type]=r.registration[r.type],wr(t)&&t.relatedModels.forEach(o=>I.getInstance().modelManager.registry.models[o.type]=o.registration().registration))),s&&D.model.preloadModel(e)(r.type),{preload:D.model.preloadModel(e),model:D.model.register(e),companion:D.companion.register(e),legacy:D.model.registerLegacyModel(e),root:e}},get:e=>as.get(e),getAll:()=>Array.from(as.entries()),getPreloadModels:()=>yr,getLegacyModels:()=>Array.from(pn.entries()).reduce((e,[t,s])=>(e[t]=s,e),{})},companion:{register:e=>(t,s)=>{const r=br.get(t)||[];return r.push(s),br.set(t,r),{preload:D.model.preloadModel(e),model:D.model.register(e),companion:D.companion.register(e),legacy:D.model.registerLegacyModel(e),root:e}},getAll:()=>Array.from(br.entries())}},ba=D.model.registerLegacyModel,wa=D.model.register,Sh=D.companion.register,$h=D.model.preloadModel,va=e=>typeof e.updateModel=="function",wr=e=>e.registration!==void 0&&typeof e.registration=="function";class Ma{constructor(t){l(this,"singleton");l(this,"type");l(this,"loader");l(this,"class");l(this,"guard");l(this,"factory");l(this,"relatedModels",[]);this.singleton=t.singleton,this.guard=ae(t.type),this.type=t.type,this.loader=`kos.extension.model.loader.${t.type}`,this.factory=t.factory,this.class=t.class}addRelatedModel(t){this.relatedModels.push(t)}registerRelatedModels(){this.relatedModels.forEach(t=>t.register())}register(){D.model.register({})(this.registration()),this.registerRelatedModels()}}class ge extends Ma{constructor(t){super({...t,singleton:!1,factory:J.Factory.create(t.type)})}instance(t){const s=this.factory(t);return{get:()=>{const r=Ue(t);if(!r)throw new Error("Model not found with id "+t);if(this.guard(r))return r;throw new Error("Model is not of type "+this.type)},forceUpdate:{options:r=>({build:()=>{const o=s(r);if(this.guard(o)){if(va(o))o.updateModel(r);else throw new Error(`Model ${this.type} is not updateable. Please implement UpdateAware interface`);return o}else throw new Error("Model is not of type "+this.type)}})},options:r=>({build:()=>{const o=s(r);if(this.guard(o))return o;throw new Error("Model is not of type "+this.type)}})}}registration(){return{type:this.type,predicate:this.guard,registration:{[this.type]:{class:this.class,singleton:!1}},factory:this.factory}}}class Ee extends Ma{constructor(t){super({...t,singleton:!0,factory:J.Singleton.create(t.type)})}instance(){const t=this.factory;return{get:()=>{const r=Ue(this.type);if(!r)throw new Error("Model not found with id "+this.type);if(this.guard(r))return r;throw new Error(`Model is not of type ${this.type}. Received type ${Object.getPrototypeOf(r).modelTypeId}`)},forceUpdate:{options:r=>({build:()=>{const o=t(r);if(this.guard(o)){if(va(o))o.updateModel(r);else throw new Error(`Model ${this.type} is not updateable. Please implement UpdateAware interface`);return o}else throw new Error(`Model is not of type ${this.type}. Received type ${Object.getPrototypeOf(o).modelTypeId}`)}})},options:r=>({build:()=>{const o=t(r);if(this.guard(o))return o;throw new Error(`Model is not of type ${this.type}. Received type ${Object.getPrototypeOf(o).modelTypeId}`)}})}}registration(){return{type:this.type,predicate:this.guard,registration:{[this.type]:{class:this.class,singleton:!0}},factory:this.factory}}}const z=p.createLogger({name:"kos-core"}),Dh=()=>{const e=ie(),t=e==null?void 0:e.alias,s=process.env.KOS_CONNECTION_ALIAS;return t||s||void 0},Ch=()=>{const e=window.location.protocol,t=ie(),s=t==null?void 0:t.host;let r;try{r=new URL(s).protocol==="https:"?"wss://":"ws://"}catch{}return r||(e==="https:"?"wss://":"ws://")},Ah=()=>{const e=window.location.hostname,t=process.env.KOS_HOST,s=ie(),r=s==null?void 0:s.host;let o;try{o=new URL(r).hostname}catch{}return o??t??e},Rh=()=>{const e=window.location.port,t=process.env.KOS_PORT,s=ie(),r=s==null?void 0:s.host;let o;try{o=new URL(r).port}catch{}return o??t??e},Ph=(e,t)=>{let s;return{promise:new Promise((n,i)=>{s=setTimeout(()=>{t?p.error(`Model ${t.modelId} - ${t.modelTypeName} preloading - timed out after ${e}ms`):p.error(`KOS Core preloading timed out after ${e}ms`),i(new Error(`Model ${t==null?void 0:t.modelId} - ${t==null?void 0:t.modelTypeName} - timed out after ${e}ms`))},e)}),cancel:()=>{s&&clearTimeout(s)}}},mn=e=>typeof e.reload=="function",xh=e=>typeof e.unload=="function";var Ea=(e=>(e.LOGGED_IN="logged_in",e.LOGGED_OUT="logged_out",e))(Ea||{});class I{constructor(t){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=t,this.loaded=!1,this.isOnline=!1,this.status=ws.CREATED,this.authState="logged_out",this._reloading=!1,this._unloading=!1,M.makeAutoObservable(this),O("token",a=>{a&&(this.transport.token=a.body)}),O(Pt.CONNECTED,async()=>{await this.whenReady(),this.fsmService.service.send(Ve.GO_ONLINE)}),O(Pt.DISCONNECTED,async()=>{this.fsmService.service.send(Ve.GO_OFFLINE)}),O("/studioServer/auth/LOGGED_IN",()=>{this.authState="logged_in",this.transport.authorized=!0}),O("/studioServer/auth/LOGIN_REQUIRED",()=>{this.authState="logged_out",this.transport.authorized=!1}),O(Pt.RELOAD,()=>{this.fsmService.service.send(Ve.RELOAD)}),O("/studio/project/reload",()=>{this.fsmService.service.send(Ve.RELOAD)});const s=Xt.getInstance(),r=Ah(),o=Rh(),n=Ch();s.host=r,s.port=Number.parseInt(o),s.protocol=n,process.env.KOS_ALLOW_ANONYMOUS==="true"&&(s.authorized=!0);const i=Dh()??t;i&&(s.alias=i.replace("{{TIMESTAMP}}",Date.now().toString())),this._transport=s.init(),this.fsmService=wh(this),this.fsmService.service.send(Ve.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 t=Date.now();if(this._reloading){z.info("reload already in progress");return}this._reloading=!0,z.warn("reloading KOS Core"),z.warn("reloading preloaded models");const s=this.modelManager;for(const c of s.preloadedModels)mn(c.modelData)&&(z.info(`reloading model ${c.modelId}`),(o=c.unload)==null||o.call(c),await c.modelData.reload(),(n=c.registerSubscribers)==null||n.call(c),z.info(`reloading model ${c.modelId} complete`));for(const c of s.models)!s.preloadedModels.includes(c)&&mn(c.modelData)&&((i=c.unload)==null||i.call(c),await c.modelData.reload(),(a=c.registerSubscribers)==null||a.call(c));const r=Date.now()-t;setTimeout(()=>{M.runInAction(()=>{z.warn("reloading KOS Core complete"),this._reloading=!1})},1e3-r)}async online(){z.debug("KOS Core going online"),await this._transport.whenReady(),z.debug("KOS Transport Ready. Calling online() for models"),U("/kosCore/online","/kosCore/online"),console.timeEnd("kosCore:startup")}async offline(){z.debug("KOS Core going offline"),U("/kosCore/offline","/kosCore/offline")}async unload(){var o;z.debug("Unloading KOS Core");const t=Date.now();this._unloading=!0,z.debug("unloading KOS Core");const s=this.modelManager;for(const n of s.models)xh(n.modelData)&&((o=n.unload)==null||o.call(n));const r=Date.now()-t;setTimeout(()=>{M.runInAction(()=>{this._unloading=!1})},1e3-r)}async whenReady(){await M.when(()=>this.status===ws.READY)}async ready(){z.debug("Readying KOS Core"),await this._transport.whenReady();const t=this.modelManager.preloadedModels.map(o=>({modelId:o.modelId,model:o,promise:o.whenReady()})),r=(await Promise.allSettled(t.map(o=>{const{promise:n,cancel:i}=Ph(5e3,o.model);Promise.race([o.promise.then(()=>{i()}),n])}))).filter(o=>o.status==="rejected");if(r.length)throw z.error(`There were ${r.length} failed models on model preloading`),Error(`There were ${r.length} failed models on model preloading`);z.debug("leaving kos-core ready() ")}get isReady(){return this.status===ws.READY}set transport(t){this._transport=t}get transport(){return this._transport}get coreInitialized(){return this.initialized}get modelsLoaded(){return this.loaded}async init(){z.debug("entering kos-core init()"),console.time("kosCore:startup"),console.time("kosCore:init"),await this._transport.whenReady(),this.initialized=!0,z.debug("initialized - leaving kos-core init()"),console.timeEnd("kosCore:init")}async load(){z.debug("entering kos-core load()"),console.time("kosCore:load"),this.loaded=!0,z.debug("loaded - leaving kos-core load()"),console.timeEnd("kosCore:load")}static create(t,s,r){var i,a,c;const o=this.getInstance({reset:s,connectionAlias:r});(i=t.extensions)!=null&&i.dataMapper&&Object.keys(t.extensions.dataMapper).forEach(d=>{var h,g;const u=(g=(h=t.extensions)==null?void 0:h.dataMapper)==null?void 0:g[d];u&&(Array.isArray(u)?u.forEach(m=>{$.dataMapper.registerDataMapper(d,m)}):$.dataMapper.registerDataMapper(d,u))}),(a=t.extensions)!=null&&a.propertyMapper&&Object.keys(t.extensions.propertyMapper).forEach(d=>{var h,g;const u=(g=(h=t.extensions)==null?void 0:h.propertyMapper)==null?void 0:g[d];u&&$.propertyMapper.registerPropertyMapper(d,u)}),(c=t.extensions)!=null&&c.contextLoader&&Object.keys(t.extensions.contextLoader).forEach(d=>{var h,g;const u=(g=(h=t.extensions)==null?void 0:h.contextLoader)==null?void 0:g[d];u&&$.loader.registerLoader(d,u)}),D.model.getAll().forEach(([,d])=>{t.models={...t.models,...d.registration}}),t.models={...t.models,...D.model.getLegacyModels()},D.companion.getAll().forEach(([d,u])=>{t.companionModels={...t.companionModels},t.companionModels[d]=t.companionModels[d]||[];for(const h of u)t.companionModels[d].push({type:h})}),D.model.getPreloadModels().forEach(d=>{t.preloadModels.includes(d)||t.preloadModels.push(d)});const n=ga.create(t,s);return o.modelManager=n,o}static getInstance(t){return this._instance=window.KosCore,(!this._instance||t!=null&&t.reset)&&(window.KosCore=new this(t==null?void 0:t.connectionAlias),this._instance=window.KosCore),this._instance}}l(I,"_instance");function Rr(e){const t=new Uint8Array(e);let s="";for(let r=0;r<t.byteLength;r++)s+=String.fromCharCode(t[r]);return btoa(s)}function Lh(e){const t=atob(e),s=new Uint8Array(t.length);for(let r=0;r<t.length;r++)s[r]=t.charCodeAt(r);return s.buffer}async function Fh(e){return await e.arrayBuffer()}function kh(e,t){return new Blob([e],{type:t||"application/octet-stream"})}async function Nh(e){const t={},s=[],r=[];e.forEach((o,n)=>{r.push([n,o])});for(const[o,n]of r)if(n instanceof File){const i=await n.arrayBuffer();s.push({name:o,filename:n.name,type:n.type,data:Rr(i)})}else t[o]=n.toString();return{fields:t,files:s}}function Uh(e){return new ReadableStream({async start(){},async pull(t){await e(t)},cancel(){}})}async function jh(e){if(!e)return{data:"",contentType:"text/plain"};if(typeof e=="string")return{data:e,contentType:"text/plain"};if(e instanceof ArrayBuffer||e instanceof Uint8Array){let t;return e instanceof Uint8Array?(t=new ArrayBuffer(e.byteLength),new Uint8Array(t).set(e)):t=e,{data:Rr(t),contentType:"application/octet-stream",encoding:"base64"}}if(e instanceof Blob){const t=await Fh(e);return{data:Rr(t),contentType:e.type||"application/octet-stream",encoding:"base64"}}if(e instanceof FormData){const t=await Nh(e);return{data:JSON.stringify(t),contentType:"multipart/form-data",encoding:"json"}}throw new Error("Unsupported body type")}const cs=p.createLogger({name:"kos-fetch"}),Bh=process.env.KOS_WS_TIMEOUT?parseInt(process.env.KOS_WS_TIMEOUT):3e4,Kh=()=>new Promise(e=>{setTimeout(()=>{e(!0)},0)}),Hh=e=>e!=null&&e.studio?Qi:e!=null&&e.fos?ea:ta,Gh=async(e,t)=>{const s=I.getInstance().transport;await s.whenReady();const r=nt(),o=new URL(e),n=`${o.pathname}${o.search}`;cs.debug(`path: ${n}`);const i=(t==null?void 0:t.timeout)||Bh,a=Hh(t),c=await jh(t==null?void 0:t.body),d={};c.contentType&&(d["content-type"]=c.contentType),c.encoding&&(d["content-encoding"]=c.encoding);const u=$e(a({path:n,requestId:r,method:(t==null?void 0:t.method)||"GET",destinationAddress:(t==null?void 0:t.destinationAddress)||"",ordered:t==null?void 0:t.ordered,tracker:t==null?void 0:t.tracker,bridge:t==null?void 0:t.bridge,headers:{...t==null?void 0:t.headers,...d}}),c.data);return new Promise(h=>{let g=null,m=null;if(t!=null&&t.signal){if(t.signal.aborted){h({headers:pt({}),status:0,ok:!1,json:async()=>null,body:mt(""),redirected:!1,statusText:"Request aborted",type:"basic",url:"",clone:function(){throw new Error("Function not implemented.")},bodyUsed:!1,arrayBuffer:function(){throw new Error("Function not implemented.")},blob:function(){throw new Error("Function not implemented.")},formData:function(){throw new Error("Function not implemented.")},text:function(){throw new Error("Function not implemented.")}});return}t.signal.addEventListener("abort",()=>{m&&clearTimeout(m),g&&g(),h({headers:pt({}),status:0,ok:!1,json:async()=>null,body:mt(""),redirected:!1,statusText:"Request aborted",type:"basic",url:"",clone:function(){throw new Error("Function not implemented.")},bodyUsed:!1,arrayBuffer:function(){throw new Error("Function not implemented.")},blob:function(){throw new Error("Function not implemented.")},formData:function(){throw new Error("Function not implemented.")},text:function(){throw new Error("Function not implemented.")}})})}m=setTimeout(()=>{cs.error(`Timeout occurred - url: ${e}`),g&&g(),h({headers:pt({}),status:404,ok:!1,json:async()=>null,body:mt(""),redirected:!1,statusText:"",type:"basic",url:"",clone:function(){throw new Error("Function not implemented.")},bodyUsed:!1,arrayBuffer:function(){throw new Error("Function not implemented.")},blob:function(){throw new Error("Function not implemented.")},formData:function(){throw new Error("Function not implemented.")},text:function(){throw new Error("Function not implemented.")}})},i);const v=O(r,E=>{m&&clearTimeout(m);const T=(E==null?void 0:E.headers)||{},K=T["content-type"]||"text/plain",H=T["content-encoding"],ce=(E==null?void 0:E.body)||"";let R=ce;if(H==="base64"&&ce)try{R=Lh(ce)}catch(k){cs.error("Failed to decode base64 response",k)}const G={headers:pt(T),status:T.status&&parseInt(T.status)||200,ok:T.status==="200",json:async()=>{try{if(typeof R=="string")return R.length?JSON.parse(R):null;{const Y=new TextDecoder().decode(R);return Y.length?JSON.parse(Y):null}}catch{throw Error("Not a JSON response")}},text:async()=>typeof R=="string"?R:new TextDecoder().decode(R),arrayBuffer:async()=>R instanceof ArrayBuffer?R:new TextEncoder().encode(R).buffer,blob:async()=>R instanceof ArrayBuffer?kh(R,K):new Blob([R],{type:K}),formData:async()=>{const k=new FormData;if(K==="multipart/form-data"&&typeof R=="string")try{const Y=JSON.parse(R);Y.fields&&Object.entries(Y.fields).forEach(([_e,dt])=>{k.append(_e,dt)}),Y.files&&cs.warn("File reconstruction in FormData not fully implemented")}catch{throw new Error("Failed to parse FormData")}return k},body:t!=null&&t.stream?Uh(async k=>{if(R instanceof ArrayBuffer)k.enqueue(new Uint8Array(R));else{const Y=new TextEncoder;k.enqueue(Y.encode(R))}k.close()}):mt(typeof R=="string"?R:""),redirected:!1,statusText:"",type:"basic",url:"",clone:function(){return{...this}},bodyUsed:!1};v.unsubscribe(),Kh().then(()=>h(G))});g=v.unsubscribe;const w=t!=null&&t.fos?s.fosSocket:s.socket;if(!w)throw Error(`No web socket transport available: ${t}`);w==null||w.send(u)})};exports.BASE_URL="kos:";exports.kosFetch=Gh;if(process.env.KOS_MOCK_FETCH==="true"){const e=process.env.KOS_PORT||"9999";exports.kosFetch=fetch,exports.BASE_URL=`http://localhost:${e}`}const zh=p.createLogger({name:"kos-model-visitor",group:"kos-ui-core"});class Vh{constructor(){l(this,"visitedModels",new Set);this.visitedModels=new Set}start(t){var r;if(t.id===void 0)throw new Error("rootModel must have an id");const s=I.getInstance().modelManager.getModelById(t.id);if(!s)throw new Error(`Could not find rootModel with id: ${t.id}`);this.visitedModels.clear(),(r=s.accept)==null||r.call(s,this)}visit(t){var r;if(this.visitedModels.has(t.modelId)){zh.info(`model ${t.modelId} already visited`);return}const s=!!this.visitModel(t.modelData,this);this.visitedModels.add(t.modelId),!s&&((r=t.getChildren)==null||r.call(t).forEach(o=>{var n;(n=o.accept)==null||n.call(o,this)}))}}const _a=()=>({isMock:!1,URL:exports.BASE_URL}),Yh=p.createLogger({name:"kos-service-request"}),qh="errUnknown";async function ls(e,t,s,r,o){const n=r!=null&&r.path?Object.keys(r.path).reduce((h,g)=>String(h).replace(`{${g}}`,r==null?void 0:r.path[g]),String(e)):String(e),i=r!=null&&r.query?Object.keys(r.query).map(h=>`${h}=${r.query[h]}`).join("&"):"",a=`${_a().URL}${n}${i?`?${encodeURIComponent(i)}`:""}`;Yh.debug(`fullUrl: ${a}`);const c={method:String(t).toUpperCase(),body:null,...s};o&&(c.body=JSON.stringify(o));const d=await exports.kosFetch(a,c);return d.status<200||d.status>=400?[`${d.statusText||qh}`,null]:[null,(await d.json()).data]}function uo(){return{get:(e,t,s)=>ls(e,"get",s,t),post:(e,t,s,r)=>ls(e,"post",r,t,s),put:(e,t,s,r)=>ls(e,"put",r,t,s),delete:(e,t,s)=>ls(e,"delete",s,t)}}class Ia{constructor(){l(this,"middlewares",[])}use(t){this.middlewares.push(t)}async execute(t){let s=0;const r=async()=>{s++,s<this.middlewares.length&&await this.middlewares[s](t,r)};await this.middlewares[s](t,r)}}const Wh=async(e,t)=>{const s=new Ia;t.forEach(o=>s.use(o));const r={data:e,result:{}};return await s.execute(r),r.result},it=e=>({type:e,build:(t,s)=>I.getInstance().modelManager.createModelInstance(e,t,s).data,buildAsync:async(t,s)=>{const r=I.getInstance().modelManager.createModelInstance(e,t,s);return await r.model.whenInitialized(),r.data}}),Zh=e=>{I.getInstance().modelManager.registerModel(e)},Jh=(e,t)=>{I.getInstance().modelManager.registerCompanionModel(e,t)},Ta=Symbol("KosObservableData");class Oa{constructor(){l(this,"map");l(this,"atomMap",new Map);l(this,"proxyHandler",{get:(t,s)=>{var r;return t[s]!==void 0?t[s]:this.atomMap.has(s)&&(r=this.atomMap.get(s))!=null&&r.reportObserved()?this.getValue(s):this.getValue(s)},set:(t,s,r)=>{var o;return this.setValue(s,r),this.atomMap.has(s)||this.atomMap.set(s,M.createAtom(s.toString())),(o=this.atomMap.get(s))==null||o.reportChanged(),!0},ownKeys:()=>Array.from(this.map.keys())});this.map=M.observable.map(new Map)}setValue(t,s){this.map.set(t,s)}getValue(t){return this.map.get(t)}has(t){return this.map.has(t)}get entries(){return Array.from(this.map.entries())}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}setValues(t){t&&Object.keys(t).forEach(s=>{this.setValue(s,t[s])})}get proxy(){return new Proxy(this,this.proxyHandler)}}Oa.prototype[Ta]=!0;function Xh(e,t){return new Proxy(e,{construct:(s,r)=>{const o=new e(...r);return o.setValues(t),o.proxy}})}const Te=e=>{const t=Xh(Oa,e);return new t(e)},yn="/kos/ui/internal/heartbeat/",Qh=({relationshipId:e,destinationAddress:t,onAbort:s,waitTime:r,beatTime:o})=>{const n=I.getInstance().transport,i=new AbortController;let a=performance.now();const c=n.subscribeTopic({topic:`${yn}${e}`,callback:()=>{a=performance.now()}}),d=r??3e3,u=window.setInterval(()=>{let w=performance.now()-a;w=w/1e3,w>d/1e3&&i.abort()},d),h=o??2e3,g=window.setInterval(()=>{ca({msg:{},options:{topic:`${yn}${e}`,destinationAddress:t}})},h),m=()=>{window.clearInterval(g),window.clearInterval(u),c()},v=()=>{m(),s&&s(),i.signal.removeEventListener("abort",v)};return i.signal.addEventListener("abort",v),{cleanUpHeartbeat:m}},Sa=(...e)=>t=>e.reduce((s,r)=>r(s),t),ef={maxAttempts:5,baseDelayMs:100,backoffFactor:1.5};async function tf(e,t){let s=1;const r={...ef,...t},{maxAttempts:o,baseDelayMs:n,backoffFactor:i}=r;let a=n;for(;s<=o;)try{return await e()}catch(c){if(p.error(`Attempt ${s} failed: ${c}`),s<o)a=n*Math.pow(i,s),await new Promise(d=>setTimeout(d,a)),s++;else throw c}throw new Error("All attempts failed")}const sf=p.createLogger({name:"kos-service-request"}),ee=e=>({isMock:!1,URL:exports.BASE_URL}),rf=(e,t,s)=>async({id:r,tracker:o,urlOverride:n,ordered:i,studio:a,fos:c,bridge:d,destinationAddress:u})=>{const h={method:"DELETE"};e&&(h.destinationAddress=e),o&&(h.tracker=o),at(h,{ordered:i,studio:a,fos:c,bridge:d,destinationAddress:u});const g=await s(n||`${t}/${r}`,h);if(!g.ok)throw Error(`There was a problem deleting the model; returned status ${g.status}`);return await g.json()},at=(e,{ordered:t,studio:s,fos:r,destinationAddress:o,bridge:n,timeout:i})=>(i&&(e.timeout=i),t&&(e.ordered=t),s&&(e.studio=s),r&&(e.fos=r),n&&(e.bridge=n),(o||o==="")&&(e.destinationAddress=o),e),of=(e,t,s)=>async({urlOverride:r,ordered:o,studio:n,fos:i,bridge:a,timeout:c,destinationAddress:d})=>{const u={method:"GET"};e&&(u.destinationAddress=e),at(u,{timeout:c,ordered:o,studio:n,fos:i,bridge:a,destinationAddress:d});const g=await s(r||t,u);if(!g.ok){let v;try{v=await g.json()}catch{}throw new ne(`There was a problem retrieving the model; returned status ${g.status}`,v)}return await g.json()},nf=(e,t,s)=>async({urlOverride:r,ordered:o,studio:n,fos:i,bridge:a,tracker:c,timeout:d,destinationAddress:u})=>{const h={method:"GET"};e&&(h.destinationAddress=e),c&&(h.tracker=c),at(h,{timeout:d,ordered:o,studio:n,fos:i,bridge:a,destinationAddress:u});const g=r||t;sf.debug(`resolvedUrl: ${g}`);const m=await s(g,h);if(!m.ok){let w;try{w=await m.json()}catch{}throw new ne(`There was a problem retrieving the model; returned status ${m.status}`,w)}return await m.json()},af=(e,t,s)=>async({urlOverride:r,id:o,ordered:n,studio:i,fos:a,bridge:c,timeout:d,destinationAddress:u})=>{const h={method:"GET"};e&&(h.destinationAddress=e),at(h,{timeout:d,ordered:n,studio:i,fos:a,bridge:c,destinationAddress:u});const g=r||`${t}/${o}`,m=await s(g,h);if(!m.ok){let w;try{w=await m.json()}catch{}throw new ne(`There was a problem retrieving the model; returned status ${m.status}`,w)}return await m.json()};class ne extends Error{constructor(s,r){super(s);l(this,"payload");this.name="FetchException",this.payload=r}}const bn=(e,t,s)=>async({model:r,urlOverride:o,ordered:n,tracker:i,studio:a,fos:c,bridge:d,timeout:u,destinationAddress:h})=>{const g={method:"POST",body:typeof r=="string"?r:JSON.stringify(r)};e&&(g.destinationAddress=e),i&&(g.tracker=i),at(g,{timeout:u,ordered:n,studio:a,fos:c,bridge:d,destinationAddress:h});const m=await s(o||t,g);if(!m.ok){let w;try{w=await m.json()}catch{}throw new ne(`There was a problem sending the POST data; returned status ${m.status}`,w)}return await m.json()},wn=(e="POST",t,s,r)=>async({model:o,id:n,urlOverride:i,ordered:a,studio:c,fos:d,bridge:u,timeout:h,destinationAddress:g})=>{const m={method:e};o&&(m.body=JSON.stringify(o)),t&&(m.destinationAddress=t),at(m,{timeout:h,ordered:a,studio:c,fos:d,bridge:u,destinationAddress:g});const v=await r(i||`${s}/${n}`,m);if(!v.ok){let E;try{E=await v.json()}catch{}throw new ne(`There was a problem modifying the model; returned status ${v.status}`,E)}return await v.json()},X={build:({destinationAddress:e="",basePath:t,getAllPath:s,getOnePath:r,deleteModelPath:o,addModelPath:n,modifyModelPath:i,mock:a=!1})=>{const c=a?fetch:exports.kosFetch;return{getAll:of(e,s||t,c),getModelById:af(e,r||t,c),getOne:nf(e,r||t,c),addModel:bn(e,n||t,c),deleteModel:rf(e,o||t,c),modifyModel:wn("POST",e,i||t,c),putModel:wn("PUT",e,i||t,c),postModel:bn(e,n||t,c)}}},cf=nt(),$a=()=>`kos-${cf}`,lf=e=>!!e&&!e.includes("VM_SERVICE")&&e.startsWith($a()),ho=async(e,t=6e4)=>new Promise((s,r)=>{const{unsubscribe:o}=O(e,i=>{S.debug(`recieved response for refId ${e}: ${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 ${e} timed out. Cancelling.`))},t)}),df=async(e,t,s)=>{const r=ho(s),o=await Promise.allSettled([e(t),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)},uf=async({topic:e,msg:t,requestId:s})=>{const r=s??nt(),o=ho(r);U(e,t,{sync:r});const n=await o;if(n.error)throw Error(n.error);return n},ye=new Map;class Da{constructor(t){l(this,"_context");l(this,"_parent");l(this,"_id");this._id=t,this._context=new M.ObservableMap({}),this._parent="",M.makeAutoObservable(this)}setParent(t){Q(()=>{this._parent=t})}get id(){return this._id}get context(){return this._context}get parentModel(){var t;if(this._parent)return(t=Ue(this._parent))==null?void 0:t.model}get(t){var s;if(this._context.has(t))return this._context.get(t);if(this._parent)return(s=ye.get(this._parent))==null?void 0:s.get(t)}set(t,s){this._context.set(t,s)}remove(t){this._context.delete(t)}clear(){this._context.clear()}}const N={createContext:(e,t)=>{const s=ye.get(e)??new Da(e);if(t){if(!ye.has(t))throw new Error(`Parent context ${t} does not exist`);s.setParent(t)}else e!=="root"&&s.setParent("root");return ye.set(e,s),s},getContext:e=>ye.get(e),deleteContext:e=>{ye.delete(e)},setParentContext:(e,t)=>{var s;if(!ye.has(t))throw new Error(`Parent context ${t} does not exist`);(s=ye.get(e))==null||s.setParent(t)},rootContext:()=>ye.get("root")};N.createContext("root");const hf=e=>N.getContext(e.id);function ff(e,t){return e.length!==t.length?!1:e.every(s=>t.includes(s))}class fo{constructor({container:t,key:s}){l(this,"_container");l(this,"_map");l(this,"_key");l(this,"data");this._container=t,this._map=M.observable.map(new Map),this._key=s,this.data=Te(),this.generateIndex(),M.autorun(()=>{this._container.revision&&this.generateIndex()}),M.makeAutoObservable(this)}refresh(){this.generateIndex()}addItemToIndex(t,s,r=this._map,o=this.data){const n=r.get(t)||new Set;n.add(s),r.set(t,n),o[t]=Array.from(n)}resolveIndex(t,s){this.data.keys.filter(o=>!Object.keys(s).includes(o)).forEach(o=>{delete this.data[o],this._map.delete(o)}),Object.keys(s).forEach(o=>{const n=s[o],i=this.data[o]||[];if(ff(n,i))p.debug(`KosContainerIndex - Index ${o} is the same`);else{this.data[o]=n;const a=t.get(o)||new Set;this._map.set(o,a)}})}generateIndex(){M.runInAction(async()=>{const t=new Map,s={};for(const r of this._container.data){const o=typeof this._key=="function"?await this._key(r):r[this._key];Array.isArray(o)?o.forEach(n=>{this.addItemToIndex(n,r,t,s)}):typeof o=="string"||typeof o=="number"?this.addItemToIndex(String(o),r,t,s):typeof o=="boolean"&&this.addItemToIndex(String(o),r,t,s)}this.resolveIndex(t,s)})}get keys(){return Array.from(this._map.keys())}get index(){return this._map}getByKey(t){const s=this._map.get(t);return s?Array.from(s):[]}}function gf(e,t,s=[]){const r=Object.getOwnPropertyDescriptors(e);return Object.keys(r).filter(i=>M.isComputedProp(e,i)).filter(i=>s.includes(i)).map(i=>M.reaction(()=>e[i],(a,c)=>{t({name:i,newValue:a,oldValue:c})}))}const ht=p.createLogger({name:"kos-container-model"});class me{constructor(t){l(this,"_data");l(this,"_sortKey");l(this,"_revision");l(this,"_index");l(this,"_optionsMap");l(this,"_disposerMap",new Map);l(this,"_parentId");l(this,"idx");this._data=M.observable.map(new Map),this._sortKey=t==null?void 0:t.sortKey,this._revision=1;const s=t!=null&&t.extensionId?$.indexExtension.loadIndexExtensions(t.extensionId):{},r=(t==null?void 0:t.indexMap)||{};this._optionsMap={...r,...s};const o=t!=null&&t.indexMap?Object.keys(t.indexMap).reduce((n,i)=>(n[i]=void 0,n),{}):{};this._index=M.observable.map(o),this.idx=Te(),this._parentId=t==null?void 0:t.parentId,M.makeAutoObservable(this),this.init()}init(){Object.keys(this._optionsMap).forEach(t=>{const s=this._optionsMap[t],r=new fo({container:this,key:s});this._index.set(t,r),this.idx[t]=r.data})}[Symbol.iterator](){return this.data[Symbol.iterator]()}get index(){return this._index}get revision(){return this._revision}get indexKeys(){return Array.from(this.index.keys()).reduce((t,s)=>{var r;return t[s]=(r=this.index.get(s))==null?void 0:r.keys,t},{})}sortFn(t,s){const r=this._sortKey;return r?String(t[r]).localeCompare(String(s[r]),void 0,{numeric:!0}):0}get data(){const t=Array.from(this._data.values());return this._sortKey&&t.sort(this.sortFn.bind(this)),t}increment(){M.runInAction(()=>{this._revision=this._revision+1})}addAll(t){M.runInAction(()=>{t.forEach(s=>this.addModel(s,!0))}),this.increment()}removeAll(t){M.runInAction(()=>{t.forEach(s=>this.removeModel(s,!0)),this.increment()})}addModel(t,s){this._data.set(t.id||"",t),t.id&&this._parentId&&N.setParentContext(t.id,this._parentId),s||this.increment();const r=this._disposerMap.get(t.id);r&&(r(),this._disposerMap.delete(t.id));const o=Object.entries(this._optionsMap||{}),n=Object.values(this._optionsMap||{}),i=new Map(o.map(([u,h])=>[h,u])),a=u=>{var g,m;n.includes(u.name)&&((g=this.index.get(i.get(u.name)))==null||g.refresh());const h=o.filter(([,v])=>typeof v=="function");for(const[v]of h)(m=this.index.get(v))==null||m.refresh()},c=gf(t,a,n.filter(u=>typeof u=="string")),d=M.observe(t,a);this._disposerMap.set(t.id||"",()=>[d,...c].forEach(u=>u()))}removeModel(t,s){this._data.delete(t),s||this.increment();const r=this._disposerMap.get(t);r&&(r(),this._disposerMap.delete(t))}updateModel(t){this._data.set(t.id||"",t),this.increment()}getModel(t){return this._data.get(t)}getIndexKeys(t){return this.index.has(t)?this.index.get(t).keys??[]:(ht.info(`index ${t} not found in ${Array.from(this.index.keys())}`),[])}getIndexByKey(t,s){if(this.index.has(t)){const r=this.index.get(t);return r.index.has(s)?r.getByKey(s):(ht.info(`key ${s} not found in ${t} index: ${Array.from(r.index.keys())}`),[])}else return ht.info(`index ${t} not found in ${Array.from(this.index.keys())}`),[]}async clear(){this._data.forEach(t=>{const s=t.id;Le(t).then(()=>{ht.debug(`${s} destroyed, removing from map`),this.removeModel(s,!0)}).catch(r=>ht.error(r))}),this.increment()}filter(t,s){return this.data.filter(t,s)}sort(t){return this.data.sort(t)}map(t,s){return this.data.map(t,s)}forEach(t,s){this.data.forEach(t,s)}toJSON(){return{indexes:this.indexKeys,data:this.data.map(s=>({id:s.id,type:s.constructor.name}))}}}const vr=p.createLogger({name:"kos-data-container"});class Ca{constructor(t){l(this,"_data");l(this,"_sortKey");l(this,"_revision");l(this,"_index");l(this,"_optionsMap");l(this,"_disposerMap",new Map);l(this,"idx");this._data=M.observable.map(new Map),this._sortKey=t==null?void 0:t.sortKey,this._revision=1,this._optionsMap=(t==null?void 0:t.indexMap)||{};const s=t!=null&&t.indexMap?Object.keys(t.indexMap).reduce((r,o)=>(r[o]=void 0,r),{}):{};this._index=M.observable.map(s),this.idx=Te(),M.makeAutoObservable(this,{}),this.init()}init(){Object.keys(this._optionsMap).forEach(t=>{const s=this._optionsMap[t],r=new fo({container:this,key:s});this._index.set(t,r),this.idx[t]=r.data})}[Symbol.iterator](){return this.data[Symbol.iterator]()}get index(){return this._index}get indexKeys(){return Array.from(this.index.keys()).reduce((t,s)=>{var r;return t[s]=(r=this.index.get(s))==null?void 0:r.keys,t},{})}get revision(){return this._revision}addAll(t){M.runInAction(()=>{t.forEach(s=>this.addModel(s))})}removeAll(t){M.runInAction(()=>{t.forEach(s=>this.removeModel(s))})}sortFn(t,s){const r=this._sortKey;return r?String(t[r]).localeCompare(String(s[r]),void 0,{numeric:!0}):0}get data(){const t=Array.from(this._data.values());return this._sortKey&&t.sort(this.sortFn.bind(this)),t}increment(){M.runInAction(()=>{this._revision=this._revision+1})}addModel(t,s){const r=M.isObservable(t)?t:M.observable.object(t),o=this._disposerMap.get(t.id);o&&(o(),this._disposerMap.delete(t.id)),this._data.set(r.id||"",r),s||this.increment();const n=M.observe(r,i=>{Object.values(this._optionsMap||{}).includes(i.name)&&this.increment()});this._disposerMap.set(r.id||"",n)}removeModel(t){this._data.delete(t),this.increment();const s=this._disposerMap.get(t);s&&(s(),this._disposerMap.delete(t))}updateModel(t){const s=M.observable.object(t);this._data.set(s.id||"",s),this.increment()}getModel(t){return this._data.get(t)}getIndexKeys(t){return this.index.has(t)?this.index.get(t).keys??[]:(vr.info(`index ${t} not found in ${Array.from(this.index.keys())}`),[])}getIndexByKey(t,s){if(this.index.has(t)){const r=this.index.get(t);return r.index.has(s)?r.getByKey(s):(vr.info(`key ${s} not found in ${t} index: ${Array.from(r.index.keys())}`),[])}else return vr.info(`index ${t} not found in ${Array.from(this.index.keys())}`),[]}async clear(){this._data.clear(),this.increment()}filter(t,s){return this.data.filter(t,s)}sort(t){return this.data.sort(t)}map(t,s){return this.data.map(t,s)}forEach(t,s){this.data.forEach(t,s)}toJSON(){return{indexes:this.indexKeys,data:this.data.map(s=>({id:s.id}))}}}class pf{constructor({type:t,model:s,childRegistration:r}){l(this,"type");l(this,"childRegistration");l(this,"model");this.type=t,this.model=s,this.childRegistration=r}get factory(){return J.Factory.create(this.type)}get registration(){return{[this.type]:{class:this.model,singleton:!1,factory:this.factory},...this.childRegistration}}get predicate(){return ae(this.type)}}class mf{constructor({type:t,model:s,childRegistration:r}){l(this,"type");l(this,"model");l(this,"childRegistration");this.type=t,this.model=s,this.childRegistration=r}get factory(){return J.Singleton.create(this.type)}get registration(){return{[this.type]:{class:this.model,singleton:!0,factory:this.factory},...this.childRegistration}}get predicate(){return ae(this.type)}}class Aa{constructor(){l(this,"_token");M.makeAutoObservable(this),O("token",t=>{this.token=t==null?void 0:t.body})}get token(){return this._token}set token(t){this._token=t}}class Ra{constructor(){l(this,"routes",[]);l(this,"openApiRoutes",[])}use(t,s,...r){this.routes.push({method:t,path:s,middlewares:r});const o=this.extractOpenApiParams(s);this.openApiRoutes.push({method:t,path:s,parameters:o})}async handle(t,s){var a;const{path:r,query:o,params:n}=this.extractPathParams(t.path),i={...t,params:n,query:o};for(const c of this.routes){const d=this.matchRoute(c.path,r);if(c.method===t.method&&d){i.params=d;let u=0;const h=async()=>{if(u<c.middlewares.length){const g=c.middlewares[u++];await g(i,s,h)}};await h();return}}(a=s.status)==null||a.call(s,404).send({error:"Route not found"})}extractOpenApiParams(t){return t.split("/").filter(s=>s.startsWith(":")).map(s=>({name:s.slice(1),in:"path",required:!0,schema:{type:"string"}}))}generateOpenApiSpec(){const t={};for(const s of this.openApiRoutes)t[s.path]||(t[s.path]={}),t[s.path][s.method.toLowerCase()]={summary:s.description||`Handles ${s.method} ${s.path}`,parameters:s.parameters||[],responses:{200:{description:"Successful response"}}};return{openapi:"3.0.0",info:{title:"Kos Router API",version:"1.0.0",description:"Dynamically generated OpenAPI documentation"},paths:t}}extractPathParams(t){const[s,r]=t.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(t,s){const r=t.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(t){return t?t.split("&").reduce((s,r)=>{const[o,n]=r.split("=").map(decodeURIComponent);return s[o]=n??"",s},{}):{}}}const Pa=p.createLogger({name:"intent-service"}),yf=e=>{Xr(`/kos/intent/${e.type}`)?U(`/kos/intent/${e.type}`,e.options,{"kos.intent.type":e.type}):Pa.info(`No subscribers for intent ${e.type}. Intent not sent.`)},bf=async e=>new Promise(t=>{const{type:s,options:r}=e;if(Xr(`/kos/intent/${e.type}`)){const o=nt(),{unsubscribe:n}=O(o,a=>{clearTimeout(i),n(),a&&(a.headers=a.headers||{},a.headers["kos.intent.type"]=s,a.headers.responseId=o),t([null,{body:a==null?void 0:a.body,payload:a}])}),i=setTimeout(()=>{n(),t([`Intent ${s} timed out after 1 second`,null]),console.warn(`Intent ${s} timed out after 1 second`)},1e3);U(`/kos/intent/${s}`,r,{"kos.intent.type":s,sync:o})}else Pa.info(`No subscribers for intent ${e.type}. Intent not sent.`),t([null,{body:void 0,payload:void 0}])}),De=uo(),be=p.createLogger({name:"app-startup-service"});async function xa(e,t={}){const{timeout:s=3e4,throwOnTimeout:r=!0,requirePostStarted:o=!1}=t;if(e.length===0)return be.warn("No app IDs provided to waitForAppsToStart"),!0;be.debug(`Waiting for apps to start: ${e.join(", ")}`);try{const n=e.map(c=>`/kos/app/started/${c}`),i=await to(n,{getCurrentState:async()=>{try{const[c,d]=await De.get("/api/kos/apps/started");return c?(be.error("Error fetching started apps:",c),[]):d}catch(c){be.error("Failed to fetch app startup status:",c)}return[]},shouldUseFetchedState:c=>e.every(d=>{const u=c.find(h=>h.appId===d);return!(!u||!u.started||o&&!u.postStarted)}),timeout:s}),a=e.filter(c=>{const d=i.find(u=>u.appId===c);return!!(!d||!d.started||o&&!d.postStarted)});if(a.length>0){const c=`Apps not started: ${a.join(", ")}`;if(be.error(c),r)throw new Error(`App startup timeout: ${c}`);return!1}return be.info(`All apps started successfully: ${e.join(", ")}`),!0}catch(n){const i=`Failed to wait for apps to start: ${e.join(", ")}`;if(be.error(i,n),r)throw new Error(`${i} - ${n instanceof Error?n.message:String(n)}`);return!1}}async function wf(e,t={}){return xa([e],t)}async function vf(e,t=!1){const s={};try{const r=await exports.kosFetch("kos:///api/kos/apps/started");if(!r.ok)return e.forEach(i=>s[i]=!1),s;const o=await r.json(),n=(o==null?void 0:o.data)??[];e.forEach(i=>{const a=n.find(c=>c.appId===i);s[i]=(a==null?void 0:a.started)===!0&&(!t||(a==null?void 0:a.postStarted)===!0)})}catch(r){be.error("Failed to check app startup status:",r),e.forEach(o=>s[o]=!1)}return s}async function Mf(){try{const e=await exports.kosFetch("kos:///api/kos/apps/started");if(!e.ok)return[];const t=await e.json();return(t==null?void 0:t.data)??[]}catch(e){return be.error("Failed to fetch started apps:",e),[]}}const Pr=M.when,go=M.computed,Q=M.runInAction,j=M.autorun,La=M.reaction,po=M.observable,mo="Not Assigned",Ef="kos.trouble.added",_f="kos.trouble.removed";var de=(e=>(e.TroubleRank="kos.trouble.rank.mapper",e.TroubleColor="kos.trouble.color.mapper",e.TroubleRole="kos.trouble.role.mapper",e))(de||{}),Lt=(e=>(e.TIME_CHANGE="/kos/internal/time/time",e.DAY_CHANGE="/kos/internal/time/day",e.TIMEZONE_CHANGE="/kos/internal/time/timezone",e))(Lt||{});const Fa=p.createLogger({name:"config-bean-service",group:"Services"}),yo=exports.BASE_URL,ka=e=>(e==null?void 0:e.decimals)!==void 0,{postModel:If,getOne:Tf}=X.build({destinationAddress:"",basePath:`${yo}/kos/config/`}),Na=async(e,t,s="/api/kos/config")=>(Fa.debug(`sending modify request for ConfigBean: ${e}`),If({model:t,urlOverride:`${yo}${s}/${e}`})),Ua=async(e,t="/api/kos/config")=>(Fa.debug(`sending get request for ConfigBean: ${e}`),await Tf({urlOverride:`${yo}${t}/details/${e}/15`})),bo=e=>e.toLowerCase()==="true"||e.toLowerCase()==="false",tr=e=>{try{const t=Number(e);return!isNaN(t)}catch{return!1}};function ja(e=[]){return e.reverse().reduce((t,s)=>{const{overrides:r}=s;return r&&(t={...t,...r}),t},{})}function Ba(e,t="",s={}){for(const r in e)if(Object.prototype.hasOwnProperty.call(e,r)){const o=t?`${t}.${r}`:r;typeof e[r]=="object"&&e[r]!==null&&!Array.isArray(e[r])?Ba(e[r],o,s):s[o]=e[r]}return s}const Ka=(e,t)=>{const s=e.details[0].bean||ja(e.details[0].scopes),r=Ba(s);M.runInAction(()=>{const o={...r};t.props.setValues(o)})},Ha=(e,t)=>{M.runInAction(()=>{e.changes.forEach(s=>{const r=s.attr;let o=s.currentValue,n=s.previousValue;typeof o=="string"&&bo(o)&&(o=o.toLowerCase()=="true",n=(n==null?void 0:n.toLowerCase())=="true"),typeof o=="string"&&tr(o)&&(o=Number(o),n=Number(n)),t.props[r]=o,t.prevProps[r]=n})})},Ga=e=>Object.fromEntries(e.props.entries),Of=e=>t=>s=>e.build(t,s);var Sf=Object.defineProperty,$f=Object.getOwnPropertyDescriptor,za=(e,t,s,r)=>{for(var o=r>1?void 0:r?$f(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&Sf(t,s,o),o};function Df(e,t){for(const s of e)if(new RegExp(`^${s}$`).test(t))return s}const wo="config-bean-model",ds=p.getLogger(wo),Cf=ke("path");let Os=class{constructor(e,t){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,t),this.id=e,this.path=t.path,this.serviceBasePath=t.serviceBasePath;const{modifyConfigBean:s=Na,getConfigBean:r=Ua}=t;this._modifyConfigBean=s,this._getConfigBean=r,this.props=Te(),this.prevProps=Te()}get values(){return this.props.values}async ready(){ds.debug(`readying config bean ${this.path}`),ds.debug(`complete readying config bean ${this.path}`)}async load(){ds.debug(`loading config bean ${this.path}`);const e=await this._getConfigBean(this.path,this.serviceBasePath);if(e!=null&&e.data){const t=e.data;Ka(t,this),ds.debug(this.values);const s=e==null?void 0:e.data.details[0].schema;Q(()=>{s&&(this._schema=s)})}}get schemaKeys(){var e;return Object.keys(((e=this._schema)==null?void 0:e.schema)||{})}getSchemaForProperty(e){var s,r;if(this.schemaKeys.includes(e))return(s=this._schema)==null?void 0:s.schema[e];const t=Df(this.schemaKeys,e);if(t)return(r=this._schema)==null?void 0:r.schema[t]}async updateProperty(e,t){this.props[e]=t,await this.updateConfigBean()}async updateConfigBean(){const e=Ga(this);await this._modifyConfigBean(this.path,e,this.serviceBasePath)}handleConfigBeanUpdated(e){Ha(e,this)}};za([x({topic:`/kos/config/${Cf}`,websocket:!0})],Os.prototype,"handleConfigBeanUpdated",1);Os=za([C(wo)],Os);const Nt=new ge({class:Os,type:wo}),sr=({path:e,lazy:t,serviceBasePath:s})=>(r,o)=>{r[F]=r[F]||{},r[F][o]={modelType:Nt.type,id:`${Nt.type}-${e}`,options:{path:e,serviceBasePath:s},lifecycle:B.INIT,lazy:t}},{URL:Va}=ee(),{getOne:Af,getAll:Rf}=X.build({basePath:`${Va}/api/kos/regions/info`}),Ya=async()=>await Af({}),qa=async()=>await Rf({urlOverride:`${Va}/api/kos/regions`}),Pf=Object.freeze(Object.defineProperty({__proto__:null,getRegionInfo:Ya,getRegions:qa},Symbol.toStringTag,{value:"Module"}));var se=(e=>(e[e.family=0]="family",e[e.scale=1]="scale",e[e.offset=2]="offset",e[e.decimals=3]="decimals",e[e.alias=4]="alias",e[e.system=5]="system",e))(se||{});const Wa={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 xf(e,t){const s=t.id,r=t.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},{...Wa});return{...e,...r}}function Lf(e,t){const s=t.id,r=t.units.reduce((o,n)=>{const i=o[n.measure]||{},a=i[s]||{};i[s]=a;const c=[n.measure,n.scale,n.offset,n.decimals,n.alias,s];return a[n.name]=c,Object.hasOwn(n,"default")&&Object.defineProperty(a,"default",{value:c,writable:!0,enumerable:!0,configurable:!0}),o[n.measure]=i,n.alias&&(o[n.alias]=i),o},{time:{[s]:{...Wa}}});return Object.keys(r).forEach(o=>{e[o]={...e[o],...r[o]}}),e}function Ff(e,t){const s=t.id,r=t.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=>{e[o]={...e[o],...r[o]}}),e}var kf=Object.defineProperty,Nf=Object.getOwnPropertyDescriptor,vo=(e,t,s,r)=>{for(var o=r>1?void 0:r?Nf(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&kf(t,s,o),o};const vs="region-info-model",ft=p.createLogger({name:"region-info-model"});let Ut=class{constructor(e){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=e,this.unitSystems={},this.unitSystemMap={},this.measureMap={},this.defaultMeasureMap={},this.timeFormats={},this.regions=[],this.dateFormats={},this.timeZoneMap={},this.regionMap={}}get availableRegions(){return this.regions}get defaultUnitSystem(){return String(this.regionSource.props.unitSystemId).toLowerCase()||""}get unitSystemId(){return this.defaultUnitSystem}get timeFormatId(){const e=this.regionSource.props.timeFormatId;if(!e)return"";const t=String(e),s=this.timeFormats[t];return s?String(s.id):""}get selectedTimeFormat(){const e=this.timeFormatId;return e?String(this.timeFormats[e].format):"HH:mm:ss"}get is12HourTimeFormat(){const e=this.timeFormatId;return e?this.timeFormats[e].ampm:!0}get dateFormatId(){const e=this.regionSource.props.dateFormatId;if(!e)return"";const t=String(e);return t?this.dateFormats[t].id:""}get selectedDateFormat(){const e=this.dateFormatId;return e?this.dateFormats[e].format:""}get selectedDateOrder(){const e=this.dateFormatId;return e?this.dateFormats[e].order.toLowerCase():"dmy"}get selectedCountry(){return this.regionSource.props.country||"en"}get selectedTimeZone(){return this.regionSource.props.timeZone||""}get timeZones(){return this.regionId?this.timeZoneMap[this.regionId]||[]:[]}get allTimeZones(){return Intl.supportedValuesOf("timeZone")}get regionId(){return this.region.props.regionId||""}get selectedRegion(){return this.regionMap[this.regionId]}get selectedUnitSystem(){return String(this.regionSource.props.unitSystemId)||""}get timeFormatOptions(){return Object.keys(this.timeFormats).map(e=>({id:e,format:this.timeFormats[e].format,ampm:this.timeFormats[e].ampm}))}get dateFormatOptions(){return Object.keys(this.dateFormats).map(e=>({id:e,format:this.dateFormats[e].format,order:this.dateFormats[e].order}))}get unitSystemOptions(){return Object.keys(this.unitSystems).map(e=>({id:e,name:e}))}setSelectedTimeFormat(e){if(!this.timeFormatOptions.find(t=>t.id===e))throw Error(`Invalid time format id. Must be one of ${this.timeFormatOptions.map(t=>t.id).join(", ")}`);this.regionSource.updateProperty("timeFormatId",e)}setSelectedDateFormat(e){if(!this.dateFormatOptions.find(t=>t.id===e))throw Error(`Invalid date format id. Must be one of ${this.dateFormatOptions.map(t=>t.id).join(", ")}`);this.regionSource.updateProperty("dateFormatId",e)}setSelectedUnitSystem(e){if(!this.unitSystemOptions.find(t=>t.id===e))throw Error(`Invalid date format id. Must be one of ${this.unitSystemOptions.map(t=>t.id).join(", ")}`);this.regionSource.updateProperty("unitSystemId",e)}getUnitSystem(e){if(!e)return this.defaultUnitSystem;const t=e==="drt"?"second":e,s=this.unitSystemMap[t];if(!s)throw Error(`No unit found with name: ${t}. Unit should be one of ${Object.keys(this.unitSystemMap).join(", ")}`);return s[se.system]}getUnitMeasure(e){const t=e==="drt"?"second":e,s=this.unitSystemMap[t];if(!s)throw Error(`No unit found with name: ${t}. Unit should be one of ${Object.keys(this.unitSystemMap).join(", ")}`);return s[se.family]}getDefaultUnitDecimalPlaces(e,t,s){if(!e||!t)throw Error("Measure and unit system are required");const r=s==="drt"?"second":s,o=this.measureMap[e];if(!o)throw Error(`No unit systems found for measure: ${e}. Measure should come from list of measures: ${Object.keys(this.measureMap).join(", ")}`);const n=o[t.toLowerCase()];if(!n)throw Error(`No unit system found for measure: ${e} and unit system: ${t}. Unit system should come form list of unit systems: ${Object.keys(o).join(", ")}`);const i=n[r||"default"];if(!i)throw Error(`No unit "${r||"default"}" found for measure: ${e} and unit system: ${t}. Unit should come from list of units: ${Object.keys(n).join(", ")}`);return i[se.decimals]}getDefaultUnitForMeasure(e,t){if(!e||!t)throw Error("Measure and unit system are required");const s=this.defaultMeasureMap[e];if(!s)throw Error(`No unit systems found for measure: ${e}. Measure should come from list of measures: ${Object.keys(this.measureMap).join(", ")}`);const r=s[t.toLowerCase()];if(!r)throw Error(`No unit system found for measure: ${e} and unit system: ${t}. Unit system should come form list of unit systems: ${Object.keys(s).join(", ")}`);return r}convertByUnit(e,t,s){if(t[se.family]!==s[se.family])throw new Error(`Cannot convert between units of different families: ${t[se.family]} and ${s[se.family]}`);const r=t[se.offset],o=t[se.scale],n=s[se.scale],i=s[se.offset],a=s[se.decimals];return((e-r)/(o/n)+i).toFixed(a)}convertByUnitName(e,t,s){const r=this.unitSystemMap[t],o=this.unitSystemMap[s];if(!r||!o)throw new Error(`No unit found with name: ${t} or ${s}. Unit should be one of ${Object.keys(this.unitSystemMap).join(", ")}`);return this.convertByUnit(e,r,o)}convert(e,t,s){var a,c;if(t.unit&&s.unit)return this.convertByUnitName(e,t.unit,s.unit);const r=t.unit||"",o=s.unit||"";let n=this.unitSystemMap[r],i=this.unitSystemMap[o];if(!i&&s.measure&&s.system){const d=this.measureMap[s.measure];if(!d)throw Error(`Could not find measure ${s.measure}. Measure should be one of ${Object.keys(this.measureMap).join(", ")}`);i=(a=d[s.system])==null?void 0:a.default,i||ft.info("Could not find default unit for measure",s.measure)}if(!n&&t.measure&&t.system){const d=this.measureMap[t.measure];if(!d)throw Error(`Could not find measure ${s.measure}. Measure should be one of ${Object.keys(this.measureMap).join(", ")}`);n=(c=d[t.system])==null?void 0:c.default,n||ft.info("Could not find default unit for measure",t.measure)}return!n||!i?(ft.warn("Could not find unit to convert to or from. Return value as is"),String(e)):this.convertByUnit(e,n,i)}async init(){ft.debug("initializing region info")}async load(){ft.debug("loading region info");const e=await qa();e&&(this.regions=e.data.map(s=>s.id),this.timeZoneMap=e.data.reduce((s,r)=>({...s,[r.id]:r.timeZones}),this.timeZoneMap),this.regionMap=e.data.reduce((s,r)=>({...s,[r.id]:r}),{}));const t=await Ya();t&&(this.unitSystems=t.data.unitSystems.reduce((s,r)=>{const o={id:r.id,name:r.id};return s[r.id]=o,s},this.unitSystems),this.unitSystemMap=t.data.unitSystems.reduce(xf,{}),this.measureMap=t.data.unitSystems.reduce(Lf,{}),this.defaultMeasureMap=t.data.unitSystems.reduce(Ff,{}),this.timeFormats=t.data.timeFormats.reduce((s,r)=>({...s,[r.id]:r}),{}),this.dateFormats=t.data.dateFormats.reduce((s,r)=>({...s,[r.id]:r}),{}))}async ready(){var e,t;await((t=(e=this.regionSource).ready)==null?void 0:t.call(e))}};vo([sr({path:"kos:service:region:settings"})],Ut.prototype,"regionSource",2);vo([sr({path:"kos:service:region"})],Ut.prototype,"region",2);Ut=vo([C(vs)],Ut);const Z={registration:{[vs]:{class:Ut,singleton:!0}},type:vs,factory:J.Singleton.create(vs)},Ss=({source:e,defaultSystem:t="si",defaultMeasure:s})=>{let r={system:t,measure:s};return typeof e=="string"?r={...r,unit:e}:r={...r,...e},r},Mo=(e,t,s)=>{const{model:r}=Ue(Z.type);if(!r)throw new Error("RegionInfo model not found");if(!Ts(r))throw new Error("RegionInfo model not ready");const o={system:r.defaultUnitSystem},n=Ss({source:t}),i=Ss({source:s||o,defaultMeasure:r.getUnitMeasure(n.unit||"")});return r.convert(e,n,i)};function vn(e,t,s){const r=t.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(e)}catch{return t}}const Uf=(e,t,s,r)=>{const o=Mo(e,t,s),n=Ss({source:t}),{model:i}=Ue(Z.type);if(!i)throw new Error("RegionInfo model not found");const a=i.getUnitMeasure(n.unit||""),c={system:i.defaultUnitSystem},d=Ss({source:s||c,defaultMeasure:i.getUnitMeasure(n.unit||"")}),u=i.getDefaultUnitForMeasure(a,d.system),h=i.getDefaultUnitDecimalPlaces(a,d.system),g={...r,minDecimals:(r==null?void 0:r.minDecimals)??h,maxDecimals:(r==null?void 0:r.maxDecimals)??h};return{value:o,unit:u||n.unit||"",display:vn(o,u||n.unit||"",{...g,mode:"long"}),shortDisplay:vn(o,u||n.unit||"",{...g,mode:"short"})}};function Mn({start:e,end:t,count:s,decimals:r=0}){if(typeof e!="number"||typeof t!="number"||typeof s!="number")throw new Error("All input values should be numbers.");if(s<2)throw new Error("Count should be at least 2 for distribution.");if(e>=t)throw new Error("Start should be less than end.");const o=(t-e)/(s-1),n=[];for(let i=0;i<s;i++){const a=Math.round(e+i*o);n.push(a.toFixed(r))}return n}function En({start:e,end:t,interval:s,decimals:r=0}){if(typeof e!="number"||typeof t!="number"||typeof s!="number")throw new Error("All input values should be numbers.");if(s<=0)throw new Error("Interval should be a positive number.");if(e>=t)throw new Error("Start should be less than end.");const o=[];let n=e;for(;n<=t;)o.push(n.toFixed(r)),n+=s;return o[o.length-1]!==t.toString()&&o.push(t.toString()),o}const Ke=(e,t)=>s=>!e||!t?s:tr(s)?Mo(Number(s),e,t):s,jf=(e,t,s,r)=>{if((e==null?void 0:e.type)==="enum"||!(e!=null&&e.options))return[];if(e.options.type==="rangeCount")return Mn(e.options).map(Ke(s,r));if(e.options.type==="rangeInterval")return En(e.options).map(Ke(s,r));if(e.options.type==="list"){const{list:o}=e.options;return o.map(Ke(s,r))}else{if(e.options.type==="unitSystemRangeCount"&&t)return Mn(e.options.unitSystems[t]).map(Ke(s,r));if(e.options.type==="unitSystemRangeInterval"&&t)return En(e.options.unitSystems[t]).map(Ke(s,r));if(e.options.type==="unitSystemList"&&t){const{list:o}=e.options.unitSystems[t];return o.map(Ke(s,r))}}return[]},Bf=(e,t)=>{if(!((e==null?void 0:e.type)==="enum"||!(e!=null&&e.options)))return e.options.type==="unitSystemRangeCount"&&t?{type:"rangeCount",...e.options.unitSystems[t]}:e.options.type==="unitSystemRangeInterval"&&t?{type:"rangeInterval",...e.options.unitSystems[t]}:e.options.type==="unitSystemList"&&t?{type:"list",...e.options.unitSystems[t]}:e.options.type==="unitSystemKeypad"&&t?{type:"keypad",...e.options.unitSystems[t]}:e.options};var Kf=Object.defineProperty,Hf=Object.getOwnPropertyDescriptor,Eo=(e,t,s,r)=>{for(var o=r>1?void 0:r?Hf(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&Kf(t,s,o),o};function Gf(e){return(e==null?void 0:e.type)==="enum"}function zf(e){switch(e){case"s":return"second";case"ms":return"millisecond";case"min":return"minute";case"h":return"hour";case"d":return"day";case"w":return"week";case"m":return"month";case"y":return"year";case"ml":return"milliliter";default:return e}}function Vf(e,t){const s=new Date;s.setHours(0,0,0,0);const r=new Date(s.getTime()+e*1e3);return Ie.format(r,t)}const Ms="config-bean-prop-model",He=p.createLogger({name:"config-bean-prop-model"}),Yf=ke("path"),qf=ke("serviceBasePath");let jt=class{constructor(e,t){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=e,this.path=t.path,this.attribute=t.attribute,this.converter=t.converter,this.formatter=t.formatter,this.serviceBasePath=t.serviceBasePath,this.optionsExpander=t.optionsExpander}getDefaultUnitDecimalPlaces(e,t,s){if(!e)throw new Error("measure is required");if(!t)throw new Error("unitSystem is required");return ka(this.displayOptions)?this.displayOptions.decimals:this.regionInfo.getDefaultUnitDecimalPlaces(e,t,s)}getDefaultUnitForMeasure(e,t){if(!e)throw new Error("measure is required");if(!t)throw new Error("unitSystem is required");return this.regionInfo.getDefaultUnitForMeasure(e,t)}get schemaType(){const e=this.bean.getSchemaForProperty(this.attribute);return e!=null&&e.type?e.type:"String"}get schemaFormat(){const e=this.bean.getSchemaForProperty(this.attribute);return e!=null&&e.format?zf(e.format):""}get options(){var i;const e=this.regionInfo.defaultUnitSystem,t=this.getConverter(),s=((i=t==null?void 0:t.to)==null?void 0:i.system)??e,r=this.bean.getSchemaForProperty(this.attribute),o=Gf(r)?r.values:jf(r,s,t==null?void 0:t.from,t==null?void 0:t.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(e,t,s){const r=(e==null?void 0:e.measure)||s,o=(e==null?void 0:e.system)||t,n=e==null?void 0:e.unit;return{measure:r,system:o,unit:n}}getConverterUnits(){const e=this.regionInfo.defaultUnitSystem,t=this.getConverter();if(!t)throw Error("No converter defined");const s=t.measure,r=this.convertUnit(t.from,"si",s),o=this.convertUnit(t.to,e,s);return{backend:r,display:o}}set value(e){this.updateProperty(e)}get value(){return this.getValue(!0)}get rawValue(){return this.bean.props[this.attribute]}get significantValue(){var o,n;const e=this.value,t=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(e)&&s&&r){const i=this.getDefaultUnitDecimalPlaces(r,t,(n=s==null?void 0:s.to)==null?void 0:n.unit);try{const c=this.getFormatterOptions(s);if(c){let d=String(e);return d=c.formatToParts(Number(e))[0].value,Number(d)}}catch(c){He.info(`error formatting value ${e}`,c)}return Number(e).toFixed(i)}return e}get previousValue(){return this.getValue(!1)}getValue(e){const t=this.bean[e?"props":"prevProps"][this.attribute];if(typeof t=="boolean")return t;if(this.getConverter()&&!isNaN(t)){const{backend:r,display:o}=this.getConverterUnits();return this.regionInfo.convert(Number(t),r,o)}return t||""}async activate(){He.debug(`activating config bean ${this.id}`)}get displayValue(){const e=this.value;if(typeof e=="boolean")return String(e);if(this.schemaFormat==="drt"){const s=this.regionInfo.is12HourTimeFormat?"h:mm:ss a":"HH:mm:ss";return Vf(e,s)}if(!isNaN(e))try{const t=this.getConverter(),s=this.getFormatterOptions(t);if(s){let r=String(e);return r=s.format(Number(e)),r}}catch(t){He.error(`error formatting value ${e}`,t)}return String(e)}get unit(){const e=this.getConverter();if(!isNaN(this.value)){const t=this.getFormatterOptions(e);if(t){const r=t.formatToParts(Number(this.value)).find(o=>o.type==="unit");return(r==null?void 0:r.value)??this.getDefaultUnit(e)}}return this.getDefaultUnit(e)}get displayOptions(){var o;const e=this.bean.getSchemaForProperty(this.attribute),t=this.regionInfo.defaultUnitSystem,s=this.getConverter(),r=((o=s==null?void 0:s.to)==null?void 0:o.system)??t;return Bf(e,r)}getMeasureFromFormat(){const e=this.schemaFormat;return e?this.regionInfo.getUnitMeasure(e):""}getConverterFromFormat(){const e=this.getMeasureFromFormat();if(e){const t=this.regionInfo.selectedUnitSystem;return{unit:this.schemaFormat||this.regionInfo.getDefaultUnitForMeasure(e,t),measure:e}}return{}}getDefaultUnit(e){var r,o;const t=this.regionInfo.defaultUnitSystem,s=e==null?void 0:e.measure;return s?((r=e==null?void 0:e.to)==null?void 0:r.unit)||this.getDefaultUnitForMeasure(s,((o=e==null?void 0:e.to)==null?void 0:o.system)||t):this.getConverterFromFormat().unit}getFormatterOptions(e){var n,i,a;const t=this.regionInfo.defaultUnitSystem,s=e==null?void 0:e.measure,r=new Intl.NumberFormat().resolvedOptions().locale;let o=null;if(s||this.formatter){const c=s?{style:"unit",unit:this.getDefaultUnit(e)}:null,d=this.formatter||c;if(d){let u=typeof d=="function"?d(((n=e==null?void 0:e.to)==null?void 0:n.system)||t):d;s&&(u={unit:this.getDefaultUnit(e),...u},u.style==="unit"&&(u.maximumFractionDigits=u.maximumFractionDigits??this.getDefaultUnitDecimalPlaces(s,((i=e==null?void 0:e.to)==null?void 0:i.system)||t,(a=e==null?void 0:e.to)==null?void 0:a.unit)));try{o=new Intl.NumberFormat(r,{...u})}catch(h){He.error(`error creating formatter ${u}. Returning the raw value`,h)}}else He.debug(`no formatter found for config bean prop ${this.id}. Returning the raw value`)}return o}getConverter(){var r,o,n,i,a,c,d,u,h,g,m;const{unit:e,measure:t}=this.getConverterFromFormat(),s=e==="drt"?"second":e;if(this.converter){const v=(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,T=v||w||E||t,K=((d=(c=this.converter)==null?void 0:c.to)==null?void 0:d.unit)||this.regionInfo.getDefaultUnitForMeasure(T,((h=(u=this.converter)==null?void 0:u.to)==null?void 0:h.system)??this.regionInfo.defaultUnitSystem),H=((m=(g=this.converter)==null?void 0:g.to)==null?void 0:m.system)??this.regionInfo.getUnitSystem(K),ce=this.schemaFormat==="drt"?"second":this.schemaFormat||s;return{...this.converter,from:{unit:ce,...this.converter.from},to:{...this.converter.to,unit:K,system:H},measure:T}}if(s&&t){const v=this.regionInfo.getDefaultUnitForMeasure(t,this.regionInfo.defaultUnitSystem),w=this.regionInfo.getUnitSystem(s),E=this.regionInfo.getUnitSystem(v);return{measure:t,to:{unit:w===E?s:v}}}}async updateProperty(e){He.debug(`updating property ${this.attribute} with value ${e}`);let t=e;if(this.getConverter()&&!isNaN(t)){const{backend:o,display:n}=this.getConverterUnits();t=this.regionInfo.convert(Number(t),n,o)}const r=Array.isArray(t)?JSON.stringify(t):String(t);await this.bean.updateProperty(this.attribute,r)}};Eo([Ne({modelType:Z.type})],jt.prototype,"regionInfo",2);Eo([sr({path:Yf,serviceBasePath:qf})],jt.prototype,"bean",2);jt=Eo([C(Ms)],jt);const je={registration:{[Ms]:{class:jt,singleton:!1}},type:Ms,factory:J.Factory.create(Ms)};function Wf(e){const{path:t,attribute:s,converter:r,formatter:o,lazy:n,optionsExpander:i,serviceBasePath:a}=e,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})),(d,u)=>{d[F]=d[F]||{},d[F][u]={modelType:je.type,id:`${t}-${s}`,options:{path:t,attribute:s,serviceBasePath:a,converter:c,formatter:o,optionsExpander:i},lifecycle:B.INIT,lazy:n}}}class Zf{constructor(t,s){l(this,"futures");l(this,"defaultContext");l(this,"context");l(this,"disposers",new Map);l(this,"container");this.futures=po.map(new Map),this.context="",this.defaultContext=s||"",this.container=t,M.makeAutoObservable(this)}get allFutures(){return Array.from(this.futures.values())}get future(){return this.futures.get(this.defaultContext)}addFuture(t,s){this.futures.set(s||t.id,t),this.context=s||t.id;const r=j(()=>{var o,n;(t.endState||t.progress)&&((n=(o=this.container)==null?void 0:o.onFutureUpdate)==null||n.call(o,t))});this.disposers.set(s||t.id,r)}removeFuture(t){var s;this.futures.delete(t||this.context),(s=this.disposers.get(t||this.context))==null||s(),this.disposers.delete(t||this.context)}getFuture(t){return this.futures.get(t||this.context)}get futureMap(){return this.futures}}class rr{constructor(t){l(this,"disposer");l(this,"_future");l(this,"container");l(this,"onFutureUpdate");this._future=void 0,this.container=t,M.makeAutoObservable(this)}removeFuture(){var t;this._future=void 0,(t=this.disposer)==null||t.call(this),this.disposer=void 0}get future(){return this._future}getFuture(){return this._future}addFuture(t){this._future=t;const s=j(()=>{var r,o;(t.endState||t.progress)&&((o=(r=this.container)==null?void 0:r.onFutureUpdate)==null||o.call(r,t))});this.disposer=s}get allFutures(){return this._future?[this._future]:[]}get timeRemaining(){var t;return((t=this._future)==null?void 0:t.timeRemaining)||""}get status(){var t;return((t=this._future)==null?void 0:t.status)||"NOT_RESOLVED"}get progress(){var t;return((t=this._future)==null?void 0:t.progress)||-1}async cancel(){if(this._future)try{await this._future.cancelFuture()}catch(t){throw p.error(t),t}}}const Za="future-model",ct=it(Za),or=p.createLogger({name:"future-service",group:"Services"}),{isMock:Jf,URL:Qt}=ee();var Oe=(e=>(e.Success="SUCCESS",e.Fail="FAIL",e.Aborted="ABORT",e.Canceled="CANCEL",e))(Oe||{});const{getAll:Xf,modifyModel:Qf,addModel:eg,deleteModel:tg,postModel:sg}=X.build({destinationAddress:"",basePath:`${Qt}/api/future`,mock:Jf}),rg=async()=>await Xf({}),Ja=async(e,t="/api/kos/future")=>(or.info(`sending delete request for Future: ${e}`),await tg({id:e,urlOverride:`${Qt}${t}/${e}`})),Xa=async(e,t="/api/kos/future")=>(or.info("sending add request for Future"),await eg({model:e,urlOverride:`${Qt}${t}`})),og=async(e,t,s="/api/kos/future")=>(or.info(`sending modify request for Future: ${e}`),Qf({model:t,id:e,urlOverride:`${Qt}${s}/${e}`})),Qa=async(e,t="/api/kos/future")=>(or.info(`sending cancel request for Future: ${e}`),sg({urlOverride:`${Qt}${t}/${e}/cancel`,ordered:!0,model:{}})),_o=e=>({id:String(e.id),progress:e.progress,remainingTimeMs:e.remainingTimeMs,endState:e.endState,reason:e.reason,clientData:e.clientData,reasonData:e.reasonData,note:e.note,tracker:e.tracker}),Io=(e,t)=>{p.debug(`future dto ${e.id} end state ${e.endState}`),p.debug(`future model ${t.id} end state ${t.endState}`),t.endState?p.debug(`future model ${t.id} is already complete`):(p.debug(`updating future model ${t.id}`),M.runInAction(()=>{const s=_o(e);Q(()=>{Object.keys(s).forEach(r=>{r==="id"?(t.futureId=s.id,s.tracker||(t.id=s.id)):r==="tracker"?t.id=s.tracker:t[r]=s[r]})})}))},ec=e=>t=>s=>e.build(String(t),s),To=e=>t=>Sa(_o,ec(e)(t.tracker||t.id))(t);var ng=Object.defineProperty,ig=Object.getOwnPropertyDescriptor,tc=(e,t,s,r)=>{for(var o=r>1?void 0:r?ig(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&ng(t,s,o),o};const Mr=p.getLogger(ct.type);let $s=class{constructor(e,t,s){l(this,"logger");l(this,"_cancelFuture");l(this,"futureId");Object.assign(this,t),this.logger=s.logger,this.id=e,this.futureId=t.id,this.namespace=t.namespace||"kos",this._cancelFuture=Qa,Pr(()=>this.status===Oe.Success||this.status===Oe.Fail,()=>{Mr.info(`Future ${this.id} has completed with status ${this.status}`),Le(this)})}async load(){Mr.debug(`loading Future ${this.id}`)}unload(){Mr.info(`unloading Future ${this.id}`)}async cancelFuture(){const e=this.namespace==="studio"?"/api/future":`/api/${this.namespace}/future`;await Pr(()=>this.futureId!==mo),await this._cancelFuture(this.futureId,e)}get status(){return this.endState?this.endState:this.progress>-1?"IN_PROGRESS":"NOT_ACTIVE"}get timeRemaining(){var a,c;const e=this.remainingTimeMs||-1;if(e<0)return"";const t={year:1e3*60*60*24*365,month:1e3*60*60*24*30,day:1e3*60*60*24,hour:1e3*60*60,minute:1e3*60,second:1e3};let s="second",r=0;for(const[d,u]of Object.entries(t))if(Math.abs(e)>=u){s=d,r=Math.round(e/u);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(e){this.logger.debug(`Future ${this.id} updated. future: ${e.id} endState: ${e.endState} progress: ${e.progress} remainingTimeMs: ${e.remainingTimeMs}`),Io(e,this)}};tc([x({topic:`kos.future/${_s}`})],$s.prototype,"handleFutureUpdated",1);$s=tc([C(ct.type)],$s);const sc=$s,rc=uo();var ag=Object.defineProperty,cg=Object.getOwnPropertyDescriptor,oc=(e,t,s,r)=>{for(var o=r>1?void 0:r?cg(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&ag(t,s,o),o};const nc="browser-router-model",lg="kos.http.request",dg="kos.http.response";let Ds=class{constructor(e,t,s){l(this,"_id");l(this,"logger");l(this,"router");this._id=e,this.logger=s.logger,this.router=new Ra}get id(){return this._id}async handleRequest(e,t){const s=t.headers["src-addr"],r=t.headers["dst-addr"],o=t.headers.url,n=t.headers.method,i=t.headers["request-id"],a={id:i,method:n,path:o,body:e};let c=200;const d={send:u=>{this.logger.debug(`sending response to ${r}`),this.logger.debug(u),la({msg:u,options:{responseId:i,destinationAddress:s,type:dg,sourceAddress:r,status:c}})},status:function(u){return c=u,this}};if(a.path==="/openapi.json"){d.send(this.router.generateOpenApiSpec());return}await this.router.handle(a,d)}use(e,t,...s){this.router.use(e,t,...s)}async init(){this.logger.debug(`initializing browser-router ${this.id}`)}async load(){this.logger.debug(`loading browser-router ${this.id}`)}};oc([x({topic:lg})],Ds.prototype,"handleRequest",1);Ds=oc([C(nc)],Ds);const nr=new Ee({class:Ds,type:nc}),ic="future-container-model",Se=it(ic),ac=e=>To(ct)(e),ug=e=>{const t=ac(e);return Se.build(Se.type,{}).addFutureModel(t),t},hg=e=>Se.build(Se.type,{}).getFuture(String(e)),Fe={buildFutureModel:ac,initiateFuture:ug,getFuture:hg};var fg=Object.defineProperty,gg=Object.getOwnPropertyDescriptor,Oo=(e,t,s,r)=>{for(var o=r>1?void 0:r?gg(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&fg(t,s,o),o};const us=p.getLogger(Se.type);let Bt=class{constructor(e,t,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=Ja,addFuture:o=Xa}=t;this.logger=s.logger,this._deleteFuture=r,this._addFuture=o,this.id=e,this._futures=new me,this.createModel=this.createFuture,this.deleteModel=this.removeFuture}get futures(){return this._futures.data}get models(){return this.futures}getFuture(e){return this._futures.getModel(e)}addFutureModel(e){this._futures.addModel(e)}removeFutureModel(e){this._futures.removeModel(e)}async removeFuture(e){try{await this._deleteFuture(e)}catch(t){us.error("error deleting a Future"),us.error(t)}}async createFuture(e){try{const t=await this._addFuture(e),s=t==null?void 0:t.data;if(s){const r=To(ct)(s);return this.addFutureModel(r),r}}catch(t){throw us.error("error creating a Future"),us.error(t),t}}handleFutureUpdated(e,t){const s=Fe.buildFutureModel(e);this.addFutureModel(s);const r=`kos.future/${e.tracker||e.id}`;this.logger.debug(`publishing future update to ${r}`),U(r,t.body,t.headers)}};Oo([fe],Bt.prototype,"_futures",2);Oo([x({topic:"kos.future"})],Bt.prototype,"handleFutureUpdated",1);Bt=Oo([C(Se.type)],Bt);const cc=Bt,{URL:es}=ee(),{getOne:pg,postModel:mg,deleteModel:lc}=X.build({basePath:`${es}/api/keyVal`}),xr=p.createLogger({name:"key-value-service",group:"Services"}),dc=async(e,t)=>{await lc({urlOverride:`${es}/api/keyVal/${e}/${t}`,id:t})},uc=async(e,t,s)=>{const r=await mg({urlOverride:`${es}/api/keyVal/${e}/${t}`,model:s.toString()});if((r==null?void 0:r.status)!==200)throw xr.error("Failed to update studio-state data",r),new Error(`Failed to update studio-state data for namespace ${e}`);return r.data},hc=async(e="studio")=>{xr.debug("sending GET for studio-state");const t=await pg({urlOverride:`${es}/api/keyVal/${e}`});if((t==null?void 0:t.status)!==200)throw xr.error("Failed to retrieve studio-state data",t),new Error(`Failed to retrieve studio-state data for namespace ${e}`);return t.data},yg=async e=>{await lc({urlOverride:`${es}/api/keyVal/${e}}`,id:""})},bg=Object.freeze(Object.defineProperty({__proto__:null,deleteKeyValue:dc,deleteKeyValueNamespace:yg,getKeyValue:hc,updateKeyValue:uc},Symbol.toStringTag,{value:"Module"}));var wg=Object.defineProperty,vg=Object.getOwnPropertyDescriptor,So=(e,t,s,r)=>{for(var o=r>1?void 0:r?vg(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&wg(t,s,o),o};const fc="key-value-model";let Kt=class{constructor(e,t,s){l(this,"id");l(this,"logger");l(this,"namespace");l(this,"data");this.id=e,this.logger=s.logger,this.data=Te(),this.namespace=t.namespace||"studio"}async init(){this.logger.debug(`initializing studio-state ${this.id}`)}async updateState(e,t){this.logger.debug(`updating studio-state ${e} with value ${t}`),t!==void 0?(await uc(this.namespace,e,t),this.data[e]=t):(await dc(this.namespace,e),this.data[e]=void 0)}async load(){this.logger.debug(`loading studio-state ${this.id}`);const e=await hc(this.namespace);this.data.setValues(e)}handleStateUpdate(e){e.namespace===this.namespace&&(this.data[e.key]=e.value)}handleStateDelete(e){e.namespace===this.namespace&&(this.data[e.key]=void 0)}};So([x({topic:"/keyVal/set"})],Kt.prototype,"handleStateUpdate",1);So([x({topic:"/keyVal/remove"})],Kt.prototype,"handleStateDelete",1);Kt=So([C(fc)],Kt);const $o=new ge({class:Kt,type:fc}),{URL:ts}=ee(),{postModel:Do,getOne:Mg}=X.build({basePath:`${ts}/api/kos-time`});p.createLogger({name:"kos-time-service",group:"Services"});const gc=async e=>{const t=await Do({model:e,urlOverride:`${ts}/api/kos/time/time`});if((t==null?void 0:t.status)!==200)throw Error("Failed to set time");return t.data},pc=async e=>{const t=await Do({model:e,urlOverride:`${ts}/api/kos/time/date`});if((t==null?void 0:t.status)!==200)throw Error("Failed to set time");return t.data},mc=async e=>{const t=await Do({model:{},urlOverride:`${ts}/api/kos/time/timezone?tz=${e}`});if((t==null?void 0:t.status)!==200)throw Error("Failed to set timezone");return t.data},yc=async()=>{const e=await Mg({urlOverride:`${ts}/api/kos/time/timezone`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set timezone");return e.data.timeZone},Eg=Object.freeze(Object.defineProperty({__proto__:null,getTimezone:yc,setDate:pc,setTime:gc,setTimezone:mc},Symbol.toStringTag,{value:"Module"}));var _g=Object.defineProperty,Ig=Object.getOwnPropertyDescriptor,ir=(e,t,s,r)=>{for(var o=r>1?void 0:r?Ig(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&_g(t,s,o),o};const yt="kos-time-model",Tg="/kos/time/time",Og="/kos/time/day",Sg="/kos/time/timezone";let Je=class{constructor(e,t,s){l(this,"id");l(this,"logger");l(this,"timezone");this.id=e,this.logger=s.logger,this.timezone=""}async updateSystemTime(e){await gc(e)}async updateSystemDate(e){await pc(e)}async updateSystemTimezone(e){await mc(e)}handleTimeChange(){U(Lt.TIME_CHANGE,{})}handleDayChange(){U(Lt.DAY_CHANGE,{})}async handleTimeZoneChange(){await this.retrieveTimezone(),U(Lt.TIMEZONE_CHANGE,{})}async init(){this.logger.debug(`initializing kos-time ${this.id}`)}async retrieveTimezone(){const e=await yc();this.setTimezone(e)}setTimezone(e){this.timezone=e}async load(){this.logger.debug(`loading kos-time ${this.id}`),this.retrieveTimezone()}};ir([x({topic:Tg,websocket:!0})],Je.prototype,"handleTimeChange",1);ir([x({topic:Og,websocket:!0})],Je.prototype,"handleDayChange",1);ir([x({topic:Sg,websocket:!0})],Je.prototype,"handleTimeZoneChange",1);Je=ir([C(yt)],Je);const Cs={registration:{[yt]:{class:Je,singleton:!0}},type:yt,predicate:ae(yt),factory:J.Singleton.create(yt)};var $g=Object.defineProperty,Dg=Object.getOwnPropertyDescriptor,bc=(e,t,s,r)=>{for(var o=r>1?void 0:r?Dg(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&$g(t,s,o),o};const wc="log-block-container-model";let As=class{constructor(e,t,s){l(this,"id");l(this,"logger");l(this,"_models");this.id=e,this.logger=s.logger,this._models=new me({parentId:e,sortKey:"blockNum"})}getModel(e){return this._models.getModel(e)}get models(){return this._models}get data(){return this._models.data}addModel(e){this._models.addModel(e)}removeModel(e){this._models.removeModel(e)}async init(){this.logger.debug(`initializing log-block-container container ${this.id}`)}async load(){this.logger.debug(`loading log-block-container container ${this.id}`)}};bc([fe],As.prototype,"_models",2);As=bc([C(wc)],As);const Cg=p.createLogger({name:"log-stream-container-service",group:"Services"}),vc=()=>{var r;const e=ie(),s=(e==null?void 0:e.connId)||((r=window==null?void 0:window.kosBridge)==null?void 0:r.call(window,"connId"));return p.error(`getKosConnectionId: ${s}`),s},lt=vc(),Ag="/api/kos/logs/node/{nodeId}/streams",Mc=async()=>(Cg.debug("sending GET for log-stream-container"),await De.get(Ag,{path:{nodeId:"primary"}},{destinationAddress:lt})),Ec=async(e,t="primary")=>{await De.post("/api/kos/logs/node/{nodeId}/{stream}/subscribe",{path:{nodeId:t,stream:e}},void 0,{destinationAddress:lt})},_c=async e=>{await De.post("/api/kos/logs/node/{nodeId}/{stream}/unsubscribe",{path:{nodeId:"primary",stream:e}},void 0,{destinationAddress:lt})},Rg=async()=>{await De.post("/api/kos/logs/overrides",{},{level:"WARN",name:"com.example",nodeType:"java",type:"package"},{destinationAddress:lt})},Ic=async e=>await De.get("/api/kos/logs/node/{nodeId}/{stream}/blocks",{path:{nodeId:"primary",stream:e}},{destinationAddress:lt}),Tc=async(e,t)=>await De.get("/api/kos/logs/node/{nodeId}/{stream}/blocks/{blockId}",{path:{nodeId:"primary",stream:e,blockId:t}},{destinationAddress:lt}),Pg=Object.freeze(Object.defineProperty({__proto__:null,createOverride:Rg,getKosConnectionId:vc,getLogStreamBlock:Tc,getLogStreamBlocks:Ic,getLogStreams:Mc,subscribeToLogStream:Ec,unsubscribeFromLogStream:_c},Symbol.toStringTag,{value:"Module"}));var xg=Object.defineProperty,Lg=Object.getOwnPropertyDescriptor,Fg=(e,t,s,r)=>{for(var o=r>1?void 0:r?Lg(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&xg(t,s,o),o};const Oc="log-block-model";let Lr=class{constructor(e,t,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=e,this.logger=s.logger,this.nodeId=t.nodeId,this.stream=t.stream,this.blockNum=t.blockNum,this.startLineNum=t.startLineNum,this.endLineNum=t.endLineNum,this.startTime=t.startTime,this.endTime=t.endTime,this.lineCount=t.lineCount,this.lines=[],this.inc=0}async syncLines(){const[e,t]=await Tc(this.stream,this.blockNum);if(e){this.logger.error(`Failed to get log block ${this.blockNum}`);return}t&&this.addLines(t.lines,!0)}updateModel(e){this.startLineNum=e.startLineNum,this.endLineNum=e.endLineNum,this.startTime=e.startTime,this.endTime=e.endTime,this.lineCount=e.lineCount}addLines(e,t){const s=t?[]:this.lines;this.lines=[...s,...e],this.inc+=1}async init(){this.logger.debug(`initializing log-block ${this.id}`)}async load(){this.logger.debug(`loading log-block ${this.id}`)}};Lr=Fg([C(Oc)],Lr);const Ht=new ge({class:Lr,type:Oc}),ar=new ge({class:As,type:wc});ar.addRelatedModel(Ht);var kg=Object.defineProperty,Ng=Object.getOwnPropertyDescriptor,Sc=(e,t,s,r)=>{for(var o=r>1?void 0:r?Ng(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&kg(t,s,o),o};const $c="log-stream-model";let Rs=class{constructor(e,t,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=e,this.logger=s.logger,this.currentBlockId="",this.name=t.name,this.nodeId=t.nodeId,this.isResetting=!0,this._blocks=ar.instance(`${e}-blocks`).options({}).build()}get firstLineNum(){const e=this.populated[0];return e?e.startLineNum:0}get currentBlock(){const e=this.currentBlockId;return this._blocks.getModel(e)}get populated(){return this._blocks.data.filter(e=>e.lines.length>0)}get blocks(){return this._blocks.data}get totalLineCount(){return this.populated.reduce((e,t)=>e+t.lineCount,0)}accept(e){e.visit(this)}updateBlock(e){var r;let t=this._blocks.models.getModel(`${e.stream}-block-${e.blockNum}`);const s={nodeId:e.nodeId,blockNum:e.blockNum,endLineNum:e.endLineNum,lineCount:e.lineCount,startLineNum:e.startLineNum,stream:this.name,endTime:new Date(e.endTime),startTime:new Date(e.startTime)};t||(t=Ht.instance(`${e.stream}-block-${e.blockNum}`).options(s).build(),this._blocks.addModel(t)),t&&t.updateModel(s),(!this.currentBlock||e.blockNum>=((r=this.currentBlock)==null?void 0:r.blockNum))&&(this.currentBlockId=`${e.stream}-block-${e.blockNum}`)}addBlock(e){var s;const t=Ht.instance(`${e.stream}-block-${e.blockNum}`).options({nodeId:e.nodeId,blockNum:e.blockNum,endLineNum:e.endLineNum,lineCount:e.lineCount,startLineNum:e.startLineNum,stream:this.name,endTime:new Date(e.endTime),startTime:new Date(e.startTime)}).build();this._blocks.addModel(t),(!this.currentBlock||e.blockNum>=((s=this.currentBlock)==null?void 0:s.blockNum))&&(this.currentBlockId=`${e.stream}-block-${e.blockNum}`)}removeBlock(e){this._blocks.models.removeModel(`${this.name}-block-${e}`)}async subscribe(){await Ec(this.name)}async unsubscribe(){await _c(this.name)}async reset(){if(this.isResetting=!0,this.populated.length>0)return;this.logger.debug(`resetting log-stream ${this.id}`);for(const t of this._blocks.models.data)t.lines=[];const e=this._blocks.data[this._blocks.data.length-1];e&&await e.syncLines(),this.isResetting=!1}async init(){this.logger.debug(`initializing log-stream ${this.id}`)}async load(){this.logger.debug(`loading log-stream ${this.id}`);const[e,t]=await Ic(this.name);if(e){this.logger.error(`Error loading log stream: ${e}`);return}if(t)for(const r of t)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 e;this.shouldStop=!0,(e=this.generatorInstance)==null||e.next(),console.log("Requested generator stop.")}async*streamLogs(){const e=[];let t=null,s=0,r=this.currentBlockId;const o=La(()=>{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,e.push(...i.lines);else{const a=i.lines.slice(s);e.push(...a),s+=a.length}t&&(t(),t=null)},{fireImmediately:!0});try{for(const n of this.populated.filter(i=>i!==this.currentBlock))for(const i of n.lines)yield i;for(;;)for(e.length===0&&await new Promise(n=>t=n);e.length>0;)yield e.shift()}finally{o()}}};Sc([fe],Rs.prototype,"_blocks",2);Rs=Sc([C($c)],Rs);const Ft=new ge({class:Rs,type:$c});var Ug=Object.defineProperty,jg=Object.getOwnPropertyDescriptor,Be=(e,t,s,r)=>{for(var o=r>1?void 0:r?jg(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&Ug(t,s,o),o};const Dc="log-stream-container-model",Bg="/kos/logs/subscription/addBlock/*",Kg="/kos/logs/subscription/updateBlock/*",Hg="/kos/logs/subscription/removeBlock/*",Gg="/kos/logs/subscription/lines/*",Cc="/kos/logs/streams/add/*";let we=class{constructor(e,t,s){l(this,"id");l(this,"logger");l(this,"selectedStream");l(this,"_models");this.id=e,this.logger=s.logger,this._models=new me({parentId:e}),this.selectedStream=void 0}getModel(e){return this._models.getModel(e)}get models(){return this._models}get data(){return this._models.data}updateModel(e){}addModel(e){this._models.addModel(e)}removeModel(e){this._models.removeModel(e)}updateSelectedStream(e){this.selectedStream=e}handleStreamAdded(e){this.logger.debug(`Received topic: ${Cc}`);const t=e.stream,s=Ft.instance(t).options({name:t,nodeId:"primary"}).build();this.addModel(s)}handleAddBlock(e,t){this.logger.debug(`Received topic: ${t.headers.topic}`);const s=e.stream,r=this.models.getModel(s);r&&r.addBlock(e)}handleRemoveBlock(e,t){this.logger.debug(`Received topic: ${t.headers.topic}`);const s=e.stream,r=this.models.getModel(s);r&&r.removeBlock(e.blockNum)}handleUpdateBlock(e,t){this.logger.debug(`Received topic: ${t.headers.topic}`);const s=e.stream,r=this.models.getModel(s);r&&r.updateBlock(e)}handleLogLine(e,t){var o;this.logger.debug(`Received topic: ${t.headers.topic}`);const s=e.stream,r=this.models.getModel(s);r&&((o=r.currentBlock)==null||o.addLines(e.lines))}async init(){this.logger.debug(`initializing log-stream-container container ${this.id}`)}async subscribeToLogStream(e){const t=Ft.instance(e).options({name:e,nodeId:"primary"}).build();this.addModel(t),await t.subscribe()}async load(){this.logger.debug(`loading log-stream-container container ${this.id}`);const[e,t]=await Mc();if(e){this.logger.error(`Error loading log-streams: ${e}`);return}t&&t.forEach(s=>{const r=Ft.instance(s).options({name:s,nodeId:"primary"}).build();this.addModel(r)})}};Be([fe],we.prototype,"_models",2);Be([x({topic:[Cc],websocket:!0})],we.prototype,"handleStreamAdded",1);Be([x({topic:[Bg],websocket:!0})],we.prototype,"handleAddBlock",1);Be([x({topic:[Hg],websocket:!0})],we.prototype,"handleRemoveBlock",1);Be([x({topic:[Kg],websocket:!0})],we.prototype,"handleUpdateBlock",1);Be([x({topic:[Gg],websocket:!0})],we.prototype,"handleLogLine",1);we=Be([C(Dc)],we);const ss=new Ee({class:we,type:Dc});ss.addRelatedModel(Ft);ss.addRelatedModel(ar);ss.addRelatedModel(Ht);const zg=e=>e.rank!==void 0,Vg=e=>e.visibleRole!==void 0,Yg=e=>e.color!==void 0,qg=e=>{const t=e.info;return zg(t)?t.rank:0},Wg=e=>{const t=e.info;return Yg(t)?t.color:"orange"},Zg=e=>{const t=e.info;return Vg(t)?t.visibleRole:"TECHNICIAN"},{URL:Co}=ee(),{getAll:Jg,postModel:Ac}=X.build({basePath:`${Co}/api/kos/troubles`}),Rc=async()=>await Jg({}),Pc=async(e,t)=>{try{const s=await Ac({model:{},urlOverride:`${Co}/api/kos/troubles/resolve/${e}`,tracker:t});return s!=null&&s.data&&Fe.initiateFuture(s.data),s.data}catch{const r={id:t||"",endState:Oe.Fail,tracker:t,reason:"Failed to resolve trouble"};return Fe.initiateFuture(r),r}},Xg=async(e,t)=>{try{const s=await Ac({model:e,urlOverride:`${Co}/api/kos/troubles/resolve/`,tracker:t});return s!=null&&s.data&&Fe.initiateFuture(s.data),s.data}catch{const r={id:t||"",endState:Oe.Fail,tracker:t,reason:"Failed to resolve troubles"};return Fe.initiateFuture(r),r}},Qg=Object.freeze(Object.defineProperty({__proto__:null,bulkResolveTroubles:Xg,getTroubles:Rc,resolveTrouble:Pc},Symbol.toStringTag,{value:"Module"})),Ps="troubleDataMapper",hs=new Map;Qs(Ps,{register:(e,t)=>{var s;hs.has(e)||hs.set(e,[]),(s=hs.get(e))==null||s.push(t)},execute:async(e,t)=>{const s=hs.get(e);if(!s)return{...t.data};const r=s.map(i=>i(t));return(await Promise.allSettled(r)).reduce((i,a)=>(a.status==="fulfilled"?i={...i,...a.value}:p.info(`Trouble mapper ${e} failed: ${a.reason}`),i),{...t.data})}});const rs="troubleMapper",fs=new Map;Qs(rs,{register:(e,t)=>{var s;fs.has(e)||fs.set(e,[]),(s=fs.get(e))==null||s.push(t)},execute:async(e,t)=>{const s=fs.get(e);if(!s)return[];const r=s.map(i=>i(t)),n=(await Promise.allSettled(r)).map(i=>i.status==="fulfilled"?i.value:(p.info(`Trouble mapper ${e} failed: ${i.reason}`),[])).flat();return Array.from(new Set(n))}});$[rs].register("nozzle",async e=>[e.data.nozzlePath]);$[rs].register("path",async e=>[e.data.path]);const ep=async e=>{const t=new Set,s=e.ifaces,r=s==null?void 0:s.map(n=>$[rs].execute(n,e));return(await Promise.allSettled(r)).forEach(n=>{n.status==="fulfilled"&&n.value.forEach(i=>t.add(i))}),Array.from(t)},xc=async e=>{const t=e.ifaces,s=t==null?void 0:t.map(i=>$[Ps].execute(i,e)),r=$[Ps].execute(e.type,e);s.push(r);const n=(await Promise.allSettled(s)).reduce((i,a)=>(a.status==="fulfilled"&&(i={...i,...a.value}),i),{});return{...e.data,...n}};class tp{constructor(){l(this,"type","ResolvableTrouble");l(this,"title","Resolvable Trouble");l(this,"subtitle","Trouble")}}class sp{constructor(){l(this,"type","BlockPumpTrouble");l(this,"title","Block Pump Trouble");l(this,"subtitle","Trouble")}}class Ge{static getHandler(t){switch(t){case"ResolvableTrouble":return new tp;case"BlockPumpTrouble":return new sp;default:return}}}var rp=Object.defineProperty,op=Object.getOwnPropertyDescriptor,Lc=(e,t,s,r)=>{for(var o=r>1?void 0:r?op(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&rp(t,s,o),o};const bt="trouble-model";function gs(e){return typeof e.shouldDefer=="boolean"}let xs=class{constructor(e,{resolvable:t,tags:s,info:r,id:o,clientData:n,rank:i,ifaces:a,type:c,group:d,createTime:u,role:h,color:g,...m},v){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,"group");l(this,"createTime");l(this,"_mapped",{});this.id=e,this.logger=v.logger,this.type=c,this._troubleId=o,this._resolvable=!!t,this.ifaces=a,this.rank=i,this.role=h,this.color=g,this.tags=s,this.info=r,this.group=d,this.createTime=u,this.clientData=n,this.data={},Object.assign(this.data,m),this.futureHandler=new rr(this)}getTitleWithContext(e){var s,r;const t=e?(r=(s=Ge.getHandler(this.type))==null?void 0:s.context)==null?void 0:r[e]:Ge.getHandler(this.type);return(t==null?void 0:t.title)||"Trouble"}getSubtitleWithContext(e){var s,r;const t=e?(r=(s=Ge.getHandler(this.type))==null?void 0:s.context)==null?void 0:r[e]:Ge.getHandler(this.type);return(t==null?void 0:t.subtitle)||"Trouble"}get rawId(){return this._troubleId}get title(){var e;return((e=Ge.getHandler(this.type))==null?void 0:e.title)||"Trouble"}get subtitle(){var e;return((e=Ge.getHandler(this.type))==null?void 0:e.subtitle)||"Trouble"}get troubleId(){return this._troubleId}get resolvable(){return this._resolvable}get future(){return this.futureHandler.future}async resolveMappedData(){return await xc(this)}get deferredCompanion(){const e=Ar(this.id,t=>gs(t));if(e&&gs(e.modelData))return e.modelData}get deferred(){return this.deferredCompanion?this.deferredCompanion.deferred:!1}get shouldDefer(){const e=Ar(this.id,t=>gs(t));return e&&gs(e.modelData)?e.modelData.shouldDefer:!1}clearDefer(){var e;(e=this.deferredCompanion)==null||e.clearDefer()}defer(){var e;(e=this.deferredCompanion)==null||e.defer()}getChildren(){return[...this.futureHandler.allFutures]}async resolve(e){var t;if(!this._resolvable)throw this.logger.error(`attempting to resolve an unresolvable trouble with id ${this._troubleId}`),new Error("Trouble is not resolvable");if(this.shouldDefer){(t=this.deferredCompanion)==null||t.defer();return}return await Pc(this._troubleId,e)}};Lc([qo()],xs.prototype,"resolve",1);xs=Lc([C(bt)],xs);const Gt={registration:{[bt]:{class:xs,singleton:!1}},type:bt,predicate:ae(bt),factory:J.Factory.create(bt)};var np=Object.defineProperty,ip=Object.getOwnPropertyDescriptor,cr=(e,t,s,r)=>{for(var o=r>1?void 0:r?ip(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&np(t,s,o),o};const _n=p.createLogger({name:"trouble-container-model"});function In(e){return $.propertyMapper.hasMapper(de.TroubleRank)?$.propertyMapper.executeMapper(de.TroubleRank,e):qg(e)}function Tn(e){return($.propertyMapper.hasMapper(de.TroubleColor)?$.propertyMapper.executeMapper(de.TroubleColor,e):Wg(e)).toLowerCase()}function On(e){return($.propertyMapper.hasMapper(de.TroubleRole)?$.propertyMapper.executeMapper(de.TroubleRole,e):Zg(e)).toLowerCase()}const ap="trouble-container-model";class oe{}l(oe,"INDEX_TROUBLES_BY_IFACE","byIface"),l(oe,"INDEX_TROUBLES_BY_TYPE","byType"),l(oe,"INDEX_TROUBLES_BY_GROUP","byGroup"),l(oe,"INDEX_TROUBLES_BY_DEFERRED","byDeferred"),l(oe,"SORT_KEY_RANK","rank"),l(oe,"TROUBLES_DEFERRED","true");let Xe=class{constructor(e){l(this,"id");l(this,"troubles");this.id=e,this.troubles=new me({indexMap:{[oe.INDEX_TROUBLES_BY_IFACE]:ep,[oe.INDEX_TROUBLES_BY_TYPE]:"type",[oe.INDEX_TROUBLES_BY_GROUP]:"group",[oe.INDEX_TROUBLES_BY_DEFERRED]:"deferred"},sortKey:oe.SORT_KEY_RANK,parentId:e})}async load(){_n.debug("loading trouble container");const e=await Rc();try{e==null||e.data.forEach(t=>{const s={...t,rank:In(t),color:Tn(t),role:On(t),id:String(t.id)},r=Gt.factory(`trouble-${t.id}`)(s);this.troubles.addModel(r)})}catch(t){throw _n.error(t),t}}handleTroubleRemoved(e){const t=`trouble-${e}`,s=this.troubles.getModel(t);this.troubles.removeModel(t),s&&Le(s)}handleTroubleAdded(e){const t={...e,rank:In(e),color:Tn(e),role:On(e),id:String(e.id)};if(t.role==="NONE")return;const s=Gt.factory(`trouble-${e.id}`)(t);this.troubles.addModel(s)}};cr([fe],Xe.prototype,"troubles",2);cr([x({topic:"/kos/trouble/remove",websocket:!0,lifecycle:B.INIT})],Xe.prototype,"handleTroubleRemoved",1);cr([x({topic:"/kos/trouble/add",websocket:!0})],Xe.prototype,"handleTroubleAdded",1);Xe=cr([C(ap)],Xe);const ps="trouble-container-model",Qe={registration:{[ps]:{class:Xe,singleton:!0}},type:ps,predicate:ae(ps),factory:J.Singleton.create(ps)},{URL:Fc}=ee(),{getAll:cp}=X.build({basePath:`${Fc}/api/kos/ota`}),Sn=p.createLogger({name:"ota-service",group:"Services"}),lp=async()=>{Sn.debug("sending GET request to /api/kos/ota/artifacts");const e=await cp({urlOverride:`${Fc}/api/kos/ota/artifacts`});return Sn.debug("getArtifacts - response:",e),e==null?void 0:e.data};var dp=Object.defineProperty,up=Object.getOwnPropertyDescriptor,lr=(e,t,s,r)=>{for(var o=r>1?void 0:r?up(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&dp(t,s,o),o};const kc="ota-model",hp=e=>{let t=null;for(const s in e){const r=e[s],o=r.lastUpdateTime;(!t||t.lastUpdateTime<o)&&(t=r)}return t},Er=e=>{const t=e.artifactInfo,s=hp(e.requests),r=(t==null?void 0:t.identifier)||(s==null?void 0:s.kabId);if(!r)return;let o;switch(e.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=t===void 0;return{id:r,manifest:n,label:t==null?void 0:t.version,name:t==null?void 0:t.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/(t==null?void 0:t.size)*100:void 0,size:t==null?void 0:t.size}};let et=class{constructor(e,t,s){l(this,"id");l(this,"logger");l(this,"data",new Ca);l(this,"troubleContainer");this.id=e,this.logger=s.logger}get downloadInProgressTrouble(){var t;return(t=this.troubleContainer.troubles.getIndexByKey("byType","OTADownloadInProgressTrouble"))==null?void 0:t[0]}get updatePendingTrouble(){var t;return(t=this.troubleContainer.troubles.getIndexByKey("byType","OTAUpdatePendingTrouble"))==null?void 0:t[0]}get pausedDueToErrorsTrouble(){var t;return(t=this.troubleContainer.troubles.getIndexByKey("byType","OTAPausedDueToErrorsTrouble"))==null?void 0:t[0]}get updates(){return this.data}get status(){return this.pausedDueToErrorsTrouble?"error":this.downloadInProgressTrouble?"downloading":this.updatePendingTrouble?"pending":"idle"}installAndReboot(){var e;this.updatePendingTrouble||this.logger.error("installAndReboot - OTAUpdatePendingTrouble not present"),this.logger.debug("installAndReboot - resolve OTAUpdatePendingTrouble"),(e=this.updatePendingTrouble)==null||e.resolve()}async init(){this.logger.debug(`initializing ota ${this.id}`)}async load(){this.logger.debug(`loading ota ${this.id}`);try{const e=await lp();e&&e.forEach(t=>{const s=Er(t);s&&this.data.addModel(s)})}catch(e){this.logger.error(`loading ota ${this.id} - error:`,e)}}async handleAllArtifacts(e){this.logger.debug("handleAllArtifacts:",e),await this.data.clear();try{e.forEach(t=>{const s=Er(t);s&&this.data.addModel(s)})}catch(t){this.logger.error(`handleAllArtifacts ${this.id} - error:`,t)}}handleChangedArtifacts(e){this.logger.debug("handleChangedArtifacts:",e);try{e.forEach(t=>{const s=Er(t);s&&this.data.updateModel(s)})}catch(t){this.logger.error(`handleChangedArtifacts ${this.id} - error:`,t)}}};lr([Ne({modelType:Qe.type})],et.prototype,"troubleContainer",2);lr([x({topic:"/kos/ota/artifacts/all",websocket:!0})],et.prototype,"handleAllArtifacts",1);lr([x({topic:"/kos/ota/artifacts/changed",websocket:!0})],et.prototype,"handleChangedArtifacts",1);et=lr([C(kc)],et);const Ls=new Ee({class:et,type:kc});function fp(e){let t;const s=async(...r)=>{t&&t.abort(),t=new AbortController;const o=t;try{return await e(...r,o.signal)}finally{t===o&&(t=void 0)}};return s.cancel=()=>{t&&(t.abort(),t=void 0)},s.getController=()=>t,s.isActive=()=>!!t,s}const _r=p.createLogger({name:"software-info-service",group:"Services"}),Ao=async e=>{_r.debug("sending GET for software-info");const[t,s]=await rc.get("/api/kos/manifest/info",void 0,{signal:e});if(!s)throw e!=null&&e.aborted?(_r.debug("Request was aborted"),new ne("Request was aborted")):(_r.error("Failed to fetch software-info",t),new ne("Failed to fetch software-info"));return s},gp=fp(Ao),pp=Object.freeze(Object.defineProperty({__proto__:null,getSoftwareInfos:Ao,getSoftwareInfosWithCancel:gp},Symbol.toStringTag,{value:"Module"}));var mp=Object.defineProperty,yp=Object.getOwnPropertyDescriptor,bp=(e,t,s,r)=>{for(var o=r>1?void 0:r?yp(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&mp(t,s,o),o};const wt="software-info-model";let Fr=class{constructor(e,t,s){l(this,"id");l(this,"logger");l(this,"nodes");this.id=e,this.logger=s.logger,this.nodes=[]}async init(){this.logger.debug(`initializing software-info ${this.id}`)}groupBy(e,t){return e.reduce((s,r)=>(s[r[t]]=[...s[r[t]]||[],r],s),{})}async load(){this.logger.debug(`loading software-info ${this.id}`);try{const e=await Ao(),t=(e==null?void 0:e.nodes)||{};Q(()=>{const r=Object.keys(t).map(o=>t[o][0]).map(o=>({nodeName:o.nodeType,kosVersion:o.kosVersion,group:this.groupBy(o.artifacts,"group")}));this.nodes=r})}catch(e){e instanceof ne&&this.logger.error("Failed to fetch software-info",e)}}};Fr=bp([C(wt)],Fr);const Fs={registration:{[wt]:{class:Fr,singleton:!1}},type:wt,predicate:ae(wt),factory:J.Factory.create(wt)},{URL:Nc}=ee(),{getOne:wp}=X.build({basePath:`${Nc}/api/kos/state`}),vp=p.createLogger({name:"state-bean-service",group:"Services"}),Uc=async({path:e})=>(vp.debug("sending GET for state-bean"),await wp({urlOverride:`${Nc}/api/kos/state/${e}`})),Mp=Object.freeze(Object.defineProperty({__proto__:null,getStateBeanData:Uc},Symbol.toStringTag,{value:"Module"}));var Ep=Object.defineProperty,_p=Object.getOwnPropertyDescriptor,jc=(e,t,s,r)=>{for(var o=r>1?void 0:r?_p(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&Ep(t,s,o),o};const vt="state-bean-model",Ip=ke("path");let ks=class{constructor(e,t,s){l(this,"id");l(this,"path");l(this,"props");l(this,"logger");this.id=e,this.logger=s.logger,this.props=po.map(new Map),$r(t,this)}updateModel(e){$r(e,this)}handleConfigBeanUpdated(e){Object.entries(e).forEach(([t,s])=>{let r=s;typeof r=="string"&&bo(r)&&(r=r.toLowerCase()=="true"),typeof r=="string"&&tr(r)&&(r=Number(r)),this.props.set(t,r)})}async init(){this.logger.debug(`initializing state-bean ${this.id}`)}updateProps(e){Object.entries(e).forEach(([t,s])=>{this.props.set(t,s)})}async load(){this.logger.debug(`loading state-bean ${this.id}`);const e=await Uc({path:this.path});e!=null&&e.data&&this.updateProps(e.data)}};jc([x({topic:`/kos/state/${Ip}`,websocket:!0})],ks.prototype,"handleConfigBeanUpdated",1);ks=jc([C(vt)],ks);const zt={registration:{[vt]:{class:ks,singleton:!1}},type:vt,predicate:ae(vt),factory:J.Factory.create(vt)};var Tp=Object.defineProperty,Op=Object.getOwnPropertyDescriptor,Bc=(e,t,s,r)=>{for(var o=r>1?void 0:r?Op(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&Tp(t,s,o),o};const Mt="state-prop-model",$n=ke("path");let Ns=class{constructor(e,t,s){l(this,"id");l(this,"path");l(this,"attribute");l(this,"logger");l(this,"stateBean");this.id=e,this.logger=s.logger,this.path=t.path,this.attribute=t.attribute}get value(){return this.stateBean.props.get(this.attribute)}async init(){this.logger.debug(`initializing state-prop ${this.id}`)}async load(){this.logger.debug(`loading state-prop ${this.id}`)}toString(){var e;return((e=this.value)==null?void 0:e.toString())??""}};Bc([Ne({modelType:zt.type,id:`state-bean-${$n}`,options:{path:$n}})],Ns.prototype,"stateBean",2);Ns=Bc([C(Mt)],Ns);const Ro={registration:{[Mt]:{class:Ns,singleton:!1}},type:Mt,predicate:ae(Mt),factory:J.Factory.create(Mt)},{URL:Sp}=ee(),{getAll:$p}=X.build({basePath:`${Sp}/api/state-prop`}),Dp=p.createLogger({name:"state-prop-service",group:"Services"}),Cp=async()=>(Dp.debug("sending GET for state-prop"),await $p({})),Ap=Object.freeze(Object.defineProperty({__proto__:null,getStateProps:Cp},Symbol.toStringTag,{value:"Module"})),{URL:Po}=ee(),{getOne:Kc}=X.build({basePath:`${Po}/api/translation`}),kt=p.createLogger({name:"translation-service",group:"Services"}),Rp=()=>{const e=window.location.origin,t=ie();return(t==null?void 0:t.host)||e},Hc=async(e,t)=>{kt.debug("sending GET for translation");const s=t??Rp();try{const r=await fetch(`${s}${e}`);return r.status!==200?(kt.warn(`Failed to fetch translations at ${e}: ${r.status}`),{}):await r.json()}catch(r){throw kt.error("Error fetching translations",r),r}},Pp=async()=>{kt.debug("getting localization descriptor");const e=await Kc({urlOverride:`${Po}/api/system/kos/localization`});if((e==null?void 0:e.status)!==200)throw new Error(`Failed to get tool localization descriptor ${e==null?void 0:e.status}`);return e.data},Gc=e=>async()=>{kt.debug("getting kos localization descriptor");const t=await Kc({urlOverride:`${Po}/api/kos/localization/contexts`});if((t==null?void 0:t.status)!==200)throw new Error(`Failed to get tool localization descriptor ${t==null?void 0:t.status}`);return t.data[e]},zc="langResolver";var xp=Object.defineProperty,Lp=Object.getOwnPropertyDescriptor,Fp=(e,t,s,r)=>{for(var o=r>1?void 0:r?Lp(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&xp(t,s,o),o};const Et="translation-model";function kp(e){const t=typeof e=="string",s=t?!1:!!(e!=null&&e.data)&&typeof(e==null?void 0:e.data)!="string",r=t?e:e==null?void 0:e.defaultValue,o=t||e==null?void 0:e.context,n=t?void 0:s?e==null?void 0:e.data:e;return{isBasicOptions:t,defaultValue:r,context:o,data:n}}function Vc(e,t=""){return Object.keys(e).reduce((s,r)=>{const o=t?`${t}.${r}`:r;if(typeof e[r]=="object"&&e[r]!==null){const n=Vc(e[r],o);return{...s,...n}}else return{...s,[o]:e[r]}},{})}function Yc(e,t){const s={...e};for(const r in t)Object.prototype.hasOwnProperty.call(t,r)&&(typeof t[r]=="object"&&t[r]!==null&&typeof e[r]=="object"&&e[r]!==null?s[r]=Yc(e[r],t[r]):s[r]=t[r]);return s}const kr=(e,t)=>{const s=/__(.*?)__/g,r=e.replace(s,(o,n)=>Object.prototype.hasOwnProperty.call(t||{},n.trim())?t==null?void 0:t[n.trim()]:o);return r===e?r:s.test(r)?kr(r,t):r},ms=(e,t,s)=>{const r=/{{(.*?)}}/g,n=kr(e,t).replace(r,(a,c)=>Object.prototype.hasOwnProperty.call(s||{},c.trim())?s==null?void 0:s[c.trim()]:a);return kr(n,t)},Dn=(e,t)=>{if(t.includes(":")){const[s,r]=t.split(":");return{namespace:s,key:r}}else return{namespace:e,key:t}};let Nr=class{constructor(e,t,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=e,this.defaultLocale=t.defaultLocale||"en",this.currentLocale=t.currentLocale||"en",this.namespace=t.namespace,this.descriptor=t.descriptor,this.rootUrl=t.rootUrl,this.data={},this.resolver=t.resolver||s.kosContext.get(zc),this.bundleResolver=t.bundleResolver,this.logger=s.logger,this.context=s.kosContext.parentModel}getTranslationLocales(e){const t=this.descriptor[e];if(!e||!t)return[this.defaultLocale];if(!this.defaultLocale&&!t.fallbacks)return[e];let s=t.fallbacks||[this.defaultLocale];return s.includes(e)||(s=[e,...s]),s}async loadTranslations(){const e=this.getTranslationLocales(this.currentLocale).reverse(),t=e.map(r=>{if(this.bundleResolver){const o=N.getContext(this.id);return this.bundleResolver(this.namespace,r,o)}try{const o=this.resolver(this.namespace,r);return Hc(o,this.rootUrl)}catch{return Promise.resolve({})}}),s=await Promise.allSettled(t);Q(()=>{const r=s.reduce((o,n,i)=>(n.status==="fulfilled"?(this.logger.debug(`resolved ${e[i]}`,n.value),n.value&&(o=Yc(o,n.value))):this.logger.error(`failed to load translation ${this.id} for ${e[i]}`),o),{});this.data=Vc(r)})}async init(){this.logger.debug(`initializing translation ${this.id}`)}exists(e){const{namespace:t,key:s}=Dn(this.namespace,e);if(t!==this.namespace){const r=this.context.getModel(t);return r?r.exists(s):!1}return!!this.data[s]}resolveKey(e,t){if(!e)return this.logger.debug("key is empty"),"";const{defaultValue:s,context:r,data:o}=kp(t),{namespace:n,key:i}=Dn(this.namespace,e),a=`${i}_${r}`;if(n!==this.namespace){const c=this.context.getModel(n);return c?c.resolveKey(i,t):i}if(r&&this.data[a]){const c=this.data[a];return Array.isArray(c)?c.map(d=>ms(d,this.data,o)):ms(this.data[a],this.data,o)}if(this.data[i]){const c=this.data[a];return Array.isArray(c)?c.map(d=>ms(d,this.data,o)):ms(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,(e,t)=>{this.logger.info(`translation langs for namespace ${this.id} changed from ${t} to ${e}`),this.loadTranslations()})}};Nr=Fp([er(),C(Et)],Nr);const Us={registration:{[Et]:{class:Nr,singleton:!1}},type:Et,predicate:ae(Et),factory:J.Factory.create(Et)};var Np=Object.defineProperty,Up=Object.getOwnPropertyDescriptor,qc=(e,t,s,r)=>{for(var o=r>1?void 0:r?Up(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&Np(t,s,o),o};const _t="translation-container-model",jp=(e,t="/")=>e.join(t).replace(new RegExp(t+"{1,}","g"),t);function Bp(e,t){const s=this.descriptor.namespaces[e];if(!s)throw new Error(`namespace ${e} not found in descriptor`);const r=s.basePath,o=s.locales[t].file;return jp([r,o])}let js=class{constructor(e,t,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=e,this.lang=t.lang||"en",this.descriptor=t.descriptor,this._defaultNamespace=t.defaultNamespace,this.descriptorUrl=t.descriptorUrl,this.rootUrl=t.rootUrl,this.resolver=t.resolver||Bp.bind(this),s.kosContext.set(zc,this.resolver),this.logger=s.logger,this._models=new me({parentId:e})}set currentLocale(e){this.lang=e,this.models.data.forEach(t=>{t.currentLocale=e})}get defaultNamespace(){return this._defaultNamespace?this.getModel(`translation-${this._defaultNamespace}`):void 0}getModel(e){return this.logger.debug(`getting model ${e}`),this._models.getModel(`translation-${e}`)}get models(){return this._models}get data(){return this._models.data}async reload(){this._models.clear(),await pa(this);for(const e of this.namespaces){const t=this.resolveNamespace(e);await re(t)}}resolveNamespace(e){var s;if((s=this.descriptor.namespaces)==null?void 0:s[e]){const r=Object.keys(this.descriptor.namespaces[e].locales)[0],o=this.descriptor.namespaces[e].locales[r].defaultLocale,n=Us.factory(`translation-${e}`)({kosParentId:this.id,namespace:e,rootUrl:this.rootUrl,currentLocale:this.lang,defaultLocale:o,descriptor:this.descriptor.namespaces[e].locales,resolver:this.resolver});return this.addModel(n),this.namespaces.includes(e)||Q(()=>{this.namespaces.push(e)}),n}else{this.logger.warn(`namespace ${e} not found in descriptor`);const r=Us.factory(`translation-${e}`)({kosParentId:this.id,namespace:e,rootUrl:this.rootUrl,currentLocale:this.lang,defaultLocale:this.lang,descriptor:{},resolver:this.resolver});return this.addModel(r),r}}addModel(e){this._models.addModel(e)}removeModel(e){this._models.removeModel(e)}async init(){this.logger.debug(`initializing translation-container container ${this.id}`)}async load(){this.logger.debug(`loading translation-container container ${this.id}`)}};qc([fe],js.prototype,"_models",2);js=qc([C(_t)],js);const ve={registration:{[_t]:{class:js,singleton:!0}},type:_t,predicate:ae(_t),factory:J.Singleton.create(_t)},Kp={set(e,t){const s=N.getContext(ve.type);s&&s.set(e,t)},get(e){const t=N.getContext(ve.type);return t==null?void 0:t.get(e)}},Wc={async init(e){const t=ve.factory(e);return await re(t),{translations:t}}},Hp=(e,t)=>{const s=t.type;return e[s]||(e[s]=[]),e[s].push(t),e},Zc="kos-ws-event",xo=it(Zc);var Gp=Object.defineProperty,zp=Object.getOwnPropertyDescriptor,Lo=(e,t,s,r)=>{for(var o=r>1?void 0:r?zp(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&Gp(t,s,o),o};const Vp=({headers:e,body:t})=>Object.entries(e).map(([r,o])=>`${r}:${o}`).join("\\n")+"\\n\\n"+t;exports.WsEventModel=class{constructor(t){l(this,"id");l(this,"events");l(this,"_topicMap");this.id=t,this.events=M.observable.map(new Map),this._topicMap=new Map}get websocketEvents(){return Array.from(this.events.values())}handleSendEvent(t,s){this.processEvent(s,!0)}handleReceiveEvent(t,s){this.processEvent(s)}processEvent(t,s=!1){p.debug("kos event received");const{body:r,headers:o}=t.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 d=this._topicMap.get(i)||0;a=`${a}-${d+1}`,this._topicMap.set(i,d+1)}const c={msgId:a,content:r,headers:o,timestamp:Date.now(),raw:Vp({headers:o,body:r}),direction:s?"send":"receive",mocked:!!o.mocked};this.events.set(a,c),p.debug(`logged ${this.events.size} events`)}}};Lo([x({topic:[Jt.SEND]})],exports.WsEventModel.prototype,"handleSendEvent",1);Lo([x({topic:[Jt.RECEIVED]})],exports.WsEventModel.prototype,"handleReceiveEvent",1);exports.WsEventModel=Lo([C(xo.type)],exports.WsEventModel);const Cn=ie(),Yp=Cn.debug==="true"||Cn.debug===!0,qp="/api/system/canvas",Jc=async(e,t)=>{const s=t||qp,r=`${exports.BASE_URL}${s}`;await exports.kosFetch(r,{method:"POST",headers:{hide:Yp?"false":"true"},body:e})},Wp=Object.freeze(Object.defineProperty({__proto__:null,sendCanvasData:Jc},Symbol.toStringTag,{value:"Module"})),Zp=(e,t,s)=>e>>5<<5|t>>5<<2|s>>6;function Jp(e,t,s){if(t==="base64"){const r=s?e.filter((o,n)=>n%4!==3):Array.from(e);return btoa(String.fromCharCode(...r))}else{const r=[];for(let o=0;o<e.length;o+=4)r.push(Zp(e[o],e[o+1],e[o+2]));return String.fromCharCode(...r)}}var Xp=Object.defineProperty,Qp=Object.getOwnPropertyDescriptor,Xc=(e,t,s,r)=>{for(var o=r>1?void 0:r?Qp(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&Xp(t,s,o),o};const Qc="canvas-renderer-model";function An(e){return typeof e.onDone=="function"}let Bs=class{constructor(e,t,s){l(this,"id");l(this,"router");l(this,"logger");l(this,"_renderer",null);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=e,this.logger=s.logger,this.width=t.width??50,this.height=t.height??30,this.fps=t.fps??10,this.durationMs=t.durationMs??null,this.apiPath=t.apiPath??"/api/system/canvas",this.endpointName=t.endpoint}set onFrame(e){this._onFrame=e}set renderer(e){var t,s;this._renderer&&(this.stopStreaming(),(s=(t=this._renderer).dispose)==null||s.call(t)),this._renderer=e,this.isStreaming&&this.startStreaming()}sendDataFrame(e,t){Jc(e,t)}checkStreaming(){if(this.isOneShotDone()||!this.isStreaming){requestAnimationFrame(()=>{this.stopStreaming()});return}}handleFrame(e){var s;const t=Jp(e,"base64",!0);this.sendDataFrame(t,this.apiPath),(s=this._onFrame)==null||s.call(this,t)}stopStreaming(){var e,t;this.isStreaming=!1,this.renderLoopId&&cancelAnimationFrame(this.renderLoopId),this.sendIntervalId&&clearInterval(this.sendIntervalId),this.timeoutId&&clearTimeout(this.timeoutId),(t=(e=this._renderer)==null?void 0:e.pause)==null||t.call(e)}isOneShotDone(){var e,t;return An(this._renderer)&&((t=(e=this._renderer).isOneShot)==null?void 0:t.call(e))===!0&&this._renderer.isOneShotDone}startStreaming(){var e,t,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(),(t=(e=this._renderer).play)==null||t.call(e);const o=An(this._renderer);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()});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,d;const a=(d=(c=this._renderer)==null?void 0:c.readPixels)==null?void 0:d.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(e,t)=>{this.stopStreaming(),t.send({status:"OK"})}),this.router.use("POST",`/api/ui/canvas/${this.endpointName}/start`,async(e,t)=>{this.startStreaming(),t.send({status:"OK"})})}};Xc([Ne({modelType:nr.type})],Bs.prototype,"router",2);Bs=Xc([C(Qc)],Bs);const Fo=new ge({class:Bs,type:Qc});class em{constructor({src:t}){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=t,this.video.crossOrigin="anonymous",this.video.muted=!0,this.video.loop=!1,this.canvas=document.createElement("canvas");const s=this.canvas.getContext("2d");if(!s)throw new Error("2D canvas not supported");this.ctx=s,this.handleEnded=this.handleEnded.bind(this),this.video.addEventListener("ended",this.handleEnded)}handleEnded(){this.doneCallback&&this.doneCallback()}reset(){this.video.pause(),this.video.currentTime=0,this.lastUpdate=performance.now()}play(){this.video.play().catch(console.warn)}pause(){this.video.pause()}renderFrame(t,s){this.canvas.width=t,this.canvas.height=s,this.video.readyState>=2&&this.ctx.drawImage(this.video,0,0,t,s)}readPixels(t,s){return this.ctx.getImageData(0,0,t,s).data}onDone(t){this.doneCallback=t}dispose(){this.video.pause(),this.video.removeAttribute("src"),this.video.load(),this.video.remove(),this.video.removeEventListener("ended",this.handleEnded),this.doneCallback=null}shouldStep(t){const s=performance.now();return s-this.lastUpdate>=t?(this.lastUpdate=s,!0):!1}}class tm{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 t=this.canvas.getContext("webgl");if(!t)throw new Error("WebGL not supported");this.gl=t}shouldStep(t){const s=performance.now();return s-this.lastUpdate>=t?(this.lastUpdate=s,!0):!1}readPixels(t=this.lastWidth,s=this.lastHeight){const r=new Uint8Array(t*s*4);this.gl.readPixels(0,0,t,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*t*4,a=(s-1-n)*t*4;o.set(r.subarray(i,i+t*4),a)}return o}}class sm extends tm{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=`
|
|
78
78
|
attribute vec2 a_position;
|
|
79
79
|
void main() {
|
|
80
80
|
gl_Position = vec4(a_position, 0, 1);
|
|
@@ -108,7 +108,7 @@ ${d}topics:${t}
|
|
|
108
108
|
vec3 rgb = hslToRgb(hue, 1.0, 0.5);
|
|
109
109
|
gl_FragColor = vec4(rgb, 1.0);
|
|
110
110
|
}
|
|
111
|
-
`,i=this.compileShader(o.VERTEX_SHADER,r),c=this.compileShader(o.FRAGMENT_SHADER,n);this.program=this.createProgram(i,c),this.posBuffer=o.createBuffer(),o.bindBuffer(o.ARRAY_BUFFER,this.posBuffer),o.bufferData(o.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,-1,1,1,-1,1,1]),o.STATIC_DRAW),this.aPosition=o.getAttribLocation(this.program,"a_position"),this.uMinHue=o.getUniformLocation(this.program,"minHue"),this.uMaxHue=o.getUniformLocation(this.program,"maxHue"),this.uHueOffset=o.getUniformLocation(this.program,"hueOffset"),this.uGridHeight=o.getUniformLocation(this.program,"gridHeight")}reset(){this.hueOffset=0,this.lastUpdate=performance.now()}renderFrame(s,o){const r=this.gl;if(this.canvas.width=s,this.canvas.height=o,this.shouldStep(50)){const n=this.speedPx/o;this.hueOffset=(this.hueOffset+n)%1}r.viewport(0,0,s,o),r.clear(r.COLOR_BUFFER_BIT),r.useProgram(this.program),r.enableVertexAttribArray(this.aPosition),r.bindBuffer(r.ARRAY_BUFFER,this.posBuffer),r.vertexAttribPointer(this.aPosition,2,r.FLOAT,!1,0,0),r.uniform1f(this.uMinHue,this.minHue/360),r.uniform1f(this.uMaxHue,this.maxHue/360),r.uniform1f(this.uHueOffset,this.hueOffset),r.uniform1f(this.uGridHeight,o),r.drawArrays(r.TRIANGLES,0,6)}compileShader(s,o){const r=this.gl.createShader(s);if(this.gl.shaderSource(r,o),this.gl.compileShader(r),!this.gl.getShaderParameter(r,this.gl.COMPILE_STATUS))throw new Error(this.gl.getShaderInfoLog(r)||"Shader compile failed");return r}createProgram(s,o){const r=this.gl.createProgram();if(this.gl.attachShader(r,s),this.gl.attachShader(r,o),this.gl.linkProgram(r),!this.gl.getProgramParameter(r,this.gl.LINK_STATUS))throw new Error("Program linking failed");return r}}class Jt{constructor(){a(this,"canvas");a(this,"ctx");a(this,"lastUpdate",0);this.canvas=document.createElement("canvas");const t=this.canvas.getContext("2d");if(!t)throw new Error("2D canvas not supported");this.ctx=t}dispose(){this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.canvas.remove()}shouldStep(t){const s=performance.now();return s-this.lastUpdate>=t?(this.lastUpdate=s,!0):!1}readPixels(t,s){return this.ctx.getImageData(0,0,t,s).data}}function Tr(e){class t extends e{constructor(){super(...arguments);a(this,"doneCallback",null);a(this,"oneShotDone",!1)}isOneShot(){return!0}onDone(r){this.doneCallback=r}signalDoneIfNeeded(){var r;this.oneShotDone||((r=this.doneCallback)==null||r.call(this),this.oneShotDone=!0)}resetOneShot(){this.doneCallback=null,this.oneShotDone=!1}get isOneShotDone(){return this.oneShotDone}}return t}const am=Tr(Jt);class cm extends am{constructor({colors:s=["red","yellow","green"],direction:o="horizontal",speed:r=2,loop:n=!0}={}){super();a(this,"offset",0);a(this,"speed");a(this,"colors");a(this,"direction");a(this,"loop");this.colors=s,this.direction=o,this.speed=r,this.loop=n}reset(){this.offset=0,this.lastUpdate=performance.now(),this.loop||this.resetOneShot()}renderFrame(s,o){if(!this.loop&&this.isOneShotDone)return;this.loop&&this.shouldStep(50)&&(this.offset+=this.speed);const r=this.loop?-this.offset:0,n=this.loop?s*2-this.offset:s,i=this.ctx.createLinearGradient(r,0,n,0),c=1/(this.colors.length-1);this.colors.forEach((l,d)=>{i.addColorStop(d*c,l)}),this.ctx.fillStyle=i,this.ctx.fillRect(0,0,s,o),!this.loop&&!this.isOneShotDone&&this.signalDoneIfNeeded()}}const lm=Tr(Jt);class dm extends lm{constructor(s){super();a(this,"img");a(this,"loaded",!1);this.img=new Image,this.img.src=s,this.img.crossOrigin="anonymous",this.img.onload=()=>{this.loaded=!0}}reset(){this.resetOneShot()}renderFrame(s,o){!this.loaded||this.isOneShotDone||(this.canvas.width=s,this.canvas.height=o,this.ctx.drawImage(this.img,0,0,s,o),this.signalDoneIfNeeded())}}class um extends Jt{constructor({speed:s=1,fallChance:o=.7}={}){super();a(this,"columns",[]);a(this,"fallChance");a(this,"speed");this.speed=s,this.fallChance=o}reset(){this.columns=[],this.lastUpdate=performance.now()}renderFrame(s,o){this.columns.length!==s&&(this.columns=Array(s).fill(0).map(()=>Math.floor(Math.random()*o))),this.shouldStep(50)&&(this.columns=this.columns.map(i=>i>o+5?0:i+(Math.random()<this.fallChance?this.speed:0)));const r=this.ctx.createImageData(s,o),n=r.data;n.fill(0);for(let i=0;i<o;i++)for(let c=0;c<s;c++){const l=this.columns[c];let d=0,u=0,h=0;i===l?(u=255,h=255):i<l&&i>l-5&&(u=100+Math.floor(30*(5-(l-i))),h=255);const f=(i*s+c)*4;n[f]=d,n[f+1]=u,n[f+2]=h,n[f+3]=255}this.ctx.putImageData(r,0,0)}}const hm=Tr(Jt);class gm extends hm{constructor({r:s,g:o,b:r}={r:0,g:0,b:0}){super();a(this,"color");this.color=`rgb(${s},${o},${r})`}setColor(s,o,r){this.color=`rgb(${s},${o},${r})`,this.resetOneShot()}reset(){this.resetOneShot()}renderFrame(s,o){this.isOneShotDone||(this.canvas.width=s,this.canvas.height=o,this.ctx.fillStyle=this.color,this.ctx.fillRect(0,0,s,o),this.signalDoneIfNeeded())}}class fm extends Jt{constructor({minHue:s=0,maxHue:o=360,speed:r=1}={}){super();a(this,"offset",0);a(this,"minHue");a(this,"maxHue");a(this,"speed");this.minHue=s,this.maxHue=o,this.speed=r}reset(){this.offset=0,this.lastUpdate=performance.now()}hslToRgb(s,o,r){let n,i,c;if(o===0)n=i=c=r;else{const l=(h,f,v)=>(v<0&&(v+=1),v>1&&(v-=1),v<.16666666666666666?h+(f-h)*6*v:v<.5?f:v<.6666666666666666?h+(f-h)*(.6666666666666666-v)*6:h),d=r<.5?r*(1+o):r+o-r*o,u=2*r-d;n=l(u,d,s+1/3),i=l(u,d,s),c=l(u,d,s-1/3)}return[Math.round(n*255),Math.round(i*255),Math.round(c*255)]}renderFrame(s,o){this.shouldStep(50)&&(this.offset=(this.offset+this.speed)%s);const r=this.ctx.createImageData(s,o),n=r.data;let i=0;for(let c=0;c<o;c++)for(let l=0;l<s;l++){const d=(l+this.offset)%s/s,u=this.minHue/360+d*((this.maxHue-this.minHue)/360),[h,f,v]=this.hslToRgb(u,1,.5);n[i++]=h,n[i++]=f,n[i++]=v,n[i++]=255}this.ctx.putImageData(r,0,0)}}const _n=new Map;Bs(ne,{register(e,t){_n.set(e,t)},execute(e,t){const s=_n.get(e);return s?new s(t):null}});$.canvas.registerRenderer("video",rm);$[ne].register("image",dm);$[ne].register("color",gm);$[ne].register("matrix",um);$[ne].register("sweep",fm);$[ne].register("gradient",cm);$[ne].register("drop",im);const En=({mode:e,data:t})=>{const s=$[ne].execute(e,t);if(s)return s;throw new Error(`Unknown mode: ${e}`)};var mm=Object.defineProperty,pm=Object.getOwnPropertyDescriptor,$r=(e,t,s,o)=>{for(var r=o>1?void 0:o?pm(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&mm(t,s,r),r};const Sc="canvas-dispatcher-model";function ym(e){if(e=e.replace(/^#/,""),e.length===3&&(e=e.split("").map(s=>s+s).join("")),e.length!==6)return null;const t=parseInt(e,16);return{r:t>>16&255,g:t>>8&255,b:t&255}}let Ut=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(this,"_content",new Map);a(this,"_patterns",new Map);a(this,"_endpointRenderers");a(this,"router");a(this,"pattern");a(this,"data");this.id=e,this.logger=s.logger,this._endpointRenderers=new ue}addNamedEndpoint(e,t){this._endpointRenderers.getModel(e)&&this.logger.warn(`Endpoint "${e}" already exists. Overwriting.`);const s=Ir.instance(e).options({apiPath:t.apiPath,width:t.width,height:t.height,fps:t.fps,durationMs:t.durationMs??null,endpoint:e}).build();return this._endpointRenderers.addModel(s),s}addContent(e,t){this._content.has(e)&&this.logger.warn(`Content "${e}" already exists. Overwriting.`),this._content.set(e,t)}addPattern(e,t){this._patterns.has(e)&&this.logger.warn(`Pattern "${e}" already exists. Overwriting.`),this._patterns.set(e,t)}async load(e){var s;const t=e==null?void 0:e.get(Ze.loader);t&&((s=t.patterns)==null||s.forEach(o=>{if(!o.id||!o.type||!o.data){this.logger.warn(`Invalid pattern data: ${JSON.stringify(o)}`);return}this.addPattern(o.id,o)})),this.router.use("POST","/api/ui/canvas/patterns",async(o,r)=>{var c,l;const n=o.body,i=Array.isArray(n)?n:[n];if(i.some(d=>!d.id||!d.type||!d.data)){(c=r.status)==null||c.call(r,400).send({error:"Invalid pattern data"});return}for(const d of i)this._patterns.has(d.id)&&this.logger.warn(`Pattern "${d.id}" already exists. Overwriting.`),this.addPattern(d.id,d);(l=r.status)==null||l.call(r,200).send({status:"OK"})}),this.router.use("POST","/api/ui/canvas/pattern/:endpoint/:pattern",async(o,r)=>{var u,h,f;const n=o.params.pattern,i=o.params.endpoint,c=this._endpointRenderers.getModel(i);if(!c){(u=r.status)==null||u.call(r,404).send({error:`Endpoint "${i}" not found`});return}if(!this._patterns.has(n)){(h=r.status)==null||h.call(r,404).send({error:`Pattern "${n}" not found`});return}const l=this._patterns.get(n),d=l.type;this.data=l.data,c.renderer=En({mode:d,data:this.data}),c.startStreaming(),(f=r.status)==null||f.call(r,200).send({status:"OK"})}),this.router.use("POST","/api/ui/canvas/color/:endpoint/:color",async(o,r)=>{var f,v,b;const n=o.params.color,i=ym(n);if(!i){(f=r.status)==null||f.call(r,400).send({error:"Invalid color format"});return}const c=o.params.endpoint,l=this._endpointRenderers.getModel(c);if(!l){(v=r.status)==null||v.call(r,404).send({error:`Endpoint "${c}" not found`});return}const{r:d,b:u,g:h}=i;l.renderer=En({mode:"color",data:{r:d,g:h,b:u}}),l.startStreaming(),(b=r.status)==null||b.call(r,200).send({status:"OK"})}),this.router.use("POST","/api/ui/canvas/endpoint",async(o,r)=>{var i,c;const n=o.body;if(!n.apiPath||!n.id){(i=r.status)==null||i.call(r,400).send({error:"Name and path are required"});return}this.addNamedEndpoint(n.id,n),(c=r.status)==null||c.call(r,200).send({status:"OK"})})}};$r([ae],Ut.prototype,"_endpointRenderers",2);$r([Ce({modelType:Ys.type})],Ut.prototype,"router",2);Ut=$r([S(Sc)],Ut);const Ze=new pe({class:Ut,type:Sc}),{URL:Or}=q(),{getOne:Dc}=Y.build({basePath:`${Or}/api/device`}),Ps=m.createLogger({name:"device-service",group:"Services"}),Ac=async()=>{Ps.debug("sending GET for device serial number");try{const e=await Dc({urlOverride:`${Or}/api/kos/device/serialNumber`});return[void 0,e==null?void 0:e.data.serialNumber]}catch(e){if(e instanceof le)return Ps.error(`Error fetching device serial number: ${e.payload.error}`),[e.payload.error,void 0]}return["unknownError",void 0]},Cc=async()=>{Ps.debug("sending GET for device details");try{const e=await Dc({urlOverride:`${Or}/api/kos/device`});return e?[void 0,e.data]:["unknownError",void 0]}catch(e){if(e instanceof le)return Ps.error(`Error fetching device serial number: ${e.payload.error}`),[e.payload.error,void 0]}return["unknownError",void 0]},bm=Object.freeze(Object.defineProperty({__proto__:null,getDeviceDetails:Cc,getSerialNumber:Ac},Symbol.toStringTag,{value:"Module"}));var vm=Object.defineProperty,wm=Object.getOwnPropertyDescriptor,Rc=(e,t,s,o)=>{for(var r=o>1?void 0:o?wm(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&vm(t,s,r),r};const Pc="device-model",Mm="/kos/criticalData/changed",_m="/kos/criticalData/available";let Ls=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(this,"_serialNumber");a(this,"_name");a(this,"_nodeId");this.id=e,this.logger=s.logger,this._serialNumber="unassigned",this._name="unassigned",this._nodeId="unassigned"}get serialNumber(){return this._serialNumber}get name(){return this._name}get nodeId(){return this._nodeId}get nodeType(){const[e]=this.nodeId.split("-");return e}get nodeName(){const[,e]=this.nodeId.split("-");return e}updateModel(e){this._serialNumber=e.serialNumber??"unassigned",this._name=e.name??"unassigned",this._nodeId=e.nodeId??"unassigned"}async loadDeviceData(){const[e,t]=await Cc();if(e){this.logger.error(`Error fetching device serial number: ${e}`);return}if(t){const{name:s,nodeId:o}=t;this.updateModel({name:s,nodeId:o,serialNumber:this.serialNumber})}}async loadSerialNumber(){const[e,t]=await Ac();if(e){this.logger.error(`Error fetching device serial number: ${e}`);return}this.updateModel({serialNumber:t,name:this.name,nodeId:this.nodeId})}async handleCriticalDataChanged(){this.logger.debug(`Critical data changed for device ${this.id}`),await this.loadSerialNumber()}async init(){this.logger.debug(`initializing device ${this.id}`)}async load(){this.logger.debug(`loading device ${this.id}`),await this.loadDeviceData(),await this.loadSerialNumber()}};Rc([R({topic:[Mm,_m],websocket:!0})],Ls.prototype,"handleCriticalDataChanged",1);Ls=Rc([S(Pc)],Ls);const xs=new pe({class:Ls,type:Pc});var Em=Object.defineProperty,Im=Object.getOwnPropertyDescriptor,Tm=(e,t,s,o)=>{for(var r=o>1?void 0:o?Im(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Em(t,s,r),r};const Lc="network-interface-model";let Co=class{constructor(e,t,s){a(this,"id");a(this,"name");a(this,"type");a(this,"nmdevicestate");a(this,"hwaddress");a(this,"mtu");a(this,"configured");a(this,"wifi");a(this,"ethernet");a(this,"ip4settings");a(this,"category");a(this,"logger");this.id=e,this.logger=s.logger,this.name=t.name,this.type=t.type,this.nmdevicestate=t.nmdevicestate,this.hwaddress=t.hwaddress,this.mtu=t.mtu,this.configured=t.configured,this.wifi=t.wifi,this.ethernet=t.ethernet,this.ip4settings=t.ip4settings,this.category=t.category}updateModel(e){this.name=e.name,this.type=e.type,this.nmdevicestate=e.nmdevicestate,this.hwaddress=e.hwaddress,this.mtu=e.mtu,this.configured=e.configured,this.wifi=e.wifi,this.ethernet=e.ethernet,this.ip4settings=e.ip4settings,this.category=e.category}async init(){this.logger.debug(`initializing network-interface ${this.id}`)}async load(){this.logger.debug(`loading network-interface ${this.id}`)}};Co=Tm([S(Lc)],Co);const Sr=new ce({class:Co,type:Lc}),{URL:$m}=q(),{getAll:Om}=Y.build({basePath:`${$m}/api/kos/network/interfaces`}),In=m.createLogger({name:"network-interface-service",group:"Services"}),xc=async()=>{In.debug("sending GET for copy-logs");try{const e=await Om({});return[void 0,e==null?void 0:e.data]}catch(e){if(e instanceof le)return In.error(`Error fetching log file size: ${e.payload.error}`),[e.payload.error,void 0]}return["unknownError",void 0]},Sm=Object.freeze(Object.defineProperty({__proto__:null,getNetworkInterfaces:xc},Symbol.toStringTag,{value:"Module"}));var Dm=Object.defineProperty,Am=Object.getOwnPropertyDescriptor,kc=(e,t,s,o)=>{for(var r=o>1?void 0:o?Am(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Dm(t,s,r),r};const Fc="network-interface-container-model";let ks=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(this,"_models");this.id=e,this.logger=s.logger,this._models=new ue({parentId:e,indexMap:{byCategory:"category"}})}getModel(e){return this._models.getModel(e)}get models(){return this._models}get data(){return this._models.data}addModel(e){this._models.addModel(e)}removeModel(e){this._models.removeModel(e)}async init(){this.logger.debug(`initializing network-interface-container container ${this.id}`)}async refreshInterfaces(){this.logger.debug("refreshing interfaces");const[e,t]=await xc();if(e){this.logger.error(`Error loading network interfaces: ${e}`);return}t&&t.forEach(s=>{const o=Sr.instance(s.name).forceUpdate.options(s).build();this.addModel(o)})}async load(){this.logger.debug(`loading network-interface-container container ${this.id}`),this.refreshInterfaces()}};kc([ae],ks.prototype,"_models",2);ks=kc([S(Fc)],ks);const jt=new pe({class:ks,type:Fc});jt.addRelatedModel(Sr);const{URL:Cm}=q(),{getAll:Rm}=Y.build({basePath:`${Cm}/api/kos/storage/devices`}),Tn=m.createLogger({name:"storage-device-service",group:"Services"}),Nc=async()=>{Tn.debug("sending GET for storage-device");const e=await Rm({});return!(e!=null&&e.data)||e.status!==200?(Tn.error("Failed to retrieve storage-device data",e),[]):e.data},Pm=Object.freeze(Object.defineProperty({__proto__:null,getStorageDevices:Nc},Symbol.toStringTag,{value:"Module"}));var Lm=Object.defineProperty,xm=Object.getOwnPropertyDescriptor,km=(e,t,s,o)=>{for(var r=o>1?void 0:o?xm(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Lm(t,s,r),r};const Uc="storage-device-model";let Ro=class{constructor(e,t,s){a(this,"id");a(this,"mountDir");a(this,"removed");a(this,"vendor");a(this,"runTimeMs");a(this,"model");a(this,"nodeId");a(this,"local");a(this,"label");a(this,"syspath");a(this,"logger");this.id=e,this.logger=s.logger,this.mountDir=t.mountDir,this.removed=t.removed,this.vendor=t.vendor,this.runTimeMs=t.runTimeMs,this.model=t.model,this.nodeId=t.nodeId,this.local=t.local,this.label=t.label,this.syspath=t.syspath}updateModel(e){this.mountDir=e.mountDir,this.removed=e.removed,this.vendor=e.vendor,this.runTimeMs=e.runTimeMs,this.model=e.model,this.nodeId=e.nodeId,this.local=e.local,this.label=e.label,this.syspath=e.syspath}async init(){this.logger.debug(`initializing storage-device ${this.id}`)}async load(){this.logger.debug(`loading storage-device ${this.id}`)}};Ro=km([Ks(),S(Uc)],Ro);const Fs=new ce({class:Ro,type:Uc});var Fm=Object.defineProperty,Nm=Object.getOwnPropertyDescriptor,Dr=(e,t,s,o)=>{for(var r=o>1?void 0:o?Nm(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Fm(t,s,r),r};const jc="storage-device-container-model",Um="/kos/storage";let Bt=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(this,"_models");this.id=e,this.logger=s.logger,this._models=new ue({parentId:e})}getModel(e){return this._models.getModel(e)}get models(){return this._models}get data(){return this._models.data}addModel(e){this._models.addModel(e)}removeModel(e){this._models.removeModel(e)}async init(){this.logger.debug(`initializing storage-device-container container ${this.id}`)}get isStorageInserted(){return this.data.length>0}get volumes(){return this.data}handleStorageAvailability(e){this._models.data.filter(s=>!e.find(o=>o.id===s.id)).forEach(s=>{this.removeModel(s.id)}),e.forEach(s=>{const o=this.getModel(s.id);if(o){const r={...s,kosParentId:this.id};o.updateModel(r)}else{const r={...s,kosParentId:this.id},n=Fs.instance(s.id).options(r).build();this.addModel(n)}})}async load(){this.logger.debug(`loading storage-device-container container ${this.id}`),(await Nc()).forEach(t=>{const s={...t,kosParentId:this.id},o=Fs.instance(t.id).options(s).build();this.addModel(o)})}};Dr([ae],Bt.prototype,"_models",2);Dr([R({topic:Um,websocket:!0})],Bt.prototype,"handleStorageAvailability",1);Bt=Dr([S(jc)],Bt);const Je=new pe({class:Bt,type:jc});Je.addRelatedModel(Fs);const{URL:Ar}=q(),{getAll:jm,postModel:Bm}=Y.build({basePath:`${Ar}/api/kos/update/available`}),$n=m.createLogger({name:"usb-update-service",group:"Services"}),Bc=async()=>{$n.debug("sending GET for usb-update");const e=await jm({urlOverride:`${Ar}/api/kos/update/available`});return!(e!=null&&e.data)||(e==null?void 0:e.status)!==200?($n.error("Failed to retrieve usb-update data",e),[]):e.data},Kc=async(e,t,s)=>{const o=await Bm({model:{manifestId:e,deviceId:t},tracker:s,urlOverride:`${Ar}/api/kos/update/install`});if(!(o!=null&&o.data))throw new Error("No response from server");return o.data},Km=Object.freeze(Object.defineProperty({__proto__:null,getAvailableUpdates:Bc,installUpdate:Kc},Symbol.toStringTag,{value:"Module"}));var Hm=Object.defineProperty,Gm=Object.getOwnPropertyDescriptor,Hc=(e,t,s,o)=>{for(var r=o>1?void 0:o?Gm(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Hm(t,s,r),r};const Gc="usb-update-model";let Ns=class{constructor(e,t,s){a(this,"id");a(this,"active");a(this,"blocked");a(this,"createTime");a(this,"deviceId");a(this,"manifestId");a(this,"notes");a(this,"futureHandler");a(this,"logger");this.id=e,this.logger=s.logger,this.active=t.active,this.blocked=t.blocked,this.createTime=t.createTime,this.deviceId=t.deviceId,this.manifestId=t.manifestId,this.notes=t.notes,this.futureHandler=new ur(this)}updateModel(e){this.active=e.active,this.blocked=e.blocked,this.createTime=e.createTime,this.deviceId=e.deviceId,this.manifestId=e.manifestId,this.notes=e.notes}reset(){this.futureHandler.removeFuture()}get future(){return this.futureHandler.future}async install(e){if(!e)throw new Error("No tracker provided");return this.logger.info(`Installing update for manifest ${this.manifestId} from device ${this.deviceId}`),Kc(this.manifestId,this.deviceId,e)}async init(){this.logger.debug(`initializing usb-update ${this.id}`)}async load(){this.logger.debug(`loading usb-update ${this.id}`)}};Hc([kr()],Ns.prototype,"install",1);Ns=Hc([S(Gc)],Ns);const Cr=new ce({class:Ns,type:Gc});var Vm=Object.defineProperty,Ym=Object.getOwnPropertyDescriptor,Js=(e,t,s,o)=>{for(var r=o>1?void 0:o?Ym(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Vm(t,s,r),r};const Vc="usb-update-container-model";let Xe=class{constructor(e,t,s){a(this,"id");a(this,"disposer");a(this,"storageService");a(this,"_activeUpdate");a(this,"logger");a(this,"_models");this.id=e,this.logger=s.logger,this._models=new ue({parentId:e})}getModel(e){return this._models.getModel(e)}get models(){return this._models}get data(){return this._models.data}addModel(e){this._models.addModel(e)}removeModel(e){this._models.removeModel(e)}get activeUpdate(){return this._activeUpdate}reset(){this.clearActiveUpdate()}clearActiveUpdate(){this._activeUpdate=void 0}updateActiveUpdate(e){this._activeUpdate=e}get isUsbInserted(){return this.storageService.isStorageInserted}get hasAvailableUpdates(){return this._models.data.length>0}async syncAvailableUpdates(){const e=await Bc();z(()=>{const t=e.map(s=>`${s.deviceId}-${s.manifestId}`);this._models.data.filter(s=>!t.includes(s.id)).forEach(s=>this.removeModel(s.id)),e.forEach(s=>{const o=`${s.deviceId}-${s.manifestId}`,r=Cr.instance(o).forceUpdate.options({...s,createTime:new Date(s.createTime)}).build();this.addModel(r)}),this.data.length===1?this.updateActiveUpdate(this.data[0]):this.clearActiveUpdate()})}usbInsertedEffect(){this.isUsbInserted?this.syncAvailableUpdates():(this._models.clear(),this.clearActiveUpdate())}async init(){this.logger.debug(`initializing usb-update-container container ${this.id}`)}unload(){var e;(e=this.disposer)==null||e.call(this)}async activate(){this.logger.debug(`activating usb-update-container container ${this.id}`),await this.syncAvailableUpdates()}async load(){this.logger.debug(`loading usb-update-container container ${this.id}`)}};Js([Ce({modelType:Je.type})],Xe.prototype,"storageService",2);Js([ae],Xe.prototype,"_models",2);Js([fi({dependencies:e=>[e.isUsbInserted]})],Xe.prototype,"usbInsertedEffect",1);Xe=Js([S(Vc)],Xe);const Kt=new pe({class:Xe,type:Vc});Kt.addRelatedModel(Cr);const zm=()=>({...{[ot.type]:{class:Da},[ve.type]:{class:xa,singleton:!0},...G.registration,...Pe.registration,...qe.registration,...As.registration,...fe.registration,[_r.type]:{class:exports.WsEventModel,singleton:!0},...Nt.registration,...wr.registration,...Ms.registration}}),Rr=zm(),qm={models:Rr,preloadModels:[]},Wm=!0,Yc=e=>()=>{const t=Rr;return zi(Po)(Ft).model(qe).model(Je).model(Kt).model(xs).model($s).model(Ct).model(Os).model(yr).model(jt).model(Ze).model(Ir).model(Ys,Wm).model(Wt),Object.keys(t).forEach(s=>{const o=t[s];Yi(Po)(s,o)}),{preload:O.model.preloadModel(e),model:O.model.register(e),companion:O.companion.register(e),legacy:O.model.registerLegacyModel(e)}},ie={};ie.core={models:Yc(ie)};ie.preload=O.model.preloadModel(ie);ie.model=O.model.register(ie);ie.companion=O.companion.register(ie);ie.legacy=O.model.registerLegacyModel(ie);const Po=ie;class Zm{registerTroubleRankMapper(t){return $.propertyMapper.registerPropertyMapper(re.TroubleRank,t),this}registerTroubleRoleMapper(t){return $.propertyMapper.registerPropertyMapper(re.TroubleRole,t),this}registerTroubleColorMapper(t){return $.propertyMapper.registerPropertyMapper(re.TroubleColor,t),this}registerModelLoader(t,s){$.loader.registerLoader(t,s)}registerCanvasPatternLoader(t){$.loader.registerLoader(Ze.loader,t)}}const Jm=async(e,t)=>{const s=yr.instance(e).options({}).build(),o=t?`${t}-`:"";return await J(s),{getState:r=>s.data[`${o}${r}`],updateState:async(r,n)=>{await s.updateState(`${o}${r}`,n)},clean:async()=>{for(const r of s.data.keys)await s.updateState(`${o}${r}`,void 0)},unsubscribe:()=>{Se(s)}}},zc="kos:service:region",qc="regionId",Xm=`${zc}-${qc}`,Wc=async e=>{const t=Pe.factory(Xm)({path:zc,attribute:qc});await J(t),t.updateProperty(e)},Pr="/kos-timer-event",Lr="/kos-timer-event/tick",xr="defaultTimerEnd",yt=m.createLogger({name:"timer-manager"}),Qm=e=>e.updateProperty!==void 0;class Zc{constructor(t,s,o){a(this,"name");a(this,"timeout");a(this,"timer");a(this,"state","inactive");a(this,"decrementValue",1);a(this,"remainingTime");a(this,"timeoutActions",new Map);this.name=t;const r=typeof s=="number"?s:s.value||60;this.timeout=r,this.state="inactive",this.remainingTime=r,Qm(s)&&N(()=>{m.info(`Updating config value timer ${t} with new timeout value ${s.value}`);const n=s.value||60;this.updateTimeout(n)}),this.addTimeoutAction({name:xr}),o&&o.forEach(n=>{this.addTimeoutAction(n)})}get id(){return this.name}start(){if(this.state==="active"){yt.debug(`Timer ${this.name} already started`);return}(this.state==="inactive"||this.state==="paused")&&(this.state="active",this.timer=setInterval(()=>this.updateTimer(),1e3))}pause(){this.timer&&(yt.debug(`Pausing timer ${this.name}`),this.state="paused",clearInterval(this.timer))}restart(){this.pause(),this.remainingTime=this.timeout,this.start()}reset(){this.pause(),this.remainingTime=this.timeout,this.state="inactive"}updateTimeout(t){this.timeout=t,this.restart()}addTimeoutAction(t){const s=t.remainingTime??0;this.timeoutActions.has(s)||this.timeoutActions.set(s,[]);const o=t.name,r=this.timeoutActions.get(s).find(n=>n.name===o);r?r.action=t.action:this.timeoutActions.get(s).push(t)}removeTimeoutAction(t){for(const[s,o]of this.timeoutActions.entries()){const r=o.filter(n=>n.name!==t);r.length===0?this.timeoutActions.delete(s):this.timeoutActions.set(s,r)}}updateTimer(){if(this.remainingTime=Math.round((this.remainingTime-this.decrementValue)*100)/100,this.remainingTime<=0){this.state==="active"&&this.executeActions(0),this.pause();return}this.state==="active"&&this.executeActions(this.remainingTime)}executeActions(t){this.timeoutActions.has(t)&&this.timeoutActions.get(t).forEach(s=>{var o;yt.debug(`Executing timer action ${s.name} at ${t}`),(o=s.action)==null||o.call(s,s.name,t),this.notifyTimeoutAction(s),s.singleUse&&(yt.info(`${this.name} Removing single-use action ${s.name}`),this.removeTimeoutAction(s.name))}),this.notifyTick()}notifyTick(){F(`${Lr}/${this.name}`,{name:this.name,remainingTime:this.remainingTime})}notifyTimeoutAction(t){F(Pr,{name:this.name,action:t.name,remainingTime:this.remainingTime})}}const bt=new Map,Ue=(e,t)=>{const s=bt.get(e);if(!s){yt.error(`Timer ${e} not found`);return}t(s)},Jc={createRelativeTimer(e,t,s){const o=new Date,r=Math.round((t.getTime()-o.getTime())/1e3);return this.createTimer(e,r,s)},createTimer(e,t=60,s){if(bt.has(e))return bt.get(e);const o=new Zc(e,t,s);return bt.set(e,o),o},getTimer(e){return bt.get(e)},clearTimer(e){Ue(e,t=>t.pause())},restartTimer(e){Ue(e,t=>t.restart())},resetTimer(e){Ue(e,t=>t.reset())},addTimeoutAction(e,t){Ue(e,s=>s.addTimeoutAction(t))},removeTimeoutAction(e,t){Ue(e,s=>s.removeTimeoutAction(t))},startTimer(e){Ue(e,t=>t.start())}},Xc="kos:service:region:settings",Qc="timeZone",ep=`${Xc}-${Qc}`,Lo=async e=>{const t=Pe.factory(ep)({path:Xc,attribute:Qc});await J(t),t.updateProperty(e)},tp=e=>!e||!e.data;function kr(e={}){const{alias:t,namespace:s}=e;return(o,r,n)=>{o[Mt]=o[Mt]||{};const i=n.value,c=async function(...l){const d=et();m.debug(`Calling future service ${r} with tracker ${d}`);const u=De.initiateFuture({tracker:d,id:rr});s&&(u.namespace=s),m.debug(`waiting for future ${u.id} to be ready`),await J(u),m.debug(`future ${u.id} is ready`),z(()=>{m.debug(`Adding future ${u.id} to futureHandler`),this.futureHandler.addFuture(u,t)});try{const h=await i.apply(this,[...l,d]);m.debug(`received future response for ${d}`,h);const f=tp(h)?h:h==null?void 0:h.data;return f?(f.progress=1,m.debug("mapping future response to future model"),u.endState?m.debug(`future ${u.id} has already completed. Not updating the model`):gr(f,u)):this.futureHandler.removeFuture(t),f}catch(h){throw m.error(h),h}};o[Mt][r]={handler:c}}}const sp=({path:e})=>(t,s)=>{t[L]=t[L]||{},t[L][s]={modelType:Nt.type,id:`${Nt.type}-${e}`,options:{path:e},lifecycle:k.INIT}};function op(e){const{path:t,attribute:s}=e;return(o,r)=>{o[L]=o[L]||{},o[L][r]={modelType:wr.type,id:`${t}-${s}`,options:{path:t,attribute:s},lifecycle:k.INIT}}}const Ke=m.createLogger({name:"services",group:"Services"}),rp=async(e,t)=>el(e,t,`${exports.BASE_URL}/api/server/login`),el=async(e,t,s=`${exports.BASE_URL}/api/login`)=>{const o=await exports.kosFetch(`${s}`,{method:"POST",destinationAddress:"",body:JSON.stringify({email:e,password:t})});if(!o.ok){const n=await o.json();throw Error(`${n==null?void 0:n.error}`)}return await o.json()},np=async e=>tl(e,`${exports.BASE_URL}/api/server/startPasswordReset`,""),tl=async(e,t=`${exports.BASE_URL}/api/startPasswordReset`,s="server")=>{const o=await exports.kosFetch(`${t}?email=${e}`,{method:"POST",destinationAddress:s});if(!o.ok)throw Error(`There was a problem reseting config; returned status ${o.status}`);return await o.json()},ip=async(e,t)=>sl(e,t,`${exports.BASE_URL}/api/server/resetPassword`),sl=async(e,t,s=`${exports.BASE_URL}/api/resetPassword`)=>{Ke.debug(`resetting password with token ${e} and password ${t.replace(/./g,"*")}`);const o=await exports.kosFetch(`${s}`,{method:"POST",destinationAddress:"",body:JSON.stringify({token:e,password:t})});if(Ke.debug(`password reset returned status ${o.status}`),!o.ok){Ke.error(`password reset failed with message ${o.statusText}`);const n=await o.json();throw Error(`${n==null?void 0:n.error}:There was a problem resetting the password.`)}return await o.json()},ap=async(e,t,s)=>ol(e,t,s,`${exports.BASE_URL}/api/server/acceptInvite`),ol=async(e,t,s,o=`${exports.BASE_URL}/api/server/acceptInvite`)=>{Ke.debug(`accepting invite with token ${e} and password ${t.replace(/./g,"*")}`);const r=await exports.kosFetch(`${o}`,{method:"POST",destinationAddress:"",body:JSON.stringify({token:e,password:t,name:s})});if(Ke.debug(`invitation accept returned status ${r.status}`),!r.ok){Ke.error(`invite failed with message ${r.statusText}`);const i=await r.json();throw Error(`${i==null?void 0:i.error}:There was a problem accepting the invite.`)}return await r.json()},cp=Te.keyframes`
|
|
111
|
+
`,i=this.compileShader(r.VERTEX_SHADER,o),a=this.compileShader(r.FRAGMENT_SHADER,n);this.program=this.createProgram(i,a),this.posBuffer=r.createBuffer(),r.bindBuffer(r.ARRAY_BUFFER,this.posBuffer),r.bufferData(r.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,-1,1,1,-1,1,1]),r.STATIC_DRAW),this.aPosition=r.getAttribLocation(this.program,"a_position"),this.uMinHue=r.getUniformLocation(this.program,"minHue"),this.uMaxHue=r.getUniformLocation(this.program,"maxHue"),this.uHueOffset=r.getUniformLocation(this.program,"hueOffset"),this.uGridHeight=r.getUniformLocation(this.program,"gridHeight")}reset(){this.hueOffset=0,this.lastUpdate=performance.now()}renderFrame(s,r){const o=this.gl;if(this.canvas.width=s,this.canvas.height=r,this.shouldStep(50)){const n=this.speedPx/r;this.hueOffset=(this.hueOffset+n)%1}o.viewport(0,0,s,r),o.clear(o.COLOR_BUFFER_BIT),o.useProgram(this.program),o.enableVertexAttribArray(this.aPosition),o.bindBuffer(o.ARRAY_BUFFER,this.posBuffer),o.vertexAttribPointer(this.aPosition,2,o.FLOAT,!1,0,0),o.uniform1f(this.uMinHue,this.minHue/360),o.uniform1f(this.uMaxHue,this.maxHue/360),o.uniform1f(this.uHueOffset,this.hueOffset),o.uniform1f(this.uGridHeight,r),o.drawArrays(o.TRIANGLES,0,6)}compileShader(s,r){const o=this.gl.createShader(s);if(this.gl.shaderSource(o,r),this.gl.compileShader(o),!this.gl.getShaderParameter(o,this.gl.COMPILE_STATUS))throw new Error(this.gl.getShaderInfoLog(o)||"Shader compile failed");return o}createProgram(s,r){const o=this.gl.createProgram();if(this.gl.attachShader(o,s),this.gl.attachShader(o,r),this.gl.linkProgram(o),!this.gl.getProgramParameter(o,this.gl.LINK_STATUS))throw new Error("Program linking failed");return o}}class os{constructor(){l(this,"canvas");l(this,"ctx");l(this,"lastUpdate",0);this.canvas=document.createElement("canvas");const t=this.canvas.getContext("2d");if(!t)throw new Error("2D canvas not supported");this.ctx=t}dispose(){this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.canvas.remove()}shouldStep(t){const s=performance.now();return s-this.lastUpdate>=t?(this.lastUpdate=s,!0):!1}readPixels(t,s){return this.ctx.getImageData(0,0,t,s).data}}function ko(e){class t extends e{constructor(){super(...arguments);l(this,"doneCallback",null);l(this,"oneShotDone",!1)}isOneShot(){return!0}onDone(o){this.doneCallback=o}signalDoneIfNeeded(){var o;this.oneShotDone||((o=this.doneCallback)==null||o.call(this),this.oneShotDone=!0)}resetOneShot(){this.doneCallback=null,this.oneShotDone=!1}get isOneShotDone(){return this.oneShotDone}}return t}const rm=ko(os);class om extends rm{constructor({colors:s=["red","yellow","green"],direction:r="horizontal",speed:o=2,loop:n=!0}={}){super();l(this,"offset",0);l(this,"speed");l(this,"colors");l(this,"direction");l(this,"loop");this.colors=s,this.direction=r,this.speed=o,this.loop=n}reset(){this.offset=0,this.lastUpdate=performance.now(),this.loop||this.resetOneShot()}renderFrame(s,r){if(!this.loop&&this.isOneShotDone)return;this.loop&&this.shouldStep(50)&&(this.offset+=this.speed);const o=this.loop?-this.offset:0,n=this.loop?s*2-this.offset:s,i=this.ctx.createLinearGradient(o,0,n,0),a=1/(this.colors.length-1);this.colors.forEach((c,d)=>{i.addColorStop(d*a,c)}),this.ctx.fillStyle=i,this.ctx.fillRect(0,0,s,r),!this.loop&&!this.isOneShotDone&&this.signalDoneIfNeeded()}}const nm=ko(os);class im extends nm{constructor({src:s}){super();l(this,"img");l(this,"loaded",!1);this.img=new Image,this.img.src=s,this.img.crossOrigin="anonymous",this.img.onload=()=>{this.loaded=!0}}reset(){this.resetOneShot()}renderFrame(s,r){!this.loaded||this.isOneShotDone||(this.canvas.width=s,this.canvas.height=r,this.ctx.drawImage(this.img,0,0,s,r),this.signalDoneIfNeeded())}}class am extends os{constructor({speed:s=1,fallChance:r=.7}={}){super();l(this,"columns",[]);l(this,"fallChance");l(this,"speed");this.speed=s,this.fallChance=r}reset(){this.columns=[],this.lastUpdate=performance.now()}renderFrame(s,r){this.columns.length!==s&&(this.columns=Array(s).fill(0).map(()=>Math.floor(Math.random()*r))),this.shouldStep(50)&&(this.columns=this.columns.map(i=>i>r+5?0:i+(Math.random()<this.fallChance?this.speed:0)));const o=this.ctx.createImageData(s,r),n=o.data;n.fill(0);for(let i=0;i<r;i++)for(let a=0;a<s;a++){const c=this.columns[a];let d=0,u=0,h=0;i===c?(u=255,h=255):i<c&&i>c-5&&(u=100+Math.floor(30*(5-(c-i))),h=255);const g=(i*s+a)*4;n[g]=d,n[g+1]=u,n[g+2]=h,n[g+3]=255}this.ctx.putImageData(o,0,0)}}const cm=ko(os);class lm extends cm{constructor({r:s,g:r,b:o}={r:0,g:0,b:0}){super();l(this,"color");this.color=`rgb(${s},${r},${o})`}setColor(s,r,o){this.color=`rgb(${s},${r},${o})`,this.resetOneShot()}reset(){this.resetOneShot()}renderFrame(s,r){this.isOneShotDone||(this.canvas.width=s,this.canvas.height=r,this.ctx.fillStyle=this.color,this.ctx.fillRect(0,0,s,r),this.signalDoneIfNeeded())}}class dm extends os{constructor({minHue:s=0,maxHue:r=360,speed:o=1}={}){super();l(this,"offset",0);l(this,"minHue");l(this,"maxHue");l(this,"speed");this.minHue=s,this.maxHue=r,this.speed=o}reset(){this.offset=0,this.lastUpdate=performance.now()}hslToRgb(s,r,o){let n,i,a;if(r===0)n=i=a=o;else{const c=(h,g,m)=>(m<0&&(m+=1),m>1&&(m-=1),m<.16666666666666666?h+(g-h)*6*m:m<.5?g:m<.6666666666666666?h+(g-h)*(.6666666666666666-m)*6:h),d=o<.5?o*(1+r):o+r-o*r,u=2*o-d;n=c(u,d,s+1/3),i=c(u,d,s),a=c(u,d,s-1/3)}return[Math.round(n*255),Math.round(i*255),Math.round(a*255)]}renderFrame(s,r){this.shouldStep(50)&&(this.offset=(this.offset+this.speed)%s);const o=this.ctx.createImageData(s,r),n=o.data;let i=0;for(let a=0;a<r;a++)for(let c=0;c<s;c++){const d=(c+this.offset)%s/s,u=this.minHue/360+d*((this.maxHue-this.minHue)/360),[h,g,m]=this.hslToRgb(u,1,.5);n[i++]=h,n[i++]=g,n[i++]=m,n[i++]=255}this.ctx.putImageData(o,0,0)}}const Rn=new Map;Qs(ue,{register(e,t){Rn.set(e,t)},execute(e,t){const s=Rn.get(e);return s?new s(t):null}});$.canvas.registerRenderer("video",em);$[ue].register("image",im);$[ue].register("color",lm);$[ue].register("matrix",am);$[ue].register("sweep",dm);$[ue].register("gradient",om);$[ue].register("drop",sm);const Pn=({mode:e,data:t})=>{const s=$[ue].execute(e,t);if(s)return s;throw new Error(`Unknown mode: ${e}`)};var um=Object.defineProperty,hm=Object.getOwnPropertyDescriptor,No=(e,t,s,r)=>{for(var o=r>1?void 0:r?hm(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&um(t,s,o),o};const el="canvas-dispatcher-model";function fm(e){if(e=e.replace(/^#/,""),e.length===3&&(e=e.split("").map(s=>s+s).join("")),e.length!==6)return null;const t=parseInt(e,16);return{r:t>>16&255,g:t>>8&255,b:t&255}}let Vt=class{constructor(e,t,s){l(this,"id");l(this,"logger");l(this,"_content",new Map);l(this,"_patterns",new Map);l(this,"_endpointRenderers");l(this,"router");l(this,"pattern");l(this,"data");this.id=e,this.logger=s.logger,this._endpointRenderers=new me}addNamedEndpoint(e,t){this._endpointRenderers.getModel(e)&&this.logger.warn(`Endpoint "${e}" already exists. Overwriting.`);const s=Fo.instance(e).options({apiPath:t.apiPath,width:t.width,height:t.height,fps:t.fps,durationMs:t.durationMs??null,endpoint:e}).build();return this._endpointRenderers.addModel(s),s}addContent(e,t){this._content.has(e)&&this.logger.warn(`Content "${e}" already exists. Overwriting.`),this._content.set(e,t)}addPattern(e,t){this._patterns.has(e)&&this.logger.warn(`Pattern "${e}" already exists. Overwriting.`),this._patterns.set(e,t)}async load(e){var s;const t=e==null?void 0:e.get(tt.loader);t&&((s=t.patterns)==null||s.forEach(r=>{if(!r.id||!r.type||!r.data){this.logger.warn(`Invalid pattern data: ${JSON.stringify(r)}`);return}this.addPattern(r.id,r)})),this.router.use("POST","/api/ui/canvas/patterns",async(r,o)=>{var a,c;const n=r.body,i=Array.isArray(n)?n:[n];if(i.some(d=>!d.id||!d.type||!d.data)){(a=o.status)==null||a.call(o,400).send({error:"Invalid pattern data"});return}for(const d of i)this._patterns.has(d.id)&&this.logger.warn(`Pattern "${d.id}" already exists. Overwriting.`),this.addPattern(d.id,d);(c=o.status)==null||c.call(o,200).send({status:"OK"})}),this.router.use("POST","/api/ui/canvas/pattern/:endpoint/:pattern",async(r,o)=>{var u,h,g;const n=r.params.pattern,i=r.params.endpoint,a=this._endpointRenderers.getModel(i);if(!a){(u=o.status)==null||u.call(o,404).send({error:`Endpoint "${i}" not found`});return}if(!this._patterns.has(n)){(h=o.status)==null||h.call(o,404).send({error:`Pattern "${n}" not found`});return}const c=this._patterns.get(n),d=c.type;this.data=c.data,a.renderer=Pn({mode:d,data:this.data}),a.startStreaming(),(g=o.status)==null||g.call(o,200).send({status:"OK"})}),this.router.use("POST","/api/ui/canvas/color/:endpoint/:color",async(r,o)=>{var g,m,v;const n=r.params.color,i=fm(n);if(!i){(g=o.status)==null||g.call(o,400).send({error:"Invalid color format"});return}const a=r.params.endpoint,c=this._endpointRenderers.getModel(a);if(!c){(m=o.status)==null||m.call(o,404).send({error:`Endpoint "${a}" not found`});return}const{r:d,b:u,g:h}=i;c.renderer=Pn({mode:"color",data:{r:d,g:h,b:u}}),c.startStreaming(),(v=o.status)==null||v.call(o,200).send({status:"OK"})}),this.router.use("POST","/api/ui/canvas/endpoint",async(r,o)=>{var i,a;const n=r.body;if(!n.apiPath||!n.id){(i=o.status)==null||i.call(o,400).send({error:"Name and path are required"});return}this.addNamedEndpoint(n.id,n),(a=o.status)==null||a.call(o,200).send({status:"OK"})})}};No([fe],Vt.prototype,"_endpointRenderers",2);No([Ne({modelType:nr.type})],Vt.prototype,"router",2);Vt=No([C(el)],Vt);const tt=new Ee({class:Vt,type:el}),{URL:Uo}=ee(),{getOne:tl}=X.build({basePath:`${Uo}/api/device`}),Ks=p.createLogger({name:"device-service",group:"Services"}),sl=async()=>{Ks.debug("sending GET for device serial number");try{const e=await tl({urlOverride:`${Uo}/api/kos/device/serialNumber`});return[void 0,e==null?void 0:e.data.serialNumber]}catch(e){if(e instanceof ne)return Ks.error(`Error fetching device serial number: ${e.payload.error}`),[e.payload.error,void 0]}return["unknownError",void 0]},rl=async()=>{Ks.debug("sending GET for device details");try{const e=await tl({urlOverride:`${Uo}/api/kos/device`});return e?[void 0,e.data]:["unknownError",void 0]}catch(e){if(e instanceof ne)return Ks.error(`Error fetching device serial number: ${e.payload.error}`),[e.payload.error,void 0]}return["unknownError",void 0]},gm=Object.freeze(Object.defineProperty({__proto__:null,getDeviceDetails:rl,getSerialNumber:sl},Symbol.toStringTag,{value:"Module"}));var pm=Object.defineProperty,mm=Object.getOwnPropertyDescriptor,ol=(e,t,s,r)=>{for(var o=r>1?void 0:r?mm(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&pm(t,s,o),o};const nl="device-model",ym="/kos/criticalData/changed",bm="/kos/criticalData/available";let Hs=class{constructor(e,t,s){l(this,"id");l(this,"logger");l(this,"_serialNumber");l(this,"_name");l(this,"_nodeId");this.id=e,this.logger=s.logger,this._serialNumber="unassigned",this._name="unassigned",this._nodeId="unassigned"}get serialNumber(){return this._serialNumber}get name(){return this._name}get nodeId(){return this._nodeId}get nodeType(){const[e]=this.nodeId.split("-");return e}get nodeName(){const[,e]=this.nodeId.split("-");return e}updateModel(e){this._serialNumber=e.serialNumber??"unassigned",this._name=e.name??"unassigned",this._nodeId=e.nodeId??"unassigned"}async loadDeviceData(){const[e,t]=await rl();if(e){this.logger.error(`Error fetching device serial number: ${e}`);return}if(t){const{name:s,nodeId:r}=t;this.updateModel({name:s,nodeId:r,serialNumber:this.serialNumber})}}async loadSerialNumber(){const[e,t]=await sl();if(e){this.logger.error(`Error fetching device serial number: ${e}`);return}this.updateModel({serialNumber:t,name:this.name,nodeId:this.nodeId})}async handleCriticalDataChanged(){this.logger.debug(`Critical data changed for device ${this.id}`),await this.loadSerialNumber()}async init(){this.logger.debug(`initializing device ${this.id}`)}async load(){this.logger.debug(`loading device ${this.id}`),await this.loadDeviceData(),await this.loadSerialNumber()}};ol([x({topic:[ym,bm],websocket:!0})],Hs.prototype,"handleCriticalDataChanged",1);Hs=ol([C(nl)],Hs);const Gs=new Ee({class:Hs,type:nl});var wm=Object.defineProperty,vm=Object.getOwnPropertyDescriptor,Mm=(e,t,s,r)=>{for(var o=r>1?void 0:r?vm(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&wm(t,s,o),o};const il="network-interface-model";let Ur=class{constructor(e,t,s){l(this,"id");l(this,"name");l(this,"type");l(this,"nmdevicestate");l(this,"hwaddress");l(this,"mtu");l(this,"configured");l(this,"wifi");l(this,"ethernet");l(this,"ip4settings");l(this,"category");l(this,"logger");this.id=e,this.logger=s.logger,this.name=t.name,this.type=t.type,this.nmdevicestate=t.nmdevicestate,this.hwaddress=t.hwaddress,this.mtu=t.mtu,this.configured=t.configured,this.wifi=t.wifi,this.ethernet=t.ethernet,this.ip4settings=t.ip4settings,this.category=t.category}updateModel(e){this.name=e.name,this.type=e.type,this.nmdevicestate=e.nmdevicestate,this.hwaddress=e.hwaddress,this.mtu=e.mtu,this.configured=e.configured,this.wifi=e.wifi,this.ethernet=e.ethernet,this.ip4settings=e.ip4settings,this.category=e.category}async init(){this.logger.debug(`initializing network-interface ${this.id}`)}async load(){this.logger.debug(`loading network-interface ${this.id}`)}};Ur=Mm([C(il)],Ur);const jo=new ge({class:Ur,type:il}),{URL:Em}=ee(),{getAll:_m}=X.build({basePath:`${Em}/api/kos/network/interfaces`}),xn=p.createLogger({name:"network-interface-service",group:"Services"}),al=async()=>{xn.debug("sending GET for copy-logs");try{const e=await _m({});return[void 0,e==null?void 0:e.data]}catch(e){if(e instanceof ne)return xn.error(`Error fetching log file size: ${e.payload.error}`),[e.payload.error,void 0]}return["unknownError",void 0]},Im=Object.freeze(Object.defineProperty({__proto__:null,getNetworkInterfaces:al},Symbol.toStringTag,{value:"Module"}));var Tm=Object.defineProperty,Om=Object.getOwnPropertyDescriptor,cl=(e,t,s,r)=>{for(var o=r>1?void 0:r?Om(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&Tm(t,s,o),o};const ll="network-interface-container-model";let zs=class{constructor(e,t,s){l(this,"id");l(this,"logger");l(this,"_models");this.id=e,this.logger=s.logger,this._models=new me({parentId:e,indexMap:{byCategory:"category"}})}getModel(e){return this._models.getModel(e)}get models(){return this._models}get data(){return this._models.data}addModel(e){this._models.addModel(e)}removeModel(e){this._models.removeModel(e)}async init(){this.logger.debug(`initializing network-interface-container container ${this.id}`)}async refreshInterfaces(){this.logger.debug("refreshing interfaces");const[e,t]=await al();if(e){this.logger.error(`Error loading network interfaces: ${e}`);return}t&&t.forEach(s=>{const r=jo.instance(s.name).forceUpdate.options(s).build();this.addModel(r)})}async load(){this.logger.debug(`loading network-interface-container container ${this.id}`),this.refreshInterfaces()}};cl([fe],zs.prototype,"_models",2);zs=cl([C(ll)],zs);const Yt=new Ee({class:zs,type:ll});Yt.addRelatedModel(jo);const{URL:Sm}=ee(),{getAll:$m}=X.build({basePath:`${Sm}/api/kos/storage/devices`}),Ln=p.createLogger({name:"storage-device-service",group:"Services"}),dl=async()=>{Ln.debug("sending GET for storage-device");const e=await $m({});return!(e!=null&&e.data)||e.status!==200?(Ln.error("Failed to retrieve storage-device data",e),[]):e.data},Dm=Object.freeze(Object.defineProperty({__proto__:null,getStorageDevices:dl},Symbol.toStringTag,{value:"Module"}));var Cm=Object.defineProperty,Am=Object.getOwnPropertyDescriptor,Rm=(e,t,s,r)=>{for(var o=r>1?void 0:r?Am(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&Cm(t,s,o),o};const ul="storage-device-model";let jr=class{constructor(e,t,s){l(this,"id");l(this,"mountDir");l(this,"removed");l(this,"vendor");l(this,"runTimeMs");l(this,"model");l(this,"nodeId");l(this,"local");l(this,"label");l(this,"syspath");l(this,"logger");this.id=e,this.logger=s.logger,this.mountDir=t.mountDir,this.removed=t.removed,this.vendor=t.vendor,this.runTimeMs=t.runTimeMs,this.model=t.model,this.nodeId=t.nodeId,this.local=t.local,this.label=t.label,this.syspath=t.syspath}updateModel(e){this.mountDir=e.mountDir,this.removed=e.removed,this.vendor=e.vendor,this.runTimeMs=e.runTimeMs,this.model=e.model,this.nodeId=e.nodeId,this.local=e.local,this.label=e.label,this.syspath=e.syspath}async init(){this.logger.debug(`initializing storage-device ${this.id}`)}async load(){this.logger.debug(`loading storage-device ${this.id}`)}};jr=Rm([er(),C(ul)],jr);const Vs=new ge({class:jr,type:ul});var Pm=Object.defineProperty,xm=Object.getOwnPropertyDescriptor,Bo=(e,t,s,r)=>{for(var o=r>1?void 0:r?xm(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&Pm(t,s,o),o};const hl="storage-device-container-model",Lm="/kos/storage";let qt=class{constructor(e,t,s){l(this,"id");l(this,"logger");l(this,"_models");this.id=e,this.logger=s.logger,this._models=new me({parentId:e})}getModel(e){return this._models.getModel(e)}get models(){return this._models}get data(){return this._models.data}addModel(e){this._models.addModel(e)}removeModel(e){this._models.removeModel(e)}async init(){this.logger.debug(`initializing storage-device-container container ${this.id}`)}get isStorageInserted(){return this.data.length>0}get volumes(){return this.data}handleStorageAvailability(e){this._models.data.filter(s=>!e.find(r=>r.id===s.id)).forEach(s=>{this.removeModel(s.id)}),e.forEach(s=>{const r=this.getModel(s.id);if(r){const o={...s,kosParentId:this.id};r.updateModel(o)}else{const o={...s,kosParentId:this.id},n=Vs.instance(s.id).options(o).build();this.addModel(n)}})}async load(){this.logger.debug(`loading storage-device-container container ${this.id}`),(await dl()).forEach(t=>{const s={...t,kosParentId:this.id},r=Vs.instance(t.id).options(s).build();this.addModel(r)})}};Bo([fe],qt.prototype,"_models",2);Bo([x({topic:Lm,websocket:!0})],qt.prototype,"handleStorageAvailability",1);qt=Bo([C(hl)],qt);const st=new Ee({class:qt,type:hl});st.addRelatedModel(Vs);const{URL:Ko}=ee(),{getAll:Fm,postModel:km}=X.build({basePath:`${Ko}/api/kos/update/available`}),Fn=p.createLogger({name:"usb-update-service",group:"Services"}),fl=async()=>{Fn.debug("sending GET for usb-update");const e=await Fm({urlOverride:`${Ko}/api/kos/update/available`});return!(e!=null&&e.data)||(e==null?void 0:e.status)!==200?(Fn.error("Failed to retrieve usb-update data",e),[]):e.data},gl=async(e,t,s)=>{const r=await km({model:{manifestId:e,deviceId:t},tracker:s,urlOverride:`${Ko}/api/kos/update/install`});if(!(r!=null&&r.data))throw new Error("No response from server");return r.data},Nm=Object.freeze(Object.defineProperty({__proto__:null,getAvailableUpdates:fl,installUpdate:gl},Symbol.toStringTag,{value:"Module"}));var Um=Object.defineProperty,jm=Object.getOwnPropertyDescriptor,pl=(e,t,s,r)=>{for(var o=r>1?void 0:r?jm(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&Um(t,s,o),o};const ml="usb-update-model";let Ys=class{constructor(e,t,s){l(this,"id");l(this,"active");l(this,"blocked");l(this,"createTime");l(this,"deviceId");l(this,"manifestId");l(this,"notes");l(this,"futureHandler");l(this,"logger");this.id=e,this.logger=s.logger,this.active=t.active,this.blocked=t.blocked,this.createTime=t.createTime,this.deviceId=t.deviceId,this.manifestId=t.manifestId,this.notes=t.notes,this.futureHandler=new rr(this)}updateModel(e){this.active=e.active,this.blocked=e.blocked,this.createTime=e.createTime,this.deviceId=e.deviceId,this.manifestId=e.manifestId,this.notes=e.notes}reset(){this.futureHandler.removeFuture()}get future(){return this.futureHandler.future}async install(e){if(!e)throw new Error("No tracker provided");return this.logger.info(`Installing update for manifest ${this.manifestId} from device ${this.deviceId}`),gl(this.manifestId,this.deviceId,e)}async init(){this.logger.debug(`initializing usb-update ${this.id}`)}async load(){this.logger.debug(`loading usb-update ${this.id}`)}};pl([qo()],Ys.prototype,"install",1);Ys=pl([C(ml)],Ys);const Ho=new ge({class:Ys,type:ml});var Bm=Object.defineProperty,Km=Object.getOwnPropertyDescriptor,dr=(e,t,s,r)=>{for(var o=r>1?void 0:r?Km(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&Bm(t,s,o),o};const yl="usb-update-container-model";let rt=class{constructor(e,t,s){l(this,"id");l(this,"disposer");l(this,"storageService");l(this,"_activeUpdate");l(this,"logger");l(this,"_models");this.id=e,this.logger=s.logger,this._models=new me({parentId:e})}getModel(e){return this._models.getModel(e)}get models(){return this._models}get data(){return this._models.data}addModel(e){this._models.addModel(e)}removeModel(e){this._models.removeModel(e)}get activeUpdate(){return this._activeUpdate}reset(){this.clearActiveUpdate()}clearActiveUpdate(){this._activeUpdate=void 0}updateActiveUpdate(e){this._activeUpdate=e}get isUsbInserted(){return this.storageService.isStorageInserted}get hasAvailableUpdates(){return this._models.data.length>0}async syncAvailableUpdates(){const e=await fl();Q(()=>{const t=e.map(s=>`${s.deviceId}-${s.manifestId}`);this._models.data.filter(s=>!t.includes(s.id)).forEach(s=>this.removeModel(s.id)),e.forEach(s=>{const r=`${s.deviceId}-${s.manifestId}`,o=Ho.instance(r).forceUpdate.options({...s,createTime:new Date(s.createTime)}).build();this.addModel(o)}),this.data.length===1?this.updateActiveUpdate(this.data[0]):this.clearActiveUpdate()})}usbInsertedEffect(){this.isUsbInserted?this.syncAvailableUpdates():(this._models.clear(),this.clearActiveUpdate())}async init(){this.logger.debug(`initializing usb-update-container container ${this.id}`)}unload(){var e;(e=this.disposer)==null||e.call(this)}async activate(){this.logger.debug(`activating usb-update-container container ${this.id}`),await this.syncAvailableUpdates()}async load(){this.logger.debug(`loading usb-update-container container ${this.id}`)}};dr([Ne({modelType:st.type})],rt.prototype,"storageService",2);dr([fe],rt.prototype,"_models",2);dr([ji({dependencies:e=>[e.isUsbInserted]})],rt.prototype,"usbInsertedEffect",1);rt=dr([C(yl)],rt);const Wt=new Ee({class:rt,type:yl});Wt.addRelatedModel(Ho);const Hm=()=>({...{[ct.type]:{class:sc},[Se.type]:{class:cc,singleton:!0},...Z.registration,...je.registration,...Qe.registration,...Us.registration,...ve.registration,[xo.type]:{class:exports.WsEventModel,singleton:!0},...zt.registration,...Ro.registration,...Cs.registration}}),Go=Hm(),Gm={models:Go,preloadModels:[]},zm=!0,bl=e=>()=>{const t=Go;return wa(Br)(Gt).model(Qe).model(st).model(Wt).model(Gs).model(Ls).model(Nt).model(Fs).model($o).model(Yt).model(tt).model(Fo).model(nr,zm).model(ss),Object.keys(t).forEach(s=>{const r=t[s];ba(Br)(s,r)}),{preload:D.model.preloadModel(e),model:D.model.register(e),companion:D.companion.register(e),legacy:D.model.registerLegacyModel(e)}},he={};he.core={models:bl(he)};he.preload=D.model.preloadModel(he);he.model=D.model.register(he);he.companion=D.companion.register(he);he.legacy=D.model.registerLegacyModel(he);const Br=he;class Vm{registerTroubleRankMapper(t){return $.propertyMapper.registerPropertyMapper(de.TroubleRank,t),this}registerTroubleRoleMapper(t){return $.propertyMapper.registerPropertyMapper(de.TroubleRole,t),this}registerTroubleColorMapper(t){return $.propertyMapper.registerPropertyMapper(de.TroubleColor,t),this}registerModelLoader(t,s){$.loader.registerLoader(t,s)}registerCanvasPatternLoader(t){$.loader.registerLoader(tt.loader,t)}}class ns{constructor(t){l(this,"futureHandler");this.futureHandler=new rr(t)}get future(){return this.futureHandler.future}get progress(){var t;return((t=this.future)==null?void 0:t.progress)||0}get status(){var t;return((t=this.future)==null?void 0:t.status)||"IDLE"}get isRunning(){return this.future?!this.future.endState:!1}get isCancelled(){var t;return((t=this.future)==null?void 0:t.status)==="CANCELLED"||!1}async cancelFuture(){this.future&&await this.future.cancelFuture()}}function Ym(e){const t=new ns(e);e.futureHandler=t.futureHandler,Object.defineProperty(e,"_futureMixin",{value:t,enumerable:!1,configurable:!1,writable:!1})}function wl(e){const t=new ns(e),s=e;s.futureHandler=t.futureHandler,Object.defineProperty(e,"_futureMixin",{value:t,enumerable:!1,configurable:!1,writable:!1}),Object.defineProperty(e,"future",{get(){return t.future},enumerable:!0,configurable:!0}),Object.defineProperty(e,"progress",{get(){return t.progress},enumerable:!0,configurable:!0}),Object.defineProperty(e,"status",{get(){return t.status},enumerable:!0,configurable:!0}),Object.defineProperty(e,"isRunning",{get(){return t.isRunning},enumerable:!0,configurable:!0}),Object.defineProperty(e,"isCancelled",{get(){return t.isCancelled},enumerable:!0,configurable:!0}),s.cancelFuture=async()=>t.cancelFuture()}function qm(){return function(e){const t=e;function s(...r){const o=t.apply(this,r)||this;return wl(o),o}return s.prototype=t.prototype,Object.setPrototypeOf(s,t),Object.getOwnPropertyNames(t).forEach(r=>{if(r!=="prototype"&&r!=="length"&&r!=="name"){const o=Object.getOwnPropertyDescriptor(t,r);o&&Object.defineProperty(s,r,o)}}),s}}function Wm(e){return new ns(e)}function Zm(e){let t;const s=()=>(t||(t=new ns(e())),t);return{get futureHandler(){return s().futureHandler},get future(){return s().future},get progress(){return s().progress},get status(){return s().status},get isRunning(){return s().isRunning},get isCancelled(){return s().isCancelled},async cancelFuture(){return s().cancelFuture()}}}function Jm(e){return e&&typeof e=="object"&&"futureHandler"in e&&"future"in e&&"_futureMixin"in e&&typeof e.cancelFuture=="function"}function Xm(e){const t=["future","progress","status","isRunning","isCancelled","futureHandler"],s={};for(const r of t){const o=Object.getOwnPropertyDescriptor(e,r);s[r]={exists:r in e,descriptor:o?{enumerable:o.enumerable,configurable:o.configurable,hasGetter:typeof o.get=="function",hasSetter:typeof o.set=="function"}:null,isObservable:e&&typeof e=="object"&&Object.getOwnPropertySymbols(e).some(n=>n.toString().includes("mobx")&&n.toString().includes(r))}}return s}class vl{constructor(t,s){l(this,"parent");l(this,"companion");this.companion=t,this.parent=s}getParent(){return this.parent}setupProxy(t={}){const{excludeProperties:s=[],includeLifecycle:r=!1}=t,o=r?[]:["init","load","unload","ready","dispose","destroy","onInit","onLoad","onUnload","onReady","onDispose","onDestroy"],n=["getDependencies","getChildren","update","toJSON","forceUpdate","makeAutoObservable","runInAction","transaction","observe","unobserve","intercept","spy","trace"],i=c=>c==="constructor"||c.startsWith("_")||c.startsWith("__")||o.includes(c)||n.includes(c)||s.includes(c)||c in this.companion,a=this.getAllParentProperties(i);for(const c of a)this.createProxyProperty(c)}getAllParentProperties(t){const s=new Set;Object.getOwnPropertyNames(this.parent).filter(o=>!t(o)).forEach(o=>s.add(o));let r=Object.getPrototypeOf(this.parent);for(;r&&r!==Object.prototype;)Object.getOwnPropertyNames(r).filter(o=>!t(o)).forEach(o=>s.add(o)),r=Object.getPrototypeOf(r);return Array.from(s)}createProxyProperty(t){try{const s=this.parent[t];typeof s=="function"?this.companion[t]=(...r)=>s.apply(this.parent,r):Object.defineProperty(this.companion,t,{get:()=>this.parent[t],set:r=>{this.parent[t]=r},enumerable:!0,configurable:!0})}catch(s){console.debug(`Skipping companion proxy for property ${t}:`,s)}}}function Qm(e,t,s={}){const r=new vl(e,t);return e.getParent=()=>r.getParent(),Object.defineProperty(e,"_companionMixin",{value:r,enumerable:!1,configurable:!1,writable:!1}),r.setupProxy(s),r}function Ml(e){return e&&typeof e=="object"&&"_companionMixin"in e&&typeof e.getParent=="function"}function El(e){return Ml(e)?e._companionMixin:null}function ey(e){const t=El(e);if(!t)return{error:"No companion mixin found"};const s=t.getParent(),r=Object.getOwnPropertyNames(e),o=Object.getOwnPropertyNames(s),n=r.filter(i=>o.includes(i)&&i!=="constructor"&&!i.startsWith("_"));return{parentType:s.constructor.name,companionType:e.constructor.name,proxiedProps:n,proxiedCount:n.length}}const ty=async(e,t)=>{const s=$o.instance(e).options({}).build(),r=t?`${t}-`:"";return await re(s),{getState:o=>s.data[`${r}${o}`],updateState:async(o,n)=>{await s.updateState(`${r}${o}`,n)},clean:async()=>{for(const o of s.data.keys)await s.updateState(`${r}${o}`,void 0)},unsubscribe:()=>{Le(s)}}},_l="kos:service:region",Il="regionId",sy=`${_l}-${Il}`,Tl=async e=>{const t=je.factory(sy)({path:_l,attribute:Il});await re(t),t.updateProperty(e)},zo="/kos-timer-event",Vo="/kos-timer-event/tick",Yo="defaultTimerEnd",It=p.createLogger({name:"timer-manager"}),ry=e=>e.updateProperty!==void 0;class Ol{constructor(t,s,r){l(this,"name");l(this,"timeout");l(this,"timer");l(this,"state","inactive");l(this,"decrementValue",1);l(this,"remainingTime");l(this,"timeoutActions",new Map);this.name=t;const o=typeof s=="number"?s:s.value||60;this.timeout=o,this.state="inactive",this.remainingTime=o,ry(s)&&j(()=>{p.info(`Updating config value timer ${t} with new timeout value ${s.value}`);const n=s.value||60;this.updateTimeout(n)}),this.addTimeoutAction({name:Yo}),r&&r.forEach(n=>{this.addTimeoutAction(n)})}get id(){return this.name}start(){if(this.state==="active"){It.debug(`Timer ${this.name} already started`);return}(this.state==="inactive"||this.state==="paused")&&(this.state="active",this.timer=setInterval(()=>this.updateTimer(),1e3))}pause(){this.timer&&(It.debug(`Pausing timer ${this.name}`),this.state="paused",clearInterval(this.timer))}restart(){this.pause(),this.remainingTime=this.timeout,this.start()}reset(){this.pause(),this.remainingTime=this.timeout,this.state="inactive"}updateTimeout(t){this.timeout=t,this.restart()}addTimeoutAction(t){const s=t.remainingTime??0;this.timeoutActions.has(s)||this.timeoutActions.set(s,[]);const r=t.name,o=this.timeoutActions.get(s).find(n=>n.name===r);o?o.action=t.action:this.timeoutActions.get(s).push(t)}removeTimeoutAction(t){for(const[s,r]of this.timeoutActions.entries()){const o=r.filter(n=>n.name!==t);o.length===0?this.timeoutActions.delete(s):this.timeoutActions.set(s,o)}}updateTimer(){if(this.remainingTime=Math.round((this.remainingTime-this.decrementValue)*100)/100,this.remainingTime<=0){this.state==="active"&&this.executeActions(0),this.pause();return}this.state==="active"&&this.executeActions(this.remainingTime)}executeActions(t){this.timeoutActions.has(t)&&this.timeoutActions.get(t).forEach(s=>{var r;It.debug(`Executing timer action ${s.name} at ${t}`),(r=s.action)==null||r.call(s,s.name,t),this.notifyTimeoutAction(s),s.singleUse&&(It.info(`${this.name} Removing single-use action ${s.name}`),this.removeTimeoutAction(s.name))}),this.notifyTick()}notifyTick(){U(`${Vo}/${this.name}`,{name:this.name,remainingTime:this.remainingTime})}notifyTimeoutAction(t){U(zo,{name:this.name,action:t.name,remainingTime:this.remainingTime})}}const Tt=new Map,ze=(e,t)=>{const s=Tt.get(e);if(!s){It.error(`Timer ${e} not found`);return}t(s)},Sl={createRelativeTimer(e,t,s){const r=new Date,o=Math.round((t.getTime()-r.getTime())/1e3);return this.createTimer(e,o,s)},createTimer(e,t=60,s){if(Tt.has(e))return Tt.get(e);const r=new Ol(e,t,s);return Tt.set(e,r),r},getTimer(e){return Tt.get(e)},clearTimer(e){ze(e,t=>t.pause())},restartTimer(e){ze(e,t=>t.restart())},resetTimer(e){ze(e,t=>t.reset())},addTimeoutAction(e,t){ze(e,s=>s.addTimeoutAction(t))},removeTimeoutAction(e,t){ze(e,s=>s.removeTimeoutAction(t))},startTimer(e){ze(e,t=>t.start())}},$l="kos:service:region:settings",Dl="timeZone",oy=`${$l}-${Dl}`,Kr=async e=>{const t=je.factory(oy)({path:$l,attribute:Dl});await re(t),t.updateProperty(e)},ny=e=>!e||!e.data;function qo(e={}){const{alias:t,namespace:s,abortController:r=!1}=e;return(o,n,i)=>{o[$t]=o[$t]||{};const a=i.value,c=async function(...d){const u=nt();p.debug(`Calling future service ${n} with tracker ${u}`);let h,g;r&&(h=new AbortController);const m=Fe.initiateFuture({tracker:u,id:mo});s&&(m.namespace=s),p.debug(`waiting for future ${m.id} to be ready`),await re(m),p.debug(`future ${m.id} is ready`),Q(()=>{p.debug(`Adding future ${m.id} to futureHandler`),this.futureHandler.addFuture(m,t)}),r&&h&&(g=j(()=>{(m.status==="CANCELLED"||m.endState===Oe.Canceled)&&(p.debug(`Future ${m.id} cancelled, aborting request`),h==null||h.abort())}),h.signal.addEventListener("abort",async()=>{if(m.status!=="CANCELLED"&&m.endState!==Oe.Canceled&&!m.endState){p.debug(`AbortController aborted, cancelling future ${m.id}`);try{await m.cancelFuture()}catch(w){p.error(`Failed to cancel future ${m.id}:`,w)}}},{once:!0}));const v=()=>{g&&(g(),g=void 0)};try{const w=[...d];if(r&&h){const K=w[w.length-1];K&&typeof K=="object"&&"aborted"in K?w[w.length-1]=h.signal:w.push(h.signal)}w.push(u);const E=await a.apply(this,w);p.debug(`received future response for ${u}`,E);const T=ny(E)?E:E==null?void 0:E.data;return T?(T.progress=1,p.debug("mapping future response to future model"),m.endState?p.debug(`future ${m.id} has already completed. Not updating the model`):Io(T,m)):this.futureHandler.removeFuture(t),v(),T}catch(w){if(v(),r&&(h!=null&&h.signal.aborted)){const E=new Error("Operation cancelled");throw p.debug(`Operation ${n} was cancelled`),E}throw p.error(w),w}};o[$t][n]={handler:c}}}const iy=({path:e})=>(t,s)=>{t[F]=t[F]||{},t[F][s]={modelType:zt.type,id:`${zt.type}-${e}`,options:{path:e},lifecycle:B.INIT}};function ay(e){const{path:t,attribute:s}=e;return(r,o)=>{r[F]=r[F]||{},r[F][o]={modelType:Ro.type,id:`${t}-${s}`,options:{path:t,attribute:s},lifecycle:B.INIT}}}const qe=p.createLogger({name:"services",group:"Services"}),cy=async(e,t)=>Cl(e,t,`${exports.BASE_URL}/api/server/login`),Cl=async(e,t,s=`${exports.BASE_URL}/api/login`)=>{const r=await exports.kosFetch(`${s}`,{method:"POST",destinationAddress:"",body:JSON.stringify({email:e,password:t})});if(!r.ok){const n=await r.json();throw Error(`${n==null?void 0:n.error}`)}return await r.json()},ly=async e=>Al(e,`${exports.BASE_URL}/api/server/startPasswordReset`,""),Al=async(e,t=`${exports.BASE_URL}/api/startPasswordReset`,s="server")=>{const r=await exports.kosFetch(`${t}?email=${e}`,{method:"POST",destinationAddress:s});if(!r.ok)throw Error(`There was a problem reseting config; returned status ${r.status}`);return await r.json()},dy=async(e,t)=>Rl(e,t,`${exports.BASE_URL}/api/server/resetPassword`),Rl=async(e,t,s=`${exports.BASE_URL}/api/resetPassword`)=>{qe.debug(`resetting password with token ${e} and password ${t.replace(/./g,"*")}`);const r=await exports.kosFetch(`${s}`,{method:"POST",destinationAddress:"",body:JSON.stringify({token:e,password:t})});if(qe.debug(`password reset returned status ${r.status}`),!r.ok){qe.error(`password reset failed with message ${r.statusText}`);const n=await r.json();throw Error(`${n==null?void 0:n.error}:There was a problem resetting the password.`)}return await r.json()},uy=async(e,t,s)=>Pl(e,t,s,`${exports.BASE_URL}/api/server/acceptInvite`),Pl=async(e,t,s,r=`${exports.BASE_URL}/api/server/acceptInvite`)=>{qe.debug(`accepting invite with token ${e} and password ${t.replace(/./g,"*")}`);const o=await exports.kosFetch(`${r}`,{method:"POST",destinationAddress:"",body:JSON.stringify({token:e,password:t,name:s})});if(qe.debug(`invitation accept returned status ${o.status}`),!o.ok){qe.error(`invite failed with message ${o.statusText}`);const i=await o.json();throw Error(`${i==null?void 0:i.error}:There was a problem accepting the invite.`)}return await o.json()};function hy(e,t,s,r){const o=e instanceof Promise?{promise:e,abortController:t,cancelFuture:s,future:r}:e,{promise:n,abortController:i,cancelFuture:a,future:c}=o,d=n;let u=0,h="PENDING",g=!0;const m=new Set;let v;return c&&typeof c=="object"&&(v=M.autorun(()=>{const w=c.progress||0,E=c.status||"PENDING",T=!c.endState;(w!==u||E!==h||T!==g)&&(u=w,h=E,g=T,m.forEach(K=>{try{K(u,h)}catch(H){console.warn("Progress callback error:",H)}}))})),n.finally(()=>{g=!1,i!=null&&i.signal.aborted||(h="COMPLETED",m.forEach(w=>{try{w(u,h)}catch(E){console.warn("Progress callback error:",E)}})),v&&v(),m.clear()}),d.cancel=async()=>{i&&!i.signal.aborted&&i.abort(),a&&await a(),g=!1,h="CANCELLED",m.forEach(w=>{try{w(u,h)}catch(E){console.warn("Progress callback error:",E)}}),v&&v()},d.getController=()=>i,d.isCancelled=()=>(i==null?void 0:i.signal.aborted)??!1,Object.defineProperty(d,"progress",{get:()=>u,enumerable:!0}),Object.defineProperty(d,"status",{get:()=>h,enumerable:!0}),Object.defineProperty(d,"isRunning",{get:()=>g,enumerable:!0}),d.onProgressUpdate=w=>(m.add(w),w(u,h),()=>m.delete(w)),d}const fy=Re.keyframes`
|
|
112
112
|
0% {
|
|
113
113
|
left: -90px;
|
|
114
114
|
color: #eee;
|
|
@@ -120,13 +120,13 @@ ${d}topics:${t}
|
|
|
120
120
|
left: 90px;
|
|
121
121
|
color: #eee;
|
|
122
122
|
}
|
|
123
|
-
`,
|
|
123
|
+
`,gy=Re.css`
|
|
124
124
|
font-size: 100px;
|
|
125
125
|
margin-top: -80px;
|
|
126
126
|
position: relative;
|
|
127
|
-
animation: ${
|
|
127
|
+
animation: ${fy} ease-in-out infinite alternate;
|
|
128
128
|
animation-duration: 1.2s;
|
|
129
|
-
`,
|
|
129
|
+
`,py=({children:e})=>jn.createPortal(e,document.body);function xl({message:e="Wait a moment while we load your app.",theme:t="light"}){return _.jsx(py,{children:_.jsxs(my,{theme:t,children:[e,_.jsx("div",{css:gy,children:"."})]})})}const my=Vr.div`
|
|
130
130
|
padding-inline: 20px;
|
|
131
131
|
width: 100%;
|
|
132
132
|
height: 100vh;
|
|
@@ -140,31 +140,31 @@ ${d}topics:${t}
|
|
|
140
140
|
left: 0;
|
|
141
141
|
color: ${({theme:e})=>e==="light"?"black":"white"};
|
|
142
142
|
z-index: 10000;
|
|
143
|
-
`;class
|
|
143
|
+
`;class Ll extends f.Component{constructor(t){super(t),this.state={error:null,errorInfo:null}}componentDidCatch(t,s){this.setState({error:t,errorInfo:s})}render(){return this.state.errorInfo?this.props.fallback||_.jsxs("div",{children:[_.jsx("h2",{children:"Something went wrong."}),_.jsxs("details",{style:{whiteSpace:"pre-wrap"},children:[this.state.error&&this.state.error.toString(),_.jsx("br",{}),this.state.errorInfo.componentStack]})]}):this.props.children}}const yy={normal:"#B5F7F6",warn:"#F3D78A",error:"#FC8486"},by=({value:e=0,title:t,status:s="normal",subtitle:r})=>{const o=Re.css`
|
|
144
144
|
display: flex;
|
|
145
145
|
flex-direction: column;
|
|
146
|
-
`,n=
|
|
146
|
+
`,n=Re.css`
|
|
147
147
|
position: relative;
|
|
148
148
|
height: 18px;
|
|
149
149
|
width: 100%;
|
|
150
150
|
background-color: #ddd;
|
|
151
151
|
border-radius: 5px;
|
|
152
152
|
overflow: hidden;
|
|
153
|
-
`,i=
|
|
153
|
+
`,i=Re.css`
|
|
154
154
|
position: absolute;
|
|
155
155
|
top: 50%; /* position the top edge of the element at the middle of the parent */
|
|
156
156
|
left: 50%; /* position the left edge of the element at the middle of the parent */
|
|
157
157
|
z-index: 5;
|
|
158
158
|
transform: translate(-50%, -50%);
|
|
159
159
|
font-size: smaller;
|
|
160
|
-
`,
|
|
160
|
+
`,a=Re.css`
|
|
161
161
|
width: ${e}%;
|
|
162
162
|
height: 35px;
|
|
163
|
-
background-color: ${
|
|
163
|
+
background-color: ${yy[s]};
|
|
164
164
|
text-align: center;
|
|
165
165
|
line-height: 32px;
|
|
166
166
|
color: black;
|
|
167
|
-
`,
|
|
167
|
+
`,c=Re.css`
|
|
168
168
|
animation: indeterminateAnimation 1s infinite linear;
|
|
169
169
|
transform-origin: 0% 50%;
|
|
170
170
|
@keyframes indeterminateAnimation {
|
|
@@ -178,7 +178,7 @@ ${d}topics:${t}
|
|
|
178
178
|
transform: translateX(100%) scaleX(0.5);
|
|
179
179
|
}
|
|
180
180
|
}
|
|
181
|
-
`;return
|
|
181
|
+
`;return _.jsxs("div",{css:o,children:[_.jsxs("div",{css:n,children:[_.jsx("div",{css:i,children:t}),_.jsx("div",{css:[a,e<0?c:""]})]}),_.jsx("div",{children:r})]})},wy={setModel:()=>!1},ur=f.createContext(wy),vy=()=>{const e=f.useContext(ur);if(e==null)throw new Error("useModels must be used within a KosModelProvider");return e.model},Fl=({children:e})=>{const[t,s]=f.useState(),r=f.useCallback(o=>(s(o),!0),[s]);return _.jsx(ur.Provider,{value:{model:t,setModel:r},children:e})},kl=p.createLogger({name:"kos-model-hierarchy-context"}),My={models:[],addModel:()=>{kl.debug("Default implementation being used. Do Nothing.")}},hr=f.createContext(My),Ey=({children:e})=>{const[t,s]=f.useState([]),r=f.useCallback(o=>{t.includes(o)||(kl.debug("adding to hierarchy context",o.id),s(n=>[...n,o]))},[t]);return _.jsx(hr.Provider,{value:{models:t,addModel:r},children:e})},_y=()=>!0,Nl=e=>{const t=f.useContext(hr);if(!t)throw new Error("useContextModelHierarchy must be used within a KosModelCollectionProvider");const s=(e==null?void 0:e.filter)||_y;return f.useMemo(()=>t.models.filter(s),[t.models,s])},Iy=e=>Nl({filter:s=>{const r=Ue(s.id);return(r==null?void 0:r.type)===e}})[0],Ty=p.createLogger({name:"kos-model-loader"}),Oy=()=>_.jsx("div",{}),Ul=({fallback:e,children:t,...s})=>_.jsx(Fl,{children:_.jsx(Ll,{fallback:e,children:_.jsx(f.Suspense,{children:_.jsx(jl,{...s,children:t})})})}),jl=e=>{const[t,s]=f.useState(),[r,o]=f.useState(!1),{setModel:n}=f.useContext(ur),i=f.useContext(hr);if(f.useEffect(()=>{e.model&&(s(e.model),n(e.model),o(!0),i&&i.addModel(e.model))},[i,e.model,n]),e.error)throw Ty.error(e.error),new Error(e.error);const a=e.loading||_.jsx(Oy,{});return _.jsx(_.Fragment,{children:t&&r?e.children:a})},Es={header:{title:"Model",createLabel:"Create new Model",deleteLabel:"Delete"},createModal:{okText:"OK",cancelText:"Cancel",title:"Create New Model"}},Bl=f.createContext(Es),Sy=({translations:e=Es,children:t})=>{const s={header:{...Es.header,...e.header},createModal:{...Es.createModal,...e.createModal}};return _.jsx(Bl.Provider,{value:s,children:t})};function $y(e,t){const s=I.create(e,!1,t),r=s.whenReady().then(()=>s);return so(r)}const Kl=f.createContext(void 0),Dy=(e={models:{},preloadModels:[]},t)=>{const s=$y(e,t),r=({children:o})=>{const n=s.read(),[i,a]=f.useState(n.isOnline);return f.useEffect(()=>{const c=j(()=>{a(n.isOnline)});return()=>{c()}},[n]),_.jsx(Kl.Provider,{value:{kosCore:n,online:i},children:o})};return{KosCoreContextProvider:Yr.observer(r)}},Hl=()=>{const e=f.useContext(Kl);if(e===void 0)throw new Error("useKosCore must be used within a KosCoreContextProvider");return e},Cy=8,Ay=(e=0)=>new Promise(t=>{setTimeout(()=>{t(!0)},2**e*10)}),Pe=new Map;function Ry(e,t){if(Pe.has(e)){const s=Pe.get(e);if(s.status==="finished"){const r=I.getInstance().modelManager.getModelById(e);return{kosModel:r,model:r==null?void 0:r.modelData}}else throw s.promise}else{const s=t().then(()=>{Pe.set(e,{status:"finished",key:e})},o=>{throw Pe.set(e,{status:"error",error:o}),o}),r={status:"pending",promise:s};throw Pe.set(e,r),s}}function Py(e,t){return Ry(e,t)}async function xy(e,t){const{modelId:s,factory:r,modelType:o,options:n,activate:i}=t;let a=0;await e.whenReady();let c;if(n){const u=typeof o=="string"?e.modelManager.getModelFactory(o):r;if(!u)throw Error("No Factory Specified. Cannot create a new instance");c=u.build(s,n)}const d=e.modelManager.getModelById(s);if(!d){if(a>Cy)throw Error(`KOS Model ${s} has not been found`);await Ay(a),a=a+1}return await(d==null?void 0:d.whenReady()),d?(c=d.modelData,{kosModel:d,model:c}):{kosModel:void 0,model:void 0}}const V=e=>{const{modelId:t,modelType:s,activate:r,destroyOnUnmount:o}=e,n=Hl(),[i,a]=f.useState(!1),[c,d]=f.useState(),{kosModel:u,model:h}=Py(t||s||"",()=>xy(n.kosCore,e));return f.useEffect(()=>{async function g(){try{return await n.kosCore.whenReady(),r&&await(u==null?void 0:u.fsm.transitionTo(A.GO_ACTIVE,b.ACTIVE)),a(!0),u}catch(v){d(v.message)}}let m;return n.kosCore&&t&&g().then(v=>{m=j(()=>{const w=(v==null?void 0:v.status)===b.READY;a(w)})}).catch(v=>{console.error(v)}),()=>{if(r){if(h!=null&&h.id){const v=n.kosCore.modelManager.getModelById(h.id);v==null||v.fsm.transitionTo(A.GO_INACTIVE,b.INACTIVE).then(()=>{if(o){const w=h.id;Le(h).then(()=>{Pe.delete(w),m==null||m()})}})}}else o&&h&&Le(h).then(()=>{Pe.delete(t),m==null||m()})}},[r,o,n.kosCore,u,h,t]),{model:h,ready:i,error:c,status:{model:h,ready:i,error:c},KosModelLoader:Ul}},Wo=()=>{const e=Cs.type;return V({modelId:e,modelType:Cs.type,options:{}})},Zo=f.createContext(void 0),Ly=({children:e})=>{const{model:t,ready:s}=Wo(),r=f.useMemo(()=>s&&t?{model:t}:{},[s,t]);return _.jsx(Zo.Provider,{value:r,children:e})},Fy=()=>{const e=f.useContext(Zo);if(!e)throw new Error("useKosTimeContext must be used within a KosTimeProvider");return e},Jo=()=>{const e=Fs.type;return V({modelId:e,modelType:Fs.type,options:{}})};function ky(e){return()=>t=>{const{model:s,status:r,KosModelLoader:o}=Jo();return _.jsx(o,{...r,children:_.jsx(e,{...t,softwareInfo:s})})}}const Xo=f.createContext(void 0),Ny=({children:e})=>{const{model:t,ready:s}=Jo(),r=f.useMemo(()=>s&&t?{model:t}:{},[s,t]);return _.jsx(Xo.Provider,{value:r,children:e})},Uy=()=>{const e=f.useContext(Xo);if(!e)throw new Error("useSoftwareInfoContext must be used within a SoftwareInfoProvider");return e},Gl=new Aa,zl=f.createContext(Gl);function jy({children:e}){return _.jsx(zl.Provider,{value:Gl,children:e})}const Qo=f.createContext(void 0),By=()=>{const e=window.location.origin,t=ie();return(t==null?void 0:t.host)||e},Ky=({children:e,appContext:t,locale:s="en",resolver:r,rootUrl:o,descriptorResolver:n})=>{const[i,a]=f.useState(!1),[c,d]=f.useState(),[u,h]=f.useState(),g=o||By(),m=f.useMemo(()=>t??"app/system",[t]);f.useEffect(()=>{async function E(){const K=(Array.isArray(m)?m:[m]).map(G=>(n||Gc(G))()),R=(await Promise.allSettled(K)).map(G=>{if(G.status==="rejected"){p.warn("Failed to load localization descriptor",G.reason);return}return G.value}).filter(G=>!!G).reverse().reduce((G,k)=>{const Y=k.path;return Object.keys(k.namespaces).forEach(_e=>{const dt=k.namespaces[_e];dt.basePath=Y}),{...G,namespaces:{...G.namespaces,...k.namespaces}}},{});d(R)}E()},[m,n]),f.useEffect(()=>{async function E(){if(c){const T=g,{translations:K}=await Wc.init({lang:s,descriptor:c,defaultNamespace:"common",resolver:r,rootUrl:T});h(K),a(!0)}}E()},[s,c,r,g]);const v=f.useMemo(()=>i?{setLocale:E=>{u&&(u.currentLocale=E)}}:{setLocale:()=>{throw new Error("Translations not ready")}},[i,u]),w=i?e:null;return _.jsx(Qo.Provider,{value:v,children:w})},Hy=()=>{const e=f.useContext(Qo);if(!e)throw new Error("useTranslationContainerContext must be used within a TranslationContainerProvider");return e},Gy=()=>{const e=tt.type;return V({modelId:e,modelType:tt.type,options:{}})};function zy(e){return t=>{const{model:s,status:r,KosModelLoader:o}=Gy();return _.jsx(o,{...r,children:_.jsx(e,{...t,canvasDispatcher:s})})}}const Vy=(e,t,s)=>{const r=atob(e),o=new Uint8ClampedArray(t*s*4);for(let n=0,i=0;n<r.length&&i<o.length;n+=3,i+=4)o[i]=r.charCodeAt(n),o[i+1]=r.charCodeAt(n+1),o[i+2]=r.charCodeAt(n+2),o[i+3]=255;return o},Yy=(e,t,s)=>{const r=new Uint8ClampedArray(t*s*4);for(let o=0;o<e.length;o++){const n=e.charCodeAt(o),i=(n>>5&7)*255/7,a=(n>>2&7)*255/7,c=(n&3)*255/3,d=o*4;r[d]=i,r[d+1]=a,r[d+2]=c,r[d+3]=255}return r};function qy({ctx:e,format:t,dataString:s,width:r,height:o,pixelSize:n}){const i=t==="base64"?Vy(s,r,o):Yy(s,r,o),a=new ImageData(i,r,o),c=document.createElement("canvas");c.width=r,c.height=o;const d=c.getContext("2d");d==null||d.putImageData(a,0,0),e.imageSmoothingEnabled=!1,e.clearRect(0,0,r*n,o*n),e.drawImage(c,0,0,r*n,o*n)}const Wy=p.createLogger({name:"canvas-streamer"});Wy.debug("main-view component loaded");const Ir=10,Vl=Yr.observer(({canvasDispatcher:e,height:t=30,width:s=50,defaultFps:r=10,showPreview:o=!1,name:n,apiPath:i="/api/system/canvas"})=>{const a=f.useRef(null),[c,d]=f.useState();f.useEffect(()=>{const h=e.addNamedEndpoint(n,{apiPath:i,fps:r,width:s,height:t,id:n});d(h)},[e]);const u=f.useCallback(h=>{if(a.current&&o){const g=a.current.getContext("2d");g&&qy({ctx:g,format:"base64",dataString:h,height:t,width:s,pixelSize:Ir})}},[s,t,o]);return f.useEffect(()=>{c&&(c.onFrame=u,c.width=s,c.height=t,c.fps=r)},[c,u,s,t,r]),o&&jn.createPortal(_.jsx(Jy,{children:_.jsx(Xy,{children:_.jsx("canvas",{ref:a,width:s*Ir,height:t*Ir,style:{border:"1px solid black"}})})}),document.body)}),Zy=zy(Vl),Jy=Vr.div`
|
|
182
182
|
display: flex;
|
|
183
183
|
flex-direction: column;
|
|
184
184
|
gap: 8px;
|
|
@@ -186,9 +186,9 @@ ${d}topics:${t}
|
|
|
186
186
|
width: 100%;
|
|
187
187
|
justify-content: space-between;
|
|
188
188
|
align-items: center;
|
|
189
|
-
`,
|
|
189
|
+
`,Xy=Vr.div`
|
|
190
190
|
display: flex;
|
|
191
191
|
flex-direction: column;
|
|
192
192
|
align-items: center;
|
|
193
|
-
`,yl=()=>{const e=xs.type;return B({modelId:e,modelType:xs.type,options:{}})};function qp(e){return t=>{const{model:s,status:o,KosModelLoader:r}=yl();return M.jsx(r,{...o,children:M.jsx(e,{...t,device:s})})}}function Wp(e,t,s){const o=new Promise(r=>{E.getInstance().whenReady().then(()=>{const{model:n}=E.getInstance().modelManager.createModelInstance(e,t??e,s);return n.whenReady().then(()=>{r(n.modelData)})})});return Vo(o)}function Zp(e){return t=>{const{model:s,status:o,KosModelLoader:r}=Fr();return M.jsx(r,{...o,children:M.jsx(e,{...t,kosTime:s})})}}const bl=()=>{const e=jt.type;return B({modelId:e,modelType:jt.type,options:{}})};function Jp(e){return t=>{const{model:s,status:o,KosModelLoader:r}=bl();return M.jsx(r,{...o,children:M.jsx(e,{...t,networkInterfaceContainer:s})})}}const vl=()=>{const e=$s.type;return B({modelId:e,modelType:$s.type,options:{}})};function Xp(e){return t=>{const{model:s,status:o,KosModelLoader:r}=vl();return M.jsx(r,{...o,children:M.jsx(e,{...t,oTA:s})})}}function Qp(e,t){g.useEffect(()=>{function s(r){e.current&&!e.current.contains(r.target)&&t()}function o(r){r.key==="Escape"&&t()}return document.addEventListener("mousedown",s),document.addEventListener("keydown",o,!1),()=>{document.removeEventListener("mousedown",s),document.removeEventListener("keydown",o,!1)}},[e,t])}function ey(e){const t=g.useRef(null),s=e.onAlert;return Qp(t,s),M.jsx("div",{ref:t,style:{width:"100%"},children:e.children})}const ty=e=>{var d;const{stateProp:t}=e,[s,o]=g.useState((d=e.stateProp)==null?void 0:d.value),[r,n]=g.useState(!1),[i,c]=g.useState(void 0);return g.useEffect(()=>{async function u(h){try{h&&(await J(h),n(!0))}catch(f){c(f.message)}}u(t)},[t]),g.useEffect(()=>{const u=N(()=>{t&&r&&o(t.value)});return()=>{u()}},[r,t]),[s,{ready:r,error:i}]},wl=()=>{const[e,t]=g.useState(!1),[s,o]=g.useState([]),r=Je.type,n=B({modelId:r,modelType:Je.type,options:{}});return g.useEffect(()=>{const i=N(()=>{var c,l;t(((c=n.model)==null?void 0:c.isStorageInserted)??!1),o(((l=n.model)==null?void 0:l.data)??[])});return()=>{i()}},[n.model]),{...n,inserted:e,devices:s}};function sy(e){return t=>{const{model:s,status:o,KosModelLoader:r}=wl();return M.jsx(r,{...o,children:M.jsx(e,{...t,storageDeviceContainer:s})})}}const po=m.createLogger({name:"use-timer"}),oy=({timerName:e,onTimerExpired:t,onTimerTick:s,timerEventActions:o,autoStart:r})=>{const n=Jc.getTimer(e);g.useEffect(()=>{if(!n){console.warn(`Timer with name ${e} does not exist.`);return}const d=U(Pr,u=>{const{name:h,action:f,remainingTime:v}=u==null?void 0:u.body;h===e&&(f===xr?t({name:h,action:f,remainingTime:v,timer:n}):o!=null&&o[f]&&o[f]({name:h,action:f,remainingTime:v,timer:n}))});return r&&n.start(),()=>{d.unsubscribe()}},[r,t,o,e,n]),g.useEffect(()=>{if(!n||!s)return;const d=`${Lr}/${e}`,u=U(d,h=>{const{name:f,remainingTime:v}=h==null?void 0:h.body;f===e&&s({name:f,remainingTime:v,timer:n})});return()=>{u.unsubscribe()}},[s,e,n]);const i=g.useCallback(()=>{n?n.start():po.warn(`Timer with name ${e} does not exist.`)},[n,e]),c=g.useCallback(()=>{n?n.reset():po.warn(`Timer with name ${e} does not exist.`)},[n,e]),l=g.useCallback(()=>{n?n.pause():po.warn(`Timer with name ${e} does not exist.`)},[n,e]);return{timer:n,start:i,reset:c,pause:l}},ry=e=>{const t=/[\\^$.*+?()[\]{}|]/g;return RegExp(t.source).test(e)?e.replace(t,"\\$&"):e},ny=e=>e instanceof RegExp,iy=e=>typeof e=="string",ay=(e,t,s)=>{if(e===""||t==="")return e;let o=t;ny(o)||(o=new RegExp("("+ry(o)+")","gi"));const r=e.split(o);for(let n=1,i=r.length;n<i;n+=2)r[n]=s(r[n],n);return r},Ml=(e,t,s)=>{let o=e;return Array.isArray(o)||(o=[o]),o.flatMap(r=>iy(r)?ay(r,t,s):r)};function cy(e,t){let s=e;return Object.entries(t).forEach(([o,r])=>{const n=new RegExp(`<${o}>(.*?)</${o}>|<${o}/>`,"g");s=Ml(s,n,(i,c)=>r.type==="br"?M.jsx("br",{}):g.cloneElement(r,{key:`${o}-${c}`},i))}),s}const ly=e=>{const{i18nKey:t,t:s,defaults:o,components:r,values:n={},context:i}=e,c=s(t,{defaultValue:o,data:n,context:i,returnObjects:!0}),l=cy(c,r||{});return M.jsx("span",{className:e.className,children:l})},Be=new Map;function dy(e,t){if(Be.has(e)){const s=Be.get(e);if(s.status==="finished")return s.result;throw s.promise}else{const s=t().then(r=>{Be.set(e,{status:"finished",result:r})},r=>{throw Be.set(e,{status:"error",error:r}),r}),o={status:"pending",promise:s};throw Be.set(e,o),s}}function xo(e,t){return dy(e,t)}const uy=async()=>{const e=await Gi(fe.type);return await J(e.model),e.model},hy=async(e,t,s)=>{const o=e.resolveNamespace(t);await J(o);for(const r of s){const n=e.resolveNamespace(r);await J(n),Be.set(r,{status:"finished",result:n})}return o},gy=(e,t)=>{const s=[e].flat(),[o,...r]=s,n=xo(fe.type,uy),i=s.join("__"),c=xo(i,()=>hy(n,o,r)),l=g.useMemo(()=>({exists:u=>{const h=t!=null&&t.keyPrefix?`${t.keyPrefix}.${u}`:u;return c?c.exists(h):!1}}),[t==null?void 0:t.keyPrefix,c]);return{t:g.useCallback((u,h)=>{const f=t!=null&&t.keyPrefix?`${t.keyPrefix}.${u}`:u;return c?c.resolveKey(f,h):(m.debug(`Translation model ${e} not ready for key: ${f}`),f)},[t==null?void 0:t.keyPrefix,e,c]),i18n:l}},_l=()=>{const e=fe.type;return B({modelId:e,modelType:fe.type,options:{}})};function fy(e){return t=>{const{model:s,status:o,KosModelLoader:r}=_l();return M.jsx(r,{...o,children:M.jsx(e,{...t,translationContainer:s})})}}const my=e=>B({modelId:e,modelType:Ft.type}),Kr=()=>B({modelId:qe.type,modelType:qe.type,options:{}}),py=({troubleType:e,condition:t})=>{const{model:s}=Kr(),[o,r]=g.useState(!1),[n,i]=g.useState([]),c=g.useCallback(()=>{var l,d;return n.length>0&&((l=n[0])!=null&&l.resolvable)?(d=n[0])==null?void 0:d.resolve():Promise.resolve(void 0)},[n]);return g.useEffect(()=>N(()=>{const d=(e?s==null?void 0:s.troubles.getIndexByKey("byType",e):s==null?void 0:s.troubles.data)||[],u=t?d.filter(t):d;r(u.length>0),i(u)}),[t,s,e]),[o,c,n.length>0?n[0]:void 0,n]};function yy(e){return t=>{const{model:s,status:o,KosModelLoader:r}=Kr();return M.jsx(r,{...o,children:M.jsx(e,{...t,troubleContainer:s})})}}const El=()=>{const e=Kt.type,t=B({modelId:e,modelType:Kt.type,options:{},activate:!0,destroyOnUnmount:!0}),[s,o]=g.useState(!1),[r,n]=g.useState(!1),[i,c]=g.useState([]);return g.useEffect(()=>{const l=N(()=>{var d,u,h;o(((d=t.model)==null?void 0:d.isUsbInserted)??!1),n(((u=t.model)==null?void 0:u.hasAvailableUpdates)??!1),c(((h=t.model)==null?void 0:h.data)??[])});return()=>{l()}},[t.model]),{...t,inserted:s,updateAvailable:r,updates:i}};function by(e){return t=>{const{model:s,status:o,KosModelLoader:r}=El();return M.jsx(r,{...o,children:M.jsx(e,{...t,usbUpdateContainer:s})})}}const vy=({path:e,propKey:t})=>{const{status:s}=B({modelType:Ct.type,modelId:e,options:{path:e}}),[o,r]=g.useState(!1),[n,i]=g.useState(),[c,l]=g.useState(""),[d,u]=g.useState(),h=f=>{n&&t&&n.updateProperty(t,f)};return g.useEffect(()=>{var f;s.model&&i(s.model),s.model&&t&&((f=s.model)!=null&&f.props.has(t)?l(s.model.props[t]):u(`property ${t} not found`)),s.ready&&r(s.ready)},[s.ready,s.model,t]),g.useEffect(()=>{t&&w.autorun(()=>{const f=n==null?void 0:n.props[t];l(f||"")})},[n,t]),{config:n,ready:o,value:c,error:d,updateValue:h}},wy=(e,t)=>{switch(t.type){case"UPDATE":return t.payload;default:return e}},Il=({configProperty:e,optionsTransformer:t})=>{const[s,o]=g.useState(!1),[r,n]=g.useState(""),[i,c]=g.useReducer(wy,{value:String(e==null?void 0:e.value),displayValue:e==null?void 0:e.displayValue,significantValue:e==null?void 0:e.significantValue,unit:e==null?void 0:e.unit,options:e==null?void 0:e.options,mappedOptions:[],updateProperty:e==null?void 0:e.updateProperty,displayOptions:e==null?void 0:e.displayOptions}),l=g.useCallback(d=>{var h;let u="factory";typeof d=="string"?u=d:(h=d==null?void 0:d.target)!=null&&h.value&&(u=d.target.value),u&&(e==null||e.updateProperty(u))},[e]);return g.useEffect(()=>{async function d(u){try{u&&(await J(u),o(!0))}catch(h){n(h.message)}}d(e)},[e]),g.useEffect(()=>{const d=N(()=>{if(e&&s){let u=[];t&&(u=t(e.options)),c({type:"UPDATE",payload:{value:String(e.value),displayValue:e.displayValue,significantValue:e.significantValue,unit:e.unit,options:e.options,mappedOptions:u,updateProperty:e.updateProperty,displayOptions:e==null?void 0:e.displayOptions}})}});return()=>{d()}},[e,t,s]),{...i,configSelectProps:{onChange:l,value:i.value,options:t?i.mappedOptions||[]:i.options||[]},ready:s,error:r}};function My(e,t){const s=t??new Date().getFullYear(),o=[31,28,31,30,31,30,31,31,30,31,30,31];return e===1&&(s%4===0&&s%100!==0||s%400===0)?29:o[e]??0}function _y(e,t){return new Date(e,t,0).getDate()}function Tl(e,t){const s=My(t,e),o=[];for(let r=1;r<=s;r++)o.push(r);return o}function $l(){return[...Array(12).keys()].map(t=>new Date(0,t).getMonth())}function Ol(e=[2018,2028]){const t=[];for(let s=e[0];s<=e[1];s++)t.push(s);return t}function Sl(e,t=[2018,2028]){const s=Ol(t);return e==="long"?s:s.map(o=>Number(o.toString().substring(2)))}function Hr(e="numeric",t="en-US"){const s=new Intl.DateTimeFormat(t,{month:e,timeZone:"UTC"}).format;return[...Array(12).keys()].map(o=>s(new Date(Date.UTC(0,o,1))))}function Ey({locale:e="en-US",year:t,month:s,day:o,formatOptions:r={weekday:"long",year:"numeric",month:"long",day:"numeric"},displayOrder:n}){const i=s-1,c=new Date(t,i,o),l=new Intl.DateTimeFormat(e,{month:r.month}).format(c),d=new Intl.DateTimeFormat(e,{year:r.year}).format(c),u=new Intl.DateTimeFormat(e,{day:r.day}).format(c);return n?n=="MMDDYY"?`${l} ${u} ${d}`:n==="DDMMYY"?`${u} ${l} ${d}`:n==="YYMMDD"?`${d} ${l} ${u}`:`${d} ${u} ${l}`:new Intl.DateTimeFormat(e,r).format(c)}function oe(e){return e.toString().length===2?new Date(Date.parse(`01 Jan 20${e}`)).getFullYear():e}function Iy(e){return typeof e=="string"?new Date(Date.parse(`01 ${e.substring(0,3)} 2023`)).getMonth()+1:e}function Dl(e,t,s){const o=oe(t),r=new Date(o,e,1).getDay(),n=new Date(o,e+1,0).getDate();return[...Array(42).keys()].map(c=>c<r||c>n+r-1?{label:"",value:0,disabled:!0}:s[c-r])}function vt(e,t,s){const o=t-1,r=new Date(e,o,s);return new Date(r).getMonth()===o&&new Date(r).getDate()===s}function wt(e,t){return new Date(e,t,0).getDate()}function Al(e="en-US",t="short"){const s=new Intl.DateTimeFormat(e,{weekday:t}).format;return[...Array(7).keys()].map(o=>s(new Date(Date.UTC(2021,5,o))))}function Cl({locale:e="en-US",year:t=new Date().getFullYear(),month:s=new Date().getMonth(),yearRange:o=[2018,2028],daysOfWeekFilter:r=[],formatOptions:{yearFormat:n="long",monthFormat:i="long",dayFormat:c="short"}={}}){const l=Gr(n,o),d=Rl(n,o,e),u=Pl(i,e),h=Ll(i,e),f=Vr(t,s),v=xl(t,s,e,r),b=Nl(s,t,v),_=kl(e,c);return{daysArray:f,monthsArray:u,yearsArray:l,yearsOptionsArray:d,monthsOptionsArray:h,daysOptionsArray:v,calendarDayArray:b,dayNamesArray:_}}function Gr(e="long",t=[2018,2028]){return g.useMemo(()=>Sl(e,t),[e,t])}function Rl(e="long",t=[2018,2028],s="en-US"){const o=Gr(e,t);return g.useMemo(()=>o.map(n=>({label:n.toLocaleString(s).replace(",",""),value:n})),[s,o])}function Pl(e,t="en-US"){return g.useMemo(()=>Hr(e,t),[e,t])}function Ll(e,t="en-US"){const s=g.useMemo(()=>$l(),[]),o=g.useMemo(()=>Hr(e,t),[e,t]);return g.useMemo(()=>[...Array(12).keys()].map(n=>({label:o[n],value:Number(s[n])})),[o,s])}function Vr(e,t){const s=oe(e);return g.useMemo(()=>Tl(s,t),[t,s])}const Ty=(e,t,s,o=[])=>{const r=new Date(e,t,s).getDay();return o.length>0&&o.includes(r)};function xl(e,t,s="en-US",o=[]){const r=Vr(e,t);return g.useMemo(()=>r.map(i=>({label:i.toLocaleString(s),value:i,disabled:Ty(e,t,i,o)})),[o,s,t,r,e])}function kl(e="en-US",t="short"){return g.useMemo(()=>Al(e,t),[e,t])}function Fl({year:e=new Date().getFullYear(),month:t=new Date().getMonth(),day:s=new Date().getDate(),formatString:o}){const r=t,n=new Date(e,r,s);return{formattedDate:ye.format(n,o)}}function Nl(e,t,s){return g.useMemo(()=>Dl(e,t,s),[e,t,s])}var Ul=(e=>(e.MMDDYY="MMDDYY",e.DDMMYY="DDMMYY",e.YYMMDD="YYMMDD",e.YYDDMM="YYDDMM",e))(Ul||{});function $y({locale:e="en-US",date:{year:t=new Date().getFullYear(),month:s=new Date().getMonth(),day:o=new Date().getDate()}={year:new Date().getFullYear(),month:new Date().getMonth(),day:new Date().getDate()},formatOptions:{yearFormat:r="long",monthFormat:n="long",dayFormat:i="short",formatString:c="yyyy/MM/dd"}={},filterOptions:{yearsRange:l=[2018,2028],daysOfWeekFilter:d=[]}={}}){const[u,h]=g.useState(t),[f,v]=g.useState(l),[b,_]=g.useState(s),[I,C]=g.useState(o);g.useEffect(()=>{h(t)},[t]),g.useEffect(()=>{_(s)},[s]),g.useEffect(()=>{C(o)},[o]);const{yearsArray:se,yearsOptionsArray:Me,monthsArray:nt,monthsOptionsArray:eo,daysArray:X,daysOptionsArray:_e,calendarDayArray:to,dayNamesArray:so}=Cl({locale:e,year:u,yearRange:f,month:b,formatOptions:{yearFormat:r,monthFormat:n,dayFormat:i},daysOfWeekFilter:d}),{formattedDate:oo}=Fl({year:u,month:b,day:I,formatString:c});return{dateActions:{setYear:h,setYearRange:v,setMonth:_,setDay:C,nextMonth:()=>{const K=b<11?oe(u):oe(u+1),W=b<11?b+1:0;if(!vt(K,W,I)){const Ee=wt(K,W);C(Ee)}W===0&&h(K),_(W)},previousMonth:()=>{const K=oe(b===0?u-1:u),W=b===0?11:b-1;if(!vt(K,W,I)){const Ee=wt(K,W);C(Ee)}W===11&&h(K),_(W)},nextYear:()=>{const K=u<f[1]?u+1:f[0],W=oe(K);if(vt(W,b,I))h(K);else{const Ee=wt(oe(u+1),b);C(Ee),h(K)}},previousYear:()=>{const K=u>f[0]?u-1:f[0],W=oe(K);if(vt(W,b,I))h(K);else{const Ee=wt(oe(u-1),b);C(Ee),h(K)}}},dateState:{year:u,yearRange:f,month:b,day:I,yearsArray:se,yearsOptionsArray:Me,monthsArray:nt,monthsOptionsArray:eo,daysArray:X,daysOptionsArray:_e,calendarDayNames:so,calendarDayArray:to,formattedDate:oo}}}function jl({date:e=new Date,dateFormat:t,timeFormat:s,options:o={}}){const[r,n]=g.useState("Formatting Time..."),[i,c]=g.useState("Formatting Date..."),l=!!o.ignoreDateFormat,{model:d,ready:u}=B({modelId:G.type,modelType:G.type,options:{}}),h=typeof e=="string"?ye.parseISO(e):e;return g.useEffect(()=>{l?c(""):t?c(ye.format(h,t)):u&&c(ye.format(h,d!=null&&d.selectedDateFormat?d==null?void 0:d.selectedDateFormat:""))},[l,e,t,h,d,u]),g.useEffect(()=>{s?n(ye.format(h,s)):u&&n(ye.format(h,d!=null&&d.selectedTimeFormat?d==null?void 0:d.selectedTimeFormat:""))},[e,s,h,d,u]),{formattedDate:i,formattedTime:r}}const Bl=({secondsFromMidnight:e=0})=>{const[t,s]=g.useState(0),[o,r]=g.useState(0),[n,i]=g.useState(0),[c,l]=g.useState(new Date),{formattedTime:d}=jl({date:c,options:{ignoreDateFormat:!0}});return g.useEffect(()=>{const u=Number(e),h=Math.floor(u/3600),f=Math.floor(u%3600/60),v=u%60;s(h),r(f),i(v);const b=new Date;b.setHours(0,0,0,0);const _=new Date(b.getTime()+u*1e3);l(new Date(_))},[e]),{hours:t,minutes:o,seconds:n,formattedTime:d,timeActions:{setHours:s,setMinutes:r,setSeconds:i}}},Oy=({configProperty:e})=>{const{value:t}=Il({configProperty:e}),s=parseInt(t||"0",10),{hours:o,minutes:r,seconds:n,formattedTime:i,timeActions:c}=Bl({secondsFromMidnight:s}),l=g.useRef();return g.useEffect(()=>{const d=o*3600+r*60+n;return l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{e&&e.updateProperty(d.toString())},100),()=>{l.current&&clearTimeout(l.current)}},[e,o,r,n]),{hours:o,minutes:r,seconds:n,formattedTime:i,timeActions:c}};function Sy(e,t={}){const{intervalMs:s=5*60*1e3,immediate:o=!0}=t;g.useEffect(()=>{const r=()=>{try{e({__warmup:!0})}catch{}};o&&("requestIdleCallback"in window?requestIdleCallback(r):setTimeout(r,1));const n=s?setInterval(r,s):null;return()=>{n&&clearInterval(n)}},[e,s,o])}const Dy=e=>M.jsx("option",{title:e.id,value:e.format,children:e.format},e.id),Ay=(e=Dy)=>{const[t,s]=g.useState([]),[o,r]=g.useState(),{model:n,ready:i}=B({modelType:G.type,modelId:G.type,options:{}});g.useEffect(()=>{const l=N(()=>{s((n==null?void 0:n.dateFormatOptions.map(e))||[])});return()=>{l()}},[n,i,e]),g.useEffect(()=>{const l=N(()=>{n!=null&&n.dateFormatId&&(n!=null&&n.selectedDateFormat)&&r({id:n==null?void 0:n.dateFormatId,value:n==null?void 0:n.selectedDateFormat})});return()=>{l()}},[n==null?void 0:n.selectedDateFormat,n==null?void 0:n.dateFormatId]);const c=g.useCallback(l=>{var u;let d="";typeof l=="string"?d=l:(u=l==null?void 0:l.target)!=null&&u.value&&(d=l.target.value),d&&(n==null||n.setSelectedDateFormat(d))},[n]);return{raw:(n==null?void 0:n.dateFormatOptions.map(l=>l.id))??[],regionModel:n,selectedDateFormat:(o==null?void 0:o.value)||"",dateFormatId:(o==null?void 0:o.id)||"",updateDateFormat:c,props:{onChange:c,value:(o==null?void 0:o.id)||"",options:t}}},Cy=e=>M.jsx("option",{title:e,value:e,children:e},e),Kl="kos:service:region:settings",Hl="timeZone",Ry=`${Kl}-${Hl}`,Py=(e=Cy)=>{const[t,s]=g.useState([]),[o,r]=g.useState(""),{model:n,ready:i}=B({modelType:G.type,modelId:G.type,options:{}}),c=Pe.factory(Ry)({path:Kl,attribute:Hl});g.useEffect(()=>{const d=N(()=>{s((n==null?void 0:n.timeZones.map(e))||[]),n!=null&&n.timeZones.length&&Lo(n==null?void 0:n.timeZones[0])});return()=>{d()}},[n,i,e]),g.useEffect(()=>{const d=N(()=>{r(c.value||"")});return()=>{d()}},[c.value]);const l=g.useCallback(d=>{var h;let u="factory";typeof d=="string"?u=d:(h=d==null?void 0:d.target)!=null&&h.value&&(u=d.target.value),u&&Lo(u)},[]);return{options:t,raw:(n==null?void 0:n.timeZones)??[],regionModel:n,selectedTimeZone:o,timeZones:(n==null?void 0:n.timeZones)??[],updateTimeZone:l,selectProps:{onChange:l,value:o,options:t}}},Gl="kos:service:region",Vl="regionId",Ly=`${Gl}-${Vl}`,xy=e=>M.jsx("option",{title:e,value:e,children:e},e),Yl=(e=xy)=>{const[t,s]=g.useState([]),[o,r]=g.useState("factory"),{model:n,ready:i}=B({modelType:G.type,modelId:G.type,options:{}}),c=Pe.factory(Ly)({path:Gl,attribute:Vl});g.useEffect(()=>{const d=N(()=>{s((n==null?void 0:n.availableRegions.map(e))||[])});return()=>{d()}},[n,i,e]),g.useEffect(()=>{const d=N(()=>{r(c.value||"factory")});return()=>{d()}},[c.value]);const l=g.useCallback(d=>{var h;let u="factory";typeof d=="string"?u=d:(h=d==null?void 0:d.target)!=null&&h.value&&(u=d.target.value),u&&Wc(u)},[]);return{raw:(n==null?void 0:n.availableRegions)??[],regionModel:n,regionData:n==null?void 0:n.selectedRegion,selectedRegion:o,updateRegion:l,regionSelectProps:{onChange:l,value:o,options:t}}},ky=e=>M.jsx("option",{title:e.id,value:e.format,children:e.format},e.id),Fy=(e=ky)=>{const[t,s]=g.useState([]),[o,r]=g.useState(),{model:n,ready:i}=B({modelType:G.type,modelId:G.type,options:{}});g.useEffect(()=>{const l=N(()=>{s((n==null?void 0:n.timeFormatOptions.map(e))||[])});return()=>{l()}},[n,i,e]),g.useEffect(()=>{const l=N(()=>{n!=null&&n.timeFormatId&&(n!=null&&n.selectedTimeFormat)&&r({id:n==null?void 0:n.timeFormatId,value:n==null?void 0:n.selectedTimeFormat})});return()=>{l()}},[n==null?void 0:n.selectedTimeFormat,n==null?void 0:n.timeFormatId]);const c=g.useCallback(l=>{var u;let d="";typeof l=="string"?d=l:(u=l==null?void 0:l.target)!=null&&u.value&&(d=l.target.value),d&&(n==null||n.setSelectedTimeFormat(d))},[n]);return{raw:(n==null?void 0:n.timeFormatOptions.map(l=>l.id))??[],regionModel:n,selectedTimeFormat:(o==null?void 0:o.value)??"",timeFormatId:(o==null?void 0:o.id)??"",updateTimeFormat:c,props:{onChange:c,value:(o==null?void 0:o.id)??"",options:t}}},Ny=(e,t)=>g.useMemo(()=>sr(e),t),Uy={config:{attributes:!0,childList:!0,subtree:!0}};function jy(e,t,s=Uy){const[o,r]=g.useState(null);g.useEffect(()=>{if(!t||typeof t!="function")throw new Error("A valid callback function is required");const n=new MutationObserver(t);r(n)},[t,s,r]),g.useEffect(()=>{if(!o)return()=>{};if(!e)throw new Error("A valid DOM element is required");const{config:n}=s;try{o.observe(e,n)}catch(i){m.error(i)}return()=>{o&&o.disconnect()}},[o,e,s])}const zl={validateStart:function(e){return!0},validateStop:function(e){const t=e.event.currentTarget.getBoundingClientRect(),[s,o]=e.xy;return s<t.left||s>t.right||o<t.top||o>t.bottom}},yo=m.createLogger({name:"usePressGesture",group:"kos-hooks"});function By({onPressed:e,onRelease:t,intersectionStrategy:s=zl}){const o=g.useRef(!1),r=rd.useGesture({onDragStart:l=>{yo.info("onDragStart",l.type),s.validateStart(l)&&(e&&e(),o.current=!0)},onDrag:l=>{yo.info("onDrag",l.type),o.current&&s.validateStop(l)&&(t&&t(),o.current=!1)},onDragEnd:l=>{yo.info("onDragEnd",l.type),o.current&&t&&(t(),o.current=!1)}}),n=()=>{e&&e(),o.current=!0},i=()=>{o.current&&t&&(t(),o.current=!1)},c=()=>{o.current&&t&&(t(),o.current=!1)};return{dom:r,mesh:()=>({onPointerDown:n,onPointerUp:i,onPointerOut:c})}}const ql=()=>{const[e,t]=g.useState(!1),s=E.getInstance();return g.useEffect(()=>{const o=N(()=>{s&&s.reloading!==e&&t(s.reloading)});return()=>{o()}},[s,e]),[e]};function Wl(e=!1,t="2-digit"){return g.useMemo(()=>{const s=e?12:24;return Array.from({length:s},(o,r)=>{const n=e&&r===0?12:r%s;return{id:r,label:t==="2-digit"?n.toString().padStart(2,"0"):n.toString()}})},[t,e])}function ko(e,t="2-digit",s=0,o=0){return g.useMemo(()=>Array.from({length:e},(r,n)=>{const i=String(n+s);return{id:n+o,label:t==="2-digit"?i.padStart(2,"0"):i}}),[e,s,o,t])}function Zl(e="en-US"){return g.useMemo(()=>["AM","PM"].map(t=>{const s=new Intl.DateTimeFormat(e,{hour:"2-digit",hour12:!0}).formatToParts(new Date().setHours(t==="AM"?0:12))[2].value;return{id:s,label:s}}),[e])}function Jl({formatOptions:{hour12:e=!0,hour:t="2-digit",minute:s="2-digit",second:o="2-digit"}={hour12:!0,hour:"2-digit",minute:"2-digit",second:"2-digit"},locale:r="en-US"}){const n=Wl(e,t),i=ko(60,s),c=ko(60,o),l=Zl(r);return{hourOptions:n,minuteOptions:i,secondOptions:c,amPmOptions:l}}function Xl(e,t){return ye.format(e,t)}function Ql({formatOptions:e,initialDate:t=new Date,locale:s="en-US",format:o="HH:mm"}){const[r,n]=g.useState(t),i=g.useCallback(_=>{n(I=>{const C=new Date(I);return C.setHours(Number(_)),C})},[]),c=g.useCallback(_=>{n(I=>{const C=new Date(I);return C.setMinutes(Number(_)),C})},[]),l=g.useCallback(_=>{n(I=>{const C=new Date(I);return C.setSeconds(Number(_)),C})},[]),d=g.useCallback(_=>{const I=new Date(_);n(I)},[]),u=Xl(r,o),{hourOptions:h,minuteOptions:f,secondOptions:v,amPmOptions:b}=Jl({formatOptions:e,locale:s});return{amPmOptions:b,formattedTime:u,hourOptions:h,minuteOptions:f,secondOptions:v,setHours:i,setMinutes:c,setSeconds:l,setTime:d,time:new Date(r)}}const Ky=e=>{const{regionModel:t}=Yl(),s=g.useMemo(()=>({hour12:t==null?void 0:t.is12HourTimeFormat}),[t==null?void 0:t.is12HourTimeFormat]);return Ql({...e,locale:t==null?void 0:t.regionId,format:t==null?void 0:t.selectedTimeFormat,formatOptions:s})};function Hy(e){return t=>{const[s]=ql();return s?M.jsx(rl,{message:"Wait a moment while your project reloads..."}):M.jsx(e,{...t})}}const On=m.createLogger({name:"studio-properties-service",group:"Services"}),Gy="/api/kos/studio/properties",ed=async e=>{if(On.debug("sending GET for studio-properties"),!e)throw On.error("connectionId is undefined"),new Error("connectionId is undefined");return await Le.get(Gy,{},{destinationAddress:e,timeout:500})},Vy=Object.freeze(Object.defineProperty({__proto__:null,getStudioProperties:ed},Symbol.toStringTag,{value:"Module"}));var Yy=Object.defineProperty,zy=Object.getOwnPropertyDescriptor,qy=(e,t,s,o)=>{for(var r=o>1?void 0:o?zy(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Yy(t,s,r),r};const td="studio-properties-model",Wy="/kos/studio/properties",Sn={"kos.studio.tool.legacy":1};let Fo=class{constructor(e,t,s){a(this,"id");a(this,"connectionId");a(this,"unsubscribe",null);a(this,"logger");a(this,"data");this.id=e,this.logger=s.logger,this.data=be(),this.connectionId=t.connectionId}async init(){this.logger.debug(`initializing studio-properties ${this.id}`)}async load(){this.logger.debug(`loading studio-properties ${this.id}`)}async terminatePropertiesSession(){var e;(e=this.unsubscribe)==null||e.call(this)}async initializePropertiesSession(){this.unsubscribe=Vt.getInstance().subscribeTopic({topic:Wy,destinationAddress:this.connectionId,callback:s=>{this.logger.error(`Received studio-properties message for connection ${this.connectionId}: ${JSON.stringify(s)}`)}});const[e,t]=await ed(this.connectionId);if(e){this.logger.error(`Error loading studio-properties: ${e}`),this.data.setValues(Sn);return}if(t){const s=Object.keys(t).reduce((o,r)=>(o[r]=t[r]??r,o),{});this.data.setValues(s??Sn),m.ifDebug(()=>this.logger.debug(`studio-properties loaded: ${JSON.stringify(s)}`))}}get(e){return this.data[e]}createObservableProperty(e){return sr(()=>this.get(e))}};Fo=qy([S(td)],Fo);const Zy=new ce({class:Fo,type:td});Object.defineProperty(exports,"makeAutoObservable",{enumerable:!0,get:()=>w.makeAutoObservable});Object.defineProperty(exports,"makeObservable",{enumerable:!0,get:()=>w.makeObservable});Object.defineProperty(exports,"kosComponent",{enumerable:!0,get:()=>Uo.observer});exports.AuthState=Zi;exports.BrowserKosRouter=ia;exports.BrowserRouter=Ys;exports.CanvasDispatcher=Ze;exports.CanvasDispatcherServices=Qf;exports.CanvasRenderer=Ir;exports.CanvasStreamer=Vp;exports.CanvasStreamerBase=pl;exports.ChildModels=_t;exports.ConfigBean=Ct;exports.CoreExtensionManager=Zm;exports.CoreModels=Rr;exports.CreateModelTranslationsContext=ul;exports.CreateModelTranslationsProvider=_p;exports.DateDisplayFormat=Ul;exports.DateHelpers=pd;exports.DependencyLifecycle=k;exports.DependencyModels=L;exports.Device=xs;exports.DeviceServices=bm;exports.DomIntersectionStrategy=zl;exports.EVENT_KOS_MODEL_READY=Ho;exports.EVENT_TROUBLE_ADDED=Oh;exports.EVENT_TROUBLE_REMOVED=Sh;exports.EXTENSION_CANVAS_RENDERER=ne;exports.EXTENSION_TROUBLE_DATA_MAPPER=Is;exports.EXTENSION_TROUBLE_MAPPER=Zt;exports.ErrorBoundaryWithFallback=nl;exports.EventBus=cd;exports.ExtensionManager=$;exports.FUTURE_CONTAINER_MODEL_TYPE=Pa;exports.FUTURE_MODEL_TYPE=Ea;exports.FUTURE_NOT_ASSIGNED=rr;exports.FeatureFlagService=qn;exports.FetchError=le;exports.FutureContainerFactory=ve;exports.FutureContainerModel=xa;exports.FutureEndState=Ve;exports.FutureFactory=ot;exports.FutureHandler=ur;exports.FutureManager=De;exports.FutureModel=Da;exports.FutureService=Mt;exports.HEADER_CACHE_CONTROL=Ln;exports.HEADER_CONTENT_TYPE=Pn;exports.HEADER_DESTINATION_ADDR=me;exports.HEADER_FOS_REQUEST_ID=xn;exports.HEADER_METHOD=Us;exports.HEADER_ORDERED=Bo;exports.HEADER_REQUEST_ID=Ht;exports.HEADER_REQUEST_TYPE=de;exports.HEADER_RESPONSE_ID=js;exports.HEADER_SOURCE_ADDR=Rn;exports.HEADER_TOPIC=Cn;exports.HEADER_URL=Qe;exports.HEADER_WORK_TRACKER=Ko;exports.KOS_MODEL_ID=fs;exports.KeyValue=yr;exports.KeyValueServices=Eg;exports.Kos=V;exports.KosConfigPropertySpec=Pe;exports.KosContainerIndex=tr;exports.KosContextBean=oa;exports.KosContextManager=x;exports.KosCore=E;exports.KosCoreModelPropertyMapper=re;exports.KosDataContainer=ra;exports.KosDependencyTypes=Rd;exports.KosExtensionUtils=Cu;exports.KosFeatureFlags=yd;exports.KosFetchMethods=$i;exports.KosGlobalConfig=Wo;exports.KosLog=m;exports.KosMockEvents=Nn;exports.KosModel=Ui;exports.KosModelCollectionProvider=yp;exports.KosModelContainer=ue;exports.KosModelContext=Xs;exports.KosModelEvents=D;exports.KosModelFactory=Ot;exports.KosModelLoader=ll;exports.KosModelLoaderDisplay=dl;exports.KosModelManager=Ki;exports.KosModelProvider=il;exports.KosModelRegistrationFactory=ce;exports.KosModelRegistry=Po;exports.KosModelState=y;exports.KosModelSymbol=gi;exports.KosModelVisitor=th;exports.KosObservableData=Qi;exports.KosRegistration=Eh;exports.KosSingletonRegistration=Ih;exports.KosTime=Ms;exports.KosTimeContext=Nr;exports.KosTimeProvider=Ap;exports.KosTimeServices=Og;exports.KosTimer=Zc;exports.KosToken=na;exports.KosTranslationProvider=Fp;exports.KosTranslations=Ec;exports.KosWSTransportStatus=Ni;exports.KosWsEvents=Gt;exports.LOGIN_HOST=kn;exports.LOGIN_URL=nd;exports.LoadingMessage=rl;exports.LogBlock=kt;exports.LogBlockContainer=qs;exports.LogConfig=It;exports.LogStream=Dt;exports.LogStreamContainer=Wt;exports.LogStreamServices=Ng;exports.MODEL_DELETION_DELAY=Bi;exports.MiddlewareChain=Xi;exports.ModelEffects=Oe;exports.MultipleFutureHandler=tg;exports.NestedModelContext=Qs;exports.NetworkInterface=Sr;exports.NetworkInterfaceContainer=jt;exports.NetworkInterfaceServices=Sm;exports.ObservableData=be;exports.Ota=$s;exports.OutsideAlerter=ey;exports.PLUGIN_EXTENSION_NAME=Ru;exports.PORT=Fn;exports.PROFILE_LOG_DEBUG=Qn;exports.PROFILE_LOG_INFO=ei;exports.PROFILE_RELAX_STORE_VALIDATION=vd;exports.PROFILE_TOOLS_PREVIEW=Xn;exports.ParentModel=Et;exports.PluginExtensionManager=Pu;exports.ProgressBar=gp;exports.ReferenceConfig=cs;exports.RegionInfo=G;exports.RegionServices=Nh;exports.RegistrationManager=O;exports.Registry=qm;exports.STATUS=jo;exports.ServiceFactory=Y;exports.SingletonKosModelRegistrationFactory=pe;exports.SoftwareInfo=Os;exports.SoftwareInfoContext=jr;exports.SoftwareInfoProvider=Pp;exports.SoftwareInfoServices=vf;exports.StateBean=Nt;exports.StateBeanServices=Tf;exports.StateProp=wr;exports.StatePropServices=xf;exports.StorageDevice=Fs;exports.StorageDeviceContainer=Je;exports.StorageDeviceServices=Pm;exports.StudioProperties=Zy;exports.StudioPropertiesServices=Vy;exports.SubscriptionHandlers=H;exports.TIMER_END=xr;exports.TIMER_EVENT=Pr;exports.TOPIC_TIMER_TICK_EVENT=Lr;exports.TimerManager=Jc;exports.TokenContext=ml;exports.TokenProvider=xp;exports.Topics=St;exports.Trans=ly;exports.TransitionMap=ls;exports.Transitions=Zo;exports.Translation=As;exports.TranslationContainer=fe;exports.TranslationContainerContext=Br;exports.TranslationContext=Yf;exports.TransportFactory=Eo;exports.Trouble=Ft;exports.TroubleContainer=qe;exports.TroubleServices=rf;exports.Troubles=Q;exports.UsbUpdate=Cr;exports.UsbUpdateContainer=Kt;exports.UsbUpdateServices=Km;exports.WS_EVENT_TYPE=Ic;exports.WebSocketEvents=$t;exports.WebSocketTransport=Vt;exports.WsEventFactory=_r;exports.acceptOrgInvitation=ol;exports.addDaysToDate=Bn;exports.addFuture=Ta;exports.addMonthsToDate=jn;exports.api=Aa;exports.applyMixins=dd;exports.arraysEqual=ud;exports.buildConfigBeanModel=Ch;exports.buildFuture=fr;exports.buildFutureModel=Oa;exports.cancelFuture=$a;exports.convert=lr;exports.convertFileSizeRaw=ld;exports.convertWithUnits=Gh;exports.createBaseMessage=Di;exports.createBroadcastMessageResponse=Pi;exports.createClient=Qo;exports.createFosBaseMessage=Si;exports.createHeaders=wo;exports.createKosHtpMessageResponse=Li;exports.createKosMessage=Ci;exports.createKosMessageResponse=xi;exports.createMessageBody=we;exports.createModelDependency=Mi;exports.createOptionKey=Pd;exports.createPropKey=Ae;exports.createReadableStream=Mo;exports.createStudioMessage=Oi;exports.createStudioMessageRequest=Ai;exports.createStudioMessageResponse=Ri;exports.debounce=zn;exports.deleteFuture=Ia;exports.destroyKosModel=Se;exports.evaluateScopes=ga;exports.executeChildrenModelLifecycle=Ii;exports.executeDependentModelLifecycle=lt;exports.executeListLifecycle=Ei;exports.fetchModel=Wp;exports.findModel=Fu;exports.findModels=Vi;exports.formatDate=Gn;exports.formatDateSince=Un;exports.formatDateTime=Yn;exports.formatTime=Vn;exports.getAllKosCompanionModels=Uu;exports.getCalendarMonthArray=Dl;exports.getConfigBean=ha;exports.getDayStrings=Al;exports.getDays=_y;exports.getDaysArray=Tl;exports.getDaysInMonth=qo;exports.getDependenciesByLifecycle=_i;exports.getFormattedDate=Ey;exports.getFormattedMonth=Iy;exports.getFormattedMonthsArray=Hr;exports.getFormattedYear=oe;exports.getFormattedYearsArray=Sl;exports.getFutures=cg;exports.getKosCompanionModel=Nu;exports.getKosLocalizationDescriptor=bc;exports.getKosMessageLogging=ni;exports.getKosModel=Gi;exports.getKosModelSync=Re;exports.getKosModelType=ku;exports.getKosSessionKey=sa;exports.getLastDayOfMonth=wt;exports.getLocalizationDescriptor=Ff;exports.getLogLevel=ri;exports.getLogMessageToStudio=ii;exports.getMessageBody=_o;exports.getMonthsArray=$l;exports.getObservableCompanions=ju;exports.getQueryParams=ee;exports.getTranslations=yc;exports.getYearsArray=Ol;exports.hasDecimals=da;exports.hasKosProfile=bo;exports.hslStringToHex=Zn;exports.hslToHex=Wn;exports.initKosProvider=Ip;exports.isBoolean=ir;exports.isKosCompanionTypeFactory=ji;exports.isKosDataModel=Tt;exports.isKosLoggingEnabled=_d;exports.isKosModel=te;exports.isKosModelContainer=Jo;exports.isKosModelReady=ps;exports.isLeapYear=zo;exports.isLocalRefId=yh;exports.isNumber=Hs;exports.isPrintable=qd;exports.isValidDate=vt;exports.kosAction=z;exports.kosAutoEffect=N;exports.kosChild=ae;exports.kosCompanion=Bd;exports.kosComputed=sr;exports.kosConfigBean=Gs;exports.kosConfigProperty=eg;exports.kosContext=Kd;exports.kosDependency=Ce;exports.kosEffect=ca;exports.kosFuture=kr;exports.kosLogger=Hd;exports.kosModel=S;exports.kosModelEffect=fi;exports.kosObservable=or;exports.kosParentAware=Ks;exports.kosReference=Gd;exports.kosStateBean=sp;exports.kosStateProp=op;exports.kosSubscribe=Vd;exports.kosTopicHandler=R;exports.kosWhen=To;exports.login=el;exports.mapConfigBeanModelToDto=ya;exports.mapDataToModel=vo;exports.mapDtoToConfigBeanModel=ma;exports.mapDtoToFutureModel=gr;exports.mapDtoToFutureOptions=hr;exports.mapUpdateDtoToConfigBeanModel=pa;exports.modelEventTopicFactory=ui;exports.modelFactory=tt;exports.modelTypeEventTopicFactory=hi;exports.modifyConfigBean=ua;exports.modifyFuture=lg;exports.pairedClientHeartbeat=ch;exports.pipe=ta;exports.preloadKosModel=Hu;exports.processId=md;exports.processMiddleware=rh;exports.registerCompanionModel=Ku;exports.registerCoreModels=Yc;exports.registerExtensionPoint=Bs;exports.registerKosModel=zi;exports.registerLegacyModel=Yi;exports.resetKosModel=Hi;exports.resetPassword=sl;exports.resolveBaseUrl=Ji;exports.resolveChild=Ti;exports.resolveContainerDeltas=hd;exports.resolveItemListDeltas=fd;exports.resolveKosCompanion=Io;exports.resolveKosContext=wh;exports.resolveKosProfiles=si;exports.resolveListDeltas=gd;exports.resolveServiceUrl=q;exports.resolveVariable=Jn;exports.retryWithExponentialBackoff=dh;exports.sendAsyncIntent=$h;exports.sendBroadcastMessage=gu;exports.sendIntent=Th;exports.sendKosHttpMessageResponse=Fi;exports.sendKosMessage=du;exports.sendKosMessageResponse=ki;exports.sendRequest=bh;exports.sendStudioMessage=hu;exports.sendStudioMessageRequest=uu;exports.startPasswordReset=tl;exports.stringComponentInsert=Ml;exports.studioAcceptOrgInvitation=ap;exports.studioLogin=rp;exports.studioResetPassword=ip;exports.studioStartPasswordReset=np;exports.subscribeStore=Jm;exports.syncPublish=vh;exports.transitionToActive=yi;exports.transitionToInit=wi;exports.transitionToLoad=vi;exports.transitionToReady=bi;exports.transitionToUnload=zd;exports.troubleByTypeReducer=zf;exports.troubleDataFactory=ac;exports.unloadKosModel=xu;exports.updateCompanionModelRegistration=ih;exports.updateModelRegistration=nh;exports.updateRegion=Wc;exports.updateTimeZone=Lo;exports.useAmPmValues=Zl;exports.useCalendarDayArray=Nl;exports.useConfigBean=vy;exports.useConfigProperty=Il;exports.useContextModel=mp;exports.useContextModelHierarchy=cl;exports.useDateArrays=Cl;exports.useDateProps=$y;exports.useDateRelativeConfig=Oy;exports.useDateRelativeData=Bl;exports.useDayNames=kl;exports.useDayOptions=xl;exports.useDays=Vr;exports.useDevice=yl;exports.useFormattedDate=Fl;exports.useFormattedTime=Xl;exports.useFunctionWarmup=Sy;exports.useHourValues=Wl;exports.useKosCore=gl;exports.useKosDateFormats=Ay;exports.useKosModel=B;exports.useKosRegions=Yl;exports.useKosTime=Fr;exports.useKosTimeContext=Cp;exports.useKosTimeFormats=Fy;exports.useKosTimeZones=Py;exports.useKosTranslation=gy;exports.useKosTranslationContext=Np;exports.useLocalComputed=Ny;exports.useModelFromHierarchy=vp;exports.useMonths=Pl;exports.useMonthsOptions=Ll;exports.useMutationObserver=jy;exports.useNetworkInterfaceContainer=bl;exports.useOta=vl;exports.usePressGesture=By;exports.useProjectReload=ql;exports.useRegionTimeProps=Ky;exports.useRegionalTimeDate=jl;exports.useSoftwareInfo=Ur;exports.useSoftwareInfoContext=Lp;exports.useStateProperty=ty;exports.useStorageDeviceContainer=wl;exports.useSuspenseData=xo;exports.useTimeOptions=Jl;exports.useTimeProps=Ql;exports.useTimeValues=ko;exports.useTimer=oy;exports.useTranslationContainer=_l;exports.useTroubleContainerModel=Kr;exports.useTroubleModel=my;exports.useTroublePresence=py;exports.useUsbUpdateContainer=El;exports.useYears=Gr;exports.useYearsOptions=Rl;exports.uuid=et;exports.variableToHex=bd;exports.waitForRequest=er;exports.whenReady=J;exports.withDevice=qp;exports.withKosTime=Zp;exports.withNetworkInterfaceContainer=Jp;exports.withOta=Xp;exports.withProjectReloading=Hy;exports.withSoftwareInfo=Rp;exports.withStorageDeviceContainer=sy;exports.withTranslationContainer=fy;exports.withTroubleContainer=yy;exports.withUsbUpdateContainer=by;exports.wrapPromise=Vo;
|
|
193
|
+
`,Yl=()=>{const e=Gs.type;return V({modelId:e,modelType:Gs.type,options:{}})};function Qy(e){return t=>{const{model:s,status:r,KosModelLoader:o}=Yl();return _.jsx(o,{...r,children:_.jsx(e,{...t,device:s})})}}function eb(e,t,s){const r=new Promise(o=>{I.getInstance().whenReady().then(()=>{const{model:n}=I.getInstance().modelManager.createModelInstance(e,t??e,s);return n.whenReady().then(()=>{o(n.modelData)})})});return so(r)}function tb(e){return t=>{const{model:s,status:r,KosModelLoader:o}=Wo();return _.jsx(o,{...r,children:_.jsx(e,{...t,kosTime:s})})}}const ql=()=>{const e=Yt.type;return V({modelId:e,modelType:Yt.type,options:{}})};function sb(e){return t=>{const{model:s,status:r,KosModelLoader:o}=ql();return _.jsx(o,{...r,children:_.jsx(e,{...t,networkInterfaceContainer:s})})}}const Wl=()=>{const e=Ls.type;return V({modelId:e,modelType:Ls.type,options:{}})};function rb(e){return t=>{const{model:s,status:r,KosModelLoader:o}=Wl();return _.jsx(o,{...r,children:_.jsx(e,{...t,oTA:s})})}}function ob(e,t){f.useEffect(()=>{function s(o){e.current&&!e.current.contains(o.target)&&t()}function r(o){o.key==="Escape"&&t()}return document.addEventListener("mousedown",s),document.addEventListener("keydown",r,!1),()=>{document.removeEventListener("mousedown",s),document.removeEventListener("keydown",r,!1)}},[e,t])}function nb(e){const t=f.useRef(null),s=e.onAlert;return ob(t,s),_.jsx("div",{ref:t,style:{width:"100%"},children:e.children})}const ib=e=>{var d;const{stateProp:t}=e,[s,r]=f.useState((d=e.stateProp)==null?void 0:d.value),[o,n]=f.useState(!1),[i,a]=f.useState(void 0);return f.useEffect(()=>{async function u(h){try{h&&(await re(h),n(!0))}catch(g){a(g.message)}}u(t)},[t]),f.useEffect(()=>{const u=j(()=>{t&&o&&r(t.value)});return()=>{u()}},[o,t]),[s,{ready:o,error:i}]},Zl=()=>{const[e,t]=f.useState(!1),[s,r]=f.useState([]),o=st.type,n=V({modelId:o,modelType:st.type,options:{}});return f.useEffect(()=>{const i=j(()=>{var a,c;t(((a=n.model)==null?void 0:a.isStorageInserted)??!1),r(((c=n.model)==null?void 0:c.data)??[])});return()=>{i()}},[n.model]),{...n,inserted:e,devices:s}};function ab(e){return t=>{const{model:s,status:r,KosModelLoader:o}=Zl();return _.jsx(o,{...r,children:_.jsx(e,{...t,storageDeviceContainer:s})})}}const Tr=p.createLogger({name:"use-timer"}),cb=({timerName:e,onTimerExpired:t,onTimerTick:s,timerEventActions:r,autoStart:o})=>{const n=Sl.getTimer(e);f.useEffect(()=>{if(!n){console.warn(`Timer with name ${e} does not exist.`);return}const d=O(zo,u=>{const{name:h,action:g,remainingTime:m}=u==null?void 0:u.body;h===e&&(g===Yo?t({name:h,action:g,remainingTime:m,timer:n}):r!=null&&r[g]&&r[g]({name:h,action:g,remainingTime:m,timer:n}))});return o&&n.start(),()=>{d.unsubscribe()}},[o,t,r,e,n]),f.useEffect(()=>{if(!n||!s)return;const d=`${Vo}/${e}`,u=O(d,h=>{const{name:g,remainingTime:m}=h==null?void 0:h.body;g===e&&s({name:g,remainingTime:m,timer:n})});return()=>{u.unsubscribe()}},[s,e,n]);const i=f.useCallback(()=>{n?n.start():Tr.warn(`Timer with name ${e} does not exist.`)},[n,e]),a=f.useCallback(()=>{n?n.reset():Tr.warn(`Timer with name ${e} does not exist.`)},[n,e]),c=f.useCallback(()=>{n?n.pause():Tr.warn(`Timer with name ${e} does not exist.`)},[n,e]);return{timer:n,start:i,reset:a,pause:c}},lb=e=>{const t=/[\\^$.*+?()[\]{}|]/g;return RegExp(t.source).test(e)?e.replace(t,"\\$&"):e},db=e=>e instanceof RegExp,ub=e=>typeof e=="string",hb=(e,t,s)=>{if(e===""||t==="")return e;let r=t;db(r)||(r=new RegExp("("+lb(r)+")","gi"));const o=e.split(r);for(let n=1,i=o.length;n<i;n+=2)o[n]=s(o[n],n);return o},Jl=(e,t,s)=>{let r=e;return Array.isArray(r)||(r=[r]),r.flatMap(o=>ub(o)?hb(o,t,s):o)};function fb(e,t){let s=e;return Object.entries(t).forEach(([r,o])=>{const n=new RegExp(`<${r}>(.*?)</${r}>|<${r}/>`,"g");s=Jl(s,n,(i,a)=>o.type==="br"?_.jsx("br",{}):f.cloneElement(o,{key:`${r}-${a}`},i))}),s}const gb=e=>{const{i18nKey:t,t:s,defaults:r,components:o,values:n={},context:i}=e,a=s(t,{defaultValue:r,data:n,context:i,returnObjects:!0}),c=fb(a,o||{});return _.jsx("span",{className:e.className,children:c})},Ye=new Map;function pb(e,t){if(Ye.has(e)){const s=Ye.get(e);if(s.status==="finished")return s.result;throw s.promise}else{const s=t().then(o=>{Ye.set(e,{status:"finished",result:o})},o=>{throw Ye.set(e,{status:"error",error:o}),o}),r={status:"pending",promise:s};throw Ye.set(e,r),s}}function Hr(e,t){return pb(e,t)}const mb=async()=>{const e=await ma(ve.type);return await re(e.model),e.model},yb=async(e,t,s)=>{const r=e.resolveNamespace(t);await re(r);for(const o of s){const n=e.resolveNamespace(o);await re(n),Ye.set(o,{status:"finished",result:n})}return r},bb=(e,t)=>{const s=[e].flat(),[r,...o]=s,n=Hr(ve.type,mb),i=s.join("__"),a=Hr(i,()=>yb(n,r,o)),c=f.useMemo(()=>({exists:u=>{const h=t!=null&&t.keyPrefix?`${t.keyPrefix}.${u}`:u;return a?a.exists(h):!1}}),[t==null?void 0:t.keyPrefix,a]);return{t:f.useCallback((u,h)=>{const g=t!=null&&t.keyPrefix?`${t.keyPrefix}.${u}`:u;return a?a.resolveKey(g,h):(p.debug(`Translation model ${e} not ready for key: ${g}`),g)},[t==null?void 0:t.keyPrefix,e,a]),i18n:c}},Xl=()=>{const e=ve.type;return V({modelId:e,modelType:ve.type,options:{}})};function wb(e){return t=>{const{model:s,status:r,KosModelLoader:o}=Xl();return _.jsx(o,{...r,children:_.jsx(e,{...t,translationContainer:s})})}}const vb=e=>V({modelId:e,modelType:Gt.type}),en=()=>V({modelId:Qe.type,modelType:Qe.type,options:{}}),Mb=({troubleType:e,condition:t})=>{const{model:s}=en(),[r,o]=f.useState(!1),[n,i]=f.useState([]),a=f.useCallback(()=>{var c,d;return n.length>0&&((c=n[0])!=null&&c.resolvable)?(d=n[0])==null?void 0:d.resolve():Promise.resolve(void 0)},[n]);return f.useEffect(()=>j(()=>{const d=(e?s==null?void 0:s.troubles.getIndexByKey("byType",e):s==null?void 0:s.troubles.data)||[],u=t?d.filter(t):d;o(u.length>0),i(u)}),[t,s,e]),[r,a,n.length>0?n[0]:void 0,n]};function Eb(e){return t=>{const{model:s,status:r,KosModelLoader:o}=en();return _.jsx(o,{...r,children:_.jsx(e,{...t,troubleContainer:s})})}}const Ql=()=>{const e=Wt.type,t=V({modelId:e,modelType:Wt.type,options:{},activate:!0,destroyOnUnmount:!0}),[s,r]=f.useState(!1),[o,n]=f.useState(!1),[i,a]=f.useState([]);return f.useEffect(()=>{const c=j(()=>{var d,u,h;r(((d=t.model)==null?void 0:d.isUsbInserted)??!1),n(((u=t.model)==null?void 0:u.hasAvailableUpdates)??!1),a(((h=t.model)==null?void 0:h.data)??[])});return()=>{c()}},[t.model]),{...t,inserted:s,updateAvailable:o,updates:i}};function _b(e){return t=>{const{model:s,status:r,KosModelLoader:o}=Ql();return _.jsx(o,{...r,children:_.jsx(e,{...t,usbUpdateContainer:s})})}}const Ib=({path:e,propKey:t})=>{const{status:s}=V({modelType:Nt.type,modelId:e,options:{path:e}}),[r,o]=f.useState(!1),[n,i]=f.useState(),[a,c]=f.useState(""),[d,u]=f.useState(),h=g=>{n&&t&&n.updateProperty(t,g)};return f.useEffect(()=>{var g;s.model&&i(s.model),s.model&&t&&((g=s.model)!=null&&g.props.has(t)?c(s.model.props[t]):u(`property ${t} not found`)),s.ready&&o(s.ready)},[s.ready,s.model,t]),f.useEffect(()=>{t&&M.autorun(()=>{const g=n==null?void 0:n.props[t];c(g||"")})},[n,t]),{config:n,ready:r,value:a,error:d,updateValue:h}},Tb=(e,t)=>{switch(t.type){case"UPDATE":return t.payload;default:return e}},ed=({configProperty:e,optionsTransformer:t})=>{const[s,r]=f.useState(!1),[o,n]=f.useState(""),[i,a]=f.useReducer(Tb,{value:String(e==null?void 0:e.value),displayValue:e==null?void 0:e.displayValue,significantValue:e==null?void 0:e.significantValue,unit:e==null?void 0:e.unit,options:e==null?void 0:e.options,mappedOptions:[],updateProperty:e==null?void 0:e.updateProperty,displayOptions:e==null?void 0:e.displayOptions}),c=f.useCallback(d=>{var h;let u="factory";typeof d=="string"?u=d:(h=d==null?void 0:d.target)!=null&&h.value&&(u=d.target.value),u&&(e==null||e.updateProperty(u))},[e]);return f.useEffect(()=>{async function d(u){try{u&&(await re(u),r(!0))}catch(h){n(h.message)}}d(e)},[e]),f.useEffect(()=>{const d=j(()=>{if(e&&s){let u=[];t&&(u=t(e.options)),a({type:"UPDATE",payload:{value:String(e.value),displayValue:e.displayValue,significantValue:e.significantValue,unit:e.unit,options:e.options,mappedOptions:u,updateProperty:e.updateProperty,displayOptions:e==null?void 0:e.displayOptions}})}});return()=>{d()}},[e,t,s]),{...i,configSelectProps:{onChange:c,value:i.value,options:t?i.mappedOptions||[]:i.options||[]},ready:s,error:o}};function Ob(e,t){const s=t??new Date().getFullYear(),r=[31,28,31,30,31,30,31,31,30,31,30,31];return e===1&&(s%4===0&&s%100!==0||s%400===0)?29:r[e]??0}function Sb(e,t){return new Date(e,t,0).getDate()}function td(e,t){const s=Ob(t,e),r=[];for(let o=1;o<=s;o++)r.push(o);return r}function sd(){return[...Array(12).keys()].map(t=>new Date(0,t).getMonth())}function rd(e=[2018,2028]){const t=[];for(let s=e[0];s<=e[1];s++)t.push(s);return t}function od(e,t=[2018,2028]){const s=rd(t);return e==="long"?s:s.map(r=>Number(r.toString().substring(2)))}function tn(e="numeric",t="en-US"){const s=new Intl.DateTimeFormat(t,{month:e,timeZone:"UTC"}).format;return[...Array(12).keys()].map(r=>s(new Date(Date.UTC(0,r,1))))}function $b({locale:e="en-US",year:t,month:s,day:r,formatOptions:o={weekday:"long",year:"numeric",month:"long",day:"numeric"},displayOrder:n}){const i=s-1,a=new Date(t,i,r),c=new Intl.DateTimeFormat(e,{month:o.month}).format(a),d=new Intl.DateTimeFormat(e,{year:o.year}).format(a),u=new Intl.DateTimeFormat(e,{day:o.day}).format(a);return n?n=="MMDDYY"?`${c} ${u} ${d}`:n==="DDMMYY"?`${u} ${c} ${d}`:n==="YYMMDD"?`${d} ${c} ${u}`:`${d} ${u} ${c}`:new Intl.DateTimeFormat(e,o).format(a)}function le(e){return e.toString().length===2?new Date(Date.parse(`01 Jan 20${e}`)).getFullYear():e}function Db(e){return typeof e=="string"?new Date(Date.parse(`01 ${e.substring(0,3)} 2023`)).getMonth()+1:e}function nd(e,t,s){const r=le(t),o=new Date(r,e,1).getDay(),n=new Date(r,e+1,0).getDate();return[...Array(42).keys()].map(a=>a<o||a>n+o-1?{label:"",value:0,disabled:!0}:s[a-o])}function Ot(e,t,s){const r=t-1,o=new Date(e,r,s);return new Date(o).getMonth()===r&&new Date(o).getDate()===s}function St(e,t){return new Date(e,t,0).getDate()}function id(e="en-US",t="short"){const s=new Intl.DateTimeFormat(e,{weekday:t}).format;return[...Array(7).keys()].map(r=>s(new Date(Date.UTC(2021,5,r))))}function ad({locale:e="en-US",year:t=new Date().getFullYear(),month:s=new Date().getMonth(),yearRange:r=[2018,2028],daysOfWeekFilter:o=[],formatOptions:{yearFormat:n="long",monthFormat:i="long",dayFormat:a="short"}={}}){const c=sn(n,r),d=cd(n,r,e),u=ld(i,e),h=dd(i,e),g=rn(t,s),m=ud(t,s,e,o),v=gd(s,t,m),w=hd(e,a);return{daysArray:g,monthsArray:u,yearsArray:c,yearsOptionsArray:d,monthsOptionsArray:h,daysOptionsArray:m,calendarDayArray:v,dayNamesArray:w}}function sn(e="long",t=[2018,2028]){return f.useMemo(()=>od(e,t),[e,t])}function cd(e="long",t=[2018,2028],s="en-US"){const r=sn(e,t);return f.useMemo(()=>r.map(n=>({label:n.toLocaleString(s).replace(",",""),value:n})),[s,r])}function ld(e,t="en-US"){return f.useMemo(()=>tn(e,t),[e,t])}function dd(e,t="en-US"){const s=f.useMemo(()=>sd(),[]),r=f.useMemo(()=>tn(e,t),[e,t]);return f.useMemo(()=>[...Array(12).keys()].map(n=>({label:r[n],value:Number(s[n])})),[r,s])}function rn(e,t){const s=le(e);return f.useMemo(()=>td(s,t),[t,s])}const Cb=(e,t,s,r=[])=>{const o=new Date(e,t,s).getDay();return r.length>0&&r.includes(o)};function ud(e,t,s="en-US",r=[]){const o=rn(e,t);return f.useMemo(()=>o.map(i=>({label:i.toLocaleString(s),value:i,disabled:Cb(e,t,i,r)})),[r,s,t,o,e])}function hd(e="en-US",t="short"){return f.useMemo(()=>id(e,t),[e,t])}function fd({year:e=new Date().getFullYear(),month:t=new Date().getMonth(),day:s=new Date().getDate(),formatString:r}){const o=t,n=new Date(e,o,s);return{formattedDate:Ie.format(n,r)}}function gd(e,t,s){return f.useMemo(()=>nd(e,t,s),[e,t,s])}var pd=(e=>(e.MMDDYY="MMDDYY",e.DDMMYY="DDMMYY",e.YYMMDD="YYMMDD",e.YYDDMM="YYDDMM",e))(pd||{});function Ab({locale:e="en-US",date:{year:t=new Date().getFullYear(),month:s=new Date().getMonth(),day:r=new Date().getDate()}={year:new Date().getFullYear(),month:new Date().getMonth(),day:new Date().getDate()},formatOptions:{yearFormat:o="long",monthFormat:n="long",dayFormat:i="short",formatString:a="yyyy/MM/dd"}={},filterOptions:{yearsRange:c=[2018,2028],daysOfWeekFilter:d=[]}={}}){const[u,h]=f.useState(t),[g,m]=f.useState(c),[v,w]=f.useState(s),[E,T]=f.useState(r);f.useEffect(()=>{h(t)},[t]),f.useEffect(()=>{w(s)},[s]),f.useEffect(()=>{T(r)},[r]);const{yearsArray:K,yearsOptionsArray:H,monthsArray:ce,monthsOptionsArray:R,daysArray:G,daysOptionsArray:k,calendarDayArray:Y,dayNamesArray:_e}=ad({locale:e,year:u,yearRange:g,month:v,formatOptions:{yearFormat:o,monthFormat:n,dayFormat:i},daysOfWeekFilter:d}),{formattedDate:dt}=fd({year:u,month:v,day:E,formatString:a});return{dateActions:{setYear:h,setYearRange:m,setMonth:w,setDay:T,nextMonth:()=>{const q=v<11?le(u):le(u+1),te=v<11?v+1:0;if(!Ot(q,te,E)){const Ce=St(q,te);T(Ce)}te===0&&h(q),w(te)},previousMonth:()=>{const q=le(v===0?u-1:u),te=v===0?11:v-1;if(!Ot(q,te,E)){const Ce=St(q,te);T(Ce)}te===11&&h(q),w(te)},nextYear:()=>{const q=u<g[1]?u+1:g[0],te=le(q);if(Ot(te,v,E))h(q);else{const Ce=St(le(u+1),v);T(Ce),h(q)}},previousYear:()=>{const q=u>g[0]?u-1:g[0],te=le(q);if(Ot(te,v,E))h(q);else{const Ce=St(le(u-1),v);T(Ce),h(q)}}},dateState:{year:u,yearRange:g,month:v,day:E,yearsArray:K,yearsOptionsArray:H,monthsArray:ce,monthsOptionsArray:R,daysArray:G,daysOptionsArray:k,calendarDayNames:_e,calendarDayArray:Y,formattedDate:dt}}}function md({date:e=new Date,dateFormat:t,timeFormat:s,options:r={}}){const[o,n]=f.useState("Formatting Time..."),[i,a]=f.useState("Formatting Date..."),c=!!r.ignoreDateFormat,{model:d,ready:u}=V({modelId:Z.type,modelType:Z.type,options:{}}),h=typeof e=="string"?Ie.parseISO(e):e;return f.useEffect(()=>{c?a(""):t?a(Ie.format(h,t)):u&&a(Ie.format(h,d!=null&&d.selectedDateFormat?d==null?void 0:d.selectedDateFormat:""))},[c,e,t,h,d,u]),f.useEffect(()=>{s?n(Ie.format(h,s)):u&&n(Ie.format(h,d!=null&&d.selectedTimeFormat?d==null?void 0:d.selectedTimeFormat:""))},[e,s,h,d,u]),{formattedDate:i,formattedTime:o}}const yd=({secondsFromMidnight:e=0})=>{const[t,s]=f.useState(0),[r,o]=f.useState(0),[n,i]=f.useState(0),[a,c]=f.useState(new Date),{formattedTime:d}=md({date:a,options:{ignoreDateFormat:!0}});return f.useEffect(()=>{const u=Number(e),h=Math.floor(u/3600),g=Math.floor(u%3600/60),m=u%60;s(h),o(g),i(m);const v=new Date;v.setHours(0,0,0,0);const w=new Date(v.getTime()+u*1e3);c(new Date(w))},[e]),{hours:t,minutes:r,seconds:n,formattedTime:d,timeActions:{setHours:s,setMinutes:o,setSeconds:i}}},Rb=({configProperty:e})=>{const{value:t}=ed({configProperty:e}),s=parseInt(t||"0",10),{hours:r,minutes:o,seconds:n,formattedTime:i,timeActions:a}=yd({secondsFromMidnight:s}),c=f.useRef();return f.useEffect(()=>{const d=r*3600+o*60+n;return c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{e&&e.updateProperty(d.toString())},100),()=>{c.current&&clearTimeout(c.current)}},[e,r,o,n]),{hours:r,minutes:o,seconds:n,formattedTime:i,timeActions:a}};function Pb(e,t={}){const{intervalMs:s=5*60*1e3,immediate:r=!0}=t;f.useEffect(()=>{const o=()=>{try{e({__warmup:!0})}catch{}};r&&("requestIdleCallback"in window?requestIdleCallback(o):setTimeout(o,1));const n=s?setInterval(o,s):null;return()=>{n&&clearInterval(n)}},[e,s,r])}const xb=e=>_.jsx("option",{title:e.id,value:e.format,children:e.format},e.id),Lb=(e=xb)=>{const[t,s]=f.useState([]),[r,o]=f.useState(),{model:n,ready:i}=V({modelType:Z.type,modelId:Z.type,options:{}});f.useEffect(()=>{const c=j(()=>{s((n==null?void 0:n.dateFormatOptions.map(e))||[])});return()=>{c()}},[n,i,e]),f.useEffect(()=>{const c=j(()=>{n!=null&&n.dateFormatId&&(n!=null&&n.selectedDateFormat)&&o({id:n==null?void 0:n.dateFormatId,value:n==null?void 0:n.selectedDateFormat})});return()=>{c()}},[n==null?void 0:n.selectedDateFormat,n==null?void 0:n.dateFormatId]);const a=f.useCallback(c=>{var u;let d="";typeof c=="string"?d=c:(u=c==null?void 0:c.target)!=null&&u.value&&(d=c.target.value),d&&(n==null||n.setSelectedDateFormat(d))},[n]);return{raw:(n==null?void 0:n.dateFormatOptions.map(c=>c.id))??[],regionModel:n,selectedDateFormat:(r==null?void 0:r.value)||"",dateFormatId:(r==null?void 0:r.id)||"",updateDateFormat:a,props:{onChange:a,value:(r==null?void 0:r.id)||"",options:t}}},Fb=e=>_.jsx("option",{title:e,value:e,children:e},e),bd="kos:service:region:settings",wd="timeZone",kb=`${bd}-${wd}`,Nb=(e=Fb)=>{const[t,s]=f.useState([]),[r,o]=f.useState(""),{model:n,ready:i}=V({modelType:Z.type,modelId:Z.type,options:{}}),a=je.factory(kb)({path:bd,attribute:wd});f.useEffect(()=>{const d=j(()=>{s((n==null?void 0:n.timeZones.map(e))||[]),n!=null&&n.timeZones.length&&Kr(n==null?void 0:n.timeZones[0])});return()=>{d()}},[n,i,e]),f.useEffect(()=>{const d=j(()=>{o(a.value||"")});return()=>{d()}},[a.value]);const c=f.useCallback(d=>{var h;let u="factory";typeof d=="string"?u=d:(h=d==null?void 0:d.target)!=null&&h.value&&(u=d.target.value),u&&Kr(u)},[]);return{options:t,raw:(n==null?void 0:n.timeZones)??[],regionModel:n,selectedTimeZone:r,timeZones:(n==null?void 0:n.timeZones)??[],updateTimeZone:c,selectProps:{onChange:c,value:r,options:t}}},vd="kos:service:region",Md="regionId",Ub=`${vd}-${Md}`,jb=e=>_.jsx("option",{title:e,value:e,children:e},e),Ed=(e=jb)=>{const[t,s]=f.useState([]),[r,o]=f.useState("factory"),{model:n,ready:i}=V({modelType:Z.type,modelId:Z.type,options:{}}),a=je.factory(Ub)({path:vd,attribute:Md});f.useEffect(()=>{const d=j(()=>{s((n==null?void 0:n.availableRegions.map(e))||[])});return()=>{d()}},[n,i,e]),f.useEffect(()=>{const d=j(()=>{o(a.value||"factory")});return()=>{d()}},[a.value]);const c=f.useCallback(d=>{var h;let u="factory";typeof d=="string"?u=d:(h=d==null?void 0:d.target)!=null&&h.value&&(u=d.target.value),u&&Tl(u)},[]);return{raw:(n==null?void 0:n.availableRegions)??[],regionModel:n,regionData:n==null?void 0:n.selectedRegion,selectedRegion:r,updateRegion:c,regionSelectProps:{onChange:c,value:r,options:t}}},Bb=e=>_.jsx("option",{title:e.id,value:e.format,children:e.format},e.id),Kb=(e=Bb)=>{const[t,s]=f.useState([]),[r,o]=f.useState(),{model:n,ready:i}=V({modelType:Z.type,modelId:Z.type,options:{}});f.useEffect(()=>{const c=j(()=>{s((n==null?void 0:n.timeFormatOptions.map(e))||[])});return()=>{c()}},[n,i,e]),f.useEffect(()=>{const c=j(()=>{n!=null&&n.timeFormatId&&(n!=null&&n.selectedTimeFormat)&&o({id:n==null?void 0:n.timeFormatId,value:n==null?void 0:n.selectedTimeFormat})});return()=>{c()}},[n==null?void 0:n.selectedTimeFormat,n==null?void 0:n.timeFormatId]);const a=f.useCallback(c=>{var u;let d="";typeof c=="string"?d=c:(u=c==null?void 0:c.target)!=null&&u.value&&(d=c.target.value),d&&(n==null||n.setSelectedTimeFormat(d))},[n]);return{raw:(n==null?void 0:n.timeFormatOptions.map(c=>c.id))??[],regionModel:n,selectedTimeFormat:(r==null?void 0:r.value)??"",timeFormatId:(r==null?void 0:r.id)??"",updateTimeFormat:a,props:{onChange:a,value:(r==null?void 0:r.id)??"",options:t}}},Hb=(e,t)=>f.useMemo(()=>go(e),t),Gb={config:{attributes:!0,childList:!0,subtree:!0}};function zb(e,t,s=Gb){const[r,o]=f.useState(null);f.useEffect(()=>{if(!t||typeof t!="function")throw new Error("A valid callback function is required");const n=new MutationObserver(t);o(n)},[t,s,o]),f.useEffect(()=>{if(!r)return()=>{};if(!e)throw new Error("A valid DOM element is required");const{config:n}=s;try{r.observe(e,n)}catch(i){p.error(i)}return()=>{r&&r.disconnect()}},[r,e,s])}const _d={validateStart:function(e){return!0},validateStop:function(e){const t=e.event.currentTarget.getBoundingClientRect(),[s,r]=e.xy;return s<t.left||s>t.right||r<t.top||r>t.bottom}},Or=p.createLogger({name:"usePressGesture",group:"kos-hooks"});function Vb({onPressed:e,onRelease:t,intersectionStrategy:s=_d}){const r=f.useRef(!1),o=xd.useGesture({onDragStart:c=>{Or.info("onDragStart",c.type),s.validateStart(c)&&(e&&e(),r.current=!0)},onDrag:c=>{Or.info("onDrag",c.type),r.current&&s.validateStop(c)&&(t&&t(),r.current=!1)},onDragEnd:c=>{Or.info("onDragEnd",c.type),r.current&&t&&(t(),r.current=!1)}}),n=()=>{e&&e(),r.current=!0},i=()=>{r.current&&t&&(t(),r.current=!1)},a=()=>{r.current&&t&&(t(),r.current=!1)};return{dom:o,mesh:()=>({onPointerDown:n,onPointerUp:i,onPointerOut:a})}}const Id=()=>{const[e,t]=f.useState(!1),s=I.getInstance();return f.useEffect(()=>{const r=j(()=>{s&&s.reloading!==e&&t(s.reloading)});return()=>{r()}},[s,e]),[e]};function Td(e=!1,t="2-digit"){return f.useMemo(()=>{const s=e?12:24;return Array.from({length:s},(r,o)=>{const n=e&&o===0?12:o%s;return{id:o,label:t==="2-digit"?n.toString().padStart(2,"0"):n.toString()}})},[t,e])}function Gr(e,t="2-digit",s=0,r=0){return f.useMemo(()=>Array.from({length:e},(o,n)=>{const i=String(n+s);return{id:n+r,label:t==="2-digit"?i.padStart(2,"0"):i}}),[e,s,r,t])}function Od(e="en-US"){return f.useMemo(()=>["AM","PM"].map(t=>{const s=new Intl.DateTimeFormat(e,{hour:"2-digit",hour12:!0}).formatToParts(new Date().setHours(t==="AM"?0:12))[2].value;return{id:s,label:s}}),[e])}function Sd({formatOptions:{hour12:e=!0,hour:t="2-digit",minute:s="2-digit",second:r="2-digit"}={hour12:!0,hour:"2-digit",minute:"2-digit",second:"2-digit"},locale:o="en-US"}){const n=Td(e,t),i=Gr(60,s),a=Gr(60,r),c=Od(o);return{hourOptions:n,minuteOptions:i,secondOptions:a,amPmOptions:c}}function $d(e,t){return Ie.format(e,t)}function Dd({formatOptions:e,initialDate:t=new Date,locale:s="en-US",format:r="HH:mm"}){const[o,n]=f.useState(t),i=f.useCallback(w=>{n(E=>{const T=new Date(E);return T.setHours(Number(w)),T})},[]),a=f.useCallback(w=>{n(E=>{const T=new Date(E);return T.setMinutes(Number(w)),T})},[]),c=f.useCallback(w=>{n(E=>{const T=new Date(E);return T.setSeconds(Number(w)),T})},[]),d=f.useCallback(w=>{const E=new Date(w);n(E)},[]),u=$d(o,r),{hourOptions:h,minuteOptions:g,secondOptions:m,amPmOptions:v}=Sd({formatOptions:e,locale:s});return{amPmOptions:v,formattedTime:u,hourOptions:h,minuteOptions:g,secondOptions:m,setHours:i,setMinutes:a,setSeconds:c,setTime:d,time:new Date(o)}}const Yb=e=>{const{regionModel:t}=Ed(),s=f.useMemo(()=>({hour12:t==null?void 0:t.is12HourTimeFormat}),[t==null?void 0:t.is12HourTimeFormat]);return Dd({...e,locale:t==null?void 0:t.regionId,format:t==null?void 0:t.selectedTimeFormat,formatOptions:s})};function qb(e){return t=>{const[s]=Id();return s?_.jsx(xl,{message:"Wait a moment while your project reloads..."}):_.jsx(e,{...t})}}const kn=p.createLogger({name:"studio-properties-service",group:"Services"}),Wb="/api/kos/studio/properties",Cd=async e=>{if(kn.debug("sending GET for studio-properties"),!e)throw kn.error("connectionId is undefined"),new Error("connectionId is undefined");return await De.get(Wb,{},{destinationAddress:e,timeout:500})},Zb=Object.freeze(Object.defineProperty({__proto__:null,getStudioProperties:Cd},Symbol.toStringTag,{value:"Module"}));var Jb=Object.defineProperty,Xb=Object.getOwnPropertyDescriptor,Qb=(e,t,s,r)=>{for(var o=r>1?void 0:r?Xb(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&Jb(t,s,o),o};const Ad="studio-properties-model",ew="/kos/studio/properties",Nn={"kos.studio.tool.legacy":1};let zr=class{constructor(e,t,s){l(this,"id");l(this,"connectionId");l(this,"unsubscribe",null);l(this,"logger");l(this,"data");this.id=e,this.logger=s.logger,this.data=Te(),this.connectionId=t.connectionId}async init(){this.logger.debug(`initializing studio-properties ${this.id}`)}async load(){this.logger.debug(`loading studio-properties ${this.id}`)}async terminatePropertiesSession(){var e;(e=this.unsubscribe)==null||e.call(this)}async initializePropertiesSession(){this.unsubscribe=Xt.getInstance().subscribeTopic({topic:ew,destinationAddress:this.connectionId,callback:s=>{this.logger.error(`Received studio-properties message for connection ${this.connectionId}: ${JSON.stringify(s)}`)}});const[e,t]=await Cd(this.connectionId);if(e){this.logger.error(`Error loading studio-properties: ${e}`),this.data.setValues(Nn);return}if(t){const s=Object.keys(t).reduce((r,o)=>(r[o]=t[o]??o,r),{});this.data.setValues(s??Nn),p.ifDebug(()=>this.logger.debug(`studio-properties loaded: ${JSON.stringify(s)}`))}}get(e){return this.data[e]}createObservableProperty(e){return go(()=>this.get(e))}};zr=Qb([C(Ad)],zr);const tw=new ge({class:zr,type:Ad});Object.defineProperty(exports,"makeAutoObservable",{enumerable:!0,get:()=>M.makeAutoObservable});Object.defineProperty(exports,"makeObservable",{enumerable:!0,get:()=>M.makeObservable});Object.defineProperty(exports,"kosComponent",{enumerable:!0,get:()=>Yr.observer});exports.AuthState=Ea;exports.BrowserKosRouter=Ra;exports.BrowserRouter=nr;exports.CanvasDispatcher=tt;exports.CanvasDispatcherServices=Wp;exports.CanvasRenderer=Fo;exports.CanvasStreamer=Zy;exports.CanvasStreamerBase=Vl;exports.ChildModels=Dt;exports.CompanionDecoratorMixin=vl;exports.ConfigBean=Nt;exports.CoreExtensionManager=Vm;exports.CoreModels=Go;exports.CreateModelTranslationsContext=Bl;exports.CreateModelTranslationsProvider=Sy;exports.DateDisplayFormat=pd;exports.DateHelpers=Zd;exports.DependencyLifecycle=B;exports.DependencyModels=F;exports.Device=Gs;exports.DeviceServices=gm;exports.DomIntersectionStrategy=_d;exports.EVENT_KOS_MODEL_READY=Jr;exports.EVENT_TROUBLE_ADDED=Ef;exports.EVENT_TROUBLE_REMOVED=_f;exports.EXTENSION_CANVAS_RENDERER=ue;exports.EXTENSION_TROUBLE_DATA_MAPPER=Ps;exports.EXTENSION_TROUBLE_MAPPER=rs;exports.ErrorBoundaryWithFallback=Ll;exports.EventBus=Nd;exports.EventBusFunctional=jd;exports.EventBusState=Kd;exports.ExtensionManager=$;exports.FUTURE_CONTAINER_MODEL_TYPE=ic;exports.FUTURE_MODEL_TYPE=Za;exports.FUTURE_NOT_ASSIGNED=mo;exports.FeatureFlagService=vi;exports.FetchError=ne;exports.FutureContainerFactory=Se;exports.FutureContainerModel=cc;exports.FutureEndState=Oe;exports.FutureFactory=ct;exports.FutureHandler=rr;exports.FutureManager=Fe;exports.FutureModel=sc;exports.FutureService=$t;exports.HEADER_CACHE_CONTROL=Gn;exports.HEADER_CONTENT_TYPE=Hn;exports.HEADER_DESTINATION_ADDR=Me;exports.HEADER_FOS_REQUEST_ID=zn;exports.HEADER_METHOD=qs;exports.HEADER_ORDERED=Wr;exports.HEADER_REQUEST_ID=Zt;exports.HEADER_REQUEST_TYPE=pe;exports.HEADER_RESPONSE_ID=Ws;exports.HEADER_SOURCE_ADDR=Kn;exports.HEADER_TOPIC=Bn;exports.HEADER_URL=ot;exports.HEADER_WORK_TRACKER=Zr;exports.KOS_MODEL_ID=_s;exports.KeyValue=$o;exports.KeyValueServices=bg;exports.Kos=J;exports.KosConfigPropertySpec=je;exports.KosContainerIndex=fo;exports.KosContextBean=Da;exports.KosContextManager=N;exports.KosCore=I;exports.KosCoreModelPropertyMapper=de;exports.KosDataContainer=Ca;exports.KosDependencyTypes=hu;exports.KosExtensionUtils=mh;exports.KosFeatureFlags=Jd;exports.KosFetchMethods=Xi;exports.KosGlobalConfig=io;exports.KosLog=p;exports.KosMockEvents=qn;exports.KosModel=ua;exports.KosModelCollectionProvider=Ey;exports.KosModelContainer=me;exports.KosModelContext=ur;exports.KosModelEvents=A;exports.KosModelFactory=xt;exports.KosModelFutureContainerMixin=ns;exports.KosModelLoader=Ul;exports.KosModelLoaderDisplay=jl;exports.KosModelManager=ga;exports.KosModelProvider=Fl;exports.KosModelRegistrationFactory=ge;exports.KosModelRegistry=Br;exports.KosModelState=b;exports.KosModelSymbol=Ui;exports.KosModelVisitor=Vh;exports.KosObservableData=Ta;exports.KosRegistration=pf;exports.KosSingletonRegistration=mf;exports.KosTime=Cs;exports.KosTimeContext=Zo;exports.KosTimeProvider=Ly;exports.KosTimeServices=Eg;exports.KosTimer=Ol;exports.KosToken=Aa;exports.KosTranslationProvider=Ky;exports.KosTranslations=Wc;exports.KosWSTransportStatus=da;exports.KosWsEvents=Jt;exports.LOGIN_HOST=Vn;exports.LOGIN_URL=Ld;exports.LoadingMessage=xl;exports.LogBlock=Ht;exports.LogBlockContainer=ar;exports.LogConfig=At;exports.LogStream=Ft;exports.LogStreamContainer=ss;exports.LogStreamServices=Pg;exports.MODEL_DELETION_DELAY=fa;exports.MiddlewareChain=Ia;exports.ModelEffects=xe;exports.MultipleFutureHandler=Zf;exports.NestedModelContext=hr;exports.NetworkInterface=jo;exports.NetworkInterfaceContainer=Yt;exports.NetworkInterfaceServices=Im;exports.ObservableData=Te;exports.Ota=Ls;exports.OutsideAlerter=nb;exports.PLUGIN_EXTENSION_NAME=yh;exports.PORT=Yn;exports.PROFILE_LOG_DEBUG=Ti;exports.PROFILE_LOG_INFO=Oi;exports.PROFILE_RELAX_STORE_VALIDATION=Qd;exports.PROFILE_TOOLS_PREVIEW=Ii;exports.ParentModel=Ct;exports.PluginExtensionManager=bh;exports.ProgressBar=by;exports.ReferenceConfig=ys;exports.RegionInfo=Z;exports.RegionServices=Pf;exports.RegistrationManager=D;exports.Registry=Gm;exports.STATUS=qr;exports.ServiceFactory=X;exports.SingletonKosModelRegistrationFactory=Ee;exports.SoftwareInfo=Fs;exports.SoftwareInfoContext=Xo;exports.SoftwareInfoProvider=Ny;exports.SoftwareInfoServices=pp;exports.StateBean=zt;exports.StateBeanServices=Mp;exports.StateProp=Ro;exports.StatePropServices=Ap;exports.StorageDevice=Vs;exports.StorageDeviceContainer=st;exports.StorageDeviceServices=Dm;exports.StudioProperties=tw;exports.StudioPropertiesServices=Zb;exports.SubscriptionHandlers=W;exports.TIMER_END=Yo;exports.TIMER_EVENT=zo;exports.TOPIC_TIMER_TICK_EVENT=Vo;exports.TimerManager=Sl;exports.TokenContext=zl;exports.TokenProvider=jy;exports.Topics=Lt;exports.Trans=gb;exports.TransitionMap=bs;exports.Transitions=ao;exports.Translation=Us;exports.TranslationContainer=ve;exports.TranslationContainerContext=Qo;exports.TranslationContext=Kp;exports.TransportFactory=Cr;exports.Trouble=Gt;exports.TroubleContainer=Qe;exports.TroubleServices=Qg;exports.Troubles=oe;exports.UsbUpdate=Ho;exports.UsbUpdateContainer=Wt;exports.UsbUpdateServices=Nm;exports.WS_EVENT_TYPE=Zc;exports.WebSocketEvents=Pt;exports.WebSocketTransport=Xt;exports.WsEventFactory=xo;exports.acceptOrgInvitation=Pl;exports.addDaysToDate=fi;exports.addFuture=Xa;exports.addMonthsToDate=hi;exports.api=rc;exports.applyMixins=Gd;exports.arraysEqual=zd;exports.buildConfigBeanModel=Of;exports.buildFuture=To;exports.buildFutureModel=ec;exports.cancelFuture=Qa;exports.checkAppsStarted=vf;exports.convert=Mo;exports.convertFileSizeRaw=Hd;exports.convertWithUnits=Uf;exports.createBaseMessage=ta;exports.createBroadcastMessageResponse=na;exports.createCancellablePromise=hy;exports.createClient=uo;exports.createFosBaseMessage=ea;exports.createHeaders=pt;exports.createKosHtpMessageResponse=ia;exports.createKosMessage=ra;exports.createKosMessageResponse=aa;exports.createKosModelFutureManager=Wm;exports.createLazyKosModelFutureManager=Zm;exports.createMessageBody=$e;exports.createModelDependency=Yi;exports.createOptionKey=fu;exports.createPropKey=ke;exports.createReadableStream=mt;exports.createStudioMessage=Qi;exports.createStudioMessageRequest=sa;exports.createStudioMessageResponse=oa;exports.debounce=wi;exports.deleteFuture=Ja;exports.destroyKosModel=Le;exports.evaluateScopes=ja;exports.executeChildrenModelLifecycle=Zi;exports.executeDependentModelLifecycle=gt;exports.executeListLifecycle=Wi;exports.fetchModel=eb;exports.findModel=Eh;exports.findModels=ya;exports.formatDate=mi;exports.formatDateSince=ui;exports.formatDateTime=bi;exports.formatTime=yi;exports.getAllKosCompanionModels=Ih;exports.getCalendarMonthArray=nd;exports.getCompanionMixin=El;exports.getConfigBean=Ua;exports.getDayStrings=id;exports.getDays=Sb;exports.getDaysArray=td;exports.getDaysInMonth=no;exports.getDependenciesByLifecycle=qi;exports.getFormattedDate=$b;exports.getFormattedMonth=Db;exports.getFormattedMonthsArray=tn;exports.getFormattedYear=le;exports.getFormattedYearsArray=od;exports.getFutures=rg;exports.getKosCompanionModel=_h;exports.getKosLocalizationDescriptor=Gc;exports.getKosMessageLogging=Ai;exports.getKosModel=ma;exports.getKosModelSync=Ue;exports.getKosModelType=Mh;exports.getKosSessionKey=$a;exports.getLastDayOfMonth=St;exports.getLocalizationDescriptor=Pp;exports.getLogLevel=Ci;exports.getLogMessageToStudio=Ri;exports.getMessageBody=Dr;exports.getMonthsArray=sd;exports.getObservableCompanions=Th;exports.getQueryParams=ie;exports.getStartedApps=Mf;exports.getTranslations=Hc;exports.getYearsArray=rd;exports.hasCompanionMixin=Ml;exports.hasDecimals=ka;exports.hasKosModelFutureSupport=Jm;exports.hasKosProfile=Sr;exports.hslStringToHex=Ei;exports.hslToHex=Mi;exports.initKosProvider=Dy;exports.inspectCompanionMixin=ey;exports.inspectFutureObservability=Xm;exports.isBoolean=bo;exports.isKosCompanionTypeFactory=ha;exports.isKosDataModel=Rt;exports.isKosLoggingEnabled=su;exports.isKosModel=ae;exports.isKosModelContainer=co;exports.isKosModelReady=Ts;exports.isLeapYear=oo;exports.isLocalRefId=lf;exports.isNumber=tr;exports.isPrintable=Pu;exports.isValidDate=Ot;exports.kosAction=Q;exports.kosAutoEffect=j;exports.kosChild=fe;exports.kosCompanion=Mu;exports.kosComputed=go;exports.kosConfigBean=sr;exports.kosConfigProperty=Wf;exports.kosContext=Eu;exports.kosDependency=Ne;exports.kosEffect=La;exports.kosFuture=qo;exports.kosLogger=_u;exports.kosModel=C;exports.kosModelEffect=ji;exports.kosObservable=po;exports.kosParentAware=er;exports.kosReference=Iu;exports.kosStateBean=iy;exports.kosStateProp=ay;exports.kosSubscribe=Tu;exports.kosTopicHandler=x;exports.kosWhen=Pr;exports.login=Cl;exports.mapConfigBeanModelToDto=Ga;exports.mapDataToModel=$r;exports.mapDtoToConfigBeanModel=Ka;exports.mapDtoToFutureModel=Io;exports.mapDtoToFutureOptions=_o;exports.mapUpdateDtoToConfigBeanModel=Ha;exports.modelEventTopicFactory=ki;exports.modelFactory=it;exports.modelTypeEventTopicFactory=Ni;exports.modifyConfigBean=Na;exports.modifyFuture=og;exports.pairedClientHeartbeat=Qh;exports.pipe=Sa;exports.preloadKosModel=$h;exports.processId=Wd;exports.processMiddleware=Wh;exports.registerCompanionModel=Sh;exports.registerCoreModels=bl;exports.registerExtensionPoint=Qs;exports.registerKosModel=wa;exports.registerLegacyModel=ba;exports.resetKosModel=pa;exports.resetPassword=Rl;exports.resolveBaseUrl=_a;exports.resolveChild=Ji;exports.resolveContainerDeltas=Vd;exports.resolveItemListDeltas=qd;exports.resolveKosCompanion=Ar;exports.resolveKosContext=hf;exports.resolveKosProfiles=$i;exports.resolveListDeltas=Yd;exports.resolveServiceUrl=ee;exports.resolveVariable=_i;exports.retryWithExponentialBackoff=tf;exports.sendAsyncIntent=bf;exports.sendBroadcastMessage=Xu;exports.sendIntent=yf;exports.sendKosHttpMessageResponse=la;exports.sendKosMessage=Wu;exports.sendKosMessageResponse=ca;exports.sendRequest=df;exports.sendStudioMessage=Ju;exports.sendStudioMessageRequest=Zu;exports.setupCompanionDecoratorMixin=Qm;exports.setupCompleteFutureSupport=wl;exports.setupMinimalFutureSupport=Ym;exports.startPasswordReset=Al;exports.stringComponentInsert=Jl;exports.studioAcceptOrgInvitation=uy;exports.studioLogin=cy;exports.studioResetPassword=dy;exports.studioStartPasswordReset=ly;exports.subscribeStore=ty;exports.syncPublish=uf;exports.transitionToActive=Hi;exports.transitionToInit=Vi;exports.transitionToLoad=zi;exports.transitionToReady=Gi;exports.transitionToUnload=Ru;exports.troubleByTypeReducer=Hp;exports.troubleDataFactory=xc;exports.unloadKosModel=vh;exports.updateCompanionModelRegistration=Jh;exports.updateModelRegistration=Zh;exports.updateRegion=Tl;exports.updateTimeZone=Kr;exports.useAmPmValues=Od;exports.useCalendarDayArray=gd;exports.useConfigBean=Ib;exports.useConfigProperty=ed;exports.useContextModel=vy;exports.useContextModelHierarchy=Nl;exports.useDateArrays=ad;exports.useDateProps=Ab;exports.useDateRelativeConfig=Rb;exports.useDateRelativeData=yd;exports.useDayNames=hd;exports.useDayOptions=ud;exports.useDays=rn;exports.useDevice=Yl;exports.useFormattedDate=fd;exports.useFormattedTime=$d;exports.useFunctionWarmup=Pb;exports.useHourValues=Td;exports.useKosCore=Hl;exports.useKosDateFormats=Lb;exports.useKosModel=V;exports.useKosRegions=Ed;exports.useKosTime=Wo;exports.useKosTimeContext=Fy;exports.useKosTimeFormats=Kb;exports.useKosTimeZones=Nb;exports.useKosTranslation=bb;exports.useKosTranslationContext=Hy;exports.useLocalComputed=Hb;exports.useModelFromHierarchy=Iy;exports.useMonths=ld;exports.useMonthsOptions=dd;exports.useMutationObserver=zb;exports.useNetworkInterfaceContainer=ql;exports.useOta=Wl;exports.usePressGesture=Vb;exports.useProjectReload=Id;exports.useRegionTimeProps=Yb;exports.useRegionalTimeDate=md;exports.useSoftwareInfo=Jo;exports.useSoftwareInfoContext=Uy;exports.useStateProperty=ib;exports.useStorageDeviceContainer=Zl;exports.useSuspenseData=Hr;exports.useTimeOptions=Sd;exports.useTimeProps=Dd;exports.useTimeValues=Gr;exports.useTimer=cb;exports.useTranslationContainer=Xl;exports.useTroubleContainerModel=en;exports.useTroubleModel=vb;exports.useTroublePresence=Mb;exports.useUsbUpdateContainer=Ql;exports.useYears=sn;exports.useYearsOptions=cd;exports.uuid=nt;exports.variableToHex=Xd;exports.waitForAppToStart=wf;exports.waitForAppsToStart=xa;exports.waitForRequest=ho;exports.whenReady=re;exports.withDevice=Qy;exports.withKosModelFutures=qm;exports.withKosTime=tb;exports.withNetworkInterfaceContainer=sb;exports.withOta=rb;exports.withProjectReloading=qb;exports.withSoftwareInfo=ky;exports.withStorageDeviceContainer=ab;exports.withTranslationContainer=wb;exports.withTroubleContainer=Eb;exports.withUsbUpdateContainer=_b;exports.wrapPromise=so;
|
|
194
194
|
//# sourceMappingURL=index.cjs.map
|