@kosdev-code/kos-ui-sdk 2.0.26 → 2.0.27
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/core/core/kosCore.d.ts.map +1 -1
- package/core/core/registration/model-registration.d.ts +1 -0
- package/core/core/registration/model-registration.d.ts.map +1 -1
- package/index.cjs +76 -98
- package/index.cjs.map +1 -1
- package/index.d.cts +1 -0
- package/index.d.ts +1 -0
- package/index.d.ts.map +1 -1
- package/index.js +3359 -3233
- package/index.js.map +1 -1
- package/models/index.d.ts +1 -0
- package/models/index.d.ts.map +1 -1
- package/models/models/browser-router/browser-router-model.d.ts.map +1 -1
- package/models/models/canvas-dispatcher/canvas-dispatcher-model.d.ts +12 -16
- package/models/models/canvas-dispatcher/canvas-dispatcher-model.d.ts.map +1 -1
- package/models/models/canvas-dispatcher/services/canvas-dispatcher-services.d.ts +1 -1
- package/models/models/canvas-dispatcher/services/canvas-dispatcher-services.d.ts.map +1 -1
- package/models/models/canvas-dispatcher/types/index.d.ts +18 -9
- package/models/models/canvas-dispatcher/utils/encode-frame.d.ts.map +1 -0
- package/models/models/canvas-dispatcher/utils/renderers/base/canvas-2d-renderer.d.ts +1 -0
- package/models/models/canvas-dispatcher/utils/renderers/base/canvas-2d-renderer.d.ts.map +1 -1
- package/models/models/canvas-dispatcher/utils/renderers/base/video-base-renderer.d.ts +2 -0
- package/models/models/canvas-dispatcher/utils/renderers/base/video-base-renderer.d.ts.map +1 -1
- package/models/models/canvas-dispatcher/utils/renderers/renderer-factory.d.ts +2 -7
- package/models/models/canvas-dispatcher/utils/renderers/renderer-factory.d.ts.map +1 -1
- package/models/models/canvas-renderer/canvas-renderer-model.d.ts +45 -0
- package/models/models/canvas-renderer/canvas-renderer-model.d.ts.map +1 -0
- package/models/models/canvas-renderer/canvas-renderer-registration.d.ts +87 -0
- package/models/models/canvas-renderer/canvas-renderer-registration.d.ts.map +1 -0
- package/models/models/canvas-renderer/index.d.ts +4 -0
- package/models/models/canvas-renderer/index.d.ts.map +1 -0
- package/models/models/canvas-renderer/types/index.d.ts +8 -0
- package/models/utils/core-registration-manager.d.ts.map +1 -1
- package/models/utils/extension-manager.d.ts +3 -1
- package/models/utils/extension-manager.d.ts.map +1 -1
- package/package.json +2 -2
- package/ui/features/canvas/components/canvas-streamer/canvas-streamer.d.ts +2 -0
- package/ui/features/canvas/components/canvas-streamer/canvas-streamer.d.ts.map +1 -1
- package/ui/features/canvas/components/index.d.ts +2 -0
- package/ui/features/canvas/components/index.d.ts.map +1 -0
- package/ui/features/canvas/hooks/canvas-dispatcher/use-canvas-dispatcher.d.ts.map +1 -1
- package/ui/features/canvas/index.d.ts +2 -0
- package/ui/features/canvas/index.d.ts.map +1 -0
- package/ui/features/index.d.ts +2 -0
- package/ui/features/index.d.ts.map +1 -0
- package/ui/index.d.ts +1 -0
- package/ui/index.d.ts.map +1 -1
- package/ui/features/canvas/utils/encode-frame.d.ts.map +0 -1
- /package/{ui/features/canvas → models/models/canvas-dispatcher}/utils/encode-frame.d.ts +0 -0
package/index.cjs
CHANGED
|
@@ -1,114 +1,80 @@
|
|
|
1
|
-
"use strict";var Ul=Object.defineProperty;var jl=(e,t,s)=>t in e?Ul(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var a=(e,t,s)=>(jl(e,typeof t!="symbol"?t+"":t,s),s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const T=require("loglevel"),w=require("mobx"),m=require("robot3"),pe=require("date-fns"),M=require("@emotion/react/jsx-runtime"),Bl=require("@emotion/styled"),Kl=require("react-dom"),Ie=require("@emotion/react"),g=require("react"),gn=require("mobx-react-lite"),Hl=require("@use-gesture/react"),Ps="method",fn="topic",We="url",jt="request-id",xs="response-id",So="status",ge="dst-addr",mn="src-addr",ie="type",Ao="ordered",Co="tracker",pn="Content-Type",yn="Cache-Control",bn="requestId",vn=process.env.KOS_LOGIN_URL||"http://localhost",wn=process.env.KOS_APP_PORT||"8080",Gl=`${vn}:${wn}`,ds="{MODEL_ID}";var Bt=(e=>(e.SEND="/ws/log/msg/send",e.RECEIVED="/ws/log/msg/receive",e))(Bt||{}),Mn=(e=>(e.MSG_RECEIVE="/mock/msg/receive",e))(Mn||{});const Ro="/kos/model/ready/";T.info("Initializing event bus");globalThis.kos=globalThis.kos||{};globalThis.kos.subscriptions=globalThis.kos.subscriptions||{};const L=globalThis.kos.subscriptions,Vl=()=>Symbol("eventKey");function Lo(e){return L[e]&&Object.getOwnPropertySymbols(L[e]).length>0}function j(e,t){const s=Vl();return L[e]||(T.debug(`Initializing subscription for ${e}`),L[e]={}),T.debug(`Subscribing to ${e} with id ${s.toString()}`),L[e][s]=t,{count:L[e]?Object.getOwnPropertySymbols(L[e]).length:0,unsubscribe:()=>(T.debug(`Unsubscribing from ${e} with id ${s.toString()}`),L[e]&&L[e][s]&&delete L[e][s],L[e]&&Object.getOwnPropertySymbols(L[e]).length===0&&delete L[e],{count:L[e]?Object.getOwnPropertySymbols(L[e]).length:0})}}function N(e,t,s={}){if(!L[e]||Object.getOwnPropertySymbols(L[e]).length===0)return T.debug(`No subscriptions for ${e}. Not publishing.`),{eventType:e,subscribers:0};const o=Object.getOwnPropertySymbols(L[e]).length;return Object.getOwnPropertySymbols(L[e]).forEach(r=>{if(s.sync){const n=s.sync;T.debug(`Performing sync publish for ${e} with sync id ${n}`),L[e][r]({body:t,headers:s}).then(i=>{T.debug(`Response recieved for ${n}, publishing back to source.`),N(n,i)})}else T.debug(`Performing async publish for ${e}`),L[e][r]({body:t,headers:s})}),{eventType:e,subscribers:o}}function Yl(){T.warn("Resetting event bus"),Object.keys(L).forEach(e=>delete L[e])}const zl=Object.freeze(Object.defineProperty({__proto__:null,hasEventSubscriptions:Lo,publish:N,reset:Yl,subscribe:j},Symbol.toStringTag,{value:"Module"})),ql=(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 Po(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 Ze(){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 Wl(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 Zl(e,t){const s=e??[],o=t??[];return s.length!==o.length?!1:s.every((r,n)=>r===o[n])}const xo=(e,t)=>{const s=e.map(n=>n.id);return t.map(n=>n.id).filter(n=>!s.includes(n))},Jl=({container:e,onAddItem:t,onRemoveItem:s,idMapper:o=r=>r})=>r=>{const n=r.map(o),c=xo(n,e.data).map(s).filter(Boolean);e.removeAll(c);const l=n.map(t).filter(Boolean);e.addAll(l)},Ql=({container:e,onAddItem:t,onRemoveItem:s,idMapper:o=r=>r})=>r=>{const n=r.map(o);xo(n,e.models).forEach(s),n.forEach(t)},Xl=({items:e,onAddItem:t,onRemoveItem:s,idMapper:o=r=>r})=>r=>{const n=r.map(o);xo(n,e).forEach(s),n.forEach(t)},ed=(e,t="parent-")=>{let s=e;return s.startsWith(t)&&(s=s.replace(t,"")),s},Rr=new Intl.RelativeTimeFormat(void 0,{numeric:"auto"}),Lr=[{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 En(e){let t=(e.getTime()-Date.now())/1e3;for(let s=0;s<=Lr.length;s++){const o=Lr[s];if(Math.abs(t)<o.amount)return Rr.format(Math.round(t),o.name);t/=o.amount}return Rr.format(Math.round(t),"years")}const ko=e=>e%4===0&&e%100!==0||e%400===0,Fo=(e,t)=>[31,ko(e)?29:28,31,30,31,30,31,31,30,31,30,31][t],_n=(e,t)=>{const s=new Date(e),o=e.getDate();return s.setDate(1),s.setMonth(s.getMonth()+t),s.setDate(Math.min(o,Fo(s.getFullYear(),s.getMonth()))),s},In=(e,t)=>{const s=new Date(e);return s.setDate(s.getDate()+t),s},je="en-US",Tn={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"}},$n={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"}},On=(e,{dateStyle:t="short",locales:s=je}={dateStyle:"short",locales:je})=>{const o=t==="short"?Tn.short:{dateStyle:t};return new Intl.DateTimeFormat(s,o).format(e)},Dn=(e,{locales:t=je,timeStyle:s="short"}={locales:je,timeStyle:"short"})=>{const o=$n[s];return new Intl.DateTimeFormat(t,o).format(e)},Sn=(e,{dateStyle:t="short",locales:s=je,timeStyle:o="short"}={dateStyle:"short",locales:je,timeStyle:"short"})=>{const r={...t&&Tn[t],...o&&$n[o]};return new Intl.DateTimeFormat(s,r).format(e)},td=Object.freeze(Object.defineProperty({__proto__:null,addDaysToDate:In,addMonthsToDate:_n,formatDate:On,formatDateSince:En,formatDateTime:Sn,formatTime:Dn,getDaysInMonth:Fo,isLeapYear:ko},Symbol.toStringTag,{value:"Module"}));function An(e,t,s=300){let o;return(...r)=>{clearTimeout(o),o=setTimeout(()=>{t.apply(e,r)},s)}}class Cn{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 Cn;const sd=window.KosFeatureFlags,ae=(e=null)=>(e||window.location.search.replace("?","")).split("&").map(t=>{const[s,o]=t.split("=");return[s,decodeURIComponent(o||"")]}).reduce((t,[s,o])=>(t[s]=o,t),{}),Rn=(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)}`},Ln=e=>{const s=new RegExp("hsl\\((\\d+),\\s+(\\d+)\\%,\\s+(\\d+)\\%\\)").exec(e);if(!s)throw Error("Invalid HSL string");return Rn(parseInt(s[1]),parseInt(s[2]),parseInt(s[3]))},Pn=(e,t)=>getComputedStyle(e).getPropertyValue(t),od=(e,t)=>Ln(Pn(e,t)),xn="studio.tools.preview",rd="studio.relax.store.validation",kn="studio.log.debug",Fn="studio.log.info",nd={profiles:[xn]};var hn;const id=((hn=globalThis.getKosConfig)==null?void 0:hn.call(globalThis))||JSON.stringify(nd),Nn=JSON.parse(id);globalThis.kosConfig=Nn;const No=Nn,Un=()=>No.profiles||[],co=e=>Un().includes(e),ad=()=>No.logging||!1,cd=(e,t)=>{const s={...e};return s.id&&delete s.id,s},lo=(e,t,s=cd)=>{const o=s(e,t);w.runInAction(()=>{Object.assign(t,o)})},Js=new Map,jn={addToDeletionQueue:(e,t)=>{const s=Js.get(e)||[];s.push(t),Js.set(e,s)},cancelDeletion:e=>{const t=Js.get(e);t&&t.forEach(s=>{clearTimeout(s)})}},ld=()=>{const e=co(kn),t=co(Fn);return e?"DEBUG":t?"INFO":void 0},Bn=()=>{const e=ae(),t=ld(),o=e.kosLogLevel??t??window.kosLogLevel??process.env.KOS_LOG_LEVEL;return o||"WARN"},Kn=()=>window.kosMessageLogging||process.env.KOS_MESSAGE_LOGGING==="true",Hn=()=>window.kosMessageStudioLogging||process.env.KOS_MESSAGE_STUDIO_LOGGING==="true",Gn="ws-log",dd=T.methodFactory,Vn=Kn(),ud=Hn();T.methodFactory=function(e,t,s){const o=dd(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!==Gn||Vn&&ud)&&globalThis.kosLog(`UI: ${c}${r}`)}};let Yn=Bn();T.setLevel(Yn);window.setKosLogLevel=e=>{Yn=e,T.setLevel(e)};const us=T.getLogger(Gn);window.enableKosMessageLog=()=>{us.setLevel(T.levels.INFO)};window.disableKosMessageLog=()=>{us.setLevel(T.levels.ERROR)};Vn?window.enableKosMessageLog():window.disableKosMessageLog();const hd=["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(";"),gd=["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(";"),qt=e=>t=>{T.getLevel()<=e&&t()},f={...T,ifDebug:qt(T.levels.DEBUG),ifInfo:qt(T.levels.INFO),ifWarn:qt(T.levels.WARN),ifError:qt(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");us.info(`%c⬆ ${t}`,hd)},wsReceive:(...e)=>{const t=String(e).replace(/\n/g,"\\n");us.info(`%c⬇ ${t}`,gd)}},fd=f.createLogger({name:"kos-dependency-manager"});class md{constructor(){a(this,"_usedByCache",new Map);a(this,"_usesCache",new Map)}add(t,s){jn.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?(fd.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||{}),O=(e=>(e.CREATE="create",e.INITIALIZE="init",e.LOAD="load",e.READY="ready",e.GO_ONLINE="go_online",e.GO_OFFLINE="go_offline",e.RESET="go_offline",e.UNLOAD="unload",e.FAILED="failed",e.GO_ACTIVE="go_active",e.GO_INACTIVE="go_inactive",e.TIMEOUT="timeout",e))(O||{});const Pr=f.createLogger({name:"kos-model-cache"});class pd{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?(Pr.debug("Returning cached preloaded models"),this._preloaded):(this._preloaded=this.preloadKeys.map(s=>(Pr.debug(`Preloading model: ${typeof s=="string"?s:s.modelType}`),t(s))).filter(s=>!!s),this._isPreloaded=!0,this._preloaded)}}const Qs=new Map,xr=new Map,Xs=new Map,eo=new Map,Uo=(e,t)=>{zn[e]=t},zn={indexExtension:{registerIndexExtension:(e,t)=>{const s=eo.get(e)||{};Object.assign(s,t),eo.set(e,t)},loadIndexExtensions:e=>eo.get(e)||{}},loader:{registerLoader:(e,t)=>{xr.set(e,t)},executeLoader:async(e,t)=>{const s=xr.get(e);if(s)return await s(t)}},propertyMapper:{registerPropertyMapper:(e,t)=>{Xs.set(e,t)},hasMapper:e=>Xs.has(e),executeMapper:(e,t,s)=>{const o=Xs.get(e);return o?o(t,s):""}},dataMapper:{registerDataMapper:(e,t)=>{const s=Qs.get(e)||[];s.push(t),Qs.set(e,s)},executeMapper:async(e,t,s)=>{const o=Qs.get(e);if(!o)return{};const r={};for(const n of o){const i=await n(t,s);Object.assign(r,i)}return r}}},C=zn;function qn(e,t){return`${Ro}${e}${t?`/${t}`:`/${e}`}`}function Wn(e){return`${Ro}${e}`}var k=(e=>(e.INIT="init",e.LOAD="load",e.READY="ready",e.ACTIVATE="activate",e.ONLINE="online",e))(k||{});const yd=Object.freeze(Object.defineProperty({__proto__:null,DependencyLifecycle:k},Symbol.toStringTag,{value:"Module"}));function kr(e){const t=[];return new Promise((s,o)=>{for(const{condition:r,onMatch:n}of e){const i=w.when(r,()=>{t.forEach(c=>c());try{n==null||n(),s()}catch(c){o(c)}});t.push(i)}})}const G=Symbol("SubscriptionHandlers"),P=Symbol("DependencyModels"),vt=Symbol("FutureService"),wt=Symbol("ChildModels"),Mt=Symbol("ParentModel"),Et=Symbol("LogConfig"),rs=Symbol("ReferenceConfig"),Zn=Symbol("KosModelSymbol"),$e=Symbol("ModelEffects"),ce=(e,t)=>{e[wt]=e[wt]||{},e[wt][t]=!0},Se=e=>`{PROP_${String(e)}}`,bd=e=>`{PROP_${String(e)}}`,vd=Se("kosParentId"),ks=e=>t=>{t[Mt]=t[Mt]||{};const s=(e==null?void 0:e.parentId)||vd;t[Mt]={parentId:s}},Be=({value:e,modelId:t,modelData:s})=>{let o=e;if(Array.isArray(o))return[...e];if(typeof o!="string"&&typeof o!="object")return o;if(typeof o=="object")o=Object.keys(o).reduce((r,n)=>(r[n]=Be({value:o[n],modelId:t,modelData:s}),r),{});else if(typeof o=="string"){const r=new RegExp(".*({PROP_(.+)})");let n=o!=null&&o.includes(ds)?o.replace(ds,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},wd=f.createLogger({name:"kos-model"});function Md(e,t,s){var n;const o=(n=e[Mt])==null?void 0:n.parentId;if(!o)return;const r=Be({value:o,modelData:s,modelId:t});r&&typeof r=="string"&&x.setParentContext(t,r)}function Ed(e){const t=e[vt];t&&Object.entries(t).forEach(([s,{handler:o}])=>{e[s]=o})}function _d(e,t){const s=e[P]||{};Object.entries(s).forEach(([o,r])=>{const n=Be({value:r.id||r.modelType,modelData:e,modelId:t}),i=Object.entries((r==null?void 0:r.options)||{}).reduce((c,[l,d])=>(c[l]=Be({value:d,modelData:e,modelId:t}),c),{});if(typeof n=="string"){if(!r.lazy){const c=_.getInstance().modelManager.createModelInstance(r.modelType,n,i);e[o]=c.data}_.getInstance().modelManager.addDependency(t,n)}})}function Id(e){try{return w.makeAutoObservable(e)}catch(t){return wd.error("Failed to make observable:",t),e}}const Td={construct(e,t){var c;const[s,o={}]=t,r=x.createContext(s);Md(e,s,o);const n=f.createLogger({name:e.prototype.modelTypeId,group:((c=e[Et])==null?void 0:c.group)??"kos-model"}),i=new e(s,o,{logger:n,kosContext:r});return Ed(i),_d(i,s),Id(i)}};function D(e){return t=>{var o,r;const s=t;return s.prototype.modelTypeId=e,s.prototype[Zn]=!0,(o=s.prototype)[G]??(o[G]={}),(r=s.prototype)[P]??(r[P]={}),f.ifDebug(()=>{f.debug(`Registering model with id ${e}`)}),new Proxy(s,Td)}}const $d=({modelType:e})=>t=>{ks()(t),D(e)(t)};function Od(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 Dd=({group:e}={group:""})=>t=>{t[Et]=t[Et]||{},t[Et]={group:e}};function Jn(e){return(t,s,o)=>{t[$e]=t[$e]||{},t[$e][s]={dependencies:e==null?void 0:e.dependencies,value:o.value},o.value=function(){throw new Error(`Method ${s} cannot be called directly.`)}}}const Sd=e=>(t,s)=>{t[rs]=t[rs]||{},t[rs][s]=e},Je=({modelType:e,id:t,options:s,lifecycle:o})=>(r,n)=>{r[P]=r[P]||{},r[P][n]={modelType:e,id:t,options:s,lifecycle:o||k.INIT}},Ad=({topic:e,handler:t,websocket:s=!1,condition:o=()=>!0})=>r=>{r[G]=r[G]||{},Array.isArray(e)?e.forEach(n=>{r[G][n]={websocket:s,handler:t,condition:o}}):r[G][e]={websocket:s,handler:An(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[G]=d[G]||{},Array.isArray(e)?e.forEach(p=>{d[G][p]={websocket:o,fos:r,bridge:n,handler:h.value,condition:t,transform:s,lifecycle:c,skipParse:i,destinationAddress:l}}):d[G][e]={websocket:o,fos:r,bridge:n,handler:h.value,condition:t,transform:s,lifecycle:c,skipParse:i,destinationAddress:l}}}const Qn=5e3;class Cd extends Error{constructor(s,o){super(s);a(this,"model");this.model=o}}const Xn=(e,t,s)=>{let o;return{promise:new Promise((i,c)=>{o=setTimeout(()=>{f.error(`Model ${t.modelId} - ${t.modelTypeName} - ${s} timed out after ${e}ms`),c(new Cd(`${t.modelId} - ${t.modelTypeName} - ${s}`,t))},e)}),cancel:()=>{o&&clearTimeout(o)}}},ei=e=>e.fsm.transitionTo(O.GO_ACTIVE,y.ACTIVE),ti=e=>e.whenReady(),si=e=>e.fsm.transitionTo(O.LOAD,y.LOADED),Rd=e=>e.fsm.transitionTo(O.UNLOAD,y.UNLOADED),oi=e=>e.fsm.transitionTo(O.INITIALIZE,y.INITIALIZED);var jo=(e=>(e.ACTIVE="active",e.READY="ready",e.LOAD="load",e.UNLOAD="unload",e.INIT="init",e))(jo||{});const ns={active:ei,ready:ti,load:si,init:oi},ri=(e,t)=>{const s=t.id||t.modelType,o=Be({value:s,modelData:e.modelData,modelId:e.modelId});f.debug(`activating dependent model ${t.modelType} with id ${o}`);const r=Object.keys((t==null?void 0:t.options)||{}).reduce((i,c)=>{const l=t.options[c];return i[c]=Be({value:l,modelData:e.modelData,modelId:e.modelId}),i},{});return{dependentModel:_.getInstance().modelManager.createModelInstance(t.modelType,o,r),dataModelId:o}},ni=(e,t=k.READY)=>{var r;const s=((r=e.modelData)==null?void 0:r[P])||{};return Object.keys(s).length===0?(f.debug(`${e.modelId} has no dependencies. Returning`),[]):Object.keys(s).filter(n=>s[n].lifecycle===t).map(n=>{const i=s[n],{dependentModel:c,dataModelId:l}=ri(e,i);e.modelData[n]=c.data,f.debug(`waiting for dependent model ${i.modelType} with id ${l} - waiting for WHENREADY`);const d=async(p,v,b)=>{var E;await((E=p.whenReady)==null?void 0:E.call(p)),f.debug(`dependent model ${v} with id ${b} - READY`)},{promise:u,cancel:h}=Xn(Qn,e,e.status);return Promise.race([d(c.model,i.modelType,l).then(()=>{h()}).catch(p=>{console.error(`Error waiting for dependent model ${i.modelType} with id ${l}:`,p),h()}),u])}).filter(n=>!!n)},ii=async(e,t,s,o)=>{if(f.debug(`Execute lifecycle with ${t.length} models`),t.length===0){f.debug(`${e.modelId} has no children. Returning`);return}if(!s){f.error(`${e.modelId} is not transitioning with a valid target ${s}`);return}const r=t.map(c=>{let l;return ns[s]&&c?l=ns[s](c):(c||f.error("model is undefined. This shouldn't happen"),ns[s]||f.error(`There is no promise in the Transition Map for ${s}`)),{promise:l,modelId:c==null?void 0:c.modelId,model:c,type:c==null?void 0:c.modelTypeName,status:c==null?void 0:c.status}}).filter(c=>c.promise?c.model?!0:(f.error(`No model found ${c.modelId}`),!1):(f.error(`No promise found ${c.modelId}`),!1)),i=(await Promise.allSettled(r.map(c=>{var u;const{promise:l,cancel:d}=Xn(Qn,c.model,c.status);return Promise.race([(u=c.promise)==null?void 0:u.then(()=>{d()}).catch(h=>{f.error(`Model ${c.modelId} - ${c.type} failed to transition to ${s}: ${h.message}`),d()}),l])}))).filter(c=>c.status==="rejected");i.length>0&&f.error(`Model ${e.modelId} had ${i.length} failed child models on ${o}`)},ai=async(e,t,s)=>{await ii(e,e.getChildren().filter(o=>!!o),t,s)},at=async(e,t)=>{const o=(await Promise.allSettled(ni(e,t))).filter(r=>r.status==="rejected");o.length&&(f.error(`There were ${o.length} failed dependent models on ${t}`),f.error(o))},Ld=e=>typeof e.toJSON=="function",_t=e=>e[P]!==void 0,Bo=e=>e.revision!==void 0&&e.index!==void 0,ci=e=>{if(e){if(_t(e))return e;if(Bo(e))return e.data;if(e instanceof Map||e instanceof w.ObservableMap||e instanceof Set)return Array.from(e.values()).filter(_t);if(Array.isArray(e))return e.filter(_t)}};function Pd(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}}}),xd(e.modelData,e.modelTypeName,e.modelId,e)}function xd(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[P]||{};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];_t(i)?r[`[KOS Model] ${n}`]=typeof i.toJSON=="function"?i.toJSON():{id:i.id,type:i.constructor.name}:Bo(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 kd{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[wt])||{};return Object.keys(t).map(o=>ci(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 Fd{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 Nd{constructor(t,s,o,r){a(this,"disposers",[]);this.modelTypeName=t,this.modelId=s,this.modelData=o,this.log=r}setup(){var s;const t=((s=this.modelData)==null?void 0:s[$e])||{};for(const o of Object.keys(t)){const{value:r,dependencies:n,options:i}=t[o],c=r.bind(this.modelData),l=()=>{this.log.info(`Running effect ${o} for ${this.modelTypeName} (${this.modelId})`),w.runInAction(()=>c())},d=n?w.reaction(()=>n(this.modelData),l,{fireImmediately:!!(i!=null&&i.fireImmediately)}):w.autorun(l);this.disposers.push(d)}}disposeAll(){for(const t of this.disposers)try{t()}catch(s){this.log.info(`Failed to dispose effect for ${this.modelId}`,s)}this.disposers=[]}}const Ud=f.createLogger({name:"model-active-machine"}),jd=e=>{const t=m.createMachine(y.INACTIVE,{[y.FAILED]:m.state(m.transition(O.GO_ACTIVE,y.ACTIVATING)),[y.INACTIVE]:m.state(m.transition(O.GO_ACTIVE,y.ACTIVATING)),[y.ACTIVATING]:m.invoke(()=>(e.activeStatus=y.ACTIVATING,e.activate()),m.transition("done",y.ACTIVE,m.action(()=>{e.activeStatus=y.ACTIVE})),m.transition("error",y.FAILED,m.action(()=>{e.activeStatus=y.FAILED}))),[y.ACTIVE]:m.state(m.transition(O.GO_INACTIVE,y.DEACTIVATING)),[y.DEACTIVATING]:m.invoke(()=>(e.activeStatus=y.DEACTIVATING,e.deactivate()),m.transition("done",y.INACTIVE,m.action(()=>{e.activeStatus=y.INACTIVE})),m.transition("error",y.FAILED,m.action(()=>{e.activeStatus=y.FAILED})))});return{service:m.interpret(t,o=>Ud.debug(o.machine.current)),machine:t}},Fr=f.createLogger({name:"model-online-machine"}),Bd=e=>{const t=m.createMachine(y.OFFLINE,{[y.ONLINE]:m.state(m.transition(O.GO_OFFLINE,y.OFFLINE,m.action(async()=>{await e.offline(),e.onlineStatus=y.OFFLINE}))),[y.OFFLINE]:m.state(m.transition(O.GO_ONLINE,y.ONLINE,m.action(async()=>{Fr.debug(`Going online with model ${e.modelId}`),await e.online(),e.onlineStatus=y.ONLINE,await e.fsm.transitionTo(O.INITIALIZE,y.INITIALIZED)})))}),s=m.interpret(t,o=>Fr.debug(o.machine.current));return{machine:t,service:s}},Kd=e=>{var o;const t=jd(e).service,s=Bd(e).service;return m.createMachine(y.CREATING,{[y.CREATING]:m.state(m.transition(O.CREATE,y.CREATED)),[y.CREATED]:m.state(m.immediate(y.INITIALIZING)),[y.INITIALIZING]:m.invoke(()=>(K(()=>{e.status=y.INITIALIZING}),e.init()),m.transition("done",y.INITIALIZED,m.action(()=>{e.status=y.INITIALIZED})),m.transition("error",y.FAILED,m.action(()=>{f.error(`Model ${e.modelId} - ${e.modelTypeName} failed to initialize. Transitioning to FAILED state.`),e.status=y.FAILED}))),[y.INITIALIZED]:m.state(m.immediate(y.LOADING)),[y.LOADING]:m.invoke(()=>(K(()=>{e.status=y.LOADING}),e.load()),m.transition("done",y.LOADED,m.action(()=>{e.status=y.LOADED})),m.transition("error",y.FAILED,m.action(()=>{e.status=y.FAILED}))),[y.LOADED]:m.state(m.immediate(y.READYING),m.transition(O.UNLOAD,y.UNLOADING)),[y.RESETTING]:m.invoke(()=>{var r;return K(()=>{e.status=y.RESETTING}),(r=e.unload)==null||r.call(e),e.load()},m.transition("done",y.LOADED,m.action(()=>{e.status=y.LOADED}))),[y.READYING]:m.invoke(()=>(K(()=>{e.status=y.READYING}),e.ready()),m.transition("done",y.READY,m.action(()=>{K(()=>{e.status=y.READY}),s.send(O.GO_ONLINE)})),m.transition("error",y.FAILED,m.action(()=>{e.status=y.FAILED}))),[y.READY]:m.state(m.transition(O.UNLOAD,y.UNLOADED,m.action((o=e.unload)==null?void 0:o.bind(e))),m.transition(O.RESET,y.RESETTING),m.transition(O.GO_ONLINE,y.READY,m.action(()=>{s.send(O.GO_ONLINE)})),m.transition(O.GO_OFFLINE,y.READY,m.action(()=>{s.send(O.GO_OFFLINE)})),m.transition(O.GO_ACTIVE,y.READY,m.action(()=>{t.send(O.GO_ACTIVE)})),m.transition(O.GO_INACTIVE,y.READY,m.action(()=>{t.send(O.GO_INACTIVE)}))),[y.UNLOADED]:m.state(),[y.FAILED]:m.state()})},Hd=f.createLogger({name:"kos-model-lifecycle"}),Gd=e=>({service:m.interpret(Kd(e),s=>Hd.debug(`state machine for model ${e.modelId}: ${s.machine.current});`))});class Vd{constructor(t,s){a(this,"disposer");a(this,"service");this.model=t,this.log=s;const o=Gd(t);this.service=o.service,this.service.send(O.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 Yd{static create({modelId:t,modelTypeName:s,component:o}){const r=[o??"kos",s,t].filter(Boolean).join(".");return f.createLogger({name:r})}}class zd{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 qd{constructor(t,s){a(this,"unsubscribers",[]);this.model=t,this.log=s}register(){const t=this.model.modelId,s=j("/kosCore/online",async()=>{this.log.debug(`Online event received for ${t}, waiting for readiness...`),await this.model.whenReady(),this.log.debug(`${t} is ready — sending GO_ONLINE`),await this.model.fsm.transitionTo(O.GO_ONLINE,y.ONLINE)}),o=j("/kosCore/offline",async()=>{this.log.debug(`Offline event received for ${t} — sending GO_OFFLINE`),await this.model.fsm.transitionTo(O.GO_OFFLINE,y.OFFLINE)});this.unsubscribers.push(s.unsubscribe),this.unsubscribers.push(o.unsubscribe)}dispose(){this.unsubscribers.forEach(t=>t()),this.unsubscribers=[]}}var li=(e=>(e.GET="GET",e.PUT="PUT",e.POST="POST",e.DELETE="DELETE",e))(li||{});const di=({path:e,requestId:t,method:s,destinationAddress:o})=>{let r=`${Ps}:${s}
|
|
1
|
+
"use strict";var Qd=Object.defineProperty;var Xd=(e,t,s)=>t in e?Qd(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var a=(e,t,s)=>(Xd(e,typeof t!="symbol"?t+"":t,s),s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const T=require("loglevel"),v=require("mobx"),m=require("robot3"),me=require("date-fns"),M=require("@emotion/react/jsx-runtime"),Po=require("@emotion/styled"),En=require("react-dom"),Ie=require("@emotion/react"),g=require("react"),ko=require("mobx-react-lite"),el=require("@use-gesture/react"),xs="method",In="topic",Je="url",Kt="request-id",Fs="response-id",xo="status",fe="dst-addr",Tn="src-addr",de="type",Fo="ordered",No="tracker",$n="Content-Type",On="Cache-Control",Dn="requestId",Sn=process.env.KOS_LOGIN_URL||"http://localhost",An=process.env.KOS_APP_PORT||"8080",tl=`${Sn}:${An}`,hs="{MODEL_ID}";var Gt=(e=>(e.SEND="/ws/log/msg/send",e.RECEIVED="/ws/log/msg/receive",e))(Gt||{}),Cn=(e=>(e.MSG_RECEIVE="/mock/msg/receive",e))(Cn||{});const Uo="/kos/model/ready/";T.info("Initializing event bus");globalThis.kos=globalThis.kos||{};globalThis.kos.subscriptions=globalThis.kos.subscriptions||{};const L=globalThis.kos.subscriptions,sl=()=>Symbol("eventKey");function jo(e){return L[e]&&Object.getOwnPropertySymbols(L[e]).length>0}function j(e,t){const s=sl();return L[e]||(T.debug(`Initializing subscription for ${e}`),L[e]={}),T.debug(`Subscribing to ${e} with id ${s.toString()}`),L[e][s]=t,{count:L[e]?Object.getOwnPropertySymbols(L[e]).length:0,unsubscribe:()=>(T.debug(`Unsubscribing from ${e} with id ${s.toString()}`),L[e]&&L[e][s]&&delete L[e][s],L[e]&&Object.getOwnPropertySymbols(L[e]).length===0&&delete L[e],{count:L[e]?Object.getOwnPropertySymbols(L[e]).length:0})}}function N(e,t,s={}){if(!L[e]||Object.getOwnPropertySymbols(L[e]).length===0)return T.debug(`No subscriptions for ${e}. Not publishing.`),{eventType:e,subscribers:0};const o=Object.getOwnPropertySymbols(L[e]).length;return Object.getOwnPropertySymbols(L[e]).forEach(r=>{if(s.sync){const n=s.sync;T.debug(`Performing sync publish for ${e} with sync id ${n}`),L[e][r]({body:t,headers:s}).then(i=>{T.debug(`Response recieved for ${n}, publishing back to source.`),N(n,i)})}else T.debug(`Performing async publish for ${e}`),L[e][r]({body:t,headers:s})}),{eventType:e,subscribers:o}}function ol(){T.warn("Resetting event bus"),Object.keys(L).forEach(e=>delete L[e])}const rl=Object.freeze(Object.defineProperty({__proto__:null,hasEventSubscriptions:jo,publish:N,reset:ol,subscribe:j},Symbol.toStringTag,{value:"Module"})),nl=(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 Bo(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 Qe(){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 il(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 al(e,t){const s=e??[],o=t??[];return s.length!==o.length?!1:s.every((r,n)=>r===o[n])}const Ko=(e,t)=>{const s=e.map(n=>n.id);return t.map(n=>n.id).filter(n=>!s.includes(n))},cl=({container:e,onAddItem:t,onRemoveItem:s,idMapper:o=r=>r})=>r=>{const n=r.map(o),c=Ko(n,e.data).map(s).filter(Boolean);e.removeAll(c);const d=n.map(t).filter(Boolean);e.addAll(d)},dl=({container:e,onAddItem:t,onRemoveItem:s,idMapper:o=r=>r})=>r=>{const n=r.map(o);Ko(n,e.models).forEach(s),n.forEach(t)},ll=({items:e,onAddItem:t,onRemoveItem:s,idMapper:o=r=>r})=>r=>{const n=r.map(o);Ko(n,e).forEach(s),n.forEach(t)},ul=(e,t="parent-")=>{let s=e;return s.startsWith(t)&&(s=s.replace(t,"")),s},jr=new Intl.RelativeTimeFormat(void 0,{numeric:"auto"}),Br=[{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 Rn(e){let t=(e.getTime()-Date.now())/1e3;for(let s=0;s<=Br.length;s++){const o=Br[s];if(Math.abs(t)<o.amount)return jr.format(Math.round(t),o.name);t/=o.amount}return jr.format(Math.round(t),"years")}const Go=e=>e%4===0&&e%100!==0||e%400===0,Ho=(e,t)=>[31,Go(e)?29:28,31,30,31,30,31,31,30,31,30,31][t],Ln=(e,t)=>{const s=new Date(e),o=e.getDate();return s.setDate(1),s.setMonth(s.getMonth()+t),s.setDate(Math.min(o,Ho(s.getFullYear(),s.getMonth()))),s},Pn=(e,t)=>{const s=new Date(e);return s.setDate(s.getDate()+t),s},Be="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"}},xn={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"}},Fn=(e,{dateStyle:t="short",locales:s=Be}={dateStyle:"short",locales:Be})=>{const o=t==="short"?kn.short:{dateStyle:t};return new Intl.DateTimeFormat(s,o).format(e)},Nn=(e,{locales:t=Be,timeStyle:s="short"}={locales:Be,timeStyle:"short"})=>{const o=xn[s];return new Intl.DateTimeFormat(t,o).format(e)},Un=(e,{dateStyle:t="short",locales:s=Be,timeStyle:o="short"}={dateStyle:"short",locales:Be,timeStyle:"short"})=>{const r={...t&&kn[t],...o&&xn[o]};return new Intl.DateTimeFormat(s,r).format(e)},hl=Object.freeze(Object.defineProperty({__proto__:null,addDaysToDate:Pn,addMonthsToDate:Ln,formatDate:Fn,formatDateSince:Rn,formatDateTime:Un,formatTime:Nn,getDaysInMonth:Ho,isLeapYear:Go},Symbol.toStringTag,{value:"Module"}));function jn(e,t,s=300){let o;return(...r)=>{clearTimeout(o),o=setTimeout(()=>{t.apply(e,r)},s)}}class Bn{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 Bn;const gl=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),{}),Kn=(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)}`},Gn=e=>{const s=new RegExp("hsl\\((\\d+),\\s+(\\d+)\\%,\\s+(\\d+)\\%\\)").exec(e);if(!s)throw Error("Invalid HSL string");return Kn(parseInt(s[1]),parseInt(s[2]),parseInt(s[3]))},Hn=(e,t)=>getComputedStyle(e).getPropertyValue(t),fl=(e,t)=>Gn(Hn(e,t)),Vn="studio.tools.preview",pl="studio.relax.store.validation",Yn="studio.log.debug",zn="studio.log.info",ml={profiles:[Vn]};var _n;const yl=((_n=globalThis.getKosConfig)==null?void 0:_n.call(globalThis))||JSON.stringify(ml),qn=JSON.parse(yl);globalThis.kosConfig=qn;const Vo=qn,Wn=()=>Vo.profiles||[],fo=e=>Wn().includes(e),bl=()=>Vo.logging||!1,vl=(e,t)=>{const s={...e};return s.id&&delete s.id,s},po=(e,t,s=vl)=>{const o=s(e,t);v.runInAction(()=>{Object.assign(t,o)})},eo=new Map,Zn={addToDeletionQueue:(e,t)=>{const s=eo.get(e)||[];s.push(t),eo.set(e,s)},cancelDeletion:e=>{const t=eo.get(e);t&&t.forEach(s=>{clearTimeout(s)})}},wl=()=>{const e=fo(Yn),t=fo(zn);return e?"DEBUG":t?"INFO":void 0},Jn=()=>{const e=ee(),t=wl(),o=e.kosLogLevel??t??window.kosLogLevel??process.env.KOS_LOG_LEVEL;return o||"WARN"},Qn=()=>window.kosMessageLogging||process.env.KOS_MESSAGE_LOGGING==="true",Xn=()=>window.kosMessageStudioLogging||process.env.KOS_MESSAGE_STUDIO_LOGGING==="true",ei="ws-log",Ml=T.methodFactory,ti=Qn(),_l=Xn();T.methodFactory=function(e,t,s){const o=Ml(e,t,s);return function(r,n){var d;const i=s?String(s):"",c=i?`[${String(i).substring(i.lastIndexOf(":")+1)}] | `:"[root] | ";o(`${c}${r}`,n||""),(d=globalThis==null?void 0:globalThis.kosConfig)!=null&&d.logging&&globalThis.kosLog&&(s!==ei||ti&&_l)&&globalThis.kosLog(`UI: ${c}${r}`)}};let si=Jn();T.setLevel(si);window.setKosLogLevel=e=>{si=e,T.setLevel(e)};const gs=T.getLogger(ei);window.enableKosMessageLog=()=>{gs.setLevel(T.levels.INFO)};window.disableKosMessageLog=()=>{gs.setLevel(T.levels.ERROR)};ti?window.enableKosMessageLog():window.disableKosMessageLog();const El=["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(";"),Il=["color: black","display: block","padding: 4px","background-color: yellow","margin: 0","text-shadow: 0 1px 0 rgba(0, 0, 0, 0.3)","box-shadow: 0 1px 0 rgba(255, 255, 255, 0.4) inset, 0 5px 3px -5px rgba(0, 0, 0, 0.5), 0 -13px 5px -10px rgba(255, 255, 255, 0.4) inset","font-weight: bold"].join(";"),Zt=e=>t=>{T.getLevel()<=e&&t()},f={...T,ifDebug:Zt(T.levels.DEBUG),ifInfo:Zt(T.levels.INFO),ifWarn:Zt(T.levels.WARN),ifError:Zt(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");gs.info(`%c⬆ ${t}`,El)},wsReceive:(...e)=>{const t=String(e).replace(/\n/g,"\\n");gs.info(`%c⬇ ${t}`,Il)}},Tl=f.createLogger({name:"kos-dependency-manager"});class $l{constructor(){a(this,"_usedByCache",new Map);a(this,"_usesCache",new Map)}add(t,s){Zn.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?(Tl.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 Kr=f.createLogger({name:"kos-model-cache"});class Ol{constructor(t=[]){a(this,"_modelsById",v.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?(Kr.debug("Returning cached preloaded models"),this._preloaded):(this._preloaded=this.preloadKeys.map(s=>(Kr.debug(`Preloading model: ${typeof s=="string"?s:s.modelType}`),t(s))).filter(s=>!!s),this._isPreloaded=!0,this._preloaded)}}const to=new Map,Gr=new Map,so=new Map,oo=new Map,Yo=(e,t)=>{oi[e]=t},oi={indexExtension:{registerIndexExtension:(e,t)=>{const s=oo.get(e)||{};Object.assign(s,t),oo.set(e,t)},loadIndexExtensions:e=>oo.get(e)||{}},loader:{registerLoader:(e,t)=>{Gr.set(e,t)},executeLoader:async(e,t)=>{const s=Gr.get(e);if(s)return await s(t)}},propertyMapper:{registerPropertyMapper:(e,t)=>{so.set(e,t)},hasMapper:e=>so.has(e),executeMapper:(e,t,s)=>{const o=so.get(e);return o?o(t,s):""}},dataMapper:{registerDataMapper:(e,t)=>{const s=to.get(e)||[];s.push(t),to.set(e,s)},executeMapper:async(e,t,s)=>{const o=to.get(e);if(!o)return{};const r={};for(const n of o){const i=await n(t,s);Object.assign(r,i)}return r}}},C=oi;function ri(e,t){return`${Uo}${e}${t?`/${t}`:`/${e}`}`}function ni(e){return`${Uo}${e}`}var x=(e=>(e.INIT="init",e.LOAD="load",e.READY="ready",e.ACTIVATE="activate",e.ONLINE="online",e))(x||{});const Dl=Object.freeze(Object.defineProperty({__proto__:null,DependencyLifecycle:x},Symbol.toStringTag,{value:"Module"}));function Hr(e){const t=[];return new Promise((s,o)=>{for(const{condition:r,onMatch:n}of e){const i=v.when(r,()=>{t.forEach(c=>c());try{n==null||n(),s()}catch(c){o(c)}});t.push(i)}})}const G=Symbol("SubscriptionHandlers"),P=Symbol("DependencyModels"),wt=Symbol("FutureService"),Mt=Symbol("ChildModels"),_t=Symbol("ParentModel"),Et=Symbol("LogConfig"),is=Symbol("ReferenceConfig"),ii=Symbol("KosModelSymbol"),$e=Symbol("ModelEffects"),ie=(e,t)=>{e[Mt]=e[Mt]||{},e[Mt][t]=!0},Se=e=>`{PROP_${String(e)}}`,Sl=e=>`{PROP_${String(e)}}`,Al=Se("kosParentId"),Ns=e=>t=>{t[_t]=t[_t]||{};const s=(e==null?void 0:e.parentId)||Al;t[_t]={parentId:s}},Ke=({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]=Ke({value:o[n],modelId:t,modelData:s}),r),{});else if(typeof o=="string"){const r=new RegExp(".*({PROP_(.+)})");let n=o!=null&&o.includes(hs)?o.replace(hs,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},Cl=f.createLogger({name:"kos-model"});function Rl(e,t,s){var n;const o=(n=e[_t])==null?void 0:n.parentId;if(!o)return;const r=Ke({value:o,modelData:s,modelId:t});r&&typeof r=="string"&&k.setParentContext(t,r)}function Ll(e){const t=e[wt];t&&Object.entries(t).forEach(([s,{handler:o}])=>{e[s]=o})}function Pl(e,t){const s=e[P]||{};Object.entries(s).forEach(([o,r])=>{const n=Ke({value:r.id||r.modelType,modelData:e,modelId:t}),i=Object.entries((r==null?void 0:r.options)||{}).reduce((c,[d,l])=>(c[d]=Ke({value:l,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 kl(e){try{return v.makeAutoObservable(e)}catch(t){return Cl.error("Failed to make observable:",t),e}}const xl={construct(e,t){var c;const[s,o={}]=t,r=k.createContext(s);Rl(e,s,o);const n=f.createLogger({name:e.prototype.modelTypeId,group:((c=e[Et])==null?void 0:c.group)??"kos-model"}),i=new e(s,o,{logger:n,kosContext:r});return Ll(i),Pl(i,s),kl(i)}};function O(e){return t=>{var o,r;const s=t;return s.prototype.modelTypeId=e,s.prototype[ii]=!0,(o=s.prototype)[G]??(o[G]={}),(r=s.prototype)[P]??(r[P]={}),f.ifDebug(()=>{f.debug(`Registering model with id ${e}`)}),new Proxy(s,xl)}}const Fl=({modelType:e})=>t=>{Ns()(t),O(e)(t)};function Nl(e,t,s){const o=s.value;s.value=function(...r){const n=k.getContext(this.id);return r.push(n),o.apply(this,r)}}const Ul=({group:e}={group:""})=>t=>{t[Et]=t[Et]||{},t[Et]={group:e}};function ai(e){return(t,s,o)=>{t[$e]=t[$e]||{},t[$e][s]={dependencies:e==null?void 0:e.dependencies,value:o.value},o.value=function(){throw new Error(`Method ${s} cannot be called directly.`)}}}const jl=e=>(t,s)=>{t[is]=t[is]||{},t[is][s]=e},Ae=({modelType:e,id:t,options:s,lifecycle:o})=>(r,n)=>{r[P]=r[P]||{},r[P][n]={modelType:e,id:t,options:s,lifecycle:o||x.INIT}},Bl=({topic:e,handler:t,websocket:s=!1,condition:o=()=>!0})=>r=>{r[G]=r[G]||{},Array.isArray(e)?e.forEach(n=>{r[G][n]={websocket:s,handler:t,condition:o}}):r[G][e]={websocket:s,handler:jn(r,v.action(t),200),condition:o}};function R({topic:e,condition:t=(l,u)=>!0,transform:s=l=>l,websocket:o=!1,fos:r=!1,bridge:n=!1,skipParse:i=!1,lifecycle:c,destinationAddress:d}){return(l,u,h)=>{l[G]=l[G]||{},Array.isArray(e)?e.forEach(p=>{l[G][p]={websocket:o,fos:r,bridge:n,handler:h.value,condition:t,transform:s,lifecycle:c,skipParse:i,destinationAddress:d}}):l[G][e]={websocket:o,fos:r,bridge:n,handler:h.value,condition:t,transform:s,lifecycle:c,skipParse:i,destinationAddress:d}}}const ci=5e3;class Kl extends Error{constructor(s,o){super(s);a(this,"model");this.model=o}}const di=(e,t,s)=>{let o;return{promise:new Promise((i,c)=>{o=setTimeout(()=>{f.error(`Model ${t.modelId} - ${t.modelTypeName} - ${s} timed out after ${e}ms`),c(new Kl(`${t.modelId} - ${t.modelTypeName} - ${s}`,t))},e)}),cancel:()=>{o&&clearTimeout(o)}}},li=e=>e.fsm.transitionTo(D.GO_ACTIVE,y.ACTIVE),ui=e=>e.whenReady(),hi=e=>e.fsm.transitionTo(D.LOAD,y.LOADED),Gl=e=>e.fsm.transitionTo(D.UNLOAD,y.UNLOADED),gi=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 as={active:li,ready:ui,load:hi,init:gi},fi=(e,t)=>{const s=t.id||t.modelType,o=Ke({value:s,modelData:e.modelData,modelId:e.modelId});f.debug(`activating dependent model ${t.modelType} with id ${o}`);const r=Object.keys((t==null?void 0:t.options)||{}).reduce((i,c)=>{const d=t.options[c];return i[c]=Ke({value:d,modelData:e.modelData,modelId:e.modelId}),i},{});return{dependentModel:E.getInstance().modelManager.createModelInstance(t.modelType,o,r),dataModelId:o}},pi=(e,t=x.READY)=>{var r;const s=((r=e.modelData)==null?void 0:r[P])||{};return Object.keys(s).length===0?(f.debug(`${e.modelId} has no dependencies. Returning`),[]):Object.keys(s).filter(n=>s[n].lifecycle===t).map(n=>{const i=s[n],{dependentModel:c,dataModelId:d}=fi(e,i);e.modelData[n]=c.data,f.debug(`waiting for dependent model ${i.modelType} with id ${d} - waiting for WHENREADY`);const l=async(p,w,b)=>{var _;await((_=p.whenReady)==null?void 0:_.call(p)),f.debug(`dependent model ${w} with id ${b} - READY`)},{promise:u,cancel:h}=di(ci,e,e.status);return Promise.race([l(c.model,i.modelType,d).then(()=>{h()}).catch(p=>{console.error(`Error waiting for dependent model ${i.modelType} with id ${d}:`,p),h()}),u])}).filter(n=>!!n)},mi=async(e,t,s,o)=>{if(f.debug(`Execute lifecycle with ${t.length} models`),t.length===0){f.debug(`${e.modelId} has no children. Returning`);return}if(!s){f.error(`${e.modelId} is not transitioning with a valid target ${s}`);return}const r=t.map(c=>{let d;return as[s]&&c?d=as[s](c):(c||f.error("model is undefined. This shouldn't happen"),as[s]||f.error(`There is no promise in the Transition Map for ${s}`)),{promise:d,modelId:c==null?void 0:c.modelId,model:c,type:c==null?void 0:c.modelTypeName,status:c==null?void 0:c.status}}).filter(c=>c.promise?c.model?!0:(f.error(`No model found ${c.modelId}`),!1):(f.error(`No promise found ${c.modelId}`),!1)),i=(await Promise.allSettled(r.map(c=>{var u;const{promise:d,cancel:l}=di(ci,c.model,c.status);return Promise.race([(u=c.promise)==null?void 0:u.then(()=>{l()}).catch(h=>{f.error(`Model ${c.modelId} - ${c.type} failed to transition to ${s}: ${h.message}`),l()}),d])}))).filter(c=>c.status==="rejected");i.length>0&&f.error(`Model ${e.modelId} had ${i.length} failed child models on ${o}`)},yi=async(e,t,s)=>{await mi(e,e.getChildren().filter(o=>!!o),t,s)},ct=async(e,t)=>{const o=(await Promise.allSettled(pi(e,t))).filter(r=>r.status==="rejected");o.length&&(f.error(`There were ${o.length} failed dependent models on ${t}`),f.error(o))},Hl=e=>typeof e.toJSON=="function",It=e=>e[P]!==void 0,qo=e=>e.revision!==void 0&&e.index!==void 0,bi=e=>{if(e){if(It(e))return e;if(qo(e))return e.data;if(e instanceof Map||e instanceof v.ObservableMap||e instanceof Set)return Array.from(e.values()).filter(It);if(Array.isArray(e))return e.filter(It)}};function Vl(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}}}),Yl(e.modelData,e.modelTypeName,e.modelId,e)}function Yl(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,d,l;const r=((c=o.getChildren)==null?void 0:c.call(o))||[],n=((d=o.companionManager)==null?void 0:d.all())||[],i=o.modelData[P]||{};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:((l=e.toJSON)==null?void 0:l.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];It(i)?r[`[KOS Model] ${n}`]=typeof i.toJSON=="function"?i.toJSON():{id:i.id,type:i.constructor.name}:qo(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 zl{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{k.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[Mt])||{};return Object.keys(t).map(o=>bi(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 ql{constructor(t){a(this,"companions",new v.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 Wl{constructor(t,s,o,r){a(this,"disposers",[]);this.modelTypeName=t,this.modelId=s,this.modelData=o,this.log=r}setup(){var s;const t=((s=this.modelData)==null?void 0:s[$e])||{};for(const o of Object.keys(t)){const{value:r,dependencies:n,options:i}=t[o],c=r.bind(this.modelData),d=()=>{this.log.info(`Running effect ${o} for ${this.modelTypeName} (${this.modelId})`),v.runInAction(()=>c())},l=n?v.reaction(()=>n(this.modelData),d,{fireImmediately:!!(i!=null&&i.fireImmediately)}):v.autorun(d);this.disposers.push(l)}}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 Zl=f.createLogger({name:"model-active-machine"}),Jl=e=>{const t=m.createMachine(y.INACTIVE,{[y.FAILED]:m.state(m.transition(D.GO_ACTIVE,y.ACTIVATING)),[y.INACTIVE]:m.state(m.transition(D.GO_ACTIVE,y.ACTIVATING)),[y.ACTIVATING]:m.invoke(()=>(e.activeStatus=y.ACTIVATING,e.activate()),m.transition("done",y.ACTIVE,m.action(()=>{e.activeStatus=y.ACTIVE})),m.transition("error",y.FAILED,m.action(()=>{e.activeStatus=y.FAILED}))),[y.ACTIVE]:m.state(m.transition(D.GO_INACTIVE,y.DEACTIVATING)),[y.DEACTIVATING]:m.invoke(()=>(e.activeStatus=y.DEACTIVATING,e.deactivate()),m.transition("done",y.INACTIVE,m.action(()=>{e.activeStatus=y.INACTIVE})),m.transition("error",y.FAILED,m.action(()=>{e.activeStatus=y.FAILED})))});return{service:m.interpret(t,o=>Zl.debug(o.machine.current)),machine:t}},Vr=f.createLogger({name:"model-online-machine"}),Ql=e=>{const t=m.createMachine(y.OFFLINE,{[y.ONLINE]:m.state(m.transition(D.GO_OFFLINE,y.OFFLINE,m.action(async()=>{await e.offline(),e.onlineStatus=y.OFFLINE}))),[y.OFFLINE]:m.state(m.transition(D.GO_ONLINE,y.ONLINE,m.action(async()=>{Vr.debug(`Going online with model ${e.modelId}`),await e.online(),e.onlineStatus=y.ONLINE,await e.fsm.transitionTo(D.INITIALIZE,y.INITIALIZED)})))}),s=m.interpret(t,o=>Vr.debug(o.machine.current));return{machine:t,service:s}},Xl=e=>{var o;const t=Jl(e).service,s=Ql(e).service;return m.createMachine(y.CREATING,{[y.CREATING]:m.state(m.transition(D.CREATE,y.CREATED)),[y.CREATED]:m.state(m.immediate(y.INITIALIZING)),[y.INITIALIZING]:m.invoke(()=>(Y(()=>{e.status=y.INITIALIZING}),e.init()),m.transition("done",y.INITIALIZED,m.action(()=>{e.status=y.INITIALIZED})),m.transition("error",y.FAILED,m.action(()=>{f.error(`Model ${e.modelId} - ${e.modelTypeName} failed to initialize. Transitioning to FAILED state.`),e.status=y.FAILED}))),[y.INITIALIZED]:m.state(m.immediate(y.LOADING)),[y.LOADING]:m.invoke(()=>(Y(()=>{e.status=y.LOADING}),e.load()),m.transition("done",y.LOADED,m.action(()=>{e.status=y.LOADED})),m.transition("error",y.FAILED,m.action(()=>{e.status=y.FAILED}))),[y.LOADED]:m.state(m.immediate(y.READYING),m.transition(D.UNLOAD,y.UNLOADING)),[y.RESETTING]:m.invoke(()=>{var r;return Y(()=>{e.status=y.RESETTING}),(r=e.unload)==null||r.call(e),e.load()},m.transition("done",y.LOADED,m.action(()=>{e.status=y.LOADED}))),[y.READYING]:m.invoke(()=>(Y(()=>{e.status=y.READYING}),e.ready()),m.transition("done",y.READY,m.action(()=>{Y(()=>{e.status=y.READY}),s.send(D.GO_ONLINE)})),m.transition("error",y.FAILED,m.action(()=>{e.status=y.FAILED}))),[y.READY]:m.state(m.transition(D.UNLOAD,y.UNLOADED,m.action((o=e.unload)==null?void 0:o.bind(e))),m.transition(D.RESET,y.RESETTING),m.transition(D.GO_ONLINE,y.READY,m.action(()=>{s.send(D.GO_ONLINE)})),m.transition(D.GO_OFFLINE,y.READY,m.action(()=>{s.send(D.GO_OFFLINE)})),m.transition(D.GO_ACTIVE,y.READY,m.action(()=>{t.send(D.GO_ACTIVE)})),m.transition(D.GO_INACTIVE,y.READY,m.action(()=>{t.send(D.GO_INACTIVE)}))),[y.UNLOADED]:m.state(),[y.FAILED]:m.state()})},eu=f.createLogger({name:"kos-model-lifecycle"}),tu=e=>({service:m.interpret(Xl(e),s=>eu.debug(`state machine for model ${e.modelId}: ${s.machine.current});`))});class su{constructor(t,s){a(this,"disposer");a(this,"service");this.model=t,this.log=s;const o=tu(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=v.when(()=>{const d=this.getTransitionStatusFor(s);return d===s||d===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 ou{static create({modelId:t,modelTypeName:s,component:o}){const r=[o??"kos",s,t].filter(Boolean).join(".");return f.createLogger({name:r})}}class ru{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 nu{constructor(t,s){a(this,"unsubscribers",[]);this.model=t,this.log=s}register(){const t=this.model.modelId,s=j("/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=j("/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 vi=(e=>(e.GET="GET",e.PUT="PUT",e.POST="POST",e.DELETE="DELETE",e))(vi||{});const wi=({path:e,requestId:t,method:s,destinationAddress:o})=>{let r=`${xs}:${s}
|
|
2
2
|
`;return r+=`topic:${e}
|
|
3
|
-
`,r+=`${
|
|
4
|
-
`,r+=`${
|
|
5
|
-
`,o&&(r+=`${
|
|
6
|
-
`),r+=`${
|
|
3
|
+
`,r+=`${Je}:${e}
|
|
4
|
+
`,r+=`${Kt}:${t}
|
|
5
|
+
`,o&&(r+=`${fe}:${o}
|
|
6
|
+
`),r+=`${de}:kos.studio.request
|
|
7
7
|
`,r+=`
|
|
8
|
-
`,r},
|
|
9
|
-
`;return i+=`${
|
|
10
|
-
`,i+=`${
|
|
11
|
-
`,i+=`${
|
|
12
|
-
`,o&&(i+=`${
|
|
13
|
-
`),r&&(i+=`${
|
|
14
|
-
`),n&&(i+=`${
|
|
15
|
-
`),i+=`${
|
|
8
|
+
`,r},Mi=({path:e,requestId:t,method:s,destinationAddress:o,ordered:r,tracker:n})=>{let i=`${In}:/http${e}
|
|
9
|
+
`;return i+=`${xs}:${s}
|
|
10
|
+
`,i+=`${Je}:${e}
|
|
11
|
+
`,i+=`${Dn}:${t}
|
|
12
|
+
`,o&&(i+=`${fe}:${o}
|
|
13
|
+
`),r&&(i+=`${Fo}:true
|
|
14
|
+
`),n&&(i+=`${No}:${n}
|
|
15
|
+
`),i+=`${de}:fos.http.request
|
|
16
16
|
`,i+=`
|
|
17
|
-
`,i},
|
|
18
|
-
`;return
|
|
19
|
-
`,
|
|
20
|
-
`,o&&(
|
|
21
|
-
`),r&&(
|
|
22
|
-
`),n&&(
|
|
23
|
-
`),c&&Object.keys(c).forEach(
|
|
24
|
-
`}),
|
|
25
|
-
`,
|
|
26
|
-
`,
|
|
27
|
-
`;return o+=`${
|
|
28
|
-
`,o+=`${
|
|
29
|
-
`,o+=`${
|
|
30
|
-
`,o+=`${
|
|
17
|
+
`,i},_i=({path:e,requestId:t,method:s,destinationAddress:o,ordered:r,tracker:n,bridge:i,headers:c})=>{let d=`${xs}:${s}
|
|
18
|
+
`;return d+=`${Je}:${e}
|
|
19
|
+
`,d+=`${Kt}:${t}
|
|
20
|
+
`,o&&(d+=`${fe}:${o}
|
|
21
|
+
`),r&&(d+=`${Fo}:true
|
|
22
|
+
`),n&&(d+=`${No}:${n}
|
|
23
|
+
`),c&&Object.keys(c).forEach(l=>{d+=`${l}:${c[l]}
|
|
24
|
+
`}),d+=`${de}:${i?"fos":"kos"}.http.request
|
|
25
|
+
`,d+=`
|
|
26
|
+
`,d},ve=(e,t)=>{let s=e;return t&&(s+=t),s};function mo(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 yo(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 Ei=({path:e,requestId:t,destinationAddress:s})=>{let o=`topic:${e}
|
|
27
|
+
`;return o+=`${Je}:${e}
|
|
28
|
+
`,o+=`${Kt}:${t}
|
|
29
|
+
`,o+=`${fe}:${s}
|
|
30
|
+
`,o+=`${de}:kos.studio.request
|
|
31
31
|
`,o+=`
|
|
32
|
-
`,o},
|
|
33
|
-
`;return r+=`${
|
|
34
|
-
`,r+=`${
|
|
32
|
+
`,o},Ii=({requestId:e,destinationAddress:t,requestType:s,headers:o})=>{let r=`${Kt}:${e}
|
|
33
|
+
`;return r+=`${fe}:${t}
|
|
34
|
+
`,r+=`${de}:${s}
|
|
35
35
|
`,o&&Object.keys(o).forEach(n=>{r+=`${n}:${o[n]}
|
|
36
36
|
`}),r+=`
|
|
37
|
-
`,r},
|
|
38
|
-
`;return r+=`${
|
|
39
|
-
`,t&&(r+=`${
|
|
40
|
-
`),r+=`${
|
|
41
|
-
`,r+=`${
|
|
42
|
-
`,r+=`${
|
|
37
|
+
`,r},iu=(e,t)=>{const s=e,o=ve(Ii(t),typeof s=="string"?s:JSON.stringify(s)),r=E.getInstance().transport.socket;r?(f.debug("Sending message",o),r.socket.send(o)):f.error("socket transport is not initialized")},Ti=({path:e,responseId:t,status:s,destinationAddress:o})=>{let r=`topic:${e}
|
|
38
|
+
`;return r+=`${Je}:${e}
|
|
39
|
+
`,t&&(r+=`${Fs}:${t}
|
|
40
|
+
`),r+=`${xo}:${s}
|
|
41
|
+
`,r+=`${fe}:${o}
|
|
42
|
+
`,r+=`${de}:kos.studio.response
|
|
43
43
|
`,r+=`
|
|
44
|
-
`,r},
|
|
45
|
-
`;return t+=`${
|
|
44
|
+
`,r},au=(e,t)=>{const s=e,o=ve(Ei(t),JSON.stringify(s)),r=E.getInstance().transport.socket;r?r.socket.send(o):f.error("socket transport is not initialized")},cu=(e,t)=>{const s=t.responseId?{status:t.status,data:e}:e,o=ve(Ti(t),JSON.stringify(s)),r=E.getInstance().transport.socket;r?r.socket.send(o):f.error("socket transport is not initialized")},$i=({topic:e})=>{let t=`topic:${e}
|
|
45
|
+
`;return t+=`${de}:kos.broker.send
|
|
46
46
|
`,t+=`
|
|
47
|
-
`,t},
|
|
48
|
-
`;return n+=`${
|
|
49
|
-
`,n+=`${
|
|
50
|
-
`,n+=`${
|
|
51
|
-
`,n+=`${
|
|
52
|
-
`,n+=`${
|
|
53
|
-
`,n+=`${
|
|
47
|
+
`,t},Oi=({responseId:e,destinationAddress:t,type:s,sourceAddress:o,status:r})=>{let n=`${Fs}:${e}
|
|
48
|
+
`;return n+=`${fe}:${t}
|
|
49
|
+
`,n+=`${Tn}:${o}
|
|
50
|
+
`,n+=`${de}:${s??"kos.message.request"}
|
|
51
|
+
`,n+=`${xo}:${r}
|
|
52
|
+
`,n+=`${$n}:application/json
|
|
53
|
+
`,n+=`${On}:no-cache
|
|
54
54
|
`,n+=`
|
|
55
|
-
`,n},
|
|
56
|
-
`;return t&&(r+=`${
|
|
57
|
-
`),r+=`${
|
|
58
|
-
`,r+=`${
|
|
55
|
+
`,n},Di=({topic:e,responseId:t,destinationAddress:s,type:o})=>{let r=`topic:${e}
|
|
56
|
+
`;return t&&(r+=`${Fs}:${t}
|
|
57
|
+
`),r+=`${fe}:${s}
|
|
58
|
+
`,r+=`${de}:${o??"kos.message.request"}
|
|
59
59
|
`,r+=`
|
|
60
|
-
`,r},
|
|
60
|
+
`,r},du=({msg:e,options:t})=>{const s=e,o=ve($i(t),JSON.stringify(s)),r=E.getInstance().transport.socket;r?r.socket.send(o):f.error("socket transport is not initialized")},Si=({msg:e,options:t})=>{const s=e,o=ve(Di(t),JSON.stringify(s)),r=E.getInstance().transport.socket;r?r.socket.send(o):f.error("socket transport is not initialized")},Ai=({msg:e,options:t})=>{const s=e,o=ve(Oi(t),JSON.stringify(s)),r=E.getInstance().transport.socket;r?r.socket.send(o):f.error("socket transport is not initialized")},bo=(e,t)=>{try{return t?e.body??e:JSON.parse(e.body)}catch{return e.body||e}};class lu extends WebSocket{constructor(t){super(t)}}function Yr(e){const t=`
|
|
61
61
|
|
|
62
62
|
`,s=`
|
|
63
|
-
`,o=/:(.*)/s,[r,n]=e.split(t).map(c=>c.trim());return{headers:r.split(s).reduce((c,
|
|
63
|
+
`,o=/:(.*)/s,[r,n]=e.split(t).map(c=>c.trim());return{headers:r.split(s).reduce((c,d)=>{const[l,u]=d.split(o).map(h=>h.trim());return l&&u&&(c[l]=u),c},{}),body:n}}function uu(e){const t=`
|
|
64
64
|
|
|
65
65
|
`,s=`
|
|
66
|
-
`,o=/:(.*)/s,[,r,n]=e.split(t).map(c=>c.trim());return{headers:r.split(s).reduce((c,
|
|
66
|
+
`,o=/:(.*)/s,[,r,n]=e.split(t).map(c=>c.trim());return{headers:r.split(s).reduce((c,d)=>{const[l,u]=d.split(o).map(h=>h.trim());return l&&u&&(c[l]=u),c},{}),body:n}}class Wo{constructor({host:t,port:s,protocol:o,alias:r,onConnectionEstablished:n,onConnectionLost:i,Transport:c=lu}){a(this,"host");a(this,"port");a(this,"protocol");a(this,"socket");a(this,"connectionEstablished");a(this,"alias");a(this,"onConnectionEstablished");a(this,"onConnectionLost");a(this,"offlineMessages",[]);a(this,"oldSend");this.host=t,this.port=s,this.protocol=o,this.onConnectionEstablished=n,this.onConnectionLost=i,this.alias=r,this.socket=new c(`${this.protocol}${this.host}:${this.port}/events`),this.socket.onmessage=this.onMessage.bind(this),this.socket.onopen=this.onOpen.bind(this),this.socket.onclose=this.onClose.bind(this),this.oldSend=this.socket.send,this.connectionEstablished=!1,j("/mock/msg/receive",d=>{var l,u;if(d!=null&&d.body){f.wsReceive(d==null?void 0:d.body);const h={data:d.body};(u=(l=this.socket)==null?void 0:l.onmessage)==null||u.call(l,h)}}),v.makeObservable(this,{connectionEstablished:v.observable})}addOfflineMessage(t){this.offlineMessages.push({msg:t})}processMessageEvent(t){const{data:s}=t;return Yr(s)}onMessage(t){try{f.debug("webSocketTransport: onMessage received");const{headers:s,body:o}=this.processMessageEvent(t);f.wsReceive(t.data);const r=s.subscription||s[this.RESPONSE_ID_HEADER]||s.topic||s.type;if(r){let n=o,i=s;if(r==="kos.sniffer.msg"){const{headers:c,body:d}=uu(t.data);n=d,i={...s,...c}}N(r,n,i)}}catch(s){f.error("onMessage exception",s.message,s.stack)}}onOpen(t){f.info("websocket connection opened"),this.socket=t.currentTarget,v.runInAction(()=>{var s;this.connectionEstablished=!0,this.alias&&this.socket.send(`type:kos.addr.alias
|
|
67
67
|
alias:${this.alias}
|
|
68
68
|
|
|
69
|
-
`),f.debug(`sending ${this.offlineMessages.length} offline FOS messages`),this.offlineMessages.forEach(o=>{var r;f.debug(`sending offline message ${o.msg}`),(r=this.socket)==null||r.send(o.msg)}),this.offlineMessages=[],(s=this.onConnectionEstablished)==null||s.call(this)})}onClose(){this.socket&&this.socket.close(),
|
|
69
|
+
`),f.debug(`sending ${this.offlineMessages.length} offline FOS messages`),this.offlineMessages.forEach(o=>{var r;f.debug(`sending offline message ${o.msg}`),(r=this.socket)==null||r.send(o.msg)}),this.offlineMessages=[],(s=this.onConnectionEstablished)==null||s.call(this)})}onClose(){this.socket&&this.socket.close(),v.runInAction(()=>{this.connectionEstablished=!1}),f.debug("websocket disconnected. Attempting calling callback"),this.onConnectionLost&&setTimeout(this.onConnectionLost,2500)}send(t){var s,o;if(f.wsSend(t),window.kosLogEvents){const{headers:r,body:n}=Yr(String(t));N(Gt.SEND,{headers:r,body:n})}if(window.kosTopicIntercept&&window.kosEnableMocks){const{handler:r,requestId:n}=window.kosTopicIntercept(t);if(r){t=`mocked:true
|
|
70
70
|
${t}`;const c={data:`mocked:true
|
|
71
|
-
${r(n)}`};(o=(s=this.socket)==null?void 0:s.onmessage)==null||o.call(s,c)}else this.oldSend.call(this.socket,t)}else this.oldSend.call(this.socket,t)}}class
|
|
71
|
+
${r(n)}`};(o=(s=this.socket)==null?void 0:s.onmessage)==null||o.call(s,c)}else this.oldSend.call(this.socket,t)}else this.oldSend.call(this.socket,t)}}class hu{constructor(t){a(this,"addEventListener");a(this,"dispatchEvent");a(this,"removeEventListener");a(this,"_onclose");a(this,"_onerror");a(this,"_onmessage");a(this,"_onopen");a(this,"messageQueue",[]);a(this,"isSending",!1);T.debug(`called Bridge Transport with addr ${t}`);const s=this;globalThis.kosWindowWebsocketRecv=o=>{if(s.onmessage){const r={data:o};s.onmessage(r)}},T.debug("Opening bridge transport"),globalThis.kosWindowWebsocketOpen(),T.debug("Opened bridge transport"),this._onclose=null,this._onerror=null,this._onmessage=null,this._onopen=null,this.addEventListener=()=>T.debug("not implemented"),this.dispatchEvent=()=>T.debug("not implemented"),this.removeEventListener=()=>T.debug("not implemented")}close(){T.debug("closing")}sendNextMessage(){if(this.messageQueue.length>0){const t=this.messageQueue.shift();globalThis.kosWindowWebsocketSend(t),setTimeout(()=>this.sendNextMessage(),1)}else this.isSending=!1}enqueueMessage(t){this.messageQueue.push(t),this.isSending||(this.isSending=!0,this.sendNextMessage())}send(t){globalThis.kosWindowWebsocketSend(t)}get onmessage(){return this._onmessage}set onmessage(t){this._onmessage=t}get onopen(){return this._onopen}set onopen(t){this._onopen=t}get onclose(){return this._onclose}set onclose(t){this._onclose=t}get onerror(){return this._onerror}set onerror(t){this._onopen=t}}class gu extends Wo{constructor({host:s,port:o,alias:r}){super({host:s,port:o,Transport:hu,alias:r,protocol:"kos://"});a(this,"RESPONSE_ID_HEADER");this.RESPONSE_ID_HEADER="response-id"}}class fu extends Wo{constructor({host:s,port:o}){super({host:s,port:o,protocol:"ws://"});a(this,"RESPONSE_ID_HEADER");this.RESPONSE_ID_HEADER="requestId"}}class pu extends Wo{constructor({host:s,port:o,protocol:r,onConnectionEstablished:n,onConnectionLost:i,alias:c}){super({host:s,port:o,onConnectionEstablished:n,onConnectionLost:i,alias:c,protocol:r});a(this,"RESPONSE_ID_HEADER");this.RESPONSE_ID_HEADER="response-id"}}window.kosEnableMocks=process.env.KOS_MOCK_WS==="true";window.kosLogEvents=process.env.KOS_LOG_WS==="true";class vo{static build({host:t,port:s,protocol:o,fos:r,alias:n,onConnectionEstablished:i,onConnectionLost:c}){return f.debug("initializing websocket connection"),f.warn(`kosWindowWebsocketOpen: ${globalThis.kosWindowWebsocketOpen?"true":"false"}`),f.warn(`fos: ${r?"true":"false"}`),window.kosMockWs||globalThis.kosWindowWebsocketOpen&&!r?(f.warn("Using bridged message transport"),new gu({host:t,port:s,protocol:o,onConnectionEstablished:i,onConnectionLost:c,alias:n})):r?new fu({host:t,port:s,protocol:o,alias:n,onConnectionEstablished:i,onConnectionLost:c}):new pu({host:t,port:s,protocol:o,alias:n,onConnectionEstablished:i,onConnectionLost:c})}}const mu=ee();mu.fos&&(window.kosUseFos=!0);const zr=process.env.KOS_FOS_PORT;window.kosUseFos=!!(window.kosUseFos||process.env.KOS_USE_FOS==="true");window.kosFosPort=zr?parseInt(zr):0;const Ee=T.getLogger("web-socket-transport");var Ci=(e=>(e.NOT_INITIALIZED="not_initialized",e.INITIALIZED="initialized",e.OFFLINE="OFFLINE",e.ONLINE="ONLINE",e))(Ci||{}),Tt=(e=>(e.CONNECTED="websocket.connected",e.DISCONNECTED="websocket.disconnected",e.RELOAD="websocket.reload",e))(Tt||{});class Ht{constructor({host:t="localhost",port:s=8080,protocol:o="ws://",token:r,initialize:n,alias:i,fos:c}){a(this,"host");a(this,"port");a(this,"protocol");a(this,"_token");a(this,"webSocketSupported",!!globalThis.WebSocket);a(this,"authorized");a(this,"alias");a(this,"socket");a(this,"fosSocket");a(this,"fosPort");a(this,"useFosTransport");this.host=t,this.port=s,this.protocol=o,this._token=r,this.alias=i,this.authorized=process.env.KOS_ALLOW_ANONYMOUS==="true",this.useFosTransport=!!c,this.fosPort=c==null?void 0:c.port,this.socket=void 0,this.fosSocket=void 0;let d=!1;v.makeObservable(this,{authorized:v.observable,socket:v.observable,fosSocket:v.observable,init:v.action,connectionEstablished:v.computed}),v.reaction(()=>this.connectionEstablished,l=>{l&&(Ee.warn("Connection Established"),N("websocket.connected","websocket.connected"),d&&N("websocket.reload","websocket.reload"),d=!0)}),n&&this.init()}get connectionEstablished(){return!this.webSocketSupported||!this.socket||this.useFosTransport&&!this.fosSocket?!1:this.useFosTransport&&this.fosSocket?this.socket.connectionEstablished&&this.fosSocket.connectionEstablished:!this.useFosTransport&&this.socket?this.socket.connectionEstablished:!1}init(){var t,s;if(f.warn(`Initializing WebSocketTransport on ${this.host}:${this.port}`),this.useFosTransport&&(this.fosSocket=vo.build({host:this.host,port:this.fosPort||9854,protocol:this.protocol,fos:!0})),this.socket=vo.build({host:this.host,port:this.port,protocol:this.protocol,alias:this.alias,onConnectionLost:()=>{Ee.error("Connection Lost"),N("websocket.disconnected","websocket.disconnected"),this.init()}}),globalThis.kosWindowWebsocketOpen){const o={currentTarget:this.socket.socket};(s=(t=this.socket.socket)==null?void 0:t.onopen)==null||s.call(t,o)}return this}_sendSubscriptionMessage(t,s,o=!1,r=!1,n){var p,w,b,_;Ee.debug(`${s} to topic ${t}`);const i=ee(),c=i==null?void 0:i.connId,d=n??c??((p=window==null?void 0:window.kosBridge)==null?void 0:p.call(window,"connId"));Ee.debug(`subscribing with connId ${d}`);const l=d?`dst-addr:${d}
|
|
72
72
|
`:"",u=o?`subscribe:${t}`:r?`type:fos.broker
|
|
73
73
|
cmd:${s}
|
|
74
|
-
${
|
|
75
|
-
`:`${
|
|
74
|
+
${l}topics:${t}
|
|
75
|
+
`:`${l}type:kos.broker.${s}
|
|
76
76
|
|
|
77
|
-
["${t}"]`;if(o?(v=this.fosSocket)==null?void 0:v.connectionEstablished:(b=this.socket)==null?void 0:b.connectionEstablished){const I=o?this.fosSocket:this.socket;(E=I==null?void 0:I.socket)==null||E.send(u)}else{_e.debug("no connection adding to offline messages");const I=o?this.fosSocket:this.socket;I==null||I.addOfflineMessage(u)}}subscribeTopic({topic:t,callback:s,fos:o,bridge:r,destinationAddress:n}){const{unsubscribe:i,count:c}=j(t,s);return _e.debug(`Topic ${t} currently has ${c} subscribers`),this._sendSubscriptionMessage(t,"subscribe",o,r,n),()=>{const{count:l}=i();_e.debug(`Topic ${t} currently has ${l} subscribers`),l===0&&this._sendSubscriptionMessage(t,"unsubscribe",o,r,n)}}async whenReady(){const t=this;return this.webSocketSupported?(await w.when(()=>{var s,o;return!!((s=t.socket)!=null&&s.connectionEstablished)&&(!t.useFosTransport||!!((o=t.fosSocket)!=null&&o.connectionEstablished))&&t.authorized}),{status:"success"}):{status:"not supported"}}get token(){return this._token}set token(t){this._token=t,this.init()}static host(t="localhost"){return this.getInstance().host=t,this}static port(t=8080){return this.getInstance().port=t,this}static alias(t){this.getInstance().alias=t}static getInstance(t=8080,s){if(!this._instance){const o=window.kosUseFos?{port:window.kosFosPort||8081}:void 0;this._instance=new this({port:t,token:s,fos:o})}return this._instance}}a(Kt,"_instance");class iu{constructor(t,s,o,r,n){a(this,"disposers",[]);a(this,"activatableDisposers",[]);this.model=t,this.modelData=s,this.modelId=o,this.offlineQueue=r,this.log=n}registerAll(t){var r;const s=((r=this.modelData)==null?void 0:r[G])||{},o=Object.keys(s);this.log.debug(`Found ${o.length} subscriptions in ${this.modelId} (lifecycle: ${t??"any"})`),o.forEach(n=>{const i=s[n],c=i.lifecycle;if(t&&t!==c)return;const l=this.resolvePropKey(n);this.log.debug(`Resolved topic: ${n} → ${l}`);const d=this.createHandler(l,i);this.subscribe(i,l,d,c===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=Kt.getInstance().subscribeTopic({topic:s,callback:o,fos:t.fos,bridge:t.bridge,destinationAddress:n});this.disposers.push(i)}else{this.log.debug(`Subscribing to EventBus topic: ${s}`);const{unsubscribe:i}=j(s,o);r?this.activatableDisposers.push(i):this.disposers.push(i)}}createHandler(t,s){return async o=>{var r;try{const n=(r=o==null?void 0:o.headers)==null?void 0:r["src-addr"],i=s.destinationAddress&&this.resolvePropKey(s.destinationAddress),c=i?n===i:!0;if(this.model.isReady()){const l=go(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=go(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 rt(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 au(e){return!!(e!=null&&e[$e])&&Object.keys(e[$e]).length>0}function cu(e){return!!(e!=null&&e[G])&&Object.keys(e[G]).length>0}class lu{static createAll(t){const{modelId:s,modelTypeName:o,modelData:r}=t,n=Yd.create({modelId:s,modelTypeName:o}),i=new Vd(t,rt(n,"fsm")),c=new zd(rt(n,"offline-queue")),l=new Fd(t),d=new kd(t),u={fsm:i,offlineQueue:c,companionManager:l,childResolver:d};if(au(r)&&(u.effectManager=new Nd(o,s,r,rt(n,"effect"))),cu(r)){const h=rt(n,"subscription");u.subscriptionManager=new iu(t,r,s,c,h),u.onlineLifecycleManager=new qd(t,rt(n,"online"))}return u}}const S=T.getLogger("kos-model"),jr="kos.extension.model.loader";class Ei{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=lu.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}),Pd(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;S.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)),S.debug(`Model ${this.modelTypeName} with id ${this.modelId} deactivated`),(o=this.subscriptionManager)==null||o.deactivate()}catch(r){throw S.debug(`Model ${this.modelId} failed to deactivated`),r}}async activate(){var t,s,o;S.debug(`activating model ${this.modelTypeName} with id ${this.modelId}`),await at(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)),S.debug(`Model ${this.modelTypeName} with id ${this.modelId} subscribing to all topics`),(o=this.subscriptionManager)==null||o.registerAll(k.ACTIVATE),S.debug(`Model ${this.modelTypeName} with id ${this.modelId} activated`)}catch(r){throw S.debug(`Model ${this.modelId} failed to activate`),r}}async whenInitialized(){await kr([{condition:()=>this.status===y.FAILED,onMatch:()=>{throw new Error(`Failed to initialize model ${this.modelId}`)}},{condition:()=>this.initialized,onMatch:()=>{S.debug(`Model ${this.modelId} is initialized`)}}])}async whenReady(){await kr([{condition:()=>this.status===y.FAILED,onMatch:()=>{throw new Error(`Failed to ready model ${this.modelId}`)}},{condition:()=>this.status===y.READY,onMatch:()=>{S.debug(`Model ${this.modelId} is ready`)}}])}async ready(){var t,s,o;if(this.fsm.current===y.READY){S.debug(`already readying model ${this.modelTypeName} with id ${this.modelId} returning`);return}try{S.debug(`readying model ${this.modelTypeName} with id ${this.modelId}`),await at(this,k.READY),await ai(this,jo.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),S.debug(`Model ${this.modelId} is ready`);const n={modelId:this.modelId,modelType:this.modelTypeName};N(qn(this.modelTypeName,this.modelId),n),N(Wn(this.modelTypeName),n)}catch(r){throw S.error(r),Error(r)}}async load(){var o,r,n,i;const{modelTypeName:t,modelId:s}=this;if(this.fsm.current===y.LOADED||this.fsm.current===y.LOADING){S.debug(`Model ${t} with id ${s} already loaded or loading`);return}S.debug(`Loading model ${t} with id ${s}`),await at(this,k.LOAD);try{const c=x.getContext(s),l=await C.loader.executeLoader(jr,{});l&&(S.info(`Setting loaded context for ${s}, type: ${t}`),c==null||c.set(jr,l)),await((r=(o=this.modelData)==null?void 0:o.load)==null?void 0:r.call(o,c)),this.loaded=!0,S.debug(`Model ${t} with id ${s} successfully loaded`),(n=this.subscriptionManager)==null||n.registerAll(k.LOAD),(i=this.effectManager)==null||i.setup()}catch(c){throw S.error(`Model ${s} failed to load`,c),c}}async unload(){var t,s,o,r,n;S.debug(`unloading model ${this.modelTypeName} with id ${this.modelId}`);try{const i=this.getChildren().map(l=>{var d;return(d=l.unload)==null?void 0:d.call(l)}).filter(l=>!!l);await Promise.allSettled(i);const c=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(),S.debug(`Model ${this.modelTypeName} with id ${this.modelId} unloaded`),(r=this.effectManager)==null||r.disposeAll(),(n=this.subscriptionManager)==null||n.disposeAll()}catch(i){throw S.debug(`Model ${this.modelId} failed to unload`),i}}async init(){var r,n,i;const{modelId:t,modelTypeName:s}=this,o=x.getContext(t);S.debug(`Initializing model ${s} with id ${t}`),await at(this,k.INIT);try{await((n=(r=this.modelData)==null?void 0:r.init)==null?void 0:n.call(r,o)),this.initialized=!0,S.debug(`Model ${s} with id ${t} initialized`),(i=this.onlineLifecycleManager)==null||i.register(),this.registerSubscribers(k.INIT)}catch(c){throw S.error(`Model ${t} failed to initialize`,c),c}}async registerSubscribers(t){var s;S.debug(`registering subscribers in ${this.modelTypeName} with id ${this.modelId}`),(s=this.subscriptionManager)==null||s.registerAll(t)}async online(){var s,o;S.debug(`online model ${this.modelTypeName} with id ${this.modelId}`),this.registerSubscribers();const t=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;S.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 _i=e=>typeof e=="function",Br=f.createLogger({name:"kos-model-instantiator"});class du{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)){Br.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 Ei({modelTypeName:t,id:n,modelData:c});this.cache.addModel(l),this._createCompanionModels(l,o)}const i=this.cache.getModelById(n);if(!i)throw Br.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=_i(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 uu=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 Xe(t)}};const Ii=10,Kr=f.createLogger({name:"kos-model-manager"});class Ti{constructor(){a(this,"cache");a(this,"instantiator");a(this,"dependencies");a(this,"_registry");globalThis.kos=globalThis.kos||{},this.dependencies=new md,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 uu(t),o.cache=new pd(t.preloadModels),o.instantiator=new du(t,o.cache),o}static getInstance(t){var s,o;return(!((s=globalThis.kos)!=null&&s.modelManager)||t)&&(Kr.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=>(Kr.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 Xe(t)}addDependency(t,s){this.cache.restoreFromDeleteCache(s),this.dependencies.add(t,s)}removeDependency(t,s){this.dependencies.remove(t,s)}async reloadModel(t){if(t.id){const s=this.getModelById(t.id);s&&await s.fsm.transitionTo(O.RESET,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),jn.addToDeletionQueue(t.id,setTimeout(()=>this.destroyModel(s),Ii)))}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 hu=async({context:e,extension:t})=>{const s=await C.loader.executeLoader(t,{});return e==null||e.set(t,s),s},gu=async({extension:e,contextData:t,data:s})=>await C.dataMapper.executeMapper(e,s,t),fu=async({extension:e,contextData:t,data:s})=>await C.propertyMapper.executeMapper(e,s,t),mu=Object.freeze(Object.defineProperty({__proto__:null,executeDataMapperExtension:gu,executeLoaderExtension:hu,executePropertyMapperExtension:fu},Symbol.toStringTag,{value:"Module"})),pu="Extensions";class yu{constructor(){a(this,"extensions");this.extensions={}}register(t,s,o){this.extensions[t]={},this.extensions[t][s]={component:o}}get(t,s){if(!this.extensions[t])throw new Error(`Extension point ${t} not found`);return this.extensions[t][s]}get allExtensions(){return this.extensions}}var is=(e=>(e.CREATING="creating",e.CREATED="created",e.INITIALIZING="initializing",e.INITIALIZED="initialized",e.LOADING="loading",e.LOADED="loaded",e.ONLINE="online",e.READYING="readying",e.READY="ready",e.OFFLINE="offline",e.UNLOADING="unloading",e.UNLOADED="unloaded",e.RELOADING="reloading",e))(is||{}),Fe=(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))(Fe||{});const bu=e=>{const t=m.createMachine("offline",{online:m.state(m.transition("go_offline","offline",m.action(()=>{e.offline(),w.runInAction(()=>{e.isOnline=!1})}))),offline:m.state(m.transition("go_online","online",m.action(()=>{e.online(),w.runInAction(()=>{e.isOnline=!0})})))}),s=m.interpret(t,n=>T.debug(n.machine.current)),o=m.createMachine({creating:m.state(m.transition("create","created")),created:m.state(m.immediate("initializing")),initializing:m.invoke(()=>e.init(),m.transition("done","initialized")),initialized:m.state(m.immediate("loading")),loading:m.invoke(()=>e.load(),m.transition("done","loaded")),loaded:m.state(m.immediate("readying"),m.transition("unload","unloading")),readying:m.invoke(()=>e.ready(),m.transition("done","ready",m.action(()=>{w.runInAction(()=>{e.status="ready"})}))),reloading:m.invoke(()=>e.reload(),m.transition("done","loading")),ready:m.state(m.transition("reload","reloading"),m.transition("unload","unloaded",m.action(e.unload.bind(e))),m.transition("go_online","ready",m.action(()=>{s.send("go_online")})),m.transition("go_offline","ready",m.action(()=>{s.send("go_offline")}))),unloaded:m.state()});return{service:m.interpret(o,n=>T.debug(n.machine.current)),online:s}},J=async e=>{if(e.id){const t=_.getInstance().modelManager.getModelById(e.id);if(!t)throw new Error(`Model with ID ${e.id} not found`);await(t==null?void 0:t.whenReady())}else throw new Error("Data model must have a valid ID");return e},Oe=async e=>{await _.getInstance().whenReady(),await _.getInstance().modelManager.initiateDestroyModel(e)},vu=async e=>{if(await _.getInstance().whenReady(),!e.id)throw new Error("Model ID is required");const t=_.getInstance().modelManager.getModelById(e.id);t&&await t.fsm.transitionTo(O.UNLOAD,y.UNLOADED)},$i=async e=>{await _.getInstance().whenReady(),await _.getInstance().modelManager.reloadModel(e),f.debug(`reload model initiated for model ${e.id}, model ready: ${hs(e)} - ${Date.now()} `),await J(e),f.debug(`reload model complete for model ${e.id}, model ready: ${hs(e)} - ${Date.now()} `)},wu=async e=>{if(await _.getInstance().whenReady(),!e)throw new Error("Model ID is required");const t=_.getInstance().modelManager.getModelById(e);return t==null?void 0:t.modelTypeName},Oi=async e=>{if(await _.getInstance().whenReady(),!e)throw new Error("Model ID is required");const t=_.getInstance().modelManager.getModelById(e);return{model:t==null?void 0:t.modelData,type:t==null?void 0:t.modelTypeName}},Qe=e=>{if(!e)throw new Error("Model ID is required");const t=_.getInstance().modelManager.getModelById(e);return{model:t==null?void 0:t.modelData,type:t==null?void 0:t.modelTypeName}},Di=(e,t)=>{if(!e)throw new Error("Model type is required");return _.getInstance().modelManager.getModelsByType(e).filter(r=>Object.keys(t).every(n=>r[n]===t[n]))},Mu=(e,t)=>Di(e,t)[0],Eu=(e,t)=>{if(!e.id)throw new Error("Model ID is required");const s=_.getInstance().modelManager.getModelById(e.id);if(!s)throw new Error("Model not found");const o=s.companionModels.get(t);return o==null?void 0:o.modelData},_u=e=>{if(!e.id)throw new Error("Model ID is required");const t=_.getInstance().modelManager.getModelById(e.id);if(!t)throw new Error("Model not found");return Array.from(t.companionModels.all()).map(o=>o.modelData)},Iu=e=>{if(!e)throw new Error("Model ID is required");const t=_.getInstance().modelManager.getModelById(e);if(!t)throw new Error("Model not found");return t.companionModels.data},mo=(e,t)=>{const s=_.getInstance().modelManager.getModelById(e);if(!s){f.info(`Model not found for id ${e}`);return}return Array.from(s.companionModels.all()).find(r=>t(r.modelData))},ee=e=>t=>Object.getPrototypeOf(t).modelTypeId===e,hs=e=>{const t=_.getInstance().modelManager.getModelById(e.id);if(!t)throw new Error("Model not found");return t.isReady()},Tu=f.createLogger({name:"kos-model-factory"}),Tt={byModelType:e=>_.getInstance().modelManager.getModelFactory(e),getModelInstance:(e,t,s)=>{const o=Tt.byModelType(t);if(!o)throw Tu.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),Tt.getModelInstance(t,e,s))},Singleton:{create:e=>(t,s)=>(s&&x.setParentContext(e,s),Tt.getModelInstance(e,e,t))},Model:{instance:e=>t=>Tt.getModelInstance(t,e)}};window.KosRegistry=window.KosRegistry||{coreModels:new Map,preloadModels:[],companionModels:new Map,models:new Map};const Hr=window.KosRegistry.coreModels,to=window.KosRegistry.preloadModels,so=window.KosRegistry.companionModels,Wt=window.KosRegistry.models,$={model:{registerLegacyModel:e=>(t,s)=>(Hr.set(t,s),{preload:$.model.preloadModel(e),model:$.model.register(e),companion:$.companion.register(e),legacy:$.model.registerLegacyModel(e),root:e}),preloadModel:e=>t=>(to.includes(t)||to.push(t),{preload:$.model.preloadModel(e),model:$.model.register(e),companion:$.companion.register(e),legacy:$.model.registerLegacyModel(e),root:e}),register:e=>(t,s)=>{const o=oo(t)?t.registration():t;return Wt.set(o.type,o),oo(t)&&t.relatedModels.forEach(r=>Wt.set(r.type,r.registration())),_.getInstance().isReady&&(_.getInstance().modelManager.registry.models[o.type]||(console.info(`Model with type ${o.type} doesn't exist. Adding new registration`),_.getInstance().modelManager.registry.models[o.type]=o.registration[o.type],oo(t)&&t.relatedModels.forEach(r=>_.getInstance().modelManager.registry.models[r.type]=r.registration().registration))),s&&$.model.preloadModel(e)(o.type),{preload:$.model.preloadModel(e),model:$.model.register(e),companion:$.companion.register(e),legacy:$.model.registerLegacyModel(e),root:e}},get:e=>Wt.get(e),getAll:()=>Array.from(Wt.entries()),getPreloadModels:()=>to,getLegacyModels:()=>Array.from(Hr.entries()).reduce((e,[t,s])=>(e[t]=s,e),{})},companion:{register:e=>(t,s)=>{const o=so.get(t)||[];return o.push(s),so.set(t,o),{preload:$.model.preloadModel(e),model:$.model.register(e),companion:$.companion.register(e),legacy:$.model.registerLegacyModel(e),root:e}},getAll:()=>Array.from(so.entries())}},Si=$.model.registerLegacyModel,Ai=$.model.register,$u=$.companion.register,Ou=$.model.preloadModel,Ci=e=>typeof e.updateModel=="function",oo=e=>e.registration!==void 0&&typeof e.registration=="function";class Ri{constructor(t){a(this,"singleton");a(this,"type");a(this,"class");a(this,"guard");a(this,"factory");a(this,"relatedModels",[]);this.singleton=t.singleton,this.guard=ee(t.type),this.type=t.type,this.factory=t.factory,this.class=t.class}addRelatedModel(t){this.relatedModels.push(t)}registerRelatedModels(){this.relatedModels.forEach(t=>t.register())}register(){$.model.register({})(this.registration()),this.registerRelatedModels()}}class le extends Ri{constructor(t){super({...t,singleton:!1,factory:V.Factory.create(t.type)})}instance(t){const s=this.factory(t);return{get:()=>{const o=Qe(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(Ci(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 fe extends Ri{constructor(t){super({...t,singleton:!0,factory:V.Singleton.create(t.type)})}instance(){const t=this.factory;return{get:()=>{const o=Qe(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(Ci(r))r.updateModel(o);else throw new Error(`Model ${this.type} is not updateable. Please implement UpdateAware interface`);return r}else throw new Error(`Model is not of type ${this.type}. Received type ${Object.getPrototypeOf(r).modelTypeId}`)}})},options:o=>({build:()=>{const r=t(o);if(this.guard(r))return r;throw new Error(`Model is not of type ${this.type}. Received type ${Object.getPrototypeOf(r).modelTypeId}`)}})}}registration(){return{type:this.type,predicate:this.guard,registration:{[this.type]:{class:this.class,singleton:!0}},factory:this.factory}}}const U=f.createLogger({name:"kos-core"}),Du=()=>{const e=window.location.protocol,t=ae(),s=t==null?void 0:t.host;let o;try{o=new URL(s).protocol==="https:"?"wss://":"ws://"}catch{}return o||(e==="https:"?"wss://":"ws://")},Su=()=>{const e=window.location.hostname,t=process.env.KOS_HOST,s=ae(),o=s==null?void 0:s.host;let r;try{r=new URL(o).hostname}catch{}return r??t??e},Au=()=>{const e=window.location.port,t=process.env.KOS_PORT,s=ae(),o=s==null?void 0:s.host;let r;try{r=new URL(o).port}catch{}return r??t??e},Cu=(e,t)=>{let s;return{promise:new Promise((n,i)=>{s=setTimeout(()=>{t?f.error(`Model ${t.modelId} - ${t.modelTypeName} preloading - timed out after ${e}ms`):f.error(`KOS Core preloading timed out after ${e}ms`),i(new Error(`Model ${t==null?void 0:t.modelId} - ${t==null?void 0:t.modelTypeName} - timed out after ${e}ms`))},e)}),cancel:()=>{s&&clearTimeout(s)}}},Gr=e=>typeof e.reload=="function",Ru=e=>typeof e.unload=="function";var Li=(e=>(e.LOGGED_IN="logged_in",e.LOGGED_OUT="logged_out",e))(Li||{});class _{constructor(t){a(this,"fsmService");a(this,"status");a(this,"initialized");a(this,"loaded");a(this,"_transport");a(this,"modelManager");a(this,"authState");a(this,"isOnline");a(this,"_reloading");a(this,"_unloading");a(this,"connectionAlias");this.initialized=!1,this.connectionAlias=t,this.loaded=!1,this.isOnline=!1,this.status=is.CREATED,this.authState="logged_out",this._reloading=!1,this._unloading=!1,w.makeAutoObservable(this),j("token",c=>{c&&(this.transport.token=c.body)}),j(It.CONNECTED,async()=>{await this.whenReady(),this.fsmService.service.send(Fe.GO_ONLINE)}),j(It.DISCONNECTED,async()=>{this.fsmService.service.send(Fe.GO_OFFLINE)}),j("/studioServer/auth/LOGGED_IN",()=>{this.authState="logged_in",this.transport.authorized=!0}),j("/studioServer/auth/LOGIN_REQUIRED",()=>{this.authState="logged_out",this.transport.authorized=!1}),j(It.RELOAD,()=>{this.fsmService.service.send(Fe.RELOAD)}),j("/studio/project/reload",()=>{this.fsmService.service.send(Fe.RELOAD)});const s=Kt.getInstance(),o=Su(),r=Au(),n=Du();s.host=o,s.port=Number.parseInt(r),s.protocol=n,process.env.KOS_ALLOW_ANONYMOUS==="true"&&(s.authorized=!0);const i=t||process.env.KOS_CONNECTION_ALIAS;i&&(s.alias=i.replace("{{TIMESTAMP}}",Date.now().toString())),this._transport=s.init(),this.fsmService=bu(this),this.fsmService.service.send(Fe.CREATE)}get onlineStatus(){return this.isOnline&&!this._reloading&&!this._unloading}get reloading(){return this._reloading}get unloading(){return this._unloading}async reload(){var r,n,i,c;const t=Date.now();if(this._reloading){U.info("reload already in progress");return}this._reloading=!0,U.warn("reloading KOS Core"),U.warn("reloading preloaded models");const s=this.modelManager;for(const l of s.preloadedModels)Gr(l.modelData)&&(U.info(`reloading model ${l.modelId}`),(r=l.unload)==null||r.call(l),await l.modelData.reload(),(n=l.registerSubscribers)==null||n.call(l),U.info(`reloading model ${l.modelId} complete`));for(const l of s.models)!s.preloadedModels.includes(l)&&Gr(l.modelData)&&((i=l.unload)==null||i.call(l),await l.modelData.reload(),(c=l.registerSubscribers)==null||c.call(l));const o=Date.now()-t;setTimeout(()=>{w.runInAction(()=>{U.warn("reloading KOS Core complete"),this._reloading=!1})},1e3-o)}async online(){U.debug("KOS Core going online"),await this._transport.whenReady(),U.debug("KOS Transport Ready. Calling online() for models"),N("/kosCore/online","/kosCore/online"),console.timeEnd("kosCore:startup")}async offline(){U.debug("KOS Core going offline"),N("/kosCore/offline","/kosCore/offline")}async unload(){var r;U.debug("Unloading KOS Core");const t=Date.now();this._unloading=!0,U.debug("unloading KOS Core");const s=this.modelManager;for(const n of s.models)Ru(n.modelData)&&((r=n.unload)==null||r.call(n));const o=Date.now()-t;setTimeout(()=>{w.runInAction(()=>{this._unloading=!1})},1e3-o)}async whenReady(){await w.when(()=>this.status===is.READY)}async ready(){U.debug("Readying KOS Core"),await this._transport.whenReady();const t=this.modelManager.preloadedModels.map(r=>({modelId:r.modelId,model:r,promise:r.whenReady()})),o=(await Promise.allSettled(t.map(r=>{const{promise:n,cancel:i}=Cu(5e3,r.model);Promise.race([r.promise.then(()=>{i()}),n])}))).filter(r=>r.status==="rejected");if(o.length)throw U.error(`There were ${o.length} failed models on model preloading`),Error(`There were ${o.length} failed models on model preloading`);U.debug("leaving kos-core ready() ")}get isReady(){return this.status===is.READY}set transport(t){this._transport=t}get transport(){return this._transport}get coreInitialized(){return this.initialized}get modelsLoaded(){return this.loaded}async init(){U.debug("entering kos-core init()"),console.time("kosCore:startup"),console.time("kosCore:init"),await this._transport.whenReady(),this.initialized=!0,U.debug("initialized - leaving kos-core init()"),console.timeEnd("kosCore:init")}async load(){U.debug("entering kos-core load()"),console.time("kosCore:load"),this.loaded=!0,U.debug("loaded - leaving kos-core load()"),console.timeEnd("kosCore:load")}static create(t,s,o){var i,c,l;const r=this.getInstance({reset:s,connectionAlias:o});(i=t.extensions)!=null&&i.dataMapper&&Object.keys(t.extensions.dataMapper).forEach(d=>{var h,p;const u=(p=(h=t.extensions)==null?void 0:h.dataMapper)==null?void 0:p[d];u&&(Array.isArray(u)?u.forEach(v=>{C.dataMapper.registerDataMapper(d,v)}):C.dataMapper.registerDataMapper(d,u))}),(c=t.extensions)!=null&&c.propertyMapper&&Object.keys(t.extensions.propertyMapper).forEach(d=>{var h,p;const u=(p=(h=t.extensions)==null?void 0:h.propertyMapper)==null?void 0:p[d];u&&C.propertyMapper.registerPropertyMapper(d,u)}),(l=t.extensions)!=null&&l.contextLoader&&Object.keys(t.extensions.contextLoader).forEach(d=>{var h,p;const u=(p=(h=t.extensions)==null?void 0:h.contextLoader)==null?void 0:p[d];u&&C.loader.registerLoader(d,u)}),$.model.getAll().forEach(([,d])=>{t.models={...t.models,...d.registration}}),t.models={...t.models,...$.model.getLegacyModels()},$.companion.getAll().forEach(([d,u])=>{t.companionModels={...t.companionModels},t.companionModels[d]=t.companionModels[d]||[];for(const h of u)t.companionModels[d].push({type:h})}),$.model.getPreloadModels().forEach(d=>{t.preloadModels.includes(d)||t.preloadModels.push(d)});const n=Ti.create(t,s);return r.modelManager=n,r}static getInstance(t){return this._instance=window.KosCore,(!this._instance||t!=null&&t.reset)&&(window.KosCore=new this(t==null?void 0:t.connectionAlias),this._instance=window.KosCore),this._instance}}a(_,"_instance");const Vr=f.createLogger({name:"kos-fetch"}),Lu=process.env.KOS_WS_TIMEOUT?parseInt(process.env.KOS_WS_TIMEOUT):3e4,Pu=()=>new Promise(e=>{setTimeout(()=>{e(!0)},0)}),xu=e=>e!=null&&e.studio?di:e!=null&&e.fos?ui:hi,ku=async(e,t)=>{const s=_.getInstance().transport;await s.whenReady();const o=Ze(),r=new URL(e),n=`${r.pathname}${r.search}`;Vr.debug(`path: ${n}`);const i=(t==null?void 0:t.timeout)||Lu,c=xu(t),l=ve(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(()=>{Vr.error(`Timeout occurred - url: ${e}`),u.abort(),d({headers:uo({}),status:404,ok:!1,json:async()=>null,body:ho(""),redirected:!1,statusText:"",type:"basic",url:"",clone:function(){throw new Error("Function not implemented.")},bodyUsed:!1,arrayBuffer:function(){throw new Error("Function not implemented.")},blob:function(){throw new Error("Function not implemented.")},formData:function(){throw new Error("Function not implemented.")},text:function(){throw new Error("Function not implemented.")}})},i),{unsubscribe:p}=j(o,b=>{var I,A,te;clearTimeout(h);const E={headers:uo((b==null?void 0:b.headers)||{}),status:((I=b==null?void 0:b.headers)==null?void 0:I.status)&&parseInt((A=b==null?void 0:b.headers)==null?void 0:A.status)||200,ok:((te=b==null?void 0:b.headers)==null?void 0:te.status)==="200",json:async()=>{var we;try{return(we=b==null?void 0:b.body)!=null&&we.length?JSON.parse(b.body):null}catch{throw Error("Not a JSON response")}},text:async()=>(b==null?void 0:b.body)||"",body:ho((b==null?void 0:b.body)||""),redirected:!1,statusText:"",type:"basic",url:"",clone:function(){throw new Error("Function not implemented.")},bodyUsed:!1,arrayBuffer:function(){throw new Error("Function not implemented.")},blob:function(){throw new Error("Function not implemented.")},formData:function(){throw new Error("Function not implemented.")}};p(),Pu().then(()=>d(E))}),v=t!=null&&t.fos?s.fosSocket:s.socket;if(!v)throw Error(`No web socket transport available: ${t}`);v==null||v.send(l)})};exports.BASE_URL="kos:";exports.kosFetch=ku;if(process.env.KOS_MOCK_FETCH==="true"){const e=process.env.KOS_PORT||"9999";exports.kosFetch=fetch,exports.BASE_URL=`http://localhost:${e}`}const Fu=f.createLogger({name:"kos-model-visitor",group:"kos-ui-core"});class Nu{constructor(){a(this,"visitedModels",new Set);this.visitedModels=new Set}start(t){var o;if(t.id===void 0)throw new Error("rootModel must have an id");const s=_.getInstance().modelManager.getModelById(t.id);if(!s)throw new Error(`Could not find rootModel with id: ${t.id}`);this.visitedModels.clear(),(o=s.accept)==null||o.call(s,this)}visit(t){var o;if(this.visitedModels.has(t.modelId)){Fu.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 Pi=()=>({isMock:!1,URL:exports.BASE_URL}),Uu=f.createLogger({name:"kos-service-request"}),ju="errUnknown";async function Zt(e,t,s,o,r){const n=o!=null&&o.path?Object.keys(o.path).reduce((h,p)=>String(h).replace(`{${p}}`,o==null?void 0:o.path[p]),String(e)):String(e),i=o!=null&&o.query?Object.keys(o.query).map(h=>`${h}=${o.query[h]}`).join("&"):"",c=`${Pi().URL}${n}${i?`?${encodeURIComponent(i)}`:""}`;Uu.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||ju}`,null]:[null,(await d.json()).data]}function Ho(){return{get:(e,t,s)=>Zt(e,"get",s,t),post:(e,t,s,o)=>Zt(e,"post",o,t,s),put:(e,t,s,o)=>Zt(e,"put",o,t,s),delete:(e,t,s)=>Zt(e,"delete",s,t)}}class 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 Bu=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},Xe=e=>({type:e,build:(t,s)=>_.getInstance().modelManager.createModelInstance(e,t,s).data,buildAsync:async(t,s)=>{const o=_.getInstance().modelManager.createModelInstance(e,t,s);return await o.model.whenInitialized(),o.data}}),Ku=e=>{_.getInstance().modelManager.registerModel(e)},Hu=(e,t)=>{_.getInstance().modelManager.registerCompanionModel(e,t)},ki=Symbol("KosObservableData");class Fi{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)}}Fi.prototype[ki]=!0;function Gu(e,t){return new Proxy(e,{construct:(s,o)=>{const r=new e(...o);return r.setValues(t),r.proxy}})}const ye=e=>{const t=Gu(Fi,e);return new t(e)},Yr="/kos/ui/internal/heartbeat/",Vu=({relationshipId:e,destinationAddress:t,onAbort:s,waitTime:o,beatTime:r})=>{const n=_.getInstance().transport,i=new AbortController;let c=performance.now();const l=n.subscribeTopic({topic:`${Yr}${e}`,callback:()=>{c=performance.now()}}),d=o??3e3,u=window.setInterval(()=>{let E=performance.now()-c;E=E/1e3,E>d/1e3&&i.abort()},d),h=r??2e3,p=window.setInterval(()=>{vi({msg:{},options:{topic:`${Yr}${e}`,destinationAddress:t}})},h),v=()=>{window.clearInterval(p),window.clearInterval(u),l()},b=()=>{v(),s&&s(),i.signal.removeEventListener("abort",b)};return i.signal.addEventListener("abort",b),{cleanUpHeartbeat:v}},Ni=(...e)=>t=>e.reduce((s,o)=>o(s),t),Yu={maxAttempts:5,baseDelayMs:100,backoffFactor:1.5};async function zu(e,t){let s=1;const o={...Yu,...t},{maxAttempts:r,baseDelayMs:n,backoffFactor:i}=o;let c=n;for(;s<=r;)try{return await e()}catch(l){if(f.error(`Attempt ${s} failed: ${l}`),s<r)c=n*Math.pow(i,s),await new Promise(d=>setTimeout(d,c)),s++;else throw l}throw new Error("All attempts failed")}const qu=f.createLogger({name:"kos-service-request"}),q=e=>({isMock:!1,URL:exports.BASE_URL}),Wu=(e,t,s)=>async({id:o,tracker:r,urlOverride:n,ordered:i,studio:c,fos:l,bridge:d,destinationAddress:u})=>{const h={method:"DELETE"};e&&(h.destinationAddress=e),r&&(h.tracker=r),et(h,{ordered:i,studio:c,fos:l,bridge:d,destinationAddress:u});const p=await s(n||`${t}/${o}`,h);if(!p.ok)throw Error(`There was a problem deleting the model; returned status ${p.status}`);return await p.json()},et=(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),Zu=(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),et(u,{timeout:l,ordered:r,studio:n,fos:i,bridge:c,destinationAddress:d});const p=await s(o||t,u);if(!p.ok){let b;try{b=await p.json()}catch{}throw new ne(`There was a problem retrieving the model; returned status ${p.status}`,b)}return await p.json()},Ju=(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),et(h,{timeout:d,ordered:r,studio:n,fos:i,bridge:c,destinationAddress:u});const p=o||t;qu.debug(`resolvedUrl: ${p}`);const v=await s(p,h);if(!v.ok){let E;try{E=await v.json()}catch{}throw new ne(`There was a problem retrieving the model; returned status ${v.status}`,E)}return await v.json()},Qu=(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),et(h,{timeout:d,ordered:n,studio:i,fos:c,bridge:l,destinationAddress:u});const p=o||`${t}/${r}`,v=await s(p,h);if(!v.ok){let E;try{E=await v.json()}catch{}throw new ne(`There was a problem retrieving the model; returned status ${v.status}`,E)}return await v.json()};class ne extends Error{constructor(s,o){super(s);a(this,"payload");this.name="FetchException",this.payload=o}}const zr=(e,t,s)=>async({model:o,urlOverride:r,ordered:n,tracker:i,studio:c,fos:l,bridge:d,timeout:u,destinationAddress:h})=>{const p={method:"POST",body:typeof o=="string"?o:JSON.stringify(o)};e&&(p.destinationAddress=e),i&&(p.tracker=i),et(p,{timeout:u,ordered:n,studio:c,fos:l,bridge:d,destinationAddress:h});const v=await s(r||t,p);if(!v.ok){let E;try{E=await v.json()}catch{}throw new ne(`There was a problem sending the POST data; returned status ${v.status}`,E)}return await v.json()},qr=(e="POST",t,s,o)=>async({model:r,id:n,urlOverride:i,ordered:c,studio:l,fos:d,bridge:u,timeout:h,destinationAddress:p})=>{const v={method:e};r&&(v.body=JSON.stringify(r)),t&&(v.destinationAddress=t),et(v,{timeout:h,ordered:c,studio:l,fos:d,bridge:u,destinationAddress:p});const b=await o(i||`${s}/${n}`,v);if(!b.ok){let I;try{I=await b.json()}catch{}throw new ne(`There was a problem modifying the model; returned status ${b.status}`,I)}return await b.json()},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:Zu(e,s||t,l),getModelById:Qu(e,o||t,l),getOne:Ju(e,o||t,l),addModel:zr(e,n||t,l),deleteModel:Wu(e,r||t,l),modifyModel:qr("POST",e,i||t,l),putModel:qr("PUT",e,i||t,l),postModel:zr(e,n||t,l)}}},Xu=Ze(),Ui=()=>`kos-${Xu}`,eh=e=>!!e&&!e.includes("VM_SERVICE")&&e.startsWith(Ui()),Go=async(e,t=6e4)=>new Promise((s,o)=>{const{unsubscribe:r}=j(e,i=>{T.debug(`recieved response for refId ${e}: ${i}`),r(),clearTimeout(n);try{const c=i!=null&&i.body?JSON.parse(i.body):{};s(c)}catch{const c=(i==null?void 0:i.body)||{};s(c)}}),n=setTimeout(()=>{r(),o(Error(`Request with ID ${e} timed out. Cancelling.`))},t)}),th=async(e,t,s)=>{const o=Go(s),r=await Promise.allSettled([e(t),o]);if(r[0].status==="fulfilled"){if(r[1].status==="rejected")throw Error(r[1].reason);if(r[0].value){if(r[1].value.error)throw Error(r[1].value.error);return r[0].value.data=r[1].value,r[0].value}}else throw Error(r[0].reason)},sh=async({topic:e,msg:t,requestId:s})=>{const o=s??Ze(),r=Go(o);N(e,t,{sync:o});const n=await r;if(n.error)throw Error(n.error);return n},de=new Map;class ji{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){K(()=>{this._parent=t})}get id(){return this._id}get context(){return this._context}get parentModel(){var t;if(this._parent)return(t=Qe(this._parent))==null?void 0:t.model}get(t){var s;if(this._context.has(t))return this._context.get(t);if(this._parent)return(s=de.get(this._parent))==null?void 0:s.get(t)}set(t,s){this._context.set(t,s)}remove(t){this._context.delete(t)}clear(){this._context.clear()}}const x={createContext:(e,t)=>{const s=de.get(e)??new ji(e);if(t){if(!de.has(t))throw new Error(`Parent context ${t} does not exist`);s.setParent(t)}else e!=="root"&&s.setParent("root");return de.set(e,s),s},getContext:e=>de.get(e),deleteContext:e=>{de.delete(e)},setParentContext:(e,t)=>{var s;if(!de.has(t))throw new Error(`Parent context ${t} does not exist`);(s=de.get(e))==null||s.setParent(t)},rootContext:()=>de.get("root")};x.createContext("root");const oh=e=>x.getContext(e.id);function rh(e,t){return e.length!==t.length?!1:e.every(s=>t.includes(s))}class Vo{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=ye(),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(rh(n,i))f.debug(`KosContainerIndex - Index ${r} is the same`);else{this.data[r]=n;const c=t.get(r)||new Set;this._map.set(r,c)}})}generateIndex(){w.runInAction(async()=>{const t=new Map,s={};for(const o of this._container.data){const r=typeof this._key=="function"?await this._key(o):o[this._key];Array.isArray(r)?r.forEach(n=>{this.addItemToIndex(n,o,t,s)}):typeof r=="string"||typeof r=="number"?this.addItemToIndex(String(r),o,t,s):typeof r=="boolean"&&this.addItemToIndex(String(r),o,t,s)}this.resolveIndex(t,s)})}get keys(){return Array.from(this._map.keys())}get index(){return this._map}getByKey(t){const s=this._map.get(t);return s?Array.from(s):[]}}function nh(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 nt=f.createLogger({name:"kos-container-model"});class me{constructor(t){a(this,"_data");a(this,"_sortKey");a(this,"_revision");a(this,"_index");a(this,"_optionsMap");a(this,"_disposerMap",new Map);a(this,"_parentId");a(this,"idx");this._data=w.observable.map(new Map),this._sortKey=t==null?void 0:t.sortKey,this._revision=1;const s=t!=null&&t.extensionId?C.indexExtension.loadIndexExtensions(t.extensionId):{},o=(t==null?void 0:t.indexMap)||{};this._optionsMap={...o,...s};const r=t!=null&&t.indexMap?Object.keys(t.indexMap).reduce((n,i)=>(n[i]=void 0,n),{}):{};this._index=w.observable.map(r),this.idx=ye(),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 Vo({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 p,v;n.includes(u.name)&&((p=this.index.get(i.get(u.name)))==null||p.refresh());const h=r.filter(([,b])=>typeof b=="function");for(const[b]of h)(v=this.index.get(b))==null||v.refresh()},l=nh(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??[]:(nt.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):(nt.info(`key ${s} not found in ${t} index: ${Array.from(o.index.keys())}`),[])}else return nt.info(`index ${t} not found in ${Array.from(this.index.keys())}`),[]}async clear(){this._data.forEach(t=>{const s=t.id;Oe(t).then(()=>{nt.debug(`${s} destroyed, removing from map`),this.removeModel(s,!0)}).catch(o=>nt.error(o))}),this.increment()}filter(t,s){return this.data.filter(t,s)}sort(t){return this.data.sort(t)}map(t,s){return this.data.map(t,s)}forEach(t,s){this.data.forEach(t,s)}toJSON(){return{indexes:this.indexKeys,data:this.data.map(s=>({id:s.id,type:s.constructor.name}))}}}const ro=f.createLogger({name:"kos-data-container"});class Bi{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=ye(),w.makeAutoObservable(this,{}),this.init()}init(){Object.keys(this._optionsMap).forEach(t=>{const s=this._optionsMap[t],o=new Vo({container:this,key:s});this._index.set(t,o),this.idx[t]=o.data})}[Symbol.iterator](){return this.data[Symbol.iterator]()}get index(){return this._index}get indexKeys(){return Array.from(this.index.keys()).reduce((t,s)=>{var o;return t[s]=(o=this.index.get(s))==null?void 0:o.keys,t},{})}get revision(){return this._revision}addAll(t){w.runInAction(()=>{t.forEach(s=>this.addModel(s))})}removeAll(t){w.runInAction(()=>{t.forEach(s=>this.removeModel(s))})}sortFn(t,s){const o=this._sortKey;return o?String(t[o]).localeCompare(String(s[o]),void 0,{numeric:!0}):0}get data(){const t=Array.from(this._data.values());return this._sortKey&&t.sort(this.sortFn.bind(this)),t}increment(){w.runInAction(()=>{this._revision=this._revision+1})}addModel(t,s){const o=w.isObservable(t)?t:w.observable.object(t),r=this._disposerMap.get(t.id);r&&(r(),this._disposerMap.delete(t.id)),this._data.set(o.id||"",o),s||this.increment();const n=w.observe(o,i=>{Object.values(this._optionsMap||{}).includes(i.name)&&this.increment()});this._disposerMap.set(o.id||"",n)}removeModel(t){this._data.delete(t),this.increment();const s=this._disposerMap.get(t);s&&(s(),this._disposerMap.delete(t))}updateModel(t){const s=w.observable.object(t);this._data.set(s.id||"",s),this.increment()}getModel(t){return this._data.get(t)}getIndexKeys(t){return this.index.has(t)?this.index.get(t).keys??[]:(ro.info(`index ${t} not found in ${Array.from(this.index.keys())}`),[])}getIndexByKey(t,s){if(this.index.has(t)){const o=this.index.get(t);return o.index.has(s)?o.getByKey(s):(ro.info(`key ${s} not found in ${t} index: ${Array.from(o.index.keys())}`),[])}else return ro.info(`index ${t} not found in ${Array.from(this.index.keys())}`),[]}async clear(){this._data.clear(),this.increment()}filter(t,s){return this.data.filter(t,s)}sort(t){return this.data.sort(t)}map(t,s){return this.data.map(t,s)}forEach(t,s){this.data.forEach(t,s)}toJSON(){return{indexes:this.indexKeys,data:this.data.map(s=>({id:s.id}))}}}class ih{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 ee(this.type)}}class ah{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 ee(this.type)}}class Ki{constructor(){a(this,"_token");w.makeAutoObservable(this),j("token",t=>{this.token=t==null?void 0:t.body})}get token(){return this._token}set token(t){this._token=t}}class Hi{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 p=l.middlewares[u++];await p(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 Gi=f.createLogger({name:"intent-service"}),ch=e=>{Lo(`/kos/intent/${e.type}`)?N(`/kos/intent/${e.type}`,e.options,{"kos.intent.type":e.type}):Gi.info(`No subscribers for intent ${e.type}. Intent not sent.`)},lh=async e=>new Promise(t=>{const{type:s,options:o}=e;if(Lo(`/kos/intent/${e.type}`)){const r=Ze(),{unsubscribe:n}=j(r,c=>{clearTimeout(i),n(),c&&(c.headers=c.headers||{},c.headers["kos.intent.type"]=s,c.headers.responseId=r),t([null,{body:c==null?void 0:c.body,payload:c}])}),i=setTimeout(()=>{n(),t([`Intent ${s} timed out after 1 second`,null]),console.warn(`Intent ${s} timed out after 1 second`)},1e3);N(`/kos/intent/${s}`,o,{"kos.intent.type":s,sync:r})}else Gi.info(`No subscribers for intent ${e.type}. Intent not sent.`),t([null,{body:void 0,payload:void 0}])}),po=w.when,Yo=w.computed,K=w.runInAction,F=w.autorun,Vi=w.reaction,zo=w.observable,qo="Not Assigned",dh="kos.trouble.added",uh="kos.trouble.removed";var oe=(e=>(e.TroubleRank="kos.trouble.rank.mapper",e.TroubleColor="kos.trouble.color.mapper",e.TroubleRole="kos.trouble.role.mapper",e))(oe||{}),$t=(e=>(e.TIME_CHANGE="/kos/internal/time/time",e.DAY_CHANGE="/kos/internal/time/day",e.TIMEZONE_CHANGE="/kos/internal/time/timezone",e))($t||{});const Yi=f.createLogger({name:"config-bean-service",group:"Services"}),Wo=exports.BASE_URL,zi=e=>(e==null?void 0:e.decimals)!==void 0,{postModel:hh,getOne:gh}=Y.build({destinationAddress:"",basePath:`${Wo}/kos/config/`}),qi=async(e,t,s="/api/kos/config")=>(Yi.debug(`sending modify request for ConfigBean: ${e}`),hh({model:t,urlOverride:`${Wo}${s}/${e}`})),Wi=async(e,t="/api/kos/config")=>(Yi.debug(`sending get request for ConfigBean: ${e}`),await gh({urlOverride:`${Wo}${t}/details/${e}/15`})),Zo=e=>e.toLowerCase()==="true"||e.toLowerCase()==="false",Fs=e=>{try{const t=Number(e);return!isNaN(t)}catch{return!1}};function Zi(e=[]){return e.reverse().reduce((t,s)=>{const{overrides:o}=s;return o&&(t={...t,...o}),t},{})}function Ji(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])?Ji(e[o],r,s):s[r]=e[o]}return s}const Qi=(e,t)=>{const s=e.details[0].bean||Zi(e.details[0].scopes),o=Ji(s);w.runInAction(()=>{const r={...o};t.props.setValues(r)})},Xi=(e,t)=>{w.runInAction(()=>{e.changes.forEach(s=>{const o=s.attr;let r=s.currentValue,n=s.previousValue;typeof r=="string"&&Zo(r)&&(r=r.toLowerCase()=="true",n=(n==null?void 0:n.toLowerCase())=="true"),typeof r=="string"&&Fs(r)&&(r=Number(r),n=Number(n)),t.props[o]=r,t.prevProps[o]=n})})},ea=e=>Object.fromEntries(e.props.entries),fh=e=>t=>s=>e.build(t,s);var mh=Object.defineProperty,ph=Object.getOwnPropertyDescriptor,ta=(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&&mh(t,s,r),r};function yh(e,t){for(const s of e)if(new RegExp(`^${s}$`).test(t))return s}const Jo="config-bean-model",Jt=f.getLogger(Jo),bh=Se("path");let gs=class{constructor(e,t){a(this,"_modifyConfigBean");a(this,"_getConfigBean");a(this,"_schema");a(this,"id");a(this,"path");a(this,"props");a(this,"prevProps");a(this,"serviceBasePath");Object.assign(this,t),this.id=e,this.path=t.path,this.serviceBasePath=t.serviceBasePath;const{modifyConfigBean:s=qi,getConfigBean:o=Wi}=t;this._modifyConfigBean=s,this._getConfigBean=o,this.props=ye(),this.prevProps=ye()}get values(){return this.props.values}async ready(){Jt.debug(`readying config bean ${this.path}`),Jt.debug(`complete readying config bean ${this.path}`)}async load(){Jt.debug(`loading config bean ${this.path}`);const e=await this._getConfigBean(this.path,this.serviceBasePath);if(e!=null&&e.data){const t=e.data;Qi(t,this),Jt.debug(this.values);const s=e==null?void 0:e.data.details[0].schema;K(()=>{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=yh(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=ea(this);await this._modifyConfigBean(this.path,e,this.serviceBasePath)}handleConfigBeanUpdated(e){Xi(e,this)}};ta([R({topic:`/kos/config/${bh}`,websocket:!0})],gs.prototype,"handleConfigBeanUpdated",1);gs=ta([D(Jo)],gs);const St=new le({class:gs,type:Jo}),Ns=({path:e,lazy:t,serviceBasePath:s})=>(o,r)=>{o[P]=o[P]||{},o[P][r]={modelType:St.type,id:`${St.type}-${e}`,options:{path:e,serviceBasePath:s},lifecycle:k.INIT,lazy:t}},{URL:sa}=q(),{getOne:vh,getAll:wh}=Y.build({basePath:`${sa}/api/kos/regions/info`}),oa=async()=>await vh({}),ra=async()=>await wh({urlOverride:`${sa}/api/kos/regions`}),Mh=Object.freeze(Object.defineProperty({__proto__:null,getRegionInfo:oa,getRegions:ra},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 na={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 Eh(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},{...na});return{...e,...o}}function _h(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]:{...na}}});return Object.keys(o).forEach(r=>{e[r]={...e[r],...o[r]}}),e}function Ih(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 Th=Object.defineProperty,$h=Object.getOwnPropertyDescriptor,Qo=(e,t,s,o)=>{for(var r=o>1?void 0:o?$h(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&&Th(t,s,r),r};const as="region-info-model",it=f.createLogger({name:"region-info-model"});let At=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||it.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||it.info("Could not find default unit for measure",t.measure)}return!n||!i?(it.warn("Could not find unit to convert to or from. Return value as is"),String(e)):this.convertByUnit(e,n,i)}async init(){it.debug("initializing region info")}async load(){it.debug("loading region info");const e=await ra();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 oa();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(Eh,{}),this.measureMap=t.data.unitSystems.reduce(_h,{}),this.defaultMeasureMap=t.data.unitSystems.reduce(Ih,{}),this.timeFormats=t.data.timeFormats.reduce((s,o)=>({...s,[o.id]:o}),{}),this.dateFormats=t.data.dateFormats.reduce((s,o)=>({...s,[o.id]:o}),{}))}async ready(){var e,t;await((t=(e=this.regionSource).ready)==null?void 0:t.call(e))}};Qo([Ns({path:"kos:service:region:settings"})],At.prototype,"regionSource",2);Qo([Ns({path:"kos:service:region"})],At.prototype,"region",2);At=Qo([D(as)],At);const z={registration:{[as]:{class:At,singleton:!0}},type:as,factory:V.Singleton.create(as)},Wr=({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},ia=(e,t,s)=>{const{model:o}=Qe(z.type);if(!o)throw new Error("RegionInfo model not found");if(!hs(o))throw new Error("RegionInfo model not ready");const r={system:o.defaultUnitSystem},n=Wr({source:t}),i=Wr({source:s||r,defaultMeasure:o.getUnitMeasure(n.unit||"")});return o.convert(e,n,i)};function Zr({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 Jr({start:e,end:t,interval:s,decimals:o=0}){if(typeof e!="number"||typeof t!="number"||typeof s!="number")throw new Error("All input values should be numbers.");if(s<=0)throw new Error("Interval should be a positive number.");if(e>=t)throw new Error("Start should be less than end.");const r=[];let n=e;for(;n<=t;)r.push(n.toFixed(o)),n+=s;return r[r.length-1]!==t.toString()&&r.push(t.toString()),r}const Le=(e,t)=>s=>!e||!t?s:Fs(s)?ia(Number(s),e,t):s,Oh=(e,t,s,o)=>{if((e==null?void 0:e.type)==="enum"||!(e!=null&&e.options))return[];if(e.options.type==="rangeCount")return Zr(e.options).map(Le(s,o));if(e.options.type==="rangeInterval")return Jr(e.options).map(Le(s,o));if(e.options.type==="list"){const{list:r}=e.options;return r.map(Le(s,o))}else{if(e.options.type==="unitSystemRangeCount"&&t)return Zr(e.options.unitSystems[t]).map(Le(s,o));if(e.options.type==="unitSystemRangeInterval"&&t)return Jr(e.options.unitSystems[t]).map(Le(s,o));if(e.options.type==="unitSystemList"&&t){const{list:r}=e.options.unitSystems[t];return r.map(Le(s,o))}}return[]},Dh=(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 Sh=Object.defineProperty,Ah=Object.getOwnPropertyDescriptor,Xo=(e,t,s,o)=>{for(var r=o>1?void 0:o?Ah(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&&Sh(t,s,r),r};function Ch(e){return(e==null?void 0:e.type)==="enum"}function Rh(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 Lh(e,t){const s=new Date;s.setHours(0,0,0,0);const o=new Date(s.getTime()+e*1e3);return pe.format(o,t)}const cs="config-bean-prop-model",Pe=f.createLogger({name:"config-bean-prop-model"}),Ph=Se("path"),xh=Se("serviceBasePath");let Ct=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 zi(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?Rh(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=Ch(o)?o.values:Oh(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){Pe.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(){Pe.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 Lh(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){Pe.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 Dh(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){Pe.error(`error creating formatter ${u}. Returning the raw value`,h)}}else Pe.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,p,v;const{unit:e,measure:t}=this.getConverterFromFormat(),s=e==="drt"?"second":e;if(this.converter){const b=(o=this.converter)==null?void 0:o.measure,E=(n=(r=this.converter)==null?void 0:r.to)==null?void 0:n.measure,I=(c=(i=this.converter)==null?void 0:i.from)==null?void 0:c.measure,A=b||E||I||t,te=((d=(l=this.converter)==null?void 0:l.to)==null?void 0:d.unit)||this.regionInfo.getDefaultUnitForMeasure(A,((h=(u=this.converter)==null?void 0:u.to)==null?void 0:h.system)??this.regionInfo.defaultUnitSystem),we=((v=(p=this.converter)==null?void 0:p.to)==null?void 0:v.system)??this.regionInfo.getUnitSystem(te),ot=this.schemaFormat==="drt"?"second":this.schemaFormat||s;return{...this.converter,from:{unit:ot,...this.converter.from},to:{...this.converter.to,unit:te,system:we},measure:A}}if(s&&t){const b=this.regionInfo.getDefaultUnitForMeasure(t,this.regionInfo.defaultUnitSystem),E=this.regionInfo.getUnitSystem(s),I=this.regionInfo.getUnitSystem(b);return{measure:t,to:{unit:E===I?s:b}}}}async updateProperty(e){Pe.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)}};Xo([Je({modelType:z.type})],Ct.prototype,"regionInfo",2);Xo([Ns({path:Ph,serviceBasePath:xh})],Ct.prototype,"bean",2);Ct=Xo([D(cs)],Ct);const Ae={registration:{[cs]:{class:Ct,singleton:!1}},type:cs,factory:V.Factory.create(cs)};function kh(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[P]=d[P]||{},d[P][u]={modelType:Ae.type,id:`${t}-${s}`,options:{path:t,attribute:s,serviceBasePath:c,converter:l,formatter:r,optionsExpander:i},lifecycle:k.INIT,lazy:n}}}class Fh{constructor(t,s){a(this,"futures");a(this,"defaultContext");a(this,"context");a(this,"disposers",new Map);a(this,"container");this.futures=zo.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=F(()=>{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 er{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=F(()=>{var o,r;(t.endState||t.progress)&&((r=(o=this.container)==null?void 0:o.onFutureUpdate)==null||r.call(o,t))});this.disposer=s}get allFutures(){return this._future?[this._future]:[]}get timeRemaining(){var t;return((t=this._future)==null?void 0:t.timeRemaining)||""}get status(){var t;return((t=this._future)==null?void 0:t.status)||"NOT_RESOLVED"}get progress(){var t;return((t=this._future)==null?void 0:t.progress)||-1}async cancel(){if(this._future)try{await this._future.cancelFuture()}catch(t){throw f.error(t),t}}}const aa="future-model",tt=Xe(aa),Us=f.createLogger({name:"future-service",group:"Services"}),{isMock:Nh,URL:Ht}=q();var Ke=(e=>(e.Success="SUCCESS",e.Fail="FAIL",e.Aborted="ABORT",e.Canceled="CANCEL",e))(Ke||{});const{getAll:Uh,modifyModel:jh,addModel:Bh,deleteModel:Kh,postModel:Hh}=Y.build({destinationAddress:"",basePath:`${Ht}/api/future`,mock:Nh}),Gh=async()=>await Uh({}),ca=async(e,t="/api/kos/future")=>(Us.info(`sending delete request for Future: ${e}`),await Kh({id:e,urlOverride:`${Ht}${t}/${e}`})),la=async(e,t="/api/kos/future")=>(Us.info("sending add request for Future"),await Bh({model:e,urlOverride:`${Ht}${t}`})),Vh=async(e,t,s="/api/kos/future")=>(Us.info(`sending modify request for Future: ${e}`),jh({model:t,id:e,urlOverride:`${Ht}${s}/${e}`})),da=async(e,t="/api/kos/future")=>(Us.info(`sending cancel request for Future: ${e}`),Hh({urlOverride:`${Ht}${t}/${e}/cancel`,ordered:!0,model:{}})),tr=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}),sr=(e,t)=>{f.debug(`future dto ${e.id} end state ${e.endState}`),f.debug(`future model ${t.id} end state ${t.endState}`),t.endState?f.debug(`future model ${t.id} is already complete`):(f.debug(`updating future model ${t.id}`),w.runInAction(()=>{const s=tr(e);K(()=>{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]})})}))},ua=e=>t=>s=>e.build(String(t),s),or=e=>t=>Ni(tr,ua(e)(t.tracker||t.id))(t);var Yh=Object.defineProperty,zh=Object.getOwnPropertyDescriptor,ha=(e,t,s,o)=>{for(var r=o>1?void 0:o?zh(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Yh(t,s,r),r};const no=f.getLogger(tt.type);let fs=class{constructor(e,t,s){a(this,"logger");a(this,"_cancelFuture");a(this,"futureId");Object.assign(this,t),this.logger=s.logger,this.id=e,this.futureId=t.id,this.namespace=t.namespace||"kos",this._cancelFuture=da,po(()=>this.status===Ke.Success||this.status===Ke.Fail,()=>{no.info(`Future ${this.id} has completed with status ${this.status}`),Oe(this)})}async load(){no.debug(`loading Future ${this.id}`)}unload(){no.info(`unloading Future ${this.id}`)}async cancelFuture(){const e=this.namespace==="studio"?"/api/future":`/api/${this.namespace}/future`;await po(()=>this.futureId!==qo),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}`),sr(e,this)}};ha([R({topic:`kos.future/${ds}`})],fs.prototype,"handleFutureUpdated",1);fs=ha([D(tt.type)],fs);const ga=fs,fa=Ho();var qh=Object.defineProperty,Wh=Object.getOwnPropertyDescriptor,ma=(e,t,s,o)=>{for(var r=o>1?void 0:o?Wh(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&qh(t,s,r),r};const pa="browser-router-model",Zh="kos.http.request",Jh="kos.http.response";let ms=class{constructor(e,t,s){a(this,"_id");a(this,"logger");a(this,"router");this._id=e,this.logger=s.logger,this.router=new Hi}get id(){return this._id}async handleRequest(e,t){const s=t.headers["src-addr"],o=t.headers["dst-addr"],r=t.headers.url,n=t.headers.method,i=t.headers["request-id"],c={id:i,method:n,path:r};let l=200;const d={send:u=>{this.logger.debug(`sending response to ${o}`),this.logger.debug(u),wi({msg:u,options:{responseId:i,destinationAddress:s,type:Jh,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}`)}};ma([R({topic:Zh})],ms.prototype,"handleRequest",1);ms=ma([D(pa)],ms);const rr=new fe({class:ms,type:pa}),ya="future-container-model",be=Xe(ya),ba=e=>or(tt)(e),Qh=e=>{const t=ba(e);return be.build(be.type,{}).addFutureModel(t),t},Xh=e=>be.build(be.type,{}).getFuture(String(e)),De={buildFutureModel:ba,initiateFuture:Qh,getFuture:Xh};var eg=Object.defineProperty,tg=Object.getOwnPropertyDescriptor,nr=(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&&eg(t,s,r),r};const Qt=f.getLogger(be.type);let Rt=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=ca,addFuture:r=la}=t;this.logger=s.logger,this._deleteFuture=o,this._addFuture=r,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){Qt.error("error deleting a Future"),Qt.error(t)}}async createFuture(e){try{const t=await this._addFuture(e),s=t==null?void 0:t.data;if(s){const o=or(tt)(s);return this.addFutureModel(o),o}}catch(t){throw Qt.error("error creating a Future"),Qt.error(t),t}}handleFutureUpdated(e,t){const s=De.buildFutureModel(e);this.addFutureModel(s);const o=`kos.future/${e.tracker||e.id}`;this.logger.debug(`publishing future update to ${o}`),N(o,t.body,t.headers)}};nr([ce],Rt.prototype,"_futures",2);nr([R({topic:"kos.future"})],Rt.prototype,"handleFutureUpdated",1);Rt=nr([D(be.type)],Rt);const va=Rt,{URL:Gt}=q(),{getOne:sg,postModel:og,deleteModel:wa}=Y.build({basePath:`${Gt}/api/keyVal`}),yo=f.createLogger({name:"key-value-service",group:"Services"}),Ma=async(e,t)=>{await wa({urlOverride:`${Gt}/api/keyVal/${e}/${t}`,id:t})},Ea=async(e,t,s)=>{const o=await og({urlOverride:`${Gt}/api/keyVal/${e}/${t}`,model:s.toString()});if((o==null?void 0:o.status)!==200)throw yo.error("Failed to update studio-state data",o),new Error(`Failed to update studio-state data for namespace ${e}`);return o.data},_a=async(e="studio")=>{yo.debug("sending GET for studio-state");const t=await sg({urlOverride:`${Gt}/api/keyVal/${e}`});if((t==null?void 0:t.status)!==200)throw yo.error("Failed to retrieve studio-state data",t),new Error(`Failed to retrieve studio-state data for namespace ${e}`);return t.data},rg=async e=>{await wa({urlOverride:`${Gt}/api/keyVal/${e}}`,id:""})},ng=Object.freeze(Object.defineProperty({__proto__:null,deleteKeyValue:Ma,deleteKeyValueNamespace:rg,getKeyValue:_a,updateKeyValue:Ea},Symbol.toStringTag,{value:"Module"}));var ig=Object.defineProperty,ag=Object.getOwnPropertyDescriptor,ir=(e,t,s,o)=>{for(var r=o>1?void 0:o?ag(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 Ia="key-value-model";let Lt=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=ye(),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 Ea(this.namespace,e,t),this.data[e]=t):(await Ma(this.namespace,e),this.data[e]=void 0)}async load(){this.logger.debug(`loading studio-state ${this.id}`);const e=await _a(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)}};ir([R({topic:"/keyVal/set"})],Lt.prototype,"handleStateUpdate",1);ir([R({topic:"/keyVal/remove"})],Lt.prototype,"handleStateDelete",1);Lt=ir([D(Ia)],Lt);const ar=new le({class:Lt,type:Ia}),{URL:Vt}=q(),{postModel:cr,getOne:cg}=Y.build({basePath:`${Vt}/api/kos-time`});f.createLogger({name:"kos-time-service",group:"Services"});const Ta=async e=>{const t=await cr({model:e,urlOverride:`${Vt}/api/kos/time/time`});if((t==null?void 0:t.status)!==200)throw Error("Failed to set time");return t.data},$a=async e=>{const t=await cr({model:e,urlOverride:`${Vt}/api/kos/time/date`});if((t==null?void 0:t.status)!==200)throw Error("Failed to set time");return t.data},Oa=async e=>{const t=await cr({model:{},urlOverride:`${Vt}/api/kos/time/timezone?tz=${e}`});if((t==null?void 0:t.status)!==200)throw Error("Failed to set timezone");return t.data},Da=async()=>{const e=await cg({urlOverride:`${Vt}/api/kos/time/timezone`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set timezone");return e.data.timeZone},lg=Object.freeze(Object.defineProperty({__proto__:null,getTimezone:Da,setDate:$a,setTime:Ta,setTimezone:Oa},Symbol.toStringTag,{value:"Module"}));var dg=Object.defineProperty,ug=Object.getOwnPropertyDescriptor,js=(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 ct="kos-time-model",hg="/kos/time/time",gg="/kos/time/day",fg="/kos/time/timezone";let He=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 Ta(e)}async updateSystemDate(e){await $a(e)}async updateSystemTimezone(e){await Oa(e)}handleTimeChange(){N($t.TIME_CHANGE,{})}handleDayChange(){N($t.DAY_CHANGE,{})}async handleTimeZoneChange(){await this.retrieveTimezone(),N($t.TIMEZONE_CHANGE,{})}async init(){this.logger.debug(`initializing kos-time ${this.id}`)}async retrieveTimezone(){const e=await Da();this.setTimezone(e)}setTimezone(e){this.timezone=e}async load(){this.logger.debug(`loading kos-time ${this.id}`),this.retrieveTimezone()}};js([R({topic:hg,websocket:!0})],He.prototype,"handleTimeChange",1);js([R({topic:gg,websocket:!0})],He.prototype,"handleDayChange",1);js([R({topic:fg,websocket:!0})],He.prototype,"handleTimeZoneChange",1);He=js([D(ct)],He);const ps={registration:{[ct]:{class:He,singleton:!0}},type:ct,predicate:ee(ct),factory:V.Singleton.create(ct)};var mg=Object.defineProperty,pg=Object.getOwnPropertyDescriptor,Sa=(e,t,s,o)=>{for(var r=o>1?void 0:o?pg(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&mg(t,s,r),r};const Aa="log-block-container-model";let ys=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(this,"_models");this.id=e,this.logger=s.logger,this._models=new 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}`)}};Sa([ce],ys.prototype,"_models",2);ys=Sa([D(Aa)],ys);const Ce=Ho(),yg=f.createLogger({name:"log-stream-container-service",group:"Services"}),Ca=()=>{var o;const e=ae(),s=(e==null?void 0:e.connId)||((o=window==null?void 0:window.kosBridge)==null?void 0:o.call(window,"connId"));return f.error(`getKosConnectionId: ${s}`),s},st=Ca(),bg="/api/kos/logs/node/{nodeId}/streams",Ra=async()=>(yg.debug("sending GET for log-stream-container"),await Ce.get(bg,{path:{nodeId:"primary"}},{destinationAddress:st})),La=async(e,t="primary")=>{await Ce.post("/api/kos/logs/node/{nodeId}/{stream}/subscribe",{path:{nodeId:t,stream:e}},void 0,{destinationAddress:st})},Pa=async e=>{await Ce.post("/api/kos/logs/node/{nodeId}/{stream}/unsubscribe",{path:{nodeId:"primary",stream:e}},void 0,{destinationAddress:st})},vg=async()=>{await Ce.post("/api/kos/logs/overrides",{},{level:"WARN",name:"com.example",nodeType:"java",type:"package"},{destinationAddress:st})},xa=async e=>await Ce.get("/api/kos/logs/node/{nodeId}/{stream}/blocks",{path:{nodeId:"primary",stream:e}},{destinationAddress:st}),ka=async(e,t)=>await Ce.get("/api/kos/logs/node/{nodeId}/{stream}/blocks/{blockId}",{path:{nodeId:"primary",stream:e,blockId:t}},{destinationAddress:st}),wg=Object.freeze(Object.defineProperty({__proto__:null,createOverride:vg,getKosConnectionId:Ca,getLogStreamBlock:ka,getLogStreamBlocks:xa,getLogStreams:Ra,subscribeToLogStream:La,unsubscribeFromLogStream:Pa},Symbol.toStringTag,{value:"Module"}));var Mg=Object.defineProperty,Eg=Object.getOwnPropertyDescriptor,_g=(e,t,s,o)=>{for(var r=o>1?void 0:o?Eg(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Mg(t,s,r),r};const Fa="log-block-model";let bo=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(this,"nodeId");a(this,"stream");a(this,"blockNum");a(this,"startLineNum");a(this,"endLineNum");a(this,"startTime");a(this,"endTime");a(this,"lineCount");a(this,"lines");a(this,"inc");this.id=e,this.logger=s.logger,this.nodeId=t.nodeId,this.stream=t.stream,this.blockNum=t.blockNum,this.startLineNum=t.startLineNum,this.endLineNum=t.endLineNum,this.startTime=t.startTime,this.endTime=t.endTime,this.lineCount=t.lineCount,this.lines=[],this.inc=0}async syncLines(){const[e,t]=await ka(this.stream,this.blockNum);if(e){this.logger.error(`Failed to get log block ${this.blockNum}`);return}t&&this.addLines(t.lines,!0)}updateModel(e){this.startLineNum=e.startLineNum,this.endLineNum=e.endLineNum,this.startTime=e.startTime,this.endTime=e.endTime,this.lineCount=e.lineCount}addLines(e,t){const s=t?[]:this.lines;this.lines=[...s,...e],this.inc+=1}async init(){this.logger.debug(`initializing log-block ${this.id}`)}async load(){this.logger.debug(`loading log-block ${this.id}`)}};bo=_g([D(Fa)],bo);const Pt=new le({class:bo,type:Fa}),Bs=new le({class:ys,type:Aa});Bs.addRelatedModel(Pt);var Ig=Object.defineProperty,Tg=Object.getOwnPropertyDescriptor,Na=(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 Ua="log-stream-model";let bs=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(this,"nodeId");a(this,"_blocks");a(this,"name");a(this,"currentBlockId");a(this,"isResetting");a(this,"generatorInstance");a(this,"shouldStop",!1);this.id=e,this.logger=s.logger,this.currentBlockId="",this.name=t.name,this.nodeId=t.nodeId,this.isResetting=!0,this._blocks=Bs.instance(`${e}-blocks`).options({}).build()}get firstLineNum(){const e=this.populated[0];return e?e.startLineNum:0}get currentBlock(){const e=this.currentBlockId;return this._blocks.getModel(e)}get populated(){return this._blocks.data.filter(e=>e.lines.length>0)}get blocks(){return this._blocks.data}get totalLineCount(){return this.populated.reduce((e,t)=>e+t.lineCount,0)}accept(e){e.visit(this)}updateBlock(e){var o;let t=this._blocks.models.getModel(`${e.stream}-block-${e.blockNum}`);const s={nodeId:e.nodeId,blockNum:e.blockNum,endLineNum:e.endLineNum,lineCount:e.lineCount,startLineNum:e.startLineNum,stream:this.name,endTime:new Date(e.endTime),startTime:new Date(e.startTime)};t||(t=Pt.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=Pt.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 La(this.name)}async unsubscribe(){await Pa(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 xa(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=Vi(()=>{const n=this.currentBlock;return n?{blockId:this.currentBlockId,lineCount:n.lines.length}:null},n=>{const i=this.currentBlock;if(i)if(o!==(n==null?void 0:n.blockId))o=n==null?void 0:n.blockId,s=0,e.push(...i.lines);else{const c=i.lines.slice(s);e.push(...c),s+=c.length}t&&(t(),t=null)},{fireImmediately:!0});try{for(const n of this.populated.filter(i=>i!==this.currentBlock))for(const i of n.lines)yield i;for(;;)for(e.length===0&&await new Promise(n=>t=n);e.length>0;)yield e.shift()}finally{r()}}};Na([ce],bs.prototype,"_blocks",2);bs=Na([D(Ua)],bs);const Ot=new le({class:bs,type:Ua});var $g=Object.defineProperty,Og=Object.getOwnPropertyDescriptor,Re=(e,t,s,o)=>{for(var r=o>1?void 0:o?Og(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&&$g(t,s,r),r};const ja="log-stream-container-model",Dg="/kos/logs/subscription/addBlock/*",Sg="/kos/logs/subscription/updateBlock/*",Ag="/kos/logs/subscription/removeBlock/*",Cg="/kos/logs/subscription/lines/*",Ba="/kos/logs/streams/add/*";let ue=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(this,"selectedStream");a(this,"_models");this.id=e,this.logger=s.logger,this._models=new 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: ${Ba}`);const t=e.stream,s=Ot.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=Ot.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 Ra();if(e){this.logger.error(`Error loading log-streams: ${e}`);return}t&&t.forEach(s=>{const o=Ot.instance(s).options({name:s,nodeId:"primary"}).build();this.addModel(o)})}};Re([ce],ue.prototype,"_models",2);Re([R({topic:[Ba],websocket:!0})],ue.prototype,"handleStreamAdded",1);Re([R({topic:[Dg],websocket:!0})],ue.prototype,"handleAddBlock",1);Re([R({topic:[Ag],websocket:!0})],ue.prototype,"handleRemoveBlock",1);Re([R({topic:[Sg],websocket:!0})],ue.prototype,"handleUpdateBlock",1);Re([R({topic:[Cg],websocket:!0})],ue.prototype,"handleLogLine",1);ue=Re([D(ja)],ue);const Yt=new fe({class:ue,type:ja});Yt.addRelatedModel(Ot);Yt.addRelatedModel(Bs);Yt.addRelatedModel(Pt);const Rg=e=>e.rank!==void 0,Lg=e=>e.visibleRole!==void 0,Pg=e=>e.color!==void 0,xg=e=>{const t=e.info;return Rg(t)?t.rank:0},kg=e=>{const t=e.info;return Pg(t)?t.color:"orange"},Fg=e=>{const t=e.info;return Lg(t)?t.visibleRole:"TECHNICIAN"},{URL:lr}=q(),{getAll:Ng,postModel:Ka}=Y.build({basePath:`${lr}/api/kos/troubles`}),Ha=async()=>await Ng({}),Ga=async(e,t)=>{try{const s=await Ka({model:{},urlOverride:`${lr}/api/kos/troubles/resolve/${e}`,tracker:t});return s!=null&&s.data&&De.initiateFuture(s.data),s.data}catch{const o={id:t||"",endState:Ke.Fail,tracker:t,reason:"Failed to resolve trouble"};return De.initiateFuture(o),o}},Ug=async(e,t)=>{try{const s=await Ka({model:e,urlOverride:`${lr}/api/kos/troubles/resolve/`,tracker:t});return s!=null&&s.data&&De.initiateFuture(s.data),s.data}catch{const o={id:t||"",endState:Ke.Fail,tracker:t,reason:"Failed to resolve troubles"};return De.initiateFuture(o),o}},jg=Object.freeze(Object.defineProperty({__proto__:null,bulkResolveTroubles:Ug,getTroubles:Ha,resolveTrouble:Ga},Symbol.toStringTag,{value:"Module"})),vs="troubleDataMapper",Xt=new Map;Uo(vs,{register:(e,t)=>{var s;Xt.has(e)||Xt.set(e,[]),(s=Xt.get(e))==null||s.push(t)},execute:async(e,t)=>{const s=Xt.get(e);if(!s)return{...t.data};const o=s.map(i=>i(t));return(await Promise.allSettled(o)).reduce((i,c)=>(c.status==="fulfilled"?i={...i,...c.value}:f.info(`Trouble mapper ${e} failed: ${c.reason}`),i),{...t.data})}});const zt="troubleMapper",es=new Map;Uo(zt,{register:(e,t)=>{var s;es.has(e)||es.set(e,[]),(s=es.get(e))==null||s.push(t)},execute:async(e,t)=>{const s=es.get(e);if(!s)return[];const o=s.map(i=>i(t)),n=(await Promise.allSettled(o)).map(i=>i.status==="fulfilled"?i.value:(f.info(`Trouble mapper ${e} failed: ${i.reason}`),[])).flat();return Array.from(new Set(n))}});C[zt].register("nozzle",async e=>[e.data.nozzlePath]);C[zt].register("path",async e=>[e.data.path]);const Bg=async e=>{const t=new Set,s=e.ifaces,o=s==null?void 0:s.map(n=>C[zt].execute(n,e));return(await Promise.allSettled(o)).forEach(n=>{n.status==="fulfilled"&&n.value.forEach(i=>t.add(i))}),Array.from(t)},Va=async e=>{const t=e.ifaces,s=t==null?void 0:t.map(i=>C[vs].execute(i,e)),o=C[vs].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 Kg{constructor(){a(this,"type","ResolvableTrouble");a(this,"title","Resolvable Trouble");a(this,"subtitle","Trouble")}}class Hg{constructor(){a(this,"type","BlockPumpTrouble");a(this,"title","Block Pump Trouble");a(this,"subtitle","Trouble")}}class xe{static getHandler(t){switch(t){case"ResolvableTrouble":return new Kg;case"BlockPumpTrouble":return new Hg;default:return}}}var Gg=Object.defineProperty,Vg=Object.getOwnPropertyDescriptor,Ya=(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 lt="trouble-model";function ts(e){return typeof e.shouldDefer=="boolean"}let ws=class{constructor(e,{resolvable:t,tags:s,info:o,id:r,clientData:n,rank:i,ifaces:c,type:l,group:d,createTime:u,role:h,color:p,...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=p,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 er(this)}getTitleWithContext(e){var s,o;const t=e?(o=(s=xe.getHandler(this.type))==null?void 0:s.context)==null?void 0:o[e]:xe.getHandler(this.type);return(t==null?void 0:t.title)||"Trouble"}getSubtitleWithContext(e){var s,o;const t=e?(o=(s=xe.getHandler(this.type))==null?void 0:s.context)==null?void 0:o[e]:xe.getHandler(this.type);return(t==null?void 0:t.subtitle)||"Trouble"}get rawId(){return this._troubleId}get title(){var e;return((e=xe.getHandler(this.type))==null?void 0:e.title)||"Trouble"}get subtitle(){var e;return((e=xe.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 Va(this)}get deferredCompanion(){const e=mo(this.id,t=>ts(t));if(e&&ts(e.modelData))return e.modelData}get deferred(){return this.deferredCompanion?this.deferredCompanion.deferred:!1}get shouldDefer(){const e=mo(this.id,t=>ts(t));return e&&ts(e.modelData)?e.modelData.shouldDefer:!1}clearDefer(){var e;(e=this.deferredCompanion)==null||e.clearDefer()}defer(){var e;(e=this.deferredCompanion)==null||e.defer()}getChildren(){return[...this.futureHandler.allFutures]}async resolve(e){var t;if(!this._resolvable)throw this.logger.error(`attempting to resolve an unresolvable trouble with id ${this._troubleId}`),new Error("Trouble is not resolvable");if(this.shouldDefer){(t=this.deferredCompanion)==null||t.defer();return}return await Ga(this._troubleId,e)}};Ya([Er()],ws.prototype,"resolve",1);ws=Ya([D(lt)],ws);const xt={registration:{[lt]:{class:ws,singleton:!1}},type:lt,predicate:ee(lt),factory:V.Factory.create(lt)};var Yg=Object.defineProperty,zg=Object.getOwnPropertyDescriptor,Ks=(e,t,s,o)=>{for(var r=o>1?void 0:o?zg(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Yg(t,s,r),r};const Qr=f.createLogger({name:"trouble-container-model"});function Xr(e){return C.propertyMapper.hasMapper(oe.TroubleRank)?C.propertyMapper.executeMapper(oe.TroubleRank,e):xg(e)}function en(e){return(C.propertyMapper.hasMapper(oe.TroubleColor)?C.propertyMapper.executeMapper(oe.TroubleColor,e):kg(e)).toLowerCase()}function tn(e){return(C.propertyMapper.hasMapper(oe.TroubleRole)?C.propertyMapper.executeMapper(oe.TroubleRole,e):Fg(e)).toLowerCase()}const qg="trouble-container-model";class X{}a(X,"INDEX_TROUBLES_BY_IFACE","byIface"),a(X,"INDEX_TROUBLES_BY_TYPE","byType"),a(X,"INDEX_TROUBLES_BY_GROUP","byGroup"),a(X,"INDEX_TROUBLES_BY_DEFERRED","byDeferred"),a(X,"SORT_KEY_RANK","rank"),a(X,"TROUBLES_DEFERRED","true");let Ge=class{constructor(e){a(this,"id");a(this,"troubles");this.id=e,this.troubles=new me({indexMap:{[X.INDEX_TROUBLES_BY_IFACE]:Bg,[X.INDEX_TROUBLES_BY_TYPE]:"type",[X.INDEX_TROUBLES_BY_GROUP]:"group",[X.INDEX_TROUBLES_BY_DEFERRED]:"deferred"},sortKey:X.SORT_KEY_RANK,parentId:e})}async load(){Qr.debug("loading trouble container");const e=await Ha();try{e==null||e.data.forEach(t=>{const s={...t,rank:Xr(t),color:en(t),role:tn(t),id:String(t.id)},o=xt.factory(`trouble-${t.id}`)(s);this.troubles.addModel(o)})}catch(t){throw Qr.error(t),t}}handleTroubleRemoved(e){const t=`trouble-${e}`,s=this.troubles.getModel(t);this.troubles.removeModel(t),s&&Oe(s)}handleTroubleAdded(e){const t={...e,rank:Xr(e),color:en(e),role:tn(e),id:String(e.id)};if(t.role==="NONE")return;const s=xt.factory(`trouble-${e.id}`)(t);this.troubles.addModel(s)}};Ks([ce],Ge.prototype,"troubles",2);Ks([R({topic:"/kos/trouble/remove",websocket:!0,lifecycle:k.INIT})],Ge.prototype,"handleTroubleRemoved",1);Ks([R({topic:"/kos/trouble/add",websocket:!0})],Ge.prototype,"handleTroubleAdded",1);Ge=Ks([D(qg)],Ge);const ss="trouble-container-model",Ve={registration:{[ss]:{class:Ge,singleton:!0}},type:ss,predicate:ee(ss),factory:V.Singleton.create(ss)},{URL:za}=q(),{getAll:Wg}=Y.build({basePath:`${za}/api/kos/ota`}),sn=f.createLogger({name:"ota-service",group:"Services"}),Zg=async()=>{sn.debug("sending GET request to /api/kos/ota/artifacts");const e=await Wg({urlOverride:`${za}/api/kos/ota/artifacts`});return sn.debug("getArtifacts - response:",e),e==null?void 0:e.data};var Jg=Object.defineProperty,Qg=Object.getOwnPropertyDescriptor,Hs=(e,t,s,o)=>{for(var r=o>1?void 0:o?Qg(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Jg(t,s,r),r};const qa="ota-model",Xg=e=>{let t=null;for(const s in e){const o=e[s],r=o.lastUpdateTime;(!t||t.lastUpdateTime<r)&&(t=o)}return t},io=e=>{const t=e.artifactInfo,s=Xg(e.requests),o=(t==null?void 0:t.identifier)||(s==null?void 0:s.kabId);if(!o)return;let r;switch(e.status){case"INSTALLED":r="ready";break;case"INVALID":r="error";break;case"MISSING":r=((s==null?void 0:s.currentSize)||0)>0?"downloading":"idle";break;case"STAGED":r="pending"}const n=t===void 0;return{id:o,manifest:n,label:t==null?void 0:t.version,name:t==null?void 0:t.name,status:r,error:r==="error"?s==null?void 0:s.lastErrorReason:void 0,errorCount:r==="error"?s==null?void 0:s.errorCount:0,progress:r==="downloading"&&s&&!n?s.currentSize/(t==null?void 0:t.size)*100:void 0,size:t==null?void 0:t.size}};let Ye=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(this,"data",new Bi);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 Zg();e&&e.forEach(t=>{const s=io(t);s&&this.data.addModel(s)})}catch(e){this.logger.error(`loading ota ${this.id} - error:`,e)}}async handleAllArtifacts(e){this.logger.debug("handleAllArtifacts:",e),await this.data.clear();try{e.forEach(t=>{const s=io(t);s&&this.data.addModel(s)})}catch(t){this.logger.error(`handleAllArtifacts ${this.id} - error:`,t)}}handleChangedArtifacts(e){this.logger.debug("handleChangedArtifacts:",e);try{e.forEach(t=>{const s=io(t);s&&this.data.updateModel(s)})}catch(t){this.logger.error(`handleChangedArtifacts ${this.id} - error:`,t)}}};Hs([Je({modelType:Ve.type})],Ye.prototype,"troubleContainer",2);Hs([R({topic:"/kos/ota/artifacts/all",websocket:!0})],Ye.prototype,"handleAllArtifacts",1);Hs([R({topic:"/kos/ota/artifacts/changed",websocket:!0})],Ye.prototype,"handleChangedArtifacts",1);Ye=Hs([D(qa)],Ye);const Ms=new fe({class:Ye,type:qa}),on=f.createLogger({name:"software-info-service",group:"Services"}),Wa=async()=>{on.debug("sending GET for software-info");const[e,t]=await fa.get("/api/kos/manifest/info");if(!t)throw on.error("Failed to fetch software-info",e),new ne("Failed to fetch software-info");return t},ef=Object.freeze(Object.defineProperty({__proto__:null,getSoftwareInfos:Wa},Symbol.toStringTag,{value:"Module"}));var tf=Object.defineProperty,sf=Object.getOwnPropertyDescriptor,of=(e,t,s,o)=>{for(var r=o>1?void 0:o?sf(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&tf(t,s,r),r};const dt="software-info-model";let vo=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 Wa(),t=(e==null?void 0:e.nodes)||{};K(()=>{const o=Object.keys(t).map(r=>t[r][0]).map(r=>({nodeName:r.node,group:this.groupBy(r.artifacts,"group")}));this.nodes=o})}catch(e){e instanceof ne&&this.logger.error("Failed to fetch software-info",e)}}};vo=of([D(dt)],vo);const Es={registration:{[dt]:{class:vo,singleton:!1}},type:dt,predicate:ee(dt),factory:V.Factory.create(dt)},{URL:Za}=q(),{getOne:rf}=Y.build({basePath:`${Za}/api/kos/state`}),nf=f.createLogger({name:"state-bean-service",group:"Services"}),Ja=async({path:e})=>(nf.debug("sending GET for state-bean"),await rf({urlOverride:`${Za}/api/kos/state/${e}`})),af=Object.freeze(Object.defineProperty({__proto__:null,getStateBeanData:Ja},Symbol.toStringTag,{value:"Module"}));var cf=Object.defineProperty,lf=Object.getOwnPropertyDescriptor,Qa=(e,t,s,o)=>{for(var r=o>1?void 0:o?lf(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&cf(t,s,r),r};const ut="state-bean-model",df=Se("path");let _s=class{constructor(e,t,s){a(this,"id");a(this,"path");a(this,"props");a(this,"logger");this.id=e,this.logger=s.logger,this.props=zo.map(new Map),lo(t,this)}updateModel(e){lo(e,this)}handleConfigBeanUpdated(e){Object.entries(e).forEach(([t,s])=>{let o=s;typeof o=="string"&&Zo(o)&&(o=o.toLowerCase()=="true"),typeof o=="string"&&Fs(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 Ja({path:this.path});e!=null&&e.data&&this.updateProps(e.data)}};Qa([R({topic:`/kos/state/${df}`,websocket:!0})],_s.prototype,"handleConfigBeanUpdated",1);_s=Qa([D(ut)],_s);const kt={registration:{[ut]:{class:_s,singleton:!1}},type:ut,predicate:ee(ut),factory:V.Factory.create(ut)};var uf=Object.defineProperty,hf=Object.getOwnPropertyDescriptor,Xa=(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 ht="state-prop-model",rn=Se("path");let Is=class{constructor(e,t,s){a(this,"id");a(this,"path");a(this,"attribute");a(this,"logger");a(this,"stateBean");this.id=e,this.logger=s.logger,this.path=t.path,this.attribute=t.attribute}get value(){return this.stateBean.props.get(this.attribute)}async init(){this.logger.debug(`initializing state-prop ${this.id}`)}async load(){this.logger.debug(`loading state-prop ${this.id}`)}toString(){var e;return((e=this.value)==null?void 0:e.toString())??""}};Xa([Je({modelType:kt.type,id:`state-bean-${rn}`,options:{path:rn}})],Is.prototype,"stateBean",2);Is=Xa([D(ht)],Is);const dr={registration:{[ht]:{class:Is,singleton:!1}},type:ht,predicate:ee(ht),factory:V.Factory.create(ht)},{URL:gf}=q(),{getAll:ff}=Y.build({basePath:`${gf}/api/state-prop`}),mf=f.createLogger({name:"state-prop-service",group:"Services"}),pf=async()=>(mf.debug("sending GET for state-prop"),await ff({})),yf=Object.freeze(Object.defineProperty({__proto__:null,getStateProps:pf},Symbol.toStringTag,{value:"Module"})),{URL:ur}=q(),{getOne:ec}=Y.build({basePath:`${ur}/api/translation`}),Dt=f.createLogger({name:"translation-service",group:"Services"}),bf=()=>{const e=window.location.origin,t=ae();return(t==null?void 0:t.host)||e},tc=async(e,t)=>{Dt.debug("sending GET for translation");const s=t??bf();try{const o=await fetch(`${s}${e}`);return o.status!==200?(Dt.warn(`Failed to fetch translations at ${e}: ${o.status}`),{}):await o.json()}catch(o){throw Dt.error("Error fetching translations",o),o}},vf=async()=>{Dt.debug("getting localization descriptor");const e=await ec({urlOverride:`${ur}/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},sc=e=>async()=>{Dt.debug("getting kos localization descriptor");const t=await ec({urlOverride:`${ur}/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]},oc="langResolver";var wf=Object.defineProperty,Mf=Object.getOwnPropertyDescriptor,Ef=(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 gt="translation-model";function _f(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 rc(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=rc(e[o],r);return{...s,...n}}else return{...s,[r]:e[o]}},{})}function nc(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]=nc(e[o],t[o]):s[o]=t[o]);return s}const wo=(e,t)=>{const s=/__(.*?)__/g,o=e.replace(s,(r,n)=>Object.prototype.hasOwnProperty.call(t||{},n.trim())?t==null?void 0:t[n.trim()]:r);return o===e?o:s.test(o)?wo(o,t):o},os=(e,t,s)=>{const o=/{{(.*?)}}/g,n=wo(e,t).replace(o,(c,l)=>Object.prototype.hasOwnProperty.call(s||{},l.trim())?s==null?void 0:s[l.trim()]:c);return wo(n,t)},nn=(e,t)=>{if(t.includes(":")){const[s,o]=t.split(":");return{namespace:s,key:o}}else return{namespace:e,key:t}};let Mo=class{constructor(e,t,s){a(this,"id");a(this,"namespace");a(this,"descriptor");a(this,"defaultLocale");a(this,"currentLocale");a(this,"bundleResolver");a(this,"data");a(this,"logger");a(this,"resolver");a(this,"disposer");a(this,"context");a(this,"rootUrl");this.id=e,this.defaultLocale=t.defaultLocale||"en",this.currentLocale=t.currentLocale||"en",this.namespace=t.namespace,this.descriptor=t.descriptor,this.rootUrl=t.rootUrl,this.data={},this.resolver=t.resolver||s.kosContext.get(oc),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 tc(r,this.rootUrl)}catch{return Promise.resolve({})}}),s=await Promise.allSettled(t);K(()=>{const o=s.reduce((r,n,i)=>(n.status==="fulfilled"?(this.logger.debug(`resolved ${e[i]}`,n.value),n.value&&(r=nc(r,n.value))):this.logger.error(`failed to load translation ${this.id} for ${e[i]}`),r),{});this.data=rc(o)})}async init(){this.logger.debug(`initializing translation ${this.id}`)}exists(e){const{namespace:t,key:s}=nn(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}=_f(t),{namespace:n,key:i}=nn(this.namespace,e),c=`${i}_${o}`;if(n!==this.namespace){const l=this.context.getModel(n);return l?l.resolveKey(i,t):i}if(o&&this.data[c]){const l=this.data[c];return Array.isArray(l)?l.map(d=>os(d,this.data,r)):os(this.data[c],this.data,r)}if(this.data[i]){const l=this.data[c];return Array.isArray(l)?l.map(d=>os(d,this.data,r)):os(this.data[i],this.data,r)}return s??i}unload(){this.logger.debug(`unloading translation ${this.id}`),this.disposer&&this.disposer()}async load(){this.logger.debug(`loading translation ${this.id}`),await this.loadTranslations()}async ready(){this.logger.debug(`ready translation ${this.id}`),this.disposer=w.reaction(()=>this.currentLocale,(e,t)=>{this.logger.info(`translation langs for namespace ${this.id} changed from ${t} to ${e}`),this.loadTranslations()})}};Mo=Ef([ks(),D(gt)],Mo);const Ts={registration:{[gt]:{class:Mo,singleton:!1}},type:gt,predicate:ee(gt),factory:V.Factory.create(gt)};var If=Object.defineProperty,Tf=Object.getOwnPropertyDescriptor,ic=(e,t,s,o)=>{for(var r=o>1?void 0:o?Tf(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&&If(t,s,r),r};const ft="translation-container-model",$f=(e,t="/")=>e.join(t).replace(new RegExp(t+"{1,}","g"),t);function Of(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 $f([o,r])}let $s=class{constructor(e,t,s){a(this,"id");a(this,"lang");a(this,"rootUrl");a(this,"descriptor");a(this,"_defaultNamespace");a(this,"resolver");a(this,"logger");a(this,"descriptorUrl");a(this,"namespaces",[]);a(this,"_models");this.id=e,this.lang=t.lang||"en",this.descriptor=t.descriptor,this._defaultNamespace=t.defaultNamespace,this.descriptorUrl=t.descriptorUrl,this.rootUrl=t.rootUrl,this.resolver=t.resolver||Of.bind(this),s.kosContext.set(oc,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 $i(this);for(const e of this.namespaces){const t=this.resolveNamespace(e);await J(t)}}resolveNamespace(e){var s;if((s=this.descriptor.namespaces)==null?void 0:s[e]){const o=Object.keys(this.descriptor.namespaces[e].locales)[0],r=this.descriptor.namespaces[e].locales[o].defaultLocale,n=Ts.factory(`translation-${e}`)({kosParentId:this.id,namespace:e,rootUrl:this.rootUrl,currentLocale:this.lang,defaultLocale:r,descriptor:this.descriptor.namespaces[e].locales,resolver:this.resolver});return this.addModel(n),this.namespaces.includes(e)||K(()=>{this.namespaces.push(e)}),n}else{this.logger.warn(`namespace ${e} not found in descriptor`);const o=Ts.factory(`translation-${e}`)({kosParentId:this.id,namespace:e,rootUrl:this.rootUrl,currentLocale:this.lang,defaultLocale:this.lang,descriptor:{},resolver:this.resolver});return this.addModel(o),o}}addModel(e){this._models.addModel(e)}removeModel(e){this._models.removeModel(e)}async init(){this.logger.debug(`initializing translation-container container ${this.id}`)}async load(){this.logger.debug(`loading translation-container container ${this.id}`)}};ic([ce],$s.prototype,"_models",2);$s=ic([D(ft)],$s);const he={registration:{[ft]:{class:$s,singleton:!0}},type:ft,predicate:ee(ft),factory:V.Singleton.create(ft)},Df={set(e,t){const s=x.getContext(he.type);s&&s.set(e,t)},get(e){const t=x.getContext(he.type);return t==null?void 0:t.get(e)}},ac={async init(e){const t=he.factory(e);return await J(t),{translations:t}}},Sf=(e,t)=>{const s=t.type;return e[s]||(e[s]=[]),e[s].push(t),e},cc="kos-ws-event",hr=Xe(cc);var Af=Object.defineProperty,Cf=Object.getOwnPropertyDescriptor,gr=(e,t,s,o)=>{for(var r=o>1?void 0:o?Cf(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Af(t,s,r),r};const Rf=({headers:e,body:t})=>Object.entries(e).map(([o,r])=>`${o}:${r}`).join("\\n")+"\\n\\n"+t;exports.WsEventModel=class{constructor(t){a(this,"id");a(this,"events");a(this,"_topicMap");this.id=t,this.events=w.observable.map(new Map),this._topicMap=new Map}get websocketEvents(){return Array.from(this.events.values())}handleSendEvent(t,s){this.processEvent(s,!0)}handleReceiveEvent(t,s){this.processEvent(s)}processEvent(t,s=!1){f.debug("kos event received");const{body:o,headers:r}=t.body,n=r["request-id"]||r["response-id"],i=r["request-id"]||r["response-id"]||r.topic||r.type;if(i){let c=i;if(n)c=`${c}-${s?"send":"receive"}`;else{const d=this._topicMap.get(i)||0;c=`${c}-${d+1}`,this._topicMap.set(i,d+1)}const l={msgId:c,content:o,headers:r,timestamp:Date.now(),raw:Rf({headers:r,body:o}),direction:s?"send":"receive",mocked:!!r.mocked};this.events.set(c,l),f.debug(`logged ${this.events.size} events`)}}};gr([R({topic:[Bt.SEND]})],exports.WsEventModel.prototype,"handleSendEvent",1);gr([R({topic:[Bt.RECEIVED]})],exports.WsEventModel.prototype,"handleReceiveEvent",1);exports.WsEventModel=gr([D(hr.type)],exports.WsEventModel);const Lf="/api/system/canvas",Pf=`${exports.BASE_URL}${Lf}`,xf=async e=>{await exports.kosFetch(Pf,{method:"POST",body:e})};class lc{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.video.addEventListener("ended",()=>{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}shouldStep(t){const s=performance.now();return s-this.lastUpdate>=t?(this.lastUpdate=s,!0):!1}}class kf{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 Ff extends kf{constructor(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=`
|
|
78
|
-
attribute vec2 a_position;
|
|
79
|
-
void main() {
|
|
80
|
-
gl_Position = vec4(a_position, 0, 1);
|
|
81
|
-
}
|
|
82
|
-
`,n=`
|
|
83
|
-
precision mediump float;
|
|
84
|
-
uniform float minHue;
|
|
85
|
-
uniform float maxHue;
|
|
86
|
-
uniform float hueOffset;
|
|
87
|
-
uniform float gridHeight;
|
|
88
|
-
|
|
89
|
-
vec3 hslToRgb(float h, float s, float l) {
|
|
90
|
-
float c = (1.0 - abs(2.0 * l - 1.0)) * s;
|
|
91
|
-
float x = c * (1.0 - abs(mod(h * 6.0, 2.0) - 1.0));
|
|
92
|
-
float m = l - c / 2.0;
|
|
93
|
-
vec3 rgb;
|
|
94
|
-
|
|
95
|
-
if (h < 1.0/6.0) rgb = vec3(c, x, 0.0);
|
|
96
|
-
else if (h < 2.0/6.0) rgb = vec3(x, c, 0.0);
|
|
97
|
-
else if (h < 3.0/6.0) rgb = vec3(0.0, c, x);
|
|
98
|
-
else if (h < 4.0/6.0) rgb = vec3(0.0, x, c);
|
|
99
|
-
else if (h < 5.0/6.0) rgb = vec3(x, 0.0, c);
|
|
100
|
-
else rgb = vec3(c, 0.0, x);
|
|
101
|
-
|
|
102
|
-
return rgb + vec3(m);
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
void main() {
|
|
106
|
-
float relY = mod((1.0 - gl_FragCoord.y / gridHeight) - hueOffset, 1.0);
|
|
107
|
-
float hue = minHue + relY * (maxHue - minHue);
|
|
108
|
-
vec3 rgb = hslToRgb(hue, 1.0, 0.5);
|
|
109
|
-
gl_FragColor = vec4(rgb, 1.0);
|
|
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 dc{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}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}}class Nf extends dc{constructor(s=1,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 p=(i*s+c)*4;n[p]=d,n[p+1]=u,n[p+2]=h,n[p+3]=255}this.ctx.putImageData(r,0,0)}}class Uf extends dc{constructor(s=0,o=360,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,p,v)=>(v<0&&(v+=1),v>1&&(v-=1),v<.16666666666666666?h+(p-h)*6*v:v<.5?p:v<.6666666666666666?h+(p-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,p,v]=this.hslToRgb(u,1,.5);n[i++]=h,n[i++]=p,n[i++]=v,n[i++]=255}this.ctx.putImageData(r,0,0)}}class jf extends lc{constructor(){super("assets/swirl.mp4")}}const Bf=({mode:e,data:t})=>{switch(e){case"sweep":return new Uf(0,360,1);case"drop":return new Ff(1);case"matrix":return new Nf(1);case"swirl":return new jf;case"video":return t?new lc(t.src):null;case"none":return null;default:throw new Error(`Unknown mode: ${e}`)}};var Kf=Object.defineProperty,Hf=Object.getOwnPropertyDescriptor,uc=(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 hc="canvas-dispatcher-model";let Os=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(this,"router");a(this,"pattern");a(this,"data");a(this,"active",!1);this.id=e,this.logger=s.logger}get renderer(){return this.pattern?Bf({mode:this.pattern,data:this.data}):(this.logger.warn("No pattern set for canvas dispatcher, returning undefined renderer."),null)}sendDataFrame(e){xf(e)}async load(){this.router.use("POST","/api/ui/canvas/stop",async(e,t)=>{K(()=>{this.active=!1}),t.send({status:"OK"})}),this.router.use("POST","/api/ui/canvas/start",async(e,t)=>{K(()=>{this.active=!0}),t.send({status:"OK"})}),this.router.use("POST","/api/ui/canvas/pattern",async(e,t)=>{var o;const s=e.body;this.logger.debug(`Updating canvas with id: ${s.id}`),this.pattern=s.id,s.type==="video"&&(this.data=s.data),this.active=!0,(o=t.status)==null||o.call(t,200).send({status:"OK"})})}};uc([Je({modelType:rr.type})],Os.prototype,"router",2);Os=uc([D(hc)],Os);const Gf=new fe({class:Os,type:hc}),{URL:fr}=q(),{getOne:gc}=Y.build({basePath:`${fr}/api/device`}),Ds=f.createLogger({name:"device-service",group:"Services"}),fc=async()=>{Ds.debug("sending GET for device serial number");try{const e=await gc({urlOverride:`${fr}/api/kos/device/serialNumber`});return[void 0,e==null?void 0:e.data.serialNumber]}catch(e){if(e instanceof ne)return Ds.error(`Error fetching device serial number: ${e.payload.error}`),[e.payload.error,void 0]}return["unknownError",void 0]},mc=async()=>{Ds.debug("sending GET for device details");try{const e=await gc({urlOverride:`${fr}/api/kos/device`});return e?[void 0,e.data]:["unknownError",void 0]}catch(e){if(e instanceof ne)return Ds.error(`Error fetching device serial number: ${e.payload.error}`),[e.payload.error,void 0]}return["unknownError",void 0]},Vf=Object.freeze(Object.defineProperty({__proto__:null,getDeviceDetails:mc,getSerialNumber:fc},Symbol.toStringTag,{value:"Module"}));var Yf=Object.defineProperty,zf=Object.getOwnPropertyDescriptor,pc=(e,t,s,o)=>{for(var r=o>1?void 0:o?zf(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&&Yf(t,s,r),r};const yc="device-model",qf="/kos/criticalData/changed",Wf="/kos/criticalData/available";let Ss=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 mc();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 fc();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()}};pc([R({topic:[qf,Wf],websocket:!0})],Ss.prototype,"handleCriticalDataChanged",1);Ss=pc([D(yc)],Ss);const As=new fe({class:Ss,type:yc});var Zf=Object.defineProperty,Jf=Object.getOwnPropertyDescriptor,Qf=(e,t,s,o)=>{for(var r=o>1?void 0:o?Jf(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Zf(t,s,r),r};const bc="network-interface-model";let Eo=class{constructor(e,t,s){a(this,"id");a(this,"name");a(this,"type");a(this,"nmdevicestate");a(this,"hwaddress");a(this,"mtu");a(this,"configured");a(this,"wifi");a(this,"ethernet");a(this,"ip4settings");a(this,"category");a(this,"logger");this.id=e,this.logger=s.logger,this.name=t.name,this.type=t.type,this.nmdevicestate=t.nmdevicestate,this.hwaddress=t.hwaddress,this.mtu=t.mtu,this.configured=t.configured,this.wifi=t.wifi,this.ethernet=t.ethernet,this.ip4settings=t.ip4settings,this.category=t.category}updateModel(e){this.name=e.name,this.type=e.type,this.nmdevicestate=e.nmdevicestate,this.hwaddress=e.hwaddress,this.mtu=e.mtu,this.configured=e.configured,this.wifi=e.wifi,this.ethernet=e.ethernet,this.ip4settings=e.ip4settings,this.category=e.category}async init(){this.logger.debug(`initializing network-interface ${this.id}`)}async load(){this.logger.debug(`loading network-interface ${this.id}`)}};Eo=Qf([D(bc)],Eo);const mr=new le({class:Eo,type:bc}),{URL:Xf}=q(),{getAll:em}=Y.build({basePath:`${Xf}/api/kos/network/interfaces`}),an=f.createLogger({name:"network-interface-service",group:"Services"}),vc=async()=>{an.debug("sending GET for copy-logs");try{const e=await em({});return[void 0,e==null?void 0:e.data]}catch(e){if(e instanceof ne)return an.error(`Error fetching log file size: ${e.payload.error}`),[e.payload.error,void 0]}return["unknownError",void 0]},tm=Object.freeze(Object.defineProperty({__proto__:null,getNetworkInterfaces:vc},Symbol.toStringTag,{value:"Module"}));var sm=Object.defineProperty,om=Object.getOwnPropertyDescriptor,wc=(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 Mc="network-interface-container-model";let Cs=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(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 vc();if(e){this.logger.error(`Error loading network interfaces: ${e}`);return}t&&t.forEach(s=>{const o=mr.instance(s.name).forceUpdate.options(s).build();this.addModel(o)})}async load(){this.logger.debug(`loading network-interface-container container ${this.id}`),this.refreshInterfaces()}};wc([ce],Cs.prototype,"_models",2);Cs=wc([D(Mc)],Cs);const Ft=new fe({class:Cs,type:Mc});Ft.addRelatedModel(mr);const{URL:rm}=q(),{getAll:nm}=Y.build({basePath:`${rm}/api/kos/storage/devices`}),cn=f.createLogger({name:"storage-device-service",group:"Services"}),Ec=async()=>{cn.debug("sending GET for storage-device");const e=await nm({});return!(e!=null&&e.data)||e.status!==200?(cn.error("Failed to retrieve storage-device data",e),[]):e.data},im=Object.freeze(Object.defineProperty({__proto__:null,getStorageDevices:Ec},Symbol.toStringTag,{value:"Module"}));var am=Object.defineProperty,cm=Object.getOwnPropertyDescriptor,lm=(e,t,s,o)=>{for(var r=o>1?void 0:o?cm(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&&am(t,s,r),r};const _c="storage-device-model";let _o=class{constructor(e,t,s){a(this,"id");a(this,"mountDir");a(this,"removed");a(this,"vendor");a(this,"runTimeMs");a(this,"model");a(this,"nodeId");a(this,"local");a(this,"label");a(this,"syspath");a(this,"logger");this.id=e,this.logger=s.logger,this.mountDir=t.mountDir,this.removed=t.removed,this.vendor=t.vendor,this.runTimeMs=t.runTimeMs,this.model=t.model,this.nodeId=t.nodeId,this.local=t.local,this.label=t.label,this.syspath=t.syspath}updateModel(e){this.mountDir=e.mountDir,this.removed=e.removed,this.vendor=e.vendor,this.runTimeMs=e.runTimeMs,this.model=e.model,this.nodeId=e.nodeId,this.local=e.local,this.label=e.label,this.syspath=e.syspath}async init(){this.logger.debug(`initializing storage-device ${this.id}`)}async load(){this.logger.debug(`loading storage-device ${this.id}`)}};_o=lm([ks(),D(_c)],_o);const Rs=new le({class:_o,type:_c});var dm=Object.defineProperty,um=Object.getOwnPropertyDescriptor,pr=(e,t,s,o)=>{for(var r=o>1?void 0:o?um(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 Ic="storage-device-container-model",hm="/kos/storage";let Nt=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(this,"_models");this.id=e,this.logger=s.logger,this._models=new 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(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=Rs.instance(s.id).options(r).build();this.addModel(n)}})}async load(){this.logger.debug(`loading storage-device-container container ${this.id}`),(await Ec()).forEach(t=>{const s={...t,kosParentId:this.id},o=Rs.instance(t.id).options(s).build();this.addModel(o)})}};pr([ce],Nt.prototype,"_models",2);pr([R({topic:hm,websocket:!0})],Nt.prototype,"handleStorageAvailability",1);Nt=pr([D(Ic)],Nt);const ze=new fe({class:Nt,type:Ic});ze.addRelatedModel(Rs);const{URL:yr}=q(),{getAll:gm,postModel:fm}=Y.build({basePath:`${yr}/api/kos/update/available`}),ln=f.createLogger({name:"usb-update-service",group:"Services"}),Tc=async()=>{ln.debug("sending GET for usb-update");const e=await gm({urlOverride:`${yr}/api/kos/update/available`});return!(e!=null&&e.data)||(e==null?void 0:e.status)!==200?(ln.error("Failed to retrieve usb-update data",e),[]):e.data},$c=async(e,t,s)=>{const o=await fm({model:{manifestId:e,deviceId:t},tracker:s,urlOverride:`${yr}/api/kos/update/install`});if(!(o!=null&&o.data))throw new Error("No response from server");return o.data},mm=Object.freeze(Object.defineProperty({__proto__:null,getAvailableUpdates:Tc,installUpdate:$c},Symbol.toStringTag,{value:"Module"}));var pm=Object.defineProperty,ym=Object.getOwnPropertyDescriptor,Oc=(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&&pm(t,s,r),r};const Dc="usb-update-model";let Ls=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 er(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}`),$c(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}`)}};Oc([Er()],Ls.prototype,"install",1);Ls=Oc([D(Dc)],Ls);const br=new le({class:Ls,type:Dc});var bm=Object.defineProperty,vm=Object.getOwnPropertyDescriptor,Gs=(e,t,s,o)=>{for(var r=o>1?void 0:o?vm(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&&bm(t,s,r),r};const Sc="usb-update-container-model";let qe=class{constructor(e,t,s){a(this,"id");a(this,"disposer");a(this,"storageService");a(this,"_activeUpdate");a(this,"logger");a(this,"_models");this.id=e,this.logger=s.logger,this._models=new 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 Tc();K(()=>{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=br.instance(o).forceUpdate.options({...s,createTime:new Date(s.createTime)}).build();this.addModel(r)}),this.data.length===1?this.updateActiveUpdate(this.data[0]):this.clearActiveUpdate()})}usbInsertedEffect(){this.isUsbInserted?this.syncAvailableUpdates():(this._models.clear(),this.clearActiveUpdate())}async init(){this.logger.debug(`initializing usb-update-container container ${this.id}`)}unload(){var e;(e=this.disposer)==null||e.call(this)}async activate(){this.logger.debug(`activating usb-update-container container ${this.id}`),await this.syncAvailableUpdates()}async load(){this.logger.debug(`loading usb-update-container container ${this.id}`)}};Gs([Je({modelType:ze.type})],qe.prototype,"storageService",2);Gs([ce],qe.prototype,"_models",2);Gs([Jn({dependencies:e=>[e.isUsbInserted]})],qe.prototype,"usbInsertedEffect",1);qe=Gs([D(Sc)],qe);const Ut=new fe({class:qe,type:Sc});Ut.addRelatedModel(br);const wm=()=>({...{[tt.type]:{class:ga},[be.type]:{class:va,singleton:!0},...z.registration,...Ae.registration,...Ve.registration,...Ts.registration,...he.registration,[hr.type]:{class:exports.WsEventModel,singleton:!0},...kt.registration,...dr.registration,...ps.registration}}),vr=wm(),Mm={models:vr,preloadModels:[]},Em=!0,Ac=e=>()=>{const t=vr;return Ai(Io)(xt).model(Ve).model(ze).model(Ut).model(As).model(Ms).model(St).model(Es).model(ar).model(Ft).model(Gf).model(rr,Em).model(Yt),Object.keys(t).forEach(s=>{const o=t[s];Si(Io)(s,o)}),{preload:$.model.preloadModel(e),model:$.model.register(e),companion:$.companion.register(e),legacy:$.model.registerLegacyModel(e)}},re={};re.core={models:Ac(re)};re.preload=$.model.preloadModel(re);re.model=$.model.register(re);re.companion=$.companion.register(re);re.legacy=$.model.registerLegacyModel(re);const Io=re;class _m{registerTroubleRankMapper(t){return C.propertyMapper.registerPropertyMapper(oe.TroubleRank,t),this}registerTroubleRoleMapper(t){return C.propertyMapper.registerPropertyMapper(oe.TroubleRole,t),this}registerTroubleColorMapper(t){return C.propertyMapper.registerPropertyMapper(oe.TroubleColor,t),this}}const Im=async(e,t)=>{const s=ar.instance(e).options({}).build(),o=t?`${t}-`:"";return await J(s),{getState:r=>s.data[`${o}${r}`],updateState:async(r,n)=>{await s.updateState(`${o}${r}`,n)},clean:async()=>{for(const r of s.data.keys)await s.updateState(`${o}${r}`,void 0)},unsubscribe:()=>{Oe(s)}}},Cc="kos:service:region",Rc="regionId",Tm=`${Cc}-${Rc}`,Lc=async e=>{const t=Ae.factory(Tm)({path:Cc,attribute:Rc});await J(t),t.updateProperty(e)},wr="/kos-timer-event",Mr="defaultTimerEnd",mt=f.createLogger({name:"timer-manager"}),$m=e=>e.updateProperty!==void 0;class Pc{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,$m(s)&&F(()=>{f.info(`Updating config value timer ${t} with new timeout value ${s.value}`);const n=s.value||60;this.updateTimeout(n)}),this.addTimeoutAction({name:Mr}),o&&o.forEach(n=>{this.addTimeoutAction(n)})}get id(){return this.name}start(){if(this.state==="active"){mt.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&&(mt.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;mt.debug(`Executing timer action ${s.name} at ${t}`),(o=s.action)==null||o.call(s,s.name,t),this.notifyTimeoutAction(s),s.singleUse&&(mt.info(`${this.name} Removing single-use action ${s.name}`),this.removeTimeoutAction(s.name))})}notifyTimeoutAction(t){N(wr,{name:this.name,action:t.name,remainingTime:this.remainingTime})}}const pt=new Map,ke=(e,t)=>{const s=pt.get(e);if(!s){mt.error(`Timer ${e} not found`);return}t(s)},xc={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(pt.has(e))return pt.get(e);const o=new Pc(e,t,s);return pt.set(e,o),o},getTimer(e){return pt.get(e)},clearTimer(e){ke(e,t=>t.pause())},restartTimer(e){ke(e,t=>t.restart())},resetTimer(e){ke(e,t=>t.reset())},addTimeoutAction(e,t){ke(e,s=>s.addTimeoutAction(t))},removeTimeoutAction(e,t){ke(e,s=>s.removeTimeoutAction(t))},startTimer(e){ke(e,t=>t.start())}},kc="kos:service:region:settings",Fc="timeZone",Om=`${kc}-${Fc}`,To=async e=>{const t=Ae.factory(Om)({path:kc,attribute:Fc});await J(t),t.updateProperty(e)},Dm=e=>!e||!e.data;function Er(e={}){const{alias:t,namespace:s}=e;return(o,r,n)=>{o[vt]=o[vt]||{};const i=n.value,c=async function(...l){const d=Ze();f.debug(`Calling future service ${r} with tracker ${d}`);const u=De.initiateFuture({tracker:d,id:qo});s&&(u.namespace=s),f.debug(`waiting for future ${u.id} to be ready`),await J(u),f.debug(`future ${u.id} is ready`),K(()=>{f.debug(`Adding future ${u.id} to futureHandler`),this.futureHandler.addFuture(u,t)});try{const h=await i.apply(this,[...l,d]);f.debug(`received future response for ${d}`,h);const p=Dm(h)?h:h==null?void 0:h.data;return p?(p.progress=1,f.debug("mapping future response to future model"),u.endState?f.debug(`future ${u.id} has already completed. Not updating the model`):sr(p,u)):this.futureHandler.removeFuture(t),p}catch(h){throw f.error(h),h}};o[vt][r]={handler:c}}}const Sm=({path:e})=>(t,s)=>{t[P]=t[P]||{},t[P][s]={modelType:kt.type,id:`${kt.type}-${e}`,options:{path:e},lifecycle:k.INIT}};function Am(e){const{path:t,attribute:s}=e;return(o,r)=>{o[P]=o[P]||{},o[P][r]={modelType:dr.type,id:`${t}-${s}`,options:{path:t,attribute:s},lifecycle:k.INIT}}}const Ue=f.createLogger({name:"services",group:"Services"}),Cm=async(e,t)=>Nc(e,t,`${exports.BASE_URL}/api/server/login`),Nc=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()},Rm=async e=>Uc(e,`${exports.BASE_URL}/api/server/startPasswordReset`,""),Uc=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()},Lm=async(e,t)=>jc(e,t,`${exports.BASE_URL}/api/server/resetPassword`),jc=async(e,t,s=`${exports.BASE_URL}/api/resetPassword`)=>{Ue.debug(`resetting password with token ${e} and password ${t.replace(/./g,"*")}`);const o=await exports.kosFetch(`${s}`,{method:"POST",destinationAddress:"",body:JSON.stringify({token:e,password:t})});if(Ue.debug(`password reset returned status ${o.status}`),!o.ok){Ue.error(`password reset failed with message ${o.statusText}`);const n=await o.json();throw Error(`${n==null?void 0:n.error}:There was a problem resetting the password.`)}return await o.json()},Pm=async(e,t,s)=>Bc(e,t,s,`${exports.BASE_URL}/api/server/acceptInvite`),Bc=async(e,t,s,o=`${exports.BASE_URL}/api/server/acceptInvite`)=>{Ue.debug(`accepting invite with token ${e} and password ${t.replace(/./g,"*")}`);const r=await exports.kosFetch(`${o}`,{method:"POST",destinationAddress:"",body:JSON.stringify({token:e,password:t,name:s})});if(Ue.debug(`invitation accept returned status ${r.status}`),!r.ok){Ue.error(`invite failed with message ${r.statusText}`);const i=await r.json();throw Error(`${i==null?void 0:i.error}:There was a problem accepting the invite.`)}return await r.json()},xm=Ie.keyframes`
|
|
77
|
+
["${t}"]`;if(o?(w=this.fosSocket)==null?void 0:w.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{Ee.debug("no connection adding to offline messages");const I=o?this.fosSocket:this.socket;I==null||I.addOfflineMessage(u)}}subscribeTopic({topic:t,callback:s,fos:o,bridge:r,destinationAddress:n}){const{unsubscribe:i,count:c}=j(t,s);return Ee.debug(`Topic ${t} currently has ${c} subscribers`),this._sendSubscriptionMessage(t,"subscribe",o,r,n),()=>{const{count:d}=i();Ee.debug(`Topic ${t} currently has ${d} subscribers`),d===0&&this._sendSubscriptionMessage(t,"unsubscribe",o,r,n)}}async whenReady(){const t=this;return this.webSocketSupported?(await v.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(Ht,"_instance");class yu{constructor(t,s,o,r,n){a(this,"disposers",[]);a(this,"activatableDisposers",[]);this.model=t,this.modelData=s,this.modelId=o,this.offlineQueue=r,this.log=n}registerAll(t){var r;const s=((r=this.modelData)==null?void 0:r[G])||{},o=Object.keys(s);this.log.debug(`Found ${o.length} subscriptions in ${this.modelId} (lifecycle: ${t??"any"})`),o.forEach(n=>{const i=s[n],c=i.lifecycle;if(t&&t!==c)return;const d=this.resolvePropKey(n);this.log.debug(`Resolved topic: ${n} → ${d}`);const l=this.createHandler(d,i);this.subscribe(i,d,l,c===x.ACTIVATE)})}deactivate(){this.log.debug(`Deactivating subscriptions for ${this.modelId}`);for(const t of this.activatableDisposers)try{t()}catch(s){this.log.error("Error during subscription disposal",s)}this.activatableDisposers=[]}disposeAll(){const t=[...this.disposers,...this.activatableDisposers];this.log.debug(`Disposing ${t.length} subscriptions for ${this.modelId}`);for(const s of t)try{s()}catch(o){this.log.error("Error during subscription disposal",o)}this.disposers=[],this.activatableDisposers=[]}subscribe(t,s,o,r){const n=t.destinationAddress?this.resolvePropKey(t.destinationAddress):null;if(t.websocket){this.log.debug(`Subscribing to WebSocket topic: ${s}`);const i=Ht.getInstance().subscribeTopic({topic:s,callback:o,fos:t.fos,bridge:t.bridge,destinationAddress:n});this.disposers.push(i)}else{this.log.debug(`Subscribing to EventBus topic: ${s}`);const{unsubscribe:i}=j(s,o);r?this.activatableDisposers.push(i):this.disposers.push(i)}}createHandler(t,s){return async o=>{var r;try{const n=(r=o==null?void 0:o.headers)==null?void 0:r["src-addr"],i=s.destinationAddress&&this.resolvePropKey(s.destinationAddress),c=i?n===i:!0;if(this.model.isReady()){const d=bo(o,s.skipParse),l=s.transform(d);if(c&&s.condition(l,this.modelData,o))return s.handler.call(this.modelData,l,o,this.modelData)}else{this.log.warn(`Model ${this.modelId} not ready. Queuing message for ${t}`);const d=()=>{const l=bo(o,s.skipParse),u=s.transform(l);if(c&&s.condition(u,this.modelData,o))return s.handler.call(this.modelData,u,o,this.modelData)};this.offlineQueue.enqueue(d)}}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 nt(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 bu(e){return!!(e!=null&&e[$e])&&Object.keys(e[$e]).length>0}function vu(e){return!!(e!=null&&e[G])&&Object.keys(e[G]).length>0}class wu{static createAll(t){const{modelId:s,modelTypeName:o,modelData:r}=t,n=ou.create({modelId:s,modelTypeName:o}),i=new su(t,nt(n,"fsm")),c=new ru(nt(n,"offline-queue")),d=new ql(t),l=new zl(t),u={fsm:i,offlineQueue:c,companionManager:d,childResolver:l};if(bu(r)&&(u.effectManager=new Wl(o,s,r,nt(n,"effect"))),vu(r)){const h=nt(n,"subscription");u.subscriptionManager=new yu(t,r,s,c,h),u.onlineLifecycleManager=new nu(t,nt(n,"online"))}return u}}const S=T.getLogger("kos-model"),Mu="kos.extension.model.loader";class Ri{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=wu.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),v.makeAutoObservable(this,{fsm:!1,effectManager:!1,subscriptionManager:!1,onlineLifecycleManager:!1,companionManager:!1,childResolver:!1,offlineQueue:!1}),Vl(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;S.debug(`deactivating model ${this.modelTypeName} with id ${this.modelId}`);try{const r=k.getContext(this.modelId);await((s=(t=this.modelData)==null?void 0:t.deactivate)==null?void 0:s.call(t,r)),S.debug(`Model ${this.modelTypeName} with id ${this.modelId} deactivated`),(o=this.subscriptionManager)==null||o.deactivate()}catch(r){throw S.debug(`Model ${this.modelId} failed to deactivated`),r}}async activate(){var t,s,o;S.debug(`activating model ${this.modelTypeName} with id ${this.modelId}`),await ct(this,x.ACTIVATE);try{const r=k.getContext(this.modelId);await((s=(t=this.modelData)==null?void 0:t.activate)==null?void 0:s.call(t,r)),S.debug(`Model ${this.modelTypeName} with id ${this.modelId} subscribing to all topics`),(o=this.subscriptionManager)==null||o.registerAll(x.ACTIVATE),S.debug(`Model ${this.modelTypeName} with id ${this.modelId} activated`)}catch(r){throw S.debug(`Model ${this.modelId} failed to activate`),r}}async whenInitialized(){await Hr([{condition:()=>this.status===y.FAILED,onMatch:()=>{throw new Error(`Failed to initialize model ${this.modelId}`)}},{condition:()=>this.initialized,onMatch:()=>{S.debug(`Model ${this.modelId} is initialized`)}}])}async whenReady(){await Hr([{condition:()=>this.status===y.FAILED,onMatch:()=>{throw new Error(`Failed to ready model ${this.modelId}`)}},{condition:()=>this.status===y.READY,onMatch:()=>{S.debug(`Model ${this.modelId} is ready`)}}])}async ready(){var t,s,o;if(this.fsm.current===y.READY){S.debug(`already readying model ${this.modelTypeName} with id ${this.modelId} returning`);return}try{S.debug(`readying model ${this.modelTypeName} with id ${this.modelId}`),await ct(this,x.READY),await yi(this,zo.READY,x.READY);const r=k.getContext(this.modelId);await((s=(t=this.modelData)==null?void 0:t.ready)==null?void 0:s.call(t,r)),this.offlineQueue.flush(),(o=this.subscriptionManager)==null||o.registerAll(x.READY),S.debug(`Model ${this.modelId} is ready`);const n={modelId:this.modelId,modelType:this.modelTypeName};N(ri(this.modelTypeName,this.modelId),n),N(ni(this.modelTypeName),n)}catch(r){throw S.error(r),Error(r)}}async load(){var o,r,n,i;const{modelTypeName:t,modelId:s}=this;if(this.fsm.current===y.LOADED||this.fsm.current===y.LOADING){S.debug(`Model ${t} with id ${s} already loaded or loading`);return}S.debug(`Loading model ${t} with id ${s}`),await ct(this,x.LOAD);try{const c=k.getContext(s),d=`${Mu}.${t}`,l=await C.loader.executeLoader(d,{});l&&(S.info(`Setting loaded context for ${s}, type: ${t}`),c==null||c.set(d,l)),await((r=(o=this.modelData)==null?void 0:o.load)==null?void 0:r.call(o,c)),this.loaded=!0,S.debug(`Model ${t} with id ${s} successfully loaded`),(n=this.subscriptionManager)==null||n.registerAll(x.LOAD),(i=this.effectManager)==null||i.setup()}catch(c){throw S.error(`Model ${s} failed to load`,c),c}}async unload(){var t,s,o,r,n;S.debug(`unloading model ${this.modelTypeName} with id ${this.modelId}`);try{const i=this.getChildren().map(d=>{var l;return(l=d.unload)==null?void 0:l.call(d)}).filter(d=>!!d);await Promise.allSettled(i);const c=k.getContext(this.modelId);await((s=(t=this.modelData)==null?void 0:t.unload)==null?void 0:s.call(t,c)),this.loaded=!1,(o=this.onlineLifecycleManager)==null||o.dispose(),S.debug(`Model ${this.modelTypeName} with id ${this.modelId} unloaded`),(r=this.effectManager)==null||r.disposeAll(),(n=this.subscriptionManager)==null||n.disposeAll()}catch(i){throw S.debug(`Model ${this.modelId} failed to unload`),i}}async init(){var r,n,i;const{modelId:t,modelTypeName:s}=this,o=k.getContext(t);S.debug(`Initializing model ${s} with id ${t}`),await ct(this,x.INIT);try{await((n=(r=this.modelData)==null?void 0:r.init)==null?void 0:n.call(r,o)),this.initialized=!0,S.debug(`Model ${s} with id ${t} initialized`),(i=this.onlineLifecycleManager)==null||i.register(),this.registerSubscribers(x.INIT)}catch(c){throw S.error(`Model ${t} failed to initialize`,c),c}}async registerSubscribers(t){var s;S.debug(`registering subscribers in ${this.modelTypeName} with id ${this.modelId}`),(s=this.subscriptionManager)==null||s.registerAll(t)}async online(){var s,o;S.debug(`online model ${this.modelTypeName} with id ${this.modelId}`),this.registerSubscribers();const t=k.getContext(this.modelId);await((o=(s=this.modelData)==null?void 0:s.online)==null?void 0:o.call(s,t))}async offline(){var s,o,r;S.debug(`offline model ${this.modelTypeName} with id ${this.modelId}`),(s=this.subscriptionManager)==null||s.disposeAll();const t=k.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 Li=e=>typeof e=="function",qr=f.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)){qr.debug(`Creating model instance: ${t} [${n}]`);const c=r.create?r.create({modelTypeId:t,id:n,options:o}):new r.class(n,o),d=new Ri({modelTypeName:t,id:n,modelData:c});this.cache.addModel(d),this._createCompanionModels(d,o)}const i=this.cache.getModelById(n);if(!i)throw qr.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=Li(i)?i(t.modelData,s):i;if(!c)continue;const d=`${c}-${t.modelId}`,l=this.createModelInstance(c,d,{data:s,companionParent:t.modelData,kosParentId:t.modelId});l!=null&&l.model&&t.addCompanionModel(l.model)}}}let Eu=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 et(t)}};const Pi=10,Wr=f.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 $l,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 Eu(t),o.cache=new Ol(t.preloadModels),o.instantiator=new _u(t,o.cache),o}static getInstance(t){var s,o;return(!((s=globalThis.kos)!=null&&s.modelManager)||t)&&(Wr.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=>(Wr.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 et(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),Zn.addToDeletionQueue(t.id,setTimeout(()=>this.destroyModel(s),Pi)))}async destroyModel(t){var s;t!=null&&t.modelId&&this.dependencies.canDestroy(t.modelId)&&(await((s=t.unload)==null?void 0:s.call(t)),this.removeModel(t))}createModelInstance(t,s,o={}){return this.instantiator.createModelInstance(t,s,o)}registerCompanionModel(t,s){this._registry.registerCompanionModel(t,s)}registerModel(t){this._registry.registerModel(t)}}const Iu=async({context:e,extension:t})=>{const s=await C.loader.executeLoader(t,{});return e==null||e.set(t,s),s},Tu=async({extension:e,contextData:t,data:s})=>await C.dataMapper.executeMapper(e,s,t),$u=async({extension:e,contextData:t,data:s})=>await C.propertyMapper.executeMapper(e,s,t),Ou=Object.freeze(Object.defineProperty({__proto__:null,executeDataMapperExtension:Tu,executeLoaderExtension:Iu,executePropertyMapperExtension:$u},Symbol.toStringTag,{value:"Module"})),Du="Extensions";class Su{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 cs=(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))(cs||{}),Ne=(e=>(e.CREATE="create",e.INITIALIZE="init",e.READY="ready",e.GO_ONLINE="go_online",e.GO_OFFLINE="go_offline",e.UNLOAD="unload",e.RELOAD="reload",e))(Ne||{});const Au=e=>{const t=m.createMachine("offline",{online:m.state(m.transition("go_offline","offline",m.action(()=>{e.offline(),v.runInAction(()=>{e.isOnline=!1})}))),offline:m.state(m.transition("go_online","online",m.action(()=>{e.online(),v.runInAction(()=>{e.isOnline=!0})})))}),s=m.interpret(t,n=>T.debug(n.machine.current)),o=m.createMachine({creating:m.state(m.transition("create","created")),created:m.state(m.immediate("initializing")),initializing:m.invoke(()=>e.init(),m.transition("done","initialized")),initialized:m.state(m.immediate("loading")),loading:m.invoke(()=>e.load(),m.transition("done","loaded")),loaded:m.state(m.immediate("readying"),m.transition("unload","unloading")),readying:m.invoke(()=>e.ready(),m.transition("done","ready",m.action(()=>{v.runInAction(()=>{e.status="ready"})}))),reloading:m.invoke(()=>e.reload(),m.transition("done","loading")),ready:m.state(m.transition("reload","reloading"),m.transition("unload","unloaded",m.action(e.unload.bind(e))),m.transition("go_online","ready",m.action(()=>{s.send("go_online")})),m.transition("go_offline","ready",m.action(()=>{s.send("go_offline")}))),unloaded:m.state()});return{service:m.interpret(o,n=>T.debug(n.machine.current)),online:s}},J=async e=>{if(e.id){const t=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},Oe=async e=>{await E.getInstance().whenReady(),await E.getInstance().modelManager.initiateDestroyModel(e)},Cu=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)},xi=async e=>{await E.getInstance().whenReady(),await E.getInstance().modelManager.reloadModel(e),f.debug(`reload model initiated for model ${e.id}, model ready: ${fs(e)} - ${Date.now()} `),await J(e),f.debug(`reload model complete for model ${e.id}, model ready: ${fs(e)} - ${Date.now()} `)},Ru=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},Fi=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}},Xe=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}},Ni=(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]))},Lu=(e,t)=>Ni(e,t)[0],Pu=(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},ku=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)},xu=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},wo=(e,t)=>{const s=E.getInstance().modelManager.getModelById(e);if(!s){f.info(`Model not found for id ${e}`);return}return Array.from(s.companionModels.all()).find(r=>t(r.modelData))},te=e=>t=>Object.getPrototypeOf(t).modelTypeId===e,fs=e=>{const t=E.getInstance().modelManager.getModelById(e.id);if(!t)throw new Error("Model not found");return t.isReady()},Fu=f.createLogger({name:"kos-model-factory"}),$t={byModelType:e=>E.getInstance().modelManager.getModelFactory(e),getModelInstance:(e,t,s)=>{const o=$t.byModelType(t);if(!o)throw Fu.error(`No registered factory found for model type ${t}. Please register a factory for this model type. `),Error(`No factory found for model type ${t}`);return o.build(e,s)}},H={Factory:{create:e=>t=>(s,o)=>(o&&k.setParentContext(t,o),$t.getModelInstance(t,e,s))},Singleton:{create:e=>(t,s)=>(s&&k.setParentContext(e,s),$t.getModelInstance(e,e,t))},Model:{instance:e=>t=>$t.getModelInstance(t,e)}};window.KosRegistry=window.KosRegistry||{coreModels:new Map,preloadModels:[],companionModels:new Map,models:new Map};const Zr=window.KosRegistry.coreModels,ro=window.KosRegistry.preloadModels,no=window.KosRegistry.companionModels,Jt=window.KosRegistry.models,$={model:{registerLegacyModel:e=>(t,s)=>(Zr.set(t,s),{preload:$.model.preloadModel(e),model:$.model.register(e),companion:$.companion.register(e),legacy:$.model.registerLegacyModel(e),root:e}),preloadModel:e=>t=>(ro.includes(t)||ro.push(t),{preload:$.model.preloadModel(e),model:$.model.register(e),companion:$.companion.register(e),legacy:$.model.registerLegacyModel(e),root:e}),register:e=>(t,s)=>{const o=io(t)?t.registration():t;return Jt.set(o.type,o),io(t)&&t.relatedModels.forEach(r=>Jt.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],io(t)&&t.relatedModels.forEach(r=>E.getInstance().modelManager.registry.models[r.type]=r.registration().registration))),s&&$.model.preloadModel(e)(o.type),{preload:$.model.preloadModel(e),model:$.model.register(e),companion:$.companion.register(e),legacy:$.model.registerLegacyModel(e),root:e}},get:e=>Jt.get(e),getAll:()=>Array.from(Jt.entries()),getPreloadModels:()=>ro,getLegacyModels:()=>Array.from(Zr.entries()).reduce((e,[t,s])=>(e[t]=s,e),{})},companion:{register:e=>(t,s)=>{const o=no.get(t)||[];return o.push(s),no.set(t,o),{preload:$.model.preloadModel(e),model:$.model.register(e),companion:$.companion.register(e),legacy:$.model.registerLegacyModel(e),root:e}},getAll:()=>Array.from(no.entries())}},Ui=$.model.registerLegacyModel,ji=$.model.register,Nu=$.companion.register,Uu=$.model.preloadModel,Bi=e=>typeof e.updateModel=="function",io=e=>e.registration!==void 0&&typeof e.registration=="function";class Ki{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(){$.model.register({})(this.registration()),this.registerRelatedModels()}}class ae extends Ki{constructor(t){super({...t,singleton:!1,factory:H.Factory.create(t.type)})}instance(t){const s=this.factory(t);return{get:()=>{const o=Xe(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(Bi(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 Ki{constructor(t){super({...t,singleton:!0,factory:H.Singleton.create(t.type)})}instance(){const t=this.factory;return{get:()=>{const o=Xe(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(Bi(r))r.updateModel(o);else throw new Error(`Model ${this.type} is not updateable. Please implement UpdateAware interface`);return r}else throw new Error(`Model is not of type ${this.type}. Received type ${Object.getPrototypeOf(r).modelTypeId}`)}})},options:o=>({build:()=>{const r=t(o);if(this.guard(r))return r;throw new Error(`Model is not of type ${this.type}. Received type ${Object.getPrototypeOf(r).modelTypeId}`)}})}}registration(){return{type:this.type,predicate:this.guard,registration:{[this.type]:{class:this.class,singleton:!0}},factory:this.factory}}}const U=f.createLogger({name:"kos-core"}),ju=()=>{const e=ee(),t=e==null?void 0:e.alias,s=process.env.KOS_CONNECTION_ALIAS;return t||s||void 0},Bu=()=>{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://")},Ku=()=>{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},Gu=()=>{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},Hu=(e,t)=>{let s;return{promise:new Promise((n,i)=>{s=setTimeout(()=>{t?f.error(`Model ${t.modelId} - ${t.modelTypeName} preloading - timed out after ${e}ms`):f.error(`KOS Core preloading timed out after ${e}ms`),i(new Error(`Model ${t==null?void 0:t.modelId} - ${t==null?void 0:t.modelTypeName} - timed out after ${e}ms`))},e)}),cancel:()=>{s&&clearTimeout(s)}}},Jr=e=>typeof e.reload=="function",Vu=e=>typeof e.unload=="function";var Gi=(e=>(e.LOGGED_IN="logged_in",e.LOGGED_OUT="logged_out",e))(Gi||{});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=cs.CREATED,this.authState="logged_out",this._reloading=!1,this._unloading=!1,v.makeAutoObservable(this),j("token",c=>{c&&(this.transport.token=c.body)}),j(Tt.CONNECTED,async()=>{await this.whenReady(),this.fsmService.service.send(Ne.GO_ONLINE)}),j(Tt.DISCONNECTED,async()=>{this.fsmService.service.send(Ne.GO_OFFLINE)}),j("/studioServer/auth/LOGGED_IN",()=>{this.authState="logged_in",this.transport.authorized=!0}),j("/studioServer/auth/LOGIN_REQUIRED",()=>{this.authState="logged_out",this.transport.authorized=!1}),j(Tt.RELOAD,()=>{this.fsmService.service.send(Ne.RELOAD)}),j("/studio/project/reload",()=>{this.fsmService.service.send(Ne.RELOAD)});const s=Ht.getInstance(),o=Ku(),r=Gu(),n=Bu();s.host=o,s.port=Number.parseInt(r),s.protocol=n,process.env.KOS_ALLOW_ANONYMOUS==="true"&&(s.authorized=!0);const i=ju()??t;i&&(s.alias=i.replace("{{TIMESTAMP}}",Date.now().toString())),this._transport=s.init(),this.fsmService=Au(this),this.fsmService.service.send(Ne.CREATE)}get onlineStatus(){return this.isOnline&&!this._reloading&&!this._unloading}get reloading(){return this._reloading}get unloading(){return this._unloading}async reload(){var r,n,i,c;const t=Date.now();if(this._reloading){U.info("reload already in progress");return}this._reloading=!0,U.warn("reloading KOS Core"),U.warn("reloading preloaded models");const s=this.modelManager;for(const d of s.preloadedModels)Jr(d.modelData)&&(U.info(`reloading model ${d.modelId}`),(r=d.unload)==null||r.call(d),await d.modelData.reload(),(n=d.registerSubscribers)==null||n.call(d),U.info(`reloading model ${d.modelId} complete`));for(const d of s.models)!s.preloadedModels.includes(d)&&Jr(d.modelData)&&((i=d.unload)==null||i.call(d),await d.modelData.reload(),(c=d.registerSubscribers)==null||c.call(d));const o=Date.now()-t;setTimeout(()=>{v.runInAction(()=>{U.warn("reloading KOS Core complete"),this._reloading=!1})},1e3-o)}async online(){U.debug("KOS Core going online"),await this._transport.whenReady(),U.debug("KOS Transport Ready. Calling online() for models"),N("/kosCore/online","/kosCore/online"),console.timeEnd("kosCore:startup")}async offline(){U.debug("KOS Core going offline"),N("/kosCore/offline","/kosCore/offline")}async unload(){var r;U.debug("Unloading KOS Core");const t=Date.now();this._unloading=!0,U.debug("unloading KOS Core");const s=this.modelManager;for(const n of s.models)Vu(n.modelData)&&((r=n.unload)==null||r.call(n));const o=Date.now()-t;setTimeout(()=>{v.runInAction(()=>{this._unloading=!1})},1e3-o)}async whenReady(){await v.when(()=>this.status===cs.READY)}async ready(){U.debug("Readying KOS Core"),await this._transport.whenReady();const t=this.modelManager.preloadedModels.map(r=>({modelId:r.modelId,model:r,promise:r.whenReady()})),o=(await Promise.allSettled(t.map(r=>{const{promise:n,cancel:i}=Hu(5e3,r.model);Promise.race([r.promise.then(()=>{i()}),n])}))).filter(r=>r.status==="rejected");if(o.length)throw U.error(`There were ${o.length} failed models on model preloading`),Error(`There were ${o.length} failed models on model preloading`);U.debug("leaving kos-core ready() ")}get isReady(){return this.status===cs.READY}set transport(t){this._transport=t}get transport(){return this._transport}get coreInitialized(){return this.initialized}get modelsLoaded(){return this.loaded}async init(){U.debug("entering kos-core init()"),console.time("kosCore:startup"),console.time("kosCore:init"),await this._transport.whenReady(),this.initialized=!0,U.debug("initialized - leaving kos-core init()"),console.timeEnd("kosCore:init")}async load(){U.debug("entering kos-core load()"),console.time("kosCore:load"),this.loaded=!0,U.debug("loaded - leaving kos-core load()"),console.timeEnd("kosCore:load")}static create(t,s,o){var i,c,d;const r=this.getInstance({reset:s,connectionAlias:o});(i=t.extensions)!=null&&i.dataMapper&&Object.keys(t.extensions.dataMapper).forEach(l=>{var h,p;const u=(p=(h=t.extensions)==null?void 0:h.dataMapper)==null?void 0:p[l];u&&(Array.isArray(u)?u.forEach(w=>{C.dataMapper.registerDataMapper(l,w)}):C.dataMapper.registerDataMapper(l,u))}),(c=t.extensions)!=null&&c.propertyMapper&&Object.keys(t.extensions.propertyMapper).forEach(l=>{var h,p;const u=(p=(h=t.extensions)==null?void 0:h.propertyMapper)==null?void 0:p[l];u&&C.propertyMapper.registerPropertyMapper(l,u)}),(d=t.extensions)!=null&&d.contextLoader&&Object.keys(t.extensions.contextLoader).forEach(l=>{var h,p;const u=(p=(h=t.extensions)==null?void 0:h.contextLoader)==null?void 0:p[l];u&&C.loader.registerLoader(l,u)}),$.model.getAll().forEach(([,l])=>{t.models={...t.models,...l.registration}}),t.models={...t.models,...$.model.getLegacyModels()},$.companion.getAll().forEach(([l,u])=>{t.companionModels={...t.companionModels},t.companionModels[l]=t.companionModels[l]||[];for(const h of u)t.companionModels[l].push({type:h})}),$.model.getPreloadModels().forEach(l=>{t.preloadModels.includes(l)||t.preloadModels.push(l)});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 Qr=f.createLogger({name:"kos-fetch"}),Yu=process.env.KOS_WS_TIMEOUT?parseInt(process.env.KOS_WS_TIMEOUT):3e4,zu=()=>new Promise(e=>{setTimeout(()=>{e(!0)},0)}),qu=e=>e!=null&&e.studio?wi:e!=null&&e.fos?Mi:_i,Wu=async(e,t)=>{const s=E.getInstance().transport;await s.whenReady();const o=Qe(),r=new URL(e),n=`${r.pathname}${r.search}`;Qr.debug(`path: ${n}`);const i=(t==null?void 0:t.timeout)||Yu,c=qu(t),d=ve(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(l=>{const u=new AbortController,h=setTimeout(()=>{Qr.error(`Timeout occurred - url: ${e}`),u.abort(),l({headers:mo({}),status:404,ok:!1,json:async()=>null,body:yo(""),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:p}=j(o,b=>{var I,A,se;clearTimeout(h);const _={headers:mo((b==null?void 0:b.headers)||{}),status:((I=b==null?void 0:b.headers)==null?void 0:I.status)&&parseInt((A=b==null?void 0:b.headers)==null?void 0:A.status)||200,ok:((se=b==null?void 0:b.headers)==null?void 0:se.status)==="200",json:async()=>{var we;try{return(we=b==null?void 0:b.body)!=null&&we.length?JSON.parse(b.body):null}catch{throw Error("Not a JSON response")}},text:async()=>(b==null?void 0:b.body)||"",body:yo((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.")}};p(),zu().then(()=>l(_))}),w=t!=null&&t.fos?s.fosSocket:s.socket;if(!w)throw Error(`No web socket transport available: ${t}`);w==null||w.send(d)})};exports.BASE_URL="kos:";exports.kosFetch=Wu;if(process.env.KOS_MOCK_FETCH==="true"){const e=process.env.KOS_PORT||"9999";exports.kosFetch=fetch,exports.BASE_URL=`http://localhost:${e}`}const Zu=f.createLogger({name:"kos-model-visitor",group:"kos-ui-core"});class Ju{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)){Zu.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 Hi=()=>({isMock:!1,URL:exports.BASE_URL}),Qu=f.createLogger({name:"kos-service-request"}),Xu="errUnknown";async function Qt(e,t,s,o,r){const n=o!=null&&o.path?Object.keys(o.path).reduce((h,p)=>String(h).replace(`{${p}}`,o==null?void 0:o.path[p]),String(e)):String(e),i=o!=null&&o.query?Object.keys(o.query).map(h=>`${h}=${o.query[h]}`).join("&"):"",c=`${Hi().URL}${n}${i?`?${encodeURIComponent(i)}`:""}`;Qu.debug(`fullUrl: ${c}`);const d={method:String(t).toUpperCase(),body:null,...s};r&&(d.body=JSON.stringify(r));const l=await exports.kosFetch(c,d);return l.status<200||l.status>=400?[`${l.statusText||Xu}`,null]:[null,(await l.json()).data]}function Zo(){return{get:(e,t,s)=>Qt(e,"get",s,t),post:(e,t,s,o)=>Qt(e,"post",o,t,s),put:(e,t,s,o)=>Qt(e,"put",o,t,s),delete:(e,t,s)=>Qt(e,"delete",s,t)}}class Vi{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 eh=async(e,t)=>{const s=new Vi;t.forEach(r=>s.use(r));const o={data:e,result:{}};return await s.execute(o),o.result},et=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}}),th=e=>{E.getInstance().modelManager.registerModel(e)},sh=(e,t)=>{E.getInstance().modelManager.registerCompanionModel(e,t)},Yi=Symbol("KosObservableData");class zi{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,v.createAtom(s.toString())),(r=this.atomMap.get(s))==null||r.reportChanged(),!0},ownKeys:()=>Array.from(this.map.keys())});this.map=v.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)}}zi.prototype[Yi]=!0;function oh(e,t){return new Proxy(e,{construct:(s,o)=>{const r=new e(...o);return r.setValues(t),r.proxy}})}const ye=e=>{const t=oh(zi,e);return new t(e)},Xr="/kos/ui/internal/heartbeat/",rh=({relationshipId:e,destinationAddress:t,onAbort:s,waitTime:o,beatTime:r})=>{const n=E.getInstance().transport,i=new AbortController;let c=performance.now();const d=n.subscribeTopic({topic:`${Xr}${e}`,callback:()=>{c=performance.now()}}),l=o??3e3,u=window.setInterval(()=>{let _=performance.now()-c;_=_/1e3,_>l/1e3&&i.abort()},l),h=r??2e3,p=window.setInterval(()=>{Si({msg:{},options:{topic:`${Xr}${e}`,destinationAddress:t}})},h),w=()=>{window.clearInterval(p),window.clearInterval(u),d()},b=()=>{w(),s&&s(),i.signal.removeEventListener("abort",b)};return i.signal.addEventListener("abort",b),{cleanUpHeartbeat:w}},qi=(...e)=>t=>e.reduce((s,o)=>o(s),t),nh={maxAttempts:5,baseDelayMs:100,backoffFactor:1.5};async function ih(e,t){let s=1;const o={...nh,...t},{maxAttempts:r,baseDelayMs:n,backoffFactor:i}=o;let c=n;for(;s<=r;)try{return await e()}catch(d){if(f.error(`Attempt ${s} failed: ${d}`),s<r)c=n*Math.pow(i,s),await new Promise(l=>setTimeout(l,c)),s++;else throw d}throw new Error("All attempts failed")}const ah=f.createLogger({name:"kos-service-request"}),q=e=>({isMock:!1,URL:exports.BASE_URL}),ch=(e,t,s)=>async({id:o,tracker:r,urlOverride:n,ordered:i,studio:c,fos:d,bridge:l,destinationAddress:u})=>{const h={method:"DELETE"};e&&(h.destinationAddress=e),r&&(h.tracker=r),tt(h,{ordered:i,studio:c,fos:d,bridge:l,destinationAddress:u});const p=await s(n||`${t}/${o}`,h);if(!p.ok)throw Error(`There was a problem deleting the model; returned status ${p.status}`);return await p.json()},tt=(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),dh=(e,t,s)=>async({urlOverride:o,ordered:r,studio:n,fos:i,bridge:c,timeout:d,destinationAddress:l})=>{const u={method:"GET"};e&&(u.destinationAddress=e),tt(u,{timeout:d,ordered:r,studio:n,fos:i,bridge:c,destinationAddress:l});const p=await s(o||t,u);if(!p.ok){let b;try{b=await p.json()}catch{}throw new ce(`There was a problem retrieving the model; returned status ${p.status}`,b)}return await p.json()},lh=(e,t,s)=>async({urlOverride:o,ordered:r,studio:n,fos:i,bridge:c,tracker:d,timeout:l,destinationAddress:u})=>{const h={method:"GET"};e&&(h.destinationAddress=e),d&&(h.tracker=d),tt(h,{timeout:l,ordered:r,studio:n,fos:i,bridge:c,destinationAddress:u});const p=o||t;ah.debug(`resolvedUrl: ${p}`);const w=await s(p,h);if(!w.ok){let _;try{_=await w.json()}catch{}throw new ce(`There was a problem retrieving the model; returned status ${w.status}`,_)}return await w.json()},uh=(e,t,s)=>async({urlOverride:o,id:r,ordered:n,studio:i,fos:c,bridge:d,timeout:l,destinationAddress:u})=>{const h={method:"GET"};e&&(h.destinationAddress=e),tt(h,{timeout:l,ordered:n,studio:i,fos:c,bridge:d,destinationAddress:u});const p=o||`${t}/${r}`,w=await s(p,h);if(!w.ok){let _;try{_=await w.json()}catch{}throw new ce(`There was a problem retrieving the model; returned status ${w.status}`,_)}return await w.json()};class ce extends Error{constructor(s,o){super(s);a(this,"payload");this.name="FetchException",this.payload=o}}const en=(e,t,s)=>async({model:o,urlOverride:r,ordered:n,tracker:i,studio:c,fos:d,bridge:l,timeout:u,destinationAddress:h})=>{const p={method:"POST",body:typeof o=="string"?o:JSON.stringify(o)};e&&(p.destinationAddress=e),i&&(p.tracker=i),tt(p,{timeout:u,ordered:n,studio:c,fos:d,bridge:l,destinationAddress:h});const w=await s(r||t,p);if(!w.ok){let _;try{_=await w.json()}catch{}throw new ce(`There was a problem sending the POST data; returned status ${w.status}`,_)}return await w.json()},tn=(e="POST",t,s,o)=>async({model:r,id:n,urlOverride:i,ordered:c,studio:d,fos:l,bridge:u,timeout:h,destinationAddress:p})=>{const w={method:e};r&&(w.body=JSON.stringify(r)),t&&(w.destinationAddress=t),tt(w,{timeout:h,ordered:c,studio:d,fos:l,bridge:u,destinationAddress:p});const b=await o(i||`${s}/${n}`,w);if(!b.ok){let I;try{I=await b.json()}catch{}throw new ce(`There was a problem modifying the model; returned status ${b.status}`,I)}return await b.json()},V={build:({destinationAddress:e="",basePath:t,getAllPath:s,getOnePath:o,deleteModelPath:r,addModelPath:n,modifyModelPath:i,mock:c=!1})=>{const d=c?fetch:exports.kosFetch;return{getAll:dh(e,s||t,d),getModelById:uh(e,o||t,d),getOne:lh(e,o||t,d),addModel:en(e,n||t,d),deleteModel:ch(e,r||t,d),modifyModel:tn("POST",e,i||t,d),putModel:tn("PUT",e,i||t,d),postModel:en(e,n||t,d)}}},hh=Qe(),Wi=()=>`kos-${hh}`,gh=e=>!!e&&!e.includes("VM_SERVICE")&&e.startsWith(Wi()),Jo=async(e,t=6e4)=>new Promise((s,o)=>{const{unsubscribe:r}=j(e,i=>{T.debug(`recieved response for refId ${e}: ${i}`),r(),clearTimeout(n);try{const c=i!=null&&i.body?JSON.parse(i.body):{};s(c)}catch{const c=(i==null?void 0:i.body)||{};s(c)}}),n=setTimeout(()=>{r(),o(Error(`Request with ID ${e} timed out. Cancelling.`))},t)}),fh=async(e,t,s)=>{const o=Jo(s),r=await Promise.allSettled([e(t),o]);if(r[0].status==="fulfilled"){if(r[1].status==="rejected")throw Error(r[1].reason);if(r[0].value){if(r[1].value.error)throw Error(r[1].value.error);return r[0].value.data=r[1].value,r[0].value}}else throw Error(r[0].reason)},ph=async({topic:e,msg:t,requestId:s})=>{const o=s??Qe(),r=Jo(o);N(e,t,{sync:o});const n=await r;if(n.error)throw Error(n.error);return n},ue=new Map;class Zi{constructor(t){a(this,"_context");a(this,"_parent");a(this,"_id");this._id=t,this._context=new v.ObservableMap({}),this._parent="",v.makeAutoObservable(this)}setParent(t){Y(()=>{this._parent=t})}get id(){return this._id}get context(){return this._context}get parentModel(){var t;if(this._parent)return(t=Xe(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=ue.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 k={createContext:(e,t)=>{const s=ue.get(e)??new Zi(e);if(t){if(!ue.has(t))throw new Error(`Parent context ${t} does not exist`);s.setParent(t)}else e!=="root"&&s.setParent("root");return ue.set(e,s),s},getContext:e=>ue.get(e),deleteContext:e=>{ue.delete(e)},setParentContext:(e,t)=>{var s;if(!ue.has(t))throw new Error(`Parent context ${t} does not exist`);(s=ue.get(e))==null||s.setParent(t)},rootContext:()=>ue.get("root")};k.createContext("root");const mh=e=>k.getContext(e.id);function yh(e,t){return e.length!==t.length?!1:e.every(s=>t.includes(s))}class Qo{constructor({container:t,key:s}){a(this,"_container");a(this,"_map");a(this,"_key");a(this,"data");this._container=t,this._map=v.observable.map(new Map),this._key=s,this.data=ye(),this.generateIndex(),v.autorun(()=>{this._container.revision&&this.generateIndex()}),v.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(yh(n,i))f.debug(`KosContainerIndex - Index ${r} is the same`);else{this.data[r]=n;const c=t.get(r)||new Set;this._map.set(r,c)}})}generateIndex(){v.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 bh(e,t,s=[]){const o=Object.getOwnPropertyDescriptors(e);return Object.keys(o).filter(i=>v.isComputedProp(e,i)).filter(i=>s.includes(i)).map(i=>v.reaction(()=>e[i],(c,d)=>{t({name:i,newValue:c,oldValue:d})}))}const it=f.createLogger({name:"kos-container-model"});class le{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=v.observable.map(new Map),this._sortKey=t==null?void 0:t.sortKey,this._revision=1;const s=t!=null&&t.extensionId?C.indexExtension.loadIndexExtensions(t.extensionId):{},o=(t==null?void 0:t.indexMap)||{};this._optionsMap={...o,...s};const r=t!=null&&t.indexMap?Object.keys(t.indexMap).reduce((n,i)=>(n[i]=void 0,n),{}):{};this._index=v.observable.map(r),this.idx=ye(),this._parentId=t==null?void 0:t.parentId,v.makeAutoObservable(this),this.init()}init(){Object.keys(this._optionsMap).forEach(t=>{const s=this._optionsMap[t],o=new Qo({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(){v.runInAction(()=>{this._revision=this._revision+1})}addAll(t){v.runInAction(()=>{t.forEach(s=>this.addModel(s,!0))}),this.increment()}removeAll(t){v.runInAction(()=>{t.forEach(s=>this.removeModel(s,!0)),this.increment()})}addModel(t,s){this._data.set(t.id||"",t),t.id&&this._parentId&&k.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 p,w;n.includes(u.name)&&((p=this.index.get(i.get(u.name)))==null||p.refresh());const h=r.filter(([,b])=>typeof b=="function");for(const[b]of h)(w=this.index.get(b))==null||w.refresh()},d=bh(t,c,n.filter(u=>typeof u=="string")),l=v.observe(t,c);this._disposerMap.set(t.id||"",()=>[l,...d].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??[]:(it.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):(it.info(`key ${s} not found in ${t} index: ${Array.from(o.index.keys())}`),[])}else return it.info(`index ${t} not found in ${Array.from(this.index.keys())}`),[]}async clear(){this._data.forEach(t=>{const s=t.id;Oe(t).then(()=>{it.debug(`${s} destroyed, removing from map`),this.removeModel(s,!0)}).catch(o=>it.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 ao=f.createLogger({name:"kos-data-container"});class Ji{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=v.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=v.observable.map(s),this.idx=ye(),v.makeAutoObservable(this,{}),this.init()}init(){Object.keys(this._optionsMap).forEach(t=>{const s=this._optionsMap[t],o=new Qo({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){v.runInAction(()=>{t.forEach(s=>this.addModel(s))})}removeAll(t){v.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(){v.runInAction(()=>{this._revision=this._revision+1})}addModel(t,s){const o=v.isObservable(t)?t:v.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=v.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=v.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??[]:(ao.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):(ao.info(`key ${s} not found in ${t} index: ${Array.from(o.index.keys())}`),[])}else return ao.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 vh{constructor({type:t,model:s,childRegistration:o}){a(this,"type");a(this,"childRegistration");a(this,"model");this.type=t,this.model=s,this.childRegistration=o}get factory(){return H.Factory.create(this.type)}get registration(){return{[this.type]:{class:this.model,singleton:!1,factory:this.factory},...this.childRegistration}}get predicate(){return te(this.type)}}class wh{constructor({type:t,model:s,childRegistration:o}){a(this,"type");a(this,"model");a(this,"childRegistration");this.type=t,this.model=s,this.childRegistration=o}get factory(){return H.Singleton.create(this.type)}get registration(){return{[this.type]:{class:this.model,singleton:!0,factory:this.factory},...this.childRegistration}}get predicate(){return te(this.type)}}class Qi{constructor(){a(this,"_token");v.makeAutoObservable(this),j("token",t=>{this.token=t==null?void 0:t.body})}get token(){return this._token}set token(t){this._token=t}}class Xi{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 d of this.routes){const l=this.matchRoute(d.path,o);if(d.method===t.method&&l){i.params=l;let u=0;const h=async()=>{if(u<d.middlewares.length){const p=d.middlewares[u++];await p(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 ea=f.createLogger({name:"intent-service"}),Mh=e=>{jo(`/kos/intent/${e.type}`)?N(`/kos/intent/${e.type}`,e.options,{"kos.intent.type":e.type}):ea.info(`No subscribers for intent ${e.type}. Intent not sent.`)},_h=async e=>new Promise(t=>{const{type:s,options:o}=e;if(jo(`/kos/intent/${e.type}`)){const r=Qe(),{unsubscribe:n}=j(r,c=>{clearTimeout(i),n(),c&&(c.headers=c.headers||{},c.headers["kos.intent.type"]=s,c.headers.responseId=r),t([null,{body:c==null?void 0:c.body,payload:c}])}),i=setTimeout(()=>{n(),t([`Intent ${s} timed out after 1 second`,null]),console.warn(`Intent ${s} timed out after 1 second`)},1e3);N(`/kos/intent/${s}`,o,{"kos.intent.type":s,sync:r})}else ea.info(`No subscribers for intent ${e.type}. Intent not sent.`),t([null,{body:void 0,payload:void 0}])}),Mo=v.when,Xo=v.computed,Y=v.runInAction,F=v.autorun,ta=v.reaction,er=v.observable,tr="Not Assigned",Eh="kos.trouble.added",Ih="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||{}),Ot=(e=>(e.TIME_CHANGE="/kos/internal/time/time",e.DAY_CHANGE="/kos/internal/time/day",e.TIMEZONE_CHANGE="/kos/internal/time/timezone",e))(Ot||{});const sa=f.createLogger({name:"config-bean-service",group:"Services"}),sr=exports.BASE_URL,oa=e=>(e==null?void 0:e.decimals)!==void 0,{postModel:Th,getOne:$h}=V.build({destinationAddress:"",basePath:`${sr}/kos/config/`}),ra=async(e,t,s="/api/kos/config")=>(sa.debug(`sending modify request for ConfigBean: ${e}`),Th({model:t,urlOverride:`${sr}${s}/${e}`})),na=async(e,t="/api/kos/config")=>(sa.debug(`sending get request for ConfigBean: ${e}`),await $h({urlOverride:`${sr}${t}/details/${e}/15`})),or=e=>e.toLowerCase()==="true"||e.toLowerCase()==="false",Us=e=>{try{const t=Number(e);return!isNaN(t)}catch{return!1}};function ia(e=[]){return e.reverse().reduce((t,s)=>{const{overrides:o}=s;return o&&(t={...t,...o}),t},{})}function aa(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])?aa(e[o],r,s):s[r]=e[o]}return s}const ca=(e,t)=>{const s=e.details[0].bean||ia(e.details[0].scopes),o=aa(s);v.runInAction(()=>{const r={...o};t.props.setValues(r)})},da=(e,t)=>{v.runInAction(()=>{e.changes.forEach(s=>{const o=s.attr;let r=s.currentValue,n=s.previousValue;typeof r=="string"&&or(r)&&(r=r.toLowerCase()=="true",n=(n==null?void 0:n.toLowerCase())=="true"),typeof r=="string"&&Us(r)&&(r=Number(r),n=Number(n)),t.props[o]=r,t.prevProps[o]=n})})},la=e=>Object.fromEntries(e.props.entries),Oh=e=>t=>s=>e.build(t,s);var Dh=Object.defineProperty,Sh=Object.getOwnPropertyDescriptor,ua=(e,t,s,o)=>{for(var r=o>1?void 0:o?Sh(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Dh(t,s,r),r};function Ah(e,t){for(const s of e)if(new RegExp(`^${s}$`).test(t))return s}const rr="config-bean-model",Xt=f.getLogger(rr),Ch=Se("path");let ps=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=ra,getConfigBean:o=na}=t;this._modifyConfigBean=s,this._getConfigBean=o,this.props=ye(),this.prevProps=ye()}get values(){return this.props.values}async ready(){Xt.debug(`readying config bean ${this.path}`),Xt.debug(`complete readying config bean ${this.path}`)}async load(){Xt.debug(`loading config bean ${this.path}`);const e=await this._getConfigBean(this.path,this.serviceBasePath);if(e!=null&&e.data){const t=e.data;ca(t,this),Xt.debug(this.values);const s=e==null?void 0:e.data.details[0].schema;Y(()=>{s&&(this._schema=s)})}}get schemaKeys(){var e;return Object.keys(((e=this._schema)==null?void 0:e.schema)||{})}getSchemaForProperty(e){var s,o;if(this.schemaKeys.includes(e))return(s=this._schema)==null?void 0:s.schema[e];const t=Ah(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=la(this);await this._modifyConfigBean(this.path,e,this.serviceBasePath)}handleConfigBeanUpdated(e){da(e,this)}};ua([R({topic:`/kos/config/${Ch}`,websocket:!0})],ps.prototype,"handleConfigBeanUpdated",1);ps=ua([O(rr)],ps);const At=new ae({class:ps,type:rr}),js=({path:e,lazy:t,serviceBasePath:s})=>(o,r)=>{o[P]=o[P]||{},o[P][r]={modelType:At.type,id:`${At.type}-${e}`,options:{path:e,serviceBasePath:s},lifecycle:x.INIT,lazy:t}},{URL:ha}=q(),{getOne:Rh,getAll:Lh}=V.build({basePath:`${ha}/api/kos/regions/info`}),ga=async()=>await Rh({}),fa=async()=>await Lh({urlOverride:`${ha}/api/kos/regions`}),Ph=Object.freeze(Object.defineProperty({__proto__:null,getRegionInfo:ga,getRegions:fa},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 pa={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 kh(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},{...pa});return{...e,...o}}function xh(e,t){const s=t.id,o=t.units.reduce((r,n)=>{const i=r[n.measure]||{},c=i[s]||{};i[s]=c;const d=[n.measure,n.scale,n.offset,n.decimals,n.alias,s];return c[n.name]=d,Object.hasOwn(n,"default")&&Object.defineProperty(c,"default",{value:d,writable:!0,enumerable:!0,configurable:!0}),r[n.measure]=i,n.alias&&(r[n.alias]=i),r},{time:{[s]:{...pa}}});return Object.keys(o).forEach(r=>{e[r]={...e[r],...o[r]}}),e}function Fh(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 Nh=Object.defineProperty,Uh=Object.getOwnPropertyDescriptor,nr=(e,t,s,o)=>{for(var r=o>1?void 0:o?Uh(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Nh(t,s,r),r};const ds="region-info-model",at=f.createLogger({name:"region-info-model"});let Ct=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,d;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 l=this.measureMap[s.measure];if(!l)throw Error(`Could not find measure ${s.measure}. Measure should be one of ${Object.keys(this.measureMap).join(", ")}`);i=(c=l[s.system])==null?void 0:c.default,i||at.info("Could not find default unit for measure",s.measure)}if(!n&&t.measure&&t.system){const l=this.measureMap[t.measure];if(!l)throw Error(`Could not find measure ${s.measure}. Measure should be one of ${Object.keys(this.measureMap).join(", ")}`);n=(d=l[t.system])==null?void 0:d.default,n||at.info("Could not find default unit for measure",t.measure)}return!n||!i?(at.warn("Could not find unit to convert to or from. Return value as is"),String(e)):this.convertByUnit(e,n,i)}async init(){at.debug("initializing region info")}async load(){at.debug("loading region info");const e=await fa();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 ga();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(kh,{}),this.measureMap=t.data.unitSystems.reduce(xh,{}),this.defaultMeasureMap=t.data.unitSystems.reduce(Fh,{}),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))}};nr([js({path:"kos:service:region:settings"})],Ct.prototype,"regionSource",2);nr([js({path:"kos:service:region"})],Ct.prototype,"region",2);Ct=nr([O(ds)],Ct);const z={registration:{[ds]:{class:Ct,singleton:!0}},type:ds,factory:H.Singleton.create(ds)},sn=({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},ma=(e,t,s)=>{const{model:o}=Xe(z.type);if(!o)throw new Error("RegionInfo model not found");if(!fs(o))throw new Error("RegionInfo model not ready");const r={system:o.defaultUnitSystem},n=sn({source:t}),i=sn({source:s||r,defaultMeasure:o.getUnitMeasure(n.unit||"")});return o.convert(e,n,i)};function on({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 rn({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 Pe=(e,t)=>s=>!e||!t?s:Us(s)?ma(Number(s),e,t):s,jh=(e,t,s,o)=>{if((e==null?void 0:e.type)==="enum"||!(e!=null&&e.options))return[];if(e.options.type==="rangeCount")return on(e.options).map(Pe(s,o));if(e.options.type==="rangeInterval")return rn(e.options).map(Pe(s,o));if(e.options.type==="list"){const{list:r}=e.options;return r.map(Pe(s,o))}else{if(e.options.type==="unitSystemRangeCount"&&t)return on(e.options.unitSystems[t]).map(Pe(s,o));if(e.options.type==="unitSystemRangeInterval"&&t)return rn(e.options.unitSystems[t]).map(Pe(s,o));if(e.options.type==="unitSystemList"&&t){const{list:r}=e.options.unitSystems[t];return r.map(Pe(s,o))}}return[]},Bh=(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 Kh=Object.defineProperty,Gh=Object.getOwnPropertyDescriptor,ir=(e,t,s,o)=>{for(var r=o>1?void 0:o?Gh(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};function Hh(e){return(e==null?void 0:e.type)==="enum"}function Vh(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 Yh(e,t){const s=new Date;s.setHours(0,0,0,0);const o=new Date(s.getTime()+e*1e3);return me.format(o,t)}const ls="config-bean-prop-model",ke=f.createLogger({name:"config-bean-prop-model"}),zh=Se("path"),qh=Se("serviceBasePath");let Rt=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 oa(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?Vh(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=Hh(o)?o.values:jh(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 d=this.getFormatterOptions(s);if(d){let l=String(e);return l=d.formatToParts(Number(e))[0].value,Number(l)}}catch(d){ke.info(`error formatting value ${e}`,d)}return Number(e).toFixed(i)}return e}get previousValue(){return this.getValue(!1)}getValue(e){const t=this.bean[e?"props":"prevProps"][this.attribute];if(typeof t=="boolean")return t;if(this.getConverter()&&!isNaN(t)){const{backend:o,display:r}=this.getConverterUnits();return this.regionInfo.convert(Number(t),o,r)}return t||""}async activate(){ke.debug(`activating config bean ${this.id}`)}get displayValue(){const e=this.value;if(typeof e=="boolean")return String(e);if(this.schemaFormat==="drt"){const s=this.regionInfo.is12HourTimeFormat?"h:mm:ss a":"HH:mm:ss";return Yh(e,s)}if(!isNaN(e))try{const t=this.getConverter(),s=this.getFormatterOptions(t);if(s){let o=String(e);return o=s.format(Number(e)),o}}catch(t){ke.error(`error formatting value ${e}`,t)}return String(e)}get unit(){const e=this.getConverter();if(!isNaN(this.value)){const t=this.getFormatterOptions(e);if(t){const o=t.formatToParts(Number(this.value)).find(r=>r.type==="unit");return(o==null?void 0:o.value)??this.getDefaultUnit(e)}}return this.getDefaultUnit(e)}get displayOptions(){var r;const e=this.bean.getSchemaForProperty(this.attribute),t=this.regionInfo.defaultUnitSystem,s=this.getConverter(),o=((r=s==null?void 0:s.to)==null?void 0:r.system)??t;return Bh(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 d=s?{style:"unit",unit:this.getDefaultUnit(e)}:null,l=this.formatter||d;if(l){let u=typeof l=="function"?l(((n=e==null?void 0:e.to)==null?void 0:n.system)||t):l;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){ke.error(`error creating formatter ${u}. Returning the raw value`,h)}}else ke.debug(`no formatter found for config bean prop ${this.id}. Returning the raw value`)}return r}getConverter(){var o,r,n,i,c,d,l,u,h,p,w;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,A=b||_||I||t,se=((l=(d=this.converter)==null?void 0:d.to)==null?void 0:l.unit)||this.regionInfo.getDefaultUnitForMeasure(A,((h=(u=this.converter)==null?void 0:u.to)==null?void 0:h.system)??this.regionInfo.defaultUnitSystem),we=((w=(p=this.converter)==null?void 0:p.to)==null?void 0:w.system)??this.regionInfo.getUnitSystem(se),rt=this.schemaFormat==="drt"?"second":this.schemaFormat||s;return{...this.converter,from:{unit:rt,...this.converter.from},to:{...this.converter.to,unit:se,system:we},measure:A}}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){ke.debug(`updating property ${this.attribute} with value ${e}`);let t=e;if(this.getConverter()&&!isNaN(t)){const{backend:r,display:n}=this.getConverterUnits();t=this.regionInfo.convert(Number(t),n,r)}const o=Array.isArray(t)?JSON.stringify(t):String(t);await this.bean.updateProperty(this.attribute,o)}};ir([Ae({modelType:z.type})],Rt.prototype,"regionInfo",2);ir([js({path:zh,serviceBasePath:qh})],Rt.prototype,"bean",2);Rt=ir([O(ls)],Rt);const Ce={registration:{[ls]:{class:Rt,singleton:!1}},type:ls,factory:H.Factory.create(ls)};function Wh(e){const{path:t,attribute:s,converter:o,formatter:r,lazy:n,optionsExpander:i,serviceBasePath:c}=e,d=o;return d&&(typeof d!="function"&&typeof d.from=="string"&&(d.from={unit:d.from}),typeof d!="function"&&typeof d.to=="string"&&(d.to={unit:d.to})),(l,u)=>{l[P]=l[P]||{},l[P][u]={modelType:Ce.type,id:`${t}-${s}`,options:{path:t,attribute:s,serviceBasePath:c,converter:d,formatter:r,optionsExpander:i},lifecycle:x.INIT,lazy:n}}}class Zh{constructor(t,s){a(this,"futures");a(this,"defaultContext");a(this,"context");a(this,"disposers",new Map);a(this,"container");this.futures=er.map(new Map),this.context="",this.defaultContext=s||"",this.container=t,v.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=F(()=>{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 ar{constructor(t){a(this,"disposer");a(this,"_future");a(this,"container");a(this,"onFutureUpdate");this._future=void 0,this.container=t,v.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=F(()=>{var o,r;(t.endState||t.progress)&&((r=(o=this.container)==null?void 0:o.onFutureUpdate)==null||r.call(o,t))});this.disposer=s}get allFutures(){return this._future?[this._future]:[]}get timeRemaining(){var t;return((t=this._future)==null?void 0:t.timeRemaining)||""}get status(){var t;return((t=this._future)==null?void 0:t.status)||"NOT_RESOLVED"}get progress(){var t;return((t=this._future)==null?void 0:t.progress)||-1}async cancel(){if(this._future)try{await this._future.cancelFuture()}catch(t){throw f.error(t),t}}}const ya="future-model",st=et(ya),Bs=f.createLogger({name:"future-service",group:"Services"}),{isMock:Jh,URL:Vt}=q();var Ge=(e=>(e.Success="SUCCESS",e.Fail="FAIL",e.Aborted="ABORT",e.Canceled="CANCEL",e))(Ge||{});const{getAll:Qh,modifyModel:Xh,addModel:eg,deleteModel:tg,postModel:sg}=V.build({destinationAddress:"",basePath:`${Vt}/api/future`,mock:Jh}),og=async()=>await Qh({}),ba=async(e,t="/api/kos/future")=>(Bs.info(`sending delete request for Future: ${e}`),await tg({id:e,urlOverride:`${Vt}${t}/${e}`})),va=async(e,t="/api/kos/future")=>(Bs.info("sending add request for Future"),await eg({model:e,urlOverride:`${Vt}${t}`})),rg=async(e,t,s="/api/kos/future")=>(Bs.info(`sending modify request for Future: ${e}`),Xh({model:t,id:e,urlOverride:`${Vt}${s}/${e}`})),wa=async(e,t="/api/kos/future")=>(Bs.info(`sending cancel request for Future: ${e}`),sg({urlOverride:`${Vt}${t}/${e}/cancel`,ordered:!0,model:{}})),cr=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}),dr=(e,t)=>{f.debug(`future dto ${e.id} end state ${e.endState}`),f.debug(`future model ${t.id} end state ${t.endState}`),t.endState?f.debug(`future model ${t.id} is already complete`):(f.debug(`updating future model ${t.id}`),v.runInAction(()=>{const s=cr(e);Y(()=>{Object.keys(s).forEach(o=>{o==="id"?(t.futureId=s.id,s.tracker||(t.id=s.id)):o==="tracker"?t.id=s.tracker:t[o]=s[o]})})}))},Ma=e=>t=>s=>e.build(String(t),s),lr=e=>t=>qi(cr,Ma(e)(t.tracker||t.id))(t);var ng=Object.defineProperty,ig=Object.getOwnPropertyDescriptor,_a=(e,t,s,o)=>{for(var r=o>1?void 0:o?ig(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&ng(t,s,r),r};const co=f.getLogger(st.type);let ms=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=wa,Mo(()=>this.status===Ge.Success||this.status===Ge.Fail,()=>{co.info(`Future ${this.id} has completed with status ${this.status}`),Oe(this)})}async load(){co.debug(`loading Future ${this.id}`)}unload(){co.info(`unloading Future ${this.id}`)}async cancelFuture(){const e=this.namespace==="studio"?"/api/future":`/api/${this.namespace}/future`;await Mo(()=>this.futureId!==tr),await this._cancelFuture(this.futureId,e)}get status(){return this.endState?this.endState:this.progress>-1?"IN_PROGRESS":"NOT_ACTIVE"}get timeRemaining(){var c,d;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[l,u]of Object.entries(t))if(Math.abs(e)>=u){s=l,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} ${((d=n[2])==null?void 0:d.value)??""}`:"0 seconds"}handleFutureUpdated(e){this.logger.debug(`Future ${this.id} updated. future: ${e.id} endState: ${e.endState} progress: ${e.progress} remainingTimeMs: ${e.remainingTimeMs}`),dr(e,this)}};_a([R({topic:`kos.future/${hs}`})],ms.prototype,"handleFutureUpdated",1);ms=_a([O(st.type)],ms);const Ea=ms,Ia=Zo();var ag=Object.defineProperty,cg=Object.getOwnPropertyDescriptor,Ta=(e,t,s,o)=>{for(var r=o>1?void 0:o?cg(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&&ag(t,s,r),r};const $a="browser-router-model",dg="kos.http.request",lg="kos.http.response";let ys=class{constructor(e,t,s){a(this,"_id");a(this,"logger");a(this,"router");this._id=e,this.logger=s.logger,this.router=new Xi}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 d=200;const l={send:u=>{this.logger.debug(`sending response to ${o}`),this.logger.debug(u),Ai({msg:u,options:{responseId:i,destinationAddress:s,type:lg,sourceAddress:o,status:d}})},status:function(u){return d=u,this}};if(c.path==="/openapi.json"){l.send(this.router.generateOpenApiSpec());return}await this.router.handle(c,l)}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}`)}};Ta([R({topic:dg})],ys.prototype,"handleRequest",1);ys=Ta([O($a)],ys);const Ks=new pe({class:ys,type:$a}),Oa="future-container-model",be=et(Oa),Da=e=>lr(st)(e),ug=e=>{const t=Da(e);return be.build(be.type,{}).addFutureModel(t),t},hg=e=>be.build(be.type,{}).getFuture(String(e)),De={buildFutureModel:Da,initiateFuture:ug,getFuture:hg};var gg=Object.defineProperty,fg=Object.getOwnPropertyDescriptor,ur=(e,t,s,o)=>{for(var r=o>1?void 0:o?fg(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 es=f.getLogger(be.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=ba,addFuture:r=va}=t;this.logger=s.logger,this._deleteFuture=o,this._addFuture=r,this.id=e,this._futures=new le,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){es.error("error deleting a Future"),es.error(t)}}async createFuture(e){try{const t=await this._addFuture(e),s=t==null?void 0:t.data;if(s){const o=lr(st)(s);return this.addFutureModel(o),o}}catch(t){throw es.error("error creating a Future"),es.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}`),N(o,t.body,t.headers)}};ur([ie],Lt.prototype,"_futures",2);ur([R({topic:"kos.future"})],Lt.prototype,"handleFutureUpdated",1);Lt=ur([O(be.type)],Lt);const Sa=Lt,{URL:Yt}=q(),{getOne:pg,postModel:mg,deleteModel:Aa}=V.build({basePath:`${Yt}/api/keyVal`}),_o=f.createLogger({name:"key-value-service",group:"Services"}),Ca=async(e,t)=>{await Aa({urlOverride:`${Yt}/api/keyVal/${e}/${t}`,id:t})},Ra=async(e,t,s)=>{const o=await mg({urlOverride:`${Yt}/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},La=async(e="studio")=>{_o.debug("sending GET for studio-state");const t=await pg({urlOverride:`${Yt}/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},yg=async e=>{await Aa({urlOverride:`${Yt}/api/keyVal/${e}}`,id:""})},bg=Object.freeze(Object.defineProperty({__proto__:null,deleteKeyValue:Ca,deleteKeyValueNamespace:yg,getKeyValue:La,updateKeyValue:Ra},Symbol.toStringTag,{value:"Module"}));var vg=Object.defineProperty,wg=Object.getOwnPropertyDescriptor,hr=(e,t,s,o)=>{for(var r=o>1?void 0:o?wg(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&&vg(t,s,r),r};const Pa="key-value-model";let Pt=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=ye(),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 Ra(this.namespace,e,t),this.data[e]=t):(await Ca(this.namespace,e),this.data[e]=void 0)}async load(){this.logger.debug(`loading studio-state ${this.id}`);const e=await La(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)}};hr([R({topic:"/keyVal/set"})],Pt.prototype,"handleStateUpdate",1);hr([R({topic:"/keyVal/remove"})],Pt.prototype,"handleStateDelete",1);Pt=hr([O(Pa)],Pt);const gr=new ae({class:Pt,type:Pa}),{URL:zt}=q(),{postModel:fr,getOne:Mg}=V.build({basePath:`${zt}/api/kos-time`});f.createLogger({name:"kos-time-service",group:"Services"});const ka=async e=>{const t=await fr({model:e,urlOverride:`${zt}/api/kos/time/time`});if((t==null?void 0:t.status)!==200)throw Error("Failed to set time");return t.data},xa=async e=>{const t=await fr({model:e,urlOverride:`${zt}/api/kos/time/date`});if((t==null?void 0:t.status)!==200)throw Error("Failed to set time");return t.data},Fa=async e=>{const t=await fr({model:{},urlOverride:`${zt}/api/kos/time/timezone?tz=${e}`});if((t==null?void 0:t.status)!==200)throw Error("Failed to set timezone");return t.data},Na=async()=>{const e=await Mg({urlOverride:`${zt}/api/kos/time/timezone`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set timezone");return e.data.timeZone},_g=Object.freeze(Object.defineProperty({__proto__:null,getTimezone:Na,setDate:xa,setTime:ka,setTimezone:Fa},Symbol.toStringTag,{value:"Module"}));var Eg=Object.defineProperty,Ig=Object.getOwnPropertyDescriptor,Gs=(e,t,s,o)=>{for(var r=o>1?void 0:o?Ig(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Eg(t,s,r),r};const dt="kos-time-model",Tg="/kos/time/time",$g="/kos/time/day",Og="/kos/time/timezone";let He=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 ka(e)}async updateSystemDate(e){await xa(e)}async updateSystemTimezone(e){await Fa(e)}handleTimeChange(){N(Ot.TIME_CHANGE,{})}handleDayChange(){N(Ot.DAY_CHANGE,{})}async handleTimeZoneChange(){await this.retrieveTimezone(),N(Ot.TIMEZONE_CHANGE,{})}async init(){this.logger.debug(`initializing kos-time ${this.id}`)}async retrieveTimezone(){const e=await Na();this.setTimezone(e)}setTimezone(e){this.timezone=e}async load(){this.logger.debug(`loading kos-time ${this.id}`),this.retrieveTimezone()}};Gs([R({topic:Tg,websocket:!0})],He.prototype,"handleTimeChange",1);Gs([R({topic:$g,websocket:!0})],He.prototype,"handleDayChange",1);Gs([R({topic:Og,websocket:!0})],He.prototype,"handleTimeZoneChange",1);He=Gs([O(dt)],He);const bs={registration:{[dt]:{class:He,singleton:!0}},type:dt,predicate:te(dt),factory:H.Singleton.create(dt)};var Dg=Object.defineProperty,Sg=Object.getOwnPropertyDescriptor,Ua=(e,t,s,o)=>{for(var r=o>1?void 0:o?Sg(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Dg(t,s,r),r};const ja="log-block-container-model";let vs=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(this,"_models");this.id=e,this.logger=s.logger,this._models=new le({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}`)}};Ua([ie],vs.prototype,"_models",2);vs=Ua([O(ja)],vs);const Re=Zo(),Ag=f.createLogger({name:"log-stream-container-service",group:"Services"}),Ba=()=>{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 f.error(`getKosConnectionId: ${s}`),s},ot=Ba(),Cg="/api/kos/logs/node/{nodeId}/streams",Ka=async()=>(Ag.debug("sending GET for log-stream-container"),await Re.get(Cg,{path:{nodeId:"primary"}},{destinationAddress:ot})),Ga=async(e,t="primary")=>{await Re.post("/api/kos/logs/node/{nodeId}/{stream}/subscribe",{path:{nodeId:t,stream:e}},void 0,{destinationAddress:ot})},Ha=async e=>{await Re.post("/api/kos/logs/node/{nodeId}/{stream}/unsubscribe",{path:{nodeId:"primary",stream:e}},void 0,{destinationAddress:ot})},Rg=async()=>{await Re.post("/api/kos/logs/overrides",{},{level:"WARN",name:"com.example",nodeType:"java",type:"package"},{destinationAddress:ot})},Va=async e=>await Re.get("/api/kos/logs/node/{nodeId}/{stream}/blocks",{path:{nodeId:"primary",stream:e}},{destinationAddress:ot}),Ya=async(e,t)=>await Re.get("/api/kos/logs/node/{nodeId}/{stream}/blocks/{blockId}",{path:{nodeId:"primary",stream:e,blockId:t}},{destinationAddress:ot}),Lg=Object.freeze(Object.defineProperty({__proto__:null,createOverride:Rg,getKosConnectionId:Ba,getLogStreamBlock:Ya,getLogStreamBlocks:Va,getLogStreams:Ka,subscribeToLogStream:Ga,unsubscribeFromLogStream:Ha},Symbol.toStringTag,{value:"Module"}));var Pg=Object.defineProperty,kg=Object.getOwnPropertyDescriptor,xg=(e,t,s,o)=>{for(var r=o>1?void 0:o?kg(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Pg(t,s,r),r};const za="log-block-model";let Eo=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 Ya(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}`)}};Eo=xg([O(za)],Eo);const kt=new ae({class:Eo,type:za}),Hs=new ae({class:vs,type:ja});Hs.addRelatedModel(kt);var Fg=Object.defineProperty,Ng=Object.getOwnPropertyDescriptor,qa=(e,t,s,o)=>{for(var r=o>1?void 0:o?Ng(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Fg(t,s,r),r};const Wa="log-stream-model";let ws=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=Hs.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 Ga(this.name)}async unsubscribe(){await Ha(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 Va(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=ta(()=>{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()}}};qa([ie],ws.prototype,"_blocks",2);ws=qa([O(Wa)],ws);const Dt=new ae({class:ws,type:Wa});var Ug=Object.defineProperty,jg=Object.getOwnPropertyDescriptor,Le=(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 Za="log-stream-container-model",Bg="/kos/logs/subscription/addBlock/*",Kg="/kos/logs/subscription/updateBlock/*",Gg="/kos/logs/subscription/removeBlock/*",Hg="/kos/logs/subscription/lines/*",Ja="/kos/logs/streams/add/*";let he=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 le({parentId:e}),this.selectedStream=void 0}getModel(e){return this._models.getModel(e)}get models(){return this._models}get data(){return this._models.data}updateModel(e){}addModel(e){this._models.addModel(e)}removeModel(e){this._models.removeModel(e)}updateSelectedStream(e){this.selectedStream=e}handleStreamAdded(e){this.logger.debug(`Received topic: ${Ja}`);const t=e.stream,s=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 Ka();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)})}};Le([ie],he.prototype,"_models",2);Le([R({topic:[Ja],websocket:!0})],he.prototype,"handleStreamAdded",1);Le([R({topic:[Bg],websocket:!0})],he.prototype,"handleAddBlock",1);Le([R({topic:[Gg],websocket:!0})],he.prototype,"handleRemoveBlock",1);Le([R({topic:[Kg],websocket:!0})],he.prototype,"handleUpdateBlock",1);Le([R({topic:[Hg],websocket:!0})],he.prototype,"handleLogLine",1);he=Le([O(Za)],he);const qt=new pe({class:he,type:Za});qt.addRelatedModel(Dt);qt.addRelatedModel(Hs);qt.addRelatedModel(kt);const Vg=e=>e.rank!==void 0,Yg=e=>e.visibleRole!==void 0,zg=e=>e.color!==void 0,qg=e=>{const t=e.info;return Vg(t)?t.rank:0},Wg=e=>{const t=e.info;return zg(t)?t.color:"orange"},Zg=e=>{const t=e.info;return Yg(t)?t.visibleRole:"TECHNICIAN"},{URL:pr}=q(),{getAll:Jg,postModel:Qa}=V.build({basePath:`${pr}/api/kos/troubles`}),Xa=async()=>await Jg({}),ec=async(e,t)=>{try{const s=await Qa({model:{},urlOverride:`${pr}/api/kos/troubles/resolve/${e}`,tracker:t});return s!=null&&s.data&&De.initiateFuture(s.data),s.data}catch{const o={id:t||"",endState:Ge.Fail,tracker:t,reason:"Failed to resolve trouble"};return De.initiateFuture(o),o}},Qg=async(e,t)=>{try{const s=await Qa({model:e,urlOverride:`${pr}/api/kos/troubles/resolve/`,tracker:t});return s!=null&&s.data&&De.initiateFuture(s.data),s.data}catch{const o={id:t||"",endState:Ge.Fail,tracker:t,reason:"Failed to resolve troubles"};return De.initiateFuture(o),o}},Xg=Object.freeze(Object.defineProperty({__proto__:null,bulkResolveTroubles:Qg,getTroubles:Xa,resolveTrouble:ec},Symbol.toStringTag,{value:"Module"})),Ms="troubleDataMapper",ts=new Map;Yo(Ms,{register:(e,t)=>{var s;ts.has(e)||ts.set(e,[]),(s=ts.get(e))==null||s.push(t)},execute:async(e,t)=>{const s=ts.get(e);if(!s)return{...t.data};const o=s.map(i=>i(t));return(await Promise.allSettled(o)).reduce((i,c)=>(c.status==="fulfilled"?i={...i,...c.value}:f.info(`Trouble mapper ${e} failed: ${c.reason}`),i),{...t.data})}});const Wt="troubleMapper",ss=new Map;Yo(Wt,{register:(e,t)=>{var s;ss.has(e)||ss.set(e,[]),(s=ss.get(e))==null||s.push(t)},execute:async(e,t)=>{const s=ss.get(e);if(!s)return[];const o=s.map(i=>i(t)),n=(await Promise.allSettled(o)).map(i=>i.status==="fulfilled"?i.value:(f.info(`Trouble mapper ${e} failed: ${i.reason}`),[])).flat();return Array.from(new Set(n))}});C[Wt].register("nozzle",async e=>[e.data.nozzlePath]);C[Wt].register("path",async e=>[e.data.path]);const ef=async e=>{const t=new Set,s=e.ifaces,o=s==null?void 0:s.map(n=>C[Wt].execute(n,e));return(await Promise.allSettled(o)).forEach(n=>{n.status==="fulfilled"&&n.value.forEach(i=>t.add(i))}),Array.from(t)},tc=async e=>{const t=e.ifaces,s=t==null?void 0:t.map(i=>C[Ms].execute(i,e)),o=C[Ms].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 tf{constructor(){a(this,"type","ResolvableTrouble");a(this,"title","Resolvable Trouble");a(this,"subtitle","Trouble")}}class sf{constructor(){a(this,"type","BlockPumpTrouble");a(this,"title","Block Pump Trouble");a(this,"subtitle","Trouble")}}class xe{static getHandler(t){switch(t){case"ResolvableTrouble":return new tf;case"BlockPumpTrouble":return new sf;default:return}}}var of=Object.defineProperty,rf=Object.getOwnPropertyDescriptor,sc=(e,t,s,o)=>{for(var r=o>1?void 0:o?rf(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&of(t,s,r),r};const lt="trouble-model";function os(e){return typeof e.shouldDefer=="boolean"}let _s=class{constructor(e,{resolvable:t,tags:s,info:o,id:r,clientData:n,rank:i,ifaces:c,type:d,group:l,createTime:u,role:h,color:p,...w},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=d,this._troubleId=r,this._resolvable=!!t,this.ifaces=c,this.rank=i,this.role=h,this.color=p,this.tags=s,this.info=o,this.group=l,this.createTime=u,this.clientData=n,this.data={},Object.assign(this.data,w),this.futureHandler=new ar(this)}getTitleWithContext(e){var s,o;const t=e?(o=(s=xe.getHandler(this.type))==null?void 0:s.context)==null?void 0:o[e]:xe.getHandler(this.type);return(t==null?void 0:t.title)||"Trouble"}getSubtitleWithContext(e){var s,o;const t=e?(o=(s=xe.getHandler(this.type))==null?void 0:s.context)==null?void 0:o[e]:xe.getHandler(this.type);return(t==null?void 0:t.subtitle)||"Trouble"}get rawId(){return this._troubleId}get title(){var e;return((e=xe.getHandler(this.type))==null?void 0:e.title)||"Trouble"}get subtitle(){var e;return((e=xe.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 tc(this)}get deferredCompanion(){const e=wo(this.id,t=>os(t));if(e&&os(e.modelData))return e.modelData}get deferred(){return this.deferredCompanion?this.deferredCompanion.deferred:!1}get shouldDefer(){const e=wo(this.id,t=>os(t));return e&&os(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 ec(this._troubleId,e)}};sc([Ar()],_s.prototype,"resolve",1);_s=sc([O(lt)],_s);const xt={registration:{[lt]:{class:_s,singleton:!1}},type:lt,predicate:te(lt),factory:H.Factory.create(lt)};var nf=Object.defineProperty,af=Object.getOwnPropertyDescriptor,Vs=(e,t,s,o)=>{for(var r=o>1?void 0:o?af(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&nf(t,s,r),r};const nn=f.createLogger({name:"trouble-container-model"});function an(e){return C.propertyMapper.hasMapper(re.TroubleRank)?C.propertyMapper.executeMapper(re.TroubleRank,e):qg(e)}function cn(e){return(C.propertyMapper.hasMapper(re.TroubleColor)?C.propertyMapper.executeMapper(re.TroubleColor,e):Wg(e)).toLowerCase()}function dn(e){return(C.propertyMapper.hasMapper(re.TroubleRole)?C.propertyMapper.executeMapper(re.TroubleRole,e):Zg(e)).toLowerCase()}const cf="trouble-container-model";class X{}a(X,"INDEX_TROUBLES_BY_IFACE","byIface"),a(X,"INDEX_TROUBLES_BY_TYPE","byType"),a(X,"INDEX_TROUBLES_BY_GROUP","byGroup"),a(X,"INDEX_TROUBLES_BY_DEFERRED","byDeferred"),a(X,"SORT_KEY_RANK","rank"),a(X,"TROUBLES_DEFERRED","true");let Ve=class{constructor(e){a(this,"id");a(this,"troubles");this.id=e,this.troubles=new le({indexMap:{[X.INDEX_TROUBLES_BY_IFACE]:ef,[X.INDEX_TROUBLES_BY_TYPE]:"type",[X.INDEX_TROUBLES_BY_GROUP]:"group",[X.INDEX_TROUBLES_BY_DEFERRED]:"deferred"},sortKey:X.SORT_KEY_RANK,parentId:e})}async load(){nn.debug("loading trouble container");const e=await Xa();try{e==null||e.data.forEach(t=>{const s={...t,rank:an(t),color:cn(t),role:dn(t),id:String(t.id)},o=xt.factory(`trouble-${t.id}`)(s);this.troubles.addModel(o)})}catch(t){throw nn.error(t),t}}handleTroubleRemoved(e){const t=`trouble-${e}`,s=this.troubles.getModel(t);this.troubles.removeModel(t),s&&Oe(s)}handleTroubleAdded(e){const t={...e,rank:an(e),color:cn(e),role:dn(e),id:String(e.id)};if(t.role==="NONE")return;const s=xt.factory(`trouble-${e.id}`)(t);this.troubles.addModel(s)}};Vs([ie],Ve.prototype,"troubles",2);Vs([R({topic:"/kos/trouble/remove",websocket:!0,lifecycle:x.INIT})],Ve.prototype,"handleTroubleRemoved",1);Vs([R({topic:"/kos/trouble/add",websocket:!0})],Ve.prototype,"handleTroubleAdded",1);Ve=Vs([O(cf)],Ve);const rs="trouble-container-model",Ye={registration:{[rs]:{class:Ve,singleton:!0}},type:rs,predicate:te(rs),factory:H.Singleton.create(rs)},{URL:oc}=q(),{getAll:df}=V.build({basePath:`${oc}/api/kos/ota`}),ln=f.createLogger({name:"ota-service",group:"Services"}),lf=async()=>{ln.debug("sending GET request to /api/kos/ota/artifacts");const e=await df({urlOverride:`${oc}/api/kos/ota/artifacts`});return ln.debug("getArtifacts - response:",e),e==null?void 0:e.data};var uf=Object.defineProperty,hf=Object.getOwnPropertyDescriptor,Ys=(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 rc="ota-model",gf=e=>{let t=null;for(const s in e){const o=e[s],r=o.lastUpdateTime;(!t||t.lastUpdateTime<r)&&(t=o)}return t},lo=e=>{const t=e.artifactInfo,s=gf(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 ze=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(this,"data",new Ji);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 lf();e&&e.forEach(t=>{const s=lo(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=lo(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=lo(t);s&&this.data.updateModel(s)})}catch(t){this.logger.error(`handleChangedArtifacts ${this.id} - error:`,t)}}};Ys([Ae({modelType:Ye.type})],ze.prototype,"troubleContainer",2);Ys([R({topic:"/kos/ota/artifacts/all",websocket:!0})],ze.prototype,"handleAllArtifacts",1);Ys([R({topic:"/kos/ota/artifacts/changed",websocket:!0})],ze.prototype,"handleChangedArtifacts",1);ze=Ys([O(rc)],ze);const Es=new pe({class:ze,type:rc}),un=f.createLogger({name:"software-info-service",group:"Services"}),nc=async()=>{un.debug("sending GET for software-info");const[e,t]=await Ia.get("/api/kos/manifest/info");if(!t)throw un.error("Failed to fetch software-info",e),new ce("Failed to fetch software-info");return t},ff=Object.freeze(Object.defineProperty({__proto__:null,getSoftwareInfos:nc},Symbol.toStringTag,{value:"Module"}));var pf=Object.defineProperty,mf=Object.getOwnPropertyDescriptor,yf=(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&&pf(t,s,r),r};const ut="software-info-model";let Io=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 nc(),t=(e==null?void 0:e.nodes)||{};Y(()=>{const o=Object.keys(t).map(r=>t[r][0]).map(r=>({nodeName:r.node,group:this.groupBy(r.artifacts,"group")}));this.nodes=o})}catch(e){e instanceof ce&&this.logger.error("Failed to fetch software-info",e)}}};Io=yf([O(ut)],Io);const Is={registration:{[ut]:{class:Io,singleton:!1}},type:ut,predicate:te(ut),factory:H.Factory.create(ut)},{URL:ic}=q(),{getOne:bf}=V.build({basePath:`${ic}/api/kos/state`}),vf=f.createLogger({name:"state-bean-service",group:"Services"}),ac=async({path:e})=>(vf.debug("sending GET for state-bean"),await bf({urlOverride:`${ic}/api/kos/state/${e}`})),wf=Object.freeze(Object.defineProperty({__proto__:null,getStateBeanData:ac},Symbol.toStringTag,{value:"Module"}));var Mf=Object.defineProperty,_f=Object.getOwnPropertyDescriptor,cc=(e,t,s,o)=>{for(var r=o>1?void 0:o?_f(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Mf(t,s,r),r};const ht="state-bean-model",Ef=Se("path");let Ts=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=er.map(new Map),po(t,this)}updateModel(e){po(e,this)}handleConfigBeanUpdated(e){Object.entries(e).forEach(([t,s])=>{let o=s;typeof o=="string"&&or(o)&&(o=o.toLowerCase()=="true"),typeof o=="string"&&Us(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 ac({path:this.path});e!=null&&e.data&&this.updateProps(e.data)}};cc([R({topic:`/kos/state/${Ef}`,websocket:!0})],Ts.prototype,"handleConfigBeanUpdated",1);Ts=cc([O(ht)],Ts);const Ft={registration:{[ht]:{class:Ts,singleton:!1}},type:ht,predicate:te(ht),factory:H.Factory.create(ht)};var If=Object.defineProperty,Tf=Object.getOwnPropertyDescriptor,dc=(e,t,s,o)=>{for(var r=o>1?void 0:o?Tf(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&&If(t,s,r),r};const gt="state-prop-model",hn=Se("path");let $s=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())??""}};dc([Ae({modelType:Ft.type,id:`state-bean-${hn}`,options:{path:hn}})],$s.prototype,"stateBean",2);$s=dc([O(gt)],$s);const mr={registration:{[gt]:{class:$s,singleton:!1}},type:gt,predicate:te(gt),factory:H.Factory.create(gt)},{URL:$f}=q(),{getAll:Of}=V.build({basePath:`${$f}/api/state-prop`}),Df=f.createLogger({name:"state-prop-service",group:"Services"}),Sf=async()=>(Df.debug("sending GET for state-prop"),await Of({})),Af=Object.freeze(Object.defineProperty({__proto__:null,getStateProps:Sf},Symbol.toStringTag,{value:"Module"})),{URL:yr}=q(),{getOne:lc}=V.build({basePath:`${yr}/api/translation`}),St=f.createLogger({name:"translation-service",group:"Services"}),Cf=()=>{const e=window.location.origin,t=ee();return(t==null?void 0:t.host)||e},uc=async(e,t)=>{St.debug("sending GET for translation");const s=t??Cf();try{const o=await fetch(`${s}${e}`);return o.status!==200?(St.warn(`Failed to fetch translations at ${e}: ${o.status}`),{}):await o.json()}catch(o){throw St.error("Error fetching translations",o),o}},Rf=async()=>{St.debug("getting localization descriptor");const e=await lc({urlOverride:`${yr}/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},hc=e=>async()=>{St.debug("getting kos localization descriptor");const t=await lc({urlOverride:`${yr}/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]},gc="langResolver";var Lf=Object.defineProperty,Pf=Object.getOwnPropertyDescriptor,kf=(e,t,s,o)=>{for(var r=o>1?void 0:o?Pf(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Lf(t,s,r),r};const ft="translation-model";function xf(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 fc(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=fc(e[o],r);return{...s,...n}}else return{...s,[r]:e[o]}},{})}function pc(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]=pc(e[o],t[o]):s[o]=t[o]);return s}const To=(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)?To(o,t):o},ns=(e,t,s)=>{const o=/{{(.*?)}}/g,n=To(e,t).replace(o,(c,d)=>Object.prototype.hasOwnProperty.call(s||{},d.trim())?s==null?void 0:s[d.trim()]:c);return To(n,t)},gn=(e,t)=>{if(t.includes(":")){const[s,o]=t.split(":");return{namespace:s,key:o}}else return{namespace:e,key:t}};let $o=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(gc),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=k.getContext(this.id);return this.bundleResolver(this.namespace,o,r)}try{const r=this.resolver(this.namespace,o);return uc(r,this.rootUrl)}catch{return Promise.resolve({})}}),s=await Promise.allSettled(t);Y(()=>{const o=s.reduce((r,n,i)=>(n.status==="fulfilled"?(this.logger.debug(`resolved ${e[i]}`,n.value),n.value&&(r=pc(r,n.value))):this.logger.error(`failed to load translation ${this.id} for ${e[i]}`),r),{});this.data=fc(o)})}async init(){this.logger.debug(`initializing translation ${this.id}`)}exists(e){const{namespace:t,key:s}=gn(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}=xf(t),{namespace:n,key:i}=gn(this.namespace,e),c=`${i}_${o}`;if(n!==this.namespace){const d=this.context.getModel(n);return d?d.resolveKey(i,t):i}if(o&&this.data[c]){const d=this.data[c];return Array.isArray(d)?d.map(l=>ns(l,this.data,r)):ns(this.data[c],this.data,r)}if(this.data[i]){const d=this.data[c];return Array.isArray(d)?d.map(l=>ns(l,this.data,r)):ns(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=v.reaction(()=>this.currentLocale,(e,t)=>{this.logger.info(`translation langs for namespace ${this.id} changed from ${t} to ${e}`),this.loadTranslations()})}};$o=kf([Ns(),O(ft)],$o);const Os={registration:{[ft]:{class:$o,singleton:!1}},type:ft,predicate:te(ft),factory:H.Factory.create(ft)};var Ff=Object.defineProperty,Nf=Object.getOwnPropertyDescriptor,mc=(e,t,s,o)=>{for(var r=o>1?void 0:o?Nf(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Ff(t,s,r),r};const pt="translation-container-model",Uf=(e,t="/")=>e.join(t).replace(new RegExp(t+"{1,}","g"),t);function jf(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 Uf([o,r])}let Ds=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||jf.bind(this),s.kosContext.set(gc,this.resolver),this.logger=s.logger,this._models=new le({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 xi(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=Os.factory(`translation-${e}`)({kosParentId:this.id,namespace:e,rootUrl:this.rootUrl,currentLocale:this.lang,defaultLocale:r,descriptor:this.descriptor.namespaces[e].locales,resolver:this.resolver});return this.addModel(n),this.namespaces.includes(e)||Y(()=>{this.namespaces.push(e)}),n}else{this.logger.warn(`namespace ${e} not found in descriptor`);const o=Os.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}`)}};mc([ie],Ds.prototype,"_models",2);Ds=mc([O(pt)],Ds);const ge={registration:{[pt]:{class:Ds,singleton:!0}},type:pt,predicate:te(pt),factory:H.Singleton.create(pt)},Bf={set(e,t){const s=k.getContext(ge.type);s&&s.set(e,t)},get(e){const t=k.getContext(ge.type);return t==null?void 0:t.get(e)}},yc={async init(e){const t=ge.factory(e);return await J(t),{translations:t}}},Kf=(e,t)=>{const s=t.type;return e[s]||(e[s]=[]),e[s].push(t),e},bc="kos-ws-event",br=et(bc);var Gf=Object.defineProperty,Hf=Object.getOwnPropertyDescriptor,vr=(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&&Gf(t,s,r),r};const Vf=({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=v.observable.map(new Map),this._topicMap=new Map}get websocketEvents(){return Array.from(this.events.values())}handleSendEvent(t,s){this.processEvent(s,!0)}handleReceiveEvent(t,s){this.processEvent(s)}processEvent(t,s=!1){f.debug("kos event received");const{body:o,headers:r}=t.body,n=r["request-id"]||r["response-id"],i=r["request-id"]||r["response-id"]||r.topic||r.type;if(i){let c=i;if(n)c=`${c}-${s?"send":"receive"}`;else{const l=this._topicMap.get(i)||0;c=`${c}-${l+1}`,this._topicMap.set(i,l+1)}const d={msgId:c,content:o,headers:r,timestamp:Date.now(),raw:Vf({headers:r,body:o}),direction:s?"send":"receive",mocked:!!r.mocked};this.events.set(c,d),f.debug(`logged ${this.events.size} events`)}}};vr([R({topic:[Gt.SEND]})],exports.WsEventModel.prototype,"handleSendEvent",1);vr([R({topic:[Gt.RECEIVED]})],exports.WsEventModel.prototype,"handleReceiveEvent",1);exports.WsEventModel=vr([O(br.type)],exports.WsEventModel);const fn=ee(),Yf=fn.debug==="true"||fn.debug===!0,zf="/api/system/canvas",vc=async(e,t)=>{const s=t||zf,o=`${exports.BASE_URL}${s}`;await exports.kosFetch(o,{method:"POST",headers:{hide:Yf?"true":"false"},body:e})},qf=Object.freeze(Object.defineProperty({__proto__:null,sendCanvasData:vc},Symbol.toStringTag,{value:"Module"})),Wf=(e,t,s)=>e>>5<<5|t>>5<<2|s>>6;function Zf(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(Wf(e[r],e[r+1],e[r+2]));return String.fromCharCode(...o)}}var Jf=Object.defineProperty,Qf=Object.getOwnPropertyDescriptor,wc=(e,t,s,o)=>{for(var r=o>1?void 0:o?Qf(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Jf(t,s,r),r};const Mc="canvas-renderer-model";function uo(e){return typeof e.onDone=="function"}let Ss=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){vc(e,t)}checkOneShot(){var t,s;if(uo(this._renderer)&&((s=(t=this._renderer).isOneShot)==null?void 0:s.call(t))===!0&&this._renderer.isOneShotDone){requestAnimationFrame(()=>{this.stopStreaming()});return}}handleFrame(e){var s;const t=Zf(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)}startStreaming(){var e,t,s,o,r,n;{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 i=uo(this._renderer);this._renderer.renderFrame(this.width,this.height);const c=(o=(s=this._renderer).readPixels)==null?void 0:o.call(s,this.width,this.height);if(c&&this._onFrame&&this.handleFrame(c),uo(this._renderer)&&((n=(r=this._renderer).isOneShot)==null?void 0:n.call(r))===!0&&this._renderer.isOneShotDone){requestAnimationFrame(()=>{this.stopStreaming()});return}const l=()=>{var u;(u=this._renderer)==null||u.renderFrame(this.width,this.height),this.renderLoopId=requestAnimationFrame(l)};this.renderLoopId=requestAnimationFrame(l),this.sendIntervalId=setInterval(()=>{var h,p;const u=(p=(h=this._renderer)==null?void 0:h.readPixels)==null?void 0:p.call(h,this.width,this.height);u&&this._onFrame&&(this.handleFrame(u),this.checkOneShot())},1e3/this.fps),!i&&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"})})}};wc([Ae({modelType:Ks.type})],Ss.prototype,"router",2);Ss=wc([O(Mc)],Ss);const wr=new ae({class:Ss,type:Mc});class Xf{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 _c{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 Ec(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 ep=Ec(_c);class tp extends ep{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())}}const sp=Ec(_c);class pn extends sp{constructor(s=0,o=0,r=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())}}const mn=({mode:e,data:t})=>{switch(e){case"color":{const{r:s,g:o,b:r}=t;return t?new pn(s,o,r):new pn(0,0,0)}case"image":return t?new tp(t.src):null;case"video":return t?new Xf(t.src):null;default:throw new Error(`Unknown mode: ${e}`)}};var op=Object.defineProperty,rp=Object.getOwnPropertyDescriptor,Mr=(e,t,s,o)=>{for(var r=o>1?void 0:o?rp(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&&op(t,s,r),r};const Ic="canvas-dispatcher-model";function np(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 Nt=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 le}addNamedEndpoint(e,t){this._endpointRenderers.getModel(e)&&this.logger.warn(`Endpoint "${e}" already exists. Overwriting.`);const s=wr.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(qe.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,d;const n=o.body,i=Array.isArray(n)?n:[n];if(i.some(l=>!l.id||!l.type||!l.data)){(c=r.status)==null||c.call(r,400).send({error:"Invalid pattern data"});return}for(const l of i)this._patterns.has(l.id)&&this.logger.warn(`Pattern "${l.id}" already exists. Overwriting.`),this.addPattern(l.id,l);(d=r.status)==null||d.call(r,200).send({status:"OK"})}),this.router.use("POST","/api/ui/canvas/pattern/:endpoint/:pattern",async(o,r)=>{var u,h,p;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 d=this._patterns.get(n),l=d.type;this.data=d.data,c.renderer=mn({mode:l,data:this.data}),c.startStreaming(),(p=r.status)==null||p.call(r,200).send({status:"OK"})}),this.router.use("POST","/api/ui/canvas/color/:endpoint/:color",async(o,r)=>{var p,w,b;const n=o.params.color,i=np(n);if(!i){(p=r.status)==null||p.call(r,400).send({error:"Invalid color format"});return}const c=o.params.endpoint,d=this._endpointRenderers.getModel(c);if(!d){(w=r.status)==null||w.call(r,404).send({error:`Endpoint "${c}" not found`});return}const{r:l,b:u,g:h}=i;d.renderer=mn({mode:"color",data:{r:l,g:h,b:u}}),d.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"})})}};Mr([ie],Nt.prototype,"_endpointRenderers",2);Mr([Ae({modelType:Ks.type})],Nt.prototype,"router",2);Nt=Mr([O(Ic)],Nt);const qe=new pe({class:Nt,type:Ic}),{URL:_r}=q(),{getOne:Tc}=V.build({basePath:`${_r}/api/device`}),As=f.createLogger({name:"device-service",group:"Services"}),$c=async()=>{As.debug("sending GET for device serial number");try{const e=await Tc({urlOverride:`${_r}/api/kos/device/serialNumber`});return[void 0,e==null?void 0:e.data.serialNumber]}catch(e){if(e instanceof ce)return As.error(`Error fetching device serial number: ${e.payload.error}`),[e.payload.error,void 0]}return["unknownError",void 0]},Oc=async()=>{As.debug("sending GET for device details");try{const e=await Tc({urlOverride:`${_r}/api/kos/device`});return e?[void 0,e.data]:["unknownError",void 0]}catch(e){if(e instanceof ce)return As.error(`Error fetching device serial number: ${e.payload.error}`),[e.payload.error,void 0]}return["unknownError",void 0]},ip=Object.freeze(Object.defineProperty({__proto__:null,getDeviceDetails:Oc,getSerialNumber:$c},Symbol.toStringTag,{value:"Module"}));var ap=Object.defineProperty,cp=Object.getOwnPropertyDescriptor,Dc=(e,t,s,o)=>{for(var r=o>1?void 0:o?cp(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&&ap(t,s,r),r};const Sc="device-model",dp="/kos/criticalData/changed",lp="/kos/criticalData/available";let Cs=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 Oc();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 $c();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()}};Dc([R({topic:[dp,lp],websocket:!0})],Cs.prototype,"handleCriticalDataChanged",1);Cs=Dc([O(Sc)],Cs);const Rs=new pe({class:Cs,type:Sc});var up=Object.defineProperty,hp=Object.getOwnPropertyDescriptor,gp=(e,t,s,o)=>{for(var r=o>1?void 0:o?hp(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&&up(t,s,r),r};const Ac="network-interface-model";let Oo=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}`)}};Oo=gp([O(Ac)],Oo);const Er=new ae({class:Oo,type:Ac}),{URL:fp}=q(),{getAll:pp}=V.build({basePath:`${fp}/api/kos/network/interfaces`}),yn=f.createLogger({name:"network-interface-service",group:"Services"}),Cc=async()=>{yn.debug("sending GET for copy-logs");try{const e=await pp({});return[void 0,e==null?void 0:e.data]}catch(e){if(e instanceof ce)return yn.error(`Error fetching log file size: ${e.payload.error}`),[e.payload.error,void 0]}return["unknownError",void 0]},mp=Object.freeze(Object.defineProperty({__proto__:null,getNetworkInterfaces:Cc},Symbol.toStringTag,{value:"Module"}));var yp=Object.defineProperty,bp=Object.getOwnPropertyDescriptor,Rc=(e,t,s,o)=>{for(var r=o>1?void 0:o?bp(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&&yp(t,s,r),r};const Lc="network-interface-container-model";let Ls=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(this,"_models");this.id=e,this.logger=s.logger,this._models=new le({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 Cc();if(e){this.logger.error(`Error loading network interfaces: ${e}`);return}t&&t.forEach(s=>{const o=Er.instance(s.name).forceUpdate.options(s).build();this.addModel(o)})}async load(){this.logger.debug(`loading network-interface-container container ${this.id}`),this.refreshInterfaces()}};Rc([ie],Ls.prototype,"_models",2);Ls=Rc([O(Lc)],Ls);const Ut=new pe({class:Ls,type:Lc});Ut.addRelatedModel(Er);const{URL:vp}=q(),{getAll:wp}=V.build({basePath:`${vp}/api/kos/storage/devices`}),bn=f.createLogger({name:"storage-device-service",group:"Services"}),Pc=async()=>{bn.debug("sending GET for storage-device");const e=await wp({});return!(e!=null&&e.data)||e.status!==200?(bn.error("Failed to retrieve storage-device data",e),[]):e.data},Mp=Object.freeze(Object.defineProperty({__proto__:null,getStorageDevices:Pc},Symbol.toStringTag,{value:"Module"}));var _p=Object.defineProperty,Ep=Object.getOwnPropertyDescriptor,Ip=(e,t,s,o)=>{for(var r=o>1?void 0:o?Ep(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&_p(t,s,r),r};const kc="storage-device-model";let Do=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}`)}};Do=Ip([Ns(),O(kc)],Do);const Ps=new ae({class:Do,type:kc});var Tp=Object.defineProperty,$p=Object.getOwnPropertyDescriptor,Ir=(e,t,s,o)=>{for(var r=o>1?void 0:o?$p(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&&Tp(t,s,r),r};const xc="storage-device-container-model",Op="/kos/storage";let jt=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(this,"_models");this.id=e,this.logger=s.logger,this._models=new le({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=Ps.instance(s.id).options(r).build();this.addModel(n)}})}async load(){this.logger.debug(`loading storage-device-container container ${this.id}`),(await Pc()).forEach(t=>{const s={...t,kosParentId:this.id},o=Ps.instance(t.id).options(s).build();this.addModel(o)})}};Ir([ie],jt.prototype,"_models",2);Ir([R({topic:Op,websocket:!0})],jt.prototype,"handleStorageAvailability",1);jt=Ir([O(xc)],jt);const We=new pe({class:jt,type:xc});We.addRelatedModel(Ps);const{URL:Tr}=q(),{getAll:Dp,postModel:Sp}=V.build({basePath:`${Tr}/api/kos/update/available`}),vn=f.createLogger({name:"usb-update-service",group:"Services"}),Fc=async()=>{vn.debug("sending GET for usb-update");const e=await Dp({urlOverride:`${Tr}/api/kos/update/available`});return!(e!=null&&e.data)||(e==null?void 0:e.status)!==200?(vn.error("Failed to retrieve usb-update data",e),[]):e.data},Nc=async(e,t,s)=>{const o=await Sp({model:{manifestId:e,deviceId:t},tracker:s,urlOverride:`${Tr}/api/kos/update/install`});if(!(o!=null&&o.data))throw new Error("No response from server");return o.data},Ap=Object.freeze(Object.defineProperty({__proto__:null,getAvailableUpdates:Fc,installUpdate:Nc},Symbol.toStringTag,{value:"Module"}));var Cp=Object.defineProperty,Rp=Object.getOwnPropertyDescriptor,Uc=(e,t,s,o)=>{for(var r=o>1?void 0:o?Rp(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&&Cp(t,s,r),r};const jc="usb-update-model";let ks=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 ar(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}`),Nc(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}`)}};Uc([Ar()],ks.prototype,"install",1);ks=Uc([O(jc)],ks);const $r=new ae({class:ks,type:jc});var Lp=Object.defineProperty,Pp=Object.getOwnPropertyDescriptor,zs=(e,t,s,o)=>{for(var r=o>1?void 0:o?Pp(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&&Lp(t,s,r),r};const Bc="usb-update-container-model";let Ze=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 le({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 Fc();Y(()=>{const t=e.map(s=>`${s.deviceId}-${s.manifestId}`);this._models.data.filter(s=>!t.includes(s.id)).forEach(s=>this.removeModel(s.id)),e.forEach(s=>{const o=`${s.deviceId}-${s.manifestId}`,r=$r.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}`)}};zs([Ae({modelType:We.type})],Ze.prototype,"storageService",2);zs([ie],Ze.prototype,"_models",2);zs([ai({dependencies:e=>[e.isUsbInserted]})],Ze.prototype,"usbInsertedEffect",1);Ze=zs([O(Bc)],Ze);const Bt=new pe({class:Ze,type:Bc});Bt.addRelatedModel($r);const kp=()=>({...{[st.type]:{class:Ea},[be.type]:{class:Sa,singleton:!0},...z.registration,...Ce.registration,...Ye.registration,...Os.registration,...ge.registration,[br.type]:{class:exports.WsEventModel,singleton:!0},...Ft.registration,...mr.registration,...bs.registration}}),Or=kp(),xp={models:Or,preloadModels:[]},Fp=!0,Kc=e=>()=>{const t=Or;return ji(So)(xt).model(Ye).model(We).model(Bt).model(Rs).model(Es).model(At).model(Is).model(gr).model(Ut).model(qe).model(wr).model(Ks,Fp).model(qt),Object.keys(t).forEach(s=>{const o=t[s];Ui(So)(s,o)}),{preload:$.model.preloadModel(e),model:$.model.register(e),companion:$.companion.register(e),legacy:$.model.registerLegacyModel(e)}},ne={};ne.core={models:Kc(ne)};ne.preload=$.model.preloadModel(ne);ne.model=$.model.register(ne);ne.companion=$.companion.register(ne);ne.legacy=$.model.registerLegacyModel(ne);const So=ne;class Np{registerTroubleRankMapper(t){return C.propertyMapper.registerPropertyMapper(re.TroubleRank,t),this}registerTroubleRoleMapper(t){return C.propertyMapper.registerPropertyMapper(re.TroubleRole,t),this}registerTroubleColorMapper(t){return C.propertyMapper.registerPropertyMapper(re.TroubleColor,t),this}registerModelLoader(t,s){C.loader.registerLoader(t,s)}registerCanvasPatternLoader(t){C.loader.registerLoader(qe.loader,t)}}const Up=async(e,t)=>{const s=gr.instance(e).options({}).build(),o=t?`${t}-`:"";return await J(s),{getState:r=>s.data[`${o}${r}`],updateState:async(r,n)=>{await s.updateState(`${o}${r}`,n)},clean:async()=>{for(const r of s.data.keys)await s.updateState(`${o}${r}`,void 0)},unsubscribe:()=>{Oe(s)}}},Gc="kos:service:region",Hc="regionId",jp=`${Gc}-${Hc}`,Vc=async e=>{const t=Ce.factory(jp)({path:Gc,attribute:Hc});await J(t),t.updateProperty(e)},Dr="/kos-timer-event",Sr="defaultTimerEnd",mt=f.createLogger({name:"timer-manager"}),Bp=e=>e.updateProperty!==void 0;class Yc{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,Bp(s)&&F(()=>{f.info(`Updating config value timer ${t} with new timeout value ${s.value}`);const n=s.value||60;this.updateTimeout(n)}),this.addTimeoutAction({name:Sr}),o&&o.forEach(n=>{this.addTimeoutAction(n)})}get id(){return this.name}start(){if(this.state==="active"){mt.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&&(mt.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;mt.debug(`Executing timer action ${s.name} at ${t}`),(o=s.action)==null||o.call(s,s.name,t),this.notifyTimeoutAction(s),s.singleUse&&(mt.info(`${this.name} Removing single-use action ${s.name}`),this.removeTimeoutAction(s.name))})}notifyTimeoutAction(t){N(Dr,{name:this.name,action:t.name,remainingTime:this.remainingTime})}}const yt=new Map,Fe=(e,t)=>{const s=yt.get(e);if(!s){mt.error(`Timer ${e} not found`);return}t(s)},zc={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(yt.has(e))return yt.get(e);const o=new Yc(e,t,s);return yt.set(e,o),o},getTimer(e){return yt.get(e)},clearTimer(e){Fe(e,t=>t.pause())},restartTimer(e){Fe(e,t=>t.restart())},resetTimer(e){Fe(e,t=>t.reset())},addTimeoutAction(e,t){Fe(e,s=>s.addTimeoutAction(t))},removeTimeoutAction(e,t){Fe(e,s=>s.removeTimeoutAction(t))},startTimer(e){Fe(e,t=>t.start())}},qc="kos:service:region:settings",Wc="timeZone",Kp=`${qc}-${Wc}`,Ao=async e=>{const t=Ce.factory(Kp)({path:qc,attribute:Wc});await J(t),t.updateProperty(e)},Gp=e=>!e||!e.data;function Ar(e={}){const{alias:t,namespace:s}=e;return(o,r,n)=>{o[wt]=o[wt]||{};const i=n.value,c=async function(...d){const l=Qe();f.debug(`Calling future service ${r} with tracker ${l}`);const u=De.initiateFuture({tracker:l,id:tr});s&&(u.namespace=s),f.debug(`waiting for future ${u.id} to be ready`),await J(u),f.debug(`future ${u.id} is ready`),Y(()=>{f.debug(`Adding future ${u.id} to futureHandler`),this.futureHandler.addFuture(u,t)});try{const h=await i.apply(this,[...d,l]);f.debug(`received future response for ${l}`,h);const p=Gp(h)?h:h==null?void 0:h.data;return p?(p.progress=1,f.debug("mapping future response to future model"),u.endState?f.debug(`future ${u.id} has already completed. Not updating the model`):dr(p,u)):this.futureHandler.removeFuture(t),p}catch(h){throw f.error(h),h}};o[wt][r]={handler:c}}}const Hp=({path:e})=>(t,s)=>{t[P]=t[P]||{},t[P][s]={modelType:Ft.type,id:`${Ft.type}-${e}`,options:{path:e},lifecycle:x.INIT}};function Vp(e){const{path:t,attribute:s}=e;return(o,r)=>{o[P]=o[P]||{},o[P][r]={modelType:mr.type,id:`${t}-${s}`,options:{path:t,attribute:s},lifecycle:x.INIT}}}const je=f.createLogger({name:"services",group:"Services"}),Yp=async(e,t)=>Zc(e,t,`${exports.BASE_URL}/api/server/login`),Zc=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()},zp=async e=>Jc(e,`${exports.BASE_URL}/api/server/startPasswordReset`,""),Jc=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()},qp=async(e,t)=>Qc(e,t,`${exports.BASE_URL}/api/server/resetPassword`),Qc=async(e,t,s=`${exports.BASE_URL}/api/resetPassword`)=>{je.debug(`resetting password with token ${e} and password ${t.replace(/./g,"*")}`);const o=await exports.kosFetch(`${s}`,{method:"POST",destinationAddress:"",body:JSON.stringify({token:e,password:t})});if(je.debug(`password reset returned status ${o.status}`),!o.ok){je.error(`password reset failed with message ${o.statusText}`);const n=await o.json();throw Error(`${n==null?void 0:n.error}:There was a problem resetting the password.`)}return await o.json()},Wp=async(e,t,s)=>Xc(e,t,s,`${exports.BASE_URL}/api/server/acceptInvite`),Xc=async(e,t,s,o=`${exports.BASE_URL}/api/server/acceptInvite`)=>{je.debug(`accepting invite with token ${e} and password ${t.replace(/./g,"*")}`);const r=await exports.kosFetch(`${o}`,{method:"POST",destinationAddress:"",body:JSON.stringify({token:e,password:t,name:s})});if(je.debug(`invitation accept returned status ${r.status}`),!r.ok){je.error(`invite failed with message ${r.statusText}`);const i=await r.json();throw Error(`${i==null?void 0:i.error}:There was a problem accepting the invite.`)}return await r.json()},Zp=Ie.keyframes`
|
|
112
78
|
0% {
|
|
113
79
|
left: -90px;
|
|
114
80
|
color: #eee;
|
|
@@ -120,13 +86,13 @@ ${d}topics:${t}
|
|
|
120
86
|
left: 90px;
|
|
121
87
|
color: #eee;
|
|
122
88
|
}
|
|
123
|
-
`,
|
|
89
|
+
`,Jp=Ie.css`
|
|
124
90
|
font-size: 100px;
|
|
125
91
|
margin-top: -80px;
|
|
126
92
|
position: relative;
|
|
127
|
-
animation: ${
|
|
93
|
+
animation: ${Zp} ease-in-out infinite alternate;
|
|
128
94
|
animation-duration: 1.2s;
|
|
129
|
-
`,
|
|
95
|
+
`,Qp=({children:e})=>En.createPortal(e,document.body);function ed({message:e="Wait a moment while we load your app.",theme:t="light"}){return M.jsx(Qp,{children:M.jsxs(Xp,{theme:t,children:[e,M.jsx("div",{css:Jp,children:"."})]})})}const Xp=Po.div`
|
|
130
96
|
padding-inline: 20px;
|
|
131
97
|
width: 100%;
|
|
132
98
|
height: 100vh;
|
|
@@ -140,7 +106,7 @@ ${d}topics:${t}
|
|
|
140
106
|
left: 0;
|
|
141
107
|
color: ${({theme:e})=>e==="light"?"black":"white"};
|
|
142
108
|
z-index: 10000;
|
|
143
|
-
`;class
|
|
109
|
+
`;class td extends g.Component{constructor(t){super(t),this.state={error:null,errorInfo:null}}componentDidCatch(t,s){this.setState({error:t,errorInfo:s})}render(){return this.state.errorInfo?this.props.fallback||M.jsxs("div",{children:[M.jsx("h2",{children:"Something went wrong."}),M.jsxs("details",{style:{whiteSpace:"pre-wrap"},children:[this.state.error&&this.state.error.toString(),M.jsx("br",{}),this.state.errorInfo.componentStack]})]}):this.props.children}}const em={normal:"#B5F7F6",warn:"#F3D78A",error:"#FC8486"},tm=({value:e=0,title:t,status:s="normal",subtitle:o})=>{const r=Ie.css`
|
|
144
110
|
display: flex;
|
|
145
111
|
flex-direction: column;
|
|
146
112
|
`,n=Ie.css`
|
|
@@ -160,11 +126,11 @@ ${d}topics:${t}
|
|
|
160
126
|
`,c=Ie.css`
|
|
161
127
|
width: ${e}%;
|
|
162
128
|
height: 35px;
|
|
163
|
-
background-color: ${
|
|
129
|
+
background-color: ${em[s]};
|
|
164
130
|
text-align: center;
|
|
165
131
|
line-height: 32px;
|
|
166
132
|
color: black;
|
|
167
|
-
`,
|
|
133
|
+
`,d=Ie.css`
|
|
168
134
|
animation: indeterminateAnimation 1s infinite linear;
|
|
169
135
|
transform-origin: 0% 50%;
|
|
170
136
|
@keyframes indeterminateAnimation {
|
|
@@ -178,5 +144,17 @@ ${d}topics:${t}
|
|
|
178
144
|
transform: translateX(100%) scaleX(0.5);
|
|
179
145
|
}
|
|
180
146
|
}
|
|
181
|
-
`;return M.jsxs("div",{css:r,children:[M.jsxs("div",{css:n,children:[M.jsx("div",{css:i,children:t}),M.jsx("div",{css:[c,e<0?l:""]})]}),M.jsx("div",{children:o})]})},Bm={setModel:()=>!1},Vs=g.createContext(Bm),Km=()=>{const e=g.useContext(Vs);if(e==null)throw new Error("useModels must be used within a KosModelProvider");return e.model},Gc=({children:e})=>{const[t,s]=g.useState(),o=g.useCallback(r=>(s(r),!0),[s]);return M.jsx(Vs.Provider,{value:{model:t,setModel:o},children:e})},Vc=f.createLogger({name:"kos-model-hierarchy-context"}),Hm={models:[],addModel:()=>{Vc.debug("Default implementation being used. Do Nothing.")}},Ys=g.createContext(Hm),Gm=({children:e})=>{const[t,s]=g.useState([]),o=g.useCallback(r=>{t.includes(r)||(Vc.debug("adding to hierarchy context",r.id),s(n=>[...n,r]))},[t]);return M.jsx(Ys.Provider,{value:{models:t,addModel:o},children:e})},Vm=()=>!0,Yc=e=>{const t=g.useContext(Ys);if(!t)throw new Error("useContextModelHierarchy must be used within a KosModelCollectionProvider");const s=(e==null?void 0:e.filter)||Vm;return g.useMemo(()=>t.models.filter(s),[t.models,s])},Ym=e=>Yc({filter:s=>{const o=Qe(s.id);return(o==null?void 0:o.type)===e}})[0],zm=f.createLogger({name:"kos-model-loader"}),qm=()=>M.jsx("div",{}),zc=({fallback:e,children:t,...s})=>M.jsx(Gc,{children:M.jsx(Hc,{fallback:e,children:M.jsx(g.Suspense,{children:M.jsx(qc,{...s,children:t})})})}),qc=e=>{const[t,s]=g.useState(),[o,r]=g.useState(!1),{setModel:n}=g.useContext(Vs),i=g.useContext(Ys);if(g.useEffect(()=>{e.model&&(s(e.model),n(e.model),r(!0),i&&i.addModel(e.model))},[i,e.model,n]),e.error)throw zm.error(e.error),new Error(e.error);const c=e.loading||M.jsx(qm,{});return M.jsx(M.Fragment,{children:t&&o?e.children:c})},ls={header:{title:"Model",createLabel:"Create new Model",deleteLabel:"Delete"},createModal:{okText:"OK",cancelText:"Cancel",title:"Create New Model"}},Wc=g.createContext(ls),Wm=({translations:e=ls,children:t})=>{const s={header:{...ls.header,...e.header},createModal:{...ls.createModal,...e.createModal}};return M.jsx(Wc.Provider,{value:s,children:t})};function Zm(e,t){const s=_.create(e,!1,t),o=s.whenReady().then(()=>s);return Po(o)}const Zc=g.createContext(void 0),Jm=(e={models:{},preloadModels:[]},t)=>{const s=Zm(e,t),o=({children:r})=>{const n=s.read(),[i,c]=g.useState(n.isOnline);return g.useEffect(()=>{const l=F(()=>{c(n.isOnline)});return()=>{l()}},[n]),M.jsx(Zc.Provider,{value:{kosCore:n,online:i},children:r})};return{KosCoreContextProvider:gn.observer(o)}},Jc=()=>{const e=g.useContext(Zc);if(e===void 0)throw new Error("useKosCore must be used within a KosCoreContextProvider");return e},Qm=8,Xm=(e=0)=>new Promise(t=>{setTimeout(()=>{t(!0)},2**e*10)}),Te=new Map;function ep(e,t){if(Te.has(e)){const s=Te.get(e);if(s.status==="finished"){const o=_.getInstance().modelManager.getModelById(e);return{kosModel:o,model:o==null?void 0:o.modelData}}else throw s.promise}else{const s=t().then(()=>{Te.set(e,{status:"finished",key:e})},r=>{throw Te.set(e,{status:"error",error:r}),r}),o={status:"pending",promise:s};throw Te.set(e,o),s}}function tp(e,t){return ep(e,t)}async function sp(e,t){const{modelId:s,factory:o,modelType:r,options:n,activate:i}=t;let c=0;await e.whenReady();let l;if(n){const u=typeof r=="string"?e.modelManager.getModelFactory(r):o;if(!u)throw Error("No Factory Specified. Cannot create a new instance");l=u.build(s,n)}const d=e.modelManager.getModelById(s);if(!d){if(c>Qm)throw Error(`KOS Model ${s} has not been found`);await Xm(c),c=c+1}return await(d==null?void 0:d.whenReady()),d?(l=d.modelData,{kosModel:d,model:l}):{kosModel:void 0,model:void 0}}const B=e=>{const{modelId:t,modelType:s,activate:o,destroyOnUnmount:r}=e,n=Jc(),[i,c]=g.useState(!1),[l,d]=g.useState(),{kosModel:u,model:h}=tp(t||s||"",()=>sp(n.kosCore,e));return g.useEffect(()=>{async function p(){try{return await n.kosCore.whenReady(),o&&await(u==null?void 0:u.fsm.transitionTo(O.GO_ACTIVE,y.ACTIVE)),c(!0),u}catch(b){d(b.message)}}let v;return n.kosCore&&t&&p().then(b=>{v=F(()=>{const E=(b==null?void 0:b.status)===y.READY;c(E)})}).catch(b=>{console.error(b)}),()=>{if(o){if(h!=null&&h.id){const b=n.kosCore.modelManager.getModelById(h.id);b==null||b.fsm.transitionTo(O.GO_INACTIVE,y.INACTIVE).then(()=>{if(r){const E=h.id;Oe(h).then(()=>{Te.delete(E),v==null||v()})}})}}else r&&h&&Oe(h).then(()=>{Te.delete(t),v==null||v()})}},[o,r,n.kosCore,u,h,t]),{model:h,ready:i,error:l,status:{model:h,ready:i,error:l},KosModelLoader:zc}},_r=()=>{const e=ps.type;return B({modelId:e,modelType:ps.type,options:{}})},Ir=g.createContext(void 0),op=({children:e})=>{const{model:t,ready:s}=_r(),o=g.useMemo(()=>s&&t?{model:t}:{},[s,t]);return M.jsx(Ir.Provider,{value:o,children:e})},rp=()=>{const e=g.useContext(Ir);if(!e)throw new Error("useKosTimeContext must be used within a KosTimeProvider");return e},Tr=()=>{const e=Es.type;return B({modelId:e,modelType:Es.type,options:{}})};function np(e){return()=>t=>{const{model:s,status:o,KosModelLoader:r}=Tr();return M.jsx(r,{...o,children:M.jsx(e,{...t,softwareInfo:s})})}}const $r=g.createContext(void 0),ip=({children:e})=>{const{model:t,ready:s}=Tr(),o=g.useMemo(()=>s&&t?{model:t}:{},[s,t]);return M.jsx($r.Provider,{value:o,children:e})},ap=()=>{const e=g.useContext($r);if(!e)throw new Error("useSoftwareInfoContext must be used within a SoftwareInfoProvider");return e},Qc=new Ki,Xc=g.createContext(Qc);function cp({children:e}){return M.jsx(Xc.Provider,{value:Qc,children:e})}const Or=g.createContext(void 0),lp=()=>{const e=window.location.origin,t=ae();return(t==null?void 0:t.host)||e},dp=({children:e,appContext:t,locale:s="en",resolver:o,rootUrl:r,descriptorResolver:n})=>{const[i,c]=g.useState(!1),[l,d]=g.useState(),[u,h]=g.useState(),p=r||lp(),v=g.useMemo(()=>t??"app/system",[t]);g.useEffect(()=>{async function I(){const te=(Array.isArray(v)?v:[v]).map(Q=>(n||sc(Q))()),zs=(await Promise.allSettled(te)).map(Q=>{if(Q.status==="rejected"){f.warn("Failed to load localization descriptor",Q.reason);return}return Q.value}).filter(Q=>!!Q).reverse().reduce((Q,Me)=>{const qs=Me.path;return Object.keys(Me.namespaces).forEach(Ws=>{const Zs=Me.namespaces[Ws];Zs.basePath=qs}),{...Q,namespaces:{...Q.namespaces,...Me.namespaces}}},{});d(zs)}I()},[v,n]),g.useEffect(()=>{async function I(){if(l){const A=p,{translations:te}=await ac.init({lang:s,descriptor:l,defaultNamespace:"common",resolver:o,rootUrl:A});h(te),c(!0)}}I()},[s,l,o,p]);const b=g.useMemo(()=>i?{setLocale:I=>{u&&(u.currentLocale=I)}}:{setLocale:()=>{throw new Error("Translations not ready")}},[i,u]),E=i?e:null;return M.jsx(Or.Provider,{value:b,children:E})},up=()=>{const e=g.useContext(Or);if(!e)throw new Error("useTranslationContainerContext must be used within a TranslationContainerProvider");return e},el=()=>{const e=As.type;return B({modelId:e,modelType:As.type,options:{}})};function hp(e){return t=>{const{model:s,status:o,KosModelLoader:r}=el();return M.jsx(r,{...o,children:M.jsx(e,{...t,device:s})})}}function gp(e,t,s){const o=new Promise(r=>{_.getInstance().whenReady().then(()=>{const{model:n}=_.getInstance().modelManager.createModelInstance(e,t??e,s);return n.whenReady().then(()=>{r(n.modelData)})})});return Po(o)}function fp(e){return t=>{const{model:s,status:o,KosModelLoader:r}=_r();return M.jsx(r,{...o,children:M.jsx(e,{...t,kosTime:s})})}}const tl=()=>{const e=Ft.type;return B({modelId:e,modelType:Ft.type,options:{}})};function mp(e){return t=>{const{model:s,status:o,KosModelLoader:r}=tl();return M.jsx(r,{...o,children:M.jsx(e,{...t,networkInterfaceContainer:s})})}}const sl=()=>{const e=Ms.type;return B({modelId:e,modelType:Ms.type,options:{}})};function pp(e){return t=>{const{model:s,status:o,KosModelLoader:r}=sl();return M.jsx(r,{...o,children:M.jsx(e,{...t,oTA:s})})}}function yp(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 bp(e){const t=g.useRef(null),s=e.onAlert;return yp(t,s),M.jsx("div",{ref:t,style:{width:"100%"},children:e.children})}const vp=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(p){c(p.message)}}u(t)},[t]),g.useEffect(()=>{const u=F(()=>{t&&r&&o(t.value)});return()=>{u()}},[r,t]),[s,{ready:r,error:i}]},ol=()=>{const[e,t]=g.useState(!1),[s,o]=g.useState([]),r=ze.type,n=B({modelId:r,modelType:ze.type,options:{}});return g.useEffect(()=>{const i=F(()=>{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 wp(e){return t=>{const{model:s,status:o,KosModelLoader:r}=ol();return M.jsx(r,{...o,children:M.jsx(e,{...t,storageDeviceContainer:s})})}}const Mp=({timerName:e,onTimerExpired:t,timerEventActions:s,autoStart:o})=>{const r=xc.getTimer(e);return g.useEffect(()=>{const n=j(wr,i=>{const{name:c,action:l,remainingTime:d}=i==null?void 0:i.body;c===e&&r&&(l===Mr?t({name:c,action:l,remainingTime:d,timer:r}):s!=null&&s[l]&&s[l]({name:c,action:l,remainingTime:d,timer:r}))});return o&&(r==null||r.start()),()=>{n.unsubscribe()}},[o,t,r,s,e]),{timer:r,start:r==null?void 0:r.start.bind(r),reset:r==null?void 0:r.reset.bind(r),pause:r==null?void 0:r.pause.bind(r)}},Ep=e=>{const t=/[\\^$.*+?()[\]{}|]/g;return RegExp(t.source).test(e)?e.replace(t,"\\$&"):e},_p=e=>e instanceof RegExp,Ip=e=>typeof e=="string",Tp=(e,t,s)=>{if(e===""||t==="")return e;let o=t;_p(o)||(o=new RegExp("("+Ep(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},rl=(e,t,s)=>{let o=e;return Array.isArray(o)||(o=[o]),o.flatMap(r=>Ip(r)?Tp(r,t,s):r)};function $p(e,t){let s=e;return Object.entries(t).forEach(([o,r])=>{const n=new RegExp(`<${o}>(.*?)</${o}>|<${o}/>`,"g");s=rl(s,n,(i,c)=>r.type==="br"?M.jsx("br",{}):g.cloneElement(r,{key:`${o}-${c}`},i))}),s}const Op=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=$p(c,r||{});return M.jsx("span",{className:e.className,children:l})},Ne=new Map;function Dp(e,t){if(Ne.has(e)){const s=Ne.get(e);if(s.status==="finished")return s.result;throw s.promise}else{const s=t().then(r=>{Ne.set(e,{status:"finished",result:r})},r=>{throw Ne.set(e,{status:"error",error:r}),r}),o={status:"pending",promise:s};throw Ne.set(e,o),s}}function $o(e,t){return Dp(e,t)}const Sp=async()=>{const e=await Oi(he.type);return await J(e.model),e.model},Ap=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),Ne.set(r,{status:"finished",result:n})}return o},Cp=(e,t)=>{const s=[e].flat(),[o,...r]=s,n=$o(he.type,Sp),i=s.join("__"),c=$o(i,()=>Ap(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 p=t!=null&&t.keyPrefix?`${t.keyPrefix}.${u}`:u;return c?c.resolveKey(p,h):(f.debug(`Translation model ${e} not ready for key: ${p}`),p)},[t==null?void 0:t.keyPrefix,e,c]),i18n:l}},nl=()=>{const e=he.type;return B({modelId:e,modelType:he.type,options:{}})};function Rp(e){return t=>{const{model:s,status:o,KosModelLoader:r}=nl();return M.jsx(r,{...o,children:M.jsx(e,{...t,translationContainer:s})})}}const Lp=e=>B({modelId:e,modelType:xt.type}),Dr=()=>B({modelId:Ve.type,modelType:Ve.type,options:{}}),Pp=({troubleType:e,condition:t})=>{const{model:s}=Dr(),[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(()=>F(()=>{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 xp(e){return t=>{const{model:s,status:o,KosModelLoader:r}=Dr();return M.jsx(r,{...o,children:M.jsx(e,{...t,troubleContainer:s})})}}const il=()=>{const e=Ut.type,t=B({modelId:e,modelType:Ut.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=F(()=>{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 kp(e){return t=>{const{model:s,status:o,KosModelLoader:r}=il();return M.jsx(r,{...o,children:M.jsx(e,{...t,usbUpdateContainer:s})})}}const Fp=({path:e,propKey:t})=>{const{status:s}=B({modelType:St.type,modelId:e,options:{path:e}}),[o,r]=g.useState(!1),[n,i]=g.useState(),[c,l]=g.useState(""),[d,u]=g.useState(),h=p=>{n&&t&&n.updateProperty(t,p)};return g.useEffect(()=>{var p;s.model&&i(s.model),s.model&&t&&((p=s.model)!=null&&p.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 p=n==null?void 0:n.props[t];l(p||"")})},[n,t]),{config:n,ready:o,value:c,error:d,updateValue:h}},Np=(e,t)=>{switch(t.type){case"UPDATE":return t.payload;default:return e}},al=({configProperty:e,optionsTransformer:t})=>{const[s,o]=g.useState(!1),[r,n]=g.useState(""),[i,c]=g.useReducer(Np,{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=F(()=>{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 Up(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 jp(e,t){return new Date(e,t,0).getDate()}function cl(e,t){const s=Up(t,e),o=[];for(let r=1;r<=s;r++)o.push(r);return o}function ll(){return[...Array(12).keys()].map(t=>new Date(0,t).getMonth())}function dl(e=[2018,2028]){const t=[];for(let s=e[0];s<=e[1];s++)t.push(s);return t}function ul(e,t=[2018,2028]){const s=dl(t);return e==="long"?s:s.map(o=>Number(o.toString().substring(2)))}function Sr(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 Bp({locale:e="en-US",year:t,month:s,day:o,formatOptions:r={weekday:"long",year:"numeric",month:"long",day:"numeric"},displayOrder:n}){const i=s-1,c=new Date(t,i,o),l=new Intl.DateTimeFormat(e,{month:r.month}).format(c),d=new Intl.DateTimeFormat(e,{year:r.year}).format(c),u=new Intl.DateTimeFormat(e,{day:r.day}).format(c);return n?n=="MMDDYY"?`${l} ${u} ${d}`:n==="DDMMYY"?`${u} ${l} ${d}`:n==="YYMMDD"?`${d} ${l} ${u}`:`${d} ${u} ${l}`:new Intl.DateTimeFormat(e,r).format(c)}function se(e){return e.toString().length===2?new Date(Date.parse(`01 Jan 20${e}`)).getFullYear():e}function Kp(e){return typeof e=="string"?new Date(Date.parse(`01 ${e.substring(0,3)} 2023`)).getMonth()+1:e}function hl(e,t,s){const o=se(t),r=new Date(o,e,1).getDay(),n=new Date(o,e+1,0).getDate();return[...Array(42).keys()].map(c=>c<r||c>n+r-1?{label:"",value:0,disabled:!0}:s[c-r])}function yt(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 bt(e,t){return new Date(e,t,0).getDate()}function gl(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 fl({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=Ar(n,o),d=ml(n,o,e),u=pl(i,e),h=yl(i,e),p=Cr(t,s),v=bl(t,s,e,r),b=Ml(s,t,v),E=vl(e,c);return{daysArray:p,monthsArray:u,yearsArray:l,yearsOptionsArray:d,monthsOptionsArray:h,daysOptionsArray:v,calendarDayArray:b,dayNamesArray:E}}function Ar(e="long",t=[2018,2028]){return g.useMemo(()=>ul(e,t),[e,t])}function ml(e="long",t=[2018,2028],s="en-US"){const o=Ar(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(()=>Sr(e,t),[e,t])}function yl(e,t="en-US"){const s=g.useMemo(()=>ll(),[]),o=g.useMemo(()=>Sr(e,t),[e,t]);return g.useMemo(()=>[...Array(12).keys()].map(n=>({label:o[n],value:Number(s[n])})),[o,s])}function Cr(e,t){const s=se(e);return g.useMemo(()=>cl(s,t),[t,s])}const Hp=(e,t,s,o=[])=>{const r=new Date(e,t,s).getDay();return o.length>0&&o.includes(r)};function bl(e,t,s="en-US",o=[]){const r=Cr(e,t);return g.useMemo(()=>r.map(i=>({label:i.toLocaleString(s),value:i,disabled:Hp(e,t,i,o)})),[o,s,t,r,e])}function vl(e="en-US",t="short"){return g.useMemo(()=>gl(e,t),[e,t])}function wl({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:pe.format(n,o)}}function Ml(e,t,s){return g.useMemo(()=>hl(e,t,s),[e,t,s])}var El=(e=>(e.MMDDYY="MMDDYY",e.DDMMYY="DDMMYY",e.YYMMDD="YYMMDD",e.YYDDMM="YYDDMM",e))(El||{});function Gp({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),[p,v]=g.useState(l),[b,E]=g.useState(s),[I,A]=g.useState(o);g.useEffect(()=>{h(t)},[t]),g.useEffect(()=>{E(s)},[s]),g.useEffect(()=>{A(o)},[o]);const{yearsArray:te,yearsOptionsArray:we,monthsArray:ot,monthsOptionsArray:zs,daysArray:Q,daysOptionsArray:Me,calendarDayArray:qs,dayNamesArray:Ws}=fl({locale:e,year:u,yearRange:p,month:b,formatOptions:{yearFormat:r,monthFormat:n,dayFormat:i},daysOfWeekFilter:d}),{formattedDate:Zs}=wl({year:u,month:b,day:I,formatString:c});return{dateActions:{setYear:h,setYearRange:v,setMonth:E,setDay:A,nextMonth:()=>{const H=b<11?se(u):se(u+1),W=b<11?b+1:0;if(!yt(H,W,I)){const Ee=bt(H,W);A(Ee)}W===0&&h(H),E(W)},previousMonth:()=>{const H=se(b===0?u-1:u),W=b===0?11:b-1;if(!yt(H,W,I)){const Ee=bt(H,W);A(Ee)}W===11&&h(H),E(W)},nextYear:()=>{const H=u<p[1]?u+1:p[0],W=se(H);if(yt(W,b,I))h(H);else{const Ee=bt(se(u+1),b);A(Ee),h(H)}},previousYear:()=>{const H=u>p[0]?u-1:p[0],W=se(H);if(yt(W,b,I))h(H);else{const Ee=bt(se(u-1),b);A(Ee),h(H)}}},dateState:{year:u,yearRange:p,month:b,day:I,yearsArray:te,yearsOptionsArray:we,monthsArray:ot,monthsOptionsArray:zs,daysArray:Q,daysOptionsArray:Me,calendarDayNames:Ws,calendarDayArray:qs,formattedDate:Zs}}}function _l({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:z.type,modelType:z.type,options:{}}),h=typeof e=="string"?pe.parseISO(e):e;return g.useEffect(()=>{l?c(""):t?c(pe.format(h,t)):u&&c(pe.format(h,d!=null&&d.selectedDateFormat?d==null?void 0:d.selectedDateFormat:""))},[l,e,t,h,d,u]),g.useEffect(()=>{s?n(pe.format(h,s)):u&&n(pe.format(h,d!=null&&d.selectedTimeFormat?d==null?void 0:d.selectedTimeFormat:""))},[e,s,h,d,u]),{formattedDate:i,formattedTime:r}}const Il=({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}=_l({date:c,options:{ignoreDateFormat:!0}});return g.useEffect(()=>{const u=Number(e),h=Math.floor(u/3600),p=Math.floor(u%3600/60),v=u%60;s(h),r(p),i(v);const b=new Date;b.setHours(0,0,0,0);const E=new Date(b.getTime()+u*1e3);l(new Date(E))},[e]),{hours:t,minutes:o,seconds:n,formattedTime:d,timeActions:{setHours:s,setMinutes:r,setSeconds:i}}},Vp=({configProperty:e})=>{const{value:t}=al({configProperty:e}),s=parseInt(t||"0",10),{hours:o,minutes:r,seconds:n,formattedTime:i,timeActions:c}=Il({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 Yp(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 zp=e=>M.jsx("option",{title:e.id,value:e.format,children:e.format},e.id),qp=(e=zp)=>{const[t,s]=g.useState([]),[o,r]=g.useState(),{model:n,ready:i}=B({modelType:z.type,modelId:z.type,options:{}});g.useEffect(()=>{const l=F(()=>{s((n==null?void 0:n.dateFormatOptions.map(e))||[])});return()=>{l()}},[n,i,e]),g.useEffect(()=>{const l=F(()=>{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}}},Wp=e=>M.jsx("option",{title:e,value:e,children:e},e),Tl="kos:service:region:settings",$l="timeZone",Zp=`${Tl}-${$l}`,Jp=(e=Wp)=>{const[t,s]=g.useState([]),[o,r]=g.useState(""),{model:n,ready:i}=B({modelType:z.type,modelId:z.type,options:{}}),c=Ae.factory(Zp)({path:Tl,attribute:$l});g.useEffect(()=>{const d=F(()=>{s((n==null?void 0:n.timeZones.map(e))||[]),n!=null&&n.timeZones.length&&To(n==null?void 0:n.timeZones[0])});return()=>{d()}},[n,i,e]),g.useEffect(()=>{const d=F(()=>{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&&To(u)},[]);return{options:t,raw:(n==null?void 0:n.timeZones)??[],regionModel:n,selectedTimeZone:o,timeZones:(n==null?void 0:n.timeZones)??[],updateTimeZone:l,selectProps:{onChange:l,value:o,options:t}}},Ol="kos:service:region",Dl="regionId",Qp=`${Ol}-${Dl}`,Xp=e=>M.jsx("option",{title:e,value:e,children:e},e),Sl=(e=Xp)=>{const[t,s]=g.useState([]),[o,r]=g.useState("factory"),{model:n,ready:i}=B({modelType:z.type,modelId:z.type,options:{}}),c=Ae.factory(Qp)({path:Ol,attribute:Dl});g.useEffect(()=>{const d=F(()=>{s((n==null?void 0:n.availableRegions.map(e))||[])});return()=>{d()}},[n,i,e]),g.useEffect(()=>{const d=F(()=>{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&&Lc(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}}},ey=e=>M.jsx("option",{title:e.id,value:e.format,children:e.format},e.id),ty=(e=ey)=>{const[t,s]=g.useState([]),[o,r]=g.useState(),{model:n,ready:i}=B({modelType:z.type,modelId:z.type,options:{}});g.useEffect(()=>{const l=F(()=>{s((n==null?void 0:n.timeFormatOptions.map(e))||[])});return()=>{l()}},[n,i,e]),g.useEffect(()=>{const l=F(()=>{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}}},sy=(e,t)=>g.useMemo(()=>Yo(e),t),oy={config:{attributes:!0,childList:!0,subtree:!0}};function ry(e,t,s=oy){const[o,r]=g.useState(null);g.useEffect(()=>{if(!t||typeof t!="function")throw new Error("A valid callback function is required");const n=new MutationObserver(t);r(n)},[t,s,r]),g.useEffect(()=>{if(!o)return()=>{};if(!e)throw new Error("A valid DOM element is required");const{config:n}=s;try{o.observe(e,n)}catch(i){f.error(i)}return()=>{o&&o.disconnect()}},[o,e,s])}const Al={validateStart:function(e){return!0},validateStop:function(e){const t=e.event.currentTarget.getBoundingClientRect(),[s,o]=e.xy;return s<t.left||s>t.right||o<t.top||o>t.bottom}},ao=f.createLogger({name:"usePressGesture",group:"kos-hooks"});function ny({onPressed:e,onRelease:t,intersectionStrategy:s=Al}){const o=g.useRef(!1),r=Hl.useGesture({onDragStart:l=>{ao.info("onDragStart",l.type),s.validateStart(l)&&(e&&e(),o.current=!0)},onDrag:l=>{ao.info("onDrag",l.type),o.current&&s.validateStop(l)&&(t&&t(),o.current=!1)},onDragEnd:l=>{ao.info("onDragEnd",l.type),o.current&&t&&(t(),o.current=!1)}}),n=()=>{e&&e(),o.current=!0},i=()=>{o.current&&t&&(t(),o.current=!1)},c=()=>{o.current&&t&&(t(),o.current=!1)};return{dom:r,mesh:()=>({onPointerDown:n,onPointerUp:i,onPointerOut:c})}}const Cl=()=>{const[e,t]=g.useState(!1),s=_.getInstance();return g.useEffect(()=>{const o=F(()=>{s&&s.reloading!==e&&t(s.reloading)});return()=>{o()}},[s,e]),[e]};function Rl(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 Oo(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 Ll(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 Pl({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=Rl(e,t),i=Oo(60,s),c=Oo(60,o),l=Ll(r);return{hourOptions:n,minuteOptions:i,secondOptions:c,amPmOptions:l}}function xl(e,t){return pe.format(e,t)}function kl({formatOptions:e,initialDate:t=new Date,locale:s="en-US",format:o="HH:mm"}){const[r,n]=g.useState(t),i=g.useCallback(E=>{n(I=>{const A=new Date(I);return A.setHours(Number(E)),A})},[]),c=g.useCallback(E=>{n(I=>{const A=new Date(I);return A.setMinutes(Number(E)),A})},[]),l=g.useCallback(E=>{n(I=>{const A=new Date(I);return A.setSeconds(Number(E)),A})},[]),d=g.useCallback(E=>{const I=new Date(E);n(I)},[]),u=xl(r,o),{hourOptions:h,minuteOptions:p,secondOptions:v,amPmOptions:b}=Pl({formatOptions:e,locale:s});return{amPmOptions:b,formattedTime:u,hourOptions:h,minuteOptions:p,secondOptions:v,setHours:i,setMinutes:c,setSeconds:l,setTime:d,time:new Date(r)}}const iy=e=>{const{regionModel:t}=Sl(),s=g.useMemo(()=>({hour12:t==null?void 0:t.is12HourTimeFormat}),[t==null?void 0:t.is12HourTimeFormat]);return kl({...e,locale:t==null?void 0:t.regionId,format:t==null?void 0:t.selectedTimeFormat,formatOptions:s})};function ay(e){return t=>{const[s]=Cl();return s?M.jsx(Kc,{message:"Wait a moment while your project reloads..."}):M.jsx(e,{...t})}}const dn=f.createLogger({name:"studio-properties-service",group:"Services"}),cy="/api/kos/studio/properties",Fl=async e=>{if(dn.debug("sending GET for studio-properties"),!e)throw dn.error("connectionId is undefined"),new Error("connectionId is undefined");return await Ce.get(cy,{},{destinationAddress:e,timeout:500})},ly=Object.freeze(Object.defineProperty({__proto__:null,getStudioProperties:Fl},Symbol.toStringTag,{value:"Module"}));var dy=Object.defineProperty,uy=Object.getOwnPropertyDescriptor,hy=(e,t,s,o)=>{for(var r=o>1?void 0:o?uy(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&&dy(t,s,r),r};const Nl="studio-properties-model",gy="/kos/studio/properties",un={"kos.studio.tool.legacy":1};let Do=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=ye(),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=Kt.getInstance().subscribeTopic({topic:gy,destinationAddress:this.connectionId,callback:s=>{this.logger.error(`Received studio-properties message for connection ${this.connectionId}: ${JSON.stringify(s)}`)}});const[e,t]=await Fl(this.connectionId);if(e){this.logger.error(`Error loading studio-properties: ${e}`),this.data.setValues(un);return}if(t){const s=Object.keys(t).reduce((o,r)=>(o[r]=t[r]??r,o),{});this.data.setValues(s??un),f.ifDebug(()=>this.logger.debug(`studio-properties loaded: ${JSON.stringify(s)}`))}}get(e){return this.data[e]}createObservableProperty(e){return Yo(()=>this.get(e))}};Do=hy([D(Nl)],Do);const fy=new le({class:Do,type:Nl});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:()=>gn.observer});exports.AuthState=Li;exports.BrowserKosRouter=Hi;exports.BrowserRouter=rr;exports.ChildModels=wt;exports.ConfigBean=St;exports.CoreExtensionManager=_m;exports.CoreModels=vr;exports.CreateModelTranslationsContext=Wc;exports.CreateModelTranslationsProvider=Wm;exports.DateDisplayFormat=El;exports.DateHelpers=td;exports.DependencyLifecycle=k;exports.DependencyModels=P;exports.Device=As;exports.DeviceServices=Vf;exports.DomIntersectionStrategy=Al;exports.EVENT_KOS_MODEL_READY=Ro;exports.EVENT_TROUBLE_ADDED=dh;exports.EVENT_TROUBLE_REMOVED=uh;exports.EXTENSION_TROUBLE_DATA_MAPPER=vs;exports.EXTENSION_TROUBLE_MAPPER=zt;exports.ErrorBoundaryWithFallback=Hc;exports.EventBus=zl;exports.ExtensionManager=C;exports.FUTURE_CONTAINER_MODEL_TYPE=ya;exports.FUTURE_MODEL_TYPE=aa;exports.FUTURE_NOT_ASSIGNED=qo;exports.FeatureFlagService=Cn;exports.FetchError=ne;exports.FutureContainerFactory=be;exports.FutureContainerModel=va;exports.FutureEndState=Ke;exports.FutureFactory=tt;exports.FutureHandler=er;exports.FutureManager=De;exports.FutureModel=ga;exports.FutureService=vt;exports.HEADER_CACHE_CONTROL=yn;exports.HEADER_CONTENT_TYPE=pn;exports.HEADER_DESTINATION_ADDR=ge;exports.HEADER_FOS_REQUEST_ID=bn;exports.HEADER_METHOD=Ps;exports.HEADER_ORDERED=Ao;exports.HEADER_REQUEST_ID=jt;exports.HEADER_REQUEST_TYPE=ie;exports.HEADER_RESPONSE_ID=xs;exports.HEADER_SOURCE_ADDR=mn;exports.HEADER_TOPIC=fn;exports.HEADER_URL=We;exports.HEADER_WORK_TRACKER=Co;exports.KOS_MODEL_ID=ds;exports.KeyValue=ar;exports.KeyValueServices=ng;exports.Kos=V;exports.KosConfigPropertySpec=Ae;exports.KosContainerIndex=Vo;exports.KosContextBean=ji;exports.KosContextManager=x;exports.KosCore=_;exports.KosCoreModelPropertyMapper=oe;exports.KosDataContainer=Bi;exports.KosDependencyTypes=yd;exports.KosExtensionUtils=mu;exports.KosFeatureFlags=sd;exports.KosFetchMethods=li;exports.KosGlobalConfig=No;exports.KosLog=f;exports.KosMockEvents=Mn;exports.KosModel=Ei;exports.KosModelCollectionProvider=Gm;exports.KosModelContainer=me;exports.KosModelContext=Vs;exports.KosModelEvents=O;exports.KosModelFactory=Tt;exports.KosModelLoader=zc;exports.KosModelLoaderDisplay=qc;exports.KosModelManager=Ti;exports.KosModelProvider=Gc;exports.KosModelRegistrationFactory=le;exports.KosModelRegistry=Io;exports.KosModelState=y;exports.KosModelSymbol=Zn;exports.KosModelVisitor=Nu;exports.KosObservableData=ki;exports.KosRegistration=ih;exports.KosSingletonRegistration=ah;exports.KosTime=ps;exports.KosTimeContext=Ir;exports.KosTimeProvider=op;exports.KosTimeServices=lg;exports.KosTimer=Pc;exports.KosToken=Ki;exports.KosTranslationProvider=dp;exports.KosTranslations=ac;exports.KosWSTransportStatus=Mi;exports.KosWsEvents=Bt;exports.LOGIN_HOST=vn;exports.LOGIN_URL=Gl;exports.LoadingMessage=Kc;exports.LogBlock=Pt;exports.LogBlockContainer=Bs;exports.LogConfig=Et;exports.LogStream=Ot;exports.LogStreamContainer=Yt;exports.LogStreamServices=wg;exports.MODEL_DELETION_DELAY=Ii;exports.MiddlewareChain=xi;exports.ModelEffects=$e;exports.MultipleFutureHandler=Fh;exports.NestedModelContext=Ys;exports.NetworkInterface=mr;exports.NetworkInterfaceContainer=Ft;exports.NetworkInterfaceServices=tm;exports.ObservableData=ye;exports.Ota=Ms;exports.OutsideAlerter=bp;exports.PLUGIN_EXTENSION_NAME=pu;exports.PORT=wn;exports.PROFILE_LOG_DEBUG=kn;exports.PROFILE_LOG_INFO=Fn;exports.PROFILE_RELAX_STORE_VALIDATION=rd;exports.PROFILE_TOOLS_PREVIEW=xn;exports.ParentModel=Mt;exports.PluginExtensionManager=yu;exports.ProgressBar=jm;exports.ReferenceConfig=rs;exports.RegionInfo=z;exports.RegionServices=Mh;exports.RegistrationManager=$;exports.Registry=Mm;exports.STATUS=So;exports.ServiceFactory=Y;exports.SingletonKosModelRegistrationFactory=fe;exports.SoftwareInfo=Es;exports.SoftwareInfoContext=$r;exports.SoftwareInfoProvider=ip;exports.SoftwareInfoServices=ef;exports.StateBean=kt;exports.StateBeanServices=af;exports.StateProp=dr;exports.StatePropServices=yf;exports.StorageDevice=Rs;exports.StorageDeviceContainer=ze;exports.StorageDeviceServices=im;exports.StudioProperties=fy;exports.StudioPropertiesServices=ly;exports.SubscriptionHandlers=G;exports.TIMER_END=Mr;exports.TIMER_EVENT=wr;exports.TimerManager=xc;exports.TokenContext=Xc;exports.TokenProvider=cp;exports.Topics=$t;exports.Trans=Op;exports.TransitionMap=ns;exports.Transitions=jo;exports.Translation=Ts;exports.TranslationContainer=he;exports.TranslationContainerContext=Or;exports.TranslationContext=Df;exports.TransportFactory=fo;exports.Trouble=xt;exports.TroubleContainer=Ve;exports.TroubleServices=jg;exports.Troubles=X;exports.UsbUpdate=br;exports.UsbUpdateContainer=Ut;exports.UsbUpdateServices=mm;exports.WS_EVENT_TYPE=cc;exports.WebSocketEvents=It;exports.WebSocketTransport=Kt;exports.WsEventFactory=hr;exports.acceptOrgInvitation=Bc;exports.addDaysToDate=In;exports.addFuture=la;exports.addMonthsToDate=_n;exports.api=fa;exports.applyMixins=Wl;exports.arraysEqual=Zl;exports.buildConfigBeanModel=fh;exports.buildFuture=or;exports.buildFutureModel=ua;exports.cancelFuture=da;exports.convert=ia;exports.convertFileSizeRaw=ql;exports.createBaseMessage=hi;exports.createBroadcastMessageResponse=pi;exports.createClient=Ho;exports.createFosBaseMessage=ui;exports.createHeaders=uo;exports.createKosHtpMessageResponse=yi;exports.createKosMessage=fi;exports.createKosMessageResponse=bi;exports.createMessageBody=ve;exports.createModelDependency=ri;exports.createOptionKey=bd;exports.createPropKey=Se;exports.createReadableStream=ho;exports.createStudioMessage=di;exports.createStudioMessageRequest=gi;exports.createStudioMessageResponse=mi;exports.debounce=An;exports.deleteFuture=ca;exports.destroyKosModel=Oe;exports.evaluateScopes=Zi;exports.executeChildrenModelLifecycle=ai;exports.executeDependentModelLifecycle=at;exports.executeListLifecycle=ii;exports.fetchModel=gp;exports.findModel=Mu;exports.findModels=Di;exports.formatDate=On;exports.formatDateSince=En;exports.formatDateTime=Sn;exports.formatTime=Dn;exports.getAllKosCompanionModels=_u;exports.getCalendarMonthArray=hl;exports.getConfigBean=Wi;exports.getDayStrings=gl;exports.getDays=jp;exports.getDaysArray=cl;exports.getDaysInMonth=Fo;exports.getDependenciesByLifecycle=ni;exports.getFormattedDate=Bp;exports.getFormattedMonth=Kp;exports.getFormattedMonthsArray=Sr;exports.getFormattedYear=se;exports.getFormattedYearsArray=ul;exports.getFutures=Gh;exports.getKosCompanionModel=Eu;exports.getKosLocalizationDescriptor=sc;exports.getKosMessageLogging=Kn;exports.getKosModel=Oi;exports.getKosModelSync=Qe;exports.getKosModelType=wu;exports.getKosSessionKey=Ui;exports.getLastDayOfMonth=bt;exports.getLocalizationDescriptor=vf;exports.getLogLevel=Bn;exports.getLogMessageToStudio=Hn;exports.getMessageBody=go;exports.getMonthsArray=ll;exports.getObservableCompanions=Iu;exports.getQueryParams=ae;exports.getTranslations=tc;exports.getYearsArray=dl;exports.hasDecimals=zi;exports.hasKosProfile=co;exports.hslStringToHex=Ln;exports.hslToHex=Rn;exports.initKosProvider=Jm;exports.isBoolean=Zo;exports.isKosCompanionTypeFactory=_i;exports.isKosDataModel=_t;exports.isKosLoggingEnabled=ad;exports.isKosModel=ee;exports.isKosModelContainer=Bo;exports.isKosModelReady=hs;exports.isLeapYear=ko;exports.isLocalRefId=eh;exports.isNumber=Fs;exports.isPrintable=Ld;exports.isValidDate=yt;exports.kosAction=K;exports.kosAutoEffect=F;exports.kosChild=ce;exports.kosCompanion=$d;exports.kosComputed=Yo;exports.kosConfigBean=Ns;exports.kosConfigProperty=kh;exports.kosContext=Od;exports.kosDependency=Je;exports.kosEffect=Vi;exports.kosFuture=Er;exports.kosLogger=Dd;exports.kosModel=D;exports.kosModelEffect=Jn;exports.kosObservable=zo;exports.kosParentAware=ks;exports.kosReference=Sd;exports.kosStateBean=Sm;exports.kosStateProp=Am;exports.kosSubscribe=Ad;exports.kosTopicHandler=R;exports.kosWhen=po;exports.login=Nc;exports.mapConfigBeanModelToDto=ea;exports.mapDataToModel=lo;exports.mapDtoToConfigBeanModel=Qi;exports.mapDtoToFutureModel=sr;exports.mapDtoToFutureOptions=tr;exports.mapUpdateDtoToConfigBeanModel=Xi;exports.modelEventTopicFactory=qn;exports.modelFactory=Xe;exports.modelTypeEventTopicFactory=Wn;exports.modifyConfigBean=qi;exports.modifyFuture=Vh;exports.pairedClientHeartbeat=Vu;exports.pipe=Ni;exports.preloadKosModel=Ou;exports.processId=ed;exports.processMiddleware=Bu;exports.registerCompanionModel=$u;exports.registerCoreModels=Ac;exports.registerExtensionPoint=Uo;exports.registerKosModel=Ai;exports.registerLegacyModel=Si;exports.resetKosModel=$i;exports.resetPassword=jc;exports.resolveBaseUrl=Pi;exports.resolveChild=ci;exports.resolveContainerDeltas=Jl;exports.resolveItemListDeltas=Xl;exports.resolveKosCompanion=mo;exports.resolveKosContext=oh;exports.resolveKosProfiles=Un;exports.resolveListDeltas=Ql;exports.resolveServiceUrl=q;exports.resolveVariable=Pn;exports.retryWithExponentialBackoff=zu;exports.sendAsyncIntent=lh;exports.sendBroadcastMessage=Qd;exports.sendIntent=ch;exports.sendKosHttpMessageResponse=wi;exports.sendKosMessage=Wd;exports.sendKosMessageResponse=vi;exports.sendRequest=th;exports.sendStudioMessage=Jd;exports.sendStudioMessageRequest=Zd;exports.startPasswordReset=Uc;exports.stringComponentInsert=rl;exports.studioAcceptOrgInvitation=Pm;exports.studioLogin=Cm;exports.studioResetPassword=Lm;exports.studioStartPasswordReset=Rm;exports.subscribeStore=Im;exports.syncPublish=sh;exports.transitionToActive=ei;exports.transitionToInit=oi;exports.transitionToLoad=si;exports.transitionToReady=ti;exports.transitionToUnload=Rd;exports.troubleByTypeReducer=Sf;exports.troubleDataFactory=Va;exports.unloadKosModel=vu;exports.updateCompanionModelRegistration=Hu;exports.updateModelRegistration=Ku;exports.updateRegion=Lc;exports.updateTimeZone=To;exports.useAmPmValues=Ll;exports.useCalendarDayArray=Ml;exports.useConfigBean=Fp;exports.useConfigProperty=al;exports.useContextModel=Km;exports.useContextModelHierarchy=Yc;exports.useDateArrays=fl;exports.useDateProps=Gp;exports.useDateRelativeConfig=Vp;exports.useDateRelativeData=Il;exports.useDayNames=vl;exports.useDayOptions=bl;exports.useDays=Cr;exports.useDevice=el;exports.useFormattedDate=wl;exports.useFormattedTime=xl;exports.useFunctionWarmup=Yp;exports.useHourValues=Rl;exports.useKosCore=Jc;exports.useKosDateFormats=qp;exports.useKosModel=B;exports.useKosRegions=Sl;exports.useKosTime=_r;exports.useKosTimeContext=rp;exports.useKosTimeFormats=ty;exports.useKosTimeZones=Jp;exports.useKosTranslation=Cp;exports.useKosTranslationContext=up;exports.useLocalComputed=sy;exports.useModelFromHierarchy=Ym;exports.useMonths=pl;exports.useMonthsOptions=yl;exports.useMutationObserver=ry;exports.useNetworkInterfaceContainer=tl;exports.useOta=sl;exports.usePressGesture=ny;exports.useProjectReload=Cl;exports.useRegionTimeProps=iy;exports.useRegionalTimeDate=_l;exports.useSoftwareInfo=Tr;exports.useSoftwareInfoContext=ap;exports.useStateProperty=vp;exports.useStorageDeviceContainer=ol;exports.useSuspenseData=$o;exports.useTimeOptions=Pl;exports.useTimeProps=kl;exports.useTimeValues=Oo;exports.useTimer=Mp;exports.useTranslationContainer=nl;exports.useTroubleContainerModel=Dr;exports.useTroubleModel=Lp;exports.useTroublePresence=Pp;exports.useUsbUpdateContainer=il;exports.useYears=Ar;exports.useYearsOptions=ml;exports.uuid=Ze;exports.variableToHex=od;exports.waitForRequest=Go;exports.whenReady=J;exports.withDevice=hp;exports.withKosTime=fp;exports.withNetworkInterfaceContainer=mp;exports.withOta=pp;exports.withProjectReloading=ay;exports.withSoftwareInfo=np;exports.withStorageDeviceContainer=wp;exports.withTranslationContainer=Rp;exports.withTroubleContainer=xp;exports.withUsbUpdateContainer=kp;exports.wrapPromise=Po;
|
|
147
|
+
`;return M.jsxs("div",{css:r,children:[M.jsxs("div",{css:n,children:[M.jsx("div",{css:i,children:t}),M.jsx("div",{css:[c,e<0?d:""]})]}),M.jsx("div",{children:o})]})},sm={setModel:()=>!1},qs=g.createContext(sm),om=()=>{const e=g.useContext(qs);if(e==null)throw new Error("useModels must be used within a KosModelProvider");return e.model},sd=({children:e})=>{const[t,s]=g.useState(),o=g.useCallback(r=>(s(r),!0),[s]);return M.jsx(qs.Provider,{value:{model:t,setModel:o},children:e})},od=f.createLogger({name:"kos-model-hierarchy-context"}),rm={models:[],addModel:()=>{od.debug("Default implementation being used. Do Nothing.")}},Ws=g.createContext(rm),nm=({children:e})=>{const[t,s]=g.useState([]),o=g.useCallback(r=>{t.includes(r)||(od.debug("adding to hierarchy context",r.id),s(n=>[...n,r]))},[t]);return M.jsx(Ws.Provider,{value:{models:t,addModel:o},children:e})},im=()=>!0,rd=e=>{const t=g.useContext(Ws);if(!t)throw new Error("useContextModelHierarchy must be used within a KosModelCollectionProvider");const s=(e==null?void 0:e.filter)||im;return g.useMemo(()=>t.models.filter(s),[t.models,s])},am=e=>rd({filter:s=>{const o=Xe(s.id);return(o==null?void 0:o.type)===e}})[0],cm=f.createLogger({name:"kos-model-loader"}),dm=()=>M.jsx("div",{}),nd=({fallback:e,children:t,...s})=>M.jsx(sd,{children:M.jsx(td,{fallback:e,children:M.jsx(g.Suspense,{children:M.jsx(id,{...s,children:t})})})}),id=e=>{const[t,s]=g.useState(),[o,r]=g.useState(!1),{setModel:n}=g.useContext(qs),i=g.useContext(Ws);if(g.useEffect(()=>{e.model&&(s(e.model),n(e.model),r(!0),i&&i.addModel(e.model))},[i,e.model,n]),e.error)throw cm.error(e.error),new Error(e.error);const c=e.loading||M.jsx(dm,{});return M.jsx(M.Fragment,{children:t&&o?e.children:c})},us={header:{title:"Model",createLabel:"Create new Model",deleteLabel:"Delete"},createModal:{okText:"OK",cancelText:"Cancel",title:"Create New Model"}},ad=g.createContext(us),lm=({translations:e=us,children:t})=>{const s={header:{...us.header,...e.header},createModal:{...us.createModal,...e.createModal}};return M.jsx(ad.Provider,{value:s,children:t})};function um(e,t){const s=E.create(e,!1,t),o=s.whenReady().then(()=>s);return Bo(o)}const cd=g.createContext(void 0),hm=(e={models:{},preloadModels:[]},t)=>{const s=um(e,t),o=({children:r})=>{const n=s.read(),[i,c]=g.useState(n.isOnline);return g.useEffect(()=>{const d=F(()=>{c(n.isOnline)});return()=>{d()}},[n]),M.jsx(cd.Provider,{value:{kosCore:n,online:i},children:r})};return{KosCoreContextProvider:ko.observer(o)}},dd=()=>{const e=g.useContext(cd);if(e===void 0)throw new Error("useKosCore must be used within a KosCoreContextProvider");return e},gm=8,fm=(e=0)=>new Promise(t=>{setTimeout(()=>{t(!0)},2**e*10)}),Te=new Map;function pm(e,t){if(Te.has(e)){const s=Te.get(e);if(s.status==="finished"){const o=E.getInstance().modelManager.getModelById(e);return{kosModel:o,model:o==null?void 0:o.modelData}}else throw s.promise}else{const s=t().then(()=>{Te.set(e,{status:"finished",key:e})},r=>{throw Te.set(e,{status:"error",error:r}),r}),o={status:"pending",promise:s};throw Te.set(e,o),s}}function mm(e,t){return pm(e,t)}async function ym(e,t){const{modelId:s,factory:o,modelType:r,options:n,activate:i}=t;let c=0;await e.whenReady();let d;if(n){const u=typeof r=="string"?e.modelManager.getModelFactory(r):o;if(!u)throw Error("No Factory Specified. Cannot create a new instance");d=u.build(s,n)}const l=e.modelManager.getModelById(s);if(!l){if(c>gm)throw Error(`KOS Model ${s} has not been found`);await fm(c),c=c+1}return await(l==null?void 0:l.whenReady()),l?(d=l.modelData,{kosModel:l,model:d}):{kosModel:void 0,model:void 0}}const B=e=>{const{modelId:t,modelType:s,activate:o,destroyOnUnmount:r}=e,n=dd(),[i,c]=g.useState(!1),[d,l]=g.useState(),{kosModel:u,model:h}=mm(t||s||"",()=>ym(n.kosCore,e));return g.useEffect(()=>{async function p(){try{return await n.kosCore.whenReady(),o&&await(u==null?void 0:u.fsm.transitionTo(D.GO_ACTIVE,y.ACTIVE)),c(!0),u}catch(b){l(b.message)}}let w;return n.kosCore&&t&&p().then(b=>{w=F(()=>{const _=(b==null?void 0:b.status)===y.READY;c(_)})}).catch(b=>{console.error(b)}),()=>{if(o){if(h!=null&&h.id){const b=n.kosCore.modelManager.getModelById(h.id);b==null||b.fsm.transitionTo(D.GO_INACTIVE,y.INACTIVE).then(()=>{if(r){const _=h.id;Oe(h).then(()=>{Te.delete(_),w==null||w()})}})}}else r&&h&&Oe(h).then(()=>{Te.delete(t),w==null||w()})}},[o,r,n.kosCore,u,h,t]),{model:h,ready:i,error:d,status:{model:h,ready:i,error:d},KosModelLoader:nd}},Cr=()=>{const e=bs.type;return B({modelId:e,modelType:bs.type,options:{}})},Rr=g.createContext(void 0),bm=({children:e})=>{const{model:t,ready:s}=Cr(),o=g.useMemo(()=>s&&t?{model:t}:{},[s,t]);return M.jsx(Rr.Provider,{value:o,children:e})},vm=()=>{const e=g.useContext(Rr);if(!e)throw new Error("useKosTimeContext must be used within a KosTimeProvider");return e},Lr=()=>{const e=Is.type;return B({modelId:e,modelType:Is.type,options:{}})};function wm(e){return()=>t=>{const{model:s,status:o,KosModelLoader:r}=Lr();return M.jsx(r,{...o,children:M.jsx(e,{...t,softwareInfo:s})})}}const Pr=g.createContext(void 0),Mm=({children:e})=>{const{model:t,ready:s}=Lr(),o=g.useMemo(()=>s&&t?{model:t}:{},[s,t]);return M.jsx(Pr.Provider,{value:o,children:e})},_m=()=>{const e=g.useContext(Pr);if(!e)throw new Error("useSoftwareInfoContext must be used within a SoftwareInfoProvider");return e},ld=new Qi,ud=g.createContext(ld);function Em({children:e}){return M.jsx(ud.Provider,{value:ld,children:e})}const kr=g.createContext(void 0),Im=()=>{const e=window.location.origin,t=ee();return(t==null?void 0:t.host)||e},Tm=({children:e,appContext:t,locale:s="en",resolver:o,rootUrl:r,descriptorResolver:n})=>{const[i,c]=g.useState(!1),[d,l]=g.useState(),[u,h]=g.useState(),p=r||Im(),w=g.useMemo(()=>t??"app/system",[t]);g.useEffect(()=>{async function I(){const se=(Array.isArray(w)?w:[w]).map(Q=>(n||hc(Q))()),Zs=(await Promise.allSettled(se)).map(Q=>{if(Q.status==="rejected"){f.warn("Failed to load localization descriptor",Q.reason);return}return Q.value}).filter(Q=>!!Q).reverse().reduce((Q,Me)=>{const Js=Me.path;return Object.keys(Me.namespaces).forEach(Qs=>{const Xs=Me.namespaces[Qs];Xs.basePath=Js}),{...Q,namespaces:{...Q.namespaces,...Me.namespaces}}},{});l(Zs)}I()},[w,n]),g.useEffect(()=>{async function I(){if(d){const A=p,{translations:se}=await yc.init({lang:s,descriptor:d,defaultNamespace:"common",resolver:o,rootUrl:A});h(se),c(!0)}}I()},[s,d,o,p]);const b=g.useMemo(()=>i?{setLocale:I=>{u&&(u.currentLocale=I)}}:{setLocale:()=>{throw new Error("Translations not ready")}},[i,u]),_=i?e:null;return M.jsx(kr.Provider,{value:b,children:_})},$m=()=>{const e=g.useContext(kr);if(!e)throw new Error("useTranslationContainerContext must be used within a TranslationContainerProvider");return e},Om=()=>{const e=qe.type;return B({modelId:e,modelType:qe.type,options:{}})};function Dm(e){return t=>{const{model:s,status:o,KosModelLoader:r}=Om();return M.jsx(r,{...o,children:M.jsx(e,{...t,canvasDispatcher:s})})}}const Sm=(e,t,s)=>{const o=atob(e),r=new Uint8ClampedArray(t*s*4);for(let n=0,i=0;n<o.length&&i<r.length;n+=3,i+=4)r[i]=o.charCodeAt(n),r[i+1]=o.charCodeAt(n+1),r[i+2]=o.charCodeAt(n+2),r[i+3]=255;return r},Am=(e,t,s)=>{const o=new Uint8ClampedArray(t*s*4);for(let r=0;r<e.length;r++){const n=e.charCodeAt(r),i=(n>>5&7)*255/7,c=(n>>2&7)*255/7,d=(n&3)*255/3,l=r*4;o[l]=i,o[l+1]=c,o[l+2]=d,o[l+3]=255}return o};function Cm({ctx:e,format:t,dataString:s,width:o,height:r,pixelSize:n}){const i=t==="base64"?Sm(s,o,r):Am(s,o,r),c=new ImageData(i,o,r),d=document.createElement("canvas");d.width=o,d.height=r;const l=d.getContext("2d");l==null||l.putImageData(c,0,0),e.imageSmoothingEnabled=!1,e.clearRect(0,0,o*n,r*n),e.drawImage(d,0,0,o*n,r*n)}const Rm=f.createLogger({name:"canvas-streamer"});Rm.debug("main-view component loaded");const ho=10,hd=ko.observer(({canvasDispatcher:e,height:t=30,width:s=50,defaultFps:o=10,showPreview:r=!1,name:n,apiPath:i="/api/system/canvas"})=>{const c=g.useRef(null),[d,l]=g.useState();g.useEffect(()=>{const h=e.addNamedEndpoint(n,{apiPath:i,fps:o,width:s,height:t,id:n});l(h)},[e]);const u=g.useCallback(h=>{if(c.current&&r){const p=c.current.getContext("2d");p&&Cm({ctx:p,format:"base64",dataString:h,height:t,width:s,pixelSize:ho})}},[s,t,r]);return g.useEffect(()=>{d&&(d.onFrame=u,d.width=s,d.height=t,d.fps=o)},[d,u,s,t,o]),r&&En.createPortal(M.jsx(Pm,{children:M.jsx(km,{children:M.jsx("canvas",{ref:c,width:s*ho,height:t*ho,style:{border:"1px solid black"}})})}),document.body)}),Lm=Dm(hd),Pm=Po.div`
|
|
148
|
+
display: flex;
|
|
149
|
+
flex-direction: column;
|
|
150
|
+
gap: 8px;
|
|
151
|
+
|
|
152
|
+
width: 100%;
|
|
153
|
+
justify-content: space-between;
|
|
154
|
+
align-items: center;
|
|
155
|
+
`,km=Po.div`
|
|
156
|
+
display: flex;
|
|
157
|
+
flex-direction: column;
|
|
158
|
+
align-items: center;
|
|
159
|
+
`,gd=()=>{const e=Rs.type;return B({modelId:e,modelType:Rs.type,options:{}})};function xm(e){return t=>{const{model:s,status:o,KosModelLoader:r}=gd();return M.jsx(r,{...o,children:M.jsx(e,{...t,device:s})})}}function Fm(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 Bo(o)}function Nm(e){return t=>{const{model:s,status:o,KosModelLoader:r}=Cr();return M.jsx(r,{...o,children:M.jsx(e,{...t,kosTime:s})})}}const fd=()=>{const e=Ut.type;return B({modelId:e,modelType:Ut.type,options:{}})};function Um(e){return t=>{const{model:s,status:o,KosModelLoader:r}=fd();return M.jsx(r,{...o,children:M.jsx(e,{...t,networkInterfaceContainer:s})})}}const pd=()=>{const e=Es.type;return B({modelId:e,modelType:Es.type,options:{}})};function jm(e){return t=>{const{model:s,status:o,KosModelLoader:r}=pd();return M.jsx(r,{...o,children:M.jsx(e,{...t,oTA:s})})}}function Bm(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 Km(e){const t=g.useRef(null),s=e.onAlert;return Bm(t,s),M.jsx("div",{ref:t,style:{width:"100%"},children:e.children})}const Gm=e=>{var l;const{stateProp:t}=e,[s,o]=g.useState((l=e.stateProp)==null?void 0:l.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(p){c(p.message)}}u(t)},[t]),g.useEffect(()=>{const u=F(()=>{t&&r&&o(t.value)});return()=>{u()}},[r,t]),[s,{ready:r,error:i}]},md=()=>{const[e,t]=g.useState(!1),[s,o]=g.useState([]),r=We.type,n=B({modelId:r,modelType:We.type,options:{}});return g.useEffect(()=>{const i=F(()=>{var c,d;t(((c=n.model)==null?void 0:c.isStorageInserted)??!1),o(((d=n.model)==null?void 0:d.data)??[])});return()=>{i()}},[n.model]),{...n,inserted:e,devices:s}};function Hm(e){return t=>{const{model:s,status:o,KosModelLoader:r}=md();return M.jsx(r,{...o,children:M.jsx(e,{...t,storageDeviceContainer:s})})}}const Vm=({timerName:e,onTimerExpired:t,timerEventActions:s,autoStart:o})=>{const r=zc.getTimer(e);return g.useEffect(()=>{const n=j(Dr,i=>{const{name:c,action:d,remainingTime:l}=i==null?void 0:i.body;c===e&&r&&(d===Sr?t({name:c,action:d,remainingTime:l,timer:r}):s!=null&&s[d]&&s[d]({name:c,action:d,remainingTime:l,timer:r}))});return o&&(r==null||r.start()),()=>{n.unsubscribe()}},[o,t,r,s,e]),{timer:r,start:r==null?void 0:r.start.bind(r),reset:r==null?void 0:r.reset.bind(r),pause:r==null?void 0:r.pause.bind(r)}},Ym=e=>{const t=/[\\^$.*+?()[\]{}|]/g;return RegExp(t.source).test(e)?e.replace(t,"\\$&"):e},zm=e=>e instanceof RegExp,qm=e=>typeof e=="string",Wm=(e,t,s)=>{if(e===""||t==="")return e;let o=t;zm(o)||(o=new RegExp("("+Ym(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},yd=(e,t,s)=>{let o=e;return Array.isArray(o)||(o=[o]),o.flatMap(r=>qm(r)?Wm(r,t,s):r)};function Zm(e,t){let s=e;return Object.entries(t).forEach(([o,r])=>{const n=new RegExp(`<${o}>(.*?)</${o}>|<${o}/>`,"g");s=yd(s,n,(i,c)=>r.type==="br"?M.jsx("br",{}):g.cloneElement(r,{key:`${o}-${c}`},i))}),s}const Jm=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}),d=Zm(c,r||{});return M.jsx("span",{className:e.className,children:d})},Ue=new Map;function Qm(e,t){if(Ue.has(e)){const s=Ue.get(e);if(s.status==="finished")return s.result;throw s.promise}else{const s=t().then(r=>{Ue.set(e,{status:"finished",result:r})},r=>{throw Ue.set(e,{status:"error",error:r}),r}),o={status:"pending",promise:s};throw Ue.set(e,o),s}}function Co(e,t){return Qm(e,t)}const Xm=async()=>{const e=await Fi(ge.type);return await J(e.model),e.model},ey=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),Ue.set(r,{status:"finished",result:n})}return o},ty=(e,t)=>{const s=[e].flat(),[o,...r]=s,n=Co(ge.type,Xm),i=s.join("__"),c=Co(i,()=>ey(n,o,r)),d=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 p=t!=null&&t.keyPrefix?`${t.keyPrefix}.${u}`:u;return c?c.resolveKey(p,h):(f.debug(`Translation model ${e} not ready for key: ${p}`),p)},[t==null?void 0:t.keyPrefix,e,c]),i18n:d}},bd=()=>{const e=ge.type;return B({modelId:e,modelType:ge.type,options:{}})};function sy(e){return t=>{const{model:s,status:o,KosModelLoader:r}=bd();return M.jsx(r,{...o,children:M.jsx(e,{...t,translationContainer:s})})}}const oy=e=>B({modelId:e,modelType:xt.type}),xr=()=>B({modelId:Ye.type,modelType:Ye.type,options:{}}),ry=({troubleType:e,condition:t})=>{const{model:s}=xr(),[o,r]=g.useState(!1),[n,i]=g.useState([]),c=g.useCallback(()=>{var d,l;return n.length>0&&((d=n[0])!=null&&d.resolvable)?(l=n[0])==null?void 0:l.resolve():Promise.resolve(void 0)},[n]);return g.useEffect(()=>F(()=>{const l=(e?s==null?void 0:s.troubles.getIndexByKey("byType",e):s==null?void 0:s.troubles.data)||[],u=t?l.filter(t):l;r(u.length>0),i(u)}),[t,s,e]),[o,c,n.length>0?n[0]:void 0,n]};function ny(e){return t=>{const{model:s,status:o,KosModelLoader:r}=xr();return M.jsx(r,{...o,children:M.jsx(e,{...t,troubleContainer:s})})}}const vd=()=>{const e=Bt.type,t=B({modelId:e,modelType:Bt.type,options:{},activate:!0,destroyOnUnmount:!0}),[s,o]=g.useState(!1),[r,n]=g.useState(!1),[i,c]=g.useState([]);return g.useEffect(()=>{const d=F(()=>{var l,u,h;o(((l=t.model)==null?void 0:l.isUsbInserted)??!1),n(((u=t.model)==null?void 0:u.hasAvailableUpdates)??!1),c(((h=t.model)==null?void 0:h.data)??[])});return()=>{d()}},[t.model]),{...t,inserted:s,updateAvailable:r,updates:i}};function iy(e){return t=>{const{model:s,status:o,KosModelLoader:r}=vd();return M.jsx(r,{...o,children:M.jsx(e,{...t,usbUpdateContainer:s})})}}const ay=({path:e,propKey:t})=>{const{status:s}=B({modelType:At.type,modelId:e,options:{path:e}}),[o,r]=g.useState(!1),[n,i]=g.useState(),[c,d]=g.useState(""),[l,u]=g.useState(),h=p=>{n&&t&&n.updateProperty(t,p)};return g.useEffect(()=>{var p;s.model&&i(s.model),s.model&&t&&((p=s.model)!=null&&p.props.has(t)?d(s.model.props[t]):u(`property ${t} not found`)),s.ready&&r(s.ready)},[s.ready,s.model,t]),g.useEffect(()=>{t&&v.autorun(()=>{const p=n==null?void 0:n.props[t];d(p||"")})},[n,t]),{config:n,ready:o,value:c,error:l,updateValue:h}},cy=(e,t)=>{switch(t.type){case"UPDATE":return t.payload;default:return e}},wd=({configProperty:e,optionsTransformer:t})=>{const[s,o]=g.useState(!1),[r,n]=g.useState(""),[i,c]=g.useReducer(cy,{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}),d=g.useCallback(l=>{var h;let u="factory";typeof l=="string"?u=l:(h=l==null?void 0:l.target)!=null&&h.value&&(u=l.target.value),u&&(e==null||e.updateProperty(u))},[e]);return g.useEffect(()=>{async function l(u){try{u&&(await J(u),o(!0))}catch(h){n(h.message)}}l(e)},[e]),g.useEffect(()=>{const l=F(()=>{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()=>{l()}},[e,t,s]),{...i,configSelectProps:{onChange:d,value:i.value,options:t?i.mappedOptions||[]:i.options||[]},ready:s,error:r}};function dy(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 ly(e,t){return new Date(e,t,0).getDate()}function Md(e,t){const s=dy(t,e),o=[];for(let r=1;r<=s;r++)o.push(r);return o}function _d(){return[...Array(12).keys()].map(t=>new Date(0,t).getMonth())}function Ed(e=[2018,2028]){const t=[];for(let s=e[0];s<=e[1];s++)t.push(s);return t}function Id(e,t=[2018,2028]){const s=Ed(t);return e==="long"?s:s.map(o=>Number(o.toString().substring(2)))}function Fr(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 uy({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),d=new Intl.DateTimeFormat(e,{month:r.month}).format(c),l=new Intl.DateTimeFormat(e,{year:r.year}).format(c),u=new Intl.DateTimeFormat(e,{day:r.day}).format(c);return n?n=="MMDDYY"?`${d} ${u} ${l}`:n==="DDMMYY"?`${u} ${d} ${l}`:n==="YYMMDD"?`${l} ${d} ${u}`:`${l} ${u} ${d}`: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 hy(e){return typeof e=="string"?new Date(Date.parse(`01 ${e.substring(0,3)} 2023`)).getMonth()+1:e}function Td(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 bt(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 vt(e,t){return new Date(e,t,0).getDate()}function $d(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 Od({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 d=Nr(n,o),l=Dd(n,o,e),u=Sd(i,e),h=Ad(i,e),p=Ur(t,s),w=Cd(t,s,e,r),b=Pd(s,t,w),_=Rd(e,c);return{daysArray:p,monthsArray:u,yearsArray:d,yearsOptionsArray:l,monthsOptionsArray:h,daysOptionsArray:w,calendarDayArray:b,dayNamesArray:_}}function Nr(e="long",t=[2018,2028]){return g.useMemo(()=>Id(e,t),[e,t])}function Dd(e="long",t=[2018,2028],s="en-US"){const o=Nr(e,t);return g.useMemo(()=>o.map(n=>({label:n.toLocaleString(s).replace(",",""),value:n})),[s,o])}function Sd(e,t="en-US"){return g.useMemo(()=>Fr(e,t),[e,t])}function Ad(e,t="en-US"){const s=g.useMemo(()=>_d(),[]),o=g.useMemo(()=>Fr(e,t),[e,t]);return g.useMemo(()=>[...Array(12).keys()].map(n=>({label:o[n],value:Number(s[n])})),[o,s])}function Ur(e,t){const s=oe(e);return g.useMemo(()=>Md(s,t),[t,s])}const gy=(e,t,s,o=[])=>{const r=new Date(e,t,s).getDay();return o.length>0&&o.includes(r)};function Cd(e,t,s="en-US",o=[]){const r=Ur(e,t);return g.useMemo(()=>r.map(i=>({label:i.toLocaleString(s),value:i,disabled:gy(e,t,i,o)})),[o,s,t,r,e])}function Rd(e="en-US",t="short"){return g.useMemo(()=>$d(e,t),[e,t])}function Ld({year:e=new Date().getFullYear(),month:t=new Date().getMonth(),day:s=new Date().getDate(),formatString:o}){const r=t,n=new Date(e,r,s);return{formattedDate:me.format(n,o)}}function Pd(e,t,s){return g.useMemo(()=>Td(e,t,s),[e,t,s])}var kd=(e=>(e.MMDDYY="MMDDYY",e.DDMMYY="DDMMYY",e.YYMMDD="YYMMDD",e.YYDDMM="YYDDMM",e))(kd||{});function fy({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:d=[2018,2028],daysOfWeekFilter:l=[]}={}}){const[u,h]=g.useState(t),[p,w]=g.useState(d),[b,_]=g.useState(s),[I,A]=g.useState(o);g.useEffect(()=>{h(t)},[t]),g.useEffect(()=>{_(s)},[s]),g.useEffect(()=>{A(o)},[o]);const{yearsArray:se,yearsOptionsArray:we,monthsArray:rt,monthsOptionsArray:Zs,daysArray:Q,daysOptionsArray:Me,calendarDayArray:Js,dayNamesArray:Qs}=Od({locale:e,year:u,yearRange:p,month:b,formatOptions:{yearFormat:r,monthFormat:n,dayFormat:i},daysOfWeekFilter:l}),{formattedDate:Xs}=Ld({year:u,month:b,day:I,formatString:c});return{dateActions:{setYear:h,setYearRange:w,setMonth:_,setDay:A,nextMonth:()=>{const K=b<11?oe(u):oe(u+1),W=b<11?b+1:0;if(!bt(K,W,I)){const _e=vt(K,W);A(_e)}W===0&&h(K),_(W)},previousMonth:()=>{const K=oe(b===0?u-1:u),W=b===0?11:b-1;if(!bt(K,W,I)){const _e=vt(K,W);A(_e)}W===11&&h(K),_(W)},nextYear:()=>{const K=u<p[1]?u+1:p[0],W=oe(K);if(bt(W,b,I))h(K);else{const _e=vt(oe(u+1),b);A(_e),h(K)}},previousYear:()=>{const K=u>p[0]?u-1:p[0],W=oe(K);if(bt(W,b,I))h(K);else{const _e=vt(oe(u-1),b);A(_e),h(K)}}},dateState:{year:u,yearRange:p,month:b,day:I,yearsArray:se,yearsOptionsArray:we,monthsArray:rt,monthsOptionsArray:Zs,daysArray:Q,daysOptionsArray:Me,calendarDayNames:Qs,calendarDayArray:Js,formattedDate:Xs}}}function xd({date:e=new Date,dateFormat:t,timeFormat:s,options:o={}}){const[r,n]=g.useState("Formatting Time..."),[i,c]=g.useState("Formatting Date..."),d=!!o.ignoreDateFormat,{model:l,ready:u}=B({modelId:z.type,modelType:z.type,options:{}}),h=typeof e=="string"?me.parseISO(e):e;return g.useEffect(()=>{d?c(""):t?c(me.format(h,t)):u&&c(me.format(h,l!=null&&l.selectedDateFormat?l==null?void 0:l.selectedDateFormat:""))},[d,e,t,h,l,u]),g.useEffect(()=>{s?n(me.format(h,s)):u&&n(me.format(h,l!=null&&l.selectedTimeFormat?l==null?void 0:l.selectedTimeFormat:""))},[e,s,h,l,u]),{formattedDate:i,formattedTime:r}}const Fd=({secondsFromMidnight:e=0})=>{const[t,s]=g.useState(0),[o,r]=g.useState(0),[n,i]=g.useState(0),[c,d]=g.useState(new Date),{formattedTime:l}=xd({date:c,options:{ignoreDateFormat:!0}});return g.useEffect(()=>{const u=Number(e),h=Math.floor(u/3600),p=Math.floor(u%3600/60),w=u%60;s(h),r(p),i(w);const b=new Date;b.setHours(0,0,0,0);const _=new Date(b.getTime()+u*1e3);d(new Date(_))},[e]),{hours:t,minutes:o,seconds:n,formattedTime:l,timeActions:{setHours:s,setMinutes:r,setSeconds:i}}},py=({configProperty:e})=>{const{value:t}=wd({configProperty:e}),s=parseInt(t||"0",10),{hours:o,minutes:r,seconds:n,formattedTime:i,timeActions:c}=Fd({secondsFromMidnight:s}),d=g.useRef();return g.useEffect(()=>{const l=o*3600+r*60+n;return d.current&&clearTimeout(d.current),d.current=setTimeout(()=>{e&&e.updateProperty(l.toString())},100),()=>{d.current&&clearTimeout(d.current)}},[e,o,r,n]),{hours:o,minutes:r,seconds:n,formattedTime:i,timeActions:c}};function my(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 yy=e=>M.jsx("option",{title:e.id,value:e.format,children:e.format},e.id),by=(e=yy)=>{const[t,s]=g.useState([]),[o,r]=g.useState(),{model:n,ready:i}=B({modelType:z.type,modelId:z.type,options:{}});g.useEffect(()=>{const d=F(()=>{s((n==null?void 0:n.dateFormatOptions.map(e))||[])});return()=>{d()}},[n,i,e]),g.useEffect(()=>{const d=F(()=>{n!=null&&n.dateFormatId&&(n!=null&&n.selectedDateFormat)&&r({id:n==null?void 0:n.dateFormatId,value:n==null?void 0:n.selectedDateFormat})});return()=>{d()}},[n==null?void 0:n.selectedDateFormat,n==null?void 0:n.dateFormatId]);const c=g.useCallback(d=>{var u;let l="";typeof d=="string"?l=d:(u=d==null?void 0:d.target)!=null&&u.value&&(l=d.target.value),l&&(n==null||n.setSelectedDateFormat(l))},[n]);return{raw:(n==null?void 0:n.dateFormatOptions.map(d=>d.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}}},vy=e=>M.jsx("option",{title:e,value:e,children:e},e),Nd="kos:service:region:settings",Ud="timeZone",wy=`${Nd}-${Ud}`,My=(e=vy)=>{const[t,s]=g.useState([]),[o,r]=g.useState(""),{model:n,ready:i}=B({modelType:z.type,modelId:z.type,options:{}}),c=Ce.factory(wy)({path:Nd,attribute:Ud});g.useEffect(()=>{const l=F(()=>{s((n==null?void 0:n.timeZones.map(e))||[]),n!=null&&n.timeZones.length&&Ao(n==null?void 0:n.timeZones[0])});return()=>{l()}},[n,i,e]),g.useEffect(()=>{const l=F(()=>{r(c.value||"")});return()=>{l()}},[c.value]);const d=g.useCallback(l=>{var h;let u="factory";typeof l=="string"?u=l:(h=l==null?void 0:l.target)!=null&&h.value&&(u=l.target.value),u&&Ao(u)},[]);return{options:t,raw:(n==null?void 0:n.timeZones)??[],regionModel:n,selectedTimeZone:o,timeZones:(n==null?void 0:n.timeZones)??[],updateTimeZone:d,selectProps:{onChange:d,value:o,options:t}}},jd="kos:service:region",Bd="regionId",_y=`${jd}-${Bd}`,Ey=e=>M.jsx("option",{title:e,value:e,children:e},e),Kd=(e=Ey)=>{const[t,s]=g.useState([]),[o,r]=g.useState("factory"),{model:n,ready:i}=B({modelType:z.type,modelId:z.type,options:{}}),c=Ce.factory(_y)({path:jd,attribute:Bd});g.useEffect(()=>{const l=F(()=>{s((n==null?void 0:n.availableRegions.map(e))||[])});return()=>{l()}},[n,i,e]),g.useEffect(()=>{const l=F(()=>{r(c.value||"factory")});return()=>{l()}},[c.value]);const d=g.useCallback(l=>{var h;let u="factory";typeof l=="string"?u=l:(h=l==null?void 0:l.target)!=null&&h.value&&(u=l.target.value),u&&Vc(u)},[]);return{raw:(n==null?void 0:n.availableRegions)??[],regionModel:n,regionData:n==null?void 0:n.selectedRegion,selectedRegion:o,updateRegion:d,regionSelectProps:{onChange:d,value:o,options:t}}},Iy=e=>M.jsx("option",{title:e.id,value:e.format,children:e.format},e.id),Ty=(e=Iy)=>{const[t,s]=g.useState([]),[o,r]=g.useState(),{model:n,ready:i}=B({modelType:z.type,modelId:z.type,options:{}});g.useEffect(()=>{const d=F(()=>{s((n==null?void 0:n.timeFormatOptions.map(e))||[])});return()=>{d()}},[n,i,e]),g.useEffect(()=>{const d=F(()=>{n!=null&&n.timeFormatId&&(n!=null&&n.selectedTimeFormat)&&r({id:n==null?void 0:n.timeFormatId,value:n==null?void 0:n.selectedTimeFormat})});return()=>{d()}},[n==null?void 0:n.selectedTimeFormat,n==null?void 0:n.timeFormatId]);const c=g.useCallback(d=>{var u;let l="";typeof d=="string"?l=d:(u=d==null?void 0:d.target)!=null&&u.value&&(l=d.target.value),l&&(n==null||n.setSelectedTimeFormat(l))},[n]);return{raw:(n==null?void 0:n.timeFormatOptions.map(d=>d.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}}},$y=(e,t)=>g.useMemo(()=>Xo(e),t),Oy={config:{attributes:!0,childList:!0,subtree:!0}};function Dy(e,t,s=Oy){const[o,r]=g.useState(null);g.useEffect(()=>{if(!t||typeof t!="function")throw new Error("A valid callback function is required");const n=new MutationObserver(t);r(n)},[t,s,r]),g.useEffect(()=>{if(!o)return()=>{};if(!e)throw new Error("A valid DOM element is required");const{config:n}=s;try{o.observe(e,n)}catch(i){f.error(i)}return()=>{o&&o.disconnect()}},[o,e,s])}const Gd={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}},go=f.createLogger({name:"usePressGesture",group:"kos-hooks"});function Sy({onPressed:e,onRelease:t,intersectionStrategy:s=Gd}){const o=g.useRef(!1),r=el.useGesture({onDragStart:d=>{go.info("onDragStart",d.type),s.validateStart(d)&&(e&&e(),o.current=!0)},onDrag:d=>{go.info("onDrag",d.type),o.current&&s.validateStop(d)&&(t&&t(),o.current=!1)},onDragEnd:d=>{go.info("onDragEnd",d.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 Hd=()=>{const[e,t]=g.useState(!1),s=E.getInstance();return g.useEffect(()=>{const o=F(()=>{s&&s.reloading!==e&&t(s.reloading)});return()=>{o()}},[s,e]),[e]};function Vd(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 Ro(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 Yd(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 zd({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=Vd(e,t),i=Ro(60,s),c=Ro(60,o),d=Yd(r);return{hourOptions:n,minuteOptions:i,secondOptions:c,amPmOptions:d}}function qd(e,t){return me.format(e,t)}function Wd({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 A=new Date(I);return A.setHours(Number(_)),A})},[]),c=g.useCallback(_=>{n(I=>{const A=new Date(I);return A.setMinutes(Number(_)),A})},[]),d=g.useCallback(_=>{n(I=>{const A=new Date(I);return A.setSeconds(Number(_)),A})},[]),l=g.useCallback(_=>{const I=new Date(_);n(I)},[]),u=qd(r,o),{hourOptions:h,minuteOptions:p,secondOptions:w,amPmOptions:b}=zd({formatOptions:e,locale:s});return{amPmOptions:b,formattedTime:u,hourOptions:h,minuteOptions:p,secondOptions:w,setHours:i,setMinutes:c,setSeconds:d,setTime:l,time:new Date(r)}}const Ay=e=>{const{regionModel:t}=Kd(),s=g.useMemo(()=>({hour12:t==null?void 0:t.is12HourTimeFormat}),[t==null?void 0:t.is12HourTimeFormat]);return Wd({...e,locale:t==null?void 0:t.regionId,format:t==null?void 0:t.selectedTimeFormat,formatOptions:s})};function Cy(e){return t=>{const[s]=Hd();return s?M.jsx(ed,{message:"Wait a moment while your project reloads..."}):M.jsx(e,{...t})}}const wn=f.createLogger({name:"studio-properties-service",group:"Services"}),Ry="/api/kos/studio/properties",Zd=async e=>{if(wn.debug("sending GET for studio-properties"),!e)throw wn.error("connectionId is undefined"),new Error("connectionId is undefined");return await Re.get(Ry,{},{destinationAddress:e,timeout:500})},Ly=Object.freeze(Object.defineProperty({__proto__:null,getStudioProperties:Zd},Symbol.toStringTag,{value:"Module"}));var Py=Object.defineProperty,ky=Object.getOwnPropertyDescriptor,xy=(e,t,s,o)=>{for(var r=o>1?void 0:o?ky(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&&Py(t,s,r),r};const Jd="studio-properties-model",Fy="/kos/studio/properties",Mn={"kos.studio.tool.legacy":1};let Lo=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=ye(),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=Ht.getInstance().subscribeTopic({topic:Fy,destinationAddress:this.connectionId,callback:s=>{this.logger.error(`Received studio-properties message for connection ${this.connectionId}: ${JSON.stringify(s)}`)}});const[e,t]=await Zd(this.connectionId);if(e){this.logger.error(`Error loading studio-properties: ${e}`),this.data.setValues(Mn);return}if(t){const s=Object.keys(t).reduce((o,r)=>(o[r]=t[r]??r,o),{});this.data.setValues(s??Mn),f.ifDebug(()=>this.logger.debug(`studio-properties loaded: ${JSON.stringify(s)}`))}}get(e){return this.data[e]}createObservableProperty(e){return Xo(()=>this.get(e))}};Lo=xy([O(Jd)],Lo);const Ny=new ae({class:Lo,type:Jd});Object.defineProperty(exports,"makeAutoObservable",{enumerable:!0,get:()=>v.makeAutoObservable});Object.defineProperty(exports,"makeObservable",{enumerable:!0,get:()=>v.makeObservable});Object.defineProperty(exports,"kosComponent",{enumerable:!0,get:()=>ko.observer});exports.AuthState=Gi;exports.BrowserKosRouter=Xi;exports.BrowserRouter=Ks;exports.CanvasDispatcher=qe;exports.CanvasDispatcherServices=qf;exports.CanvasRenderer=wr;exports.CanvasStreamer=Lm;exports.CanvasStreamerBase=hd;exports.ChildModels=Mt;exports.ConfigBean=At;exports.CoreExtensionManager=Np;exports.CoreModels=Or;exports.CreateModelTranslationsContext=ad;exports.CreateModelTranslationsProvider=lm;exports.DateDisplayFormat=kd;exports.DateHelpers=hl;exports.DependencyLifecycle=x;exports.DependencyModels=P;exports.Device=Rs;exports.DeviceServices=ip;exports.DomIntersectionStrategy=Gd;exports.EVENT_KOS_MODEL_READY=Uo;exports.EVENT_TROUBLE_ADDED=Eh;exports.EVENT_TROUBLE_REMOVED=Ih;exports.EXTENSION_TROUBLE_DATA_MAPPER=Ms;exports.EXTENSION_TROUBLE_MAPPER=Wt;exports.ErrorBoundaryWithFallback=td;exports.EventBus=rl;exports.ExtensionManager=C;exports.FUTURE_CONTAINER_MODEL_TYPE=Oa;exports.FUTURE_MODEL_TYPE=ya;exports.FUTURE_NOT_ASSIGNED=tr;exports.FeatureFlagService=Bn;exports.FetchError=ce;exports.FutureContainerFactory=be;exports.FutureContainerModel=Sa;exports.FutureEndState=Ge;exports.FutureFactory=st;exports.FutureHandler=ar;exports.FutureManager=De;exports.FutureModel=Ea;exports.FutureService=wt;exports.HEADER_CACHE_CONTROL=On;exports.HEADER_CONTENT_TYPE=$n;exports.HEADER_DESTINATION_ADDR=fe;exports.HEADER_FOS_REQUEST_ID=Dn;exports.HEADER_METHOD=xs;exports.HEADER_ORDERED=Fo;exports.HEADER_REQUEST_ID=Kt;exports.HEADER_REQUEST_TYPE=de;exports.HEADER_RESPONSE_ID=Fs;exports.HEADER_SOURCE_ADDR=Tn;exports.HEADER_TOPIC=In;exports.HEADER_URL=Je;exports.HEADER_WORK_TRACKER=No;exports.KOS_MODEL_ID=hs;exports.KeyValue=gr;exports.KeyValueServices=bg;exports.Kos=H;exports.KosConfigPropertySpec=Ce;exports.KosContainerIndex=Qo;exports.KosContextBean=Zi;exports.KosContextManager=k;exports.KosCore=E;exports.KosCoreModelPropertyMapper=re;exports.KosDataContainer=Ji;exports.KosDependencyTypes=Dl;exports.KosExtensionUtils=Ou;exports.KosFeatureFlags=gl;exports.KosFetchMethods=vi;exports.KosGlobalConfig=Vo;exports.KosLog=f;exports.KosMockEvents=Cn;exports.KosModel=Ri;exports.KosModelCollectionProvider=nm;exports.KosModelContainer=le;exports.KosModelContext=qs;exports.KosModelEvents=D;exports.KosModelFactory=$t;exports.KosModelLoader=nd;exports.KosModelLoaderDisplay=id;exports.KosModelManager=ki;exports.KosModelProvider=sd;exports.KosModelRegistrationFactory=ae;exports.KosModelRegistry=So;exports.KosModelState=y;exports.KosModelSymbol=ii;exports.KosModelVisitor=Ju;exports.KosObservableData=Yi;exports.KosRegistration=vh;exports.KosSingletonRegistration=wh;exports.KosTime=bs;exports.KosTimeContext=Rr;exports.KosTimeProvider=bm;exports.KosTimeServices=_g;exports.KosTimer=Yc;exports.KosToken=Qi;exports.KosTranslationProvider=Tm;exports.KosTranslations=yc;exports.KosWSTransportStatus=Ci;exports.KosWsEvents=Gt;exports.LOGIN_HOST=Sn;exports.LOGIN_URL=tl;exports.LoadingMessage=ed;exports.LogBlock=kt;exports.LogBlockContainer=Hs;exports.LogConfig=Et;exports.LogStream=Dt;exports.LogStreamContainer=qt;exports.LogStreamServices=Lg;exports.MODEL_DELETION_DELAY=Pi;exports.MiddlewareChain=Vi;exports.ModelEffects=$e;exports.MultipleFutureHandler=Zh;exports.NestedModelContext=Ws;exports.NetworkInterface=Er;exports.NetworkInterfaceContainer=Ut;exports.NetworkInterfaceServices=mp;exports.ObservableData=ye;exports.Ota=Es;exports.OutsideAlerter=Km;exports.PLUGIN_EXTENSION_NAME=Du;exports.PORT=An;exports.PROFILE_LOG_DEBUG=Yn;exports.PROFILE_LOG_INFO=zn;exports.PROFILE_RELAX_STORE_VALIDATION=pl;exports.PROFILE_TOOLS_PREVIEW=Vn;exports.ParentModel=_t;exports.PluginExtensionManager=Su;exports.ProgressBar=tm;exports.ReferenceConfig=is;exports.RegionInfo=z;exports.RegionServices=Ph;exports.RegistrationManager=$;exports.Registry=xp;exports.STATUS=xo;exports.ServiceFactory=V;exports.SingletonKosModelRegistrationFactory=pe;exports.SoftwareInfo=Is;exports.SoftwareInfoContext=Pr;exports.SoftwareInfoProvider=Mm;exports.SoftwareInfoServices=ff;exports.StateBean=Ft;exports.StateBeanServices=wf;exports.StateProp=mr;exports.StatePropServices=Af;exports.StorageDevice=Ps;exports.StorageDeviceContainer=We;exports.StorageDeviceServices=Mp;exports.StudioProperties=Ny;exports.StudioPropertiesServices=Ly;exports.SubscriptionHandlers=G;exports.TIMER_END=Sr;exports.TIMER_EVENT=Dr;exports.TimerManager=zc;exports.TokenContext=ud;exports.TokenProvider=Em;exports.Topics=Ot;exports.Trans=Jm;exports.TransitionMap=as;exports.Transitions=zo;exports.Translation=Os;exports.TranslationContainer=ge;exports.TranslationContainerContext=kr;exports.TranslationContext=Bf;exports.TransportFactory=vo;exports.Trouble=xt;exports.TroubleContainer=Ye;exports.TroubleServices=Xg;exports.Troubles=X;exports.UsbUpdate=$r;exports.UsbUpdateContainer=Bt;exports.UsbUpdateServices=Ap;exports.WS_EVENT_TYPE=bc;exports.WebSocketEvents=Tt;exports.WebSocketTransport=Ht;exports.WsEventFactory=br;exports.acceptOrgInvitation=Xc;exports.addDaysToDate=Pn;exports.addFuture=va;exports.addMonthsToDate=Ln;exports.api=Ia;exports.applyMixins=il;exports.arraysEqual=al;exports.buildConfigBeanModel=Oh;exports.buildFuture=lr;exports.buildFutureModel=Ma;exports.cancelFuture=wa;exports.convert=ma;exports.convertFileSizeRaw=nl;exports.createBaseMessage=_i;exports.createBroadcastMessageResponse=$i;exports.createClient=Zo;exports.createFosBaseMessage=Mi;exports.createHeaders=mo;exports.createKosHtpMessageResponse=Oi;exports.createKosMessage=Ii;exports.createKosMessageResponse=Di;exports.createMessageBody=ve;exports.createModelDependency=fi;exports.createOptionKey=Sl;exports.createPropKey=Se;exports.createReadableStream=yo;exports.createStudioMessage=wi;exports.createStudioMessageRequest=Ei;exports.createStudioMessageResponse=Ti;exports.debounce=jn;exports.deleteFuture=ba;exports.destroyKosModel=Oe;exports.evaluateScopes=ia;exports.executeChildrenModelLifecycle=yi;exports.executeDependentModelLifecycle=ct;exports.executeListLifecycle=mi;exports.fetchModel=Fm;exports.findModel=Lu;exports.findModels=Ni;exports.formatDate=Fn;exports.formatDateSince=Rn;exports.formatDateTime=Un;exports.formatTime=Nn;exports.getAllKosCompanionModels=ku;exports.getCalendarMonthArray=Td;exports.getConfigBean=na;exports.getDayStrings=$d;exports.getDays=ly;exports.getDaysArray=Md;exports.getDaysInMonth=Ho;exports.getDependenciesByLifecycle=pi;exports.getFormattedDate=uy;exports.getFormattedMonth=hy;exports.getFormattedMonthsArray=Fr;exports.getFormattedYear=oe;exports.getFormattedYearsArray=Id;exports.getFutures=og;exports.getKosCompanionModel=Pu;exports.getKosLocalizationDescriptor=hc;exports.getKosMessageLogging=Qn;exports.getKosModel=Fi;exports.getKosModelSync=Xe;exports.getKosModelType=Ru;exports.getKosSessionKey=Wi;exports.getLastDayOfMonth=vt;exports.getLocalizationDescriptor=Rf;exports.getLogLevel=Jn;exports.getLogMessageToStudio=Xn;exports.getMessageBody=bo;exports.getMonthsArray=_d;exports.getObservableCompanions=xu;exports.getQueryParams=ee;exports.getTranslations=uc;exports.getYearsArray=Ed;exports.hasDecimals=oa;exports.hasKosProfile=fo;exports.hslStringToHex=Gn;exports.hslToHex=Kn;exports.initKosProvider=hm;exports.isBoolean=or;exports.isKosCompanionTypeFactory=Li;exports.isKosDataModel=It;exports.isKosLoggingEnabled=bl;exports.isKosModel=te;exports.isKosModelContainer=qo;exports.isKosModelReady=fs;exports.isLeapYear=Go;exports.isLocalRefId=gh;exports.isNumber=Us;exports.isPrintable=Hl;exports.isValidDate=bt;exports.kosAction=Y;exports.kosAutoEffect=F;exports.kosChild=ie;exports.kosCompanion=Fl;exports.kosComputed=Xo;exports.kosConfigBean=js;exports.kosConfigProperty=Wh;exports.kosContext=Nl;exports.kosDependency=Ae;exports.kosEffect=ta;exports.kosFuture=Ar;exports.kosLogger=Ul;exports.kosModel=O;exports.kosModelEffect=ai;exports.kosObservable=er;exports.kosParentAware=Ns;exports.kosReference=jl;exports.kosStateBean=Hp;exports.kosStateProp=Vp;exports.kosSubscribe=Bl;exports.kosTopicHandler=R;exports.kosWhen=Mo;exports.login=Zc;exports.mapConfigBeanModelToDto=la;exports.mapDataToModel=po;exports.mapDtoToConfigBeanModel=ca;exports.mapDtoToFutureModel=dr;exports.mapDtoToFutureOptions=cr;exports.mapUpdateDtoToConfigBeanModel=da;exports.modelEventTopicFactory=ri;exports.modelFactory=et;exports.modelTypeEventTopicFactory=ni;exports.modifyConfigBean=ra;exports.modifyFuture=rg;exports.pairedClientHeartbeat=rh;exports.pipe=qi;exports.preloadKosModel=Uu;exports.processId=ul;exports.processMiddleware=eh;exports.registerCompanionModel=Nu;exports.registerCoreModels=Kc;exports.registerExtensionPoint=Yo;exports.registerKosModel=ji;exports.registerLegacyModel=Ui;exports.resetKosModel=xi;exports.resetPassword=Qc;exports.resolveBaseUrl=Hi;exports.resolveChild=bi;exports.resolveContainerDeltas=cl;exports.resolveItemListDeltas=ll;exports.resolveKosCompanion=wo;exports.resolveKosContext=mh;exports.resolveKosProfiles=Wn;exports.resolveListDeltas=dl;exports.resolveServiceUrl=q;exports.resolveVariable=Hn;exports.retryWithExponentialBackoff=ih;exports.sendAsyncIntent=_h;exports.sendBroadcastMessage=du;exports.sendIntent=Mh;exports.sendKosHttpMessageResponse=Ai;exports.sendKosMessage=iu;exports.sendKosMessageResponse=Si;exports.sendRequest=fh;exports.sendStudioMessage=cu;exports.sendStudioMessageRequest=au;exports.startPasswordReset=Jc;exports.stringComponentInsert=yd;exports.studioAcceptOrgInvitation=Wp;exports.studioLogin=Yp;exports.studioResetPassword=qp;exports.studioStartPasswordReset=zp;exports.subscribeStore=Up;exports.syncPublish=ph;exports.transitionToActive=li;exports.transitionToInit=gi;exports.transitionToLoad=hi;exports.transitionToReady=ui;exports.transitionToUnload=Gl;exports.troubleByTypeReducer=Kf;exports.troubleDataFactory=tc;exports.unloadKosModel=Cu;exports.updateCompanionModelRegistration=sh;exports.updateModelRegistration=th;exports.updateRegion=Vc;exports.updateTimeZone=Ao;exports.useAmPmValues=Yd;exports.useCalendarDayArray=Pd;exports.useConfigBean=ay;exports.useConfigProperty=wd;exports.useContextModel=om;exports.useContextModelHierarchy=rd;exports.useDateArrays=Od;exports.useDateProps=fy;exports.useDateRelativeConfig=py;exports.useDateRelativeData=Fd;exports.useDayNames=Rd;exports.useDayOptions=Cd;exports.useDays=Ur;exports.useDevice=gd;exports.useFormattedDate=Ld;exports.useFormattedTime=qd;exports.useFunctionWarmup=my;exports.useHourValues=Vd;exports.useKosCore=dd;exports.useKosDateFormats=by;exports.useKosModel=B;exports.useKosRegions=Kd;exports.useKosTime=Cr;exports.useKosTimeContext=vm;exports.useKosTimeFormats=Ty;exports.useKosTimeZones=My;exports.useKosTranslation=ty;exports.useKosTranslationContext=$m;exports.useLocalComputed=$y;exports.useModelFromHierarchy=am;exports.useMonths=Sd;exports.useMonthsOptions=Ad;exports.useMutationObserver=Dy;exports.useNetworkInterfaceContainer=fd;exports.useOta=pd;exports.usePressGesture=Sy;exports.useProjectReload=Hd;exports.useRegionTimeProps=Ay;exports.useRegionalTimeDate=xd;exports.useSoftwareInfo=Lr;exports.useSoftwareInfoContext=_m;exports.useStateProperty=Gm;exports.useStorageDeviceContainer=md;exports.useSuspenseData=Co;exports.useTimeOptions=zd;exports.useTimeProps=Wd;exports.useTimeValues=Ro;exports.useTimer=Vm;exports.useTranslationContainer=bd;exports.useTroubleContainerModel=xr;exports.useTroubleModel=oy;exports.useTroublePresence=ry;exports.useUsbUpdateContainer=vd;exports.useYears=Nr;exports.useYearsOptions=Dd;exports.uuid=Qe;exports.variableToHex=fl;exports.waitForRequest=Jo;exports.whenReady=J;exports.withDevice=xm;exports.withKosTime=Nm;exports.withNetworkInterfaceContainer=Um;exports.withOta=jm;exports.withProjectReloading=Cy;exports.withSoftwareInfo=wm;exports.withStorageDeviceContainer=Hm;exports.withTranslationContainer=sy;exports.withTroubleContainer=ny;exports.withUsbUpdateContainer=iy;exports.wrapPromise=Bo;
|
|
182
160
|
//# sourceMappingURL=index.cjs.map
|