@kosdev-code/kos-ui-sdk 2.0.2 → 2.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.cjs +52 -52
- package/index.cjs.map +1 -1
- package/index.js +1199 -1199
- package/index.js.map +1 -1
- package/package.json +2 -2
- package/ui/contexts/translation-container/kos-translations-provider.d.ts.map +1 -1
package/index.cjs
CHANGED
|
@@ -1,79 +1,79 @@
|
|
|
1
|
-
"use strict";var ul=Object.defineProperty;var hl=(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)=>(hl(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"),_=require("@emotion/react/jsx-runtime"),gl=require("@emotion/styled"),Ie=require("@emotion/react"),fl=require("react-dom"),g=require("react"),
|
|
1
|
+
"use strict";var ul=Object.defineProperty;var hl=(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)=>(hl(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"),_=require("@emotion/react/jsx-runtime"),gl=require("@emotion/styled"),Ie=require("@emotion/react"),fl=require("react-dom"),g=require("react"),Xr=require("mobx-react-lite"),ml=require("@use-gesture/react"),Rs="method",Jr="topic",qe="url",kt="request-id",Ls="response-id",Oo="status",ge="dst-addr",en="src-addr",ae="type",So="ordered",Do="tracker",tn="Content-Type",sn="Cache-Control",on="requestId",rn=process.env.KOS_LOGIN_URL||"http://localhost",nn=process.env.KOS_APP_PORT||"8080",pl=`${rn}:${nn}`,cs="{MODEL_ID}";var Pt=(e=>(e.SEND="/ws/log/msg/send",e.RECEIVED="/ws/log/msg/receive",e))(Pt||{}),an=(e=>(e.MSG_RECEIVE="/mock/msg/receive",e))(an||{});T.info("Initializing event bus");globalThis.kos=globalThis.kos||{};globalThis.kos.subscriptions=globalThis.kos.subscriptions||{};const k=globalThis.kos.subscriptions,yl=()=>Symbol("eventKey");function U(e,t){const s=yl();return k[e]||(T.debug(`Initializing subscription for ${e}`),k[e]={}),T.debug(`Subscribing to ${e} with id ${s.toString()}`),k[e][s]=t,{count:k[e]?Object.getOwnPropertySymbols(k[e]).length:0,unsubscribe:()=>(T.debug(`Unsubscribing from ${e} with id ${s.toString()}`),k[e]&&k[e][s]&&delete k[e][s],k[e]&&Object.getOwnPropertySymbols(k[e]).length===0&&delete k[e],{count:k[e]?Object.getOwnPropertySymbols(k[e]).length:0})}}function G(e,t,s={}){if(!k[e]||Object.getOwnPropertySymbols(k[e]).length===0)return T.debug(`No subscriptions for ${e}. Not publishing.`),{eventType:e,subscribers:0};const o=Object.getOwnPropertySymbols(k[e]).length;return Object.getOwnPropertySymbols(k[e]).forEach(r=>{if(s.sync){const n=s.sync;T.debug(`Performing sync publish for ${e} with sync id ${n}`),k[e][r]({body:t,headers:s}).then(i=>{T.debug(`Response recieved for ${n}, publishing back to source.`),G(n,i)})}else T.debug(`Performing async publish for ${e}`),k[e][r]({body:t,headers:s})}),{eventType:e,subscribers:o}}function bl(){T.warn("Resetting event bus"),Object.keys(k).forEach(e=>delete k[e])}const wl=Object.freeze(Object.defineProperty({__proto__:null,publish:G,reset:bl,subscribe:U},Symbol.toStringTag,{value:"Module"})),vl=(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 Co(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 Nt(){return"xxxxxxxx-xxxx-4xxx-2xxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){const t=Math.random()*16|0;return(e=="x"?t:t&3|8).toString(16)})}function Ml(e,t){t.forEach(s=>{Object.getOwnPropertyNames(s.prototype).forEach(o=>{const r=Object.getOwnPropertyDescriptor(s.prototype,o);Object.defineProperty(e.prototype,o,r)})})}const Ao=(e,t)=>{const s=e.map(n=>n.id);return t.map(n=>n.id).filter(n=>!s.includes(n))},_l=({container:e,onAddItem:t,onRemoveItem:s,idMapper:o=r=>r})=>r=>{const n=r.map(o),c=Ao(n,e.data).map(s).filter(Boolean);e.removeAll(c);const l=n.map(t).filter(Boolean);e.addAll(l)},El=({container:e,onAddItem:t,onRemoveItem:s,idMapper:o=r=>r})=>r=>{const n=r.map(o);Ao(n,e.models).forEach(s),n.forEach(t)},Il=({items:e,onAddItem:t,onRemoveItem:s,idMapper:o=r=>r})=>r=>{const n=r.map(o);Ao(n,e).forEach(s),n.forEach(t)},Tl=(e,t="parent-")=>{let s=e;return s.startsWith(t)&&(s=s.replace(t,"")),s},Er=new Intl.RelativeTimeFormat(void 0,{numeric:"auto"}),Ir=[{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 $l(e){let t=(e.getTime()-Date.now())/1e3;for(let s=0;s<=Ir.length;s++){const o=Ir[s];if(Math.abs(t)<o.amount)return Er.format(Math.round(t),o.name);t/=o.amount}return Er.format(Math.round(t),"years")}function cn(e,t,s=300){let o;return(...r)=>{clearTimeout(o),o=setTimeout(()=>{t.apply(e,r)},s)}}class ln{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 ln;const Ol=window.KosFeatureFlags,ce=(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),{}),dn=(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)}`},un=e=>{const s=new RegExp("hsl\\((\\d+),\\s+(\\d+)\\%,\\s+(\\d+)\\%\\)").exec(e);if(!s)throw Error("Invalid HSL string");return dn(parseInt(s[1]),parseInt(s[2]),parseInt(s[3]))},hn=(e,t)=>getComputedStyle(e).getPropertyValue(t),Sl=(e,t)=>un(hn(e,t)),gn="studio.tools.preview",Dl="studio.relax.store.validation",fn="studio.log.debug",mn="studio.log.info",Cl={profiles:[gn]};var Qr;const Al=((Qr=globalThis.getKosConfig)==null?void 0:Qr.call(globalThis))||JSON.stringify(Cl),pn=JSON.parse(Al);globalThis.kosConfig=pn;const Ro=pn,yn=()=>Ro.profiles||[],ao=e=>yn().includes(e),Rl=()=>Ro.logging||!1,Ll=(e,t)=>{const s={...e};return s.id&&delete s.id,s},co=(e,t,s=Ll)=>{const o=s(e,t);w.runInAction(()=>{Object.assign(t,o)})},Zs=new Map,Tr={addToDeletionQueue:(e,t)=>{const s=Zs.get(e)||[];s.push(t),Zs.set(e,s)},cancelDeletion:e=>{const t=Zs.get(e);t&&t.forEach(s=>{clearTimeout(s)})}},ee=Symbol("SubscriptionHandlers"),P=Symbol("DependencyModels"),Fe=Symbol("FutureService"),mt=Symbol("ChildModels"),pt=Symbol("ParentModel"),yt=Symbol("LogConfig"),ts=Symbol("ReferenceConfig"),bn=Symbol("KosModelSymbol"),bt=Symbol("ModelEffects"),Qs=new Map,$r=new Map,Xs=new Map,Js=new Map,Lo=(e,t)=>{wn[e]=t},wn={indexExtension:{registerIndexExtension:(e,t)=>{const s=Js.get(e)||{};Object.assign(s,t),Js.set(e,t)},loadIndexExtensions:e=>Js.get(e)||{}},loader:{registerLoader:(e,t)=>{$r.set(e,t)},executeLoader:async(e,t)=>{const s=$r.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}}},A=wn;var j=(e=>(e.INIT="init",e.LOAD="load",e.READY="ready",e.ACTIVATE="activate",e.ONLINE="online",e))(j||{});const xl=Object.freeze(Object.defineProperty({__proto__:null,DependencyLifecycle:j},Symbol.toStringTag,{value:"Module"})),kl=()=>{const e=ao(fn),t=ao(mn);return e?"DEBUG":t?"INFO":void 0},vn=()=>{const e=ce(),t=kl(),o=e.kosLogLevel??t??window.kosLogLevel??process.env.KOS_LOG_LEVEL;return o||"WARN"},Mn=()=>window.kosMessageLogging||process.env.KOS_MESSAGE_LOGGING==="true",_n=()=>window.kosMessageStudioLogging||process.env.KOS_MESSAGE_STUDIO_LOGGING==="true",En="ws-log",Pl=T.methodFactory,In=Mn(),Nl=_n();T.methodFactory=function(e,t,s){const o=Pl(e,t,s);return function(r,n){var i;o(r,n||""),(i=globalThis==null?void 0:globalThis.kosConfig)!=null&&i.logging&&globalThis.kosLog&&(s!==En||In&&Nl)&&globalThis.kosLog(`UI: ${String(s||"Root")} - ${r}`)}};let Tn=vn();T.setLevel(Tn);window.setKosLogLevel=e=>{Tn=e,T.setLevel(e)};const ls=T.getLogger(En);window.enableKosMessageLog=()=>{ls.setLevel(T.levels.INFO)};window.disableKosMessageLog=()=>{ls.setLevel(T.levels.ERROR)};In?window.enableKosMessageLog():window.disableKosMessageLog();const Fl=["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(";"),Ul=["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(";"),Vt=e=>t=>{T.getLevel()<=e&&t()},f={...T,ifDebug:Vt(T.levels.DEBUG),ifInfo:Vt(T.levels.INFO),ifWarn:Vt(T.levels.WARN),ifError:Vt(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");ls.info(`%c⬆ ${t}`,Fl)},wsReceive:(...e)=>{const t=String(e).replace(/\n/g,"\\n");ls.info(`%c⬇ ${t}`,Ul)}},$n=({path:e,requestId:t,method:s,destinationAddress:o})=>{let r=`${Rs}:${s}
|
|
2
2
|
`;return r+=`topic:${e}
|
|
3
|
-
`,r+=`${
|
|
4
|
-
`,r+=`${
|
|
5
|
-
`,o&&(r+=`${
|
|
6
|
-
`),r+=`${
|
|
3
|
+
`,r+=`${qe}:${e}
|
|
4
|
+
`,r+=`${kt}:${t}
|
|
5
|
+
`,o&&(r+=`${ge}:${o}
|
|
6
|
+
`),r+=`${ae}:kos.studio.request
|
|
7
7
|
`,r+=`
|
|
8
|
-
`,r}
|
|
8
|
+
`,r},On=({path:e,requestId:t,method:s,destinationAddress:o,ordered:r,tracker:n})=>{let i=`${Jr}:/http${e}
|
|
9
9
|
`;return i+=`${Rs}:${s}
|
|
10
|
-
`,i+=`${
|
|
11
|
-
`,i+=`${
|
|
12
|
-
`,o&&(i+=`${
|
|
13
|
-
`),r&&(i+=`${
|
|
14
|
-
`),n&&(i+=`${
|
|
15
|
-
`),i+=`${
|
|
10
|
+
`,i+=`${qe}:${e}
|
|
11
|
+
`,i+=`${on}:${t}
|
|
12
|
+
`,o&&(i+=`${ge}:${o}
|
|
13
|
+
`),r&&(i+=`${So}:true
|
|
14
|
+
`),n&&(i+=`${Do}:${n}
|
|
15
|
+
`),i+=`${ae}:fos.http.request
|
|
16
16
|
`,i+=`
|
|
17
|
-
`,i},
|
|
18
|
-
`;return c+=`${
|
|
19
|
-
`,c+=`${
|
|
20
|
-
`,o&&(c+=`${
|
|
21
|
-
`),r&&(c+=`${
|
|
22
|
-
`),n&&(c+=`${
|
|
23
|
-
`),c+=`${
|
|
17
|
+
`,i},Sn=({path:e,requestId:t,method:s,destinationAddress:o,ordered:r,tracker:n,bridge:i})=>{let c=`${Rs}:${s}
|
|
18
|
+
`;return c+=`${qe}:${e}
|
|
19
|
+
`,c+=`${kt}:${t}
|
|
20
|
+
`,o&&(c+=`${ge}:${o}
|
|
21
|
+
`),r&&(c+=`${So}:true
|
|
22
|
+
`),n&&(c+=`${Do}:${n}
|
|
23
|
+
`),c+=`${ae}:${i?"fos":"kos"}.http.request
|
|
24
24
|
`,c+=`
|
|
25
|
-
`,c},be=(e,t)=>{let s=e;return t&&(s+=t),s};function
|
|
26
|
-
`;return o+=`${
|
|
27
|
-
`,o+=`${
|
|
28
|
-
`,o+=`${
|
|
29
|
-
`,o+=`${
|
|
25
|
+
`,c},be=(e,t)=>{let s=e;return t&&(s+=t),s};function lo(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 uo(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 Dn=({path:e,requestId:t,destinationAddress:s})=>{let o=`topic:${e}
|
|
26
|
+
`;return o+=`${qe}:${e}
|
|
27
|
+
`,o+=`${kt}:${t}
|
|
28
|
+
`,o+=`${ge}:${s}
|
|
29
|
+
`,o+=`${ae}:kos.studio.request
|
|
30
30
|
`,o+=`
|
|
31
|
-
`,o},
|
|
32
|
-
`;return r+=`${
|
|
33
|
-
`,r+=`${
|
|
31
|
+
`,o},Cn=({requestId:e,destinationAddress:t,requestType:s,headers:o})=>{let r=`${kt}:${e}
|
|
32
|
+
`;return r+=`${ge}:${t}
|
|
33
|
+
`,r+=`${ae}:${s}
|
|
34
34
|
`,o&&Object.keys(o).forEach(n=>{r+=`${n}:${o[n]}
|
|
35
35
|
`}),r+=`
|
|
36
|
-
`,r},jl=(e,t)=>{const s=e,o=be(
|
|
37
|
-
`;return r+=`${
|
|
36
|
+
`,r},jl=(e,t)=>{const s=e,o=be(Cn(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")},An=({path:e,responseId:t,status:s,destinationAddress:o})=>{let r=`topic:${e}
|
|
37
|
+
`;return r+=`${qe}:${e}
|
|
38
38
|
`,t&&(r+=`${Ls}:${t}
|
|
39
|
-
`),r+=`${
|
|
40
|
-
`,r+=`${
|
|
41
|
-
`,r+=`${
|
|
39
|
+
`),r+=`${Oo}:${s}
|
|
40
|
+
`,r+=`${ge}:${o}
|
|
41
|
+
`,r+=`${ae}:kos.studio.response
|
|
42
42
|
`,r+=`
|
|
43
|
-
`,r},Bl=(e,t)=>{const s=e,o=be(
|
|
44
|
-
`;return t+=`${
|
|
43
|
+
`,r},Bl=(e,t)=>{const s=e,o=be(Dn(t),JSON.stringify(s)),r=E.getInstance().transport.socket;r?r.socket.send(o):f.error("socket transport is not initialized")},Kl=(e,t)=>{const s=t.responseId?{status:t.status,data:e}:e,o=be(An(t),JSON.stringify(s)),r=E.getInstance().transport.socket;r?r.socket.send(o):f.error("socket transport is not initialized")},Rn=({topic:e})=>{let t=`topic:${e}
|
|
44
|
+
`;return t+=`${ae}:kos.broker.send
|
|
45
45
|
`,t+=`
|
|
46
|
-
`,t},
|
|
47
|
-
`;return n+=`${
|
|
48
|
-
`,n+=`${
|
|
49
|
-
`,n+=`${
|
|
50
|
-
`,n+=`${
|
|
51
|
-
`,n+=`${
|
|
52
|
-
`,n+=`${
|
|
46
|
+
`,t},Ln=({responseId:e,destinationAddress:t,type:s,sourceAddress:o,status:r})=>{let n=`${Ls}:${e}
|
|
47
|
+
`;return n+=`${ge}:${t}
|
|
48
|
+
`,n+=`${en}:${o}
|
|
49
|
+
`,n+=`${ae}:${s??"kos.message.request"}
|
|
50
|
+
`,n+=`${Oo}:${r}
|
|
51
|
+
`,n+=`${tn}:application/json
|
|
52
|
+
`,n+=`${sn}:no-cache
|
|
53
53
|
`,n+=`
|
|
54
|
-
`,n},
|
|
54
|
+
`,n},xn=({topic:e,responseId:t,destinationAddress:s,type:o})=>{let r=`topic:${e}
|
|
55
55
|
`;return t&&(r+=`${Ls}:${t}
|
|
56
|
-
`),r+=`${
|
|
57
|
-
`,r+=`${
|
|
56
|
+
`),r+=`${ge}:${s}
|
|
57
|
+
`,r+=`${ae}:${o??"kos.message.request"}
|
|
58
58
|
`,r+=`
|
|
59
|
-
`,r},Gl=({msg:e,options:t})=>{const s=e,o=be(Cn(t),JSON.stringify(s)),r=E.getInstance().transport.socket;r?r.socket.send(o):f.error("socket transport is not initialized")},kn=({msg:e,options:t})=>{const s=e,o=be(Ln(t),JSON.stringify(s)),r=E.getInstance().transport.socket;r?r.socket.send(o):f.error("socket transport is not initialized")},xn=({msg:e,options:t})=>{const s=e,o=be(Rn(t),JSON.stringify(s)),r=E.getInstance().transport.socket;r?r.socket.send(o):f.error("socket transport is not initialized")},uo=(e,t)=>{try{return t?e.body??e:JSON.parse(e.body)}catch{return e.body||e}},ce=(e,t)=>{e[mt]=e[mt]||{},e[mt][t]=!0},De=e=>`{PROP_${String(e)}}`,Hl=e=>`{PROP_${String(e)}}`,Vl=De("kosParentId"),ks=e=>t=>{t[pt]=t[pt]||{};const s=(e==null?void 0:e.parentId)||Vl;t[pt]={parentId:s}},je=({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]=je({value:o[n],modelId:t,modelData:s}),r),{});else if(typeof o=="string"){const r=new RegExp(".*({PROP_(.+)})");let n=o!=null&&o.includes(cs)?o.replace(cs,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},$r=f.createLogger({name:"kos-model"}),Yl={construct(e,t){var c,l;const s=k.createContext(t[0]);let o=(c=e[pt])==null?void 0:c.parentId;o&&(o=je({value:o,modelData:t[1]||{},modelId:t[0]}),k.setParentContext(t[0],o));const r=new e(...t,{logger:f.createLogger({name:e.prototype.modelTypeId,group:((l=e[yt])==null?void 0:l.group)??"kos-model"}),kosContext:s});try{Object.keys(r[Ue]||{}).forEach(d=>{r[d]=r[Ue][d].handler})}catch(d){$r.error("error while creating model instance",d)}const n=r[P]||{};Object.keys(n).forEach(d=>{const u=n[d],h=je({value:u.id||u.modelType,modelData:r,modelId:t[0]}),b=Object.keys((u==null?void 0:u.options)||{}).reduce((v,p)=>{const M=u.options[p];return v[p]=je({value:M,modelData:r,modelId:t[0]}),v},{});typeof h=="string"&&(r[d]=u.lazy?void 0:E.getInstance().modelManager.createModelInstance(u.modelType,h,b||{}).data,E.getInstance().modelManager.addDependency(t[0],h))});let i;try{i=w.makeAutoObservable(r)}catch(d){$r.error(d)}return i}},A=e=>t=>{t.prototype.modelTypeId=e,t.prototype[yn]=!0,t.prototype[ee]=t.prototype[ee]||{},t.prototype[P]=t.prototype[P]||{};const s={};return f.ifDebug(()=>{f.debug(`Registering model with options ${s}`)}),new Proxy(t,Yl)},zl=({modelType:e})=>t=>{ks()(t),A(e)(t)};function ql(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 Wl=({group:e}={group:""})=>t=>{t[yt]=t[yt]||{},t[yt]={group:e}};function Pn(e){return(t,s,o)=>{t[bt]=t[bt]||{},t[bt][s]={dependencies:e==null?void 0:e.dependencies,value:o.value},o.value=function(){throw new Error(`Method ${s} cannot be called directly.`)}}}const Zl=e=>(t,s)=>{t[ts]=t[ts]||{},t[ts][s]=e},Ft=({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||j.INIT}},Ql=({topic:e,handler:t,websocket:s=!1,condition:o=()=>!0})=>r=>{r[ee]=r[ee]||{},Array.isArray(e)?e.forEach(n=>{r[ee][n]={websocket:s,handler:t,condition:o}}):r[ee][e]={websocket:s,handler:an(r,w.action(t),200),condition:o}};function R({topic:e,condition:t=(l,d)=>!0,transform:s=l=>l,websocket:o=!1,fos:r=!1,bridge:n=!1,skipParse:i=!1,lifecycle:c}){return(l,d,u)=>{l[ee]=l[ee]||{},Array.isArray(e)?e.forEach(h=>{l[ee][h]={websocket:o,fos:r,bridge:n,handler:u.value,condition:t,transform:s,lifecycle:c,skipParse:i}}):l[ee][e]={websocket:o,fos:r,bridge:n,handler:u.value,condition:t,transform:s,lifecycle:c,skipParse:i}}}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||{}),S=(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))(S||{});const Nn=5e3;class Xl extends Error{constructor(s,o){super(s);a(this,"model");this.model=o}}const Fn=(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 Xl(`${t.modelId} - ${t.modelTypeName} - ${s}`,t))},e)}),cancel:()=>{o&&clearTimeout(o)}}},Un=e=>e.transition(S.GO_ACTIVE,y.ACTIVE),jn=e=>e.whenReady(),Bn=e=>e.transition(S.LOAD,y.LOADED),Jl=e=>e.transition(S.UNLOAD,y.UNLOADED),Kn=e=>e.transition(S.INITIALIZE,y.INITIALIZED);var Lo=(e=>(e.ACTIVE="active",e.READY="ready",e.LOAD="load",e.UNLOAD="unload",e.INIT="init",e))(Lo||{});const ss={active:Un,ready:jn,load:Bn,init:Kn},Gn=(e,t)=>{const s=t.id||t.modelType,o=je({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]=je({value:l,modelData:e.modelData,modelId:e.modelId}),i},{});return{dependentModel:E.getInstance().modelManager.createModelInstance(t.modelType,o,r),dataModelId:o}},Hn=(e,t=j.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}=Gn(e,i);e.modelData[n]=c.data,f.debug(`waiting for dependent model ${i.modelType} with id ${l} - waiting for WHENREADY`);const d=async(b,v,p)=>{var M;await((M=b.whenReady)==null?void 0:M.call(b)),f.debug(`dependent model ${v} with id ${p} - READY`)},{promise:u,cancel:h}=Fn(Nn,e,e.status);return Promise.race([d(c.model,i.modelType,l).then(()=>{h()}),u])}).filter(n=>!!n)},Vn=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 ss[s]&&c?l=ss[s](c):(c||f.error("model is undefined. This shouldn't happen"),ss[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}=Fn(Nn,c.model,c.status);return Promise.race([(u=c.promise)==null?void 0:u.then(()=>{d()}),l])}))).filter(c=>c.status==="rejected");i.length>0&&f.error(`Model ${e.modelId} had ${i.length} failed child models on ${o}`)},Yn=async(e,t,s)=>{await Vn(e,e.getChildren().filter(o=>!!o),t,s)},ot=async(e,t)=>{const o=(await Promise.allSettled(Hn(e,t))).filter(r=>r.status==="rejected");o.length&&(f.error(`There were ${o.length} failed dependent models on ${t}`),f.error(o))},os=e=>e[P]!==void 0,zn=e=>e.revision!==void 0&&e.index!==void 0,qn=e=>{if(e){if(os(e))return e;if(zn(e))return e.data;if(e instanceof Map||e instanceof w.ObservableMap||e instanceof Set)return Array.from(e.values()).filter(os);if(Array.isArray(e))return e.filter(os)}},ed=f.createLogger({name:"model-active-machine"}),td=e=>{const t=m.createMachine(y.INACTIVE,{[y.FAILED]:m.state(m.transition(S.GO_ACTIVE,y.ACTIVATING)),[y.INACTIVE]:m.state(m.transition(S.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(S.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=>ed.debug(o.machine.current)),machine:t}},Or=f.createLogger({name:"model-online-machine"}),sd=e=>{const t=m.createMachine(y.OFFLINE,{[y.ONLINE]:m.state(m.transition(S.GO_OFFLINE,y.OFFLINE,m.action(async()=>{await e.offline(),e.onlineStatus=y.OFFLINE}))),[y.OFFLINE]:m.state(m.transition(S.GO_ONLINE,y.ONLINE,m.action(async()=>{Or.debug(`Going online with model ${e.modelId}`),await e.online(),e.onlineStatus=y.ONLINE,await e.transition(S.INITIALIZE,y.INITIALIZED)})))}),s=m.interpret(t,o=>Or.debug(o.machine.current));return{machine:t,service:s}},od=e=>{var o;const t=td(e).service,s=sd(e).service;return m.createMachine(y.CREATING,{[y.CREATING]:m.state(m.transition(S.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}))),[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(S.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(S.GO_ONLINE)})),m.transition("error",y.FAILED,m.action(()=>{e.status=y.FAILED}))),[y.READY]:m.state(m.transition(S.UNLOAD,y.UNLOADED,m.action((o=e.unload)==null?void 0:o.bind(e))),m.transition(S.RESET,y.RESETTING),m.transition(S.GO_ONLINE,y.READY,m.action(()=>{s.send(S.GO_ONLINE)})),m.transition(S.GO_OFFLINE,y.READY,m.action(()=>{s.send(S.GO_OFFLINE)})),m.transition(S.GO_ACTIVE,y.READY,m.action(()=>{t.send(S.GO_ACTIVE)})),m.transition(S.GO_INACTIVE,y.READY,m.action(()=>{t.send(S.GO_INACTIVE)}))),[y.UNLOADED]:m.state(),[y.FAILED]:m.state()})},rd=f.createLogger({name:"kos-model-lifecycle"}),nd=e=>({service:m.interpret(od(e),s=>rd.debug(`state machine for model ${e.modelId}: ${s.machine.current});`))});class id extends WebSocket{constructor(t){super(t)}}function Sr(e){const t=`
|
|
59
|
+
`,r},Gl=({msg:e,options:t})=>{const s=e,o=be(Rn(t),JSON.stringify(s)),r=E.getInstance().transport.socket;r?r.socket.send(o):f.error("socket transport is not initialized")},kn=({msg:e,options:t})=>{const s=e,o=be(xn(t),JSON.stringify(s)),r=E.getInstance().transport.socket;r?r.socket.send(o):f.error("socket transport is not initialized")},Pn=({msg:e,options:t})=>{const s=e,o=be(Ln(t),JSON.stringify(s)),r=E.getInstance().transport.socket;r?r.socket.send(o):f.error("socket transport is not initialized")},ho=(e,t)=>{try{return t?e.body??e:JSON.parse(e.body)}catch{return e.body||e}},le=(e,t)=>{e[mt]=e[mt]||{},e[mt][t]=!0},De=e=>`{PROP_${String(e)}}`,Hl=e=>`{PROP_${String(e)}}`,Vl=De("kosParentId"),xs=e=>t=>{t[pt]=t[pt]||{};const s=(e==null?void 0:e.parentId)||Vl;t[pt]={parentId:s}},Ue=({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]=Ue({value:o[n],modelId:t,modelData:s}),r),{});else if(typeof o=="string"){const r=new RegExp(".*({PROP_(.+)})");let n=o!=null&&o.includes(cs)?o.replace(cs,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},Or=f.createLogger({name:"kos-model"}),Yl={construct(e,t){var c,l;const s=x.createContext(t[0]);let o=(c=e[pt])==null?void 0:c.parentId;o&&(o=Ue({value:o,modelData:t[1]||{},modelId:t[0]}),x.setParentContext(t[0],o));const r=new e(...t,{logger:f.createLogger({name:e.prototype.modelTypeId,group:((l=e[yt])==null?void 0:l.group)??"kos-model"}),kosContext:s});try{Object.keys(r[Fe]||{}).forEach(d=>{r[d]=r[Fe][d].handler})}catch(d){Or.error("error while creating model instance",d)}const n=r[P]||{};Object.keys(n).forEach(d=>{const u=n[d],h=Ue({value:u.id||u.modelType,modelData:r,modelId:t[0]}),b=Object.keys((u==null?void 0:u.options)||{}).reduce((v,p)=>{const M=u.options[p];return v[p]=Ue({value:M,modelData:r,modelId:t[0]}),v},{});typeof h=="string"&&(r[d]=u.lazy?void 0:E.getInstance().modelManager.createModelInstance(u.modelType,h,b||{}).data,E.getInstance().modelManager.addDependency(t[0],h))});let i;try{i=w.makeAutoObservable(r)}catch(d){Or.error(d)}return i}},D=e=>t=>{t.prototype.modelTypeId=e,t.prototype[bn]=!0,t.prototype[ee]=t.prototype[ee]||{},t.prototype[P]=t.prototype[P]||{};const s={};return f.ifDebug(()=>{f.debug(`Registering model with options ${s}`)}),new Proxy(t,Yl)},zl=({modelType:e})=>t=>{xs()(t),D(e)(t)};function ql(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 Wl=({group:e}={group:""})=>t=>{t[yt]=t[yt]||{},t[yt]={group:e}};function Nn(e){return(t,s,o)=>{t[bt]=t[bt]||{},t[bt][s]={dependencies:e==null?void 0:e.dependencies,value:o.value},o.value=function(){throw new Error(`Method ${s} cannot be called directly.`)}}}const Zl=e=>(t,s)=>{t[ts]=t[ts]||{},t[ts][s]=e},Ft=({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||j.INIT}},Ql=({topic:e,handler:t,websocket:s=!1,condition:o=()=>!0})=>r=>{r[ee]=r[ee]||{},Array.isArray(e)?e.forEach(n=>{r[ee][n]={websocket:s,handler:t,condition:o}}):r[ee][e]={websocket:s,handler:cn(r,w.action(t),200),condition:o}};function R({topic:e,condition:t=(l,d)=>!0,transform:s=l=>l,websocket:o=!1,fos:r=!1,bridge:n=!1,skipParse:i=!1,lifecycle:c}){return(l,d,u)=>{l[ee]=l[ee]||{},Array.isArray(e)?e.forEach(h=>{l[ee][h]={websocket:o,fos:r,bridge:n,handler:u.value,condition:t,transform:s,lifecycle:c,skipParse:i}}):l[ee][e]={websocket:o,fos:r,bridge:n,handler:u.value,condition:t,transform:s,lifecycle:c,skipParse:i}}}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||{}),S=(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))(S||{});const Fn=5e3;class Xl extends Error{constructor(s,o){super(s);a(this,"model");this.model=o}}const Un=(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 Xl(`${t.modelId} - ${t.modelTypeName} - ${s}`,t))},e)}),cancel:()=>{o&&clearTimeout(o)}}},jn=e=>e.transition(S.GO_ACTIVE,y.ACTIVE),Bn=e=>e.whenReady(),Kn=e=>e.transition(S.LOAD,y.LOADED),Jl=e=>e.transition(S.UNLOAD,y.UNLOADED),Gn=e=>e.transition(S.INITIALIZE,y.INITIALIZED);var xo=(e=>(e.ACTIVE="active",e.READY="ready",e.LOAD="load",e.UNLOAD="unload",e.INIT="init",e))(xo||{});const ss={active:jn,ready:Bn,load:Kn,init:Gn},Hn=(e,t)=>{const s=t.id||t.modelType,o=Ue({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]=Ue({value:l,modelData:e.modelData,modelId:e.modelId}),i},{});return{dependentModel:E.getInstance().modelManager.createModelInstance(t.modelType,o,r),dataModelId:o}},Vn=(e,t=j.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}=Hn(e,i);e.modelData[n]=c.data,f.debug(`waiting for dependent model ${i.modelType} with id ${l} - waiting for WHENREADY`);const d=async(b,v,p)=>{var M;await((M=b.whenReady)==null?void 0:M.call(b)),f.debug(`dependent model ${v} with id ${p} - READY`)},{promise:u,cancel:h}=Un(Fn,e,e.status);return Promise.race([d(c.model,i.modelType,l).then(()=>{h()}),u])}).filter(n=>!!n)},Yn=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 ss[s]&&c?l=ss[s](c):(c||f.error("model is undefined. This shouldn't happen"),ss[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}=Un(Fn,c.model,c.status);return Promise.race([(u=c.promise)==null?void 0:u.then(()=>{d()}),l])}))).filter(c=>c.status==="rejected");i.length>0&&f.error(`Model ${e.modelId} had ${i.length} failed child models on ${o}`)},zn=async(e,t,s)=>{await Yn(e,e.getChildren().filter(o=>!!o),t,s)},ot=async(e,t)=>{const o=(await Promise.allSettled(Vn(e,t))).filter(r=>r.status==="rejected");o.length&&(f.error(`There were ${o.length} failed dependent models on ${t}`),f.error(o))},os=e=>e[P]!==void 0,qn=e=>e.revision!==void 0&&e.index!==void 0,Wn=e=>{if(e){if(os(e))return e;if(qn(e))return e.data;if(e instanceof Map||e instanceof w.ObservableMap||e instanceof Set)return Array.from(e.values()).filter(os);if(Array.isArray(e))return e.filter(os)}},ed=f.createLogger({name:"model-active-machine"}),td=e=>{const t=m.createMachine(y.INACTIVE,{[y.FAILED]:m.state(m.transition(S.GO_ACTIVE,y.ACTIVATING)),[y.INACTIVE]:m.state(m.transition(S.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(S.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=>ed.debug(o.machine.current)),machine:t}},Sr=f.createLogger({name:"model-online-machine"}),sd=e=>{const t=m.createMachine(y.OFFLINE,{[y.ONLINE]:m.state(m.transition(S.GO_OFFLINE,y.OFFLINE,m.action(async()=>{await e.offline(),e.onlineStatus=y.OFFLINE}))),[y.OFFLINE]:m.state(m.transition(S.GO_ONLINE,y.ONLINE,m.action(async()=>{Sr.debug(`Going online with model ${e.modelId}`),await e.online(),e.onlineStatus=y.ONLINE,await e.transition(S.INITIALIZE,y.INITIALIZED)})))}),s=m.interpret(t,o=>Sr.debug(o.machine.current));return{machine:t,service:s}},od=e=>{var o;const t=td(e).service,s=sd(e).service;return m.createMachine(y.CREATING,{[y.CREATING]:m.state(m.transition(S.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}))),[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(S.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(S.GO_ONLINE)})),m.transition("error",y.FAILED,m.action(()=>{e.status=y.FAILED}))),[y.READY]:m.state(m.transition(S.UNLOAD,y.UNLOADED,m.action((o=e.unload)==null?void 0:o.bind(e))),m.transition(S.RESET,y.RESETTING),m.transition(S.GO_ONLINE,y.READY,m.action(()=>{s.send(S.GO_ONLINE)})),m.transition(S.GO_OFFLINE,y.READY,m.action(()=>{s.send(S.GO_OFFLINE)})),m.transition(S.GO_ACTIVE,y.READY,m.action(()=>{t.send(S.GO_ACTIVE)})),m.transition(S.GO_INACTIVE,y.READY,m.action(()=>{t.send(S.GO_INACTIVE)}))),[y.UNLOADED]:m.state(),[y.FAILED]:m.state()})},rd=f.createLogger({name:"kos-model-lifecycle"}),nd=e=>({service:m.interpret(od(e),s=>rd.debug(`state machine for model ${e.modelId}: ${s.machine.current});`))});class id extends WebSocket{constructor(t){super(t)}}function Dr(e){const t=`
|
|
60
60
|
|
|
61
61
|
`,s=`
|
|
62
62
|
`,o=/:(.*)/s,[r,n]=e.split(t).map(c=>c.trim());return{headers:r.split(s).reduce((c,l)=>{const[d,u]=l.split(o).map(h=>h.trim());return d&&u&&(c[d]=u),c},{}),body:n}}function ad(e){const t=`
|
|
63
63
|
|
|
64
64
|
`,s=`
|
|
65
|
-
`,o=/:(.*)/s,[,r,n]=e.split(t).map(c=>c.trim());return{headers:r.split(s).reduce((c,l)=>{const[d,u]=l.split(o).map(h=>h.trim());return d&&u&&(c[d]=u),c},{}),body:n}}class ko{constructor({host:t,port:s,protocol:o,alias:r,onConnectionEstablished:n,onConnectionLost:i,Transport:c=id}){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,U("/mock/msg/receive",l=>{var d,u;if(l!=null&&l.body){f.wsReceive(l==null?void 0:l.body);const h={data:l.body};(u=(d=this.socket)==null?void 0:d.onmessage)==null||u.call(d,h)}}),w.makeObservable(this,{connectionEstablished:w.observable})}addOfflineMessage(t){this.offlineMessages.push({msg:t})}processMessageEvent(t){const{data:s}=t;return
|
|
65
|
+
`,o=/:(.*)/s,[,r,n]=e.split(t).map(c=>c.trim());return{headers:r.split(s).reduce((c,l)=>{const[d,u]=l.split(o).map(h=>h.trim());return d&&u&&(c[d]=u),c},{}),body:n}}class ko{constructor({host:t,port:s,protocol:o,alias:r,onConnectionEstablished:n,onConnectionLost:i,Transport:c=id}){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,U("/mock/msg/receive",l=>{var d,u;if(l!=null&&l.body){f.wsReceive(l==null?void 0:l.body);const h={data:l.body};(u=(d=this.socket)==null?void 0:d.onmessage)==null||u.call(d,h)}}),w.makeObservable(this,{connectionEstablished:w.observable})}addOfflineMessage(t){this.offlineMessages.push({msg:t})}processMessageEvent(t){const{data:s}=t;return Dr(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:l}=ad(t.data);n=l,i={...s,...c}}G(r,n,i)}}catch(s){f.error("onMessage exception",s.message,s.stack)}}onOpen(t){f.info("websocket connection opened"),this.socket=t.currentTarget,w.runInAction(()=>{var s;this.connectionEstablished=!0,this.alias&&this.socket.send(`type:kos.addr.alias
|
|
66
66
|
alias:${this.alias}
|
|
67
67
|
|
|
68
|
-
`),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(),w.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}=
|
|
68
|
+
`),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(),w.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}=Dr(String(t));G(Pt.SEND,{headers:r,body:n})}if(window.kosTopicIntercept&&window.kosEnableMocks){const{handler:r,requestId:n}=window.kosTopicIntercept(t);if(r){t=`mocked:true
|
|
69
69
|
${t}`;const c={data:`mocked:true
|
|
70
|
-
${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 cd{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 ld extends ko{constructor({host:s,port:o,alias:r}){super({host:s,port:o,Transport:cd,alias:r,protocol:"kos://"});a(this,"RESPONSE_ID_HEADER");this.RESPONSE_ID_HEADER="response-id"}}class dd extends ko{constructor({host:s,port:o}){super({host:s,port:o,protocol:"ws://"});a(this,"RESPONSE_ID_HEADER");this.RESPONSE_ID_HEADER="requestId"}}class ud extends ko{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
|
|
70
|
+
${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 cd{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 ld extends ko{constructor({host:s,port:o,alias:r}){super({host:s,port:o,Transport:cd,alias:r,protocol:"kos://"});a(this,"RESPONSE_ID_HEADER");this.RESPONSE_ID_HEADER="response-id"}}class dd extends ko{constructor({host:s,port:o}){super({host:s,port:o,protocol:"ws://"});a(this,"RESPONSE_ID_HEADER");this.RESPONSE_ID_HEADER="requestId"}}class ud extends ko{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 go{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 ld({host:t,port:s,protocol:o,onConnectionEstablished:i,onConnectionLost:c,alias:n})):r?new dd({host:t,port:s,protocol:o,alias:n,onConnectionEstablished:i,onConnectionLost:c}):new ud({host:t,port:s,protocol:o,alias:n,onConnectionEstablished:i,onConnectionLost:c})}}const hd=ce();hd.fos&&(window.kosUseFos=!0);const Cr=process.env.KOS_FOS_PORT;window.kosUseFos=!!(window.kosUseFos||process.env.KOS_USE_FOS==="true");window.kosFosPort=Cr?parseInt(Cr):0;const Ee=T.getLogger("web-socket-transport");var Zn=(e=>(e.NOT_INITIALIZED="not_initialized",e.INITIALIZED="initialized",e.OFFLINE="OFFLINE",e.ONLINE="ONLINE",e))(Zn||{}),wt=(e=>(e.CONNECTED="websocket.connected",e.DISCONNECTED="websocket.disconnected",e.RELOAD="websocket.reload",e))(wt||{});class ks{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 l=!1;w.makeObservable(this,{authorized:w.observable,socket:w.observable,fosSocket:w.observable,init:w.action,connectionEstablished:w.computed}),w.reaction(()=>this.connectionEstablished,d=>{d&&(Ee.warn("Connection Established"),G("websocket.connected","websocket.connected"),l&&G("websocket.reload","websocket.reload"),l=!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=go.build({host:this.host,port:this.fosPort||9854,protocol:this.protocol,fos:!0})),this.socket=go.build({host:this.host,port:this.port,protocol:this.protocol,alias:this.alias,onConnectionLost:()=>{Ee.error("Connection Lost"),G("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){var h,b,v,p;Ee.debug(`${s} to topic ${t}`);const n=ce(),c=(n==null?void 0:n.connId)||((h=window==null?void 0:window.kosBridge)==null?void 0:h.call(window,"connId"));Ee.debug(`subscribing with connId ${c}`);const l=c?`dst-addr:${c}
|
|
71
71
|
`:"",d=o?`subscribe:${t}`:r?`type:fos.broker
|
|
72
72
|
cmd:${s}
|
|
73
73
|
${l}topics:${t}
|
|
74
74
|
`:`${l}type:kos.broker.${s}
|
|
75
75
|
|
|
76
|
-
["${t}"]`;if(o?(b=this.fosSocket)==null?void 0:b.connectionEstablished:(v=this.socket)==null?void 0:v.connectionEstablished){const M=o?this.fosSocket:this.socket;(p=M==null?void 0:M.socket)==null||p.send(d)}else{Ee.debug("no connection adding to offline messages");const M=o?this.fosSocket:this.socket;M==null||M.addOfflineMessage(d)}}subscribeTopic({topic:t,callback:s,fos:o,bridge:r}){const{unsubscribe:n,count:i}=U(t,s);return Ee.debug(`Topic ${t} currently has ${i} subscribers`),this._sendSubscriptionMessage(t,"subscribe",o,r),()=>{const{count:c}=n();Ee.debug(`Topic ${t} currently has ${c} subscribers`),c===0&&this._sendSubscriptionMessage(t,"unsubscribe",o)}}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(xs,"_instance");const I=T.getLogger("kos-model"),Ar="kos.extension.model.loader",gd=({subscription:e,modelData:t,skipParse:s,model:o,resolvedTopic:r})=>n=>{try{if(o!=null&&o.isReady){const i=uo(n,s),c=e.transform(i);if(e.condition(c,t,n))return e.handler.call(t,c,n,t)}else{f.warn(`model ${o==null?void 0:o.modelId} not ready. adding message for topic ${r} to offline queue`);const i=()=>{f.warn(`processing offline message for ${r} on model ${o==null?void 0:o.modelId}`);const c=uo(n,s),l=e.transform(c);if(e.condition(l,t))return e.handler.call(t,l,n,t)};o._offlineQueue.push(i)}}catch(i){I.error(i)}},fd=(e,t,s)=>{const o=new RegExp(".*({PROP_(.+)})");let r=e.includes("{MODEL_ID}")?e.replace("{MODEL_ID}",t):e;const n=r.match(o);if(n&&s&&Object.getOwnPropertyNames(s).includes(n[2])){const i=s[n[2]];r=r.replace(n[1],i)}return r};class Zn{constructor({modelTypeName:t,id:s,modelData:o,modelManager:r}){a(this,"_id");a(this,"_status");a(this,"_activeStatus");a(this,"_onlineStatus");a(this,"_subscriptions");a(this,"_onlineSubscriptions");a(this,"modelData");a(this,"modelTypeName");a(this,"initialized");a(this,"loaded");a(this,"_offlineQueue");a(this,"fsmService");a(this,"disposers",[]);a(this,"modelManager");a(this,"_companionModels");this.modelManager=r,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,this.fsmService=nd(this),this._subscriptions=[],this._onlineSubscriptions=[],this.fsmService.service.send(S.CREATE),this._companionModels=new Map,this._offlineQueue=[],w.makeAutoObservable(this)}get companionModels(){return this._companionModels}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}isActive(){return this._status===y.ACTIVE}isOnline(){return this._onlineStatus===y.ONLINE}isReady(){return this._status===y.READY}async deactivate(){var t,s;I.debug(`deactivating model ${this.modelTypeName} with id ${this.modelId}`);try{const o=k.getContext(this.modelId);await((s=(t=this.modelData)==null?void 0:t.deactivate)==null?void 0:s.call(t,o)),I.debug(`Model ${this.modelTypeName} with id ${this.modelId} deactivated`)}catch(o){throw I.debug(`Model ${this.modelId} failed to deactivated`),o}}transition(t,s,o=y.FAILED){const r=this;if((s===y.ACTIVE||s===y.INACTIVE?r.activeStatus:r.status)===s)return I.debug(`model ${this.modelId} already at target state ${s}. resolving immediately. `),Promise.resolve();let i;return new Promise((c,l)=>{i=w.autorun(()=>{const d=s===y.ACTIVE||s===y.INACTIVE?r.activeStatus:r.status;d===o?l(Error(`Failed to transition ${r.modelId} to ${t}`)):d===s&&c()}),r.fsmService.service.send(t)}).then(()=>{i==null||i()})}async activate(){var t,s;I.debug(`activating model ${this.modelTypeName} with id ${this.modelId}`),await ot(this,j.ACTIVATE);try{const o=k.getContext(this.modelId);await((s=(t=this.modelData)==null?void 0:t.activate)==null?void 0:s.call(t,o)),I.debug(`Model ${this.modelTypeName} with id ${this.modelId} activated`)}catch(o){throw I.debug(`Model ${this.modelId} failed to activate`),o}}async whenInitialized(){const t=this;let s,o;return new Promise((r,n)=>{s=w.when(()=>t._status===y.FAILED,()=>{n(Error(`Failed to load ${t.modelId} model ${t.modelTypeName}`))}),o=w.when(()=>t.initialized,()=>{r()})}).then(()=>{s==null||s(),o==null||o()})}async whenReady(){const t=this;let s,o;return new Promise((r,n)=>{s=w.when(()=>t._status===y.FAILED,()=>{n(Error(`Failed to load ${t.modelId} model ${t.modelTypeName}`))}),o=w.when(()=>t._status===y.READY,()=>{r()})}).then(()=>{s==null||s(),o==null||o()})}async ready(){var t,s;if(this.fsmService.service.machine.current===y.READY){I.debug(`already readying model ${this.modelTypeName} with id ${this.modelId} returning`);return}try{I.debug(`readying model ${this.modelTypeName} with id ${this.modelId}`),await ot(this,j.READY),await Yn(this,Lo.READY,j.READY);const o=k.getContext(this.modelId);await((s=(t=this.modelData)==null?void 0:t.ready)==null?void 0:s.call(t,o)),this._offlineQueue.length>0&&(f.warn(`processing ${this._offlineQueue.length} messages offline queue for ${this.modelId}`),this._offlineQueue.forEach(r=>r()),f.info(`offline queue processed for ${this.modelId}`)),this._offlineQueue=[],I.debug(`Model ${this.modelId} is ready`)}catch(o){throw I.error(o),Error(o)}}async load(){var t,s,o;if(this.fsmService.service.machine.current===y.LOADED||this.fsmService.service.machine.current===y.LOADING){I.debug(`already loaded model ${this.modelTypeName} with id ${this.modelId} returning`);return}I.debug(`loading model ${this.modelTypeName} with id ${this.modelId}`),await ot(this,j.LOAD),I.debug(`loading model ${this.modelTypeName} with id ${this.modelId}`);try{const r=k.getContext(this.modelId),n=await C.loader.executeLoader(Ar,{});n&&(I.info(`setting loaded context for ${this.modelId}, type: ${this.modelTypeName}`),r==null||r.set(Ar,n)),await((s=(t=this.modelData)==null?void 0:t.load)==null?void 0:s.call(t,r)),this.loaded=!0,I.debug(`Model ${this.modelTypeName} with id ${this.modelId} loaded`),this.registerSubscribers(j.LOAD);const i=((o=this.modelData)==null?void 0:o[bt])||{};Object.keys(i).forEach(c=>{const l=i[c].value.bind(this.modelData),d=function(){I.info(`running effect ${c} for model type ${this.modelTypeName} id: ${this.modelId}`),w.runInAction(()=>{l.apply(this.modelData)})};if(i[c].dependencies){const u=()=>i[c].dependencies(this.modelData),h=w.reaction(u,d.bind(this));this.disposers.push(h)}else{const u=w.autorun(d.bind(this));this.disposers.push(u)}})}catch(r){throw I.error(`Model ${this.modelId} failed to load`),r}}async unload(){var t,s;I.debug(`unloading model ${this.modelTypeName} with id ${this.modelId}`);try{const o=this.getChildren().map(n=>{var i;return(i=n.unload)==null?void 0:i.call(n)}).filter(n=>!!n);await Promise.allSettled(o);const r=k.getContext(this.modelId);await((s=(t=this.modelData)==null?void 0:t.unload)==null?void 0:s.call(t,r)),this.loaded=!1,this._onlineSubscriptions.forEach(n=>n()),this._onlineSubscriptions=[],I.debug(`Model ${this.modelTypeName} with id ${this.modelId} unloaded`),this.disposers.forEach(n=>n()),this.disposers=[]}catch(o){throw I.debug(`Model ${this.modelId} failed to unload`),o}}async init(){var t,s;I.debug(`initializing init dependencies of model ${this.modelTypeName} with id ${this.modelId}`),await ot(this,j.INIT),I.debug(`initializing model ${this.modelTypeName} with id ${this.modelId}`);try{const o=k.getContext(this.modelId);await((s=(t=this.modelData)==null?void 0:t.init)==null?void 0:s.call(t,o)),this.initialized=!0,I.debug(`Model ${this.modelTypeName} with id ${this.modelId} initialized`);const r=U("/kosCore/online",async()=>{I.debug(`online subscription called for ${this.modelId} waiting for ready state`),await this.whenReady(),I.debug(` ${this.modelId} is ready. Going online`),this.fsmService.service.send(S.GO_ONLINE)}),n=U("/kosCore/offline",async()=>{I.debug(` offline sub called for model ${this.modelId}. Going offline`),this.fsmService.service.send(S.GO_OFFLINE)});this._onlineSubscriptions.push(r.unsubscribe),this._onlineSubscriptions.push(n.unsubscribe),this.registerSubscribers(j.INIT)}catch(o){throw I.error(`Model ${this.modelId} failed to initialize`),o}}_registerSubscription(t,s,o){if(t.websocket){I.debug(`subscribing ${s} via WebSocketTransport`);const r=xs.getInstance().subscribeTopic({topic:s,callback:o,fos:t.fos,bridge:t.bridge});this._subscriptions.push(r)}else{I.debug(`subscribing ${s} directly to EventBus`);const{unsubscribe:r}=U(s,o);this._subscriptions.push(r)}}async registerSubscribers(t){var o;I.debug(`registering subscribers in ${this.modelTypeName} with id ${this.modelId}`);const s=((o=this.modelData)==null?void 0:o[ee])||{};I.debug(`found ${Object.keys(s).length} topics to subscribe to`),Object.keys(s).forEach(r=>{const n=s[r].lifecycle;if(t&&t!==n)return;const i=!!s[r].skipParse;I.debug(`found subscription for ${r}`),I.debug(`${r} skipParse: ${i}`);const c=fd(r,this.modelId,this.modelData);I.debug(`resolved subscription to ${c}`);const l=gd({model:this,resolvedTopic:c,skipParse:i,modelData:this.modelData,subscription:s[r]});this._registerSubscription(s[r],c,l)})}async online(){var s,o;I.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;I.debug(`offline model ${this.modelTypeName} with id ${this.modelId}`),this._subscriptions.forEach(r=>{r()}),this._subscriptions=[];const t=k.getContext(this.modelId);await((o=(s=this.modelData)==null?void 0:s.offline)==null?void 0:o.call(s,t))}accept(t){t.visit(this)}getChildren(){const t=this.getDecoratedChildren(),s=this.getResolvedChildren(t),o=this.getAdditionalChildren(),r=Array.from(new Set([...s,...o,...Array.from(this._companionModels.values())]));return this.filterAndMapToModels(r)}clearCompanionModels(){this._companionModels.clear()}addCompanionModel(t){this._companionModels.set(t.modelTypeName,t)}getDecoratedChildren(){var t;return((t=this.modelData)==null?void 0:t[mt])||{}}getResolvedChildren(t){return Object.keys(t).map(s=>{var o;return qn((o=this.modelData)==null?void 0:o[s])}).filter(s=>!!s).flat()}getAdditionalChildren(){var t,s;return((s=(t=this.modelData)==null?void 0:t.getChildren)==null?void 0:s.call(t))||[]}filterAndMapToModels(t){const s=t.map(o=>this.modelManager.getModelById(o.id||"")).filter(o=>!!o);return s.forEach(o=>{try{k.setParentContext(o.modelId,this.modelId)}catch{I.error(`failed to set parent context for model ${o.modelId} with parent ${this.modelId}`)}}),s}}const Qn=e=>typeof e=="function",Xn=10,L=f.createLogger({name:"kos-model-manager"});class Jn{constructor(){a(this,"_modelsById");a(this,"_registry");a(this,"_usesCache");a(this,"_isPreloaded",!1);a(this,"_preloaded");a(this,"_usedByCache");a(this,"_toDelete");this._modelsById=w.observable.map(new Map),this._registry={models:{},preloadModels:[]},this._preloaded=[],this._usedByCache=new Map,this._usesCache=new Map,this._toDelete=new Map,globalThis.kos=globalThis.kos||{},globalThis.kos.modelManager=this}get registry(){return this._registry}set registry(t){this._registry=t}get preloadedModels(){return L.debug("preloading models"),this._isPreloaded?(L.error("returning cased preloaded models"),this._preloaded):(this._preloaded=this._registry.preloadModels.map(t=>(L.debug(`preloading ${t}`),typeof t=="string"?this.createModelInstance(t).model:this.createModelInstance(t.modelType,t.modelId,t.options).model)),this._preloaded)}get models(){return Array.from(this._modelsById.values())}removeModel(t){var r;const s=this;L.debug(`Removing models: Currently ${s._modelsById.size} models cached`);const o={visit(n){var c;const i=n.getChildren();i==null||i.forEach(l=>{var d;(d=l.accept)==null||d.call(l,this)}),L.debug(`removing ${n.modelTypeName} model ${n.modelId} from model manager`),(c=n.offline)==null||c.call(n),n.clearCompanionModels(),k.deleteContext(n.modelId),s._modelsById.delete(n.modelId),s._toDelete.delete(n.modelId)}};(r=t.accept)==null||r.call(t,o),L.debug(`Models Removed: Currently ${s._modelsById.size} models cached`)}addModel(t){L.debug("adding model to kosModelManager");const s=this.getModelById(t.modelId)||t;return this._modelsById.set(s.modelId,s),s}hasModel(t){return!!t&&!!this.getModelById(t)}getModelById(t){return this._toDelete.has(t)?void 0:this._modelsById.get(t)}getModelsByType(t,s){return Array.from(this._modelsById.values()).filter(r=>r.modelTypeName===t).filter(r=>!this._toDelete.get(r.modelId)).filter(r=>s?s(r.modelData):!0).map(r=>r.modelData)}getModelTypeRegistry(t){var o,r;const s=(r=(o=this._registry)==null?void 0:o.models)==null?void 0:r[t];if(!s)throw Error(`No registration defined for model type ${t}}`);return s}getModelSubscriptions(t){var s;return((s=this.getModelTypeRegistry(t))==null?void 0:s.subscriptions)||{}}getDataModelBuilder(t){var s;return(s=this.getModelTypeRegistry(t))==null?void 0:s.builder}getModelFactory(t){return Ut(t)}restoreModelFromDeleteCache(t){if(t&&this._toDelete.has(t)){const s=this._toDelete.get(t);this._toDelete.delete(t),this._modelsById.set(t,s)}}addDependency(t,s){Ir.cancelDeletion(s),this.restoreModelFromDeleteCache(s),this._usedByCache||(this._usedByCache=new Map),this._usesCache||(this._usesCache=new Map);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))}removeDependency(t,s){this._usedByCache||(this._usedByCache=new Map),this._usesCache||(this._usesCache=new Map);const o=this._usedByCache.get(s)||[],r=o.indexOf(t);r>-1&&(o.splice(r,1),this._usedByCache.set(s,o));const n=this._usesCache.get(t)||[],i=n.indexOf(s);i>-1&&(n.splice(i,1),this._usesCache.set(t,n))}async reloadModel(t){if(t.id){L.info(`fetching model ${t.id} to reload`);const s=this.getModelById(t.id);s?(L.info(`reloading model ${t.id}`),await s.transition(S.RESET,y.RESETTING)):L.warn(`${t.id} not found in KOS Model Manager`)}}canDestroyModel(t){const s=this._usedByCache.get(t);return s&&s.length>0?(L.info(`model ${t} is used by ${s.join(", ")}. Returning without destroying.`),!1):!0}async initiateDestroyModel(t){if(!t.id)throw new Error("Model ID is required");const s=t.id;if(this.canDestroyModel(s)){L.info(`fetching model ${s} to add to deletion queue`);const o=this.getModelById(t.id);o&&(this._modelsById.delete(s),this._toDelete.set(s,o),Ir.addToDeletionQueue(t.id,setTimeout(async()=>{this.destroyModel(o)},Xn)))}}registerCompanionModel(t,s){this.registry.companionModels||(this.registry.companionModels={}),this.registry.companionModels[t]||(this.registry.companionModels[t]=[]),!!this.registry.companionModels[t].find(r=>r.type===s)||this.registry.companionModels[t].push({type:s})}registerModel(t){const s=t.type;this.registry.models||(this.registry.models={}),this.registry.models[s]||(L.info(`Model with type ${s} doesn't exist. Adding new registration`),this.registry.models={...this.registry.models,...t.registration})}async destroyModel(t){var s;if(t!=null&&t.modelId){const o=t.modelId;this.canDestroyModel(o)&&(t?(L.info(`destroying model ${o}`),await((s=t.unload)==null?void 0:s.call(t)),this.removeModel(t)):L.warn(`${o} not found in KOS Model Manager`))}}createModelInstance(t,s,o){var r;L.debug(`retrieving new model instance of type ${t} ${s||""}`);try{const n=this.getModelTypeRegistry(t),i=n.create,c=n.class,l=n.singleton?t:s;if(this.restoreModelFromDeleteCache(l),this.hasModel(l))L.debug(`model ${l} found in cache`);else{L.debug(`model ${l} not found in cache...creating`);const u=i?i({modelTypeId:t,id:l,options:o}):new c(l,o||{}),h=new Zn({modelTypeName:t,id:l,modelData:u,modelManager:this});this._modelsById.set(l,h),(r=this.registry.companionModels)!=null&&r[t]&&this.registry.companionModels[t].forEach(v=>{let p=v.type;if(Qn(p)){L.debug(`using companionModelType factory for ${t}`);const D=p(h.modelData,o);if(!D)return;p=D,L.debug(`factory resolved to type ${p}`)}const M=`${p}-${l}`,O=this.createModelInstance(p,M,{data:o,companionParent:h.modelData,kosParentId:l});h.addCompanionModel(O.model)})}const d=this.getModelById(l);return L.debug(`returning model ${l} from createModelInstance`),{model:d,data:d.modelData}}catch(n){throw L.error(`Error creating model instance: ${n}`),n}}static create(t,s){const o=this.getInstance(s);return o.registry=t,o}static getInstance(t){var s,o;return(!((s=globalThis.kos)!=null&&s.modelManager)||t)&&(L.debug("Creating new instance of KosModelManager"),new this),(o=globalThis.kos)==null?void 0:o.modelManager}}const md=async({context:e,extension:t})=>{const s=await C.loader.executeLoader(t,{});return e==null||e.set(t,s),s},pd=async({extension:e,contextData:t,data:s})=>await C.dataMapper.executeMapper(e,s,t),yd=async({extension:e,contextData:t,data:s})=>await C.propertyMapper.executeMapper(e,s,t),bd=Object.freeze(Object.defineProperty({__proto__:null,executeDataMapperExtension:pd,executeLoaderExtension:md,executePropertyMapperExtension:yd},Symbol.toStringTag,{value:"Module"})),wd="Extensions";class vd{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 rs=(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))(rs||{}),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 Md=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}},Q=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},$e=async e=>{await E.getInstance().whenReady(),await E.getInstance().modelManager.initiateDestroyModel(e)},_d=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.transition(S.UNLOAD,y.UNLOADED)},ei=async e=>{await E.getInstance().whenReady(),await E.getInstance().modelManager.reloadModel(e),f.debug(`reload model initiated for model ${e.id}, model ready: ${ds(e)} - ${Date.now()} `),await Q(e),f.debug(`reload model complete for model ${e.id}, model ready: ${ds(e)} - ${Date.now()} `)},Ed=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},ti=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}},Ze=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}},si=(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]))},Id=(e,t)=>si(e,t)[0],Td=(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},$d=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.values()).map(o=>o.modelData)},go=(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.values()).find(r=>t(r.modelData))},te=e=>t=>Object.getPrototypeOf(t).modelTypeId===e,ds=e=>{const t=E.getInstance().modelManager.getModelById(e.id);if(!t)throw new Error("Model not found");return t.isReady()},Od=f.createLogger({name:"kos-model-factory"}),vt={byModelType:e=>E.getInstance().modelManager.getModelFactory(e),getModelInstance:(e,t,s)=>{const o=vt.byModelType(t);if(!o)throw Od.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),vt.getModelInstance(t,e,s))},Singleton:{create:e=>(t,s)=>(s&&k.setParentContext(e,s),vt.getModelInstance(e,e,t))},Model:{instance:e=>t=>vt.getModelInstance(t,e)}};window.KosRegistry=window.KosRegistry||{coreModels:new Map,preloadModels:[],companionModels:new Map,models:new Map};const Cr=window.KosRegistry.coreModels,Js=window.KosRegistry.preloadModels,eo=window.KosRegistry.companionModels,Yt=window.KosRegistry.models,$={model:{registerLegacyModel:e=>(t,s)=>(Cr.set(t,s),{preload:$.model.preloadModel(e),model:$.model.register(e),companion:$.companion.register(e),legacy:$.model.registerLegacyModel(e),root:e}),preloadModel:e=>t=>(Js.includes(t)||Js.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=to(t)?t.registration():t;return Yt.set(o.type,o),to(t)&&t.relatedModels.forEach(r=>Yt.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],to(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=>Yt.get(e),getAll:()=>Array.from(Yt.entries()),getPreloadModels:()=>Js,getLegacyModels:()=>Array.from(Cr.entries()).reduce((e,[t,s])=>(e[t]=s,e),{})},companion:{register:e=>(t,s)=>{const o=eo.get(t)||[];return o.push(s),eo.set(t,o),{preload:$.model.preloadModel(e),model:$.model.register(e),companion:$.companion.register(e),legacy:$.model.registerLegacyModel(e),root:e}},getAll:()=>Array.from(eo.entries())}},oi=$.model.registerLegacyModel,ri=$.model.register,Sd=$.companion.register,Dd=$.model.preloadModel,ni=e=>typeof e.updateModel=="function",to=e=>e.registration!==void 0&&typeof e.registration=="function";class ii{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=te(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 ge extends ii{constructor(t){super({...t,singleton:!1,factory:H.Factory.create(t.type)})}instance(t){const s=this.factory(t);return{get:()=>{const o=Ze(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(ni(r))r.updateModel(o);else throw new Error(`Model ${this.type} is not updateable. Please implement UpdateAware interface`);return r}else throw new Error("Model is not of type "+this.type)}})},options:o=>({build:()=>{const r=s(o);if(this.guard(r))return r;throw new Error("Model is not of type "+this.type)}})}}registration(){return{type:this.type,predicate:this.guard,registration:{[this.type]:{class:this.class,singleton:!1}},factory:this.factory}}}class we extends ii{constructor(t){super({...t,singleton:!0,factory:H.Singleton.create(t.type)})}instance(){const t=this.factory;return{get:()=>{const o=Ze(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)},forceUpdate:{options:o=>({build:()=>{const r=t(o);if(this.guard(r)){if(ni(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=t(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:!0}},factory:this.factory}}}const F=f.createLogger({name:"kos-core"}),Ad=()=>{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://")},Cd=()=>{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},Rd=()=>{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},Ld=(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)}}},Rr=e=>typeof e.reload=="function",kd=e=>typeof e.unload=="function";var ai=(e=>(e.LOGGED_IN="logged_in",e.LOGGED_OUT="logged_out",e))(ai||{});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=rs.CREATED,this.authState="logged_out",this._reloading=!1,this._unloading=!1,w.makeAutoObservable(this),U("token",c=>{c&&(this.transport.token=c.body)}),U(wt.CONNECTED,async()=>{await this.whenReady(),this.fsmService.service.send(Ne.GO_ONLINE)}),U(wt.DISCONNECTED,async()=>{this.fsmService.service.send(Ne.GO_OFFLINE)}),U("/studioServer/auth/LOGGED_IN",()=>{this.authState="logged_in",this.transport.authorized=!0}),U("/studioServer/auth/LOGIN_REQUIRED",()=>{this.authState="logged_out",this.transport.authorized=!1}),U(wt.RELOAD,()=>{this.fsmService.service.send(Ne.RELOAD)}),U("/studio/project/reload",()=>{this.fsmService.service.send(Ne.RELOAD)});const s=xs.getInstance(),o=Cd(),r=Rd(),n=Ad();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=Md(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;const t=Date.now();if(this._reloading){F.info("reload already in progress");return}this._reloading=!0,F.warn("reloading KOS Core"),F.warn("reloading preloaded models");const s=this.modelManager;for(const i of s.preloadedModels)Rr(i.modelData)&&(F.info(`reloading model ${i.modelId}`),(r=i.unload)==null||r.call(i),await i.modelData.reload(),F.info(`reloading model ${i.modelId} complete`));for(const i of s.models)!s.preloadedModels.includes(i)&&Rr(i.modelData)&&((n=i.unload)==null||n.call(i),await i.modelData.reload());const o=Date.now()-t;setTimeout(()=>{w.runInAction(()=>{F.warn("reloading KOS Core complete"),this._reloading=!1})},1e3-o)}async online(){F.debug("KOS Core going online"),await this._transport.whenReady(),F.debug("KOS Transport Ready. Calling online() for models"),G("/kosCore/online","/kosCore/online"),console.timeEnd("kosCore:startup")}async offline(){F.debug("KOS Core going offline"),G("/kosCore/offline","/kosCore/offline")}async unload(){var r;F.debug("Unloading kOS Core");const t=Date.now();this._unloading=!0,F.debug("unloading KOS Core");const s=this.modelManager;for(const n of s.models)kd(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===rs.READY)}async ready(){F.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}=Ld(5e3,r.model);Promise.race([r.promise.then(()=>{i()}),n])}))).filter(r=>r.status==="rejected");if(o.length)throw F.error(`There were ${o.length} failed models on model preloading`),Error(`There were ${o.length} failed models on model preloading`);F.debug("leaving kos-core ready() ")}get isReady(){return this.status===rs.READY}set transport(t){this._transport=t}get transport(){return this._transport}get coreInitialized(){return this.initialized}get modelsLoaded(){return this.loaded}async init(){F.debug("entering kos-core init()"),console.time("kosCore:startup"),console.time("kosCore:init"),await this._transport.whenReady(),this.initialized=!0,F.debug("initialized - leaving kos-core init()"),console.timeEnd("kosCore:init")}async load(){F.debug("entering kos-core load()"),console.time("kosCore:load"),this.loaded=!0,F.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,b;const u=(b=(h=t.extensions)==null?void 0:h.dataMapper)==null?void 0:b[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,b;const u=(b=(h=t.extensions)==null?void 0:h.propertyMapper)==null?void 0:b[d];u&&C.propertyMapper.registerPropertyMapper(d,u)}),(l=t.extensions)!=null&&l.contextLoader&&Object.keys(t.extensions.contextLoader).forEach(d=>{var h,b;const u=(b=(h=t.extensions)==null?void 0:h.contextLoader)==null?void 0:b[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=Jn.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 xd=f.createLogger({name:"kos-fetch"}),Pd=process.env.KOS_WS_TIMEOUT?parseInt(process.env.KOS_WS_TIMEOUT):3e4,Nd=()=>new Promise(e=>{setTimeout(()=>{e(!0)},0)}),Fd=e=>e!=null&&e.studio?Tn:e!=null&&e.fos?$n:On,Ud=async(e,t)=>{const s=E.getInstance().transport;await s.whenReady();const o=Nt(),r=new URL(e),n=`${r.pathname}${r.search}`,i=(t==null?void 0:t.timeout)||Pd,c=Fd(t),l=be(c({path:n,requestId:o,method:(t==null?void 0:t.method)||"GET",destinationAddress:(t==null?void 0:t.destinationAddress)||"",ordered:t==null?void 0:t.ordered,tracker:t==null?void 0:t.tracker,bridge:t==null?void 0:t.bridge}),t==null?void 0:t.body);return new Promise(d=>{const u=new AbortController,h=setTimeout(()=>{xd.error(`Timeout occurred - url: ${e}`),u.abort(),d({headers:co({}),status:404,ok:!1,json:async()=>null,body:lo(""),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:b}=U(o,p=>{var O,D,me;clearTimeout(h);const M={headers:co((p==null?void 0:p.headers)||{}),status:((O=p==null?void 0:p.headers)==null?void 0:O.status)&&parseInt((D=p==null?void 0:p.headers)==null?void 0:D.status)||200,ok:((me=p==null?void 0:p.headers)==null?void 0:me.status)==="200",json:async()=>{var ve;try{return(ve=p==null?void 0:p.body)!=null&&ve.length?JSON.parse(p.body):null}catch{throw Error("Not a JSON response")}},text:async()=>(p==null?void 0:p.body)||"",body:lo((p==null?void 0:p.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.")}};b(),Nd().then(()=>d(M))}),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=Ud;if(process.env.KOS_MOCK_FETCH==="true"){const e=process.env.KOS_PORT||"9999";exports.kosFetch=fetch,exports.BASE_URL=`http://localhost:${e}`}const jd=f.createLogger({name:"kos-model-visitor",group:"kos-ui-core"});class Bd{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)){jd.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 ci=()=>({isMock:!1,URL:exports.BASE_URL}),Kd="errUnknown";async function zt(e,t,s,o,r){const n=o!=null&&o.path?Object.keys(o.path).reduce((h,b)=>String(h).replace(`{${b}}`,o==null?void 0:o.path[b]),String(e)):String(e),i=o!=null&&o.query?Object.keys(o.query).map(h=>`${h}=${o.query[h]}`).join("&"):"",c=`${ci().URL}//${n}${i?`?${encodeURIComponent(i)}`:""}`,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||Kd}`,null]:[null,(await d.json()).data]}function xo(){return{get:(e,t,s)=>zt(e,"get",s,t),post:(e,t,s,o)=>zt(e,"post",o,t,s),put:(e,t,s,o)=>zt(e,"put",o,t,s),delete:(e,t,s)=>zt(e,"delete",s,t)}}class li{constructor(){a(this,"middlewares",[])}use(t){this.middlewares.push(t)}async execute(t){let s=0;const o=async()=>{s++,s<this.middlewares.length&&await this.middlewares[s](t,o)};await this.middlewares[s](t,o)}}const Gd=async(e,t)=>{const s=new li;t.forEach(r=>s.use(r));const o={data:e,result:{}};return await s.execute(o),o.result},Ut=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}}),Hd=e=>{E.getInstance().modelManager.registerModel(e)},Vd=(e,t)=>{E.getInstance().modelManager.registerCompanionModel(e,t)},di=Symbol("KosObservableData");class ui{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)}}ui.prototype[di]=!0;function Yd(e,t){return new Proxy(e,{construct:(s,o)=>{const r=new e(...o);return r.setValues(t),r.proxy}})}const Oe=e=>{const t=Yd(ui,e);return new t(e)},Lr="/kos/ui/internal/heartbeat/",zd=({relationshipId:e,destinationAddress:t,onAbort:s,waitTime:o,beatTime:r})=>{const n=E.getInstance().transport,i=new AbortController;let c=performance.now();const l=n.subscribeTopic({topic:`${Lr}${e}`,callback:()=>{c=performance.now()}}),d=o??3e3,u=window.setInterval(()=>{let M=performance.now()-c;M=M/1e3,M>d/1e3&&i.abort()},d),h=r??2e3,b=window.setInterval(()=>{kn({msg:{},options:{topic:`${Lr}${e}`,destinationAddress:t}})},h),v=()=>{window.clearInterval(b),window.clearInterval(u),l()},p=()=>{v(),s&&s(),i.signal.removeEventListener("abort",p)};return i.signal.addEventListener("abort",p),{cleanUpHeartbeat:v}},hi=(...e)=>t=>e.reduce((s,o)=>o(s),t),qd={maxAttempts:5,baseDelayMs:100,backoffFactor:1.5};async function Wd(e,t){let s=1;const o={...qd,...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 q=e=>({isMock:!1,URL:exports.BASE_URL}),Zd=(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),Qe(h,{ordered:i,studio:c,fos:l,bridge:d,destinationAddress:u});const b=await s(n||`${t}/${o}`,h);if(!b.ok)throw Error(`There was a problem deleting the model; returned status ${b.status}`);return await b.json()},Qe=(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),Qd=(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),Qe(u,{timeout:l,ordered:r,studio:n,fos:i,bridge:c,destinationAddress:d});const b=await s(o||t,u);if(!b.ok){let p;try{p=await b.json()}catch{}throw new ne(`There was a problem retrieving the model; returned status ${b.status}`,p)}return await b.json()},Xd=(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),Qe(h,{timeout:d,ordered:r,studio:n,fos:i,bridge:c,destinationAddress:u});const v=await s(o||t,h);if(!v.ok){let M;try{M=await v.json()}catch{}throw new ne(`There was a problem retrieving the model; returned status ${v.status}`,M)}return await v.json()},Jd=(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),Qe(h,{timeout:d,ordered:n,studio:i,fos:c,bridge:l,destinationAddress:u});const b=o||`${t}/${r}`,v=await s(b,h);if(!v.ok){let M;try{M=await v.json()}catch{}throw new ne(`There was a problem retrieving the model; returned status ${v.status}`,M)}return await v.json()};class ne extends Error{constructor(s,o){super(s);a(this,"payload");this.name="FetchException",this.payload=o}}const kr=(e,t,s)=>async({model:o,urlOverride:r,ordered:n,tracker:i,studio:c,fos:l,bridge:d,timeout:u,destinationAddress:h})=>{const b={method:"POST",body:typeof o=="string"?o:JSON.stringify(o)};e&&(b.destinationAddress=e),i&&(b.tracker=i),Qe(b,{timeout:u,ordered:n,studio:c,fos:l,bridge:d,destinationAddress:h});const v=await s(r||t,b);if(!v.ok){let M;try{M=await v.json()}catch{}throw new ne(`There was a problem sending the POST data; returned status ${v.status}`,M)}return await v.json()},xr=(e="POST",t,s,o)=>async({model:r,id:n,urlOverride:i,ordered:c,studio:l,fos:d,bridge:u,timeout:h,destinationAddress:b})=>{const v={method:e};r&&(v.body=JSON.stringify(r)),t&&(v.destinationAddress=t),Qe(v,{timeout:h,ordered:c,studio:l,fos:d,bridge:u,destinationAddress:b});const p=await o(i||`${s}/${n}`,v);if(!p.ok){let O;try{O=await p.json()}catch{}throw new ne(`There was a problem modifying the model; returned status ${p.status}`,O)}return await p.json()},V={build:({destinationAddress:e="",basePath:t,getAllPath:s,getOnePath:o,deleteModelPath:r,addModelPath:n,modifyModelPath:i,mock:c=!1})=>{const l=c?fetch:exports.kosFetch;return{getAll:Qd(e,s||t,l),getModelById:Jd(e,o||t,l),getOne:Xd(e,o||t,l),addModel:kr(e,n||t,l),deleteModel:Zd(e,r||t,l),modifyModel:xr("POST",e,i||t,l),putModel:xr("PUT",e,i||t,l),postModel:kr(e,n||t,l)}}},eu=Nt(),gi=()=>`kos-${eu}`,tu=e=>!!e&&!e.includes("VM_SERVICE")&&e.startsWith(gi()),Po=async(e,t=6e4)=>new Promise((s,o)=>{const{unsubscribe:r}=U(e,i=>{T.debug(`recieved response for refId ${e}: ${i}`),r(),clearTimeout(n);try{const c=i!=null&&i.body?JSON.parse(i.body):{};s(c)}catch{const c=(i==null?void 0:i.body)||{};s(c)}}),n=setTimeout(()=>{r(),o(Error(`Request with ID ${e} timed out. Cancelling.`))},t)}),su=async(e,t,s)=>{const o=Po(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)},ou=async({topic:e,msg:t,requestId:s})=>{const o=s??Nt(),r=Po(o);G(e,t,{sync:o});const n=await r;if(n.error)throw Error(n.error);return n},le=new Map;class fi{constructor(t){a(this,"_context");a(this,"_parent");a(this,"_id");this._id=t,this._context=new w.ObservableMap({}),this._parent="",w.makeAutoObservable(this)}setParent(t){Y(()=>{this._parent=t})}get id(){return this._id}get context(){return this._context}get parentModel(){var t;if(this._parent)return(t=Ze(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=le.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=le.get(e)??new fi(e);if(t){if(!le.has(t))throw new Error(`Parent context ${t} does not exist`);s.setParent(t)}else e!=="root"&&s.setParent("root");return le.set(e,s),s},getContext:e=>le.get(e),deleteContext:e=>{le.delete(e)},setParentContext:(e,t)=>{var s;if(!le.has(t))throw new Error(`Parent context ${t} does not exist`);(s=le.get(e))==null||s.setParent(t)},rootContext:()=>le.get("root")};k.createContext("root");const ru=e=>k.getContext(e.id);function nu(e,t){return e.length!==t.length?!1:e.every(s=>t.includes(s))}class No{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=Oe(),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(nu(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 iu(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 tt=f.createLogger({name:"kos-container-model"});class fe{constructor(t){a(this,"_data");a(this,"_sortKey");a(this,"_revision");a(this,"_index");a(this,"_optionsMap");a(this,"_disposerMap",new Map);a(this,"_parentId");a(this,"idx");this._data=w.observable.map(new Map),this._sortKey=t==null?void 0:t.sortKey,this._revision=1;const s=t!=null&&t.extensionId?C.indexExtension.loadIndexExtensions(t.extensionId):{},o=(t==null?void 0:t.indexMap)||{};this._optionsMap={...o,...s};const r=t!=null&&t.indexMap?Object.keys(t.indexMap).reduce((n,i)=>(n[i]=void 0,n),{}):{};this._index=w.observable.map(r),this.idx=Oe(),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 No({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&&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 b,v;n.includes(u.name)&&((b=this.index.get(i.get(u.name)))==null||b.refresh());const h=r.filter(([,p])=>typeof p=="function");for(const[p]of h)(v=this.index.get(p))==null||v.refresh()},l=iu(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??[]:(tt.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):(tt.info(`key ${s} not found in ${t} index: ${Array.from(o.index.keys())}`),[])}else return tt.info(`index ${t} not found in ${Array.from(this.index.keys())}`),[]}async clear(){this._data.forEach(t=>{const s=t.id;$e(t).then(()=>{tt.debug(`${s} destroyed, removing from map`),this.removeModel(s,!0)}).catch(o=>tt.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)}}const so=f.createLogger({name:"kos-data-container"});class mi{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=Oe(),w.makeAutoObservable(this,{}),this.init()}init(){Object.keys(this._optionsMap).forEach(t=>{const s=this._optionsMap[t],o=new No({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??[]:(so.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):(so.info(`key ${s} not found in ${t} index: ${Array.from(o.index.keys())}`),[])}else return so.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)}}class au{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 cu{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 pi{constructor(){a(this,"_token");w.makeAutoObservable(this),U("token",t=>{this.token=t==null?void 0:t.body})}get token(){return this._token}set token(t){this._token=t}}class yi{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 b=l.middlewares[u++];await b(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{unsubscribe:lu}=U("kos.intent",e=>{if(e){const t=e.body,s=t.type;bi(s,t.options)}}),us=new Map,du=(e,t)=>{const s=us.get(e)||[];s.push(t),us.set(e,s)},bi=(e,t)=>{us.has(e)&&us.get(e)[0].call(void 0,t)};var wi=(e=>(e.GET="GET",e.PUT="PUT",e.POST="POST",e.DELETE="DELETE",e))(wi||{});const fo=w.when,vi=w.computed,Y=w.runInAction,N=w.autorun,Mi=w.reaction,Fo=w.observable,Uo="Not Assigned",uu="kos.trouble.added",hu="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||{}),Mt=(e=>(e.TIME_CHANGE="/kos/internal/time/time",e.DAY_CHANGE="/kos/internal/time/day",e.TIMEZONE_CHANGE="/kos/internal/time/timezone",e))(Mt||{});const _i=f.createLogger({name:"config-bean-service",group:"Services"}),jo=exports.BASE_URL,Ei=e=>(e==null?void 0:e.decimals)!==void 0,{postModel:gu,getOne:fu}=V.build({destinationAddress:"",basePath:`${jo}/kos/config/`}),Ii=async(e,t,s="/api/kos/config")=>(_i.debug(`sending modify request for ConfigBean: ${e}`),gu({model:t,urlOverride:`${jo}${s}/${e}`})),Ti=async(e,t="/api/kos/config")=>(_i.debug(`sending get request for ConfigBean: ${e}`),await fu({urlOverride:`${jo}${t}/details/${e}/15`})),Bo=e=>e.toLowerCase()==="true"||e.toLowerCase()==="false",Ps=e=>{try{const t=Number(e);return!isNaN(t)}catch{return!1}};function $i(e=[]){return e.reverse().reduce((t,s)=>{const{overrides:o}=s;return o&&(t={...t,...o}),t},{})}function Oi(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])?Oi(e[o],r,s):s[r]=e[o]}return s}const Si=(e,t)=>{const s=e.details[0].bean||$i(e.details[0].scopes),o=Oi(s);w.runInAction(()=>{const r={...o};t.props.setValues(r)})},Di=(e,t)=>{w.runInAction(()=>{e.changes.forEach(s=>{const o=s.attr;let r=s.currentValue,n=s.previousValue;typeof r=="string"&&Bo(r)&&(r=r.toLowerCase()=="true",n=(n==null?void 0:n.toLowerCase())=="true"),typeof r=="string"&&Ps(r)&&(r=Number(r),n=Number(n)),t.props[o]=r,t.prevProps[o]=n})})},Ai=e=>Object.fromEntries(e.props.entries),mu=e=>t=>s=>e.build(t,s);var pu=Object.defineProperty,yu=Object.getOwnPropertyDescriptor,Ci=(e,t,s,o)=>{for(var r=o>1?void 0:o?yu(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&&pu(t,s,r),r};function bu(e,t){for(const s of e)if(new RegExp(`^${s}$`).test(t))return s}const Ko="config-bean-model",qt=f.getLogger(Ko),wu=De("path");let hs=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=Ii,getConfigBean:o=Ti}=t;this._modifyConfigBean=s,this._getConfigBean=o,this.props=Oe(),this.prevProps=Oe()}get values(){return this.props.values}async ready(){qt.debug(`readying config bean ${this.path}`),qt.debug(`complete readying config bean ${this.path}`)}async load(){qt.debug(`loading config bean ${this.path}`);const e=await this._getConfigBean(this.path,this.serviceBasePath);if(e!=null&&e.data){const t=e.data;Si(t,this),qt.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=bu(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=Ai(this);await this._modifyConfigBean(this.path,e,this.serviceBasePath)}handleConfigBeanUpdated(e){Di(e,this)}};Ci([R({topic:`/kos/config/${wu}`,websocket:!0})],hs.prototype,"handleConfigBeanUpdated",1);hs=Ci([A(Ko)],hs);const It=new ge({class:hs,type:Ko}),Ns=({path:e,lazy:t,serviceBasePath:s})=>(o,r)=>{o[P]=o[P]||{},o[P][r]={modelType:It.type,id:`${It.type}-${e}`,options:{path:e,serviceBasePath:s},lifecycle:j.INIT,lazy:t}},{URL:Ri}=q(),{getOne:vu,getAll:Mu}=V.build({basePath:`${Ri}/api/kos/regions/info`}),Li=async()=>await vu({}),ki=async()=>await Mu({urlOverride:`${Ri}/api/kos/regions`}),_u=Object.freeze(Object.defineProperty({__proto__:null,getRegionInfo:Li,getRegions:ki},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 xi={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 Eu(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},{...xi});return{...e,...o}}function Iu(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]:{...xi}}});return Object.keys(o).forEach(r=>{e[r]={...e[r],...o[r]}}),e}function Tu(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 $u=Object.defineProperty,Ou=Object.getOwnPropertyDescriptor,Go=(e,t,s,o)=>{for(var r=o>1?void 0:o?Ou(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&&$u(t,s,r),r};const ns="region-info-model",st=f.createLogger({name:"region-info-model"});let Tt=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||st.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||st.info("Could not find default unit for measure",t.measure)}return!n||!i?(st.warn("Could not find unit to convert to or from. Return value as is"),String(e)):this.convertByUnit(e,n,i)}async init(){st.debug("initializing region info")}async load(){st.debug("loading region info");const e=await ki();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 Li();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(Eu,{}),this.measureMap=t.data.unitSystems.reduce(Iu,{}),this.defaultMeasureMap=t.data.unitSystems.reduce(Tu,{}),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))}};Go([Ns({path:"kos:service:region:settings"})],Tt.prototype,"regionSource",2);Go([Ns({path:"kos:service:region"})],Tt.prototype,"region",2);Tt=Go([A(ns)],Tt);const z={registration:{[ns]:{class:Tt,singleton:!0}},type:ns,factory:H.Singleton.create(ns)},Pr=({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},Pi=(e,t,s)=>{const{model:o}=Ze(z.type);if(!o)throw new Error("RegionInfo model not found");if(!ds(o))throw new Error("RegionInfo model not ready");const r={system:o.defaultUnitSystem},n=Pr({source:t}),i=Pr({source:s||r,defaultMeasure:o.getUnitMeasure(n.unit||"")});return o.convert(e,n,i)};function Nr({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 Fr({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:Ps(s)?Pi(Number(s),e,t):s,Su=(e,t,s,o)=>{if((e==null?void 0:e.type)==="enum"||!(e!=null&&e.options))return[];if(e.options.type==="rangeCount")return Nr(e.options).map(Le(s,o));if(e.options.type==="rangeInterval")return Fr(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 Nr(e.options.unitSystems[t]).map(Le(s,o));if(e.options.type==="unitSystemRangeInterval"&&t)return Fr(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[]},Du=(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 Au=Object.defineProperty,Cu=Object.getOwnPropertyDescriptor,Ho=(e,t,s,o)=>{for(var r=o>1?void 0:o?Cu(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&&Au(t,s,r),r};function Ru(e){return(e==null?void 0:e.type)==="enum"}function Lu(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 ku(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 is="config-bean-prop-model",ke=f.createLogger({name:"config-bean-prop-model"}),xu=De("path"),Pu=De("serviceBasePath");let $t=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 Ei(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?Lu(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=Ru(o)?o.values:Su(o,s,t==null?void 0:t.from,t==null?void 0:t.to),n=r.length>0?r.map(c=>({label:c,value:c})):[];return this.optionsExpander?typeof this.optionsExpander=="function"?this.optionsExpander(s,r):this.optionsExpander:n}convertUnit(e,t,s){const o=(e==null?void 0:e.measure)||s,r=(e==null?void 0:e.system)||t,n=e==null?void 0:e.unit;return{measure:o,system:r,unit:n}}getConverterUnits(){const e=this.regionInfo.defaultUnitSystem,t=this.getConverter();if(!t)throw Error("No converter defined");const s=t.measure,o=this.convertUnit(t.from,"si",s),r=this.convertUnit(t.to,e,s);return{backend:o,display:r}}set value(e){this.updateProperty(e)}get value(){return this.getValue(!0)}get rawValue(){return this.bean.props[this.attribute]}get significantValue(){var r,n;const e=this.value,t=this.regionInfo.defaultUnitSystem,s=this.getConverter(),o=(s==null?void 0:s.measure)||((r=s==null?void 0:s.to)==null?void 0:r.measure);if(!isNaN(e)&&s&&o){const i=this.getDefaultUnitDecimalPlaces(o,t,(n=s==null?void 0:s.to)==null?void 0:n.unit);try{const l=this.getFormatterOptions(s);if(l){let d=String(e);return d=l.formatToParts(Number(e))[0].value,Number(d)}}catch(l){ke.info(`error formatting value ${e}`,l)}return Number(e).toFixed(i)}return e}get previousValue(){return this.getValue(!1)}getValue(e){const t=this.bean[e?"props":"prevProps"][this.attribute];if(typeof t=="boolean")return t;if(this.getConverter()&&!isNaN(t)){const{backend:o,display:r}=this.getConverterUnits();return this.regionInfo.convert(Number(t),o,r)}return t||""}async activate(){ke.debug(`activating config bean ${this.id}`)}get displayValue(){const e=this.value;if(typeof e=="boolean")return String(e);if(this.schemaFormat==="drt"){const s=this.regionInfo.is12HourTimeFormat?"h:mm:ss a":"HH:mm:ss";return ku(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 Du(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){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,l,d,u,h,b,v;const{unit:e,measure:t}=this.getConverterFromFormat(),s=e==="drt"?"second":e;if(this.converter){const p=(o=this.converter)==null?void 0:o.measure,M=(n=(r=this.converter)==null?void 0:r.to)==null?void 0:n.measure,O=(c=(i=this.converter)==null?void 0:i.from)==null?void 0:c.measure,D=p||M||O||t,me=((d=(l=this.converter)==null?void 0:l.to)==null?void 0:d.unit)||this.regionInfo.getDefaultUnitForMeasure(D,((h=(u=this.converter)==null?void 0:u.to)==null?void 0:h.system)??this.regionInfo.defaultUnitSystem),ve=((v=(b=this.converter)==null?void 0:b.to)==null?void 0:v.system)??this.regionInfo.getUnitSystem(me),Re=this.schemaFormat==="drt"?"second":this.schemaFormat||s;return{...this.converter,from:{unit:Re,...this.converter.from},to:{...this.converter.to,unit:me,system:ve},measure:D}}if(s&&t){const p=this.regionInfo.getDefaultUnitForMeasure(t,this.regionInfo.defaultUnitSystem),M=this.regionInfo.getUnitSystem(s),O=this.regionInfo.getUnitSystem(p);return{measure:t,to:{unit:M===O?s:p}}}}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)}};Ho([Ft({modelType:z.type})],$t.prototype,"regionInfo",2);Ho([Ns({path:xu,serviceBasePath:Pu})],$t.prototype,"bean",2);$t=Ho([A(is)],$t);const Ae={registration:{[is]:{class:$t,singleton:!1}},type:is,factory:H.Factory.create(is)};function Nu(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:j.INIT,lazy:n}}}class Fu{constructor(t,s){a(this,"futures");a(this,"defaultContext");a(this,"context");a(this,"disposers",new Map);a(this,"container");this.futures=Fo.map(new Map),this.context="",this.defaultContext=s||"",this.container=t,w.makeAutoObservable(this)}get allFutures(){return Array.from(this.futures.values())}get future(){return this.futures.get(this.defaultContext)}addFuture(t,s){this.futures.set(s||t.id,t),this.context=s||t.id;const o=N(()=>{var r,n;(t.endState||t.progress)&&((n=(r=this.container)==null?void 0:r.onFutureUpdate)==null||n.call(r,t))});this.disposers.set(s||t.id,o)}removeFuture(t){var s;this.futures.delete(t||this.context),(s=this.disposers.get(t||this.context))==null||s(),this.disposers.delete(t||this.context)}getFuture(t){return this.futures.get(t||this.context)}}class Vo{constructor(t){a(this,"disposer");a(this,"_future");a(this,"container");a(this,"onFutureUpdate");this._future=void 0,this.container=t,w.makeAutoObservable(this)}removeFuture(){var t;this._future=void 0,(t=this.disposer)==null||t.call(this),this.disposer=void 0}get future(){return this._future}getFuture(){return this._future}addFuture(t){this._future=t;const s=N(()=>{var o,r;(t.endState||t.progress)&&((r=(o=this.container)==null?void 0:o.onFutureUpdate)==null||r.call(o,t))});this.disposer=s}get allFutures(){return this._future?[this._future]:[]}get timeRemaining(){var t;return((t=this._future)==null?void 0:t.timeRemaining)||""}get status(){var t;return((t=this._future)==null?void 0:t.status)||"NOT_RESOLVED"}get progress(){var t;return((t=this._future)==null?void 0:t.progress)||-1}async cancel(){if(this._future)try{await this._future.cancelFuture()}catch(t){throw f.error(t),t}}}const Ni="future-model",Xe=Ut(Ni),Fs=f.createLogger({name:"future-service",group:"Services"}),{isMock:Uu,URL:jt}=q();var Ke=(e=>(e.Success="SUCCESS",e.Fail="FAIL",e.Aborted="ABORT",e.Canceled="CANCEL",e))(Ke||{});const{getAll:ju,modifyModel:Bu,addModel:Ku,deleteModel:Gu,postModel:Hu}=V.build({destinationAddress:"",basePath:`${jt}/api/future`,mock:Uu}),Vu=async()=>await ju({}),Fi=async(e,t="/api/kos/future")=>(Fs.info(`sending delete request for Future: ${e}`),await Gu({id:e,urlOverride:`${jt}${t}/${e}`})),Ui=async(e,t="/api/kos/future")=>(Fs.info("sending add request for Future"),await Ku({model:e,urlOverride:`${jt}${t}`})),Yu=async(e,t,s="/api/kos/future")=>(Fs.info(`sending modify request for Future: ${e}`),Bu({model:t,id:e,urlOverride:`${jt}${s}/${e}`})),ji=async(e,t="/api/kos/future")=>(Fs.info(`sending cancel request for Future: ${e}`),Hu({urlOverride:`${jt}${t}/${e}/cancel`,ordered:!0,model:{}})),Yo=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}),zo=(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=Yo(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]})})}))},Bi=e=>t=>s=>e.build(String(t),s),qo=e=>t=>hi(Yo,Bi(e)(t.tracker||t.id))(t);var zu=Object.defineProperty,qu=Object.getOwnPropertyDescriptor,Ki=(e,t,s,o)=>{for(var r=o>1?void 0:o?qu(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&&zu(t,s,r),r};const oo=f.getLogger(Xe.type);let gs=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=ji,fo(()=>this.status===Ke.Success||this.status===Ke.Fail,()=>{oo.info(`Future ${this.id} has completed with status ${this.status}`),$e(this)})}async load(){oo.debug(`loading Future ${this.id}`)}unload(){oo.info(`unloading Future ${this.id}`)}async cancelFuture(){const e=this.namespace==="studio"?"/api/future":`/api/${this.namespace}/future`;await fo(()=>this.futureId!==Uo),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}`),zo(e,this)}};Ki([R({topic:`kos.future/${cs}`})],gs.prototype,"handleFutureUpdated",1);gs=Ki([A(Xe.type)],gs);const Gi=gs,Hi=xo();var Wu=Object.defineProperty,Zu=Object.getOwnPropertyDescriptor,Vi=(e,t,s,o)=>{for(var r=o>1?void 0:o?Zu(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&&Wu(t,s,r),r};const Yi="browser-router-model",Qu="kos.http.request",Xu="kos.http.response";let fs=class{constructor(e,t,s){a(this,"_id");a(this,"logger");a(this,"router");this._id=e,this.logger=s.logger,this.router=new yi}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),xn({msg:u,options:{responseId:i,destinationAddress:s,type:Xu,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}`)}};Vi([R({topic:Qu})],fs.prototype,"handleRequest",1);fs=Vi([A(Yi)],fs);const zi=new we({class:fs,type:Yi}),qi="future-container-model",ye=Ut(qi),Wi=e=>qo(Xe)(e),Ju=e=>{const t=Wi(e);return ye.build(ye.type,{}).addFutureModel(t),t},eh=e=>ye.build(ye.type,{}).getFuture(String(e)),Se={buildFutureModel:Wi,initiateFuture:Ju,getFuture:eh};var th=Object.defineProperty,sh=Object.getOwnPropertyDescriptor,Wo=(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&&th(t,s,r),r};const Wt=f.getLogger(ye.type);let Ot=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=Fi,addFuture:r=Ui}=t;this.logger=s.logger,this._deleteFuture=o,this._addFuture=r,this.id=e,this._futures=new fe,this.createModel=this.createFuture,this.deleteModel=this.removeFuture}get futures(){return this._futures.data}get models(){return this.futures}getFuture(e){return this._futures.getModel(e)}addFutureModel(e){this._futures.addModel(e)}removeFutureModel(e){this._futures.removeModel(e)}async removeFuture(e){try{await this._deleteFuture(e)}catch(t){Wt.error("error deleting a Future"),Wt.error(t)}}async createFuture(e){try{const t=await this._addFuture(e),s=t==null?void 0:t.data;if(s){const o=qo(Xe)(s);return this.addFutureModel(o),o}}catch(t){throw Wt.error("error creating a Future"),Wt.error(t),t}}handleFutureUpdated(e,t){const s=Se.buildFutureModel(e);this.addFutureModel(s);const o=`kos.future/${e.tracker||e.id}`;this.logger.debug(`publishing future update to ${o}`),G(o,t.body,t.headers)}};Wo([ce],Ot.prototype,"_futures",2);Wo([R({topic:"kos.future"})],Ot.prototype,"handleFutureUpdated",1);Ot=Wo([A(ye.type)],Ot);const Zi=Ot,{URL:Bt}=q(),{getOne:oh,postModel:rh,deleteModel:Qi}=V.build({basePath:`${Bt}/api/keyVal`}),mo=f.createLogger({name:"key-value-service",group:"Services"}),Xi=async(e,t)=>{await Qi({urlOverride:`${Bt}/api/keyVal/${e}/${t}`,id:t})},Ji=async(e,t,s)=>{const o=await rh({urlOverride:`${Bt}/api/keyVal/${e}/${t}`,model:s.toString()});if((o==null?void 0:o.status)!==200)throw mo.error("Failed to update studio-state data",o),new Error(`Failed to update studio-state data for namespace ${e}`);return o.data},ea=async(e="studio")=>{mo.debug("sending GET for studio-state");const t=await oh({urlOverride:`${Bt}/api/keyVal/${e}`});if((t==null?void 0:t.status)!==200)throw mo.error("Failed to retrieve studio-state data",t),new Error(`Failed to retrieve studio-state data for namespace ${e}`);return t.data},nh=async e=>{await Qi({urlOverride:`${Bt}/api/keyVal/${e}}`,id:""})},ih=Object.freeze(Object.defineProperty({__proto__:null,deleteKeyValue:Xi,deleteKeyValueNamespace:nh,getKeyValue:ea,updateKeyValue:Ji},Symbol.toStringTag,{value:"Module"}));var ah=Object.defineProperty,ch=Object.getOwnPropertyDescriptor,Zo=(e,t,s,o)=>{for(var r=o>1?void 0:o?ch(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&&ah(t,s,r),r};const ta="key-value-model";let St=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=Oe(),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 Ji(this.namespace,e,t),this.data[e]=t):(await Xi(this.namespace,e),this.data[e]=void 0)}async load(){this.logger.debug(`loading studio-state ${this.id}`);const e=await ea(this.namespace);this.data.setValues(e)}handleStateUpdate(e){e.namespace===this.namespace&&(this.data[e.key]=e.value)}handleStateDelete(e){e.namespace===this.namespace&&(this.data[e.key]=void 0)}};Zo([R({topic:"/keyVal/set"})],St.prototype,"handleStateUpdate",1);Zo([R({topic:"/keyVal/remove"})],St.prototype,"handleStateDelete",1);St=Zo([A(ta)],St);const Qo=new ge({class:St,type:ta}),{URL:Kt}=q(),{postModel:Xo,getOne:lh}=V.build({basePath:`${Kt}/api/kos-time`});f.createLogger({name:"kos-time-service",group:"Services"});const sa=async e=>{const t=await Xo({model:e,urlOverride:`${Kt}/api/kos/time/time`});if((t==null?void 0:t.status)!==200)throw Error("Failed to set time");return t.data},oa=async e=>{const t=await Xo({model:e,urlOverride:`${Kt}/api/kos/time/date`});if((t==null?void 0:t.status)!==200)throw Error("Failed to set time");return t.data},ra=async e=>{const t=await Xo({model:{},urlOverride:`${Kt}/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 lh({urlOverride:`${Kt}/api/kos/time/timezone`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set timezone");return e.data.timeZone},dh=Object.freeze(Object.defineProperty({__proto__:null,getTimezone:na,setDate:oa,setTime:sa,setTimezone:ra},Symbol.toStringTag,{value:"Module"}));var uh=Object.defineProperty,hh=Object.getOwnPropertyDescriptor,Us=(e,t,s,o)=>{for(var r=o>1?void 0:o?hh(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&uh(t,s,r),r};const rt="kos-time-model",gh="/kos/time/time",fh="/kos/time/day",mh="/kos/time/timezone";let Ge=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(this,"timezone");this.id=e,this.logger=s.logger,this.timezone=""}async updateSystemTime(e){await sa(e)}async updateSystemDate(e){await oa(e)}async updateSystemTimezone(e){await ra(e)}handleTimeChange(){G(Mt.TIME_CHANGE,{})}handleDayChange(){G(Mt.DAY_CHANGE,{})}async handleTimeZoneChange(){await this.retrieveTimezone(),G(Mt.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()}};Us([R({topic:gh,websocket:!0})],Ge.prototype,"handleTimeChange",1);Us([R({topic:fh,websocket:!0})],Ge.prototype,"handleDayChange",1);Us([R({topic:mh,websocket:!0})],Ge.prototype,"handleTimeZoneChange",1);Ge=Us([A(rt)],Ge);const ms={registration:{[rt]:{class:Ge,singleton:!0}},type:rt,predicate:te(rt),factory:H.Singleton.create(rt)};var ph=Object.defineProperty,yh=Object.getOwnPropertyDescriptor,ia=(e,t,s,o)=>{for(var r=o>1?void 0:o?yh(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&&ph(t,s,r),r};const aa="log-block-container-model";let ps=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(this,"_models");this.id=e,this.logger=s.logger,this._models=new fe({parentId:e,sortKey:"blockNum"})}getModel(e){return this._models.getModel(e)}get models(){return this._models}get data(){return this._models.data}addModel(e){this._models.addModel(e)}removeModel(e){this._models.removeModel(e)}async init(){this.logger.debug(`initializing log-block-container container ${this.id}`)}async load(){this.logger.debug(`loading log-block-container container ${this.id}`)}};ia([ce],ps.prototype,"_models",2);ps=ia([A(aa)],ps);const Je=xo(),bh=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},et=ca(),wh="/api/kos/logs/node/{nodeId}/streams",la=async()=>(bh.debug("sending GET for log-stream-container"),await Je.get(wh,{path:{nodeId:"primary"}},{destinationAddress:et})),da=async(e,t="primary")=>{await Je.post("/api/kos/logs/node/{nodeId}/{stream}/subscribe",{path:{nodeId:t,stream:e}},void 0,{destinationAddress:et})},ua=async e=>{await Je.post("/api/kos/logs/node/{nodeId}/{stream}/unsubscribe",{path:{nodeId:"primary",stream:e}},void 0,{destinationAddress:et})},vh=async()=>{await Je.post("/api/kos/logs/overrides",{},{level:"WARN",name:"com.example",nodeType:"java",type:"package"},{destinationAddress:et})},ha=async e=>await Je.get("/api/kos/logs/node/{nodeId}/{stream}/blocks",{path:{nodeId:"primary",stream:e}},{destinationAddress:et}),ga=async(e,t)=>await Je.get("/api/kos/logs/node/{nodeId}/{stream}/blocks/{blockId}",{path:{nodeId:"primary",stream:e,blockId:t}},{destinationAddress:et}),Mh=Object.freeze(Object.defineProperty({__proto__:null,createOverride:vh,getKosConnectionId:ca,getLogStreamBlock:ga,getLogStreamBlocks:ha,getLogStreams:la,subscribeToLogStream:da,unsubscribeFromLogStream:ua},Symbol.toStringTag,{value:"Module"}));var _h=Object.defineProperty,Eh=Object.getOwnPropertyDescriptor,Ih=(e,t,s,o)=>{for(var r=o>1?void 0:o?Eh(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&&_h(t,s,r),r};const fa="log-block-model";let po=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 ga(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}`)}};po=Ih([A(fa)],po);const Dt=new ge({class:po,type:fa}),js=new ge({class:ps,type:aa});js.addRelatedModel(Dt);var Th=Object.defineProperty,$h=Object.getOwnPropertyDescriptor,ma=(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 pa="log-stream-model";let ys=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(this,"nodeId");a(this,"_blocks");a(this,"name");a(this,"currentBlockId");a(this,"isResetting");a(this,"generatorInstance");a(this,"shouldStop",!1);this.id=e,this.logger=s.logger,this.currentBlockId="",this.name=t.name,this.nodeId=t.nodeId,this.isResetting=!0,this._blocks=js.instance(`${e}-blocks`).options({}).build()}get firstLineNum(){const e=this.populated[0];return e?e.startLineNum:0}get currentBlock(){const e=this.currentBlockId;return this._blocks.getModel(e)}get populated(){return this._blocks.data.filter(e=>e.lines.length>0)}get blocks(){return this._blocks.data}get totalLineCount(){return this.populated.reduce((e,t)=>e+t.lineCount,0)}accept(e){e.visit(this)}updateBlock(e){var o;let t=this._blocks.models.getModel(`${e.stream}-block-${e.blockNum}`);const s={nodeId:e.nodeId,blockNum:e.blockNum,endLineNum:e.endLineNum,lineCount:e.lineCount,startLineNum:e.startLineNum,stream:this.name,endTime:new Date(e.endTime),startTime:new Date(e.startTime)};t||(t=Dt.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=Dt.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 da(this.name)}async unsubscribe(){await ua(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 ha(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=Mi(()=>{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()}}};ma([ce],ys.prototype,"_blocks",2);ys=ma([A(pa)],ys);const _t=new ge({class:ys,type:pa});var Oh=Object.defineProperty,Sh=Object.getOwnPropertyDescriptor,Ce=(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&&Oh(t,s,r),r};const ya="log-stream-container-model",Dh="/kos/logs/subscription/addBlock/*",Ah="/kos/logs/subscription/updateBlock/*",Ch="/kos/logs/subscription/removeBlock/*",Rh="/kos/logs/subscription/lines/*",ba="/kos/logs/streams/add/*";let de=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(this,"selectedStream");a(this,"_models");this.id=e,this.logger=s.logger,this._models=new fe({parentId:e}),this.selectedStream=void 0}getModel(e){return this._models.getModel(e)}get models(){return this._models}get data(){return this._models.data}updateModel(e){}addModel(e){this._models.addModel(e)}removeModel(e){this._models.removeModel(e)}updateSelectedStream(e){this.selectedStream=e}handleStreamAdded(e){this.logger.debug(`Received topic: ${ba}`);const t=e.stream,s=_t.instance(t).options({name:t,nodeId:"primary"}).build();this.addModel(s)}handleAddBlock(e,t){this.logger.debug(`Received topic: ${t.headers.topic}`);const s=e.stream,o=this.models.getModel(s);o&&o.addBlock(e)}handleRemoveBlock(e,t){this.logger.debug(`Received topic: ${t.headers.topic}`);const s=e.stream,o=this.models.getModel(s);o&&o.removeBlock(e.blockNum)}handleUpdateBlock(e,t){this.logger.debug(`Received topic: ${t.headers.topic}`);const s=e.stream,o=this.models.getModel(s);o&&o.updateBlock(e)}handleLogLine(e,t){var r;this.logger.debug(`Received topic: ${t.headers.topic}`);const s=e.stream,o=this.models.getModel(s);o&&((r=o.currentBlock)==null||r.addLines(e.lines))}async init(){this.logger.debug(`initializing log-stream-container container ${this.id}`)}async subscribeToLogStream(e){const t=_t.instance(e).options({name:e,nodeId:"primary"}).build();this.addModel(t),await t.subscribe()}async load(){this.logger.debug(`loading log-stream-container container ${this.id}`);const[e,t]=await la();if(e){this.logger.error(`Error loading log-streams: ${e}`);return}t&&t.forEach(s=>{const o=_t.instance(s).options({name:s,nodeId:"primary"}).build();this.addModel(o)})}};Ce([ce],de.prototype,"_models",2);Ce([R({topic:[ba],websocket:!0})],de.prototype,"handleStreamAdded",1);Ce([R({topic:[Dh],websocket:!0})],de.prototype,"handleAddBlock",1);Ce([R({topic:[Ch],websocket:!0})],de.prototype,"handleRemoveBlock",1);Ce([R({topic:[Ah],websocket:!0})],de.prototype,"handleUpdateBlock",1);Ce([R({topic:[Rh],websocket:!0})],de.prototype,"handleLogLine",1);de=Ce([A(ya)],de);const Gt=new we({class:de,type:ya});Gt.addRelatedModel(_t);Gt.addRelatedModel(js);Gt.addRelatedModel(Dt);const Lh=e=>e.rank!==void 0,kh=e=>e.visibleRole!==void 0,xh=e=>e.color!==void 0,Ph=e=>{const t=e.info;return Lh(t)?t.rank:0},Nh=e=>{const t=e.info;return xh(t)?t.color:"orange"},Fh=e=>{const t=e.info;return kh(t)?t.visibleRole:"TECHNICIAN"},{URL:Jo}=q(),{getAll:Uh,postModel:wa}=V.build({basePath:`${Jo}/api/kos/troubles`}),va=async()=>await Uh({}),Ma=async(e,t)=>{try{const s=await wa({model:{},urlOverride:`${Jo}/api/kos/troubles/resolve/${e}`,tracker:t});return s!=null&&s.data&&Se.initiateFuture(s.data),s.data}catch{const o={id:t||"",endState:Ke.Fail,tracker:t,reason:"Failed to resolve trouble"};return Se.initiateFuture(o),o}},jh=async(e,t)=>{try{const s=await wa({model:e,urlOverride:`${Jo}/api/kos/troubles/resolve/`,tracker:t});return s!=null&&s.data&&Se.initiateFuture(s.data),s.data}catch{const o={id:t||"",endState:Ke.Fail,tracker:t,reason:"Failed to resolve troubles"};return Se.initiateFuture(o),o}},Bh=Object.freeze(Object.defineProperty({__proto__:null,bulkResolveTroubles:jh,getTroubles:va,resolveTrouble:Ma},Symbol.toStringTag,{value:"Module"})),bs="troubleDataMapper",Zt=new Map;Ro(bs,{register:(e,t)=>{var s;Zt.has(e)||Zt.set(e,[]),(s=Zt.get(e))==null||s.push(t)},execute:async(e,t)=>{const s=Zt.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 Ht="troubleMapper",Qt=new Map;Ro(Ht,{register:(e,t)=>{var s;Qt.has(e)||Qt.set(e,[]),(s=Qt.get(e))==null||s.push(t)},execute:async(e,t)=>{const s=Qt.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[Ht].register("nozzle",async e=>[e.data.nozzlePath]);C[Ht].register("path",async e=>[e.data.path]);const Kh=async e=>{const t=new Set,s=e.ifaces,o=s==null?void 0:s.map(n=>C[Ht].execute(n,e));return(await Promise.allSettled(o)).forEach(n=>{n.status==="fulfilled"&&n.value.forEach(i=>t.add(i))}),Array.from(t)},_a=async e=>{const t=e.ifaces,s=t==null?void 0:t.map(i=>C[bs].execute(i,e)),o=C[bs].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 Gh{constructor(){a(this,"type","ResolvableTrouble");a(this,"title","Resolvable Trouble");a(this,"subtitle","Trouble")}}class Hh{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 Gh;case"BlockPumpTrouble":return new Hh;default:return}}}var Vh=Object.defineProperty,Yh=Object.getOwnPropertyDescriptor,Ea=(e,t,s,o)=>{for(var r=o>1?void 0:o?Yh(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Vh(t,s,r),r};const nt="trouble-model";function Xt(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:b,...v},p){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=p.logger,this.type=l,this._troubleId=r,this._resolvable=!!t,this.ifaces=c,this.rank=i,this.role=h,this.color=b,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 Vo(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 _a(this)}get deferredCompanion(){const e=go(this.id,t=>Xt(t));if(e&&Xt(e.modelData))return e.modelData}get deferred(){return this.deferredCompanion?this.deferredCompanion.deferred:!1}get shouldDefer(){const e=go(this.id,t=>Xt(t));return e&&Xt(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 Ma(this._troubleId,e)}};Ea([hr()],ws.prototype,"resolve",1);ws=Ea([A(nt)],ws);const At={registration:{[nt]:{class:ws,singleton:!1}},type:nt,predicate:te(nt),factory:H.Factory.create(nt)};var zh=Object.defineProperty,qh=Object.getOwnPropertyDescriptor,Bs=(e,t,s,o)=>{for(var r=o>1?void 0:o?qh(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&zh(t,s,r),r};const Ur=f.createLogger({name:"trouble-container-model"});function jr(e){return C.propertyMapper.hasMapper(oe.TroubleRank)?C.propertyMapper.executeMapper(oe.TroubleRank,e):Ph(e)}function Br(e){return(C.propertyMapper.hasMapper(oe.TroubleColor)?C.propertyMapper.executeMapper(oe.TroubleColor,e):Nh(e)).toLowerCase()}function Kr(e){return(C.propertyMapper.hasMapper(oe.TroubleRole)?C.propertyMapper.executeMapper(oe.TroubleRole,e):Fh(e)).toLowerCase()}const Wh="trouble-container-model";class J{}a(J,"INDEX_TROUBLES_BY_IFACE","byIface"),a(J,"INDEX_TROUBLES_BY_TYPE","byType"),a(J,"INDEX_TROUBLES_BY_GROUP","byGroup"),a(J,"INDEX_TROUBLES_BY_DEFERRED","byDeferred"),a(J,"SORT_KEY_RANK","rank"),a(J,"TROUBLES_DEFERRED","true");let He=class{constructor(e){a(this,"id");a(this,"troubles");this.id=e,this.troubles=new fe({indexMap:{[J.INDEX_TROUBLES_BY_IFACE]:Kh,[J.INDEX_TROUBLES_BY_TYPE]:"type",[J.INDEX_TROUBLES_BY_GROUP]:"group",[J.INDEX_TROUBLES_BY_DEFERRED]:"deferred"},sortKey:J.SORT_KEY_RANK,parentId:e})}async load(){Ur.debug("loading trouble container");const e=await va();try{e==null||e.data.forEach(t=>{const s={...t,rank:jr(t),color:Br(t),role:Kr(t),id:String(t.id)},o=At.factory(`trouble-${t.id}`)(s);this.troubles.addModel(o)})}catch(t){throw Ur.error(t),t}}handleTroubleRemoved(e){const t=`trouble-${e}`,s=this.troubles.getModel(t);this.troubles.removeModel(t),s&&$e(s)}handleTroubleAdded(e){const t={...e,rank:jr(e),color:Br(e),role:Kr(e),id:String(e.id)};if(t.role==="NONE")return;const s=At.factory(`trouble-${e.id}`)(t);this.troubles.addModel(s)}};Bs([ce],He.prototype,"troubles",2);Bs([R({topic:"/kos/trouble/remove",websocket:!0,lifecycle:j.INIT})],He.prototype,"handleTroubleRemoved",1);Bs([R({topic:"/kos/trouble/add",websocket:!0})],He.prototype,"handleTroubleAdded",1);He=Bs([A(Wh)],He);const Jt="trouble-container-model",Ve={registration:{[Jt]:{class:He,singleton:!0}},type:Jt,predicate:te(Jt),factory:H.Singleton.create(Jt)},{URL:Ia}=q(),{getAll:Zh}=V.build({basePath:`${Ia}/api/kos/ota`}),Gr=f.createLogger({name:"ota-service",group:"Services"}),Qh=async()=>{Gr.debug("sending GET request to /api/kos/ota/artifacts");const e=await Zh({urlOverride:`${Ia}/api/kos/ota/artifacts`});return Gr.debug("getArtifacts - response:",e),e==null?void 0:e.data};var Xh=Object.defineProperty,Jh=Object.getOwnPropertyDescriptor,Ks=(e,t,s,o)=>{for(var r=o>1?void 0:o?Jh(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&&Xh(t,s,r),r};const Ta="ota-model",eg=e=>{let t=null;for(const s in e){const o=e[s],r=o.lastUpdateTime;(!t||t.lastUpdateTime<r)&&(t=o)}return t},ro=e=>{const t=e.artifactInfo,s=eg(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 mi);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 Qh();e&&e.forEach(t=>{const s=ro(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=ro(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=ro(t);s&&this.data.updateModel(s)})}catch(t){this.logger.error(`handleChangedArtifacts ${this.id} - error:`,t)}}};Ks([Ft({modelType:Ve.type})],Ye.prototype,"troubleContainer",2);Ks([R({topic:"/kos/ota/artifacts/all",websocket:!0})],Ye.prototype,"handleAllArtifacts",1);Ks([R({topic:"/kos/ota/artifacts/changed",websocket:!0})],Ye.prototype,"handleChangedArtifacts",1);Ye=Ks([A(Ta)],Ye);const vs=new we({class:Ye,type:Ta}),Hr=f.createLogger({name:"software-info-service",group:"Services"}),$a=async()=>{Hr.debug("sending GET for software-info");const[e,t]=await Hi.get("/api/kos/manifest/info");if(!t)throw Hr.error("Failed to fetch software-info",e),new ne("Failed to fetch software-info");return t},tg=Object.freeze(Object.defineProperty({__proto__:null,getSoftwareInfos:$a},Symbol.toStringTag,{value:"Module"}));var sg=Object.defineProperty,og=Object.getOwnPropertyDescriptor,rg=(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&&sg(t,s,r),r};const it="software-info-model";let yo=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 $a(),t=(e==null?void 0:e.nodes)||{};Y(()=>{const o=Object.keys(t).map(r=>t[r][0]).map(r=>({nodeName:r.node,group:this.groupBy(r.artifacts,"group")}));this.nodes=o})}catch(e){e instanceof ne&&this.logger.error("Failed to fetch software-info",e)}}};yo=rg([A(it)],yo);const Ms={registration:{[it]:{class:yo,singleton:!1}},type:it,predicate:te(it),factory:H.Factory.create(it)},{URL:Oa}=q(),{getOne:ng}=V.build({basePath:`${Oa}/api/kos/state`}),ig=f.createLogger({name:"state-bean-service",group:"Services"}),Sa=async({path:e})=>(ig.debug("sending GET for state-bean"),await ng({urlOverride:`${Oa}/api/kos/state/${e}`})),ag=Object.freeze(Object.defineProperty({__proto__:null,getStateBeanData:Sa},Symbol.toStringTag,{value:"Module"}));var cg=Object.defineProperty,lg=Object.getOwnPropertyDescriptor,Da=(e,t,s,o)=>{for(var r=o>1?void 0:o?lg(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&cg(t,s,r),r};const at="state-bean-model",dg=De("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=Fo.map(new Map),ao(t,this)}updateModel(e){ao(e,this)}handleConfigBeanUpdated(e){Object.entries(e).forEach(([t,s])=>{let o=s;typeof o=="string"&&Bo(o)&&(o=o.toLowerCase()=="true"),typeof o=="string"&&Ps(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 Sa({path:this.path});e!=null&&e.data&&this.updateProps(e.data)}};Da([R({topic:`/kos/state/${dg}`,websocket:!0})],_s.prototype,"handleConfigBeanUpdated",1);_s=Da([A(at)],_s);const Ct={registration:{[at]:{class:_s,singleton:!1}},type:at,predicate:te(at),factory:H.Factory.create(at)};var ug=Object.defineProperty,hg=Object.getOwnPropertyDescriptor,Aa=(e,t,s,o)=>{for(var r=o>1?void 0:o?hg(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&ug(t,s,r),r};const ct="state-prop-model",Vr=De("path");let Es=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())??""}};Aa([Ft({modelType:Ct.type,id:`state-bean-${Vr}`,options:{path:Vr}})],Es.prototype,"stateBean",2);Es=Aa([A(ct)],Es);const er={registration:{[ct]:{class:Es,singleton:!1}},type:ct,predicate:te(ct),factory:H.Factory.create(ct)},{URL:gg}=q(),{getAll:fg}=V.build({basePath:`${gg}/api/state-prop`}),mg=f.createLogger({name:"state-prop-service",group:"Services"}),pg=async()=>(mg.debug("sending GET for state-prop"),await fg({})),yg=Object.freeze(Object.defineProperty({__proto__:null,getStateProps:pg},Symbol.toStringTag,{value:"Module"})),{URL:tr}=q(),{getOne:Ca}=V.build({basePath:`${tr}/api/translation`}),Et=f.createLogger({name:"translation-service",group:"Services"}),bg=()=>{const e=window.location.origin,t=ae();return(t==null?void 0:t.host)||e},Ra=async(e,t)=>{Et.debug("sending GET for translation");const s=t??bg();try{const o=await fetch(`${s}${e}`);return o.status!==200?(Et.warn(`Failed to fetch translations at ${e}: ${o.status}`),{}):await o.json()}catch(o){throw Et.error("Error fetching translations",o),o}},wg=async()=>{Et.debug("getting localization descriptor");const e=await Ca({urlOverride:`${tr}/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},La=e=>async()=>{Et.debug("getting kos localization descriptor");const t=await Ca({urlOverride:`${tr}/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]},ka="langResolver";var vg=Object.defineProperty,Mg=Object.getOwnPropertyDescriptor,_g=(e,t,s,o)=>{for(var r=o>1?void 0:o?Mg(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 lt="translation-model";function Eg(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 xa(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=xa(e[o],r);return{...s,...n}}else return{...s,[r]:e[o]}},{})}function Pa(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]=Pa(e[o],t[o]):s[o]=t[o]);return s}const bo=(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)?bo(o,t):o},es=(e,t,s)=>{const o=/{{(.*?)}}/g,n=bo(e,t).replace(o,(c,l)=>Object.prototype.hasOwnProperty.call(s||{},l.trim())?s==null?void 0:s[l.trim()]:c);return bo(n,t)},Yr=(e,t)=>{if(t.includes(":")){const[s,o]=t.split(":");return{namespace:s,key:o}}else return{namespace:e,key:t}};let wo=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(ka),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 Ra(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=Pa(r,n.value))):this.logger.error(`failed to load translation ${this.id} for ${e[i]}`),r),{});this.data=xa(o)})}async init(){this.logger.debug(`initializing translation ${this.id}`)}exists(e){const{namespace:t,key:s}=Yr(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.warn("key is empty"),"";const{defaultValue:s,context:o,data:r}=Eg(t),{namespace:n,key:i}=Yr(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=>es(d,this.data,r)):es(this.data[c],this.data,r)}if(this.data[i]){const l=this.data[c];return Array.isArray(l)?l.map(d=>es(d,this.data,r)):es(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()})}};wo=_g([ks(),A(lt)],wo);const Is={registration:{[lt]:{class:wo,singleton:!1}},type:lt,predicate:te(lt),factory:H.Factory.create(lt)};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 dt="translation-container-model",$g=(e,t="/")=>e.join(t).replace(new RegExp(t+"{1,}","g"),t);function Og(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 $g([o,r])}let Ts=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||Og.bind(this),s.kosContext.set(ka,this.resolver),this.logger=s.logger,this._models=new fe({parentId:e})}set currentLocale(e){this.lang=e,this.models.data.forEach(t=>{t.currentLocale=e})}get defaultNamespace(){return this._defaultNamespace?this.getModel(`translation-${this._defaultNamespace}`):void 0}getModel(e){return this.logger.debug(`getting model ${e}`),this._models.getModel(`translation-${e}`)}get models(){return this._models}get data(){return this._models.data}async reload(){this._models.clear(),await ei(this);for(const e of this.namespaces){const t=this.resolveNamespace(e);await Q(t)}}resolveNamespace(e){if(this.descriptor.namespaces[e]){const s=Object.keys(this.descriptor.namespaces[e].locales)[0],o=this.descriptor.namespaces[e].locales[s].defaultLocale,r=Is.factory(`translation-${e}`)({kosParentId:this.id,namespace:e,rootUrl:this.rootUrl,currentLocale:this.lang,defaultLocale:o,descriptor:this.descriptor.namespaces[e].locales,resolver:this.resolver});return this.addModel(r),this.namespaces.includes(e)||Y(()=>{this.namespaces.push(e)}),r}else{this.logger.warn(`namespace ${e} not found in descriptor`);const s=Is.factory(`translation-${e}`)({kosParentId:this.id,namespace:e,rootUrl:this.rootUrl,currentLocale:this.lang,defaultLocale:this.lang,descriptor:{},resolver:this.resolver});return this.addModel(s),s}}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}`)}};Na([ce],Ts.prototype,"_models",2);Ts=Na([A(dt)],Ts);const ue={registration:{[dt]:{class:Ts,singleton:!0}},type:dt,predicate:te(dt),factory:H.Singleton.create(dt)},Sg={set(e,t){const s=k.getContext(ue.type);s&&s.set(e,t)},get(e){const t=k.getContext(ue.type);return t==null?void 0:t.get(e)}},Fa={async init(e){const t=ue.factory(e);return await Q(t),{translations:t}}},Dg=(e,t)=>{const s=t.type;return e[s]||(e[s]=[]),e[s].push(t),e},Ua="kos-ws-event",sr=Ut(Ua);var Ag=Object.defineProperty,Cg=Object.getOwnPropertyDescriptor,or=(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 Rg=({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:Rg({headers:r,body:o}),direction:s?"send":"receive",mocked:!!r.mocked};this.events.set(c,l),f.debug(`logged ${this.events.size} events`)}}};or([R({topic:[Pt.SEND]})],exports.WsEventModel.prototype,"handleSendEvent",1);or([R({topic:[Pt.RECEIVED]})],exports.WsEventModel.prototype,"handleReceiveEvent",1);exports.WsEventModel=or([A(sr.type)],exports.WsEventModel);const{URL:rr}=q(),{getOne:ja}=V.build({basePath:`${rr}/api/device`}),$s=f.createLogger({name:"device-service",group:"Services"}),Ba=async()=>{$s.debug("sending GET for device serial number");try{const e=await ja({urlOverride:`${rr}/api/kos/device/serialNumber`});return[void 0,e==null?void 0:e.data.serialNumber]}catch(e){if(e instanceof ne)return $s.error(`Error fetching device serial number: ${e.payload.error}`),[e.payload.error,void 0]}return["unknownError",void 0]},Ka=async()=>{$s.debug("sending GET for device details");try{const e=await ja({urlOverride:`${rr}/api/kos/device`});return e?[void 0,e.data]:["unknownError",void 0]}catch(e){if(e instanceof ne)return $s.error(`Error fetching device serial number: ${e.payload.error}`),[e.payload.error,void 0]}return["unknownError",void 0]},Lg=Object.freeze(Object.defineProperty({__proto__:null,getDeviceDetails:Ka,getSerialNumber:Ba},Symbol.toStringTag,{value:"Module"}));var kg=Object.defineProperty,xg=Object.getOwnPropertyDescriptor,Ga=(e,t,s,o)=>{for(var r=o>1?void 0:o?xg(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&kg(t,s,r),r};const Ha="device-model",Pg="/kos/criticalData/changed",Ng="/kos/criticalData/available";let Os=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 Ka();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 Ba();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()}};Ga([R({topic:[Pg,Ng],websocket:!0})],Os.prototype,"handleCriticalDataChanged",1);Os=Ga([A(Ha)],Os);const Ss=new we({class:Os,type:Ha});var Fg=Object.defineProperty,Ug=Object.getOwnPropertyDescriptor,jg=(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&&Fg(t,s,r),r};const Va="network-interface-model";let vo=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}`)}};vo=jg([A(Va)],vo);const nr=new ge({class:vo,type:Va}),{URL:Bg}=q(),{getAll:Kg}=V.build({basePath:`${Bg}/api/kos/network/interfaces`}),zr=f.createLogger({name:"network-interface-service",group:"Services"}),Ya=async()=>{zr.debug("sending GET for copy-logs");try{const e=await Kg({});return[void 0,e==null?void 0:e.data]}catch(e){if(e instanceof ne)return zr.error(`Error fetching log file size: ${e.payload.error}`),[e.payload.error,void 0]}return["unknownError",void 0]},Gg=Object.freeze(Object.defineProperty({__proto__:null,getNetworkInterfaces:Ya},Symbol.toStringTag,{value:"Module"}));var Hg=Object.defineProperty,Vg=Object.getOwnPropertyDescriptor,za=(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&&Hg(t,s,r),r};const qa="network-interface-container-model";let Ds=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(this,"_models");this.id=e,this.logger=s.logger,this._models=new fe({parentId:e,indexMap:{byCategory:"category"}})}getModel(e){return this._models.getModel(e)}get models(){return this._models}get data(){return this._models.data}addModel(e){this._models.addModel(e)}removeModel(e){this._models.removeModel(e)}async init(){this.logger.debug(`initializing network-interface-container container ${this.id}`)}async refreshInterfaces(){this.logger.debug("refreshing interfaces");const[e,t]=await Ya();if(e){this.logger.error(`Error loading network interfaces: ${e}`);return}t&&t.forEach(s=>{const o=nr.instance(s.name).forceUpdate.options(s).build();this.addModel(o)})}async load(){this.logger.debug(`loading network-interface-container container ${this.id}`),this.refreshInterfaces()}};za([ce],Ds.prototype,"_models",2);Ds=za([A(qa)],Ds);const Rt=new we({class:Ds,type:qa});Rt.addRelatedModel(nr);const{URL:Yg}=q(),{getAll:zg}=V.build({basePath:`${Yg}/api/kos/storage/devices`}),qr=f.createLogger({name:"storage-device-service",group:"Services"}),Wa=async()=>{qr.debug("sending GET for storage-device");const e=await zg({});return!(e!=null&&e.data)||e.status!==200?(qr.error("Failed to retrieve storage-device data",e),[]):e.data},qg=Object.freeze(Object.defineProperty({__proto__:null,getStorageDevices:Wa},Symbol.toStringTag,{value:"Module"}));var Wg=Object.defineProperty,Zg=Object.getOwnPropertyDescriptor,Qg=(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&&Wg(t,s,r),r};const Za="storage-device-model";let Mo=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}`)}};Mo=Qg([ks(),A(Za)],Mo);const As=new ge({class:Mo,type:Za});var Xg=Object.defineProperty,Jg=Object.getOwnPropertyDescriptor,ir=(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&&Xg(t,s,r),r};const Qa="storage-device-container-model",ef="/kos/storage";let Lt=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(this,"_models");this.id=e,this.logger=s.logger,this._models=new fe({parentId:e})}getModel(e){return this._models.getModel(e)}get models(){return this._models}get data(){return this._models.data}addModel(e){this._models.addModel(e)}removeModel(e){this._models.removeModel(e)}async init(){this.logger.debug(`initializing storage-device-container container ${this.id}`)}get isStorageInserted(){return this.data.length>0}get volumes(){return this.data}handleStorageAvailability(e){this._models.data.filter(s=>!e.find(o=>o.id===s.id)).forEach(s=>{this.removeModel(s.id)}),e.forEach(s=>{const o=this.getModel(s.id);if(o){const r={...s,kosParentId:this.id};o.updateModel(r)}else{const r={...s,kosParentId:this.id},n=As.instance(s.id).options(r).build();this.addModel(n)}})}async load(){this.logger.debug(`loading storage-device-container container ${this.id}`),(await Wa()).forEach(t=>{const s={...t,kosParentId:this.id},o=As.instance(t.id).options(s).build();this.addModel(o)})}};ir([ce],Lt.prototype,"_models",2);ir([R({topic:ef,websocket:!0})],Lt.prototype,"handleStorageAvailability",1);Lt=ir([A(Qa)],Lt);const ze=new we({class:Lt,type:Qa});ze.addRelatedModel(As);const{URL:ar}=q(),{getAll:tf,postModel:sf}=V.build({basePath:`${ar}/api/kos/update/available`}),Wr=f.createLogger({name:"usb-update-service",group:"Services"}),Xa=async()=>{Wr.debug("sending GET for usb-update");const e=await tf({urlOverride:`${ar}/api/kos/update/available`});return!(e!=null&&e.data)||(e==null?void 0:e.status)!==200?(Wr.error("Failed to retrieve usb-update data",e),[]):e.data},Ja=async(e,t,s)=>{const o=await sf({model:{manifestId:e,deviceId:t},tracker:s,urlOverride:`${ar}/api/kos/update/install`});if(!(o!=null&&o.data))throw new Error("No response from server");return o.data},of=Object.freeze(Object.defineProperty({__proto__:null,getAvailableUpdates:Xa,installUpdate:Ja},Symbol.toStringTag,{value:"Module"}));var rf=Object.defineProperty,nf=Object.getOwnPropertyDescriptor,ec=(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&&rf(t,s,r),r};const tc="usb-update-model";let Cs=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 Vo(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}`),Ja(this.manifestId,this.deviceId,e)}async init(){this.logger.debug(`initializing usb-update ${this.id}`)}async load(){this.logger.debug(`loading usb-update ${this.id}`)}};ec([hr()],Cs.prototype,"install",1);Cs=ec([A(tc)],Cs);const cr=new ge({class:Cs,type:tc});var af=Object.defineProperty,cf=Object.getOwnPropertyDescriptor,Gs=(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 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 fe({parentId:e})}getModel(e){return this._models.getModel(e)}get models(){return this._models}get data(){return this._models.data}addModel(e){this._models.addModel(e)}removeModel(e){this._models.removeModel(e)}get activeUpdate(){return this._activeUpdate}reset(){this.clearActiveUpdate()}clearActiveUpdate(){this._activeUpdate=void 0}updateActiveUpdate(e){this._activeUpdate=e}get isUsbInserted(){return this.storageService.isStorageInserted}get hasAvailableUpdates(){return this._models.data.length>0}async syncAvailableUpdates(){const e=await Xa();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=cr.instance(o).forceUpdate.options({...s,createTime:new Date(s.createTime)}).build();this.addModel(r)}),this.data.length===1?this.updateActiveUpdate(this.data[0]):this.clearActiveUpdate()})}usbInsertedEffect(){this.isUsbInserted?this.syncAvailableUpdates():(this._models.clear(),this.clearActiveUpdate())}async init(){this.logger.debug(`initializing usb-update-container container ${this.id}`)}unload(){var e;(e=this.disposer)==null||e.call(this)}async activate(){this.logger.debug(`activating usb-update-container container ${this.id}`),await this.syncAvailableUpdates()}async load(){this.logger.debug(`loading usb-update-container container ${this.id}`)}};Gs([Ft({modelType:ze.type})],qe.prototype,"storageService",2);Gs([ce],qe.prototype,"_models",2);Gs([Pn({dependencies:e=>[e.isUsbInserted]})],qe.prototype,"usbInsertedEffect",1);qe=Gs([A(sc)],qe);const kt=new we({class:qe,type:sc});kt.addRelatedModel(cr);const lf=()=>({...{[Xe.type]:{class:Gi},[ye.type]:{class:Zi,singleton:!0},...z.registration,...Ae.registration,...Ve.registration,...Is.registration,...ue.registration,[sr.type]:{class:exports.WsEventModel,singleton:!0},...Ct.registration,...er.registration,...ms.registration}}),lr=lf(),df={models:lr,preloadModels:[]},uf=!0,oc=e=>()=>{const t=lr;return ri(_o)(At).model(Ve).model(ze).model(kt).model(Ss).model(vs).model(It).model(Ms).model(Qo).model(Rt).model(zi,uf).model(Gt),Object.keys(t).forEach(s=>{const o=t[s];oi(_o)(s,o)}),{preload:$.model.preloadModel(e),model:$.model.register(e),companion:$.companion.register(e),legacy:$.model.registerLegacyModel(e)}},re={};re.core={models:oc(re)};re.preload=$.model.preloadModel(re);re.model=$.model.register(re);re.companion=$.companion.register(re);re.legacy=$.model.registerLegacyModel(re);const _o=re;class hf{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 gf=async(e,t)=>{const s=Qo.instance(e).options({}).build(),o=t?`${t}-`:"";return await Q(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:()=>{$e(s)}}},rc="kos:service:region",nc="regionId",ff=`${rc}-${nc}`,ic=async e=>{const t=Ae.factory(ff)({path:rc,attribute:nc});await Q(t),t.updateProperty(e)},dr="/kos-timer-event",ur="defaultTimerEnd",ut=f.createLogger({name:"timer-manager"}),mf=e=>e.updateProperty!==void 0;class ac{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,mf(s)&&N(()=>{f.info(`Updating config value timer ${t} with new timeout value ${s.value}`);const n=s.value||60;this.updateTimeout(n)}),this.addTimeoutAction({name:ur}),o&&o.forEach(n=>{this.addTimeoutAction(n)})}start(){if(this.state==="active"){ut.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&&(ut.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;ut.debug(`Executing timer action ${s.name} at ${t}`),(o=s.action)==null||o.call(s,s.name,t),this.notifyTimeoutAction(s),s.singleUse&&(ut.info(`${this.name} Removing single-use action ${s.name}`),this.removeTimeoutAction(s.name))})}notifyTimeoutAction(t){G(dr,{name:this.name,action:t.name,remainingTime:this.remainingTime})}}const ht=new Map,Pe=(e,t)=>{const s=ht.get(e);if(!s){ut.error(`Timer ${e} not found`);return}t(s)},cc={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(ht.has(e))return ht.get(e);const o=new ac(e,t,s);return ht.set(e,o),o},getTimer(e){return ht.get(e)},clearTimer(e){Pe(e,t=>t.pause())},restartTimer(e){Pe(e,t=>t.restart())},resetTimer(e){Pe(e,t=>t.reset())},addTimeoutAction(e,t){Pe(e,s=>s.addTimeoutAction(t))},removeTimeoutAction(e,t){Pe(e,s=>s.removeTimeoutAction(t))},startTimer(e){Pe(e,t=>t.start())}},lc="kos:service:region:settings",dc="timeZone",pf=`${lc}-${dc}`,Eo=async e=>{const t=Ae.factory(pf)({path:lc,attribute:dc});await Q(t),t.updateProperty(e)},yf=e=>!e||!e.data;function hr(e={}){const{alias:t,namespace:s}=e;return(o,r,n)=>{o[Ue]=o[Ue]||{};const i=n.value,c=async function(...l){const d=Nt();f.debug(`Calling future service ${r} with tracker ${d}`);const u=Se.initiateFuture({tracker:d,id:Uo});s&&(u.namespace=s),f.debug(`waiting for future ${u.id} to be ready`),await Q(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,[...l,d]);f.debug(`received future response for ${d}`,h);const b=yf(h)?h:h==null?void 0:h.data;return b?(b.progress=1,f.debug("mapping future response to future model"),u.endState?f.debug(`future ${u.id} has already completed. Not updating the model`):zo(b,u)):this.futureHandler.removeFuture(t),b}catch(h){throw f.error(h),h}};o[Ue][r]={handler:c}}}const bf=({path:e})=>(t,s)=>{t[P]=t[P]||{},t[P][s]={modelType:Ct.type,id:`${Ct.type}-${e}`,options:{path:e},lifecycle:j.INIT}};function wf(e){const{path:t,attribute:s}=e;return(o,r)=>{o[P]=o[P]||{},o[P][r]={modelType:er.type,id:`${t}-${s}`,options:{path:t,attribute:s},lifecycle:j.INIT}}}const Be=f.createLogger({name:"services",group:"Services"}),vf=async(e,t)=>uc(e,t,`${exports.BASE_URL}/api/server/login`),uc=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()},Mf=async e=>hc(e,`${exports.BASE_URL}/api/server/startPasswordReset`,""),hc=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()},_f=async(e,t)=>gc(e,t,`${exports.BASE_URL}/api/server/resetPassword`),gc=async(e,t,s=`${exports.BASE_URL}/api/resetPassword`)=>{Be.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(Be.debug(`password reset returned status ${o.status}`),!o.ok){Be.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()},Ef=async(e,t,s)=>fc(e,t,s,`${exports.BASE_URL}/api/server/acceptInvite`),fc=async(e,t,s,o=`${exports.BASE_URL}/api/server/acceptInvite`)=>{Be.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(Be.debug(`invitation accept returned status ${r.status}`),!r.ok){Be.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()},If=Ie.keyframes`
|
|
76
|
+
["${t}"]`;if(o?(b=this.fosSocket)==null?void 0:b.connectionEstablished:(v=this.socket)==null?void 0:v.connectionEstablished){const M=o?this.fosSocket:this.socket;(p=M==null?void 0:M.socket)==null||p.send(d)}else{Ee.debug("no connection adding to offline messages");const M=o?this.fosSocket:this.socket;M==null||M.addOfflineMessage(d)}}subscribeTopic({topic:t,callback:s,fos:o,bridge:r}){const{unsubscribe:n,count:i}=U(t,s);return Ee.debug(`Topic ${t} currently has ${i} subscribers`),this._sendSubscriptionMessage(t,"subscribe",o,r),()=>{const{count:c}=n();Ee.debug(`Topic ${t} currently has ${c} subscribers`),c===0&&this._sendSubscriptionMessage(t,"unsubscribe",o)}}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(ks,"_instance");const I=T.getLogger("kos-model"),Ar="kos.extension.model.loader",gd=({subscription:e,modelData:t,skipParse:s,model:o,resolvedTopic:r})=>n=>{try{if(o!=null&&o.isReady){const i=ho(n,s),c=e.transform(i);if(e.condition(c,t,n))return e.handler.call(t,c,n,t)}else{f.warn(`model ${o==null?void 0:o.modelId} not ready. adding message for topic ${r} to offline queue`);const i=()=>{f.warn(`processing offline message for ${r} on model ${o==null?void 0:o.modelId}`);const c=ho(n,s),l=e.transform(c);if(e.condition(l,t))return e.handler.call(t,l,n,t)};o._offlineQueue.push(i)}}catch(i){I.error(i)}},fd=(e,t,s)=>{const o=new RegExp(".*({PROP_(.+)})");let r=e.includes("{MODEL_ID}")?e.replace("{MODEL_ID}",t):e;const n=r.match(o);if(n&&s&&Object.getOwnPropertyNames(s).includes(n[2])){const i=s[n[2]];r=r.replace(n[1],i)}return r};class Qn{constructor({modelTypeName:t,id:s,modelData:o,modelManager:r}){a(this,"_id");a(this,"_status");a(this,"_activeStatus");a(this,"_onlineStatus");a(this,"_subscriptions");a(this,"_onlineSubscriptions");a(this,"modelData");a(this,"modelTypeName");a(this,"initialized");a(this,"loaded");a(this,"_offlineQueue");a(this,"fsmService");a(this,"disposers",[]);a(this,"modelManager");a(this,"_companionModels");this.modelManager=r,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,this.fsmService=nd(this),this._subscriptions=[],this._onlineSubscriptions=[],this.fsmService.service.send(S.CREATE),this._companionModels=new Map,this._offlineQueue=[],w.makeAutoObservable(this)}get companionModels(){return this._companionModels}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}isActive(){return this._status===y.ACTIVE}isOnline(){return this._onlineStatus===y.ONLINE}isReady(){return this._status===y.READY}async deactivate(){var t,s;I.debug(`deactivating model ${this.modelTypeName} with id ${this.modelId}`);try{const o=x.getContext(this.modelId);await((s=(t=this.modelData)==null?void 0:t.deactivate)==null?void 0:s.call(t,o)),I.debug(`Model ${this.modelTypeName} with id ${this.modelId} deactivated`)}catch(o){throw I.debug(`Model ${this.modelId} failed to deactivated`),o}}transition(t,s,o=y.FAILED){const r=this;if((s===y.ACTIVE||s===y.INACTIVE?r.activeStatus:r.status)===s)return I.debug(`model ${this.modelId} already at target state ${s}. resolving immediately. `),Promise.resolve();let i;return new Promise((c,l)=>{i=w.autorun(()=>{const d=s===y.ACTIVE||s===y.INACTIVE?r.activeStatus:r.status;d===o?l(Error(`Failed to transition ${r.modelId} to ${t}`)):d===s&&c()}),r.fsmService.service.send(t)}).then(()=>{i==null||i()})}async activate(){var t,s;I.debug(`activating model ${this.modelTypeName} with id ${this.modelId}`),await ot(this,j.ACTIVATE);try{const o=x.getContext(this.modelId);await((s=(t=this.modelData)==null?void 0:t.activate)==null?void 0:s.call(t,o)),I.debug(`Model ${this.modelTypeName} with id ${this.modelId} activated`)}catch(o){throw I.debug(`Model ${this.modelId} failed to activate`),o}}async whenInitialized(){const t=this;let s,o;return new Promise((r,n)=>{s=w.when(()=>t._status===y.FAILED,()=>{n(Error(`Failed to load ${t.modelId} model ${t.modelTypeName}`))}),o=w.when(()=>t.initialized,()=>{r()})}).then(()=>{s==null||s(),o==null||o()})}async whenReady(){const t=this;let s,o;return new Promise((r,n)=>{s=w.when(()=>t._status===y.FAILED,()=>{n(Error(`Failed to load ${t.modelId} model ${t.modelTypeName}`))}),o=w.when(()=>t._status===y.READY,()=>{r()})}).then(()=>{s==null||s(),o==null||o()})}async ready(){var t,s;if(this.fsmService.service.machine.current===y.READY){I.debug(`already readying model ${this.modelTypeName} with id ${this.modelId} returning`);return}try{I.debug(`readying model ${this.modelTypeName} with id ${this.modelId}`),await ot(this,j.READY),await zn(this,xo.READY,j.READY);const o=x.getContext(this.modelId);await((s=(t=this.modelData)==null?void 0:t.ready)==null?void 0:s.call(t,o)),this._offlineQueue.length>0&&(f.warn(`processing ${this._offlineQueue.length} messages offline queue for ${this.modelId}`),this._offlineQueue.forEach(r=>r()),f.info(`offline queue processed for ${this.modelId}`)),this._offlineQueue=[],I.debug(`Model ${this.modelId} is ready`)}catch(o){throw I.error(o),Error(o)}}async load(){var t,s,o;if(this.fsmService.service.machine.current===y.LOADED||this.fsmService.service.machine.current===y.LOADING){I.debug(`already loaded model ${this.modelTypeName} with id ${this.modelId} returning`);return}I.debug(`loading model ${this.modelTypeName} with id ${this.modelId}`),await ot(this,j.LOAD),I.debug(`loading model ${this.modelTypeName} with id ${this.modelId}`);try{const r=x.getContext(this.modelId),n=await A.loader.executeLoader(Ar,{});n&&(I.info(`setting loaded context for ${this.modelId}, type: ${this.modelTypeName}`),r==null||r.set(Ar,n)),await((s=(t=this.modelData)==null?void 0:t.load)==null?void 0:s.call(t,r)),this.loaded=!0,I.debug(`Model ${this.modelTypeName} with id ${this.modelId} loaded`),this.registerSubscribers(j.LOAD);const i=((o=this.modelData)==null?void 0:o[bt])||{};Object.keys(i).forEach(c=>{const l=i[c].value.bind(this.modelData),d=function(){I.info(`running effect ${c} for model type ${this.modelTypeName} id: ${this.modelId}`),w.runInAction(()=>{l.apply(this.modelData)})};if(i[c].dependencies){const u=()=>i[c].dependencies(this.modelData),h=w.reaction(u,d.bind(this));this.disposers.push(h)}else{const u=w.autorun(d.bind(this));this.disposers.push(u)}})}catch(r){throw I.error(`Model ${this.modelId} failed to load`),r}}async unload(){var t,s;I.debug(`unloading model ${this.modelTypeName} with id ${this.modelId}`);try{const o=this.getChildren().map(n=>{var i;return(i=n.unload)==null?void 0:i.call(n)}).filter(n=>!!n);await Promise.allSettled(o);const r=x.getContext(this.modelId);await((s=(t=this.modelData)==null?void 0:t.unload)==null?void 0:s.call(t,r)),this.loaded=!1,this._onlineSubscriptions.forEach(n=>n()),this._onlineSubscriptions=[],I.debug(`Model ${this.modelTypeName} with id ${this.modelId} unloaded`),this.disposers.forEach(n=>n()),this.disposers=[]}catch(o){throw I.debug(`Model ${this.modelId} failed to unload`),o}}async init(){var t,s;I.debug(`initializing init dependencies of model ${this.modelTypeName} with id ${this.modelId}`),await ot(this,j.INIT),I.debug(`initializing model ${this.modelTypeName} with id ${this.modelId}`);try{const o=x.getContext(this.modelId);await((s=(t=this.modelData)==null?void 0:t.init)==null?void 0:s.call(t,o)),this.initialized=!0,I.debug(`Model ${this.modelTypeName} with id ${this.modelId} initialized`);const r=U("/kosCore/online",async()=>{I.debug(`online subscription called for ${this.modelId} waiting for ready state`),await this.whenReady(),I.debug(` ${this.modelId} is ready. Going online`),this.fsmService.service.send(S.GO_ONLINE)}),n=U("/kosCore/offline",async()=>{I.debug(` offline sub called for model ${this.modelId}. Going offline`),this.fsmService.service.send(S.GO_OFFLINE)});this._onlineSubscriptions.push(r.unsubscribe),this._onlineSubscriptions.push(n.unsubscribe),this.registerSubscribers(j.INIT)}catch(o){throw I.error(`Model ${this.modelId} failed to initialize`),o}}_registerSubscription(t,s,o){if(t.websocket){I.debug(`subscribing ${s} via WebSocketTransport`);const r=ks.getInstance().subscribeTopic({topic:s,callback:o,fos:t.fos,bridge:t.bridge});this._subscriptions.push(r)}else{I.debug(`subscribing ${s} directly to EventBus`);const{unsubscribe:r}=U(s,o);this._subscriptions.push(r)}}async registerSubscribers(t){var o;I.debug(`registering subscribers in ${this.modelTypeName} with id ${this.modelId}`);const s=((o=this.modelData)==null?void 0:o[ee])||{};I.debug(`found ${Object.keys(s).length} topics to subscribe to`),Object.keys(s).forEach(r=>{const n=s[r].lifecycle;if(t&&t!==n)return;const i=!!s[r].skipParse;I.debug(`found subscription for ${r}`),I.debug(`${r} skipParse: ${i}`);const c=fd(r,this.modelId,this.modelData);I.debug(`resolved subscription to ${c}`);const l=gd({model:this,resolvedTopic:c,skipParse:i,modelData:this.modelData,subscription:s[r]});this._registerSubscription(s[r],c,l)})}async online(){var s,o;I.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;I.debug(`offline model ${this.modelTypeName} with id ${this.modelId}`),this._subscriptions.forEach(r=>{r()}),this._subscriptions=[];const t=x.getContext(this.modelId);await((o=(s=this.modelData)==null?void 0:s.offline)==null?void 0:o.call(s,t))}accept(t){t.visit(this)}getChildren(){const t=this.getDecoratedChildren(),s=this.getResolvedChildren(t),o=this.getAdditionalChildren(),r=Array.from(new Set([...s,...o,...Array.from(this._companionModels.values())]));return this.filterAndMapToModels(r)}clearCompanionModels(){this._companionModels.clear()}addCompanionModel(t){this._companionModels.set(t.modelTypeName,t)}getDecoratedChildren(){var t;return((t=this.modelData)==null?void 0:t[mt])||{}}getResolvedChildren(t){return Object.keys(t).map(s=>{var o;return Wn((o=this.modelData)==null?void 0:o[s])}).filter(s=>!!s).flat()}getAdditionalChildren(){var t,s;return((s=(t=this.modelData)==null?void 0:t.getChildren)==null?void 0:s.call(t))||[]}filterAndMapToModels(t){const s=t.map(o=>this.modelManager.getModelById(o.id||"")).filter(o=>!!o);return s.forEach(o=>{try{x.setParentContext(o.modelId,this.modelId)}catch{I.error(`failed to set parent context for model ${o.modelId} with parent ${this.modelId}`)}}),s}}const Xn=e=>typeof e=="function",Jn=10,L=f.createLogger({name:"kos-model-manager"});class ei{constructor(){a(this,"_modelsById");a(this,"_registry");a(this,"_usesCache");a(this,"_isPreloaded",!1);a(this,"_preloaded");a(this,"_usedByCache");a(this,"_toDelete");this._modelsById=w.observable.map(new Map),this._registry={models:{},preloadModels:[]},this._preloaded=[],this._usedByCache=new Map,this._usesCache=new Map,this._toDelete=new Map,globalThis.kos=globalThis.kos||{},globalThis.kos.modelManager=this}get registry(){return this._registry}set registry(t){this._registry=t}get preloadedModels(){return L.debug("preloading models"),this._isPreloaded?(L.error("returning cased preloaded models"),this._preloaded):(this._preloaded=this._registry.preloadModels.map(t=>(L.debug(`preloading ${t}`),typeof t=="string"?this.createModelInstance(t).model:this.createModelInstance(t.modelType,t.modelId,t.options).model)),this._preloaded)}get models(){return Array.from(this._modelsById.values())}removeModel(t){var r;const s=this;L.debug(`Removing models: Currently ${s._modelsById.size} models cached`);const o={visit(n){var c;const i=n.getChildren();i==null||i.forEach(l=>{var d;(d=l.accept)==null||d.call(l,this)}),L.debug(`removing ${n.modelTypeName} model ${n.modelId} from model manager`),(c=n.offline)==null||c.call(n),n.clearCompanionModels(),x.deleteContext(n.modelId),s._modelsById.delete(n.modelId),s._toDelete.delete(n.modelId)}};(r=t.accept)==null||r.call(t,o),L.debug(`Models Removed: Currently ${s._modelsById.size} models cached`)}addModel(t){L.debug("adding model to kosModelManager");const s=this.getModelById(t.modelId)||t;return this._modelsById.set(s.modelId,s),s}hasModel(t){return!!t&&!!this.getModelById(t)}getModelById(t){return this._toDelete.has(t)?void 0:this._modelsById.get(t)}getModelsByType(t,s){return Array.from(this._modelsById.values()).filter(r=>r.modelTypeName===t).filter(r=>!this._toDelete.get(r.modelId)).filter(r=>s?s(r.modelData):!0).map(r=>r.modelData)}getModelTypeRegistry(t){var o,r;const s=(r=(o=this._registry)==null?void 0:o.models)==null?void 0:r[t];if(!s)throw Error(`No registration defined for model type ${t}}`);return s}getModelSubscriptions(t){var s;return((s=this.getModelTypeRegistry(t))==null?void 0:s.subscriptions)||{}}getDataModelBuilder(t){var s;return(s=this.getModelTypeRegistry(t))==null?void 0:s.builder}getModelFactory(t){return Ut(t)}restoreModelFromDeleteCache(t){if(t&&this._toDelete.has(t)){const s=this._toDelete.get(t);this._toDelete.delete(t),this._modelsById.set(t,s)}}addDependency(t,s){Tr.cancelDeletion(s),this.restoreModelFromDeleteCache(s),this._usedByCache||(this._usedByCache=new Map),this._usesCache||(this._usesCache=new Map);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))}removeDependency(t,s){this._usedByCache||(this._usedByCache=new Map),this._usesCache||(this._usesCache=new Map);const o=this._usedByCache.get(s)||[],r=o.indexOf(t);r>-1&&(o.splice(r,1),this._usedByCache.set(s,o));const n=this._usesCache.get(t)||[],i=n.indexOf(s);i>-1&&(n.splice(i,1),this._usesCache.set(t,n))}async reloadModel(t){if(t.id){L.info(`fetching model ${t.id} to reload`);const s=this.getModelById(t.id);s?(L.info(`reloading model ${t.id}`),await s.transition(S.RESET,y.RESETTING)):L.warn(`${t.id} not found in KOS Model Manager`)}}canDestroyModel(t){const s=this._usedByCache.get(t);return s&&s.length>0?(L.info(`model ${t} is used by ${s.join(", ")}. Returning without destroying.`),!1):!0}async initiateDestroyModel(t){if(!t.id)throw new Error("Model ID is required");const s=t.id;if(this.canDestroyModel(s)){L.info(`fetching model ${s} to add to deletion queue`);const o=this.getModelById(t.id);o&&(this._modelsById.delete(s),this._toDelete.set(s,o),Tr.addToDeletionQueue(t.id,setTimeout(async()=>{this.destroyModel(o)},Jn)))}}registerCompanionModel(t,s){this.registry.companionModels||(this.registry.companionModels={}),this.registry.companionModels[t]||(this.registry.companionModels[t]=[]),!!this.registry.companionModels[t].find(r=>r.type===s)||this.registry.companionModels[t].push({type:s})}registerModel(t){const s=t.type;this.registry.models||(this.registry.models={}),this.registry.models[s]||(L.info(`Model with type ${s} doesn't exist. Adding new registration`),this.registry.models={...this.registry.models,...t.registration})}async destroyModel(t){var s;if(t!=null&&t.modelId){const o=t.modelId;this.canDestroyModel(o)&&(t?(L.info(`destroying model ${o}`),await((s=t.unload)==null?void 0:s.call(t)),this.removeModel(t)):L.warn(`${o} not found in KOS Model Manager`))}}createModelInstance(t,s,o){var r;L.debug(`retrieving new model instance of type ${t} ${s||""}`);try{const n=this.getModelTypeRegistry(t),i=n.create,c=n.class,l=n.singleton?t:s;if(this.restoreModelFromDeleteCache(l),this.hasModel(l))L.debug(`model ${l} found in cache`);else{L.debug(`model ${l} not found in cache...creating`);const u=i?i({modelTypeId:t,id:l,options:o}):new c(l,o||{}),h=new Qn({modelTypeName:t,id:l,modelData:u,modelManager:this});this._modelsById.set(l,h),(r=this.registry.companionModels)!=null&&r[t]&&this.registry.companionModels[t].forEach(v=>{let p=v.type;if(Xn(p)){L.debug(`using companionModelType factory for ${t}`);const C=p(h.modelData,o);if(!C)return;p=C,L.debug(`factory resolved to type ${p}`)}const M=`${p}-${l}`,$=this.createModelInstance(p,M,{data:o,companionParent:h.modelData,kosParentId:l});h.addCompanionModel($.model)})}const d=this.getModelById(l);return L.debug(`returning model ${l} from createModelInstance`),{model:d,data:d.modelData}}catch(n){throw L.error(`Error creating model instance: ${n}`),n}}static create(t,s){const o=this.getInstance(s);return o.registry=t,o}static getInstance(t){var s,o;return(!((s=globalThis.kos)!=null&&s.modelManager)||t)&&(L.debug("Creating new instance of KosModelManager"),new this),(o=globalThis.kos)==null?void 0:o.modelManager}}const md=async({context:e,extension:t})=>{const s=await A.loader.executeLoader(t,{});return e==null||e.set(t,s),s},pd=async({extension:e,contextData:t,data:s})=>await A.dataMapper.executeMapper(e,s,t),yd=async({extension:e,contextData:t,data:s})=>await A.propertyMapper.executeMapper(e,s,t),bd=Object.freeze(Object.defineProperty({__proto__:null,executeDataMapperExtension:pd,executeLoaderExtension:md,executePropertyMapperExtension:yd},Symbol.toStringTag,{value:"Module"})),wd="Extensions";class vd{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 rs=(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))(rs||{}),Pe=(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))(Pe||{});const Md=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}},Q=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},$e=async e=>{await E.getInstance().whenReady(),await E.getInstance().modelManager.initiateDestroyModel(e)},_d=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.transition(S.UNLOAD,y.UNLOADED)},ti=async e=>{await E.getInstance().whenReady(),await E.getInstance().modelManager.reloadModel(e),f.debug(`reload model initiated for model ${e.id}, model ready: ${ds(e)} - ${Date.now()} `),await Q(e),f.debug(`reload model complete for model ${e.id}, model ready: ${ds(e)} - ${Date.now()} `)},Ed=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},si=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}},We=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}},oi=(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]))},Id=(e,t)=>oi(e,t)[0],Td=(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},$d=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.values()).map(o=>o.modelData)},fo=(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.values()).find(r=>t(r.modelData))},te=e=>t=>Object.getPrototypeOf(t).modelTypeId===e,ds=e=>{const t=E.getInstance().modelManager.getModelById(e.id);if(!t)throw new Error("Model not found");return t.isReady()},Od=f.createLogger({name:"kos-model-factory"}),vt={byModelType:e=>E.getInstance().modelManager.getModelFactory(e),getModelInstance:(e,t,s)=>{const o=vt.byModelType(t);if(!o)throw Od.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&&x.setParentContext(t,o),vt.getModelInstance(t,e,s))},Singleton:{create:e=>(t,s)=>(s&&x.setParentContext(e,s),vt.getModelInstance(e,e,t))},Model:{instance:e=>t=>vt.getModelInstance(t,e)}};window.KosRegistry=window.KosRegistry||{coreModels:new Map,preloadModels:[],companionModels:new Map,models:new Map};const Rr=window.KosRegistry.coreModels,eo=window.KosRegistry.preloadModels,to=window.KosRegistry.companionModels,Yt=window.KosRegistry.models,O={model:{registerLegacyModel:e=>(t,s)=>(Rr.set(t,s),{preload:O.model.preloadModel(e),model:O.model.register(e),companion:O.companion.register(e),legacy:O.model.registerLegacyModel(e),root:e}),preloadModel:e=>t=>(eo.includes(t)||eo.push(t),{preload:O.model.preloadModel(e),model:O.model.register(e),companion:O.companion.register(e),legacy:O.model.registerLegacyModel(e),root:e}),register:e=>(t,s)=>{const o=so(t)?t.registration():t;return Yt.set(o.type,o),so(t)&&t.relatedModels.forEach(r=>Yt.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],so(t)&&t.relatedModels.forEach(r=>E.getInstance().modelManager.registry.models[r.type]=r.registration().registration))),s&&O.model.preloadModel(e)(o.type),{preload:O.model.preloadModel(e),model:O.model.register(e),companion:O.companion.register(e),legacy:O.model.registerLegacyModel(e),root:e}},get:e=>Yt.get(e),getAll:()=>Array.from(Yt.entries()),getPreloadModels:()=>eo,getLegacyModels:()=>Array.from(Rr.entries()).reduce((e,[t,s])=>(e[t]=s,e),{})},companion:{register:e=>(t,s)=>{const o=to.get(t)||[];return o.push(s),to.set(t,o),{preload:O.model.preloadModel(e),model:O.model.register(e),companion:O.companion.register(e),legacy:O.model.registerLegacyModel(e),root:e}},getAll:()=>Array.from(to.entries())}},ri=O.model.registerLegacyModel,ni=O.model.register,Sd=O.companion.register,Dd=O.model.preloadModel,ii=e=>typeof e.updateModel=="function",so=e=>e.registration!==void 0&&typeof e.registration=="function";class ai{constructor(t){a(this,"singleton");a(this,"type");a(this,"class");a(this,"guard");a(this,"factory");a(this,"relatedModels",[]);this.singleton=t.singleton,this.guard=te(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(){O.model.register({})(this.registration()),this.registerRelatedModels()}}class fe extends ai{constructor(t){super({...t,singleton:!1,factory:H.Factory.create(t.type)})}instance(t){const s=this.factory(t);return{get:()=>{const o=We(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(ii(r))r.updateModel(o);else throw new Error(`Model ${this.type} is not updateable. Please implement UpdateAware interface`);return r}else throw new Error("Model is not of type "+this.type)}})},options:o=>({build:()=>{const r=s(o);if(this.guard(r))return r;throw new Error("Model is not of type "+this.type)}})}}registration(){return{type:this.type,predicate:this.guard,registration:{[this.type]:{class:this.class,singleton:!1}},factory:this.factory}}}class we extends ai{constructor(t){super({...t,singleton:!0,factory:H.Singleton.create(t.type)})}instance(){const t=this.factory;return{get:()=>{const o=We(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)},forceUpdate:{options:o=>({build:()=>{const r=t(o);if(this.guard(r)){if(ii(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=t(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:!0}},factory:this.factory}}}const F=f.createLogger({name:"kos-core"}),Cd=()=>{const e=window.location.protocol,t=ce(),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://")},Ad=()=>{const e=window.location.hostname,t=process.env.KOS_HOST,s=ce(),o=s==null?void 0:s.host;let r;try{r=new URL(o).hostname}catch{}return r??t??e},Rd=()=>{const e=window.location.port,t=process.env.KOS_PORT,s=ce(),o=s==null?void 0:s.host;let r;try{r=new URL(o).port}catch{}return r??t??e},Ld=(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)}}},Lr=e=>typeof e.reload=="function",xd=e=>typeof e.unload=="function";var ci=(e=>(e.LOGGED_IN="logged_in",e.LOGGED_OUT="logged_out",e))(ci||{});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=rs.CREATED,this.authState="logged_out",this._reloading=!1,this._unloading=!1,w.makeAutoObservable(this),U("token",c=>{c&&(this.transport.token=c.body)}),U(wt.CONNECTED,async()=>{await this.whenReady(),this.fsmService.service.send(Pe.GO_ONLINE)}),U(wt.DISCONNECTED,async()=>{this.fsmService.service.send(Pe.GO_OFFLINE)}),U("/studioServer/auth/LOGGED_IN",()=>{this.authState="logged_in",this.transport.authorized=!0}),U("/studioServer/auth/LOGIN_REQUIRED",()=>{this.authState="logged_out",this.transport.authorized=!1}),U(wt.RELOAD,()=>{this.fsmService.service.send(Pe.RELOAD)}),U("/studio/project/reload",()=>{this.fsmService.service.send(Pe.RELOAD)});const s=ks.getInstance(),o=Ad(),r=Rd(),n=Cd();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=Md(this),this.fsmService.service.send(Pe.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;const t=Date.now();if(this._reloading){F.info("reload already in progress");return}this._reloading=!0,F.warn("reloading KOS Core"),F.warn("reloading preloaded models");const s=this.modelManager;for(const i of s.preloadedModels)Lr(i.modelData)&&(F.info(`reloading model ${i.modelId}`),(r=i.unload)==null||r.call(i),await i.modelData.reload(),F.info(`reloading model ${i.modelId} complete`));for(const i of s.models)!s.preloadedModels.includes(i)&&Lr(i.modelData)&&((n=i.unload)==null||n.call(i),await i.modelData.reload());const o=Date.now()-t;setTimeout(()=>{w.runInAction(()=>{F.warn("reloading KOS Core complete"),this._reloading=!1})},1e3-o)}async online(){F.debug("KOS Core going online"),await this._transport.whenReady(),F.debug("KOS Transport Ready. Calling online() for models"),G("/kosCore/online","/kosCore/online"),console.timeEnd("kosCore:startup")}async offline(){F.debug("KOS Core going offline"),G("/kosCore/offline","/kosCore/offline")}async unload(){var r;F.debug("Unloading kOS Core");const t=Date.now();this._unloading=!0,F.debug("unloading KOS Core");const s=this.modelManager;for(const n of s.models)xd(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===rs.READY)}async ready(){F.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}=Ld(5e3,r.model);Promise.race([r.promise.then(()=>{i()}),n])}))).filter(r=>r.status==="rejected");if(o.length)throw F.error(`There were ${o.length} failed models on model preloading`),Error(`There were ${o.length} failed models on model preloading`);F.debug("leaving kos-core ready() ")}get isReady(){return this.status===rs.READY}set transport(t){this._transport=t}get transport(){return this._transport}get coreInitialized(){return this.initialized}get modelsLoaded(){return this.loaded}async init(){F.debug("entering kos-core init()"),console.time("kosCore:startup"),console.time("kosCore:init"),await this._transport.whenReady(),this.initialized=!0,F.debug("initialized - leaving kos-core init()"),console.timeEnd("kosCore:init")}async load(){F.debug("entering kos-core load()"),console.time("kosCore:load"),this.loaded=!0,F.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,b;const u=(b=(h=t.extensions)==null?void 0:h.dataMapper)==null?void 0:b[d];u&&(Array.isArray(u)?u.forEach(v=>{A.dataMapper.registerDataMapper(d,v)}):A.dataMapper.registerDataMapper(d,u))}),(c=t.extensions)!=null&&c.propertyMapper&&Object.keys(t.extensions.propertyMapper).forEach(d=>{var h,b;const u=(b=(h=t.extensions)==null?void 0:h.propertyMapper)==null?void 0:b[d];u&&A.propertyMapper.registerPropertyMapper(d,u)}),(l=t.extensions)!=null&&l.contextLoader&&Object.keys(t.extensions.contextLoader).forEach(d=>{var h,b;const u=(b=(h=t.extensions)==null?void 0:h.contextLoader)==null?void 0:b[d];u&&A.loader.registerLoader(d,u)}),O.model.getAll().forEach(([,d])=>{t.models={...t.models,...d.registration}}),t.models={...t.models,...O.model.getLegacyModels()},O.companion.getAll().forEach(([d,u])=>{t.companionModels={...t.companionModels},t.companionModels[d]=t.companionModels[d]||[];for(const h of u)t.companionModels[d].push({type:h})}),O.model.getPreloadModels().forEach(d=>{t.preloadModels.includes(d)||t.preloadModels.push(d)});const n=ei.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 kd=f.createLogger({name:"kos-fetch"}),Pd=process.env.KOS_WS_TIMEOUT?parseInt(process.env.KOS_WS_TIMEOUT):3e4,Nd=()=>new Promise(e=>{setTimeout(()=>{e(!0)},0)}),Fd=e=>e!=null&&e.studio?$n:e!=null&&e.fos?On:Sn,Ud=async(e,t)=>{const s=E.getInstance().transport;await s.whenReady();const o=Nt(),r=new URL(e),n=`${r.pathname}${r.search}`,i=(t==null?void 0:t.timeout)||Pd,c=Fd(t),l=be(c({path:n,requestId:o,method:(t==null?void 0:t.method)||"GET",destinationAddress:(t==null?void 0:t.destinationAddress)||"",ordered:t==null?void 0:t.ordered,tracker:t==null?void 0:t.tracker,bridge:t==null?void 0:t.bridge}),t==null?void 0:t.body);return new Promise(d=>{const u=new AbortController,h=setTimeout(()=>{kd.error(`Timeout occurred - url: ${e}`),u.abort(),d({headers:lo({}),status:404,ok:!1,json:async()=>null,body:uo(""),redirected:!1,statusText:"",type:"basic",url:"",clone:function(){throw new Error("Function not implemented.")},bodyUsed:!1,arrayBuffer:function(){throw new Error("Function not implemented.")},blob:function(){throw new Error("Function not implemented.")},formData:function(){throw new Error("Function not implemented.")},text:function(){throw new Error("Function not implemented.")}})},i),{unsubscribe:b}=U(o,p=>{var $,C,se;clearTimeout(h);const M={headers:lo((p==null?void 0:p.headers)||{}),status:(($=p==null?void 0:p.headers)==null?void 0:$.status)&&parseInt((C=p==null?void 0:p.headers)==null?void 0:C.status)||200,ok:((se=p==null?void 0:p.headers)==null?void 0:se.status)==="200",json:async()=>{var ve;try{return(ve=p==null?void 0:p.body)!=null&&ve.length?JSON.parse(p.body):null}catch{throw Error("Not a JSON response")}},text:async()=>(p==null?void 0:p.body)||"",body:uo((p==null?void 0:p.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.")}};b(),Nd().then(()=>d(M))}),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=Ud;if(process.env.KOS_MOCK_FETCH==="true"){const e=process.env.KOS_PORT||"9999";exports.kosFetch=fetch,exports.BASE_URL=`http://localhost:${e}`}const jd=f.createLogger({name:"kos-model-visitor",group:"kos-ui-core"});class Bd{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)){jd.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 li=()=>({isMock:!1,URL:exports.BASE_URL}),Kd="errUnknown";async function zt(e,t,s,o,r){const n=o!=null&&o.path?Object.keys(o.path).reduce((h,b)=>String(h).replace(`{${b}}`,o==null?void 0:o.path[b]),String(e)):String(e),i=o!=null&&o.query?Object.keys(o.query).map(h=>`${h}=${o.query[h]}`).join("&"):"",c=`${li().URL}//${n}${i?`?${encodeURIComponent(i)}`:""}`,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||Kd}`,null]:[null,(await d.json()).data]}function Po(){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 di{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 Gd=async(e,t)=>{const s=new di;t.forEach(r=>s.use(r));const o={data:e,result:{}};return await s.execute(o),o.result},Ut=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}}),Hd=e=>{E.getInstance().modelManager.registerModel(e)},Vd=(e,t)=>{E.getInstance().modelManager.registerCompanionModel(e,t)},ui=Symbol("KosObservableData");class hi{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)}}hi.prototype[ui]=!0;function Yd(e,t){return new Proxy(e,{construct:(s,o)=>{const r=new e(...o);return r.setValues(t),r.proxy}})}const Oe=e=>{const t=Yd(hi,e);return new t(e)},xr="/kos/ui/internal/heartbeat/",zd=({relationshipId:e,destinationAddress:t,onAbort:s,waitTime:o,beatTime:r})=>{const n=E.getInstance().transport,i=new AbortController;let c=performance.now();const l=n.subscribeTopic({topic:`${xr}${e}`,callback:()=>{c=performance.now()}}),d=o??3e3,u=window.setInterval(()=>{let M=performance.now()-c;M=M/1e3,M>d/1e3&&i.abort()},d),h=r??2e3,b=window.setInterval(()=>{kn({msg:{},options:{topic:`${xr}${e}`,destinationAddress:t}})},h),v=()=>{window.clearInterval(b),window.clearInterval(u),l()},p=()=>{v(),s&&s(),i.signal.removeEventListener("abort",p)};return i.signal.addEventListener("abort",p),{cleanUpHeartbeat:v}},gi=(...e)=>t=>e.reduce((s,o)=>o(s),t),qd={maxAttempts:5,baseDelayMs:100,backoffFactor:1.5};async function Wd(e,t){let s=1;const o={...qd,...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 q=e=>({isMock:!1,URL:exports.BASE_URL}),Zd=(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),Ze(h,{ordered:i,studio:c,fos:l,bridge:d,destinationAddress:u});const b=await s(n||`${t}/${o}`,h);if(!b.ok)throw Error(`There was a problem deleting the model; returned status ${b.status}`);return await b.json()},Ze=(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),Qd=(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),Ze(u,{timeout:l,ordered:r,studio:n,fos:i,bridge:c,destinationAddress:d});const b=await s(o||t,u);if(!b.ok){let p;try{p=await b.json()}catch{}throw new ie(`There was a problem retrieving the model; returned status ${b.status}`,p)}return await b.json()},Xd=(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),Ze(h,{timeout:d,ordered:r,studio:n,fos:i,bridge:c,destinationAddress:u});const v=await s(o||t,h);if(!v.ok){let M;try{M=await v.json()}catch{}throw new ie(`There was a problem retrieving the model; returned status ${v.status}`,M)}return await v.json()},Jd=(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),Ze(h,{timeout:d,ordered:n,studio:i,fos:c,bridge:l,destinationAddress:u});const b=o||`${t}/${r}`,v=await s(b,h);if(!v.ok){let M;try{M=await v.json()}catch{}throw new ie(`There was a problem retrieving the model; returned status ${v.status}`,M)}return await v.json()};class ie extends Error{constructor(s,o){super(s);a(this,"payload");this.name="FetchException",this.payload=o}}const kr=(e,t,s)=>async({model:o,urlOverride:r,ordered:n,tracker:i,studio:c,fos:l,bridge:d,timeout:u,destinationAddress:h})=>{const b={method:"POST",body:typeof o=="string"?o:JSON.stringify(o)};e&&(b.destinationAddress=e),i&&(b.tracker=i),Ze(b,{timeout:u,ordered:n,studio:c,fos:l,bridge:d,destinationAddress:h});const v=await s(r||t,b);if(!v.ok){let M;try{M=await v.json()}catch{}throw new ie(`There was a problem sending the POST data; returned status ${v.status}`,M)}return await v.json()},Pr=(e="POST",t,s,o)=>async({model:r,id:n,urlOverride:i,ordered:c,studio:l,fos:d,bridge:u,timeout:h,destinationAddress:b})=>{const v={method:e};r&&(v.body=JSON.stringify(r)),t&&(v.destinationAddress=t),Ze(v,{timeout:h,ordered:c,studio:l,fos:d,bridge:u,destinationAddress:b});const p=await o(i||`${s}/${n}`,v);if(!p.ok){let $;try{$=await p.json()}catch{}throw new ie(`There was a problem modifying the model; returned status ${p.status}`,$)}return await p.json()},V={build:({destinationAddress:e="",basePath:t,getAllPath:s,getOnePath:o,deleteModelPath:r,addModelPath:n,modifyModelPath:i,mock:c=!1})=>{const l=c?fetch:exports.kosFetch;return{getAll:Qd(e,s||t,l),getModelById:Jd(e,o||t,l),getOne:Xd(e,o||t,l),addModel:kr(e,n||t,l),deleteModel:Zd(e,r||t,l),modifyModel:Pr("POST",e,i||t,l),putModel:Pr("PUT",e,i||t,l),postModel:kr(e,n||t,l)}}},eu=Nt(),fi=()=>`kos-${eu}`,tu=e=>!!e&&!e.includes("VM_SERVICE")&&e.startsWith(fi()),No=async(e,t=6e4)=>new Promise((s,o)=>{const{unsubscribe:r}=U(e,i=>{T.debug(`recieved response for refId ${e}: ${i}`),r(),clearTimeout(n);try{const c=i!=null&&i.body?JSON.parse(i.body):{};s(c)}catch{const c=(i==null?void 0:i.body)||{};s(c)}}),n=setTimeout(()=>{r(),o(Error(`Request with ID ${e} timed out. Cancelling.`))},t)}),su=async(e,t,s)=>{const o=No(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)},ou=async({topic:e,msg:t,requestId:s})=>{const o=s??Nt(),r=No(o);G(e,t,{sync:o});const n=await r;if(n.error)throw Error(n.error);return n},de=new Map;class mi{constructor(t){a(this,"_context");a(this,"_parent");a(this,"_id");this._id=t,this._context=new w.ObservableMap({}),this._parent="",w.makeAutoObservable(this)}setParent(t){Y(()=>{this._parent=t})}get id(){return this._id}get context(){return this._context}get parentModel(){var t;if(this._parent)return(t=We(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 mi(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 ru=e=>x.getContext(e.id);function nu(e,t){return e.length!==t.length?!1:e.every(s=>t.includes(s))}class Fo{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=Oe(),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(nu(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 iu(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 tt=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?A.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=Oe(),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 Fo({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 b,v;n.includes(u.name)&&((b=this.index.get(i.get(u.name)))==null||b.refresh());const h=r.filter(([,p])=>typeof p=="function");for(const[p]of h)(v=this.index.get(p))==null||v.refresh()},l=iu(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??[]:(tt.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):(tt.info(`key ${s} not found in ${t} index: ${Array.from(o.index.keys())}`),[])}else return tt.info(`index ${t} not found in ${Array.from(this.index.keys())}`),[]}async clear(){this._data.forEach(t=>{const s=t.id;$e(t).then(()=>{tt.debug(`${s} destroyed, removing from map`),this.removeModel(s,!0)}).catch(o=>tt.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)}}const oo=f.createLogger({name:"kos-data-container"});class pi{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=Oe(),w.makeAutoObservable(this,{}),this.init()}init(){Object.keys(this._optionsMap).forEach(t=>{const s=this._optionsMap[t],o=new Fo({container:this,key:s});this._index.set(t,o),this.idx[t]=o.data})}[Symbol.iterator](){return this.data[Symbol.iterator]()}get index(){return this._index}get indexKeys(){return Array.from(this.index.keys()).reduce((t,s)=>{var o;return t[s]=(o=this.index.get(s))==null?void 0:o.keys,t},{})}get revision(){return this._revision}addAll(t){w.runInAction(()=>{t.forEach(s=>this.addModel(s))})}removeAll(t){w.runInAction(()=>{t.forEach(s=>this.removeModel(s))})}sortFn(t,s){const o=this._sortKey;return o?String(t[o]).localeCompare(String(s[o]),void 0,{numeric:!0}):0}get data(){const t=Array.from(this._data.values());return this._sortKey&&t.sort(this.sortFn.bind(this)),t}increment(){w.runInAction(()=>{this._revision=this._revision+1})}addModel(t,s){const o=w.isObservable(t)?t:w.observable.object(t),r=this._disposerMap.get(t.id);r&&(r(),this._disposerMap.delete(t.id)),this._data.set(o.id||"",o),s||this.increment();const n=w.observe(o,i=>{Object.values(this._optionsMap||{}).includes(i.name)&&this.increment()});this._disposerMap.set(o.id||"",n)}removeModel(t){this._data.delete(t),this.increment();const s=this._disposerMap.get(t);s&&(s(),this._disposerMap.delete(t))}updateModel(t){const s=w.observable.object(t);this._data.set(s.id||"",s),this.increment()}getModel(t){return this._data.get(t)}getIndexKeys(t){return this.index.has(t)?this.index.get(t).keys??[]:(oo.info(`index ${t} not found in ${Array.from(this.index.keys())}`),[])}getIndexByKey(t,s){if(this.index.has(t)){const o=this.index.get(t);return o.index.has(s)?o.getByKey(s):(oo.info(`key ${s} not found in ${t} index: ${Array.from(o.index.keys())}`),[])}else return oo.info(`index ${t} not found in ${Array.from(this.index.keys())}`),[]}async clear(){this._data.clear(),this.increment()}filter(t,s){return this.data.filter(t,s)}sort(t){return this.data.sort(t)}map(t,s){return this.data.map(t,s)}forEach(t,s){this.data.forEach(t,s)}}class au{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 cu{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 yi{constructor(){a(this,"_token");w.makeAutoObservable(this),U("token",t=>{this.token=t==null?void 0:t.body})}get token(){return this._token}set token(t){this._token=t}}class bi{constructor(){a(this,"routes",[]);a(this,"openApiRoutes",[])}use(t,s,...o){this.routes.push({method:t,path:s,middlewares:o});const r=this.extractOpenApiParams(s);this.openApiRoutes.push({method:t,path:s,parameters:r})}async handle(t,s){var c;const{path:o,query:r,params:n}=this.extractPathParams(t.path),i={...t,params:n,query:r};for(const l of this.routes){const d=this.matchRoute(l.path,o);if(l.method===t.method&&d){i.params=d;let u=0;const h=async()=>{if(u<l.middlewares.length){const b=l.middlewares[u++];await b(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{unsubscribe:lu}=U("kos.intent",e=>{if(e){const t=e.body,s=t.type;wi(s,t.options)}}),us=new Map,du=(e,t)=>{const s=us.get(e)||[];s.push(t),us.set(e,s)},wi=(e,t)=>{us.has(e)&&us.get(e)[0].call(void 0,t)};var vi=(e=>(e.GET="GET",e.PUT="PUT",e.POST="POST",e.DELETE="DELETE",e))(vi||{});const mo=w.when,Mi=w.computed,Y=w.runInAction,N=w.autorun,_i=w.reaction,Uo=w.observable,jo="Not Assigned",uu="kos.trouble.added",hu="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||{}),Mt=(e=>(e.TIME_CHANGE="/kos/internal/time/time",e.DAY_CHANGE="/kos/internal/time/day",e.TIMEZONE_CHANGE="/kos/internal/time/timezone",e))(Mt||{});const Ei=f.createLogger({name:"config-bean-service",group:"Services"}),Bo=exports.BASE_URL,Ii=e=>(e==null?void 0:e.decimals)!==void 0,{postModel:gu,getOne:fu}=V.build({destinationAddress:"",basePath:`${Bo}/kos/config/`}),Ti=async(e,t,s="/api/kos/config")=>(Ei.debug(`sending modify request for ConfigBean: ${e}`),gu({model:t,urlOverride:`${Bo}${s}/${e}`})),$i=async(e,t="/api/kos/config")=>(Ei.debug(`sending get request for ConfigBean: ${e}`),await fu({urlOverride:`${Bo}${t}/details/${e}/15`})),Ko=e=>e.toLowerCase()==="true"||e.toLowerCase()==="false",Ps=e=>{try{const t=Number(e);return!isNaN(t)}catch{return!1}};function Oi(e=[]){return e.reverse().reduce((t,s)=>{const{overrides:o}=s;return o&&(t={...t,...o}),t},{})}function Si(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])?Si(e[o],r,s):s[r]=e[o]}return s}const Di=(e,t)=>{const s=e.details[0].bean||Oi(e.details[0].scopes),o=Si(s);w.runInAction(()=>{const r={...o};t.props.setValues(r)})},Ci=(e,t)=>{w.runInAction(()=>{e.changes.forEach(s=>{const o=s.attr;let r=s.currentValue,n=s.previousValue;typeof r=="string"&&Ko(r)&&(r=r.toLowerCase()=="true",n=(n==null?void 0:n.toLowerCase())=="true"),typeof r=="string"&&Ps(r)&&(r=Number(r),n=Number(n)),t.props[o]=r,t.prevProps[o]=n})})},Ai=e=>Object.fromEntries(e.props.entries),mu=e=>t=>s=>e.build(t,s);var pu=Object.defineProperty,yu=Object.getOwnPropertyDescriptor,Ri=(e,t,s,o)=>{for(var r=o>1?void 0:o?yu(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&&pu(t,s,r),r};function bu(e,t){for(const s of e)if(new RegExp(`^${s}$`).test(t))return s}const Go="config-bean-model",qt=f.getLogger(Go),wu=De("path");let hs=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=Ti,getConfigBean:o=$i}=t;this._modifyConfigBean=s,this._getConfigBean=o,this.props=Oe(),this.prevProps=Oe()}get values(){return this.props.values}async ready(){qt.debug(`readying config bean ${this.path}`),qt.debug(`complete readying config bean ${this.path}`)}async load(){qt.debug(`loading config bean ${this.path}`);const e=await this._getConfigBean(this.path,this.serviceBasePath);if(e!=null&&e.data){const t=e.data;Di(t,this),qt.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=bu(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=Ai(this);await this._modifyConfigBean(this.path,e,this.serviceBasePath)}handleConfigBeanUpdated(e){Ci(e,this)}};Ri([R({topic:`/kos/config/${wu}`,websocket:!0})],hs.prototype,"handleConfigBeanUpdated",1);hs=Ri([D(Go)],hs);const It=new fe({class:hs,type:Go}),Ns=({path:e,lazy:t,serviceBasePath:s})=>(o,r)=>{o[P]=o[P]||{},o[P][r]={modelType:It.type,id:`${It.type}-${e}`,options:{path:e,serviceBasePath:s},lifecycle:j.INIT,lazy:t}},{URL:Li}=q(),{getOne:vu,getAll:Mu}=V.build({basePath:`${Li}/api/kos/regions/info`}),xi=async()=>await vu({}),ki=async()=>await Mu({urlOverride:`${Li}/api/kos/regions`}),_u=Object.freeze(Object.defineProperty({__proto__:null,getRegionInfo:xi,getRegions:ki},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 Pi={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 Eu(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},{...Pi});return{...e,...o}}function Iu(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]:{...Pi}}});return Object.keys(o).forEach(r=>{e[r]={...e[r],...o[r]}}),e}function Tu(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 $u=Object.defineProperty,Ou=Object.getOwnPropertyDescriptor,Ho=(e,t,s,o)=>{for(var r=o>1?void 0:o?Ou(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&&$u(t,s,r),r};const ns="region-info-model",st=f.createLogger({name:"region-info-model"});let Tt=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||st.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||st.info("Could not find default unit for measure",t.measure)}return!n||!i?(st.warn("Could not find unit to convert to or from. Return value as is"),String(e)):this.convertByUnit(e,n,i)}async init(){st.debug("initializing region info")}async load(){st.debug("loading region info");const e=await ki();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 xi();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(Eu,{}),this.measureMap=t.data.unitSystems.reduce(Iu,{}),this.defaultMeasureMap=t.data.unitSystems.reduce(Tu,{}),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))}};Ho([Ns({path:"kos:service:region:settings"})],Tt.prototype,"regionSource",2);Ho([Ns({path:"kos:service:region"})],Tt.prototype,"region",2);Tt=Ho([D(ns)],Tt);const z={registration:{[ns]:{class:Tt,singleton:!0}},type:ns,factory:H.Singleton.create(ns)},Nr=({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},Ni=(e,t,s)=>{const{model:o}=We(z.type);if(!o)throw new Error("RegionInfo model not found");if(!ds(o))throw new Error("RegionInfo model not ready");const r={system:o.defaultUnitSystem},n=Nr({source:t}),i=Nr({source:s||r,defaultMeasure:o.getUnitMeasure(n.unit||"")});return o.convert(e,n,i)};function Fr({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 Ur({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 Re=(e,t)=>s=>!e||!t?s:Ps(s)?Ni(Number(s),e,t):s,Su=(e,t,s,o)=>{if((e==null?void 0:e.type)==="enum"||!(e!=null&&e.options))return[];if(e.options.type==="rangeCount")return Fr(e.options).map(Re(s,o));if(e.options.type==="rangeInterval")return Ur(e.options).map(Re(s,o));if(e.options.type==="list"){const{list:r}=e.options;return r.map(Re(s,o))}else{if(e.options.type==="unitSystemRangeCount"&&t)return Fr(e.options.unitSystems[t]).map(Re(s,o));if(e.options.type==="unitSystemRangeInterval"&&t)return Ur(e.options.unitSystems[t]).map(Re(s,o));if(e.options.type==="unitSystemList"&&t){const{list:r}=e.options.unitSystems[t];return r.map(Re(s,o))}}return[]},Du=(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 Cu=Object.defineProperty,Au=Object.getOwnPropertyDescriptor,Vo=(e,t,s,o)=>{for(var r=o>1?void 0:o?Au(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&&Cu(t,s,r),r};function Ru(e){return(e==null?void 0:e.type)==="enum"}function Lu(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 xu(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 is="config-bean-prop-model",Le=f.createLogger({name:"config-bean-prop-model"}),ku=De("path"),Pu=De("serviceBasePath");let $t=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 Ii(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?Lu(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=Ru(o)?o.values:Su(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){Le.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(){Le.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 xu(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){Le.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 Du(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){Le.error(`error creating formatter ${u}. Returning the raw value`,h)}}else Le.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,b,v;const{unit:e,measure:t}=this.getConverterFromFormat(),s=e==="drt"?"second":e;if(this.converter){const p=(o=this.converter)==null?void 0:o.measure,M=(n=(r=this.converter)==null?void 0:r.to)==null?void 0:n.measure,$=(c=(i=this.converter)==null?void 0:i.from)==null?void 0:c.measure,C=p||M||$||t,se=((d=(l=this.converter)==null?void 0:l.to)==null?void 0:d.unit)||this.regionInfo.getDefaultUnitForMeasure(C,((h=(u=this.converter)==null?void 0:u.to)==null?void 0:h.system)??this.regionInfo.defaultUnitSystem),ve=((v=(b=this.converter)==null?void 0:b.to)==null?void 0:v.system)??this.regionInfo.getUnitSystem(se),et=this.schemaFormat==="drt"?"second":this.schemaFormat||s;return{...this.converter,from:{unit:et,...this.converter.from},to:{...this.converter.to,unit:se,system:ve},measure:C}}if(s&&t){const p=this.regionInfo.getDefaultUnitForMeasure(t,this.regionInfo.defaultUnitSystem),M=this.regionInfo.getUnitSystem(s),$=this.regionInfo.getUnitSystem(p);return{measure:t,to:{unit:M===$?s:p}}}}async updateProperty(e){Le.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)}};Vo([Ft({modelType:z.type})],$t.prototype,"regionInfo",2);Vo([Ns({path:ku,serviceBasePath:Pu})],$t.prototype,"bean",2);$t=Vo([D(is)],$t);const Ce={registration:{[is]:{class:$t,singleton:!1}},type:is,factory:H.Factory.create(is)};function Nu(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:Ce.type,id:`${t}-${s}`,options:{path:t,attribute:s,serviceBasePath:c,converter:l,formatter:r,optionsExpander:i},lifecycle:j.INIT,lazy:n}}}class Fu{constructor(t,s){a(this,"futures");a(this,"defaultContext");a(this,"context");a(this,"disposers",new Map);a(this,"container");this.futures=Uo.map(new Map),this.context="",this.defaultContext=s||"",this.container=t,w.makeAutoObservable(this)}get allFutures(){return Array.from(this.futures.values())}get future(){return this.futures.get(this.defaultContext)}addFuture(t,s){this.futures.set(s||t.id,t),this.context=s||t.id;const o=N(()=>{var r,n;(t.endState||t.progress)&&((n=(r=this.container)==null?void 0:r.onFutureUpdate)==null||n.call(r,t))});this.disposers.set(s||t.id,o)}removeFuture(t){var s;this.futures.delete(t||this.context),(s=this.disposers.get(t||this.context))==null||s(),this.disposers.delete(t||this.context)}getFuture(t){return this.futures.get(t||this.context)}}class Yo{constructor(t){a(this,"disposer");a(this,"_future");a(this,"container");a(this,"onFutureUpdate");this._future=void 0,this.container=t,w.makeAutoObservable(this)}removeFuture(){var t;this._future=void 0,(t=this.disposer)==null||t.call(this),this.disposer=void 0}get future(){return this._future}getFuture(){return this._future}addFuture(t){this._future=t;const s=N(()=>{var o,r;(t.endState||t.progress)&&((r=(o=this.container)==null?void 0:o.onFutureUpdate)==null||r.call(o,t))});this.disposer=s}get allFutures(){return this._future?[this._future]:[]}get timeRemaining(){var t;return((t=this._future)==null?void 0:t.timeRemaining)||""}get status(){var t;return((t=this._future)==null?void 0:t.status)||"NOT_RESOLVED"}get progress(){var t;return((t=this._future)==null?void 0:t.progress)||-1}async cancel(){if(this._future)try{await this._future.cancelFuture()}catch(t){throw f.error(t),t}}}const Fi="future-model",Qe=Ut(Fi),Fs=f.createLogger({name:"future-service",group:"Services"}),{isMock:Uu,URL:jt}=q();var Be=(e=>(e.Success="SUCCESS",e.Fail="FAIL",e.Aborted="ABORT",e.Canceled="CANCEL",e))(Be||{});const{getAll:ju,modifyModel:Bu,addModel:Ku,deleteModel:Gu,postModel:Hu}=V.build({destinationAddress:"",basePath:`${jt}/api/future`,mock:Uu}),Vu=async()=>await ju({}),Ui=async(e,t="/api/kos/future")=>(Fs.info(`sending delete request for Future: ${e}`),await Gu({id:e,urlOverride:`${jt}${t}/${e}`})),ji=async(e,t="/api/kos/future")=>(Fs.info("sending add request for Future"),await Ku({model:e,urlOverride:`${jt}${t}`})),Yu=async(e,t,s="/api/kos/future")=>(Fs.info(`sending modify request for Future: ${e}`),Bu({model:t,id:e,urlOverride:`${jt}${s}/${e}`})),Bi=async(e,t="/api/kos/future")=>(Fs.info(`sending cancel request for Future: ${e}`),Hu({urlOverride:`${jt}${t}/${e}/cancel`,ordered:!0,model:{}})),zo=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}),qo=(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=zo(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]})})}))},Ki=e=>t=>s=>e.build(String(t),s),Wo=e=>t=>gi(zo,Ki(e)(t.tracker||t.id))(t);var zu=Object.defineProperty,qu=Object.getOwnPropertyDescriptor,Gi=(e,t,s,o)=>{for(var r=o>1?void 0:o?qu(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&&zu(t,s,r),r};const ro=f.getLogger(Qe.type);let gs=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=Bi,mo(()=>this.status===Be.Success||this.status===Be.Fail,()=>{ro.info(`Future ${this.id} has completed with status ${this.status}`),$e(this)})}async load(){ro.debug(`loading Future ${this.id}`)}unload(){ro.info(`unloading Future ${this.id}`)}async cancelFuture(){const e=this.namespace==="studio"?"/api/future":`/api/${this.namespace}/future`;await mo(()=>this.futureId!==jo),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}`),qo(e,this)}};Gi([R({topic:`kos.future/${cs}`})],gs.prototype,"handleFutureUpdated",1);gs=Gi([D(Qe.type)],gs);const Hi=gs,Vi=Po();var Wu=Object.defineProperty,Zu=Object.getOwnPropertyDescriptor,Yi=(e,t,s,o)=>{for(var r=o>1?void 0:o?Zu(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&&Wu(t,s,r),r};const zi="browser-router-model",Qu="kos.http.request",Xu="kos.http.response";let fs=class{constructor(e,t,s){a(this,"_id");a(this,"logger");a(this,"router");this._id=e,this.logger=s.logger,this.router=new bi}get id(){return this._id}async handleRequest(e,t){const s=t.headers["src-addr"],o=t.headers["dst-addr"],r=t.headers.url,n=t.headers.method,i=t.headers["request-id"],c={id:i,method:n,path:r};let l=200;const d={send:u=>{this.logger.debug(`sending response to ${o}`),this.logger.debug(u),Pn({msg:u,options:{responseId:i,destinationAddress:s,type:Xu,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}`)}};Yi([R({topic:Qu})],fs.prototype,"handleRequest",1);fs=Yi([D(zi)],fs);const qi=new we({class:fs,type:zi}),Wi="future-container-model",ye=Ut(Wi),Zi=e=>Wo(Qe)(e),Ju=e=>{const t=Zi(e);return ye.build(ye.type,{}).addFutureModel(t),t},eh=e=>ye.build(ye.type,{}).getFuture(String(e)),Se={buildFutureModel:Zi,initiateFuture:Ju,getFuture:eh};var th=Object.defineProperty,sh=Object.getOwnPropertyDescriptor,Zo=(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&&th(t,s,r),r};const Wt=f.getLogger(ye.type);let Ot=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=Ui,addFuture:r=ji}=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){Wt.error("error deleting a Future"),Wt.error(t)}}async createFuture(e){try{const t=await this._addFuture(e),s=t==null?void 0:t.data;if(s){const o=Wo(Qe)(s);return this.addFutureModel(o),o}}catch(t){throw Wt.error("error creating a Future"),Wt.error(t),t}}handleFutureUpdated(e,t){const s=Se.buildFutureModel(e);this.addFutureModel(s);const o=`kos.future/${e.tracker||e.id}`;this.logger.debug(`publishing future update to ${o}`),G(o,t.body,t.headers)}};Zo([le],Ot.prototype,"_futures",2);Zo([R({topic:"kos.future"})],Ot.prototype,"handleFutureUpdated",1);Ot=Zo([D(ye.type)],Ot);const Qi=Ot,{URL:Bt}=q(),{getOne:oh,postModel:rh,deleteModel:Xi}=V.build({basePath:`${Bt}/api/keyVal`}),po=f.createLogger({name:"key-value-service",group:"Services"}),Ji=async(e,t)=>{await Xi({urlOverride:`${Bt}/api/keyVal/${e}/${t}`,id:t})},ea=async(e,t,s)=>{const o=await rh({urlOverride:`${Bt}/api/keyVal/${e}/${t}`,model:s.toString()});if((o==null?void 0:o.status)!==200)throw po.error("Failed to update studio-state data",o),new Error(`Failed to update studio-state data for namespace ${e}`);return o.data},ta=async(e="studio")=>{po.debug("sending GET for studio-state");const t=await oh({urlOverride:`${Bt}/api/keyVal/${e}`});if((t==null?void 0:t.status)!==200)throw po.error("Failed to retrieve studio-state data",t),new Error(`Failed to retrieve studio-state data for namespace ${e}`);return t.data},nh=async e=>{await Xi({urlOverride:`${Bt}/api/keyVal/${e}}`,id:""})},ih=Object.freeze(Object.defineProperty({__proto__:null,deleteKeyValue:Ji,deleteKeyValueNamespace:nh,getKeyValue:ta,updateKeyValue:ea},Symbol.toStringTag,{value:"Module"}));var ah=Object.defineProperty,ch=Object.getOwnPropertyDescriptor,Qo=(e,t,s,o)=>{for(var r=o>1?void 0:o?ch(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&&ah(t,s,r),r};const sa="key-value-model";let St=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=Oe(),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 Ji(this.namespace,e),this.data[e]=void 0)}async load(){this.logger.debug(`loading studio-state ${this.id}`);const e=await ta(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)}};Qo([R({topic:"/keyVal/set"})],St.prototype,"handleStateUpdate",1);Qo([R({topic:"/keyVal/remove"})],St.prototype,"handleStateDelete",1);St=Qo([D(sa)],St);const Xo=new fe({class:St,type:sa}),{URL:Kt}=q(),{postModel:Jo,getOne:lh}=V.build({basePath:`${Kt}/api/kos-time`});f.createLogger({name:"kos-time-service",group:"Services"});const oa=async e=>{const t=await Jo({model:e,urlOverride:`${Kt}/api/kos/time/time`});if((t==null?void 0:t.status)!==200)throw Error("Failed to set time");return t.data},ra=async e=>{const t=await Jo({model:e,urlOverride:`${Kt}/api/kos/time/date`});if((t==null?void 0:t.status)!==200)throw Error("Failed to set time");return t.data},na=async e=>{const t=await Jo({model:{},urlOverride:`${Kt}/api/kos/time/timezone?tz=${e}`});if((t==null?void 0:t.status)!==200)throw Error("Failed to set timezone");return t.data},ia=async()=>{const e=await lh({urlOverride:`${Kt}/api/kos/time/timezone`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set timezone");return e.data.timeZone},dh=Object.freeze(Object.defineProperty({__proto__:null,getTimezone:ia,setDate:ra,setTime:oa,setTimezone:na},Symbol.toStringTag,{value:"Module"}));var uh=Object.defineProperty,hh=Object.getOwnPropertyDescriptor,Us=(e,t,s,o)=>{for(var r=o>1?void 0:o?hh(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&uh(t,s,r),r};const rt="kos-time-model",gh="/kos/time/time",fh="/kos/time/day",mh="/kos/time/timezone";let Ke=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 oa(e)}async updateSystemDate(e){await ra(e)}async updateSystemTimezone(e){await na(e)}handleTimeChange(){G(Mt.TIME_CHANGE,{})}handleDayChange(){G(Mt.DAY_CHANGE,{})}async handleTimeZoneChange(){await this.retrieveTimezone(),G(Mt.TIMEZONE_CHANGE,{})}async init(){this.logger.debug(`initializing kos-time ${this.id}`)}async retrieveTimezone(){const e=await ia();this.setTimezone(e)}setTimezone(e){this.timezone=e}async load(){this.logger.debug(`loading kos-time ${this.id}`),this.retrieveTimezone()}};Us([R({topic:gh,websocket:!0})],Ke.prototype,"handleTimeChange",1);Us([R({topic:fh,websocket:!0})],Ke.prototype,"handleDayChange",1);Us([R({topic:mh,websocket:!0})],Ke.prototype,"handleTimeZoneChange",1);Ke=Us([D(rt)],Ke);const ms={registration:{[rt]:{class:Ke,singleton:!0}},type:rt,predicate:te(rt),factory:H.Singleton.create(rt)};var ph=Object.defineProperty,yh=Object.getOwnPropertyDescriptor,aa=(e,t,s,o)=>{for(var r=o>1?void 0:o?yh(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&&ph(t,s,r),r};const ca="log-block-container-model";let ps=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}`)}};aa([le],ps.prototype,"_models",2);ps=aa([D(ca)],ps);const Xe=Po(),bh=f.createLogger({name:"log-stream-container-service",group:"Services"}),la=()=>{var o;const e=ce(),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},Je=la(),wh="/api/kos/logs/node/{nodeId}/streams",da=async()=>(bh.debug("sending GET for log-stream-container"),await Xe.get(wh,{path:{nodeId:"primary"}},{destinationAddress:Je})),ua=async(e,t="primary")=>{await Xe.post("/api/kos/logs/node/{nodeId}/{stream}/subscribe",{path:{nodeId:t,stream:e}},void 0,{destinationAddress:Je})},ha=async e=>{await Xe.post("/api/kos/logs/node/{nodeId}/{stream}/unsubscribe",{path:{nodeId:"primary",stream:e}},void 0,{destinationAddress:Je})},vh=async()=>{await Xe.post("/api/kos/logs/overrides",{},{level:"WARN",name:"com.example",nodeType:"java",type:"package"},{destinationAddress:Je})},ga=async e=>await Xe.get("/api/kos/logs/node/{nodeId}/{stream}/blocks",{path:{nodeId:"primary",stream:e}},{destinationAddress:Je}),fa=async(e,t)=>await Xe.get("/api/kos/logs/node/{nodeId}/{stream}/blocks/{blockId}",{path:{nodeId:"primary",stream:e,blockId:t}},{destinationAddress:Je}),Mh=Object.freeze(Object.defineProperty({__proto__:null,createOverride:vh,getKosConnectionId:la,getLogStreamBlock:fa,getLogStreamBlocks:ga,getLogStreams:da,subscribeToLogStream:ua,unsubscribeFromLogStream:ha},Symbol.toStringTag,{value:"Module"}));var _h=Object.defineProperty,Eh=Object.getOwnPropertyDescriptor,Ih=(e,t,s,o)=>{for(var r=o>1?void 0:o?Eh(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&&_h(t,s,r),r};const ma="log-block-model";let yo=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(this,"nodeId");a(this,"stream");a(this,"blockNum");a(this,"startLineNum");a(this,"endLineNum");a(this,"startTime");a(this,"endTime");a(this,"lineCount");a(this,"lines");a(this,"inc");this.id=e,this.logger=s.logger,this.nodeId=t.nodeId,this.stream=t.stream,this.blockNum=t.blockNum,this.startLineNum=t.startLineNum,this.endLineNum=t.endLineNum,this.startTime=t.startTime,this.endTime=t.endTime,this.lineCount=t.lineCount,this.lines=[],this.inc=0}async syncLines(){const[e,t]=await fa(this.stream,this.blockNum);if(e){this.logger.error(`Failed to get log block ${this.blockNum}`);return}t&&this.addLines(t.lines,!0)}updateModel(e){this.startLineNum=e.startLineNum,this.endLineNum=e.endLineNum,this.startTime=e.startTime,this.endTime=e.endTime,this.lineCount=e.lineCount}addLines(e,t){const s=t?[]:this.lines;this.lines=[...s,...e],this.inc+=1}async init(){this.logger.debug(`initializing log-block ${this.id}`)}async load(){this.logger.debug(`loading log-block ${this.id}`)}};yo=Ih([D(ma)],yo);const Dt=new fe({class:yo,type:ma}),js=new fe({class:ps,type:ca});js.addRelatedModel(Dt);var Th=Object.defineProperty,$h=Object.getOwnPropertyDescriptor,pa=(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 ya="log-stream-model";let ys=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(this,"nodeId");a(this,"_blocks");a(this,"name");a(this,"currentBlockId");a(this,"isResetting");a(this,"generatorInstance");a(this,"shouldStop",!1);this.id=e,this.logger=s.logger,this.currentBlockId="",this.name=t.name,this.nodeId=t.nodeId,this.isResetting=!0,this._blocks=js.instance(`${e}-blocks`).options({}).build()}get firstLineNum(){const e=this.populated[0];return e?e.startLineNum:0}get currentBlock(){const e=this.currentBlockId;return this._blocks.getModel(e)}get populated(){return this._blocks.data.filter(e=>e.lines.length>0)}get blocks(){return this._blocks.data}get totalLineCount(){return this.populated.reduce((e,t)=>e+t.lineCount,0)}accept(e){e.visit(this)}updateBlock(e){var o;let t=this._blocks.models.getModel(`${e.stream}-block-${e.blockNum}`);const s={nodeId:e.nodeId,blockNum:e.blockNum,endLineNum:e.endLineNum,lineCount:e.lineCount,startLineNum:e.startLineNum,stream:this.name,endTime:new Date(e.endTime),startTime:new Date(e.startTime)};t||(t=Dt.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=Dt.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 ua(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 ga(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=_i(()=>{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()}}};pa([le],ys.prototype,"_blocks",2);ys=pa([D(ya)],ys);const _t=new fe({class:ys,type:ya});var Oh=Object.defineProperty,Sh=Object.getOwnPropertyDescriptor,Ae=(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&&Oh(t,s,r),r};const ba="log-stream-container-model",Dh="/kos/logs/subscription/addBlock/*",Ch="/kos/logs/subscription/updateBlock/*",Ah="/kos/logs/subscription/removeBlock/*",Rh="/kos/logs/subscription/lines/*",wa="/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: ${wa}`);const t=e.stream,s=_t.instance(t).options({name:t,nodeId:"primary"}).build();this.addModel(s)}handleAddBlock(e,t){this.logger.debug(`Received topic: ${t.headers.topic}`);const s=e.stream,o=this.models.getModel(s);o&&o.addBlock(e)}handleRemoveBlock(e,t){this.logger.debug(`Received topic: ${t.headers.topic}`);const s=e.stream,o=this.models.getModel(s);o&&o.removeBlock(e.blockNum)}handleUpdateBlock(e,t){this.logger.debug(`Received topic: ${t.headers.topic}`);const s=e.stream,o=this.models.getModel(s);o&&o.updateBlock(e)}handleLogLine(e,t){var r;this.logger.debug(`Received topic: ${t.headers.topic}`);const s=e.stream,o=this.models.getModel(s);o&&((r=o.currentBlock)==null||r.addLines(e.lines))}async init(){this.logger.debug(`initializing log-stream-container container ${this.id}`)}async subscribeToLogStream(e){const t=_t.instance(e).options({name:e,nodeId:"primary"}).build();this.addModel(t),await t.subscribe()}async load(){this.logger.debug(`loading log-stream-container container ${this.id}`);const[e,t]=await da();if(e){this.logger.error(`Error loading log-streams: ${e}`);return}t&&t.forEach(s=>{const o=_t.instance(s).options({name:s,nodeId:"primary"}).build();this.addModel(o)})}};Ae([le],ue.prototype,"_models",2);Ae([R({topic:[wa],websocket:!0})],ue.prototype,"handleStreamAdded",1);Ae([R({topic:[Dh],websocket:!0})],ue.prototype,"handleAddBlock",1);Ae([R({topic:[Ah],websocket:!0})],ue.prototype,"handleRemoveBlock",1);Ae([R({topic:[Ch],websocket:!0})],ue.prototype,"handleUpdateBlock",1);Ae([R({topic:[Rh],websocket:!0})],ue.prototype,"handleLogLine",1);ue=Ae([D(ba)],ue);const Gt=new we({class:ue,type:ba});Gt.addRelatedModel(_t);Gt.addRelatedModel(js);Gt.addRelatedModel(Dt);const Lh=e=>e.rank!==void 0,xh=e=>e.visibleRole!==void 0,kh=e=>e.color!==void 0,Ph=e=>{const t=e.info;return Lh(t)?t.rank:0},Nh=e=>{const t=e.info;return kh(t)?t.color:"orange"},Fh=e=>{const t=e.info;return xh(t)?t.visibleRole:"TECHNICIAN"},{URL:er}=q(),{getAll:Uh,postModel:va}=V.build({basePath:`${er}/api/kos/troubles`}),Ma=async()=>await Uh({}),_a=async(e,t)=>{try{const s=await va({model:{},urlOverride:`${er}/api/kos/troubles/resolve/${e}`,tracker:t});return s!=null&&s.data&&Se.initiateFuture(s.data),s.data}catch{const o={id:t||"",endState:Be.Fail,tracker:t,reason:"Failed to resolve trouble"};return Se.initiateFuture(o),o}},jh=async(e,t)=>{try{const s=await va({model:e,urlOverride:`${er}/api/kos/troubles/resolve/`,tracker:t});return s!=null&&s.data&&Se.initiateFuture(s.data),s.data}catch{const o={id:t||"",endState:Be.Fail,tracker:t,reason:"Failed to resolve troubles"};return Se.initiateFuture(o),o}},Bh=Object.freeze(Object.defineProperty({__proto__:null,bulkResolveTroubles:jh,getTroubles:Ma,resolveTrouble:_a},Symbol.toStringTag,{value:"Module"})),bs="troubleDataMapper",Zt=new Map;Lo(bs,{register:(e,t)=>{var s;Zt.has(e)||Zt.set(e,[]),(s=Zt.get(e))==null||s.push(t)},execute:async(e,t)=>{const s=Zt.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 Ht="troubleMapper",Qt=new Map;Lo(Ht,{register:(e,t)=>{var s;Qt.has(e)||Qt.set(e,[]),(s=Qt.get(e))==null||s.push(t)},execute:async(e,t)=>{const s=Qt.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))}});A[Ht].register("nozzle",async e=>[e.data.nozzlePath]);A[Ht].register("path",async e=>[e.data.path]);const Kh=async e=>{const t=new Set,s=e.ifaces,o=s==null?void 0:s.map(n=>A[Ht].execute(n,e));return(await Promise.allSettled(o)).forEach(n=>{n.status==="fulfilled"&&n.value.forEach(i=>t.add(i))}),Array.from(t)},Ea=async e=>{const t=e.ifaces,s=t==null?void 0:t.map(i=>A[bs].execute(i,e)),o=A[bs].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 Gh{constructor(){a(this,"type","ResolvableTrouble");a(this,"title","Resolvable Trouble");a(this,"subtitle","Trouble")}}class Hh{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 Gh;case"BlockPumpTrouble":return new Hh;default:return}}}var Vh=Object.defineProperty,Yh=Object.getOwnPropertyDescriptor,Ia=(e,t,s,o)=>{for(var r=o>1?void 0:o?Yh(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Vh(t,s,r),r};const nt="trouble-model";function Xt(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:b,...v},p){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=p.logger,this.type=l,this._troubleId=r,this._resolvable=!!t,this.ifaces=c,this.rank=i,this.role=h,this.color=b,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 Yo(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 Ea(this)}get deferredCompanion(){const e=fo(this.id,t=>Xt(t));if(e&&Xt(e.modelData))return e.modelData}get deferred(){return this.deferredCompanion?this.deferredCompanion.deferred:!1}get shouldDefer(){const e=fo(this.id,t=>Xt(t));return e&&Xt(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 _a(this._troubleId,e)}};Ia([gr()],ws.prototype,"resolve",1);ws=Ia([D(nt)],ws);const Ct={registration:{[nt]:{class:ws,singleton:!1}},type:nt,predicate:te(nt),factory:H.Factory.create(nt)};var zh=Object.defineProperty,qh=Object.getOwnPropertyDescriptor,Bs=(e,t,s,o)=>{for(var r=o>1?void 0:o?qh(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&zh(t,s,r),r};const jr=f.createLogger({name:"trouble-container-model"});function Br(e){return A.propertyMapper.hasMapper(re.TroubleRank)?A.propertyMapper.executeMapper(re.TroubleRank,e):Ph(e)}function Kr(e){return(A.propertyMapper.hasMapper(re.TroubleColor)?A.propertyMapper.executeMapper(re.TroubleColor,e):Nh(e)).toLowerCase()}function Gr(e){return(A.propertyMapper.hasMapper(re.TroubleRole)?A.propertyMapper.executeMapper(re.TroubleRole,e):Fh(e)).toLowerCase()}const Wh="trouble-container-model";class J{}a(J,"INDEX_TROUBLES_BY_IFACE","byIface"),a(J,"INDEX_TROUBLES_BY_TYPE","byType"),a(J,"INDEX_TROUBLES_BY_GROUP","byGroup"),a(J,"INDEX_TROUBLES_BY_DEFERRED","byDeferred"),a(J,"SORT_KEY_RANK","rank"),a(J,"TROUBLES_DEFERRED","true");let Ge=class{constructor(e){a(this,"id");a(this,"troubles");this.id=e,this.troubles=new me({indexMap:{[J.INDEX_TROUBLES_BY_IFACE]:Kh,[J.INDEX_TROUBLES_BY_TYPE]:"type",[J.INDEX_TROUBLES_BY_GROUP]:"group",[J.INDEX_TROUBLES_BY_DEFERRED]:"deferred"},sortKey:J.SORT_KEY_RANK,parentId:e})}async load(){jr.debug("loading trouble container");const e=await Ma();try{e==null||e.data.forEach(t=>{const s={...t,rank:Br(t),color:Kr(t),role:Gr(t),id:String(t.id)},o=Ct.factory(`trouble-${t.id}`)(s);this.troubles.addModel(o)})}catch(t){throw jr.error(t),t}}handleTroubleRemoved(e){const t=`trouble-${e}`,s=this.troubles.getModel(t);this.troubles.removeModel(t),s&&$e(s)}handleTroubleAdded(e){const t={...e,rank:Br(e),color:Kr(e),role:Gr(e),id:String(e.id)};if(t.role==="NONE")return;const s=Ct.factory(`trouble-${e.id}`)(t);this.troubles.addModel(s)}};Bs([le],Ge.prototype,"troubles",2);Bs([R({topic:"/kos/trouble/remove",websocket:!0,lifecycle:j.INIT})],Ge.prototype,"handleTroubleRemoved",1);Bs([R({topic:"/kos/trouble/add",websocket:!0})],Ge.prototype,"handleTroubleAdded",1);Ge=Bs([D(Wh)],Ge);const Jt="trouble-container-model",He={registration:{[Jt]:{class:Ge,singleton:!0}},type:Jt,predicate:te(Jt),factory:H.Singleton.create(Jt)},{URL:Ta}=q(),{getAll:Zh}=V.build({basePath:`${Ta}/api/kos/ota`}),Hr=f.createLogger({name:"ota-service",group:"Services"}),Qh=async()=>{Hr.debug("sending GET request to /api/kos/ota/artifacts");const e=await Zh({urlOverride:`${Ta}/api/kos/ota/artifacts`});return Hr.debug("getArtifacts - response:",e),e==null?void 0:e.data};var Xh=Object.defineProperty,Jh=Object.getOwnPropertyDescriptor,Ks=(e,t,s,o)=>{for(var r=o>1?void 0:o?Jh(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&&Xh(t,s,r),r};const $a="ota-model",eg=e=>{let t=null;for(const s in e){const o=e[s],r=o.lastUpdateTime;(!t||t.lastUpdateTime<r)&&(t=o)}return t},no=e=>{const t=e.artifactInfo,s=eg(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 Ve=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(this,"data",new pi);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 Qh();e&&e.forEach(t=>{const s=no(t);s&&this.data.addModel(s)})}catch(e){this.logger.error(`loading ota ${this.id} - error:`,e)}}async handleAllArtifacts(e){this.logger.debug("handleAllArtifacts:",e),await this.data.clear();try{e.forEach(t=>{const s=no(t);s&&this.data.addModel(s)})}catch(t){this.logger.error(`handleAllArtifacts ${this.id} - error:`,t)}}handleChangedArtifacts(e){this.logger.debug("handleChangedArtifacts:",e);try{e.forEach(t=>{const s=no(t);s&&this.data.updateModel(s)})}catch(t){this.logger.error(`handleChangedArtifacts ${this.id} - error:`,t)}}};Ks([Ft({modelType:He.type})],Ve.prototype,"troubleContainer",2);Ks([R({topic:"/kos/ota/artifacts/all",websocket:!0})],Ve.prototype,"handleAllArtifacts",1);Ks([R({topic:"/kos/ota/artifacts/changed",websocket:!0})],Ve.prototype,"handleChangedArtifacts",1);Ve=Ks([D($a)],Ve);const vs=new we({class:Ve,type:$a}),Vr=f.createLogger({name:"software-info-service",group:"Services"}),Oa=async()=>{Vr.debug("sending GET for software-info");const[e,t]=await Vi.get("/api/kos/manifest/info");if(!t)throw Vr.error("Failed to fetch software-info",e),new ie("Failed to fetch software-info");return t},tg=Object.freeze(Object.defineProperty({__proto__:null,getSoftwareInfos:Oa},Symbol.toStringTag,{value:"Module"}));var sg=Object.defineProperty,og=Object.getOwnPropertyDescriptor,rg=(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&&sg(t,s,r),r};const it="software-info-model";let bo=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(this,"nodes");this.id=e,this.logger=s.logger,this.nodes=[]}async init(){this.logger.debug(`initializing software-info ${this.id}`)}groupBy(e,t){return e.reduce((s,o)=>(s[o[t]]=[...s[o[t]]||[],o],s),{})}async load(){this.logger.debug(`loading software-info ${this.id}`);try{const e=await Oa(),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 ie&&this.logger.error("Failed to fetch software-info",e)}}};bo=rg([D(it)],bo);const Ms={registration:{[it]:{class:bo,singleton:!1}},type:it,predicate:te(it),factory:H.Factory.create(it)},{URL:Sa}=q(),{getOne:ng}=V.build({basePath:`${Sa}/api/kos/state`}),ig=f.createLogger({name:"state-bean-service",group:"Services"}),Da=async({path:e})=>(ig.debug("sending GET for state-bean"),await ng({urlOverride:`${Sa}/api/kos/state/${e}`})),ag=Object.freeze(Object.defineProperty({__proto__:null,getStateBeanData:Da},Symbol.toStringTag,{value:"Module"}));var cg=Object.defineProperty,lg=Object.getOwnPropertyDescriptor,Ca=(e,t,s,o)=>{for(var r=o>1?void 0:o?lg(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&cg(t,s,r),r};const at="state-bean-model",dg=De("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=Uo.map(new Map),co(t,this)}updateModel(e){co(e,this)}handleConfigBeanUpdated(e){Object.entries(e).forEach(([t,s])=>{let o=s;typeof o=="string"&&Ko(o)&&(o=o.toLowerCase()=="true"),typeof o=="string"&&Ps(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 Da({path:this.path});e!=null&&e.data&&this.updateProps(e.data)}};Ca([R({topic:`/kos/state/${dg}`,websocket:!0})],_s.prototype,"handleConfigBeanUpdated",1);_s=Ca([D(at)],_s);const At={registration:{[at]:{class:_s,singleton:!1}},type:at,predicate:te(at),factory:H.Factory.create(at)};var ug=Object.defineProperty,hg=Object.getOwnPropertyDescriptor,Aa=(e,t,s,o)=>{for(var r=o>1?void 0:o?hg(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&ug(t,s,r),r};const ct="state-prop-model",Yr=De("path");let Es=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())??""}};Aa([Ft({modelType:At.type,id:`state-bean-${Yr}`,options:{path:Yr}})],Es.prototype,"stateBean",2);Es=Aa([D(ct)],Es);const tr={registration:{[ct]:{class:Es,singleton:!1}},type:ct,predicate:te(ct),factory:H.Factory.create(ct)},{URL:gg}=q(),{getAll:fg}=V.build({basePath:`${gg}/api/state-prop`}),mg=f.createLogger({name:"state-prop-service",group:"Services"}),pg=async()=>(mg.debug("sending GET for state-prop"),await fg({})),yg=Object.freeze(Object.defineProperty({__proto__:null,getStateProps:pg},Symbol.toStringTag,{value:"Module"})),{URL:sr}=q(),{getOne:Ra}=V.build({basePath:`${sr}/api/translation`}),Et=f.createLogger({name:"translation-service",group:"Services"}),bg=()=>{const e=window.location.origin,t=ce();return(t==null?void 0:t.host)||e},La=async(e,t)=>{Et.debug("sending GET for translation");const s=t??bg();try{const o=await fetch(`${s}${e}`);return o.status!==200?(Et.warn(`Failed to fetch translations at ${e}: ${o.status}`),{}):await o.json()}catch(o){throw Et.error("Error fetching translations",o),o}},wg=async()=>{Et.debug("getting localization descriptor");const e=await Ra({urlOverride:`${sr}/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},xa=e=>async()=>{Et.debug("getting kos localization descriptor");const t=await Ra({urlOverride:`${sr}/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]},ka="langResolver";var vg=Object.defineProperty,Mg=Object.getOwnPropertyDescriptor,_g=(e,t,s,o)=>{for(var r=o>1?void 0:o?Mg(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 lt="translation-model";function Eg(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 Pa(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=Pa(e[o],r);return{...s,...n}}else return{...s,[r]:e[o]}},{})}function Na(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]=Na(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},es=(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)},zr=(e,t)=>{if(t.includes(":")){const[s,o]=t.split(":");return{namespace:s,key:o}}else return{namespace:e,key:t}};let vo=class{constructor(e,t,s){a(this,"id");a(this,"namespace");a(this,"descriptor");a(this,"defaultLocale");a(this,"currentLocale");a(this,"bundleResolver");a(this,"data");a(this,"logger");a(this,"resolver");a(this,"disposer");a(this,"context");a(this,"rootUrl");this.id=e,this.defaultLocale=t.defaultLocale||"en",this.currentLocale=t.currentLocale||"en",this.namespace=t.namespace,this.descriptor=t.descriptor,this.rootUrl=t.rootUrl,this.data={},this.resolver=t.resolver||s.kosContext.get(ka),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 La(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=Na(r,n.value))):this.logger.error(`failed to load translation ${this.id} for ${e[i]}`),r),{});this.data=Pa(o)})}async init(){this.logger.debug(`initializing translation ${this.id}`)}exists(e){const{namespace:t,key:s}=zr(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.warn("key is empty"),"";const{defaultValue:s,context:o,data:r}=Eg(t),{namespace:n,key:i}=zr(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=>es(d,this.data,r)):es(this.data[c],this.data,r)}if(this.data[i]){const l=this.data[c];return Array.isArray(l)?l.map(d=>es(d,this.data,r)):es(this.data[i],this.data,r)}return s??i}unload(){this.logger.debug(`unloading translation ${this.id}`),this.disposer&&this.disposer()}async load(){this.logger.debug(`loading translation ${this.id}`),await this.loadTranslations()}async ready(){this.logger.debug(`ready translation ${this.id}`),this.disposer=w.reaction(()=>this.currentLocale,(e,t)=>{this.logger.info(`translation langs for namespace ${this.id} changed from ${t} to ${e}`),this.loadTranslations()})}};vo=_g([xs(),D(lt)],vo);const Is={registration:{[lt]:{class:vo,singleton:!1}},type:lt,predicate:te(lt),factory:H.Factory.create(lt)};var Ig=Object.defineProperty,Tg=Object.getOwnPropertyDescriptor,Fa=(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 dt="translation-container-model",$g=(e,t="/")=>e.join(t).replace(new RegExp(t+"{1,}","g"),t);function Og(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 $g([o,r])}let Ts=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||Og.bind(this),s.kosContext.set(ka,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 ti(this);for(const e of this.namespaces){const t=this.resolveNamespace(e);await Q(t)}}resolveNamespace(e){if(this.descriptor.namespaces[e]){const s=Object.keys(this.descriptor.namespaces[e].locales)[0],o=this.descriptor.namespaces[e].locales[s].defaultLocale,r=Is.factory(`translation-${e}`)({kosParentId:this.id,namespace:e,rootUrl:this.rootUrl,currentLocale:this.lang,defaultLocale:o,descriptor:this.descriptor.namespaces[e].locales,resolver:this.resolver});return this.addModel(r),this.namespaces.includes(e)||Y(()=>{this.namespaces.push(e)}),r}else{this.logger.warn(`namespace ${e} not found in descriptor`);const s=Is.factory(`translation-${e}`)({kosParentId:this.id,namespace:e,rootUrl:this.rootUrl,currentLocale:this.lang,defaultLocale:this.lang,descriptor:{},resolver:this.resolver});return this.addModel(s),s}}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}`)}};Fa([le],Ts.prototype,"_models",2);Ts=Fa([D(dt)],Ts);const he={registration:{[dt]:{class:Ts,singleton:!0}},type:dt,predicate:te(dt),factory:H.Singleton.create(dt)},Sg={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)}},Ua={async init(e){const t=he.factory(e);return await Q(t),{translations:t}}},Dg=(e,t)=>{const s=t.type;return e[s]||(e[s]=[]),e[s].push(t),e},ja="kos-ws-event",or=Ut(ja);var Cg=Object.defineProperty,Ag=Object.getOwnPropertyDescriptor,rr=(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&&Cg(t,s,r),r};const Rg=({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:Rg({headers:r,body:o}),direction:s?"send":"receive",mocked:!!r.mocked};this.events.set(c,l),f.debug(`logged ${this.events.size} events`)}}};rr([R({topic:[Pt.SEND]})],exports.WsEventModel.prototype,"handleSendEvent",1);rr([R({topic:[Pt.RECEIVED]})],exports.WsEventModel.prototype,"handleReceiveEvent",1);exports.WsEventModel=rr([D(or.type)],exports.WsEventModel);const{URL:nr}=q(),{getOne:Ba}=V.build({basePath:`${nr}/api/device`}),$s=f.createLogger({name:"device-service",group:"Services"}),Ka=async()=>{$s.debug("sending GET for device serial number");try{const e=await Ba({urlOverride:`${nr}/api/kos/device/serialNumber`});return[void 0,e==null?void 0:e.data.serialNumber]}catch(e){if(e instanceof ie)return $s.error(`Error fetching device serial number: ${e.payload.error}`),[e.payload.error,void 0]}return["unknownError",void 0]},Ga=async()=>{$s.debug("sending GET for device details");try{const e=await Ba({urlOverride:`${nr}/api/kos/device`});return e?[void 0,e.data]:["unknownError",void 0]}catch(e){if(e instanceof ie)return $s.error(`Error fetching device serial number: ${e.payload.error}`),[e.payload.error,void 0]}return["unknownError",void 0]},Lg=Object.freeze(Object.defineProperty({__proto__:null,getDeviceDetails:Ga,getSerialNumber:Ka},Symbol.toStringTag,{value:"Module"}));var xg=Object.defineProperty,kg=Object.getOwnPropertyDescriptor,Ha=(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&&xg(t,s,r),r};const Va="device-model",Pg="/kos/criticalData/changed",Ng="/kos/criticalData/available";let Os=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 Ga();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 Ka();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()}};Ha([R({topic:[Pg,Ng],websocket:!0})],Os.prototype,"handleCriticalDataChanged",1);Os=Ha([D(Va)],Os);const Ss=new we({class:Os,type:Va});var Fg=Object.defineProperty,Ug=Object.getOwnPropertyDescriptor,jg=(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&&Fg(t,s,r),r};const Ya="network-interface-model";let Mo=class{constructor(e,t,s){a(this,"id");a(this,"name");a(this,"type");a(this,"nmdevicestate");a(this,"hwaddress");a(this,"mtu");a(this,"configured");a(this,"wifi");a(this,"ethernet");a(this,"ip4settings");a(this,"category");a(this,"logger");this.id=e,this.logger=s.logger,this.name=t.name,this.type=t.type,this.nmdevicestate=t.nmdevicestate,this.hwaddress=t.hwaddress,this.mtu=t.mtu,this.configured=t.configured,this.wifi=t.wifi,this.ethernet=t.ethernet,this.ip4settings=t.ip4settings,this.category=t.category}updateModel(e){this.name=e.name,this.type=e.type,this.nmdevicestate=e.nmdevicestate,this.hwaddress=e.hwaddress,this.mtu=e.mtu,this.configured=e.configured,this.wifi=e.wifi,this.ethernet=e.ethernet,this.ip4settings=e.ip4settings,this.category=e.category}async init(){this.logger.debug(`initializing network-interface ${this.id}`)}async load(){this.logger.debug(`loading network-interface ${this.id}`)}};Mo=jg([D(Ya)],Mo);const ir=new fe({class:Mo,type:Ya}),{URL:Bg}=q(),{getAll:Kg}=V.build({basePath:`${Bg}/api/kos/network/interfaces`}),qr=f.createLogger({name:"network-interface-service",group:"Services"}),za=async()=>{qr.debug("sending GET for copy-logs");try{const e=await Kg({});return[void 0,e==null?void 0:e.data]}catch(e){if(e instanceof ie)return qr.error(`Error fetching log file size: ${e.payload.error}`),[e.payload.error,void 0]}return["unknownError",void 0]},Gg=Object.freeze(Object.defineProperty({__proto__:null,getNetworkInterfaces:za},Symbol.toStringTag,{value:"Module"}));var Hg=Object.defineProperty,Vg=Object.getOwnPropertyDescriptor,qa=(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&&Hg(t,s,r),r};const Wa="network-interface-container-model";let Ds=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 za();if(e){this.logger.error(`Error loading network interfaces: ${e}`);return}t&&t.forEach(s=>{const o=ir.instance(s.name).forceUpdate.options(s).build();this.addModel(o)})}async load(){this.logger.debug(`loading network-interface-container container ${this.id}`),this.refreshInterfaces()}};qa([le],Ds.prototype,"_models",2);Ds=qa([D(Wa)],Ds);const Rt=new we({class:Ds,type:Wa});Rt.addRelatedModel(ir);const{URL:Yg}=q(),{getAll:zg}=V.build({basePath:`${Yg}/api/kos/storage/devices`}),Wr=f.createLogger({name:"storage-device-service",group:"Services"}),Za=async()=>{Wr.debug("sending GET for storage-device");const e=await zg({});return!(e!=null&&e.data)||e.status!==200?(Wr.error("Failed to retrieve storage-device data",e),[]):e.data},qg=Object.freeze(Object.defineProperty({__proto__:null,getStorageDevices:Za},Symbol.toStringTag,{value:"Module"}));var Wg=Object.defineProperty,Zg=Object.getOwnPropertyDescriptor,Qg=(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&&Wg(t,s,r),r};const Qa="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=Qg([xs(),D(Qa)],_o);const Cs=new fe({class:_o,type:Qa});var Xg=Object.defineProperty,Jg=Object.getOwnPropertyDescriptor,ar=(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&&Xg(t,s,r),r};const Xa="storage-device-container-model",ef="/kos/storage";let Lt=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=Cs.instance(s.id).options(r).build();this.addModel(n)}})}async load(){this.logger.debug(`loading storage-device-container container ${this.id}`),(await Za()).forEach(t=>{const s={...t,kosParentId:this.id},o=Cs.instance(t.id).options(s).build();this.addModel(o)})}};ar([le],Lt.prototype,"_models",2);ar([R({topic:ef,websocket:!0})],Lt.prototype,"handleStorageAvailability",1);Lt=ar([D(Xa)],Lt);const Ye=new we({class:Lt,type:Xa});Ye.addRelatedModel(Cs);const{URL:cr}=q(),{getAll:tf,postModel:sf}=V.build({basePath:`${cr}/api/kos/update/available`}),Zr=f.createLogger({name:"usb-update-service",group:"Services"}),Ja=async()=>{Zr.debug("sending GET for usb-update");const e=await tf({urlOverride:`${cr}/api/kos/update/available`});return!(e!=null&&e.data)||(e==null?void 0:e.status)!==200?(Zr.error("Failed to retrieve usb-update data",e),[]):e.data},ec=async(e,t,s)=>{const o=await sf({model:{manifestId:e,deviceId:t},tracker:s,urlOverride:`${cr}/api/kos/update/install`});if(!(o!=null&&o.data))throw new Error("No response from server");return o.data},of=Object.freeze(Object.defineProperty({__proto__:null,getAvailableUpdates:Ja,installUpdate:ec},Symbol.toStringTag,{value:"Module"}));var rf=Object.defineProperty,nf=Object.getOwnPropertyDescriptor,tc=(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&&rf(t,s,r),r};const sc="usb-update-model";let As=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 Yo(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}`),ec(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}`)}};tc([gr()],As.prototype,"install",1);As=tc([D(sc)],As);const lr=new fe({class:As,type:sc});var af=Object.defineProperty,cf=Object.getOwnPropertyDescriptor,Gs=(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 oc="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 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 Ja();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=lr.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([Ft({modelType:Ye.type})],ze.prototype,"storageService",2);Gs([le],ze.prototype,"_models",2);Gs([Nn({dependencies:e=>[e.isUsbInserted]})],ze.prototype,"usbInsertedEffect",1);ze=Gs([D(oc)],ze);const xt=new we({class:ze,type:oc});xt.addRelatedModel(lr);const lf=()=>({...{[Qe.type]:{class:Hi},[ye.type]:{class:Qi,singleton:!0},...z.registration,...Ce.registration,...He.registration,...Is.registration,...he.registration,[or.type]:{class:exports.WsEventModel,singleton:!0},...At.registration,...tr.registration,...ms.registration}}),dr=lf(),df={models:dr,preloadModels:[]},uf=!0,rc=e=>()=>{const t=dr;return ni(Eo)(Ct).model(He).model(Ye).model(xt).model(Ss).model(vs).model(It).model(Ms).model(Xo).model(Rt).model(qi,uf).model(Gt),Object.keys(t).forEach(s=>{const o=t[s];ri(Eo)(s,o)}),{preload:O.model.preloadModel(e),model:O.model.register(e),companion:O.companion.register(e),legacy:O.model.registerLegacyModel(e)}},ne={};ne.core={models:rc(ne)};ne.preload=O.model.preloadModel(ne);ne.model=O.model.register(ne);ne.companion=O.companion.register(ne);ne.legacy=O.model.registerLegacyModel(ne);const Eo=ne;class hf{registerTroubleRankMapper(t){return A.propertyMapper.registerPropertyMapper(re.TroubleRank,t),this}registerTroubleRoleMapper(t){return A.propertyMapper.registerPropertyMapper(re.TroubleRole,t),this}registerTroubleColorMapper(t){return A.propertyMapper.registerPropertyMapper(re.TroubleColor,t),this}}const gf=async(e,t)=>{const s=Xo.instance(e).options({}).build(),o=t?`${t}-`:"";return await Q(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:()=>{$e(s)}}},nc="kos:service:region",ic="regionId",ff=`${nc}-${ic}`,ac=async e=>{const t=Ce.factory(ff)({path:nc,attribute:ic});await Q(t),t.updateProperty(e)},ur="/kos-timer-event",hr="defaultTimerEnd",ut=f.createLogger({name:"timer-manager"}),mf=e=>e.updateProperty!==void 0;class cc{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,mf(s)&&N(()=>{f.info(`Updating config value timer ${t} with new timeout value ${s.value}`);const n=s.value||60;this.updateTimeout(n)}),this.addTimeoutAction({name:hr}),o&&o.forEach(n=>{this.addTimeoutAction(n)})}start(){if(this.state==="active"){ut.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&&(ut.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;ut.debug(`Executing timer action ${s.name} at ${t}`),(o=s.action)==null||o.call(s,s.name,t),this.notifyTimeoutAction(s),s.singleUse&&(ut.info(`${this.name} Removing single-use action ${s.name}`),this.removeTimeoutAction(s.name))})}notifyTimeoutAction(t){G(ur,{name:this.name,action:t.name,remainingTime:this.remainingTime})}}const ht=new Map,ke=(e,t)=>{const s=ht.get(e);if(!s){ut.error(`Timer ${e} not found`);return}t(s)},lc={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(ht.has(e))return ht.get(e);const o=new cc(e,t,s);return ht.set(e,o),o},getTimer(e){return ht.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())}},dc="kos:service:region:settings",uc="timeZone",pf=`${dc}-${uc}`,Io=async e=>{const t=Ce.factory(pf)({path:dc,attribute:uc});await Q(t),t.updateProperty(e)},yf=e=>!e||!e.data;function gr(e={}){const{alias:t,namespace:s}=e;return(o,r,n)=>{o[Fe]=o[Fe]||{};const i=n.value,c=async function(...l){const d=Nt();f.debug(`Calling future service ${r} with tracker ${d}`);const u=Se.initiateFuture({tracker:d,id:jo});s&&(u.namespace=s),f.debug(`waiting for future ${u.id} to be ready`),await Q(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,[...l,d]);f.debug(`received future response for ${d}`,h);const b=yf(h)?h:h==null?void 0:h.data;return b?(b.progress=1,f.debug("mapping future response to future model"),u.endState?f.debug(`future ${u.id} has already completed. Not updating the model`):qo(b,u)):this.futureHandler.removeFuture(t),b}catch(h){throw f.error(h),h}};o[Fe][r]={handler:c}}}const bf=({path:e})=>(t,s)=>{t[P]=t[P]||{},t[P][s]={modelType:At.type,id:`${At.type}-${e}`,options:{path:e},lifecycle:j.INIT}};function wf(e){const{path:t,attribute:s}=e;return(o,r)=>{o[P]=o[P]||{},o[P][r]={modelType:tr.type,id:`${t}-${s}`,options:{path:t,attribute:s},lifecycle:j.INIT}}}const je=f.createLogger({name:"services",group:"Services"}),vf=async(e,t)=>hc(e,t,`${exports.BASE_URL}/api/server/login`),hc=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()},Mf=async e=>gc(e,`${exports.BASE_URL}/api/server/startPasswordReset`,""),gc=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()},_f=async(e,t)=>fc(e,t,`${exports.BASE_URL}/api/server/resetPassword`),fc=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()},Ef=async(e,t,s)=>mc(e,t,s,`${exports.BASE_URL}/api/server/acceptInvite`),mc=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()},If=Ie.keyframes`
|
|
77
77
|
0% {
|
|
78
78
|
left: -90px;
|
|
79
79
|
color: #eee;
|
|
@@ -91,7 +91,7 @@ ${l}topics:${t}
|
|
|
91
91
|
position: relative;
|
|
92
92
|
animation: ${If} ease-in-out infinite alternate;
|
|
93
93
|
animation-duration: 1.2s;
|
|
94
|
-
`,$f=({children:e})=>fl.createPortal(e,document.body);function
|
|
94
|
+
`,$f=({children:e})=>fl.createPortal(e,document.body);function pc({message:e="Wait a moment while we load your app."}){return _.jsx($f,{children:_.jsxs(Of,{children:[e,_.jsx("div",{css:Tf,children:"."})]})})}const Of=gl.div`
|
|
95
95
|
padding-inline: 20px;
|
|
96
96
|
width: 100%;
|
|
97
97
|
height: 100vh;
|
|
@@ -104,7 +104,7 @@ ${l}topics:${t}
|
|
|
104
104
|
top: 0;
|
|
105
105
|
left: 0;
|
|
106
106
|
z-index: 10000;
|
|
107
|
-
`;class
|
|
107
|
+
`;class yc 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||_.jsxs("div",{children:[_.jsx("h2",{children:"Something went wrong."}),_.jsxs("details",{style:{whiteSpace:"pre-wrap"},children:[this.state.error&&this.state.error.toString(),_.jsx("br",{}),this.state.errorInfo.componentStack]})]}):this.props.children}}const Sf={normal:"#B5F7F6",warn:"#F3D78A",error:"#FC8486"},Df=({value:e=0,title:t,status:s="normal",subtitle:o})=>{const r=Ie.css`
|
|
108
108
|
display: flex;
|
|
109
109
|
flex-direction: column;
|
|
110
110
|
`,n=Ie.css`
|
|
@@ -142,5 +142,5 @@ ${l}topics:${t}
|
|
|
142
142
|
transform: translateX(100%) scaleX(0.5);
|
|
143
143
|
}
|
|
144
144
|
}
|
|
145
|
-
`;return _.jsxs("div",{css:r,children:[_.jsxs("div",{css:n,children:[_.jsx("div",{css:i,children:t}),_.jsx("div",{css:[c,e<0?l:""]})]}),_.jsx("div",{children:o})]})},Af={setModel:()=>!1},Hs=g.createContext(Af),Cf=()=>{const e=g.useContext(Hs);if(e==null)throw new Error("useModels must be used within a KosModelProvider");return e.model},yc=({children:e})=>{const[t,s]=g.useState(),o=g.useCallback(r=>(s(r),!0),[s]);return _.jsx(Hs.Provider,{value:{model:t,setModel:o},children:e})},bc=f.createLogger({name:"kos-model-hierarchy-context"}),Rf={models:[],addModel:()=>{bc.debug("Default implementation being used. Do Nothing.")}},Vs=g.createContext(Rf),Lf=({children:e})=>{const[t,s]=g.useState([]),o=g.useCallback(r=>{t.includes(r)||(bc.debug("adding to hierarchy context",r.id),s(n=>[...n,r]))},[t]);return _.jsx(Vs.Provider,{value:{models:t,addModel:o},children:e})},kf=()=>!0,wc=e=>{const t=g.useContext(Vs);if(!t)throw new Error("useContextModelHierarchy must be used within a KosModelCollectionProvider");const s=(e==null?void 0:e.filter)||kf;return g.useMemo(()=>t.models.filter(s),[t.models,s])},xf=e=>wc({filter:s=>{const o=Ze(s.id);return(o==null?void 0:o.type)===e}})[0],Pf=f.createLogger({name:"kos-model-loader"}),Nf=()=>_.jsx("div",{}),vc=({fallback:e,children:t,...s})=>_.jsx(yc,{children:_.jsx(pc,{fallback:e,children:_.jsx(g.Suspense,{children:_.jsx(Mc,{...s,children:t})})})}),Mc=e=>{const[t,s]=g.useState(),[o,r]=g.useState(!1),{setModel:n}=g.useContext(Hs),i=g.useContext(Vs);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 Pf.error(e.error),new Error(e.error);const c=e.loading||_.jsx(Nf,{});return _.jsx(_.Fragment,{children:t&&o?e.children:c})},as={header:{title:"Model",createLabel:"Create new Model",deleteLabel:"Delete"},createModal:{okText:"OK",cancelText:"Cancel",title:"Create New Model"}},_c=g.createContext(as),Ff=({translations:e=as,children:t})=>{const s={header:{...as.header,...e.header},createModal:{...as.createModal,...e.createModal}};return _.jsx(_c.Provider,{value:s,children:t})};function Uf(e,t){const s=E.create(e,!1,t),o=s.whenReady().then(()=>s);return Do(o)}const Ec=g.createContext(void 0),jf=(e={models:{},preloadModels:[]},t)=>{const s=Uf(e,t),o=({children:r})=>{const n=s.read(),[i,c]=g.useState(n.onlineStatus);return g.useEffect(()=>{const l=N(()=>{c(n.onlineStatus)});return()=>{l()}},[n]),_.jsx(Ec.Provider,{value:{kosCore:n,online:i},children:r})};return{KosCoreContextProvider:Qr.observer(o)}},Ic=()=>{const e=g.useContext(Ec);if(e===void 0)throw new Error("useKosCore must be used within a KosCoreContextProvider");return e},Bf=8,Kf=(e=0)=>new Promise(t=>{setTimeout(()=>{t(!0)},2**e*10)}),Te=new Map;function Gf(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 Hf(e,t){return Gf(e,t)}async function Vf(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>Bf)throw Error(`kOS Model ${s} has not been found`);await Kf(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=Ic(),[i,c]=g.useState(!1),[l,d]=g.useState(),{kosModel:u,model:h}=Hf(t||s||"",()=>Vf(n.kosCore,e));return g.useEffect(()=>{async function b(){try{return await n.kosCore.whenReady(),o&&await(u==null?void 0:u.transition(S.GO_ACTIVE,y.ACTIVE)),c(!0),u}catch(p){d(p.message)}}let v;return n.kosCore&&t&&b().then(p=>{v=N(()=>{const M=(p==null?void 0:p.status)===y.READY;c(M)})}).catch(p=>{console.error(p)}),()=>{if(o){if(h!=null&&h.id){const p=n.kosCore.modelManager.getModelById(h.id);p==null||p.transition(S.GO_INACTIVE,y.INACTIVE).then(()=>{if(r){const M=h.id;$e(h).then(()=>{Te.delete(M),v==null||v()})}})}}else r&&h&&$e(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:vc}},gr=()=>{const e=ms.type;return B({modelId:e,modelType:ms.type,options:{}})},fr=g.createContext(void 0),Yf=({children:e})=>{const{model:t,ready:s}=gr(),o=g.useMemo(()=>s&&t?{model:t}:{},[s,t]);return _.jsx(fr.Provider,{value:o,children:e})},zf=()=>{const e=g.useContext(fr);if(!e)throw new Error("useKosTimeContext must be used within a KosTimeProvider");return e},mr=()=>{const e=Ms.type;return B({modelId:e,modelType:Ms.type,options:{}})};function qf(e){return()=>t=>{const{model:s,status:o,KosModelLoader:r}=mr();return _.jsx(r,{...o,children:_.jsx(e,{...t,softwareInfo:s})})}}const pr=g.createContext(void 0),Wf=({children:e})=>{const{model:t,ready:s}=mr(),o=g.useMemo(()=>s&&t?{model:t}:{},[s,t]);return _.jsx(pr.Provider,{value:o,children:e})},Zf=()=>{const e=g.useContext(pr);if(!e)throw new Error("useSoftwareInfoContext must be used within a SoftwareInfoProvider");return e},Tc=new pi,$c=g.createContext(Tc);function Qf({children:e}){return _.jsx($c.Provider,{value:Tc,children:e})}const yr=g.createContext(void 0),Xf=()=>{const e=window.location.origin,t=ae();return(t==null?void 0:t.host)||e},Jf=({children:e,appContext:t=["app/system"],locale:s="en",resolver:o,rootUrl:r,descriptorResolver:n})=>{const[i,c]=g.useState(!1),[l,d]=g.useState(),[u,h]=g.useState(),b=r||Xf();g.useEffect(()=>{async function M(){const D=(Array.isArray(t)?t:[t]).map(X=>(n||La(X))()),Re=(await Promise.allSettled(D)).map(X=>{if(X.status==="rejected"){f.warn("Failed to load localization descriptor",X.reason);return}return X.value}).filter(X=>!!X).reverse().reduce((X,Me)=>{const Ys=Me.path;return Object.keys(Me.namespaces).forEach(zs=>{const qs=Me.namespaces[zs];qs.basePath=Ys}),{...X,namespaces:{...X.namespaces,...Me.namespaces}}},{});d(Re)}M()},[t,n]),g.useEffect(()=>{async function M(){if(l){const O=b,{translations:D}=await Fa.init({lang:s,descriptor:l,defaultNamespace:"common",resolver:o,rootUrl:O});h(D),c(!0)}}M()},[t,s,l,o,b]);const v=g.useMemo(()=>i?{setLocale:M=>{u&&(u.currentLocale=M)}}:{setLocale:()=>{throw new Error("Translations not ready")}},[i,u]),p=i?e:null;return _.jsx(yr.Provider,{value:v,children:p})},em=()=>{const e=g.useContext(yr);if(!e)throw new Error("useTranslationContainerContext must be used within a TranslationContainerProvider");return e},Oc=()=>{const e=Ss.type;return B({modelId:e,modelType:Ss.type,options:{}})};function tm(e){return t=>{const{model:s,status:o,KosModelLoader:r}=Oc();return _.jsx(r,{...o,children:_.jsx(e,{...t,device:s})})}}function sm(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 Do(o)}function om(e){return t=>{const{model:s,status:o,KosModelLoader:r}=gr();return _.jsx(r,{...o,children:_.jsx(e,{...t,kosTime:s})})}}const Sc=()=>{const e=Rt.type;return B({modelId:e,modelType:Rt.type,options:{}})};function rm(e){return t=>{const{model:s,status:o,KosModelLoader:r}=Sc();return _.jsx(r,{...o,children:_.jsx(e,{...t,networkInterfaceContainer:s})})}}const Dc=()=>{const e=vs.type;return B({modelId:e,modelType:vs.type,options:{}})};function nm(e){return t=>{const{model:s,status:o,KosModelLoader:r}=Dc();return _.jsx(r,{...o,children:_.jsx(e,{...t,oTA:s})})}}function im(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 am(e){const t=g.useRef(null),s=e.onAlert;return im(t,s),_.jsx("div",{ref:t,style:{width:"100%"},children:e.children})}const cm=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 Q(h),n(!0))}catch(b){c(b.message)}}u(t)},[t]),g.useEffect(()=>{const u=N(()=>{t&&r&&o(t.value)});return()=>{u()}},[r,t]),[s,{ready:r,error:i}]},Ac=()=>{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=N(()=>{var c,l;t(((c=n.model)==null?void 0:c.isStorageInserted)??!1),o(((l=n.model)==null?void 0:l.data)??[])});return()=>{i()}},[n.model]),{...n,inserted:e,devices:s}};function lm(e){return t=>{const{model:s,status:o,KosModelLoader:r}=Ac();return _.jsx(r,{...o,children:_.jsx(e,{...t,storageDeviceContainer:s})})}}const dm=({timerName:e,onTimerExpired:t,timerEventActions:s,autoStart:o})=>{const r=cc.getTimer(e);return g.useEffect(()=>{const n=U(dr,i=>{const{name:c,action:l,remainingTime:d}=i==null?void 0:i.body;c===e&&r&&(l===ur?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)}},um=e=>{const t=/[\\^$.*+?()[\]{}|]/g;return RegExp(t.source).test(e)?e.replace(t,"\\$&"):e},hm=e=>e instanceof RegExp,gm=e=>typeof e=="string",fm=(e,t,s)=>{if(e===""||t==="")return e;let o=t;hm(o)||(o=new RegExp("("+um(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},Cc=(e,t,s)=>{let o=e;return Array.isArray(o)||(o=[o]),o.flatMap(r=>gm(r)?fm(r,t,s):r)};function mm(e,t){let s=e;return Object.entries(t).forEach(([o,r])=>{const n=new RegExp(`<${o}>(.*?)</${o}>|<${o}/>`,"g");s=Cc(s,n,(i,c)=>r.type==="br"?_.jsx("br",{}):g.cloneElement(r,{key:`${o}-${c}`},i))}),s}const pm=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=mm(c,r||{});return _.jsx("span",{className:e.className,children:l})},Fe=new Map;function ym(e,t){if(Fe.has(e)){const s=Fe.get(e);if(s.status==="finished")return s.result;throw s.promise}else{const s=t().then(r=>{Fe.set(e,{status:"finished",result:r})},r=>{throw Fe.set(e,{status:"error",error:r}),r}),o={status:"pending",promise:s};throw Fe.set(e,o),s}}function Io(e,t){return ym(e,t)}const bm=async()=>{const e=await ti(ue.type);return await Q(e.model),e.model},wm=async(e,t,s)=>{const o=e.resolveNamespace(t);await Q(o);for(const r of s){const n=e.resolveNamespace(r);await Q(n),Fe.set(r,{status:"finished",result:n})}return o},vm=(e,t)=>{const s=[e].flat(),[o,...r]=s,n=Io(ue.type,bm),i=s.join("__"),c=Io(i,()=>wm(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 b=t!=null&&t.keyPrefix?`${t.keyPrefix}.${u}`:u;return c?c.resolveKey(b,h):(f.debug(`Translation model ${e} not ready for key: ${b}`),b)},[t==null?void 0:t.keyPrefix,e,c]),i18n:l}},Rc=()=>{const e=ue.type;return B({modelId:e,modelType:ue.type,options:{}})};function Mm(e){return t=>{const{model:s,status:o,KosModelLoader:r}=Rc();return _.jsx(r,{...o,children:_.jsx(e,{...t,translationContainer:s})})}}const _m=e=>B({modelId:e,modelType:At.type}),br=()=>B({modelId:Ve.type,modelType:Ve.type,options:{}}),Em=({troubleType:e,condition:t})=>{const{model:s}=br(),[o,r]=g.useState(!1),[n,i]=g.useState([]),c=g.useCallback(()=>{var l,d;return n.length>0&&((l=n[0])!=null&&l.resolvable)?(d=n[0])==null?void 0:d.resolve():Promise.resolve(void 0)},[n]);return g.useEffect(()=>N(()=>{const d=(e?s==null?void 0:s.troubles.getIndexByKey("byType",e):s==null?void 0:s.troubles.data)||[],u=t?d.filter(t):d;r(u.length>0),i(u)}),[t,s,e]),[o,c,n.length>0?n[0]:void 0,n]};function Im(e){return t=>{const{model:s,status:o,KosModelLoader:r}=br();return _.jsx(r,{...o,children:_.jsx(e,{...t,troubleContainer:s})})}}const Lc=()=>{const e=kt.type,t=B({modelId:e,modelType:kt.type,options:{},activate:!0,destroyOnUnmount:!0}),[s,o]=g.useState(!1),[r,n]=g.useState(!1),[i,c]=g.useState([]);return g.useEffect(()=>{const l=N(()=>{var d,u,h;o(((d=t.model)==null?void 0:d.isUsbInserted)??!1),n(((u=t.model)==null?void 0:u.hasAvailableUpdates)??!1),c(((h=t.model)==null?void 0:h.data)??[])});return()=>{l()}},[t.model]),{...t,inserted:s,updateAvailable:r,updates:i}};function Tm(e){return t=>{const{model:s,status:o,KosModelLoader:r}=Lc();return _.jsx(r,{...o,children:_.jsx(e,{...t,usbUpdateContainer:s})})}}const $m=({path:e,propKey:t})=>{const{status:s}=B({modelType:It.type,modelId:e,options:{path:e}}),[o,r]=g.useState(!1),[n,i]=g.useState(),[c,l]=g.useState(""),[d,u]=g.useState(),h=b=>{n&&t&&n.updateProperty(t,b)};return g.useEffect(()=>{var b;s.model&&i(s.model),s.model&&t&&((b=s.model)!=null&&b.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 b=n==null?void 0:n.props[t];l(b||"")})},[n,t]),{config:n,ready:o,value:c,error:d,updateValue:h}},Om=(e,t)=>{switch(t.type){case"UPDATE":return t.payload;default:return e}},kc=({configProperty:e,optionsTransformer:t})=>{const[s,o]=g.useState(!1),[r,n]=g.useState(""),[i,c]=g.useReducer(Om,{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 Q(u),o(!0))}catch(h){n(h.message)}}d(e)},[e]),g.useEffect(()=>{const d=N(()=>{if(e&&s){let u=[];t&&(u=t(e.options)),c({type:"UPDATE",payload:{value:String(e.value),displayValue:e.displayValue,significantValue:e.significantValue,unit:e.unit,options:e.options,mappedOptions:u,updateProperty:e.updateProperty,displayOptions:e==null?void 0:e.displayOptions}})}});return()=>{d()}},[e,t,s]),{...i,configSelectProps:{onChange:l,value:i.value,options:t?i.mappedOptions||[]:i.options||[]},ready:s,error:r}};function Sm(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 Dm(e,t){return new Date(e,t,0).getDate()}function xc(e,t){const s=Sm(t,e),o=[];for(let r=1;r<=s;r++)o.push(r);return o}function Pc(){return[...Array(12).keys()].map(t=>new Date(0,t).getMonth())}function Nc(e=[2018,2028]){const t=[];for(let s=e[0];s<=e[1];s++)t.push(s);return t}function Fc(e,t=[2018,2028]){const s=Nc(t);return e==="long"?s:s.map(o=>Number(o.toString().substring(2)))}function wr(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 Am({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 Cm(e){return typeof e=="string"?new Date(Date.parse(`01 ${e.substring(0,3)} 2023`)).getMonth()+1:e}function Uc(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 gt(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 ft(e,t){return new Date(e,t,0).getDate()}function jc(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 Bc({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=vr(n,o),d=Kc(n,o,e),u=Gc(i,e),h=Hc(i,e),b=Mr(t,s),v=Vc(t,s,e,r),p=qc(s,t,v),M=Yc(e,c);return{daysArray:b,monthsArray:u,yearsArray:l,yearsOptionsArray:d,monthsOptionsArray:h,daysOptionsArray:v,calendarDayArray:p,dayNamesArray:M}}function vr(e="long",t=[2018,2028]){return g.useMemo(()=>Fc(e,t),[e,t])}function Kc(e="long",t=[2018,2028],s="en-US"){const o=vr(e,t);return g.useMemo(()=>o.map(n=>({label:n.toLocaleString(s).replace(",",""),value:n})),[s,o])}function Gc(e,t="en-US"){return g.useMemo(()=>wr(e,t),[e,t])}function Hc(e,t="en-US"){const s=g.useMemo(()=>Pc(),[]),o=g.useMemo(()=>wr(e,t),[e,t]);return g.useMemo(()=>[...Array(12).keys()].map(n=>({label:o[n],value:Number(s[n])})),[o,s])}function Mr(e,t){const s=se(e);return g.useMemo(()=>xc(s,t),[t,s])}const Rm=(e,t,s,o=[])=>{const r=new Date(e,t,s).getDay();return o.length>0&&o.includes(r)};function Vc(e,t,s="en-US",o=[]){const r=Mr(e,t);return g.useMemo(()=>r.map(i=>({label:i.toLocaleString(s),value:i,disabled:Rm(e,t,i,o)})),[o,s,t,r,e])}function Yc(e="en-US",t="short"){return g.useMemo(()=>jc(e,t),[e,t])}function zc({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 qc(e,t,s){return g.useMemo(()=>Uc(e,t,s),[e,t,s])}var Wc=(e=>(e.MMDDYY="MMDDYY",e.DDMMYY="DDMMYY",e.YYMMDD="YYMMDD",e.YYDDMM="YYDDMM",e))(Wc||{});function Lm({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),[b,v]=g.useState(l),[p,M]=g.useState(s),[O,D]=g.useState(o);g.useEffect(()=>{h(t)},[t]),g.useEffect(()=>{M(s)},[s]),g.useEffect(()=>{D(o)},[o]);const{yearsArray:me,yearsOptionsArray:ve,monthsArray:Re,monthsOptionsArray:X,daysArray:Me,daysOptionsArray:Ys,calendarDayArray:zs,dayNamesArray:qs}=Bc({locale:e,year:u,yearRange:b,month:p,formatOptions:{yearFormat:r,monthFormat:n,dayFormat:i},daysOfWeekFilter:d}),{formattedDate:dl}=zc({year:u,month:p,day:O,formatString:c});return{dateActions:{setYear:h,setYearRange:v,setMonth:M,setDay:D,nextMonth:()=>{const K=p<11?se(u):se(u+1),W=p<11?p+1:0;if(!gt(K,W,O)){const _e=ft(K,W);D(_e)}W===0&&h(K),M(W)},previousMonth:()=>{const K=se(p===0?u-1:u),W=p===0?11:p-1;if(!gt(K,W,O)){const _e=ft(K,W);D(_e)}W===11&&h(K),M(W)},nextYear:()=>{const K=u<b[1]?u+1:b[0],W=se(K);if(gt(W,p,O))h(K);else{const _e=ft(se(u+1),p);D(_e),h(K)}},previousYear:()=>{const K=u>b[0]?u-1:b[0],W=se(K);if(gt(W,p,O))h(K);else{const _e=ft(se(u-1),p);D(_e),h(K)}}},dateState:{year:u,yearRange:b,month:p,day:O,yearsArray:me,yearsOptionsArray:ve,monthsArray:Re,monthsOptionsArray:X,daysArray:Me,daysOptionsArray:Ys,calendarDayNames:qs,calendarDayArray:zs,formattedDate:dl}}}function Zc({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 Qc=({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}=Zc({date:c,options:{ignoreDateFormat:!0}});return g.useEffect(()=>{const u=Number(e),h=Math.floor(u/3600),b=Math.floor(u%3600/60),v=u%60;s(h),r(b),i(v);const p=new Date;p.setHours(0,0,0,0);const M=new Date(p.getTime()+u*1e3);l(new Date(M))},[e]),{hours:t,minutes:o,seconds:n,formattedTime:d,timeActions:{setHours:s,setMinutes:r,setSeconds:i}}},km=({configProperty:e})=>{const{value:t}=kc({configProperty:e}),s=parseInt(t||"0",10),{hours:o,minutes:r,seconds:n,formattedTime:i,timeActions:c}=Qc({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}},xm=e=>_.jsx("option",{title:e.id,value:e.format,children:e.format},e.id),Pm=(e=xm)=>{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=N(()=>{s((n==null?void 0:n.dateFormatOptions.map(e))||[])});return()=>{l()}},[n,i,e]),g.useEffect(()=>{const l=N(()=>{n!=null&&n.dateFormatId&&(n!=null&&n.selectedDateFormat)&&r({id:n==null?void 0:n.dateFormatId,value:n==null?void 0:n.selectedDateFormat})});return()=>{l()}},[n==null?void 0:n.selectedDateFormat,n==null?void 0:n.dateFormatId]);const c=g.useCallback(l=>{var u;let d="";typeof l=="string"?d=l:(u=l==null?void 0:l.target)!=null&&u.value&&(d=l.target.value),d&&(n==null||n.setSelectedDateFormat(d))},[n]);return{raw:(n==null?void 0:n.dateFormatOptions.map(l=>l.id))??[],regionModel:n,selectedDateFormat:(o==null?void 0:o.value)||"",dateFormatId:(o==null?void 0:o.id)||"",updateDateFormat:c,props:{onChange:c,value:(o==null?void 0:o.id)||"",options:t}}},Nm=e=>_.jsx("option",{title:e,value:e,children:e},e),Xc="kos:service:region:settings",Jc="timeZone",Fm=`${Xc}-${Jc}`,Um=(e=Nm)=>{const[t,s]=g.useState([]),[o,r]=g.useState(""),{model:n,ready:i}=B({modelType:z.type,modelId:z.type,options:{}}),c=Ae.factory(Fm)({path:Xc,attribute:Jc});g.useEffect(()=>{const d=N(()=>{s((n==null?void 0:n.timeZones.map(e))||[]),n!=null&&n.timeZones.length&&Eo(n==null?void 0:n.timeZones[0])});return()=>{d()}},[n,i,e]),g.useEffect(()=>{const d=N(()=>{r(c.value||"")});return()=>{d()}},[c.value]);const l=g.useCallback(d=>{var h;let u="factory";typeof d=="string"?u=d:(h=d==null?void 0:d.target)!=null&&h.value&&(u=d.target.value),u&&Eo(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}}},el="kos:service:region",tl="regionId",jm=`${el}-${tl}`,Bm=e=>_.jsx("option",{title:e,value:e,children:e},e),sl=(e=Bm)=>{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(jm)({path:el,attribute:tl});g.useEffect(()=>{const d=N(()=>{s((n==null?void 0:n.availableRegions.map(e))||[])});return()=>{d()}},[n,i,e]),g.useEffect(()=>{const d=N(()=>{r(c.value||"factory")});return()=>{d()}},[c.value]);const l=g.useCallback(d=>{var h;let u="factory";typeof d=="string"?u=d:(h=d==null?void 0:d.target)!=null&&h.value&&(u=d.target.value),u&&ic(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}}},Km=e=>_.jsx("option",{title:e.id,value:e.format,children:e.format},e.id),Gm=(e=Km)=>{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=N(()=>{s((n==null?void 0:n.timeFormatOptions.map(e))||[])});return()=>{l()}},[n,i,e]),g.useEffect(()=>{const l=N(()=>{n!=null&&n.timeFormatId&&(n!=null&&n.selectedTimeFormat)&&r({id:n==null?void 0:n.timeFormatId,value:n==null?void 0:n.selectedTimeFormat})});return()=>{l()}},[n==null?void 0:n.selectedTimeFormat,n==null?void 0:n.timeFormatId]);const c=g.useCallback(l=>{var u;let d="";typeof l=="string"?d=l:(u=l==null?void 0:l.target)!=null&&u.value&&(d=l.target.value),d&&(n==null||n.setSelectedTimeFormat(d))},[n]);return{raw:(n==null?void 0:n.timeFormatOptions.map(l=>l.id))??[],regionModel:n,selectedTimeFormat:(o==null?void 0:o.value)??"",timeFormatId:(o==null?void 0:o.id)??"",updateTimeFormat:c,props:{onChange:c,value:(o==null?void 0:o.id)??"",options:t}}},Hm=(e,t)=>g.useMemo(()=>vi(e),t),Vm={config:{attributes:!0,childList:!0,subtree:!0}};function Ym(e,t,s=Vm){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 ol={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}},no=f.createLogger({name:"usePressGesture",group:"kos-hooks"});function zm({onPressed:e,onRelease:t,intersectionStrategy:s=ol}){const o=g.useRef(!1),r=ml.useGesture({onDragStart:l=>{no.info("onDragStart",l.type),s.validateStart(l)&&(e&&e(),o.current=!0)},onDrag:l=>{no.info("onDrag",l.type),o.current&&s.validateStop(l)&&(t&&t(),o.current=!1)},onDragEnd:l=>{no.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 rl=()=>{const[e,t]=g.useState(!1),s=E.getInstance();return g.useEffect(()=>{const o=N(()=>{s&&s.reloading!==e&&t(s.reloading)});return()=>{o()}},[s,e]),[e]};function nl(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 To(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 il(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 al({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=nl(e,t),i=To(60,s),c=To(60,o),l=il(r);return{hourOptions:n,minuteOptions:i,secondOptions:c,amPmOptions:l}}function cl(e,t){return pe.format(e,t)}function ll({formatOptions:e,initialDate:t=new Date,locale:s="en-US",format:o="HH:mm"}){const[r,n]=g.useState(t),i=g.useCallback(M=>{n(O=>{const D=new Date(O);return D.setHours(Number(M)),D})},[]),c=g.useCallback(M=>{n(O=>{const D=new Date(O);return D.setMinutes(Number(M)),D})},[]),l=g.useCallback(M=>{n(O=>{const D=new Date(O);return D.setSeconds(Number(M)),D})},[]),d=g.useCallback(M=>{const O=new Date(M);n(O)},[]),u=cl(r,o),{hourOptions:h,minuteOptions:b,secondOptions:v,amPmOptions:p}=al({formatOptions:e,locale:s});return{amPmOptions:p,formattedTime:u,hourOptions:h,minuteOptions:b,secondOptions:v,setHours:i,setMinutes:c,setSeconds:l,setTime:d,time:new Date(r)}}const qm=e=>{const{regionModel:t}=sl(),s=g.useMemo(()=>({hour12:t==null?void 0:t.is12HourTimeFormat}),[t==null?void 0:t.is12HourTimeFormat]);return ll({...e,locale:t==null?void 0:t.regionId,format:t==null?void 0:t.selectedTimeFormat,formatOptions:s})};function Wm(e){return t=>{const[s]=rl();return s?_.jsx(mc,{message:"Wait a moment while your project reloads..."}):_.jsx(e,{...t})}}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:()=>Qr.observer});exports.AuthState=ai;exports.BrowserKosRouter=yi;exports.BrowserRouter=zi;exports.ChildModels=mt;exports.ConfigBean=It;exports.CoreExtensionManager=hf;exports.CoreModels=lr;exports.CreateModelTranslationsContext=_c;exports.CreateModelTranslationsProvider=Ff;exports.DateDisplayFormat=Wc;exports.DependencyLifecycle=j;exports.DependencyModels=P;exports.Device=Ss;exports.DeviceServices=Lg;exports.DomIntersectionStrategy=ol;exports.EVENT_TROUBLE_ADDED=uu;exports.EVENT_TROUBLE_REMOVED=hu;exports.EXTENSION_TROUBLE_DATA_MAPPER=bs;exports.EXTENSION_TROUBLE_MAPPER=Ht;exports.ErrorBoundaryWithFallback=pc;exports.EventBus=wl;exports.ExtensionManager=C;exports.FUTURE_CONTAINER_MODEL_TYPE=qi;exports.FUTURE_MODEL_TYPE=Ni;exports.FUTURE_NOT_ASSIGNED=Uo;exports.FeatureFlagService=cn;exports.FetchError=ne;exports.FutureContainerFactory=ye;exports.FutureContainerModel=Zi;exports.FutureEndState=Ke;exports.FutureFactory=Xe;exports.FutureHandler=Vo;exports.FutureManager=Se;exports.FutureModel=Gi;exports.FutureService=Ue;exports.HEADER_CACHE_CONTROL=tn;exports.HEADER_CONTENT_TYPE=en;exports.HEADER_DESTINATION_ADDR=he;exports.HEADER_FOS_REQUEST_ID=sn;exports.HEADER_METHOD=Rs;exports.HEADER_ORDERED=Oo;exports.HEADER_REQUEST_ID=xt;exports.HEADER_REQUEST_TYPE=ie;exports.HEADER_RESPONSE_ID=Ls;exports.HEADER_SOURCE_ADDR=Jr;exports.HEADER_TOPIC=Xr;exports.HEADER_URL=We;exports.HEADER_WORK_TRACKER=So;exports.KOS_MODEL_ID=cs;exports.KeyValue=Qo;exports.KeyValueServices=ih;exports.Kos=H;exports.KosConfigPropertySpec=Ae;exports.KosContainerIndex=No;exports.KosContextBean=fi;exports.KosContextManager=k;exports.KosCore=E;exports.KosCoreModelPropertyMapper=oe;exports.KosDataContainer=mi;exports.KosDependencyTypes=kl;exports.KosExtensionUtils=bd;exports.KosFeatureFlags=Ol;exports.KosFetchMethods=wi;exports.KosGlobalConfig=Co;exports.KosLog=f;exports.KosMockEvents=nn;exports.KosModel=Zn;exports.KosModelCollectionProvider=Lf;exports.KosModelContainer=fe;exports.KosModelContext=Hs;exports.KosModelEvents=S;exports.KosModelFactory=vt;exports.KosModelLoader=vc;exports.KosModelLoaderDisplay=Mc;exports.KosModelManager=Jn;exports.KosModelProvider=yc;exports.KosModelRegistrationFactory=ge;exports.KosModelRegistry=_o;exports.KosModelState=y;exports.KosModelSymbol=yn;exports.KosModelVisitor=Bd;exports.KosObservableData=di;exports.KosRegistration=au;exports.KosSingletonRegistration=cu;exports.KosTime=ms;exports.KosTimeContext=fr;exports.KosTimeProvider=Yf;exports.KosTimeServices=dh;exports.KosTimer=ac;exports.KosToken=pi;exports.KosTranslationProvider=Jf;exports.KosTranslations=Fa;exports.KosWSTransportStatus=Wn;exports.KosWsEvents=Pt;exports.LOGIN_HOST=on;exports.LOGIN_URL=pl;exports.LoadingMessage=mc;exports.LogBlock=Dt;exports.LogBlockContainer=js;exports.LogConfig=yt;exports.LogStream=_t;exports.LogStreamContainer=Gt;exports.LogStreamServices=Mh;exports.MODEL_DELETION_DELAY=Xn;exports.MiddlewareChain=li;exports.ModelEffects=bt;exports.MultipleFutureHandler=Fu;exports.NestedModelContext=Vs;exports.NetworkInterface=nr;exports.NetworkInterfaceContainer=Rt;exports.NetworkInterfaceServices=Gg;exports.ObservableData=Oe;exports.Ota=vs;exports.OutsideAlerter=am;exports.PLUGIN_EXTENSION_NAME=wd;exports.PORT=rn;exports.PROFILE_LOG_DEBUG=gn;exports.PROFILE_LOG_INFO=fn;exports.PROFILE_RELAX_STORE_VALIDATION=Dl;exports.PROFILE_TOOLS_PREVIEW=hn;exports.ParentModel=pt;exports.PluginExtensionManager=vd;exports.ProgressBar=Df;exports.ReferenceConfig=ts;exports.RegionInfo=z;exports.RegionServices=_u;exports.RegistrationManager=$;exports.Registry=df;exports.STATUS=$o;exports.ServiceFactory=V;exports.SingletonKosModelRegistrationFactory=we;exports.SoftwareInfo=Ms;exports.SoftwareInfoContext=pr;exports.SoftwareInfoProvider=Wf;exports.SoftwareInfoServices=tg;exports.StateBean=Ct;exports.StateBeanServices=ag;exports.StateProp=er;exports.StatePropServices=yg;exports.StorageDevice=As;exports.StorageDeviceContainer=ze;exports.StorageDeviceServices=qg;exports.SubscriptionHandlers=ee;exports.TIMER_END=ur;exports.TIMER_EVENT=dr;exports.TimerManager=cc;exports.TokenContext=$c;exports.TokenProvider=Qf;exports.Topics=Mt;exports.Trans=pm;exports.TransitionMap=ss;exports.Transitions=Lo;exports.Translation=Is;exports.TranslationContainer=ue;exports.TranslationContainerContext=yr;exports.TranslationContext=Sg;exports.TransportFactory=ho;exports.Trouble=At;exports.TroubleContainer=Ve;exports.TroubleServices=Bh;exports.Troubles=J;exports.UsbUpdate=cr;exports.UsbUpdateContainer=kt;exports.UsbUpdateServices=of;exports.WS_EVENT_TYPE=Ua;exports.WebSocketEvents=wt;exports.WebSocketTransport=xs;exports.WsEventFactory=sr;exports.acceptOrgInvitation=fc;exports.addFuture=Ui;exports.api=Hi;exports.applyMixins=Ml;exports.buildConfigBeanModel=mu;exports.buildFuture=qo;exports.buildFutureModel=Bi;exports.cancelFuture=ji;exports.convert=Pi;exports.convertFileSizeRaw=vl;exports.createBaseMessage=On;exports.createBroadcastMessageResponse=Cn;exports.createClient=xo;exports.createFosBaseMessage=$n;exports.createHeaders=co;exports.createKosHtpMessageResponse=Rn;exports.createKosMessage=Dn;exports.createKosMessageResponse=Ln;exports.createMessageBody=be;exports.createModelDependency=Gn;exports.createOptionKey=Hl;exports.createPropKey=De;exports.createReadableStream=lo;exports.createStudioMessage=Tn;exports.createStudioMessageRequest=Sn;exports.createStudioMessageResponse=An;exports.debounce=an;exports.deleteFuture=Fi;exports.destroyKosModel=$e;exports.evaluateScopes=$i;exports.executeChildrenModelLifecycle=Yn;exports.executeDependentModelLifecycle=ot;exports.executeListLifecycle=Vn;exports.fetchModel=sm;exports.findModel=Id;exports.findModels=si;exports.fireIntent=bi;exports.formatDateSince=$l;exports.getAllKosCompanionModels=$d;exports.getCalendarMonthArray=Uc;exports.getConfigBean=Ti;exports.getDayStrings=jc;exports.getDays=Dm;exports.getDaysArray=xc;exports.getDependenciesByLifecycle=Hn;exports.getFormattedDate=Am;exports.getFormattedMonth=Cm;exports.getFormattedMonthsArray=wr;exports.getFormattedYear=se;exports.getFormattedYearsArray=Fc;exports.getFutures=Vu;exports.getKosCompanionModel=Td;exports.getKosLocalizationDescriptor=La;exports.getKosMessageLogging=vn;exports.getKosModel=ti;exports.getKosModelSync=Ze;exports.getKosModelType=Ed;exports.getKosSessionKey=gi;exports.getLastDayOfMonth=ft;exports.getLocalizationDescriptor=wg;exports.getLogLevel=wn;exports.getLogMessageToStudio=Mn;exports.getMessageBody=uo;exports.getMonthsArray=Pc;exports.getQueryParams=ae;exports.getTranslations=Ra;exports.getYearsArray=Nc;exports.hasDecimals=Ei;exports.hasKosProfile=io;exports.hslStringToHex=dn;exports.hslToHex=ln;exports.initKosProvider=jf;exports.isBoolean=Bo;exports.isKosCompanionTypeFactory=Qn;exports.isKosDataModel=os;exports.isKosLoggingEnabled=Rl;exports.isKosModel=te;exports.isKosModelContainer=zn;exports.isKosModelReady=ds;exports.isLocalRefId=tu;exports.isNumber=Ps;exports.isValidDate=gt;exports.kosAction=Y;exports.kosAutoEffect=N;exports.kosChild=ce;exports.kosCompanion=zl;exports.kosComputed=vi;exports.kosConfigBean=Ns;exports.kosConfigProperty=Nu;exports.kosContext=ql;exports.kosDependency=Ft;exports.kosEffect=Mi;exports.kosFuture=hr;exports.kosLogger=Wl;exports.kosModel=A;exports.kosModelEffect=Pn;exports.kosObservable=Fo;exports.kosParentAware=ks;exports.kosReference=Zl;exports.kosStateBean=bf;exports.kosStateProp=wf;exports.kosSubscribe=Ql;exports.kosTopicHandler=R;exports.kosWhen=fo;exports.login=uc;exports.mapConfigBeanModelToDto=Ai;exports.mapDataToModel=ao;exports.mapDtoToConfigBeanModel=Si;exports.mapDtoToFutureModel=zo;exports.mapDtoToFutureOptions=Yo;exports.mapUpdateDtoToConfigBeanModel=Di;exports.modelFactory=Ut;exports.modifyConfigBean=Ii;exports.modifyFuture=Yu;exports.pairedClientHeartbeat=zd;exports.pipe=hi;exports.preloadKosModel=Dd;exports.processId=Tl;exports.processMiddleware=Gd;exports.registerCompanionModel=Sd;exports.registerCoreModels=oc;exports.registerExtensionPoint=Ro;exports.registerIntentHandler=du;exports.registerKosModel=ri;exports.registerLegacyModel=oi;exports.resetKosModel=ei;exports.resetPassword=gc;exports.resolveBaseUrl=ci;exports.resolveChild=qn;exports.resolveContainerDeltas=_l;exports.resolveItemListDeltas=Il;exports.resolveKosCompanion=go;exports.resolveKosContext=ru;exports.resolveKosProfiles=pn;exports.resolveListDeltas=El;exports.resolveServiceUrl=q;exports.resolveVariable=un;exports.retryWithExponentialBackoff=Wd;exports.sendBroadcastMessage=Gl;exports.sendKosHttpMessageResponse=xn;exports.sendKosMessage=jl;exports.sendKosMessageResponse=kn;exports.sendRequest=su;exports.sendStudioMessage=Kl;exports.sendStudioMessageRequest=Bl;exports.startPasswordReset=hc;exports.stringComponentInsert=Cc;exports.studioAcceptOrgInvitation=Ef;exports.studioLogin=vf;exports.studioResetPassword=_f;exports.studioStartPasswordReset=Mf;exports.subscribeStore=gf;exports.syncPublish=ou;exports.transitionToActive=Un;exports.transitionToInit=Kn;exports.transitionToLoad=Bn;exports.transitionToReady=jn;exports.transitionToUnload=Jl;exports.troubleByTypeReducer=Dg;exports.troubleDataFactory=_a;exports.unloadKosModel=_d;exports.unsubscribeIntentService=lu;exports.updateCompanionModelRegistration=Vd;exports.updateModelRegistration=Hd;exports.updateRegion=ic;exports.updateTimeZone=Eo;exports.useAmPmValues=il;exports.useCalendarDayArray=qc;exports.useConfigBean=$m;exports.useConfigProperty=kc;exports.useContextModel=Cf;exports.useContextModelHierarchy=wc;exports.useDateArrays=Bc;exports.useDateProps=Lm;exports.useDateRelativeConfig=km;exports.useDateRelativeData=Qc;exports.useDayNames=Yc;exports.useDayOptions=Vc;exports.useDays=Mr;exports.useDevice=Oc;exports.useFormattedDate=zc;exports.useFormattedTime=cl;exports.useHourValues=nl;exports.useKosCore=Ic;exports.useKosDateFormats=Pm;exports.useKosModel=B;exports.useKosRegions=sl;exports.useKosTime=gr;exports.useKosTimeContext=zf;exports.useKosTimeFormats=Gm;exports.useKosTimeZones=Um;exports.useKosTranslation=vm;exports.useKosTranslationContext=em;exports.useLocalComputed=Hm;exports.useModelFromHierarchy=xf;exports.useMonths=Gc;exports.useMonthsOptions=Hc;exports.useMutationObserver=Ym;exports.useNetworkInterfaceContainer=Sc;exports.useOta=Dc;exports.usePressGesture=zm;exports.useProjectReload=rl;exports.useRegionTimeProps=qm;exports.useRegionalTimeDate=Zc;exports.useSoftwareInfo=mr;exports.useSoftwareInfoContext=Zf;exports.useStateProperty=cm;exports.useStorageDeviceContainer=Ac;exports.useSuspenseData=Io;exports.useTimeOptions=al;exports.useTimeProps=ll;exports.useTimeValues=To;exports.useTimer=dm;exports.useTranslationContainer=Rc;exports.useTroubleContainerModel=br;exports.useTroubleModel=_m;exports.useTroublePresence=Em;exports.useUsbUpdateContainer=Lc;exports.useYears=vr;exports.useYearsOptions=Kc;exports.uuid=Nt;exports.variableToHex=Sl;exports.waitForRequest=Po;exports.whenReady=Q;exports.withDevice=tm;exports.withKosTime=om;exports.withNetworkInterfaceContainer=rm;exports.withOta=nm;exports.withProjectReloading=Wm;exports.withSoftwareInfo=qf;exports.withStorageDeviceContainer=lm;exports.withTranslationContainer=Mm;exports.withTroubleContainer=Im;exports.withUsbUpdateContainer=Tm;exports.wrapPromise=Do;
|
|
145
|
+
`;return _.jsxs("div",{css:r,children:[_.jsxs("div",{css:n,children:[_.jsx("div",{css:i,children:t}),_.jsx("div",{css:[c,e<0?l:""]})]}),_.jsx("div",{children:o})]})},Cf={setModel:()=>!1},Hs=g.createContext(Cf),Af=()=>{const e=g.useContext(Hs);if(e==null)throw new Error("useModels must be used within a KosModelProvider");return e.model},bc=({children:e})=>{const[t,s]=g.useState(),o=g.useCallback(r=>(s(r),!0),[s]);return _.jsx(Hs.Provider,{value:{model:t,setModel:o},children:e})},wc=f.createLogger({name:"kos-model-hierarchy-context"}),Rf={models:[],addModel:()=>{wc.debug("Default implementation being used. Do Nothing.")}},Vs=g.createContext(Rf),Lf=({children:e})=>{const[t,s]=g.useState([]),o=g.useCallback(r=>{t.includes(r)||(wc.debug("adding to hierarchy context",r.id),s(n=>[...n,r]))},[t]);return _.jsx(Vs.Provider,{value:{models:t,addModel:o},children:e})},xf=()=>!0,vc=e=>{const t=g.useContext(Vs);if(!t)throw new Error("useContextModelHierarchy must be used within a KosModelCollectionProvider");const s=(e==null?void 0:e.filter)||xf;return g.useMemo(()=>t.models.filter(s),[t.models,s])},kf=e=>vc({filter:s=>{const o=We(s.id);return(o==null?void 0:o.type)===e}})[0],Pf=f.createLogger({name:"kos-model-loader"}),Nf=()=>_.jsx("div",{}),Mc=({fallback:e,children:t,...s})=>_.jsx(bc,{children:_.jsx(yc,{fallback:e,children:_.jsx(g.Suspense,{children:_.jsx(_c,{...s,children:t})})})}),_c=e=>{const[t,s]=g.useState(),[o,r]=g.useState(!1),{setModel:n}=g.useContext(Hs),i=g.useContext(Vs);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 Pf.error(e.error),new Error(e.error);const c=e.loading||_.jsx(Nf,{});return _.jsx(_.Fragment,{children:t&&o?e.children:c})},as={header:{title:"Model",createLabel:"Create new Model",deleteLabel:"Delete"},createModal:{okText:"OK",cancelText:"Cancel",title:"Create New Model"}},Ec=g.createContext(as),Ff=({translations:e=as,children:t})=>{const s={header:{...as.header,...e.header},createModal:{...as.createModal,...e.createModal}};return _.jsx(Ec.Provider,{value:s,children:t})};function Uf(e,t){const s=E.create(e,!1,t),o=s.whenReady().then(()=>s);return Co(o)}const Ic=g.createContext(void 0),jf=(e={models:{},preloadModels:[]},t)=>{const s=Uf(e,t),o=({children:r})=>{const n=s.read(),[i,c]=g.useState(n.onlineStatus);return g.useEffect(()=>{const l=N(()=>{c(n.onlineStatus)});return()=>{l()}},[n]),_.jsx(Ic.Provider,{value:{kosCore:n,online:i},children:r})};return{KosCoreContextProvider:Xr.observer(o)}},Tc=()=>{const e=g.useContext(Ic);if(e===void 0)throw new Error("useKosCore must be used within a KosCoreContextProvider");return e},Bf=8,Kf=(e=0)=>new Promise(t=>{setTimeout(()=>{t(!0)},2**e*10)}),Te=new Map;function Gf(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 Hf(e,t){return Gf(e,t)}async function Vf(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>Bf)throw Error(`kOS Model ${s} has not been found`);await Kf(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=Tc(),[i,c]=g.useState(!1),[l,d]=g.useState(),{kosModel:u,model:h}=Hf(t||s||"",()=>Vf(n.kosCore,e));return g.useEffect(()=>{async function b(){try{return await n.kosCore.whenReady(),o&&await(u==null?void 0:u.transition(S.GO_ACTIVE,y.ACTIVE)),c(!0),u}catch(p){d(p.message)}}let v;return n.kosCore&&t&&b().then(p=>{v=N(()=>{const M=(p==null?void 0:p.status)===y.READY;c(M)})}).catch(p=>{console.error(p)}),()=>{if(o){if(h!=null&&h.id){const p=n.kosCore.modelManager.getModelById(h.id);p==null||p.transition(S.GO_INACTIVE,y.INACTIVE).then(()=>{if(r){const M=h.id;$e(h).then(()=>{Te.delete(M),v==null||v()})}})}}else r&&h&&$e(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:Mc}},fr=()=>{const e=ms.type;return B({modelId:e,modelType:ms.type,options:{}})},mr=g.createContext(void 0),Yf=({children:e})=>{const{model:t,ready:s}=fr(),o=g.useMemo(()=>s&&t?{model:t}:{},[s,t]);return _.jsx(mr.Provider,{value:o,children:e})},zf=()=>{const e=g.useContext(mr);if(!e)throw new Error("useKosTimeContext must be used within a KosTimeProvider");return e},pr=()=>{const e=Ms.type;return B({modelId:e,modelType:Ms.type,options:{}})};function qf(e){return()=>t=>{const{model:s,status:o,KosModelLoader:r}=pr();return _.jsx(r,{...o,children:_.jsx(e,{...t,softwareInfo:s})})}}const yr=g.createContext(void 0),Wf=({children:e})=>{const{model:t,ready:s}=pr(),o=g.useMemo(()=>s&&t?{model:t}:{},[s,t]);return _.jsx(yr.Provider,{value:o,children:e})},Zf=()=>{const e=g.useContext(yr);if(!e)throw new Error("useSoftwareInfoContext must be used within a SoftwareInfoProvider");return e},$c=new yi,Oc=g.createContext($c);function Qf({children:e}){return _.jsx(Oc.Provider,{value:$c,children:e})}const br=g.createContext(void 0),Xf=()=>{const e=window.location.origin,t=ce();return(t==null?void 0:t.host)||e},Jf=({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(),b=r||Xf(),v=g.useMemo(()=>t??"app/system",[t]);g.useEffect(()=>{async function $(){const se=(Array.isArray(v)?v:[v]).map(X=>(n||xa(X))()),Ys=(await Promise.allSettled(se)).map(X=>{if(X.status==="rejected"){f.warn("Failed to load localization descriptor",X.reason);return}return X.value}).filter(X=>!!X).reverse().reduce((X,Me)=>{const zs=Me.path;return Object.keys(Me.namespaces).forEach(qs=>{const Ws=Me.namespaces[qs];Ws.basePath=zs}),{...X,namespaces:{...X.namespaces,...Me.namespaces}}},{});d(Ys)}$()},[v,n]),g.useEffect(()=>{async function $(){if(l){const C=b,{translations:se}=await Ua.init({lang:s,descriptor:l,defaultNamespace:"common",resolver:o,rootUrl:C});h(se),c(!0)}}$()},[s,l,o,b]);const p=g.useMemo(()=>i?{setLocale:$=>{u&&(u.currentLocale=$)}}:{setLocale:()=>{throw new Error("Translations not ready")}},[i,u]),M=i?e:null;return _.jsx(br.Provider,{value:p,children:M})},em=()=>{const e=g.useContext(br);if(!e)throw new Error("useTranslationContainerContext must be used within a TranslationContainerProvider");return e},Sc=()=>{const e=Ss.type;return B({modelId:e,modelType:Ss.type,options:{}})};function tm(e){return t=>{const{model:s,status:o,KosModelLoader:r}=Sc();return _.jsx(r,{...o,children:_.jsx(e,{...t,device:s})})}}function sm(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 Co(o)}function om(e){return t=>{const{model:s,status:o,KosModelLoader:r}=fr();return _.jsx(r,{...o,children:_.jsx(e,{...t,kosTime:s})})}}const Dc=()=>{const e=Rt.type;return B({modelId:e,modelType:Rt.type,options:{}})};function rm(e){return t=>{const{model:s,status:o,KosModelLoader:r}=Dc();return _.jsx(r,{...o,children:_.jsx(e,{...t,networkInterfaceContainer:s})})}}const Cc=()=>{const e=vs.type;return B({modelId:e,modelType:vs.type,options:{}})};function nm(e){return t=>{const{model:s,status:o,KosModelLoader:r}=Cc();return _.jsx(r,{...o,children:_.jsx(e,{...t,oTA:s})})}}function im(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 am(e){const t=g.useRef(null),s=e.onAlert;return im(t,s),_.jsx("div",{ref:t,style:{width:"100%"},children:e.children})}const cm=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 Q(h),n(!0))}catch(b){c(b.message)}}u(t)},[t]),g.useEffect(()=>{const u=N(()=>{t&&r&&o(t.value)});return()=>{u()}},[r,t]),[s,{ready:r,error:i}]},Ac=()=>{const[e,t]=g.useState(!1),[s,o]=g.useState([]),r=Ye.type,n=B({modelId:r,modelType:Ye.type,options:{}});return g.useEffect(()=>{const i=N(()=>{var c,l;t(((c=n.model)==null?void 0:c.isStorageInserted)??!1),o(((l=n.model)==null?void 0:l.data)??[])});return()=>{i()}},[n.model]),{...n,inserted:e,devices:s}};function lm(e){return t=>{const{model:s,status:o,KosModelLoader:r}=Ac();return _.jsx(r,{...o,children:_.jsx(e,{...t,storageDeviceContainer:s})})}}const dm=({timerName:e,onTimerExpired:t,timerEventActions:s,autoStart:o})=>{const r=lc.getTimer(e);return g.useEffect(()=>{const n=U(ur,i=>{const{name:c,action:l,remainingTime:d}=i==null?void 0:i.body;c===e&&r&&(l===hr?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)}},um=e=>{const t=/[\\^$.*+?()[\]{}|]/g;return RegExp(t.source).test(e)?e.replace(t,"\\$&"):e},hm=e=>e instanceof RegExp,gm=e=>typeof e=="string",fm=(e,t,s)=>{if(e===""||t==="")return e;let o=t;hm(o)||(o=new RegExp("("+um(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},Rc=(e,t,s)=>{let o=e;return Array.isArray(o)||(o=[o]),o.flatMap(r=>gm(r)?fm(r,t,s):r)};function mm(e,t){let s=e;return Object.entries(t).forEach(([o,r])=>{const n=new RegExp(`<${o}>(.*?)</${o}>|<${o}/>`,"g");s=Rc(s,n,(i,c)=>r.type==="br"?_.jsx("br",{}):g.cloneElement(r,{key:`${o}-${c}`},i))}),s}const pm=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=mm(c,r||{});return _.jsx("span",{className:e.className,children:l})},Ne=new Map;function ym(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 To(e,t){return ym(e,t)}const bm=async()=>{const e=await si(he.type);return await Q(e.model),e.model},wm=async(e,t,s)=>{const o=e.resolveNamespace(t);await Q(o);for(const r of s){const n=e.resolveNamespace(r);await Q(n),Ne.set(r,{status:"finished",result:n})}return o},vm=(e,t)=>{const s=[e].flat(),[o,...r]=s,n=To(he.type,bm),i=s.join("__"),c=To(i,()=>wm(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 b=t!=null&&t.keyPrefix?`${t.keyPrefix}.${u}`:u;return c?c.resolveKey(b,h):(f.debug(`Translation model ${e} not ready for key: ${b}`),b)},[t==null?void 0:t.keyPrefix,e,c]),i18n:l}},Lc=()=>{const e=he.type;return B({modelId:e,modelType:he.type,options:{}})};function Mm(e){return t=>{const{model:s,status:o,KosModelLoader:r}=Lc();return _.jsx(r,{...o,children:_.jsx(e,{...t,translationContainer:s})})}}const _m=e=>B({modelId:e,modelType:Ct.type}),wr=()=>B({modelId:He.type,modelType:He.type,options:{}}),Em=({troubleType:e,condition:t})=>{const{model:s}=wr(),[o,r]=g.useState(!1),[n,i]=g.useState([]),c=g.useCallback(()=>{var l,d;return n.length>0&&((l=n[0])!=null&&l.resolvable)?(d=n[0])==null?void 0:d.resolve():Promise.resolve(void 0)},[n]);return g.useEffect(()=>N(()=>{const d=(e?s==null?void 0:s.troubles.getIndexByKey("byType",e):s==null?void 0:s.troubles.data)||[],u=t?d.filter(t):d;r(u.length>0),i(u)}),[t,s,e]),[o,c,n.length>0?n[0]:void 0,n]};function Im(e){return t=>{const{model:s,status:o,KosModelLoader:r}=wr();return _.jsx(r,{...o,children:_.jsx(e,{...t,troubleContainer:s})})}}const xc=()=>{const e=xt.type,t=B({modelId:e,modelType:xt.type,options:{},activate:!0,destroyOnUnmount:!0}),[s,o]=g.useState(!1),[r,n]=g.useState(!1),[i,c]=g.useState([]);return g.useEffect(()=>{const l=N(()=>{var d,u,h;o(((d=t.model)==null?void 0:d.isUsbInserted)??!1),n(((u=t.model)==null?void 0:u.hasAvailableUpdates)??!1),c(((h=t.model)==null?void 0:h.data)??[])});return()=>{l()}},[t.model]),{...t,inserted:s,updateAvailable:r,updates:i}};function Tm(e){return t=>{const{model:s,status:o,KosModelLoader:r}=xc();return _.jsx(r,{...o,children:_.jsx(e,{...t,usbUpdateContainer:s})})}}const $m=({path:e,propKey:t})=>{const{status:s}=B({modelType:It.type,modelId:e,options:{path:e}}),[o,r]=g.useState(!1),[n,i]=g.useState(),[c,l]=g.useState(""),[d,u]=g.useState(),h=b=>{n&&t&&n.updateProperty(t,b)};return g.useEffect(()=>{var b;s.model&&i(s.model),s.model&&t&&((b=s.model)!=null&&b.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 b=n==null?void 0:n.props[t];l(b||"")})},[n,t]),{config:n,ready:o,value:c,error:d,updateValue:h}},Om=(e,t)=>{switch(t.type){case"UPDATE":return t.payload;default:return e}},kc=({configProperty:e,optionsTransformer:t})=>{const[s,o]=g.useState(!1),[r,n]=g.useState(""),[i,c]=g.useReducer(Om,{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 Q(u),o(!0))}catch(h){n(h.message)}}d(e)},[e]),g.useEffect(()=>{const d=N(()=>{if(e&&s){let u=[];t&&(u=t(e.options)),c({type:"UPDATE",payload:{value:String(e.value),displayValue:e.displayValue,significantValue:e.significantValue,unit:e.unit,options:e.options,mappedOptions:u,updateProperty:e.updateProperty,displayOptions:e==null?void 0:e.displayOptions}})}});return()=>{d()}},[e,t,s]),{...i,configSelectProps:{onChange:l,value:i.value,options:t?i.mappedOptions||[]:i.options||[]},ready:s,error:r}};function Sm(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 Dm(e,t){return new Date(e,t,0).getDate()}function Pc(e,t){const s=Sm(t,e),o=[];for(let r=1;r<=s;r++)o.push(r);return o}function Nc(){return[...Array(12).keys()].map(t=>new Date(0,t).getMonth())}function Fc(e=[2018,2028]){const t=[];for(let s=e[0];s<=e[1];s++)t.push(s);return t}function Uc(e,t=[2018,2028]){const s=Fc(t);return e==="long"?s:s.map(o=>Number(o.toString().substring(2)))}function vr(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 Cm({locale:e="en-US",year:t,month:s,day:o,formatOptions:r={weekday:"long",year:"numeric",month:"long",day:"numeric"},displayOrder:n}){const i=s-1,c=new Date(t,i,o),l=new Intl.DateTimeFormat(e,{month:r.month}).format(c),d=new Intl.DateTimeFormat(e,{year:r.year}).format(c),u=new Intl.DateTimeFormat(e,{day:r.day}).format(c);return n?n=="MMDDYY"?`${l} ${u} ${d}`:n==="DDMMYY"?`${u} ${l} ${d}`:n==="YYMMDD"?`${d} ${l} ${u}`:`${d} ${u} ${l}`:new Intl.DateTimeFormat(e,r).format(c)}function oe(e){return e.toString().length===2?new Date(Date.parse(`01 Jan 20${e}`)).getFullYear():e}function Am(e){return typeof e=="string"?new Date(Date.parse(`01 ${e.substring(0,3)} 2023`)).getMonth()+1:e}function jc(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 gt(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 ft(e,t){return new Date(e,t,0).getDate()}function Bc(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 Kc({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=Mr(n,o),d=Gc(n,o,e),u=Hc(i,e),h=Vc(i,e),b=_r(t,s),v=Yc(t,s,e,r),p=Wc(s,t,v),M=zc(e,c);return{daysArray:b,monthsArray:u,yearsArray:l,yearsOptionsArray:d,monthsOptionsArray:h,daysOptionsArray:v,calendarDayArray:p,dayNamesArray:M}}function Mr(e="long",t=[2018,2028]){return g.useMemo(()=>Uc(e,t),[e,t])}function Gc(e="long",t=[2018,2028],s="en-US"){const o=Mr(e,t);return g.useMemo(()=>o.map(n=>({label:n.toLocaleString(s).replace(",",""),value:n})),[s,o])}function Hc(e,t="en-US"){return g.useMemo(()=>vr(e,t),[e,t])}function Vc(e,t="en-US"){const s=g.useMemo(()=>Nc(),[]),o=g.useMemo(()=>vr(e,t),[e,t]);return g.useMemo(()=>[...Array(12).keys()].map(n=>({label:o[n],value:Number(s[n])})),[o,s])}function _r(e,t){const s=oe(e);return g.useMemo(()=>Pc(s,t),[t,s])}const Rm=(e,t,s,o=[])=>{const r=new Date(e,t,s).getDay();return o.length>0&&o.includes(r)};function Yc(e,t,s="en-US",o=[]){const r=_r(e,t);return g.useMemo(()=>r.map(i=>({label:i.toLocaleString(s),value:i,disabled:Rm(e,t,i,o)})),[o,s,t,r,e])}function zc(e="en-US",t="short"){return g.useMemo(()=>Bc(e,t),[e,t])}function qc({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 Wc(e,t,s){return g.useMemo(()=>jc(e,t,s),[e,t,s])}var Zc=(e=>(e.MMDDYY="MMDDYY",e.DDMMYY="DDMMYY",e.YYMMDD="YYMMDD",e.YYDDMM="YYDDMM",e))(Zc||{});function Lm({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),[b,v]=g.useState(l),[p,M]=g.useState(s),[$,C]=g.useState(o);g.useEffect(()=>{h(t)},[t]),g.useEffect(()=>{M(s)},[s]),g.useEffect(()=>{C(o)},[o]);const{yearsArray:se,yearsOptionsArray:ve,monthsArray:et,monthsOptionsArray:Ys,daysArray:X,daysOptionsArray:Me,calendarDayArray:zs,dayNamesArray:qs}=Kc({locale:e,year:u,yearRange:b,month:p,formatOptions:{yearFormat:r,monthFormat:n,dayFormat:i},daysOfWeekFilter:d}),{formattedDate:Ws}=qc({year:u,month:p,day:$,formatString:c});return{dateActions:{setYear:h,setYearRange:v,setMonth:M,setDay:C,nextMonth:()=>{const K=p<11?oe(u):oe(u+1),W=p<11?p+1:0;if(!gt(K,W,$)){const _e=ft(K,W);C(_e)}W===0&&h(K),M(W)},previousMonth:()=>{const K=oe(p===0?u-1:u),W=p===0?11:p-1;if(!gt(K,W,$)){const _e=ft(K,W);C(_e)}W===11&&h(K),M(W)},nextYear:()=>{const K=u<b[1]?u+1:b[0],W=oe(K);if(gt(W,p,$))h(K);else{const _e=ft(oe(u+1),p);C(_e),h(K)}},previousYear:()=>{const K=u>b[0]?u-1:b[0],W=oe(K);if(gt(W,p,$))h(K);else{const _e=ft(oe(u-1),p);C(_e),h(K)}}},dateState:{year:u,yearRange:b,month:p,day:$,yearsArray:se,yearsOptionsArray:ve,monthsArray:et,monthsOptionsArray:Ys,daysArray:X,daysOptionsArray:Me,calendarDayNames:qs,calendarDayArray:zs,formattedDate:Ws}}}function Qc({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 Xc=({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}=Qc({date:c,options:{ignoreDateFormat:!0}});return g.useEffect(()=>{const u=Number(e),h=Math.floor(u/3600),b=Math.floor(u%3600/60),v=u%60;s(h),r(b),i(v);const p=new Date;p.setHours(0,0,0,0);const M=new Date(p.getTime()+u*1e3);l(new Date(M))},[e]),{hours:t,minutes:o,seconds:n,formattedTime:d,timeActions:{setHours:s,setMinutes:r,setSeconds:i}}},xm=({configProperty:e})=>{const{value:t}=kc({configProperty:e}),s=parseInt(t||"0",10),{hours:o,minutes:r,seconds:n,formattedTime:i,timeActions:c}=Xc({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}},km=e=>_.jsx("option",{title:e.id,value:e.format,children:e.format},e.id),Pm=(e=km)=>{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=N(()=>{s((n==null?void 0:n.dateFormatOptions.map(e))||[])});return()=>{l()}},[n,i,e]),g.useEffect(()=>{const l=N(()=>{n!=null&&n.dateFormatId&&(n!=null&&n.selectedDateFormat)&&r({id:n==null?void 0:n.dateFormatId,value:n==null?void 0:n.selectedDateFormat})});return()=>{l()}},[n==null?void 0:n.selectedDateFormat,n==null?void 0:n.dateFormatId]);const c=g.useCallback(l=>{var u;let d="";typeof l=="string"?d=l:(u=l==null?void 0:l.target)!=null&&u.value&&(d=l.target.value),d&&(n==null||n.setSelectedDateFormat(d))},[n]);return{raw:(n==null?void 0:n.dateFormatOptions.map(l=>l.id))??[],regionModel:n,selectedDateFormat:(o==null?void 0:o.value)||"",dateFormatId:(o==null?void 0:o.id)||"",updateDateFormat:c,props:{onChange:c,value:(o==null?void 0:o.id)||"",options:t}}},Nm=e=>_.jsx("option",{title:e,value:e,children:e},e),Jc="kos:service:region:settings",el="timeZone",Fm=`${Jc}-${el}`,Um=(e=Nm)=>{const[t,s]=g.useState([]),[o,r]=g.useState(""),{model:n,ready:i}=B({modelType:z.type,modelId:z.type,options:{}}),c=Ce.factory(Fm)({path:Jc,attribute:el});g.useEffect(()=>{const d=N(()=>{s((n==null?void 0:n.timeZones.map(e))||[]),n!=null&&n.timeZones.length&&Io(n==null?void 0:n.timeZones[0])});return()=>{d()}},[n,i,e]),g.useEffect(()=>{const d=N(()=>{r(c.value||"")});return()=>{d()}},[c.value]);const l=g.useCallback(d=>{var h;let u="factory";typeof d=="string"?u=d:(h=d==null?void 0:d.target)!=null&&h.value&&(u=d.target.value),u&&Io(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}}},tl="kos:service:region",sl="regionId",jm=`${tl}-${sl}`,Bm=e=>_.jsx("option",{title:e,value:e,children:e},e),ol=(e=Bm)=>{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(jm)({path:tl,attribute:sl});g.useEffect(()=>{const d=N(()=>{s((n==null?void 0:n.availableRegions.map(e))||[])});return()=>{d()}},[n,i,e]),g.useEffect(()=>{const d=N(()=>{r(c.value||"factory")});return()=>{d()}},[c.value]);const l=g.useCallback(d=>{var h;let u="factory";typeof d=="string"?u=d:(h=d==null?void 0:d.target)!=null&&h.value&&(u=d.target.value),u&&ac(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}}},Km=e=>_.jsx("option",{title:e.id,value:e.format,children:e.format},e.id),Gm=(e=Km)=>{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=N(()=>{s((n==null?void 0:n.timeFormatOptions.map(e))||[])});return()=>{l()}},[n,i,e]),g.useEffect(()=>{const l=N(()=>{n!=null&&n.timeFormatId&&(n!=null&&n.selectedTimeFormat)&&r({id:n==null?void 0:n.timeFormatId,value:n==null?void 0:n.selectedTimeFormat})});return()=>{l()}},[n==null?void 0:n.selectedTimeFormat,n==null?void 0:n.timeFormatId]);const c=g.useCallback(l=>{var u;let d="";typeof l=="string"?d=l:(u=l==null?void 0:l.target)!=null&&u.value&&(d=l.target.value),d&&(n==null||n.setSelectedTimeFormat(d))},[n]);return{raw:(n==null?void 0:n.timeFormatOptions.map(l=>l.id))??[],regionModel:n,selectedTimeFormat:(o==null?void 0:o.value)??"",timeFormatId:(o==null?void 0:o.id)??"",updateTimeFormat:c,props:{onChange:c,value:(o==null?void 0:o.id)??"",options:t}}},Hm=(e,t)=>g.useMemo(()=>Mi(e),t),Vm={config:{attributes:!0,childList:!0,subtree:!0}};function Ym(e,t,s=Vm){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 rl={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}},io=f.createLogger({name:"usePressGesture",group:"kos-hooks"});function zm({onPressed:e,onRelease:t,intersectionStrategy:s=rl}){const o=g.useRef(!1),r=ml.useGesture({onDragStart:l=>{io.info("onDragStart",l.type),s.validateStart(l)&&(e&&e(),o.current=!0)},onDrag:l=>{io.info("onDrag",l.type),o.current&&s.validateStop(l)&&(t&&t(),o.current=!1)},onDragEnd:l=>{io.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 nl=()=>{const[e,t]=g.useState(!1),s=E.getInstance();return g.useEffect(()=>{const o=N(()=>{s&&s.reloading!==e&&t(s.reloading)});return()=>{o()}},[s,e]),[e]};function il(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 $o(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 al(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 cl({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=il(e,t),i=$o(60,s),c=$o(60,o),l=al(r);return{hourOptions:n,minuteOptions:i,secondOptions:c,amPmOptions:l}}function ll(e,t){return pe.format(e,t)}function dl({formatOptions:e,initialDate:t=new Date,locale:s="en-US",format:o="HH:mm"}){const[r,n]=g.useState(t),i=g.useCallback(M=>{n($=>{const C=new Date($);return C.setHours(Number(M)),C})},[]),c=g.useCallback(M=>{n($=>{const C=new Date($);return C.setMinutes(Number(M)),C})},[]),l=g.useCallback(M=>{n($=>{const C=new Date($);return C.setSeconds(Number(M)),C})},[]),d=g.useCallback(M=>{const $=new Date(M);n($)},[]),u=ll(r,o),{hourOptions:h,minuteOptions:b,secondOptions:v,amPmOptions:p}=cl({formatOptions:e,locale:s});return{amPmOptions:p,formattedTime:u,hourOptions:h,minuteOptions:b,secondOptions:v,setHours:i,setMinutes:c,setSeconds:l,setTime:d,time:new Date(r)}}const qm=e=>{const{regionModel:t}=ol(),s=g.useMemo(()=>({hour12:t==null?void 0:t.is12HourTimeFormat}),[t==null?void 0:t.is12HourTimeFormat]);return dl({...e,locale:t==null?void 0:t.regionId,format:t==null?void 0:t.selectedTimeFormat,formatOptions:s})};function Wm(e){return t=>{const[s]=nl();return s?_.jsx(pc,{message:"Wait a moment while your project reloads..."}):_.jsx(e,{...t})}}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:()=>Xr.observer});exports.AuthState=ci;exports.BrowserKosRouter=bi;exports.BrowserRouter=qi;exports.ChildModels=mt;exports.ConfigBean=It;exports.CoreExtensionManager=hf;exports.CoreModels=dr;exports.CreateModelTranslationsContext=Ec;exports.CreateModelTranslationsProvider=Ff;exports.DateDisplayFormat=Zc;exports.DependencyLifecycle=j;exports.DependencyModels=P;exports.Device=Ss;exports.DeviceServices=Lg;exports.DomIntersectionStrategy=rl;exports.EVENT_TROUBLE_ADDED=uu;exports.EVENT_TROUBLE_REMOVED=hu;exports.EXTENSION_TROUBLE_DATA_MAPPER=bs;exports.EXTENSION_TROUBLE_MAPPER=Ht;exports.ErrorBoundaryWithFallback=yc;exports.EventBus=wl;exports.ExtensionManager=A;exports.FUTURE_CONTAINER_MODEL_TYPE=Wi;exports.FUTURE_MODEL_TYPE=Fi;exports.FUTURE_NOT_ASSIGNED=jo;exports.FeatureFlagService=ln;exports.FetchError=ie;exports.FutureContainerFactory=ye;exports.FutureContainerModel=Qi;exports.FutureEndState=Be;exports.FutureFactory=Qe;exports.FutureHandler=Yo;exports.FutureManager=Se;exports.FutureModel=Hi;exports.FutureService=Fe;exports.HEADER_CACHE_CONTROL=sn;exports.HEADER_CONTENT_TYPE=tn;exports.HEADER_DESTINATION_ADDR=ge;exports.HEADER_FOS_REQUEST_ID=on;exports.HEADER_METHOD=Rs;exports.HEADER_ORDERED=So;exports.HEADER_REQUEST_ID=kt;exports.HEADER_REQUEST_TYPE=ae;exports.HEADER_RESPONSE_ID=Ls;exports.HEADER_SOURCE_ADDR=en;exports.HEADER_TOPIC=Jr;exports.HEADER_URL=qe;exports.HEADER_WORK_TRACKER=Do;exports.KOS_MODEL_ID=cs;exports.KeyValue=Xo;exports.KeyValueServices=ih;exports.Kos=H;exports.KosConfigPropertySpec=Ce;exports.KosContainerIndex=Fo;exports.KosContextBean=mi;exports.KosContextManager=x;exports.KosCore=E;exports.KosCoreModelPropertyMapper=re;exports.KosDataContainer=pi;exports.KosDependencyTypes=xl;exports.KosExtensionUtils=bd;exports.KosFeatureFlags=Ol;exports.KosFetchMethods=vi;exports.KosGlobalConfig=Ro;exports.KosLog=f;exports.KosMockEvents=an;exports.KosModel=Qn;exports.KosModelCollectionProvider=Lf;exports.KosModelContainer=me;exports.KosModelContext=Hs;exports.KosModelEvents=S;exports.KosModelFactory=vt;exports.KosModelLoader=Mc;exports.KosModelLoaderDisplay=_c;exports.KosModelManager=ei;exports.KosModelProvider=bc;exports.KosModelRegistrationFactory=fe;exports.KosModelRegistry=Eo;exports.KosModelState=y;exports.KosModelSymbol=bn;exports.KosModelVisitor=Bd;exports.KosObservableData=ui;exports.KosRegistration=au;exports.KosSingletonRegistration=cu;exports.KosTime=ms;exports.KosTimeContext=mr;exports.KosTimeProvider=Yf;exports.KosTimeServices=dh;exports.KosTimer=cc;exports.KosToken=yi;exports.KosTranslationProvider=Jf;exports.KosTranslations=Ua;exports.KosWSTransportStatus=Zn;exports.KosWsEvents=Pt;exports.LOGIN_HOST=rn;exports.LOGIN_URL=pl;exports.LoadingMessage=pc;exports.LogBlock=Dt;exports.LogBlockContainer=js;exports.LogConfig=yt;exports.LogStream=_t;exports.LogStreamContainer=Gt;exports.LogStreamServices=Mh;exports.MODEL_DELETION_DELAY=Jn;exports.MiddlewareChain=di;exports.ModelEffects=bt;exports.MultipleFutureHandler=Fu;exports.NestedModelContext=Vs;exports.NetworkInterface=ir;exports.NetworkInterfaceContainer=Rt;exports.NetworkInterfaceServices=Gg;exports.ObservableData=Oe;exports.Ota=vs;exports.OutsideAlerter=am;exports.PLUGIN_EXTENSION_NAME=wd;exports.PORT=nn;exports.PROFILE_LOG_DEBUG=fn;exports.PROFILE_LOG_INFO=mn;exports.PROFILE_RELAX_STORE_VALIDATION=Dl;exports.PROFILE_TOOLS_PREVIEW=gn;exports.ParentModel=pt;exports.PluginExtensionManager=vd;exports.ProgressBar=Df;exports.ReferenceConfig=ts;exports.RegionInfo=z;exports.RegionServices=_u;exports.RegistrationManager=O;exports.Registry=df;exports.STATUS=Oo;exports.ServiceFactory=V;exports.SingletonKosModelRegistrationFactory=we;exports.SoftwareInfo=Ms;exports.SoftwareInfoContext=yr;exports.SoftwareInfoProvider=Wf;exports.SoftwareInfoServices=tg;exports.StateBean=At;exports.StateBeanServices=ag;exports.StateProp=tr;exports.StatePropServices=yg;exports.StorageDevice=Cs;exports.StorageDeviceContainer=Ye;exports.StorageDeviceServices=qg;exports.SubscriptionHandlers=ee;exports.TIMER_END=hr;exports.TIMER_EVENT=ur;exports.TimerManager=lc;exports.TokenContext=Oc;exports.TokenProvider=Qf;exports.Topics=Mt;exports.Trans=pm;exports.TransitionMap=ss;exports.Transitions=xo;exports.Translation=Is;exports.TranslationContainer=he;exports.TranslationContainerContext=br;exports.TranslationContext=Sg;exports.TransportFactory=go;exports.Trouble=Ct;exports.TroubleContainer=He;exports.TroubleServices=Bh;exports.Troubles=J;exports.UsbUpdate=lr;exports.UsbUpdateContainer=xt;exports.UsbUpdateServices=of;exports.WS_EVENT_TYPE=ja;exports.WebSocketEvents=wt;exports.WebSocketTransport=ks;exports.WsEventFactory=or;exports.acceptOrgInvitation=mc;exports.addFuture=ji;exports.api=Vi;exports.applyMixins=Ml;exports.buildConfigBeanModel=mu;exports.buildFuture=Wo;exports.buildFutureModel=Ki;exports.cancelFuture=Bi;exports.convert=Ni;exports.convertFileSizeRaw=vl;exports.createBaseMessage=Sn;exports.createBroadcastMessageResponse=Rn;exports.createClient=Po;exports.createFosBaseMessage=On;exports.createHeaders=lo;exports.createKosHtpMessageResponse=Ln;exports.createKosMessage=Cn;exports.createKosMessageResponse=xn;exports.createMessageBody=be;exports.createModelDependency=Hn;exports.createOptionKey=Hl;exports.createPropKey=De;exports.createReadableStream=uo;exports.createStudioMessage=$n;exports.createStudioMessageRequest=Dn;exports.createStudioMessageResponse=An;exports.debounce=cn;exports.deleteFuture=Ui;exports.destroyKosModel=$e;exports.evaluateScopes=Oi;exports.executeChildrenModelLifecycle=zn;exports.executeDependentModelLifecycle=ot;exports.executeListLifecycle=Yn;exports.fetchModel=sm;exports.findModel=Id;exports.findModels=oi;exports.fireIntent=wi;exports.formatDateSince=$l;exports.getAllKosCompanionModels=$d;exports.getCalendarMonthArray=jc;exports.getConfigBean=$i;exports.getDayStrings=Bc;exports.getDays=Dm;exports.getDaysArray=Pc;exports.getDependenciesByLifecycle=Vn;exports.getFormattedDate=Cm;exports.getFormattedMonth=Am;exports.getFormattedMonthsArray=vr;exports.getFormattedYear=oe;exports.getFormattedYearsArray=Uc;exports.getFutures=Vu;exports.getKosCompanionModel=Td;exports.getKosLocalizationDescriptor=xa;exports.getKosMessageLogging=Mn;exports.getKosModel=si;exports.getKosModelSync=We;exports.getKosModelType=Ed;exports.getKosSessionKey=fi;exports.getLastDayOfMonth=ft;exports.getLocalizationDescriptor=wg;exports.getLogLevel=vn;exports.getLogMessageToStudio=_n;exports.getMessageBody=ho;exports.getMonthsArray=Nc;exports.getQueryParams=ce;exports.getTranslations=La;exports.getYearsArray=Fc;exports.hasDecimals=Ii;exports.hasKosProfile=ao;exports.hslStringToHex=un;exports.hslToHex=dn;exports.initKosProvider=jf;exports.isBoolean=Ko;exports.isKosCompanionTypeFactory=Xn;exports.isKosDataModel=os;exports.isKosLoggingEnabled=Rl;exports.isKosModel=te;exports.isKosModelContainer=qn;exports.isKosModelReady=ds;exports.isLocalRefId=tu;exports.isNumber=Ps;exports.isValidDate=gt;exports.kosAction=Y;exports.kosAutoEffect=N;exports.kosChild=le;exports.kosCompanion=zl;exports.kosComputed=Mi;exports.kosConfigBean=Ns;exports.kosConfigProperty=Nu;exports.kosContext=ql;exports.kosDependency=Ft;exports.kosEffect=_i;exports.kosFuture=gr;exports.kosLogger=Wl;exports.kosModel=D;exports.kosModelEffect=Nn;exports.kosObservable=Uo;exports.kosParentAware=xs;exports.kosReference=Zl;exports.kosStateBean=bf;exports.kosStateProp=wf;exports.kosSubscribe=Ql;exports.kosTopicHandler=R;exports.kosWhen=mo;exports.login=hc;exports.mapConfigBeanModelToDto=Ai;exports.mapDataToModel=co;exports.mapDtoToConfigBeanModel=Di;exports.mapDtoToFutureModel=qo;exports.mapDtoToFutureOptions=zo;exports.mapUpdateDtoToConfigBeanModel=Ci;exports.modelFactory=Ut;exports.modifyConfigBean=Ti;exports.modifyFuture=Yu;exports.pairedClientHeartbeat=zd;exports.pipe=gi;exports.preloadKosModel=Dd;exports.processId=Tl;exports.processMiddleware=Gd;exports.registerCompanionModel=Sd;exports.registerCoreModels=rc;exports.registerExtensionPoint=Lo;exports.registerIntentHandler=du;exports.registerKosModel=ni;exports.registerLegacyModel=ri;exports.resetKosModel=ti;exports.resetPassword=fc;exports.resolveBaseUrl=li;exports.resolveChild=Wn;exports.resolveContainerDeltas=_l;exports.resolveItemListDeltas=Il;exports.resolveKosCompanion=fo;exports.resolveKosContext=ru;exports.resolveKosProfiles=yn;exports.resolveListDeltas=El;exports.resolveServiceUrl=q;exports.resolveVariable=hn;exports.retryWithExponentialBackoff=Wd;exports.sendBroadcastMessage=Gl;exports.sendKosHttpMessageResponse=Pn;exports.sendKosMessage=jl;exports.sendKosMessageResponse=kn;exports.sendRequest=su;exports.sendStudioMessage=Kl;exports.sendStudioMessageRequest=Bl;exports.startPasswordReset=gc;exports.stringComponentInsert=Rc;exports.studioAcceptOrgInvitation=Ef;exports.studioLogin=vf;exports.studioResetPassword=_f;exports.studioStartPasswordReset=Mf;exports.subscribeStore=gf;exports.syncPublish=ou;exports.transitionToActive=jn;exports.transitionToInit=Gn;exports.transitionToLoad=Kn;exports.transitionToReady=Bn;exports.transitionToUnload=Jl;exports.troubleByTypeReducer=Dg;exports.troubleDataFactory=Ea;exports.unloadKosModel=_d;exports.unsubscribeIntentService=lu;exports.updateCompanionModelRegistration=Vd;exports.updateModelRegistration=Hd;exports.updateRegion=ac;exports.updateTimeZone=Io;exports.useAmPmValues=al;exports.useCalendarDayArray=Wc;exports.useConfigBean=$m;exports.useConfigProperty=kc;exports.useContextModel=Af;exports.useContextModelHierarchy=vc;exports.useDateArrays=Kc;exports.useDateProps=Lm;exports.useDateRelativeConfig=xm;exports.useDateRelativeData=Xc;exports.useDayNames=zc;exports.useDayOptions=Yc;exports.useDays=_r;exports.useDevice=Sc;exports.useFormattedDate=qc;exports.useFormattedTime=ll;exports.useHourValues=il;exports.useKosCore=Tc;exports.useKosDateFormats=Pm;exports.useKosModel=B;exports.useKosRegions=ol;exports.useKosTime=fr;exports.useKosTimeContext=zf;exports.useKosTimeFormats=Gm;exports.useKosTimeZones=Um;exports.useKosTranslation=vm;exports.useKosTranslationContext=em;exports.useLocalComputed=Hm;exports.useModelFromHierarchy=kf;exports.useMonths=Hc;exports.useMonthsOptions=Vc;exports.useMutationObserver=Ym;exports.useNetworkInterfaceContainer=Dc;exports.useOta=Cc;exports.usePressGesture=zm;exports.useProjectReload=nl;exports.useRegionTimeProps=qm;exports.useRegionalTimeDate=Qc;exports.useSoftwareInfo=pr;exports.useSoftwareInfoContext=Zf;exports.useStateProperty=cm;exports.useStorageDeviceContainer=Ac;exports.useSuspenseData=To;exports.useTimeOptions=cl;exports.useTimeProps=dl;exports.useTimeValues=$o;exports.useTimer=dm;exports.useTranslationContainer=Lc;exports.useTroubleContainerModel=wr;exports.useTroubleModel=_m;exports.useTroublePresence=Em;exports.useUsbUpdateContainer=xc;exports.useYears=Mr;exports.useYearsOptions=Gc;exports.uuid=Nt;exports.variableToHex=Sl;exports.waitForRequest=No;exports.whenReady=Q;exports.withDevice=tm;exports.withKosTime=om;exports.withNetworkInterfaceContainer=rm;exports.withOta=nm;exports.withProjectReloading=Wm;exports.withSoftwareInfo=qf;exports.withStorageDeviceContainer=lm;exports.withTranslationContainer=Mm;exports.withTroubleContainer=Im;exports.withUsbUpdateContainer=Tm;exports.wrapPromise=Co;
|
|
146
146
|
//# sourceMappingURL=index.cjs.map
|