@kosdev-code/kos-ui-sdk 0.1.0-next.944 → 0.1.0-next.958

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.
Files changed (320) hide show
  1. package/.kos.json +2 -1
  2. package/common/events/async-event-bus.d.ts +2 -11
  3. package/common/events/async-event-bus.d.ts.map +1 -1
  4. package/common/events/eventBus.d.ts +1 -18
  5. package/common/events/eventBus.d.ts.map +1 -1
  6. package/core/core/decorators/kos-child.d.ts +2 -3
  7. package/core/core/decorators/kos-child.d.ts.map +1 -1
  8. package/core/core/decorators/kos-companion.d.ts +25 -87
  9. package/core/core/decorators/kos-companion.d.ts.map +1 -1
  10. package/core/core/decorators/kos-container-aware-reconcile.test-d.d.ts +2 -0
  11. package/core/core/decorators/kos-container-aware-reconcile.test-d.d.ts.map +1 -0
  12. package/core/core/decorators/kos-container-aware.d.ts +191 -420
  13. package/core/core/decorators/kos-container-aware.d.ts.map +1 -1
  14. package/core/core/decorators/kos-execute-service-request.d.ts +7 -11
  15. package/core/core/decorators/kos-execute-service-request.d.ts.map +1 -1
  16. package/core/core/decorators/kos-execution-context.d.ts +14 -31
  17. package/core/core/decorators/kos-execution-context.d.ts.map +1 -1
  18. package/core/core/decorators/kos-future-aware.d.ts +21 -74
  19. package/core/core/decorators/kos-future-aware.d.ts.map +1 -1
  20. package/core/core/decorators/kos-http-decorators.d.ts +18 -62
  21. package/core/core/decorators/kos-http-decorators.d.ts.map +1 -1
  22. package/core/core/decorators/kos-logger-aware.d.ts +10 -60
  23. package/core/core/decorators/kos-logger-aware.d.ts.map +1 -1
  24. package/core/core/decorators/kos-model-effect.d.ts +10 -9
  25. package/core/core/decorators/kos-model-effect.d.ts.map +1 -1
  26. package/core/core/decorators/kos-multiple-future-aware.d.ts +21 -94
  27. package/core/core/decorators/kos-multiple-future-aware.d.ts.map +1 -1
  28. package/core/core/decorators/kos-reload-aware.d.ts +14 -16
  29. package/core/core/decorators/kos-reload-aware.d.ts.map +1 -1
  30. package/core/core/decorators/kos-service-request.d.ts +80 -238
  31. package/core/core/decorators/kos-service-request.d.ts.map +1 -1
  32. package/core/core/decorators/kos-state-machine.d.ts +35 -275
  33. package/core/core/decorators/kos-state-machine.d.ts.map +1 -1
  34. package/core/core/decorators/kos-trouble-aware.d.ts +9 -43
  35. package/core/core/decorators/kos-trouble-aware.d.ts.map +1 -1
  36. package/core/core/decorators/kos-view-model.d.ts +20 -100
  37. package/core/core/decorators/kos-view-model.d.ts.map +1 -1
  38. package/core/core/decorators/kosModel.d.ts.map +1 -1
  39. package/core/core/decorators/kosTopicHandler.d.ts +28 -89
  40. package/core/core/decorators/kosTopicHandler.d.ts.map +1 -1
  41. package/core/core/indexing/index.d.ts +2 -4
  42. package/core/core/indexing/index.d.ts.map +1 -1
  43. package/core/core/indexing/kos-container-index-aware.d.ts +17 -48
  44. package/core/core/indexing/kos-container-index-aware.d.ts.map +1 -1
  45. package/core/core/indexing/kos-index-aware.d.ts +11 -37
  46. package/core/core/indexing/kos-index-aware.d.ts.map +1 -1
  47. package/core/core/kos-container-model.d.ts +11 -32
  48. package/core/core/kos-container-model.d.ts.map +1 -1
  49. package/core/core/kos-data-container.d.ts +6 -6
  50. package/core/core/kos-data-container.d.ts.map +1 -1
  51. package/core/core/kosCore.d.ts +7 -4
  52. package/core/core/kosCore.d.ts.map +1 -1
  53. package/core/core/kosModel.d.ts +16 -8
  54. package/core/core/kosModel.d.ts.map +1 -1
  55. package/core/core/kosModelManager.d.ts +2 -3
  56. package/core/core/kosModelManager.d.ts.map +1 -1
  57. package/core/core/lifecycle/constants.d.ts +6 -2
  58. package/core/core/lifecycle/constants.d.ts.map +1 -1
  59. package/core/core/lifecycle/kosCoreLifecycle.d.ts +11 -1
  60. package/core/core/lifecycle/kosCoreLifecycle.d.ts.map +1 -1
  61. package/core/core/lifecycle/kosModelLifecycle.d.ts +6 -0
  62. package/core/core/lifecycle/kosModelLifecycle.d.ts.map +1 -1
  63. package/core/core/lifecycle/model-machine.d.ts +6 -0
  64. package/core/core/lifecycle/model-machine.d.ts.map +1 -1
  65. package/core/core/model/kos-fsm-manager.d.ts +6 -0
  66. package/core/core/model/kos-fsm-manager.d.ts.map +1 -1
  67. package/core/core/model/kos-offline-queue.d.ts +1 -1
  68. package/core/core/model/service-response-store.d.ts +2 -15
  69. package/core/core/model/service-response-store.d.ts.map +1 -1
  70. package/core/core/reconnect/reconnect-fixture.d.ts +17 -0
  71. package/core/core/reconnect/reconnect-fixture.d.ts.map +1 -0
  72. package/core/core/services/app-startup-service.d.ts +5 -13
  73. package/core/core/services/app-startup-service.d.ts.map +1 -1
  74. package/core/core/services/intent-service.d.ts +3 -12
  75. package/core/core/services/intent-service.d.ts.map +1 -1
  76. package/core/core/transport/mock/mock-frames.d.ts +3 -3
  77. package/core/core/transport/transport.d.ts +1 -1
  78. package/core/core/transport/transport.d.ts.map +1 -1
  79. package/core/core/transport/webSocketTransport.d.ts +10 -0
  80. package/core/core/transport/webSocketTransport.d.ts.map +1 -1
  81. package/core/types/model.d.ts +4 -8
  82. package/core/types/model.d.ts.map +1 -1
  83. package/core/types/service-response-store.d.ts +3 -11
  84. package/core/types/service-response-store.d.ts.map +1 -1
  85. package/core/types/utils/kos-fetch.d.ts +25 -37
  86. package/core/types/utils/kos-fetch.d.ts.map +1 -1
  87. package/core/util/abortable-when.d.ts +5 -6
  88. package/core/util/abortable-when.d.ts.map +1 -1
  89. package/core/util/ancestor-path-visitor.d.ts +14 -20
  90. package/core/util/ancestor-path-visitor.d.ts.map +1 -1
  91. package/core/util/container-utils.d.ts +26 -159
  92. package/core/util/container-utils.d.ts.map +1 -1
  93. package/core/util/date-utils.d.ts +9 -58
  94. package/core/util/date-utils.d.ts.map +1 -1
  95. package/core/util/debounce.d.ts +1 -8
  96. package/core/util/debounce.d.ts.map +1 -1
  97. package/core/util/kos-fetch.d.ts +1 -1
  98. package/core/util/kos-fetch.d.ts.map +1 -1
  99. package/core/util/kos-model-utils.d.ts +10 -11
  100. package/core/util/kos-model-utils.d.ts.map +1 -1
  101. package/core/util/model-attribute-utils.d.ts +5 -22
  102. package/core/util/model-attribute-utils.d.ts.map +1 -1
  103. package/core/util/promise-utils.d.ts +1 -26
  104. package/core/util/promise-utils.d.ts.map +1 -1
  105. package/core/util/service-factory.d.ts +5 -23
  106. package/core/util/service-factory.d.ts.map +1 -1
  107. package/core/util/service-request-error.d.ts +3 -5
  108. package/core/util/service-request-error.d.ts.map +1 -1
  109. package/core/util/service-response.d.ts +12 -67
  110. package/core/util/service-response.d.ts.map +1 -1
  111. package/core/util/transport-not-ready-error.d.ts +11 -13
  112. package/core/util/transport-not-ready-error.d.ts.map +1 -1
  113. package/core/util/when-ready.d.ts +1 -8
  114. package/core/util/when-ready.d.ts.map +1 -1
  115. package/index.cjs +144 -109
  116. package/index.cjs.map +1 -1
  117. package/index.js +173 -138
  118. package/index.js.map +1 -1
  119. package/models/decorators/future-service.d.ts +7 -7
  120. package/models/models/browser-router/browser-router-model.d.ts +10 -39
  121. package/models/models/browser-router/browser-router-model.d.ts.map +1 -1
  122. package/models/models/browser-router/browser-router-registration.d.ts +5 -77
  123. package/models/models/browser-router/browser-router-registration.d.ts.map +1 -1
  124. package/models/models/browser-router/types/index.d.ts +2 -16
  125. package/models/models/canvas-dispatcher/canvas-dispatcher-registration.d.ts +5 -77
  126. package/models/models/canvas-dispatcher/canvas-dispatcher-registration.d.ts.map +1 -1
  127. package/models/models/canvas-renderer/canvas-renderer-registration.d.ts +5 -75
  128. package/models/models/canvas-renderer/canvas-renderer-registration.d.ts.map +1 -1
  129. package/models/models/config-bean/config-bean-model-builder.d.ts +4 -11
  130. package/models/models/config-bean/config-bean-model-builder.d.ts.map +1 -1
  131. package/models/models/config-bean/config-bean-model.d.ts +23 -66
  132. package/models/models/config-bean/config-bean-model.d.ts.map +1 -1
  133. package/models/models/config-bean-prop/config-bean-prop-model.d.ts +15 -62
  134. package/models/models/config-bean-prop/config-bean-prop-model.d.ts.map +1 -1
  135. package/models/models/config-bean-prop/types/index.d.ts +34 -215
  136. package/models/models/device/device-model.d.ts +20 -199
  137. package/models/models/device/device-model.d.ts.map +1 -1
  138. package/models/models/device/device-registration.d.ts +7 -87
  139. package/models/models/device/device-registration.d.ts.map +1 -1
  140. package/models/models/device/types/index.d.ts +5 -34
  141. package/models/models/future/future-aware.d.ts +7 -71
  142. package/models/models/future/future-aware.d.ts.map +1 -1
  143. package/models/models/future/future-model-builder.d.ts +2 -2
  144. package/models/models/future/future-model.d.ts +3 -23
  145. package/models/models/future/future-model.d.ts.map +1 -1
  146. package/models/models/future/future-types.d.ts +28 -145
  147. package/models/models/future/future-types.d.ts.map +1 -1
  148. package/models/models/gpio-chip/gpio-chip-builders.d.ts +14 -0
  149. package/models/models/gpio-chip/gpio-chip-builders.d.ts.map +1 -0
  150. package/models/models/gpio-chip/gpio-chip-container-model.d.ts +2 -1
  151. package/models/models/gpio-chip/gpio-chip-container-model.d.ts.map +1 -1
  152. package/models/models/key-value/key-value-model.d.ts +12 -72
  153. package/models/models/key-value/key-value-model.d.ts.map +1 -1
  154. package/models/models/key-value/key-value-registration.d.ts +5 -77
  155. package/models/models/key-value/key-value-registration.d.ts.map +1 -1
  156. package/models/models/key-value/services/key-value-services.d.ts +13 -72
  157. package/models/models/key-value/services/key-value-services.d.ts.map +1 -1
  158. package/models/models/key-value/types/index.d.ts +3 -46
  159. package/models/models/kos-expression-evaluator/kos-expression-evaluator-model.d.ts +32 -99
  160. package/models/models/kos-expression-evaluator/kos-expression-evaluator-model.d.ts.map +1 -1
  161. package/models/models/kos-expression-evaluator/services/kos-expression-evaluator-services.d.ts +2 -12
  162. package/models/models/kos-expression-evaluator/services/kos-expression-evaluator-services.d.ts.map +1 -1
  163. package/models/models/kos-log-manager/kos-log-manager-model.d.ts +7 -46
  164. package/models/models/kos-log-manager/kos-log-manager-model.d.ts.map +1 -1
  165. package/models/models/kos-log-manager/kos-log-manager-registration.d.ts +5 -80
  166. package/models/models/kos-log-manager/kos-log-manager-registration.d.ts.map +1 -1
  167. package/models/models/kos-log-manager/types/index.d.ts +13 -156
  168. package/models/models/kos-time/kos-time-model.d.ts +8 -39
  169. package/models/models/kos-time/kos-time-model.d.ts.map +1 -1
  170. package/models/models/kos-time/kos-time-registration.d.ts +6 -73
  171. package/models/models/kos-time/kos-time-registration.d.ts.map +1 -1
  172. package/models/models/kos-time/types/index.d.ts +3 -58
  173. package/models/models/log-block/log-block-container-model.d.ts +2 -118
  174. package/models/models/log-block/log-block-container-model.d.ts.map +1 -1
  175. package/models/models/log-block/log-block-container-registration.d.ts +5 -75
  176. package/models/models/log-block/log-block-container-registration.d.ts.map +1 -1
  177. package/models/models/log-block/log-block-model.d.ts +5 -168
  178. package/models/models/log-block/log-block-model.d.ts.map +1 -1
  179. package/models/models/log-block/log-block-registration.d.ts +5 -75
  180. package/models/models/log-block/log-block-registration.d.ts.map +1 -1
  181. package/models/models/log-block/types/index.d.ts +14 -81
  182. package/models/models/log-stream/log-stream-container-model.d.ts +8 -35
  183. package/models/models/log-stream/log-stream-container-model.d.ts.map +1 -1
  184. package/models/models/log-stream/log-stream-container-registration.d.ts +5 -75
  185. package/models/models/log-stream/log-stream-container-registration.d.ts.map +1 -1
  186. package/models/models/log-stream/log-stream-model.d.ts +8 -29
  187. package/models/models/log-stream/log-stream-model.d.ts.map +1 -1
  188. package/models/models/log-stream/log-stream-registration.d.ts +5 -75
  189. package/models/models/log-stream/log-stream-registration.d.ts.map +1 -1
  190. package/models/models/log-stream/types/index.d.ts +5 -60
  191. package/models/models/network-interface/network-interface-container-model.d.ts +6 -35
  192. package/models/models/network-interface/network-interface-container-model.d.ts.map +1 -1
  193. package/models/models/network-interface/network-interface-container-registration.d.ts +5 -73
  194. package/models/models/network-interface/network-interface-container-registration.d.ts.map +1 -1
  195. package/models/models/network-interface/network-interface-model.d.ts +5 -43
  196. package/models/models/network-interface/network-interface-model.d.ts.map +1 -1
  197. package/models/models/network-interface/network-interface-registration.d.ts +5 -73
  198. package/models/models/network-interface/network-interface-registration.d.ts.map +1 -1
  199. package/models/models/network-interface/types/index.d.ts +2 -16
  200. package/models/models/ota/ota-model.d.ts +11 -39
  201. package/models/models/ota/ota-model.d.ts.map +1 -1
  202. package/models/models/ota/ota-registration.d.ts +5 -77
  203. package/models/models/ota/ota-registration.d.ts.map +1 -1
  204. package/models/models/ota/types/index.d.ts +2 -141
  205. package/models/models/region-info/types/index.d.ts +19 -99
  206. package/models/models/region-info/types/index.d.ts.map +1 -1
  207. package/models/models/software-info/services/software-info-services.d.ts +2 -14
  208. package/models/models/software-info/services/software-info-services.d.ts.map +1 -1
  209. package/models/models/software-info/software-info-model.d.ts +3 -39
  210. package/models/models/software-info/software-info-model.d.ts.map +1 -1
  211. package/models/models/software-info/software-info-registration.d.ts +6 -73
  212. package/models/models/software-info/software-info-registration.d.ts.map +1 -1
  213. package/models/models/software-info/types/index.d.ts +6 -20
  214. package/models/models/state-bean/state-bean-model.d.ts +10 -41
  215. package/models/models/state-bean/state-bean-model.d.ts.map +1 -1
  216. package/models/models/state-bean/state-bean-registration.d.ts +6 -73
  217. package/models/models/state-bean/state-bean-registration.d.ts.map +1 -1
  218. package/models/models/state-bean/types/index.d.ts +4 -84
  219. package/models/models/state-prop/state-prop-model.d.ts +6 -40
  220. package/models/models/state-prop/state-prop-model.d.ts.map +1 -1
  221. package/models/models/state-prop/state-prop-registration.d.ts +6 -73
  222. package/models/models/state-prop/state-prop-registration.d.ts.map +1 -1
  223. package/models/models/state-prop/types/index.d.ts +5 -37
  224. package/models/models/storage-device/storage-device-container-model.d.ts +7 -273
  225. package/models/models/storage-device/storage-device-container-model.d.ts.map +1 -1
  226. package/models/models/storage-device/storage-device-container-registration.d.ts +5 -75
  227. package/models/models/storage-device/storage-device-container-registration.d.ts.map +1 -1
  228. package/models/models/storage-device/storage-device-model.d.ts +3 -49
  229. package/models/models/storage-device/storage-device-model.d.ts.map +1 -1
  230. package/models/models/storage-device/storage-device-registration.d.ts +5 -75
  231. package/models/models/storage-device/storage-device-registration.d.ts.map +1 -1
  232. package/models/models/storage-device/types/index.d.ts +13 -82
  233. package/models/models/studio-properties/studio-properties-model.d.ts +13 -36
  234. package/models/models/studio-properties/studio-properties-model.d.ts.map +1 -1
  235. package/models/models/studio-properties/studio-properties-registration.d.ts +5 -75
  236. package/models/models/studio-properties/studio-properties-registration.d.ts.map +1 -1
  237. package/models/models/studio-properties/types/index.d.ts +2 -24
  238. package/models/models/translation/descriptor-merge.d.ts +13 -17
  239. package/models/models/translation/descriptor-merge.d.ts.map +1 -1
  240. package/models/models/translation/services/translation-services.d.ts +19 -77
  241. package/models/models/translation/services/translation-services.d.ts.map +1 -1
  242. package/models/models/translation/test-harness.d.ts +6 -8
  243. package/models/models/translation/test-harness.d.ts.map +1 -1
  244. package/models/models/translation/translation-container-model.d.ts +7 -59
  245. package/models/models/translation/translation-container-model.d.ts.map +1 -1
  246. package/models/models/translation/translation-container-registration.d.ts +6 -73
  247. package/models/models/translation/translation-container-registration.d.ts.map +1 -1
  248. package/models/models/translation/translation-model.d.ts +17 -50
  249. package/models/models/translation/translation-model.d.ts.map +1 -1
  250. package/models/models/translation/translation-registration.d.ts +6 -73
  251. package/models/models/translation/translation-registration.d.ts.map +1 -1
  252. package/models/models/translation/types/index.d.ts +51 -276
  253. package/models/models/trouble/trouble-registration.d.ts +6 -73
  254. package/models/models/trouble/trouble-registration.d.ts.map +1 -1
  255. package/models/models/trouble/types/index.d.ts +17 -188
  256. package/models/models/trouble/utils/is-trouble-aware.d.ts +4 -85
  257. package/models/models/trouble/utils/is-trouble-aware.d.ts.map +1 -1
  258. package/models/models/trouble-container/trouble-builders.d.ts +11 -0
  259. package/models/models/trouble-container/trouble-builders.d.ts.map +1 -0
  260. package/models/models/trouble-container/trouble-container-model.d.ts +2 -1
  261. package/models/models/trouble-container/trouble-container-model.d.ts.map +1 -1
  262. package/models/models/usb-update/usb-update-container-registration.d.ts +5 -75
  263. package/models/models/usb-update/usb-update-container-registration.d.ts.map +1 -1
  264. package/models/models/usb-update/usb-update-registration.d.ts +5 -75
  265. package/models/models/usb-update/usb-update-registration.d.ts.map +1 -1
  266. package/models/types/cancellable-promise.d.ts +6 -9
  267. package/models/types/cancellable-promise.d.ts.map +1 -1
  268. package/models/utils/await-future-call.d.ts +9 -21
  269. package/models/utils/await-future-call.d.ts.map +1 -1
  270. package/models/utils/cancellable-future-call.d.ts +8 -19
  271. package/models/utils/cancellable-future-call.d.ts.map +1 -1
  272. package/models/utils/cancellable-service.d.ts +14 -23
  273. package/models/utils/cancellable-service.d.ts.map +1 -1
  274. package/models/utils/conversion-utils.d.ts +8 -48
  275. package/models/utils/conversion-utils.d.ts.map +1 -1
  276. package/models/utils/persistence-store.d.ts +1 -1
  277. package/models/utils/service.d.ts +14 -48
  278. package/models/utils/service.d.ts.map +1 -1
  279. package/models/utils/services/kos/daily/service.d.ts +4 -4
  280. package/models/utils/services/vfs/daily/service.d.ts +4 -4
  281. package/models/utils/timer-manager.d.ts.map +1 -1
  282. package/package.json +3 -3
  283. package/{software-info-registration-CKlTQPet.js → software-info-registration-C8kf-pBB.js} +551 -530
  284. package/software-info-registration-C8kf-pBB.js.map +1 -0
  285. package/{software-info-registration-GUbTY4KD.cjs → software-info-registration-Y1iADHWT.cjs} +522 -501
  286. package/software-info-registration-Y1iADHWT.cjs.map +1 -0
  287. package/testing/index.d.ts +28 -33
  288. package/testing/index.d.ts.map +1 -1
  289. package/testing.cjs +1 -1
  290. package/testing.cjs.map +1 -1
  291. package/testing.js +1 -1
  292. package/testing.js.map +1 -1
  293. package/ui/components/connection-dev-button/connection-dev-button-styles.d.ts +9 -0
  294. package/ui/components/connection-dev-button/connection-dev-button-styles.d.ts.map +1 -0
  295. package/ui/components/connection-dev-button/index.d.ts +36 -0
  296. package/ui/components/connection-dev-button/index.d.ts.map +1 -0
  297. package/ui/components/connection-dev-button/use-connection-dev-state.d.ts +29 -0
  298. package/ui/components/connection-dev-button/use-connection-dev-state.d.ts.map +1 -0
  299. package/ui/components/index.d.ts +1 -0
  300. package/ui/components/index.d.ts.map +1 -1
  301. package/ui/features/canvas/hooks/use-image-renderer.d.ts +5 -4
  302. package/ui/features/canvas/hooks/use-image-renderer.d.ts.map +1 -1
  303. package/ui/hooks/use-function-warmup.d.ts +4 -14
  304. package/ui/hooks/use-function-warmup.d.ts.map +1 -1
  305. package/ui/hooks/use-kos-date-formats.d.ts +15 -29
  306. package/ui/hooks/use-kos-date-formats.d.ts.map +1 -1
  307. package/ui/hooks/use-kos-region-timezones.d.ts +4 -55
  308. package/ui/hooks/use-kos-region-timezones.d.ts.map +1 -1
  309. package/ui/hooks/use-kos-regions.d.ts +11 -23
  310. package/ui/hooks/use-kos-regions.d.ts.map +1 -1
  311. package/ui/hooks/use-kos-time-formats.d.ts +16 -31
  312. package/ui/hooks/use-kos-time-formats.d.ts.map +1 -1
  313. package/ui/hooks/use-kos-unit-systems.d.ts +13 -27
  314. package/ui/hooks/use-kos-unit-systems.d.ts.map +1 -1
  315. package/ui/hooks/view-model/use-view-model.d.ts +6 -31
  316. package/ui/hooks/view-model/use-view-model.d.ts.map +1 -1
  317. package/ui/policies/reload-on-disconnect-policy.d.ts +5 -6
  318. package/ui/policies/reload-on-disconnect-policy.d.ts.map +1 -1
  319. package/software-info-registration-CKlTQPet.js.map +0 -1
  320. package/software-info-registration-GUbTY4KD.cjs.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"software-info-registration-GUbTY4KD.cjs","sources":["../../../packages/kos-ui-sdk/src/common/constants/index.ts","../../../packages/kos-ui-sdk/src/common/events/eventBus.ts","../../../packages/kos-ui-sdk/src/common/events/eventBus.state.ts","../../../packages/kos-ui-sdk/src/core/util/get-query-params.ts","../../../packages/kos-ui-sdk/src/core/util/kos-config-init.ts","../../../packages/kos-ui-sdk/src/core/util/log-utils.ts","../../../packages/kos-ui-sdk/src/core/core/log/log.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/propKeys.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/fsm-injection-utils.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kos-child.ts","../../../packages/kos-ui-sdk/src/core/util/model-attribute-utils.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kos-parent.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kos-container-aware.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kos-execution-context.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kos-future-aware.ts","../../../packages/kos-ui-sdk/src/core/types/kos-dependency.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kos-http-decorators.ts","../../../packages/kos-ui-sdk/src/core/core/model/kos-logger-factory.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kos-logger-aware.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kos-model-effect.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kos-reload-aware.ts","../../../packages/kos-ui-sdk/src/core/util/service-request-error.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/resolve-parameters.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kos-service-request-helpers.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kos-service-request.ts","../../../packages/kos-ui-sdk/src/core/types/service-response-store.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kos-state-machine.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kosDependency.ts","../../../packages/kos-ui-sdk/src/models/models/future/future-aware.ts","../../../packages/kos-ui-sdk/src/models/models/trouble/utils/trouble-reducer.ts","../../../packages/kos-ui-sdk/src/core/util/observable-proxy-map.ts","../../../packages/kos-ui-sdk/src/core/core/extension/extension-manager.ts","../../../packages/kos-ui-sdk/src/core/core/indexing/topics.ts","../../../packages/kos-ui-sdk/src/core/core/indexing/types.ts","../../../packages/kos-ui-sdk/src/core/core/kos-container-index.ts","../../../packages/kos-ui-sdk/src/core/core/kos-container-model.ts","../../../packages/kos-ui-sdk/src/core/core/lifecycle/constants.ts","../../../packages/kos-ui-sdk/src/core/util/when-ready.ts","../../../packages/kos-ui-sdk/src/core/util/kos-model-utils.ts","../../../packages/kos-ui-sdk/src/core/core/kos-model-factory.ts","../../../packages/kos-ui-sdk/src/core/core/registration/registration-manager.ts","../../../packages/kos-ui-sdk/src/core/core/registration/model-registration.ts","../../../packages/kos-ui-sdk/src/core/core/registration/base-kos-model-registration.ts","../../../packages/kos-ui-sdk/src/core/core/registration/singleton-kos-model-registration-factory.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kosModel.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kosTopicHandler.ts","../../../packages/kos-ui-sdk/src/core/util/model-type-guards.ts","../../../packages/kos-ui-sdk/src/core/core/kos-deletion-manager.ts","../../../packages/kos-ui-sdk/src/core/core/dependency-manager.ts","../../../packages/kos-ui-sdk/src/core/core/model-cache.ts","../../../packages/kos-ui-sdk/src/core/core/model/model-hook-cache.ts","../../../packages/kos-ui-sdk/src/core/util/model-error-utils.ts","../../../packages/kos-ui-sdk/src/core/util/error-logger.ts","../../../packages/kos-ui-sdk/src/core/core/types/registration.ts","../../../packages/kos-ui-sdk/src/core/core/companion-instantiator.ts","../../../packages/kos-ui-sdk/src/models/utils/model-event-utils.ts","../../../packages/kos-ui-sdk/src/core/util/await-first-matching-when.ts","../../../packages/kos-ui-sdk/src/core/constants/model-constants.ts","../../../packages/kos-ui-sdk/src/core/util/model-transition-utils.ts","../../../packages/kos-ui-sdk/src/core/util/promise-utils.ts","../../../packages/kos-ui-sdk/src/core/util/model-utils.ts","../../../packages/kos-ui-sdk/src/core/core/model/apply-kos-dev-tool-support.ts","../../../packages/kos-ui-sdk/src/core/core/model/kos-child-resolver.ts","../../../packages/kos-ui-sdk/src/core/core/model/kos-companion-model-manager.ts","../../../packages/kos-ui-sdk/src/core/core/model/kos-effects-manager.ts","../../../packages/kos-ui-sdk/src/core/core/lifecycle/model-active-machine.ts","../../../packages/kos-ui-sdk/src/core/core/lifecycle/model-online-machine.ts","../../../packages/kos-ui-sdk/src/core/core/lifecycle/model-machine.ts","../../../packages/kos-ui-sdk/src/core/core/lifecycle/kosModelLifecycle.ts","../../../packages/kos-ui-sdk/src/core/core/model/kos-fsm-manager.ts","../../../packages/kos-ui-sdk/src/core/core/model/kos-http-route-manager.ts","../../../packages/kos-ui-sdk/src/core/core/model/kos-offline-queue.ts","../../../packages/kos-ui-sdk/src/core/core/model/kos-online-lifecycle-manager.ts","../../../packages/kos-ui-sdk/src/core/util/api-request-id.ts","../../../packages/kos-ui-sdk/src/core/util/binary-utils.ts","../../../packages/kos-ui-sdk/src/core/util/kos-message-utils.ts","../../../packages/kos-ui-sdk/src/core/util/transport-not-ready-error.ts","../../../packages/kos-ui-sdk/src/core/util/kos-fetch.ts","../../../packages/kos-ui-sdk/src/core/util/kos-service-request.ts","../../../packages/kos-ui-sdk/src/models/utils/service.ts","../../../packages/kos-ui-sdk/src/core/core/model/kos-service-request-manager.ts","../../../packages/kos-ui-sdk/src/common/events/async-event-bus.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kos-topic-handler-flow-control.ts","../../../packages/kos-ui-sdk/src/core/util/abortable-when.ts","../../../packages/kos-ui-sdk/src/core/core/transport/mock/mock-frames.ts","../../../packages/kos-ui-sdk/src/core/core/transport/mock/future-simulator.ts","../../../packages/kos-ui-sdk/src/core/core/transport/mock/mock-fixtures.ts","../../../packages/kos-ui-sdk/src/core/core/transport/mock/route-matcher.ts","../../../packages/kos-ui-sdk/src/core/core/transport/mock/mock-playback.ts","../../../packages/kos-ui-sdk/src/core/core/transport/mock/mock-recorder.ts","../../../packages/kos-ui-sdk/src/core/core/transport/mock/mock-setups.ts","../../../packages/kos-ui-sdk/src/core/core/transport/mock/mock-config.ts","../../../packages/kos-ui-sdk/src/core/core/transport/mock/mock-registry.ts","../../../packages/kos-ui-sdk/src/core/core/transport/mock/mock-interceptor.ts","../../../packages/kos-ui-sdk/src/core/core/transport/web-socket-transport-adapter.ts","../../../packages/kos-ui-sdk/src/core/core/transport/base-message-transport.ts","../../../packages/kos-ui-sdk/src/core/core/transport/bridge-transport.ts","../../../packages/kos-ui-sdk/src/core/core/transport/bridge-message-transport.ts","../../../packages/kos-ui-sdk/src/core/core/transport/fos-message-transport.ts","../../../packages/kos-ui-sdk/src/core/core/transport/kos-message-transport.ts","../../../packages/kos-ui-sdk/src/core/core/transport/mock/standalone-mock-socket.ts","../../../packages/kos-ui-sdk/src/core/core/transport/transport-factory.ts","../../../packages/kos-ui-sdk/src/core/core/transport/webSocketTransport.ts","../../../packages/kos-ui-sdk/src/core/core/model/kos-subscription-manager.ts","../../../packages/kos-ui-sdk/src/core/core/model/logger-utils.ts","../../../packages/kos-ui-sdk/src/core/core/model/model-introspection-utils.ts","../../../packages/kos-ui-sdk/src/core/core/model/service-response-store.ts","../../../packages/kos-ui-sdk/src/core/core/model/kos-model-component-factory.ts","../../../packages/kos-ui-sdk/src/core/core/kosModel.ts","../../../packages/kos-ui-sdk/src/core/core/model-instantiator.ts","../../../packages/kos-ui-sdk/src/core/core/model-registry.ts","../../../packages/kos-ui-sdk/src/core/core/kosModelManager.ts","../../../packages/kos-ui-sdk/src/core/core/lifecycle/kosCoreLifecycle.ts","../../../packages/kos-ui-sdk/src/core/core/kosCore.ts","../../../packages/kos-ui-sdk/src/core/util/kos-model-visitor.ts","../../../packages/kos-ui-sdk/src/core/util/feature-flags.ts","../../../packages/kos-ui-sdk/src/core/util/kos-data-mapper-utils.ts","../../../packages/kos-ui-sdk/src/core/util/model-factory.ts","../../../packages/kos-ui-sdk/src/core/util/pipe.ts","../../../packages/kos-ui-sdk/src/core/util/service-factory.ts","../../../packages/kos-ui-sdk/src/core/util/session-utils.ts","../../../packages/kos-ui-sdk/src/core/core/context/kos-context-manager.ts","../../../packages/kos-ui-sdk/src/core/core/kos-data-container.ts","../../../packages/kos-ui-sdk/src/core/core/services/browser-router.ts","../../../packages/kos-ui-sdk/src/core/core/services/intent-service.ts","../../../packages/kos-ui-sdk/src/core/core/services/app-startup-service.ts","../../../packages/kos-ui-sdk/src/core/index.ts","../../../packages/kos-ui-sdk/src/models/constants/index.ts","../../../packages/kos-ui-sdk/src/models/services/config-bean/index.ts","../../../packages/kos-ui-sdk/src/models/utils/prop-utils.ts","../../../packages/kos-ui-sdk/src/models/models/config-bean/config-bean-model-builder.ts","../../../packages/kos-ui-sdk/src/models/models/config-bean/config-bean-model.ts","../../../packages/kos-ui-sdk/src/models/models/region-info/services/region-info-services.ts","../../../packages/kos-ui-sdk/src/models/models/region-info/types/index.ts","../../../packages/kos-ui-sdk/src/models/models/region-info/utils/unit-system-utils.ts","../../../packages/kos-ui-sdk/src/models/models/region-info/region-info-model.ts","../../../packages/kos-ui-sdk/src/models/utils/conversion-utils.ts","../../../packages/kos-ui-sdk/src/models/models/config-bean-prop/config-options-factory.ts","../../../packages/kos-ui-sdk/src/models/models/config-bean-prop/config-bean-prop-model.ts","../../../packages/kos-ui-sdk/src/models/models/future/future-model-builder.ts","../../../packages/kos-ui-sdk/src/models/services/future/index.ts","../../../packages/kos-ui-sdk/src/models/models/future/future-factory.ts","../../../packages/kos-ui-sdk/src/models/models/future-container/future-container-factory.ts","../../../packages/kos-ui-sdk/src/models/utils/future-manager/index.ts","../../../packages/kos-ui-sdk/src/models/decorators/future-service.ts","../../../packages/kos-ui-sdk/src/models/models/state-bean/services/state-bean-services.ts","../../../packages/kos-ui-sdk/src/models/models/state-bean/state-bean-model.ts","../../../packages/kos-ui-sdk/src/models/models/state-bean/state-bean-registration.ts","../../../packages/kos-ui-sdk/src/models/models/state-prop/state-prop-model.ts","../../../packages/kos-ui-sdk/src/models/models/state-prop/state-prop-registration.ts","../../../packages/kos-ui-sdk/src/models/models/state-prop/services/state-prop-services.ts","../../../packages/kos-ui-sdk/src/models/models/browser-router/browser-router-model.ts","../../../packages/kos-ui-sdk/src/models/models/browser-router/browser-router-registration.ts","../../../packages/kos-ui-sdk/src/models/models/future/future-model.ts","../../../packages/kos-ui-sdk/src/models/models/future-container/future-container-model.ts","../../../packages/kos-ui-sdk/src/models/models/key-value/services/key-value-services.ts","../../../packages/kos-ui-sdk/src/models/models/key-value/key-value-model.ts","../../../packages/kos-ui-sdk/src/models/models/key-value/key-value-registration.ts","../../../node_modules/expr-eval/dist/index.mjs","../../../packages/kos-ui-sdk/src/models/models/kos-expression-evaluator/kos-expression-evaluator-model.ts","../../../packages/kos-ui-sdk/src/models/models/kos-expression-evaluator/index.ts","../../../packages/kos-ui-sdk/src/models/models/kos-log-manager/services/kos-log-manager-services.ts","../../../packages/kos-ui-sdk/src/models/models/kos-log-manager/kos-log-manager-model.ts","../../../packages/kos-ui-sdk/src/models/models/kos-log-manager/kos-log-manager-registration.ts","../../../packages/kos-ui-sdk/src/models/models/kos-time/services/kos-time-services.ts","../../../packages/kos-ui-sdk/src/models/models/kos-time/kos-time-model.ts","../../../packages/kos-ui-sdk/src/models/models/kos-time/kos-time-registration.ts","../../../packages/kos-ui-sdk/src/models/models/log-block/log-block-container-model.ts","../../../packages/kos-ui-sdk/src/models/utils/get-kos-connection-id.ts","../../../packages/kos-ui-sdk/src/models/models/log-stream/services/log-stream-services.ts","../../../packages/kos-ui-sdk/src/models/models/log-block/log-block-model.ts","../../../packages/kos-ui-sdk/src/models/models/log-block/log-block-registration.ts","../../../packages/kos-ui-sdk/src/models/models/log-block/log-block-container-registration.ts","../../../packages/kos-ui-sdk/src/models/models/log-stream/log-stream-model.ts","../../../packages/kos-ui-sdk/src/models/models/log-stream/log-stream-registration.ts","../../../packages/kos-ui-sdk/src/models/models/log-stream/log-stream-container-model.ts","../../../packages/kos-ui-sdk/src/models/models/log-stream/log-stream-container-registration.ts","../../../packages/kos-ui-sdk/src/models/utils/trouble-utils.ts","../../../packages/kos-ui-sdk/src/models/models/trouble/services/trouble-services.ts","../../../packages/kos-ui-sdk/src/models/models/trouble/utils/trouble-data-extension.ts","../../../packages/kos-ui-sdk/src/models/models/trouble/utils/trouble-extension.ts","../../../packages/kos-ui-sdk/src/models/models/trouble-container/trouble-utils.ts","../../../packages/kos-ui-sdk/src/models/models/trouble/handlers/resolvable-trouble-handler.ts","../../../packages/kos-ui-sdk/src/models/models/trouble/trouble-model.ts","../../../packages/kos-ui-sdk/src/models/models/trouble/trouble-registration.ts","../../../packages/kos-ui-sdk/src/models/models/trouble-container/trouble-container-model.ts","../../../packages/kos-ui-sdk/src/models/models/trouble-container/index.ts","../../../packages/kos-ui-sdk/src/models/models/ota/services/ota-services.ts","../../../packages/kos-ui-sdk/src/models/models/ota/ota-model.ts","../../../packages/kos-ui-sdk/src/models/models/ota/ota-registration.ts","../../../packages/kos-ui-sdk/src/models/utils/await-future-call.ts","../../../packages/kos-ui-sdk/src/models/utils/cancellable-service.ts","../../../packages/kos-ui-sdk/src/models/utils/client.ts","../../../packages/kos-ui-sdk/src/models/models/canvas-dispatcher/services/canvas-dispatcher-services.ts","../../../packages/kos-ui-sdk/src/models/models/canvas-dispatcher/utils/encode-frame.tsx","../../../packages/kos-ui-sdk/src/models/models/canvas-renderer/canvas-renderer-model.ts","../../../packages/kos-ui-sdk/src/models/models/canvas-renderer/canvas-renderer-registration.ts","../../../packages/kos-ui-sdk/src/models/models/canvas-dispatcher/utils/renderers/base/video-base-renderer.ts","../../../packages/kos-ui-sdk/src/models/models/canvas-dispatcher/utils/renderers/base/webgl-base-renderer.ts","../../../packages/kos-ui-sdk/src/models/models/canvas-dispatcher/utils/renderers/drop-renderer.ts","../../../packages/kos-ui-sdk/src/models/models/canvas-dispatcher/utils/renderers/base/canvas-2d-renderer.ts","../../../packages/kos-ui-sdk/src/models/models/canvas-dispatcher/utils/renderers/mixins/one-shot-renderer-mixin.ts","../../../packages/kos-ui-sdk/src/models/models/canvas-dispatcher/utils/renderers/gradient-renderer.ts","../../../packages/kos-ui-sdk/src/models/models/canvas-dispatcher/utils/renderers/image-renderer.ts","../../../packages/kos-ui-sdk/src/models/models/canvas-dispatcher/utils/renderers/looping-video-renderer.ts","../../../packages/kos-ui-sdk/src/models/models/canvas-dispatcher/utils/color-utils.ts","../../../packages/kos-ui-sdk/src/models/models/canvas-dispatcher/utils/renderers/matrix-renderer.ts","../../../packages/kos-ui-sdk/src/models/models/canvas-dispatcher/utils/renderers/overlay-renderer.ts","../../../packages/kos-ui-sdk/src/models/models/canvas-dispatcher/utils/renderers/scrolling-image-renderer.ts","../../../packages/kos-ui-sdk/src/models/models/canvas-dispatcher/utils/renderers/scrolling-text-renderer.ts","../../../packages/kos-ui-sdk/src/models/models/canvas-dispatcher/utils/renderers/sequence-renderer.ts","../../../packages/kos-ui-sdk/src/models/models/canvas-dispatcher/utils/renderers/solid-color-renderer.ts","../../../packages/kos-ui-sdk/src/models/models/canvas-dispatcher/utils/renderers/sweep-renderer.ts","../../../packages/kos-ui-sdk/src/models/models/canvas-dispatcher/utils/renderers/renderer-factory.ts","../../../packages/kos-ui-sdk/src/models/models/canvas-dispatcher/canvas-dispatcher-model.ts","../../../packages/kos-ui-sdk/src/models/models/canvas-dispatcher/canvas-dispatcher-registration.ts","../../../packages/kos-ui-sdk/src/models/models/device/services/device-services.ts","../../../packages/kos-ui-sdk/src/models/models/device/device-model.ts","../../../packages/kos-ui-sdk/src/models/models/device/device-registration.ts","../../../packages/kos-ui-sdk/src/models/models/network-interface/network-interface-model.ts","../../../packages/kos-ui-sdk/src/models/models/network-interface/network-interface-registration.ts","../../../packages/kos-ui-sdk/src/models/models/network-interface/services/network-interface-services.ts","../../../packages/kos-ui-sdk/src/models/models/network-interface/network-interface-container-model.ts","../../../packages/kos-ui-sdk/src/models/models/network-interface/network-interface-container-registration.ts","../../../packages/kos-ui-sdk/src/models/models/storage-device/services/storage-device-services.ts","../../../packages/kos-ui-sdk/src/models/models/storage-device/storage-device-model.ts","../../../packages/kos-ui-sdk/src/models/models/storage-device/storage-device-registration.ts","../../../packages/kos-ui-sdk/src/models/models/storage-device/storage-device-container-model.ts","../../../packages/kos-ui-sdk/src/models/models/storage-device/storage-device-container-registration.ts","../../../packages/kos-ui-sdk/src/models/models/usb-update/services/usb-update-services.ts","../../../packages/kos-ui-sdk/src/models/models/usb-update/usb-update-model.ts","../../../packages/kos-ui-sdk/src/models/models/usb-update/usb-update-registration.ts","../../../packages/kos-ui-sdk/src/models/models/usb-update/usb-update-container-model.ts","../../../packages/kos-ui-sdk/src/models/models/usb-update/usb-update-container-registration.ts","../../../packages/kos-ui-sdk/src/models/models/translation/services/translation-services.ts","../../../packages/kos-ui-sdk/src/models/models/translation/constants.ts","../../../packages/kos-ui-sdk/src/models/models/translation/translation-model.ts","../../../packages/kos-ui-sdk/src/models/models/translation/translation-registration.ts","../../../packages/kos-ui-sdk/src/models/models/translation/translation-container-model.ts","../../../packages/kos-ui-sdk/src/models/models/translation/translation-container-registration.ts","../../../packages/kos-ui-sdk/src/models/models/ws-event/ws-event-factory.ts","../../../packages/kos-ui-sdk/src/models/models/ws-event/ws-event-model.ts","../../../packages/kos-ui-sdk/src/models/registration.ts","../../../packages/kos-ui-sdk/src/models/utils/core-registration-manager.ts","../../../packages/kos-ui-sdk/src/models/utils/timer-manager.ts","../../../packages/kos-ui-sdk/src/models/models/software-info/services/software-info-services.ts","../../../packages/kos-ui-sdk/src/models/models/software-info/software-info-model.ts","../../../packages/kos-ui-sdk/src/models/models/software-info/software-info-registration.ts"],"sourcesContent":["export const HEADER_METHOD = `method`;\nexport const HEADER_TOPIC = `topic`;\nexport const HEADER_URL = `url`;\nexport const HEADER_REQUEST_ID = `request-id`;\nexport const HEADER_RESPONSE_ID = `response-id`;\nexport const STATUS = `status`;\nexport const HEADER_DESTINATION_ADDR = `dst-addr`;\nexport const HEADER_SOURCE_ADDR = `src-addr`;\nexport const HEADER_REQUEST_TYPE = `type`;\nexport const HEADER_ORDERED = `ordered`;\nexport const HEADER_WORK_TRACKER = `tracker`;\nexport const HEADER_CONTENT_TYPE = `Content-Type`;\nexport const HEADER_CACHE_CONTROL = `Cache-Control`;\n\nexport const HEADER_FOS_REQUEST_ID = `requestId`;\nexport const LOGIN_HOST = process.env.KOS_LOGIN_URL || \"http://localhost\";\nexport const PORT = process.env.KOS_APP_PORT || \"8080\";\n\nexport const LOGIN_URL = `${LOGIN_HOST}:${PORT}`;\n\nexport const KOS_MODEL_ID = `{MODEL_ID}`;\n\nexport enum KosWsEvents {\n SEND = \"/ws/log/msg/send\",\n RECEIVED = \"/ws/log/msg/receive\",\n}\n\nexport const EVENT_KOS_MODEL_READY = \"/kos/model/ready/\";\n","import log from \"loglevel\";\nlog.info(\"Initializing event bus\");\nglobalThis.kos = globalThis.kos || {};\nglobalThis.kos.subscriptions = globalThis.kos.subscriptions || {};\nconst subscriptions: Record<string, any> = globalThis.kos.subscriptions;\nconst getNextUniqueId = () => Symbol(`eventKey`);\n\n/**\n * @kosService core.event-bus\n * @kosApiLevel 2\n */\nexport interface ApiCallback<T = string> {\n headers: Record<string, string>;\n body: T;\n}\n/**\n * @kosService core.event-bus\n */\nexport type EventCallback<T = ApiCallback> = (msg?: T) => void;\n\n/**\n * @kosService core.event-bus\n * @kosApiLevel 2\n */\nexport interface PublishResponse {\n eventType: string;\n subscribers: number;\n}\n\n/**\n * @kosService core.event-bus\n * @kosApiLevel 7\n */\nexport function hasEventSubscriptions(eventType: string): boolean {\n return (\n subscriptions[eventType] &&\n Object.getOwnPropertySymbols(subscriptions[eventType]).length > 0\n );\n}\n\n/**\n * Subscribes to a specific event type with a callback function.\n *\n * @template T - The type of the callback function, defaults to `ApiCallback`.\n *\n * @param eventType - The name of the event to subscribe to.\n * @param callback - The callback function to execute when the event is triggered.\n *\n * @returns An object containing:\n * - `count`: The number of active subscriptions for the event type.\n * - `unsubscribe`: A function to unsubscribe from the event, which also returns the updated subscription count.\n *\n * @kosService core.event-bus\n * @kosApiLevel 2\n */\nexport function subscribe<T = ApiCallback>(\n eventType: string,\n callback: EventCallback<T>\n) {\n const id = getNextUniqueId();\n if (!subscriptions[eventType]) {\n log.debug(`Initializing subscription for ${eventType}`);\n subscriptions[eventType] = {};\n }\n\n log.debug(`Subscribing to ${eventType} with id ${id.toString()}`);\n subscriptions[eventType][id] = callback;\n\n return {\n count: subscriptions[eventType]\n ? Object.getOwnPropertySymbols(subscriptions[eventType]).length\n : 0,\n unsubscribe: () => {\n log.debug(`Unsubscribing from ${eventType} with id ${id.toString()}`);\n\n if (subscriptions[eventType] && subscriptions[eventType][id]) {\n delete subscriptions[eventType][id];\n }\n\n if (\n subscriptions[eventType] &&\n Object.getOwnPropertySymbols(subscriptions[eventType]).length === 0\n ) {\n delete subscriptions[eventType];\n }\n return {\n count: subscriptions[eventType]\n ? Object.getOwnPropertySymbols(subscriptions[eventType]).length\n : 0,\n };\n },\n };\n}\n\n/**\n * Publishes an event to all subscribers of the specified event type.\n *\n * @param eventType - The type of the event to publish.\n * @param msg - The message payload to send to subscribers.\n * @param headers - Optional headers to include with the event. If the \"sync\" header is provided,\n * the event will be published synchronously, and the response will be sent back\n * to the source using the specified sync ID.\n * @returns An object containing the event type and the number of subscribers the event was published to.\n *\n * The function checks if there are any subscriptions for the given event type. If no subscriptions\n * exist, it logs a debug message and returns an object indicating zero subscribers. Otherwise, it\n * iterates over the subscribers and publishes the event:\n * - If the \"sync\" header is present, the function waits for a response from the subscriber and\n * publishes the response back to the source using the sync ID.\n * - If the \"sync\" header is not present, the event is published asynchronously in a fire-and-forget manner.\n *\n * @kosService core.event-bus\n * @kosApiLevel 2\n */\nexport function publish(\n eventType: string,\n msg: unknown,\n headers: Record<string, string> = {}\n): PublishResponse {\n if (\n !subscriptions[eventType] ||\n Object.getOwnPropertySymbols(subscriptions[eventType]).length === 0\n ) {\n log.debug(`No subscriptions for ${eventType}. Not publishing.`);\n return {\n eventType,\n subscribers: 0,\n };\n }\n\n const count = Object.getOwnPropertySymbols(subscriptions[eventType]).length;\n // eslint-disable-next-line max-len\n Object.getOwnPropertySymbols(subscriptions[eventType]).forEach((id) => {\n if (headers[\"sync\"]) {\n // wait for the response and send it back if sync\n const responseId = headers[\"sync\"];\n log.debug(\n `Performing sync publish for ${eventType} with sync id ${responseId}`\n );\n subscriptions[eventType][id]({ body: msg, headers }).then(\n (response: any) => {\n log.debug(\n `Response recieved for ${responseId}, publishing back to source.`\n );\n publish(responseId, response);\n }\n );\n } else {\n // fire and forget if not sync\n log.debug(`Performing async publish for ${eventType}`);\n subscriptions[eventType][id]({ body: msg, headers });\n }\n });\n return {\n eventType,\n subscribers: count,\n };\n}\n\n/**\n * Resets the event bus by clearing all existing subscriptions.\n * Logs a warning message indicating the reset operation.\n *\n * @remarks\n * This function iterates through all keys in the `subscriptions` object\n * and deletes them, effectively removing all event listeners.\n *\n * @example\n * ```typescript\n * reset(); // Clears all event subscriptions and logs a warning.\n * ```\n *\n * @kosService core.event-bus\n * @kosApiLevel 2\n */\nexport function reset() {\n log.warn(\"Resetting event bus\");\n Object.keys(subscriptions).forEach((key) => delete subscriptions[key]);\n}\n\n/**\n * Subscribe to an event that will automatically unsubscribe after the first occurrence\n *\n * @param eventType - The event type to listen for\n * @param callback - The callback to execute once\n * @returns Unsubscribe function\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function once<T = ApiCallback>(\n eventType: string,\n callback: EventCallback<T>\n): () => void {\n const subscription = subscribe(eventType, (msg?: T) => {\n // Unsubscribe immediately after first call\n subscription.unsubscribe();\n callback(msg);\n });\n\n return subscription.unsubscribe;\n}\n\n/**\n * Wait for a specific event to occur, returning a Promise\n *\n * @param eventType - The event type to wait for\n * @param timeout - Optional timeout in milliseconds\n * @returns Promise that resolves with the event data\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function waitFor<T = ApiCallback>(\n eventType: string,\n timeout?: number\n): Promise<T> {\n return new Promise((resolve, reject) => {\n let timeoutId: NodeJS.Timeout | null = null;\n\n const unsubscribe = once(eventType, (msg?: T) => {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n resolve(msg!);\n });\n\n if (timeout) {\n timeoutId = setTimeout(() => {\n unsubscribe();\n reject(new Error(`Timeout waiting for event: ${eventType}`));\n }, timeout);\n }\n });\n}\n","/**\n * State-aware event utilities that handle the race condition between\n * initial state and event subscriptions\n */\n\nimport { ApiCallback, EventCallback, subscribe, waitFor } from \"./eventBus\";\n\n/**\n * Options for state-aware event subscriptions\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport interface StateAwareOptions<T> {\n /** Function to fetch the current state */\n getCurrentState: () => Promise<T> | T;\n /** Optional transform function to normalize API response to event format */\n transformState?: (state: any) => T;\n /** Optional function to determine if we should use the fetched state */\n shouldUseFetchedState?: (state: T) => boolean;\n /** Timeout for waiting for events (ms) */\n timeout?: number;\n}\n\n/**\n * Wait for an event OR get the current state if the event already happened\n * This prevents race conditions where events fire before subscription\n *\n * @param eventType - The event type to wait for\n * @param options - Options for state fetching and transformation\n * @returns Promise that resolves with either the event data or current state\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport async function waitForOrGetState<T = ApiCallback>(\n eventType: string,\n options: StateAwareOptions<T>\n): Promise<T> {\n const { getCurrentState, transformState, shouldUseFetchedState, timeout } =\n options;\n\n // Set up event listener first to minimize race window\n const eventPromise = waitFor<T>(eventType, timeout);\n\n // Fetch current state\n const currentState = await getCurrentState();\n const normalizedState = transformState\n ? transformState(currentState)\n : currentState;\n\n // Check if we should use the fetched state\n if (shouldUseFetchedState) {\n if (shouldUseFetchedState(normalizedState)) {\n // Cancel the event wait and return current state\n eventPromise.catch(() => {}); // Ignore timeout error\n return normalizedState;\n }\n }\n\n // Race between the event and a small delay\n // This gives the event a chance to fire if it's in flight\n const result = await Promise.race([\n eventPromise,\n new Promise<T>((resolve) => {\n setTimeout(() => resolve(normalizedState), 100);\n }),\n ]);\n\n return result;\n}\n\n/**\n * Subscribe to events with initial state, ensuring no events are missed\n *\n * @param eventType - The event type to subscribe to\n * @param callback - Callback for state updates\n * @param options - Options for initial state fetching\n * @returns Unsubscribe function\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function subscribeWithInitialState<T = ApiCallback>(\n eventType: string,\n callback: EventCallback<T>,\n options: StateAwareOptions<T>\n): () => void {\n const { getCurrentState, transformState } = options;\n let initialized = false;\n\n // Subscribe first to avoid missing events\n const subscription = subscribe(eventType, (msg?: T) => {\n if (msg) {\n initialized = true;\n callback(msg);\n }\n });\n\n // Fetch and emit initial state\n Promise.resolve(getCurrentState())\n .then((state) => {\n const normalizedState = transformState ? transformState(state) : state;\n\n // Only emit if we haven't received an event yet\n if (!initialized) {\n callback(normalizedState);\n }\n })\n .catch((error) => {\n console.error(\"Failed to fetch initial state:\", error);\n });\n\n return subscription.unsubscribe;\n}\n\n/**\n * Create a state-synchronized event stream that combines initial state with events\n *\n * @param eventType - The event type for updates\n * @param stateApi - API endpoint or function to fetch current state\n * @returns Object with subscribe method and current state getter\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function createStatefulEventStream<T = any>(\n eventType: string,\n stateApi: string | (() => Promise<T>)\n) {\n let currentState: T | undefined;\n const subscribers = new Set<(state: T) => void>();\n\n // Fetch initial state\n const fetchState = async () => {\n try {\n if (typeof stateApi === \"string\") {\n const response = await fetch(stateApi);\n currentState = await response.json();\n } else {\n currentState = await stateApi();\n }\n\n // Notify all subscribers of initial state\n subscribers.forEach((callback) => callback(currentState!));\n } catch (error) {\n console.error(\"Failed to fetch initial state:\", error);\n throw error;\n }\n };\n\n // Subscribe to events for updates\n subscribe(eventType, (msg?: ApiCallback<T>) => {\n if (msg?.body) {\n currentState = msg.body;\n subscribers.forEach((callback) => callback(currentState!));\n }\n });\n\n // Initialize state on first subscription\n let initialized = false;\n const ensureInitialized = () => {\n if (!initialized) {\n initialized = true;\n fetchState();\n }\n };\n\n return {\n /** Get current state synchronously (may be undefined if not loaded) */\n get state() {\n return currentState;\n },\n\n /** Get current state asynchronously (waits for initial load) */\n async getState(): Promise<T> {\n ensureInitialized();\n if (currentState === undefined) {\n await new Promise<void>((resolve) => {\n const checkState = () => {\n if (currentState !== undefined) {\n resolve();\n } else {\n setTimeout(checkState, 10);\n }\n };\n checkState();\n });\n }\n return currentState!;\n },\n\n /** Subscribe to state changes (includes initial state) */\n subscribe(callback: (state: T) => void): () => void {\n ensureInitialized();\n subscribers.add(callback);\n\n // Emit current state if available\n if (currentState !== undefined) {\n callback(currentState);\n }\n\n return () => {\n subscribers.delete(callback);\n };\n },\n\n /** Refresh state from API */\n async refresh(): Promise<T> {\n await fetchState();\n return currentState!;\n },\n };\n}\n\n/**\n * Wait for multiple events with shared state checking\n * Checks global state once to see if all conditions are already met\n *\n * @param eventTypes - Array of event types to wait for\n * @param options - Shared state checking options\n * @returns Promise that resolves when all events have occurred or state is ready\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport async function waitForAllWithState<T = ApiCallback>(\n eventTypes: string[],\n options: StateAwareOptions<T>\n): Promise<T>;\n\n/**\n * Wait for a single event with state checking (convenience overload)\n *\n * @param eventType - Single event type to wait for\n * @param options - State checking options\n * @returns Promise that resolves when event occurs or state is ready\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport async function waitForAllWithState<T = ApiCallback>(\n eventType: string,\n options: StateAwareOptions<T>\n): Promise<T>;\n\nexport async function waitForAllWithState<T = ApiCallback>(\n eventTypesOrType: string | string[],\n options: StateAwareOptions<T>\n): Promise<T> {\n // Handle single event case (most common)\n if (typeof eventTypesOrType === \"string\") {\n return waitForOrGetState(eventTypesOrType, options);\n }\n\n // Handle multiple events case\n const eventTypes = eventTypesOrType;\n const { getCurrentState, shouldUseFetchedState, timeout } = options;\n\n // Check global state first\n const currentState = await getCurrentState();\n const normalizedState = options.transformState\n ? options.transformState(currentState)\n : currentState;\n\n // If state shows we're already ready, return immediately\n if (shouldUseFetchedState && shouldUseFetchedState(normalizedState)) {\n return normalizedState;\n }\n\n // Otherwise wait for all events\n const eventPromises = eventTypes.map((eventType) =>\n waitFor<T>(eventType, timeout)\n );\n\n // Race between all events completing and a timeout\n const results = await Promise.all(eventPromises);\n\n // Return the last result (or could return all results if needed)\n return results[results.length - 1];\n}\n\n/**\n * Create a resilient event handler that can recover from missed events\n *\n * @param eventType - Event type to handle\n * @param handler - Event handler function\n * @param recoveryStrategy - Strategy for recovering missed events\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function createResilientEventHandler<T = ApiCallback>(\n eventType: string,\n handler: (data: T) => void | Promise<void>,\n recoveryStrategy: {\n /** API to fetch missed events or current state */\n fetchMissedEvents: () => Promise<T[]> | Promise<T>;\n /** How often to check for missed events (ms) */\n checkInterval?: number;\n /** Whether to deduplicate events by ID */\n deduplicateById?: (event: T) => string;\n }\n) {\n const {\n fetchMissedEvents,\n checkInterval = 30000,\n deduplicateById,\n } = recoveryStrategy;\n const processedIds = new Set<string>();\n\n // Handle incoming events\n const subscription = subscribe(eventType, async (msg?: T) => {\n if (msg) {\n if (deduplicateById) {\n const id = deduplicateById(msg);\n if (processedIds.has(id)) {\n return; // Already processed\n }\n processedIds.add(id);\n\n // Keep set size manageable\n if (processedIds.size > 1000) {\n const idsArray = Array.from(processedIds);\n idsArray.slice(0, 500).forEach((id) => processedIds.delete(id));\n }\n }\n\n await handler(msg);\n }\n });\n\n // Periodically check for missed events\n const intervalId = setInterval(async () => {\n try {\n const missed = await fetchMissedEvents();\n const events = Array.isArray(missed) ? missed : [missed];\n\n for (const event of events) {\n if (deduplicateById) {\n const id = deduplicateById(event);\n if (!processedIds.has(id)) {\n processedIds.add(id);\n await handler(event);\n }\n } else {\n await handler(event);\n }\n }\n } catch (error) {\n console.error(\"Failed to fetch missed events:\", error);\n }\n }, checkInterval);\n\n // Return cleanup function\n return () => {\n subscription.unsubscribe();\n clearInterval(intervalId);\n };\n}\n\n/**\n * Pattern for handling connection state with events\n * Useful for WebSocket connections, plugin loading, etc.\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport interface ConnectionStateManager<T = any> {\n /** Current connection state */\n state: \"disconnected\" | \"connecting\" | \"connected\" | \"error\";\n /** Current data (if connected) */\n data?: T;\n /** Wait for connection to be established */\n waitForConnection(timeout?: number): Promise<T>;\n /** Subscribe to state changes */\n subscribe(callback: (state: ConnectionStateManager<T>) => void): () => void;\n /** Manually trigger reconnection */\n reconnect(): Promise<void>;\n}\n\n/**\n * Create a connection state manager that handles online/offline scenarios\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function createConnectionStateManager<T = any>(config: {\n connectEvent: string;\n disconnectEvent: string;\n errorEvent?: string;\n dataEvent?: string;\n fetchInitialState: () => Promise<T>;\n reconnectDelay?: number;\n}): ConnectionStateManager<T> {\n const {\n connectEvent,\n disconnectEvent,\n errorEvent,\n dataEvent,\n fetchInitialState,\n reconnectDelay = 5000,\n } = config;\n\n const manager: ConnectionStateManager<T> = {\n state: \"disconnected\",\n data: undefined,\n\n async waitForConnection(timeout?: number): Promise<T> {\n if (manager.state === \"connected\" && manager.data) {\n return manager.data;\n }\n\n // Wait for connection event or fetch current state\n const result = await waitForOrGetState<T>(connectEvent, {\n getCurrentState: fetchInitialState,\n shouldUseFetchedState: (state) => !!state,\n timeout,\n });\n\n manager.state = \"connected\";\n manager.data = result;\n notifySubscribers();\n\n return result;\n },\n\n subscribe(\n callback: (state: ConnectionStateManager<T>) => void\n ): () => void {\n subscribers.add(callback);\n callback(manager); // Emit current state\n return () => {\n subscribers.delete(callback);\n };\n },\n\n async reconnect(): Promise<void> {\n manager.state = \"connecting\";\n notifySubscribers();\n\n try {\n const data = await fetchInitialState();\n manager.state = \"connected\";\n manager.data = data;\n notifySubscribers();\n } catch (error) {\n manager.state = \"error\";\n notifySubscribers();\n\n // Auto-retry after delay\n setTimeout(() => {\n if (manager.state === \"error\") {\n manager.reconnect();\n }\n }, reconnectDelay);\n }\n },\n };\n\n const subscribers = new Set<(state: ConnectionStateManager<T>) => void>();\n const notifySubscribers = () => {\n subscribers.forEach((callback) => callback(manager));\n };\n\n // Subscribe to connection events\n subscribe(connectEvent, (msg?: ApiCallback<T>) => {\n manager.state = \"connected\";\n if (msg?.body) {\n manager.data = msg.body;\n }\n notifySubscribers();\n });\n\n subscribe(disconnectEvent, () => {\n manager.state = \"disconnected\";\n notifySubscribers();\n\n // Auto-reconnect\n setTimeout(() => {\n if (manager.state === \"disconnected\") {\n manager.reconnect();\n }\n }, reconnectDelay);\n });\n\n if (errorEvent) {\n subscribe(errorEvent, () => {\n manager.state = \"error\";\n notifySubscribers();\n });\n }\n\n if (dataEvent) {\n subscribe(dataEvent, (msg?: ApiCallback<T>) => {\n if (msg?.body && manager.state === \"connected\") {\n manager.data = msg.body;\n notifySubscribers();\n }\n });\n }\n\n // Check initial state\n manager.reconnect();\n\n return manager;\n}\n\n/**\n * Namespace collecting all state-aware event bus utilities.\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport const EventBusState = {\n waitForOrGetState,\n subscribeWithInitialState,\n createStatefulEventStream,\n waitForAllWithState,\n createResilientEventHandler,\n createConnectionStateManager,\n};\n","/**\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport const getQueryParams = (query = null) =>\n (query || window.location.search.replace(\"?\", \"\"))\n\n // get array of KeyValue pairs\n .split(\"&\")\n\n // Decode values\n .map((pair) => {\n const [key, val] = pair.split(\"=\");\n\n return [key, decodeURIComponent(val || \"\")];\n })\n\n // array to object\n .reduce((result, [key, val]) => {\n result[key] = val;\n return result;\n }, {});\n","import { getQueryParams } from \"./get-query-params\";\n\ninterface KosConfig {\n logging: boolean;\n profiles: string[];\n [key: string]: boolean | string[] | string | number | undefined;\n}\n\n/**\n * @kosService core.utils\n * @kosApiLevel 20\n */\nexport const PROFILE_ENABLE_RELEASES = \"studio.enable.releases\";\n/**\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport const PROFILE_TOOLS_PREVIEW = \"studio.tools.preview\";\n/**\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport const PROFILE_RELAX_STORE_VALIDATION = \"studio.relax.store.validation\";\n/**\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport const PROFILE_LOG_DEBUG = \"studio.log.debug\";\n/**\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport const PROFILE_LOG_INFO = \"studio.log.info\";\nconst defaultConfig = {\n profiles: [PROFILE_TOOLS_PREVIEW],\n};\nconst config = globalThis.getKosConfig?.() || JSON.stringify(defaultConfig);\n\nconst configObj: KosConfig = JSON.parse(config);\n\n/**\n * Profiles named on the URL, comma separated, added to whatever the host\n * supplied. Only a launched window gets `getKosConfig`, so a dev-server tab\n * would otherwise be stuck with the defaults and no way to turn a profile on.\n */\nconst urlProfiles = (): string[] => {\n if (typeof window === \"undefined\") {\n return [];\n }\n const value = getQueryParams()?.[\"kosProfiles\"];\n return value\n ? value\n .split(\",\")\n .map((profile) => profile.trim())\n .filter(Boolean)\n : [];\n};\n\nconfigObj.profiles = [\n ...(configObj.profiles ?? []),\n ...urlProfiles().filter((profile) => !configObj.profiles?.includes(profile)),\n];\n\nglobalThis.kosConfig = configObj;\n\n/**\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport const KosGlobalConfig: KosConfig = configObj;\n\n/**\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport const resolveKosProfiles = () => KosGlobalConfig.profiles || [];\n\n/**\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport const hasKosProfile = (profile: string) =>\n resolveKosProfiles().includes(profile);\n\n/**\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport const isKosLoggingEnabled = () => KosGlobalConfig.logging || false;\n","import { LogLevelDesc } from \"loglevel\";\nimport { getQueryParams } from \"../util/get-query-params\";\nimport {\n hasKosProfile,\n PROFILE_LOG_DEBUG,\n PROFILE_LOG_INFO,\n} from \"../util/kos-config-init\";\n\nconst resolveLogLevelProfile = (): LogLevelDesc | undefined => {\n const showDebugLogProfile = hasKosProfile(PROFILE_LOG_DEBUG);\n const showInfoLogProfile = hasKosProfile(PROFILE_LOG_INFO);\n return showDebugLogProfile\n ? \"DEBUG\"\n : showInfoLogProfile\n ? \"INFO\"\n : undefined;\n};\n/**\n * @kosService core.logging\n * @kosApiLevel 2\n */\nexport const getLogLevel = (): LogLevelDesc => {\n const params = getQueryParams();\n\n const profileLogLevel = resolveLogLevelProfile();\n const logLevelParam = params[\"kosLogLevel\"];\n const logLevel =\n logLevelParam ??\n profileLogLevel ??\n window.kosLogLevel ??\n process.env.KOS_LOG_LEVEL;\n if (logLevel) {\n return logLevel as LogLevelDesc;\n }\n return \"WARN\";\n};\n\n/**\n * @kosService core.logging\n * @kosApiLevel 2\n */\nexport const getKosMessageLogging = (): boolean => {\n const enableAll =\n window.kosMessageLogging || process.env.KOS_MESSAGE_LOGGING === \"true\";\n return enableAll;\n};\n\n/**\n * @kosService core.logging\n * @kosApiLevel 2\n */\nexport const getLogMessageToStudio = (): boolean => {\n const enableAll =\n window.kosMessageStudioLogging ||\n process.env.KOS_MESSAGE_STUDIO_LOGGING === \"true\";\n return enableAll;\n};\n","import log, { LogLevel } from \"loglevel\";\nimport {\n getKosMessageLogging,\n getLogLevel,\n getLogMessageToStudio,\n} from \"../../util/log-utils\";\n\nconst WS_LOG = \"ws-log\";\nconst originalFactory = log.methodFactory;\n\nconst enableMessageLogging = getKosMessageLogging();\n\nconst enableStudioMessageLogging = getLogMessageToStudio();\nlog.methodFactory = function (methodName, logLevel, loggerName) {\n const rawMethod = originalFactory(methodName, logLevel, loggerName);\n\n return function (...args: any[]) {\n const _name = loggerName ? String(loggerName) : \"\";\n\n const prefix = _name\n ? `[${String(_name).substring(_name.lastIndexOf(\":\") + 1)}] | `\n : \"[root] | \";\n\n // Concatenate all arguments similar to console.log\n const message = args\n .map((arg) =>\n typeof arg === \"object\" ? JSON.stringify(arg) : String(arg)\n )\n .join(\" \");\n\n rawMethod(`${prefix}${message}`);\n if (\n globalThis?.kosConfig?.logging &&\n globalThis.kosLog &&\n (loggerName !== WS_LOG ||\n (enableMessageLogging && enableStudioMessageLogging))\n ) {\n globalThis.kosLog(`UI: ${prefix}${message}`);\n }\n };\n};\nlet level = getLogLevel();\nlog.setLevel(level);\n\nwindow.setKosLogLevel = (_level: log.LogLevelDesc) => {\n level = _level;\n log.setLevel(_level);\n};\nconst wsLog = log.getLogger(WS_LOG);\nwindow.enableKosMessageLog = () => {\n wsLog.setLevel(log.levels.INFO);\n};\n\nwindow.disableKosMessageLog = () => {\n wsLog.setLevel(log.levels.ERROR);\n};\n\nif (enableMessageLogging) {\n window.enableKosMessageLog();\n} else {\n window.disableKosMessageLog();\n}\nconst styles = [\n \"color: black\",\n \"display: block\",\n \"background-color: lightgreen\",\n\n \"padding: 4px\",\n \"margin: 0\",\n \"text-shadow: 0 1px 0 rgba(0, 0, 0, 0.3)\",\n \"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\",\n\n \"font-weight: bold\",\n].join(\";\");\n\nconst received = [\n \"color: black\",\n \"display: block\",\n\n \"padding: 4px\",\n \"background-color: yellow\",\n \"margin: 0\",\n \"text-shadow: 0 1px 0 rgba(0, 0, 0, 0.3)\",\n \"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\",\n\n \"font-weight: bold\",\n].join(\";\");\n\nconst conditionallyLog =\n (level: LogLevel[keyof LogLevel]) => (fn: VoidFunction) => {\n if (log.getLevel() <= level) {\n fn();\n }\n };\nexport const KosLog = {\n ...log,\n\n ifDebug: conditionallyLog(log.levels.DEBUG),\n ifInfo: conditionallyLog(log.levels.INFO),\n ifWarn: conditionallyLog(log.levels.WARN),\n ifError: conditionallyLog(log.levels.ERROR),\n getLogger: (name: string) => log.getLogger(`kos::${name}`),\n getLoggers: () => log.getLoggers(),\n createLogger: ({ name, group }: { name: string; group?: string }) => {\n const loggerName = `${group ? `${group}:` : \"kos\"}::${name}`;\n const _log = log.getLogger(loggerName);\n let _level = globalThis.kos.logOverrides?.find(\n (override) => override.name === loggerName\n )?.level;\n if (_level) {\n _log.setLevel(_level);\n } else {\n _level = globalThis.kos.logOverrides?.find((override) =>\n loggerName.startsWith(override.name)\n )?.level;\n if (_level) {\n _log.setLevel(_level);\n }\n }\n return _log;\n },\n wsSend: (...msg: any[]) => {\n const str = String(msg).replace(/\\n/g, \"\\\\n\");\n wsLog.info(`%c⬆ ${str}`, styles);\n },\n wsReceive: (...msg: any[]) => {\n const str = String(msg).replace(/\\n/g, \"\\\\n\");\n wsLog.info(`%c⬇ ${str}`, received);\n },\n};\n","/**\n * @internal\n */\nexport const SubscriptionHandlers = Symbol(`SubscriptionHandlers`);\nexport const DependencyModels = Symbol(`DependencyModels`);\nexport const FutureService = Symbol(`FutureService`);\nexport const ChildModels = Symbol(`ChildModels`);\nexport const ParentModel = Symbol(`ParentModel`);\nexport const LogConfig = Symbol(`LogConfig`);\nexport const ReferenceConfig = Symbol(`ReferenceConfig`);\nexport const KosModelSymbol = Symbol(`KosModelSymbol`);\nexport const ModelEffects = Symbol(`ModelEffects`);\nexport const CompanionParentModel = Symbol(`CompanionParentModel`);\nexport const FutureContainerSetup = Symbol(`FutureContainerSetup`);\nexport const MultipleFutureContainerSetup = Symbol(\n `MultipleFutureContainerSetup`\n);\nexport const FutureAliases = Symbol(`FutureAliases`);\nexport const TroubleAwareSetup = Symbol(`TroubleAwareSetup`);\nexport const LoggerSetup = Symbol(`LoggerSetup`);\nexport const ContainerAwareSetup = Symbol(`ContainerAwareSetup`);\nexport const StateMachineSetup = Symbol(`StateMachineSetup`);\nexport const StateEntryHandlers = Symbol(`StateEntryHandlers`);\nexport const StateExitHandlers = Symbol(`StateExitHandlers`);\nexport const StateActionHandlers = Symbol(`StateActionHandlers`);\nexport const OptionsRequired = Symbol(`OptionsRequired`);\nexport const KosViewModelSymbol = Symbol(`KosViewModelSymbol`);\nexport const ViewModelConfig = Symbol(`ViewModelConfig`);\nexport const ReloadAwareSetup = Symbol(`ReloadAwareSetup`);\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable no-param-reassign */\nimport { KosLog } from \"../log\";\nimport {\n StateEntryHandlers,\n StateExitHandlers,\n StateMachineSetup,\n} from \"./propKeys\";\n\nconst log = KosLog.createLogger({ group: \"decorators\", name: \"fsm-injection\" });\n\n// ============================================================================\n// Zone 2: Coordination Functions\n// ============================================================================\n\n/**\n * Main coordinator for injecting FSM support into a model instance.\n * Delegates to Zone 3 functions for actual implementation.\n *\n * @param modelInstance The model instance to inject FSM support into\n */\nexport function injectStateMachineSupport(modelInstance: any) {\n const fsmSetup = modelInstance[StateMachineSetup];\n if (!fsmSetup) return;\n\n const { config, options } = fsmSetup;\n\n // Store configuration for later access\n storeFsmConfiguration(modelInstance, config, options);\n\n // Initialize FSM properties\n initializeFsmProperties(modelInstance, options);\n\n // Retrieve handlers from prototype\n const handlers = retrieveHandlers(modelInstance);\n\n // Attach FSM methods\n attachFsmMethods(modelInstance, config, options, handlers);\n\n // Setup FSM getters\n setupFsmGetters(modelInstance, config, options);\n}\n\n/**\n * Attach all FSM methods to the model instance.\n *\n * @param modelInstance The model instance\n * @param config FSM configuration\n * @param options FSM options\n * @param handlers Entry/exit handlers\n */\nfunction attachFsmMethods(\n modelInstance: any,\n config: any,\n options: any,\n handlers: { entry: Map<string, string>; exit: Map<string, string> }\n) {\n modelInstance.transition = createTransitionMethod(\n modelInstance,\n config,\n options,\n handlers.entry,\n handlers.exit\n );\n\n modelInstance.canTransition = createCanTransitionMethod(\n modelInstance,\n config,\n options\n );\n modelInstance.isInState = createIsInStateMethod(modelInstance, options);\n}\n\n/**\n * Setup reactive getters for FSM state.\n *\n * @param modelInstance The model instance\n * @param config FSM configuration\n * @param options FSM options\n */\nfunction setupFsmGetters(modelInstance: any, config: any, options: any) {\n defineIsFsmInitializedGetter(modelInstance);\n defineAllowedTransitionsGetter(modelInstance, config, options);\n}\n\n/**\n * Retrieve entry and exit handlers from prototype.\n *\n * @param modelInstance The model instance\n * @returns Object containing entry and exit handler maps\n */\nfunction retrieveHandlers(modelInstance: any): {\n entry: Map<string, string>;\n exit: Map<string, string>;\n} {\n const entryHandlers =\n modelInstance.constructor.prototype[StateEntryHandlers] || new Map();\n const exitHandlers =\n modelInstance.constructor.prototype[StateExitHandlers] || new Map();\n\n return { entry: entryHandlers, exit: exitHandlers };\n}\n\n// ============================================================================\n// Zone 3: Implementation Functions\n// ============================================================================\n\n/**\n * Store FSM configuration on the model instance.\n *\n * @param modelInstance The model instance\n * @param config FSM configuration\n * @param options FSM options\n */\nfunction storeFsmConfiguration(modelInstance: any, config: any, options: any) {\n modelInstance._fsmConfig = config;\n modelInstance._fsmOptions = options;\n}\n\n/**\n * Initialize FSM state properties on the model instance.\n * Uses computeInitialState if provided, otherwise uses the static initial state from config.\n *\n * When computeInitialState is provided, the FSM is immediately active since it\n * represents current state (not a transition) — no entry handlers are needed.\n * Otherwise, initialization is deferred to the configured lifecycle phase so\n * that initializeStateMachine can fire the initial state's entry handler.\n *\n * @param modelInstance The model instance\n * @param options FSM options\n */\nfunction initializeFsmProperties(modelInstance: any, options: any) {\n const { stateProperty, trackHistory, computeInitialState } = options;\n const config = modelInstance._fsmConfig;\n\n // Use computeInitialState if provided, otherwise use static initial from config\n const initialState = computeInitialState\n ? computeInitialState(modelInstance)\n : config.initial;\n\n // Validate that the computed state exists in the config\n if (computeInitialState && !config.states[initialState]) {\n log.warn(\n `computeInitialState returned \"${initialState}\" which is not a valid state. Falling back to \"${config.initial}\".`\n );\n modelInstance[stateProperty] = config.initial;\n } else {\n modelInstance[stateProperty] = initialState;\n }\n\n // Only mark as initialized when computeInitialState is provided.\n // For the standard path, initializeStateMachine will set this at the\n // configured lifecycle phase and fire the initial state's entry handler.\n modelInstance._fsmInitialized = !!computeInitialState;\n modelInstance.isTransitioning = false;\n\n if (trackHistory) {\n // Pre-populate history only for computeInitialState (already active).\n // For the standard path, initializeStateMachine will add the first entry.\n modelInstance.stateHistory = computeInitialState\n ? [{ state: modelInstance[stateProperty], timestamp: new Date() }]\n : [];\n }\n}\n\n/**\n * Define the isFsmInitialized getter on the model instance.\n *\n * @param modelInstance The model instance\n */\nfunction defineIsFsmInitializedGetter(modelInstance: any) {\n Object.defineProperty(modelInstance, \"isFsmInitialized\", {\n get() {\n return this._fsmInitialized;\n },\n enumerable: true,\n configurable: true,\n });\n}\n\n/**\n * Define the allowedTransitions computed getter on the model instance.\n *\n * @param modelInstance The model instance\n * @param _config FSM configuration (unused, provided for consistency)\n * @param options FSM options\n */\nfunction defineAllowedTransitionsGetter(\n modelInstance: any,\n _config: any,\n options: any\n) {\n const { stateProperty } = options;\n\n Object.defineProperty(modelInstance, \"allowedTransitions\", {\n get() {\n if (!this._fsmInitialized) return [];\n const currentState = this[stateProperty];\n const stateConfig = this._fsmConfig.states[currentState];\n return stateConfig?.on ? Object.keys(stateConfig.on) : [];\n },\n enumerable: true,\n configurable: true,\n });\n}\n\n/**\n * Create the transition method for the model instance.\n *\n * @param _instance The model instance (unused, provided for consistency)\n * @param config FSM configuration\n * @param options FSM options\n * @param entryHandlers Map of entry handlers\n * @param exitHandlers Map of exit handlers\n * @returns The transition function\n */\nfunction createTransitionMethod(\n _instance: any,\n config: any,\n options: any,\n entryHandlers: Map<string, string>,\n exitHandlers: Map<string, string>\n): (event: string) => void {\n const { stateProperty, throwOnInvalid } = options;\n\n return function (this: any, event: string) {\n // Validate FSM is initialized\n if (!this._fsmInitialized) {\n handleUninitializedFsm(config.initializeAt, throwOnInvalid);\n return;\n }\n\n // Get current state and resolve next state\n const currentState = this[stateProperty];\n const nextState = resolveNextState(\n currentState,\n event,\n this._fsmConfig,\n throwOnInvalid\n );\n\n if (!nextState) return;\n\n // Execute the transition\n executeTransition(\n this,\n currentState,\n nextState,\n event,\n stateProperty,\n entryHandlers,\n exitHandlers,\n options\n );\n };\n}\n\n/**\n * Handle case when FSM is not initialized.\n *\n * @param initializeAt The lifecycle phase FSM initializes at\n * @param throwOnInvalid Whether to throw or warn\n */\nfunction handleUninitializedFsm(initializeAt: string, throwOnInvalid: boolean) {\n const message = `Cannot transition: FSM not initialized. Waiting for ${initializeAt} lifecycle phase.`;\n if (throwOnInvalid) {\n throw new Error(message);\n } else {\n console.warn(message);\n }\n}\n\n/**\n * Resolve the next state for a given event from the current state.\n *\n * @param currentState The current state\n * @param event The event to trigger\n * @param config FSM configuration\n * @param throwOnInvalid Whether to throw or warn on invalid transition\n * @returns The next state, or undefined if invalid\n */\nfunction resolveNextState(\n currentState: string,\n event: string,\n config: any,\n throwOnInvalid: boolean\n): string | undefined {\n const stateConfig = config.states[currentState];\n const nextState = stateConfig?.on?.[event];\n\n if (!nextState) {\n handleInvalidTransition(currentState, event, throwOnInvalid);\n return undefined;\n }\n\n return nextState;\n}\n\n/**\n * Handle invalid transition attempt.\n *\n * @param currentState The current state\n * @param event The invalid event\n * @param throwOnInvalid Whether to throw or warn\n */\nfunction handleInvalidTransition(\n currentState: string,\n event: string,\n throwOnInvalid: boolean\n) {\n const message = `Invalid transition: Event \"${event}\" not allowed from state \"${currentState}\"`;\n if (throwOnInvalid) {\n throw new Error(message);\n } else {\n console.warn(message);\n }\n}\n\n/**\n * Execute a state transition with entry/exit handlers.\n *\n * @param instance The model instance\n * @param currentState The current state\n * @param nextState The next state\n * @param event The triggering event\n * @param stateProperty The property name for storing state\n * @param entryHandlers Map of entry handlers\n * @param exitHandlers Map of exit handlers\n * @param options FSM options\n */\nfunction executeTransition(\n instance: any,\n currentState: string,\n nextState: string,\n event: string,\n stateProperty: string,\n entryHandlers: Map<string, string>,\n exitHandlers: Map<string, string>,\n options: any\n) {\n instance.isTransitioning = true;\n\n try {\n // Call exit handler for current state\n executeExitHandler(instance, currentState, exitHandlers);\n\n // Update state\n instance[stateProperty] = nextState;\n\n // Track history if enabled\n trackTransitionHistory(instance, nextState, event, options);\n\n // Call entry handler for next state\n const result = executeEntryHandler(instance, nextState, entryHandlers);\n\n // Handle async entry handlers with onDone/onError auto-transitions\n handleAsyncEntryResult(instance, nextState, stateProperty, result);\n } finally {\n instance.isTransitioning = false;\n }\n}\n\n/**\n * Execute exit handler for a state if it exists.\n *\n * @param instance The model instance\n * @param state The state being exited\n * @param exitHandlers Map of exit handlers\n */\nfunction executeExitHandler(\n instance: any,\n state: string,\n exitHandlers: Map<string, string>\n) {\n const exitHandler = exitHandlers.get(state);\n if (exitHandler && typeof instance[exitHandler] === \"function\") {\n instance[exitHandler]();\n }\n}\n\n/**\n * Execute entry handler for a state if it exists.\n *\n * @param instance The model instance\n * @param state The state being entered\n * @param entryHandlers Map of entry handlers\n * @returns The handler's return value (may be a Promise for async handlers)\n */\nfunction executeEntryHandler(\n instance: any,\n state: string,\n entryHandlers: Map<string, string>\n): unknown {\n const entryHandler = entryHandlers.get(state);\n if (entryHandler && typeof instance[entryHandler] === \"function\") {\n return instance[entryHandler]();\n }\n return undefined;\n}\n\n/**\n * Handle async entry handler results for onDone/onError auto-transitions.\n *\n * If the entry handler returns a Promise and the state config has onDone/onError,\n * automatically sends the configured event when the Promise resolves/rejects.\n * Only triggers if the FSM is still in the same state when the handler completes\n * (guards against races where another event already moved the FSM forward).\n *\n * @param instance The model instance\n * @param state The state whose entry handler was called\n * @param stateProperty The property name for storing state\n * @param result The return value from the entry handler\n */\nfunction handleAsyncEntryResult(\n instance: any,\n state: string,\n stateProperty: string,\n result: unknown\n) {\n // Only handle Promise results\n if (!result || typeof (result as Promise<unknown>).then !== \"function\") {\n return;\n }\n\n const stateConfig = instance._fsmConfig?.states?.[state];\n if (!stateConfig?.onDone && !stateConfig?.onError) {\n return;\n }\n\n (result as Promise<unknown>).then(\n () => {\n // Only auto-transition if still in the same state\n if (stateConfig.onDone && instance[stateProperty] === state) {\n instance.transition(stateConfig.onDone);\n }\n },\n (err: unknown) => {\n if (stateConfig.onError && instance[stateProperty] === state) {\n instance.transition(stateConfig.onError);\n } else {\n log.error(`Async entry handler for state \"${state}\" failed:`, err);\n }\n }\n );\n}\n\n/**\n * Track state transition in history if enabled.\n *\n * @param instance The model instance\n * @param nextState The new state\n * @param event The triggering event\n * @param options FSM options\n */\nfunction trackTransitionHistory(\n instance: any,\n nextState: string,\n event: string,\n options: any\n) {\n if (options.trackHistory && instance.stateHistory) {\n instance.stateHistory.push({\n state: nextState,\n timestamp: new Date(),\n event,\n });\n }\n}\n\n/**\n * Create the canTransition method for the model instance.\n *\n * @param _instance The model instance (unused, provided for consistency)\n * @param _config FSM configuration (unused, provided for consistency)\n * @param options FSM options\n * @returns The canTransition function\n */\nfunction createCanTransitionMethod(\n _instance: any,\n _config: any,\n options: any\n): (event: string) => boolean {\n const { stateProperty } = options;\n\n return function (this: any, event: string): boolean {\n if (!this._fsmInitialized) return false;\n const currentState = this[stateProperty];\n const stateConfig = this._fsmConfig.states[currentState];\n return stateConfig?.on?.[event] !== undefined;\n };\n}\n\n/**\n * Create the isInState method for the model instance.\n *\n * @param _instance The model instance (unused, provided for consistency)\n * @param options FSM options\n * @returns The isInState function\n */\nfunction createIsInStateMethod(\n _instance: any,\n options: any\n): (state: string) => boolean {\n const { stateProperty } = options;\n\n return function (this: any, state: string): boolean {\n if (!this._fsmInitialized) return false;\n return this[stateProperty] === state;\n };\n}\n\n// ============================================================================\n// Initialization Functions\n// ============================================================================\n\n/**\n * Initialize the state machine at a specific lifecycle phase.\n * Called from KosModel lifecycle hooks.\n *\n * @param modelInstance The model instance\n * @param lifecycle The current lifecycle phase\n */\nexport function initializeStateMachine(modelInstance: any, lifecycle: string) {\n const fsmSetup = modelInstance[StateMachineSetup];\n if (!fsmSetup) return;\n\n const { config, options } = fsmSetup;\n const { stateProperty } = options;\n\n // Only initialize if we're at the configured lifecycle phase\n if (config.initializeAt !== lifecycle) return;\n\n // Only initialize once\n if (modelInstance._fsmInitialized) return;\n\n // Set initial state\n setInitialState(modelInstance, stateProperty, config.initial);\n modelInstance._fsmInitialized = true;\n\n // Track initial state in history if enabled\n trackInitialStateInHistory(modelInstance, config.initial, options);\n\n // Call entry handler for initial state\n executeInitialStateEntryHandler(modelInstance, config.initial);\n\n log.debug(\n `FSM initialized for model ${modelInstance.id} at lifecycle ${lifecycle} with initial state \"${config.initial}\"`\n );\n}\n\n/**\n * Set the initial state on the model instance.\n *\n * @param instance The model instance\n * @param stateProperty The property name for storing state\n * @param initialState The initial state value\n */\nfunction setInitialState(\n instance: any,\n stateProperty: string,\n initialState: string\n) {\n instance[stateProperty] = initialState;\n}\n\n/**\n * Track initial state in history if tracking is enabled.\n *\n * @param instance The model instance\n * @param initialState The initial state\n * @param options FSM options\n */\nfunction trackInitialStateInHistory(\n instance: any,\n initialState: string,\n options: any\n) {\n if (options.trackHistory && instance.stateHistory) {\n instance.stateHistory.push({\n state: initialState,\n timestamp: new Date(),\n });\n }\n}\n\n/**\n * Execute entry handler for initial state if it exists.\n *\n * @param instance The model instance\n * @param initialState The initial state\n */\nfunction executeInitialStateEntryHandler(instance: any, initialState: string) {\n const entryHandlers =\n instance.constructor.prototype[StateEntryHandlers] || new Map();\n const entryHandler = entryHandlers.get(initialState);\n if (entryHandler && typeof instance[entryHandler] === \"function\") {\n instance[entryHandler]();\n }\n}\n","import { ChildModels } from \"./propKeys\";\n\n/**\n * Decorator for marking a property as a child model within a Kos Data Model class.\n *\n * If a property is marked as a child model, it will be automatically included in the model's\n * lifecycle management. This means that when the parent model will not transition to a ready state\n * until all of its child models are ready.\n *\n * Similarly, when the parent model is destroyed, all of its child models will be destroyed as well.\n *\n * If the property is a KosModelContainer then all of the underlying child models will be included in the\n * child model lifecycle management.\n *\n * @param target - The target object or class.\n * @param name - The name of the property to be marked as a child model.\n * @returns A decorator function that marks the property as a child model.\n * @category KOS Model Decorator\n * @kosService core.child\n * @kosApiLevel 2\n */\nexport const kosChild = (target: {} | any, name: PropertyKey): any => {\n target[ChildModels] = target[ChildModels] || {};\n target[ChildModels][name] = true;\n};\n","import type { IKosDataModel } from \"../core/kosModel\";\n\n/**\n * Creates a property key string based on a given key from a Kos data model.\n *\n * Property keys are used by the KOS model framework to provide property expansion in model data.\n *\n * When create a model dependency or any model metadata that is derived from the existing model data,\n * a property key should be used to reference the data model key.\n *\n * For kos dependencies, propKeys can be used to resolve any dependency options that are derived from the data model.\n *\n * For topic handlers, the resolved topic can include propKey to allow for dynamic topic resolution based on the data model.\n *\n * @param key - The key from a Kos data model.\n * @returns A property key string enclosed in curly braces with a \"PROP_\" prefix.\n *\n * @example\n * // Create a property key for a data model key \"name\"\n * const propertyKey = createPropKey(\"name\");\n * // Result: \"{PROP_name}\"\n *\n * @example\n * // Create a property key for a data model key \"id\"\n * const propertyKey = createPropKey(\"id\");\n * // Result: \"{PROP_id}\"\n *\n * @example\n * The propKey can be used as part of dependency or topic listener to allow for models to\n * dynamically change the dependency or topic listener based on the data model.\n * ```typescript\n * @kosDependency({modelType: Ingredient.type, id: propertyKey})\n * ```\n *\n * @kosService core.kos-model\n * @kosApiLevel 2\n */\nexport const createPropKey = <R extends IKosDataModel>(key: keyof R) =>\n `{PROP_${String(key)}}`;\n\n/**\n * @kosService core.kos-model\n * @kosApiLevel 2\n */\nexport const createOptionKey = <R extends object>(key: keyof R) =>\n `{PROP_${String(key)}}`;\n","/* eslint-disable no-param-reassign */\nimport { createPropKey } from \"../../util/model-attribute-utils\";\nimport { IKosDataModel } from \"../kosModel\";\nimport { OptionsRequired, ParentModel } from \"./propKeys\";\n\ninterface DecoratedKosModel<T extends IKosDataModel = IKosDataModel> {\n new (...args: any[]): T;\n}\n\n/**\n * @kosService core.parent\n * @kosApiLevel 2\n */\nexport interface KosParentProps {\n parentId?: string;\n}\n\n/**\n * Decorator for declaring that a KOS model should be aware of its parent model.\n * This decorator will ensure that the parent model is available to the child model immediately after creation.\n * There is a slight performance overhead to this decorator, so it should only be used when necessary.\n *\n * **Note**: This decorator automatically sets the model's `optionsRequired` flag to true since\n * parent-aware models require at least the parent ID to be provided in options.\n *\n * @category KOS Model Decorator\n * @kosService core.parent\n * @kosApiLevel 2\n */\nconst DEFAULT_OPTION_KEY = createPropKey<any>(\"kosParentId\");\nexport const kosParentAware =\n <T extends IKosDataModel>(options?: KosParentProps) =>\n (constructor: DecoratedKosModel<T>): any => {\n constructor[ParentModel] = constructor[ParentModel] || {};\n const parentId = options?.parentId || DEFAULT_OPTION_KEY;\n constructor[ParentModel] = { parentId };\n\n // Parent-aware models require options (at minimum the parent ID)\n constructor.prototype[OptionsRequired] = true;\n };\n","/* eslint-disable no-param-reassign */\nimport type { IKosModelContainer } from \"../kos-container-model\";\nimport type { IKosDataModel } from \"../kosModel\";\nimport { ContainerAwareSetup } from \"./propKeys\";\ntype MaybePromise<T> = T | Promise<T>;\n/**\n * Configuration options for the @kosContainerAware decorator.\n *\n * @template T The type of models contained in the container (must extend IKosDataModel)\n *\n * @kosService core.container-aware\n * @kosApiLevel 13\n */\nexport interface KosContainerAwareOptions<\n T extends IKosDataModel = IKosDataModel\n> {\n /**\n * Container property name on the model instance.\n *\n * @default \"container\"\n * @example\n * ```typescript\n * @kosContainerAware({ containerProperty: \"devices\" })\n * class DeviceContainer {\n * // Access via: this.devices.addModel(...)\n * }\n * ```\n */\n containerProperty?: string;\n\n /**\n * Whether to include convenience methods (getModel, addModel, removeModel, addAll, removeAll,\n * removeAndDestroy, removeAndDestroyAll).\n *\n * @default true\n * @example\n * ```typescript\n * @kosContainerAware({ includeMethods: false })\n * class Container {\n * // Only this.container property available, no convenience methods\n * }\n * ```\n */\n includeMethods?: boolean;\n\n /**\n * Whether to include reactive getters (models, data).\n *\n * @default true\n * @example\n * ```typescript\n * @kosContainerAware({ includeGetters: false })\n * class Container {\n * // No this.models or this.data getters, use this.container.data directly\n * }\n * ```\n */\n includeGetters?: boolean;\n\n /**\n * Container-specific configuration options passed to KosModelContainer constructor.\n *\n * @example\n * ```typescript\n * @kosContainerAware({\n * containerOptions: {\n * sortKey: \"name\",\n * indexMap: {\n * byType: \"deviceType\",\n * active: (device) => device.isOnline\n * },\n * parentId: \"custom-parent\", // Overrides automatic inference\n * extensionId: \"device-manager\",\n * maxCapacity: 1000, // Safety net for unbounded growth\n * evictionStrategy: \"fifo\"\n * }\n * })\n * ```\n */\n containerOptions?: {\n /** Default property to sort models by */\n sortKey?: keyof T;\n\n /**\n * Index mapping for efficient queries. Keys are index names, values are either:\n * - Property names (string keys) for simple property-based indexing\n * - Functions that return index keys for complex logic\n *\n * @example\n * ```typescript\n * indexMap: {\n * byStatus: \"connectionStatus\", // Property-based\n * byType: (device) => device.type.toLowerCase(), // Function-based\n * needsUpdate: (device) => device.version < \"2.0\" // Boolean logic\n * }\n * ```\n */\n indexMap?: Record<\n string,\n keyof T | ((model: T) => MaybePromise<string | string[] | undefined>)\n >;\n\n /**\n * Parent model ID for the container. If not provided, automatically uses\n * the modelId parameter from the model's constructor.\n *\n * @default Inferred from constructor modelId parameter\n */\n parentId?: string;\n\n /** Extension identifier for the container */\n extensionId?: string;\n\n /**\n * SAFETY NET: Maximum number of models this container can hold.\n * When exceeded, models are automatically evicted and destroyed based on evictionStrategy.\n *\n * **Primary use case**: Prevent memory overflow when cleanup handlers are missing or\n * data becomes inconsistent. Set higher than normal usage to catch edge cases.\n *\n * @example\n * ```typescript\n * containerOptions: {\n * maxCapacity: 10000, // Safety net: expect ~100-1000 normally\n * evictionStrategy: 'fifo'\n * }\n * ```\n */\n maxCapacity?: number;\n\n /**\n * Strategy for selecting which models to evict when maxCapacity is exceeded.\n *\n * - **fifo** (default): Remove oldest models first - best for event streams, logs\n * - **lru**: Remove least recently accessed models - best for caches\n * - **custom**: Use customEvictionFilter to determine eviction candidates\n *\n * @default 'fifo'\n */\n evictionStrategy?: \"fifo\" | \"lru\" | \"custom\";\n\n /**\n * Number of models to evict when maxCapacity is exceeded.\n * @default Math.max(10, Math.ceil(maxCapacity * 0.1))\n */\n evictionBatchSize?: number;\n\n /**\n * Custom filter function for 'custom' eviction strategy.\n * Should return models that are candidates for eviction.\n *\n * @example\n * ```typescript\n * customEvictionFilter: (models) => {\n * return models.filter(m =>\n * m.status === 'resolved' &&\n * Date.now() - m.resolvedAt > 3600000\n * );\n * }\n * ```\n */\n customEvictionFilter?: (models: T[]) => T[];\n };\n\n /**\n * Custom name for the reactive models array getter.\n *\n * @default \"models\"\n * @example\n * ```typescript\n * @kosContainerAware({ modelsProperty: \"items\" })\n * class Container {\n * get items() { return this.container.data; } // Instead of 'models'\n * }\n * ```\n */\n modelsProperty?: string;\n\n /**\n * Legacy compatibility mode. Uses '_models' as the container property name\n * instead of 'container' for backward compatibility with existing code.\n *\n * @default false\n * @deprecated Use containerProperty instead for new code\n */\n legacy?: boolean;\n}\n\n/**\n * Interface for models using @kosContainerAware decorator.\n *\n * **IMPORTANT**: Use TypeScript interface merging to add container management properties to your model class.\n * This provides full type safety and IntelliSense support for all injected container functionality.\n *\n * ## Interface Merging Pattern\n *\n * ```typescript\n * // 1. Declare interface merging BEFORE the class\n * interface MyContainerModelImpl extends KosContainerAware<ItemModel> {}\n *\n * // 2. Apply decorator and implement the class\n * @kosModel(\"my-container-model\")\n * @kosContainerAware<ItemModel>()\n * export class MyContainerModelImpl implements IKosDataModel {\n * // All container properties are now available with full type safety\n * }\n * ```\n *\n * ## Custom Container Property Name\n *\n * When using a custom `containerProperty` name, use `KosContainerAwareWithProp`:\n *\n * ```typescript\n * // For custom container property name\n * interface DeviceManagerImpl extends KosContainerAwareWithProp<DeviceModel, \"devices\"> {}\n *\n * @kosContainerAware<DeviceModel>({ containerProperty: \"devices\" })\n * class DeviceManagerImpl implements IKosDataModel {\n * // Access via: this.devices instead of this.container\n * }\n * ```\n *\n * ## Injected Properties and Methods\n *\n * The decorator automatically injects the following members (configurable via options):\n *\n * - **`container`**: Core KosModelContainer instance for direct access (or custom name via `containerProperty`)\n * - **`getModel(id)`**: Retrieve a model by ID from the container\n * - **`addModel(model)`**: Add a model to the container\n * - **`removeModel(id)`**: Remove a model from the container by ID (does not destroy)\n * - **`addAll(models)`**: Add multiple models to the container at once\n * - **`removeAll(ids)`**: Remove multiple models from the container by IDs (does not destroy)\n * - **`removeAndDestroy(id)`**: Remove a model from the container and destroy it\n * - **`removeAndDestroyAll(ids)`**: Remove multiple models from the container and destroy them\n * - **`models`**: Readonly KosModelContainer instance (compatible with IKosModelHolder)\n * - **`data`**: Reactive array of all model instances (compatible with IKosModelHolder)\n *\n * All injected getters are reactive and will automatically update UI components when container contents change.\n *\n * @template T The type of models contained in the container (must extend IKosDataModel)\n *\n * @example\n * ```typescript\n * // Basic usage with minimal configuration\n * interface DeviceContainerModelImpl extends KosContainerAware<DeviceModel> {}\n *\n * @kosModel(\"device-container-model\")\n * @kosContainerAware<DeviceModel>()\n * class DeviceContainerModelImpl implements IKosDataModel {\n * constructor(modelId: string, options: ContainerOptions, context: KosCreationContext) {\n * this.id = modelId;\n * // Container automatically injected with parentId: modelId\n * }\n *\n * // Use injected methods\n * addDevice(device: DeviceModel): void {\n * this.addModel(device); // Method injected by decorator\n * }\n *\n * // Use injected reactive getters\n * get deviceCount(): number {\n * return this.data.length; // Reactive array getter injected by decorator\n * }\n * }\n * ```\n *\n * @example\n * ```typescript\n * // Advanced usage with indexing and custom configuration\n * interface UserContainerModelImpl extends KosContainerAware<UserModel> {}\n *\n * @kosModel(\"user-container-model\")\n * @kosContainerAware<UserModel>({\n * containerOptions: {\n * indexMap: {\n * byRole: \"role\",\n * byDepartment: \"department\",\n * active: (user) => user.status === \"active\"\n * },\n * sortKey: \"lastName\"\n * }\n * })\n * class UserContainerModelImpl implements IKosDataModel {\n * // Access indexed data via injected container\n * getActiveUsers(): UserModel[] {\n * return this.container.getIndexByKey(\"active\", true);\n * }\n *\n * getUsersByRole(role: string): UserModel[] {\n * return this.container.getIndexByKey(\"byRole\", role);\n * }\n * }\n * ```\n *\n * @see {@link kosContainerAware} - The decorator function\n * @see {@link KosContainerAwareOptions} - Configuration options\n *\n * @kosService core.container-aware\n * @kosApiLevel 13\n */\nexport interface KosContainerAware<T extends IKosDataModel = IKosDataModel> {\n /**\n * Core container that manages the collection of models.\n * Provides methods to add, remove, and query model instances.\n * Automatically injected by @kosContainerAware decorator.\n */\n container: IKosModelContainer<T>;\n\n /**\n * Retrieves a model from the container by its ID.\n * @param id - The unique identifier of the model to retrieve\n * @returns The model instance if found, undefined otherwise\n */\n getModel(id: string): T | undefined;\n\n /**\n * Adds a model to the container.\n * @param model - The model instance to add\n */\n addModel(model: T): void;\n\n /**\n * Removes a model from the container by its ID.\n * @param id - The unique identifier of the model to remove\n */\n removeModel(id: string): void;\n\n /**\n * Adds multiple models to the container at once.\n * @param models - Array of model instances to add\n * @kosApiLevel 19\n */\n addAll(models: T[]): void;\n\n /**\n * Removes multiple models from the container by their IDs.\n * @param ids - Array of unique identifiers of the models to remove\n * @kosApiLevel 19\n */\n removeAll(ids: string[]): void;\n\n /**\n * Removes a model from the container and destroys it.\n * Convenience method that combines removeModel() and destroyKosModel().\n * @param id - The unique identifier of the model to remove and destroy\n * @kosApiLevel 19\n */\n removeAndDestroy(id: string): Promise<void>;\n\n /**\n * Removes multiple models from the container and destroys them.\n * Convenience method that combines removeAll() and destroyKosModel().\n * @param ids - Array of unique identifiers of the models to remove and destroy\n * @kosApiLevel 19\n */\n removeAndDestroyAll(ids: string[]): Promise<void>;\n\n /**\n * The container instance managing the models.\n * Readonly property that provides access to the KosModelContainer.\n * Compatible with IKosModelHolder interface.\n * Updates automatically when models are added or removed.\n */\n readonly models: IKosModelContainer<T>;\n\n /**\n * Reactive array of all model instances in the container.\n * This is the actual array of models, compatible with IKosModelHolder interface.\n * Updates automatically when models are added or removed.\n */\n data: T[];\n}\n\n/**\n * Base interface providing common container-aware methods and properties.\n * Used internally by both KosContainerAware and KosContainerAwareWithProp.\n *\n * @template T The type of models contained in the container\n *\n * @kosService core.container-aware\n * @kosApiLevel 13\n */\nexport interface KosContainerAwareBase<\n T extends IKosDataModel = IKosDataModel\n> {\n /**\n * Retrieves a model from the container by its ID.\n * @param id - The unique identifier of the model to retrieve\n * @returns The model instance if found, undefined otherwise\n */\n getModel(id: string): T | undefined;\n\n /**\n * Adds a model to the container.\n * @param model - The model instance to add\n */\n addModel(model: T): void;\n\n /**\n * Removes a model from the container by its ID.\n * @param id - The unique identifier of the model to remove\n */\n removeModel(id: string): void;\n\n /**\n * Adds multiple models to the container at once.\n * @param models - Array of model instances to add\n * @kosApiLevel 19\n */\n addAll(models: T[]): void;\n\n /**\n * Removes multiple models from the container by their IDs.\n * @param ids - Array of unique identifiers of the models to remove\n * @kosApiLevel 19\n */\n removeAll(ids: string[]): void;\n\n /**\n * Removes a model from the container and destroys it.\n * Convenience method that combines removeModel() and destroyKosModel().\n * @param id - The unique identifier of the model to remove and destroy\n * @kosApiLevel 19\n */\n removeAndDestroy(id: string): Promise<void>;\n\n /**\n * Removes multiple models from the container and destroys them.\n * Convenience method that combines removeAll() and destroyKosModel().\n * @param ids - Array of unique identifiers of the models to remove and destroy\n * @kosApiLevel 19\n */\n removeAndDestroyAll(ids: string[]): Promise<void>;\n\n /**\n * The container instance managing the models.\n * Readonly property that provides access to the KosModelContainer.\n * Compatible with IKosModelHolder interface.\n * Updates automatically when models are added or removed.\n */\n readonly models: IKosModelContainer<T>;\n\n /**\n * Reactive array of all model instances in the container.\n * This is the actual array of models, compatible with IKosModelHolder interface.\n * Updates automatically when models are added or removed.\n */\n data: T[];\n}\n\n/**\n * Interface for models using @kosContainerAware decorator with a custom container property name.\n *\n * Use this interface when you specify a custom `containerProperty` in the decorator options\n * to get proper type safety for the custom property name.\n *\n * @template T The type of models contained in the container\n * @template P The custom property name for the container (string literal type)\n *\n * @example\n * ```typescript\n * // Specify the custom property name \"devices\" in both the interface and decorator\n * interface DeviceManagerImpl extends KosContainerAwareWithProp<DeviceModel, \"devices\"> {}\n *\n * @kosModel(\"device-manager\")\n * @kosContainerAware<DeviceModel>({ containerProperty: \"devices\" })\n * class DeviceManagerImpl implements IKosDataModel {\n * constructor(modelId: string, options: ContainerOptions, context: KosCreationContext) {\n * this.id = modelId;\n * }\n *\n * addDevice(device: DeviceModel): void {\n * // Access container via custom property name\n * this.devices.addModel(device);\n * }\n *\n * getDeviceCount(): number {\n * // The 'data' property is still available\n * return this.data.length;\n * }\n * }\n * ```\n *\n * @example\n * ```typescript\n * // Custom property for user management\n * interface UserManagerImpl extends KosContainerAwareWithProp<UserModel, \"users\"> {}\n *\n * @kosContainerAware<UserModel>({\n * containerProperty: \"users\",\n * containerOptions: {\n * indexMap: {\n * byRole: \"role\"\n * }\n * }\n * })\n * class UserManagerImpl implements IKosDataModel {\n * getUsersByRole(role: string): UserModel[] {\n * // Access via this.users instead of this.container\n * return this.users.getIndexByKey(\"byRole\", role);\n * }\n * }\n * ```\n *\n * @kosService core.container-aware\n */\nexport type KosContainerAwareWithProp<\n T extends IKosDataModel = IKosDataModel,\n P extends string = \"container\"\n> = KosContainerAwareBase<T> & {\n [K in P]: IKosModelContainer<T>;\n};\n\n/**\n * Class decorator that automatically adds container management capabilities to a KOS model.\n *\n * This decorator eliminates the need for manual container setup by:\n * - **Adding a container property** (default: `container`) for managing model collections\n * - **Adding convenience methods** (`getModel`, `addModel`, `removeModel`, `addAll`, `removeAll`, `removeAndDestroy`, `removeAndDestroyAll`) if `includeMethods` is true (default)\n * - **Adding reactive getters** (`models`, `data`) if `includeGetters` is true (default)\n * - **Automatically inferring parentId** from the model's constructor `modelId` parameter\n * - **Registering container as @kosChild** for proper lifecycle management and cleanup\n * - **Supporting custom indexing** via `containerOptions.indexMap` for efficient queries\n *\n * ## Automatic Hierarchy Integration\n *\n * The decorator automatically registers the container as a `@kosChild`, ensuring:\n * - Proper lifecycle management (init, load, destroy)\n * - Automatic cleanup when parent model is destroyed\n * - Participation in the KOS reactive system\n * - Memory management and observer disposal\n *\n * ## TypeScript Usage\n *\n * **IMPORTANT**: Use TypeScript interface merging to get proper type information:\n *\n * ```typescript\n * interface MyContainerModelImpl extends KosContainerAware<MyItemModel> {}\n *\n * @kosContainerAware<MyItemModel>()\n * class MyContainerModelImpl implements IKosDataModel {\n * // All container properties are now available with full type safety\n * }\n * ```\n *\n * ## Model Lifecycle: removeModel vs removeAndDestroy\n *\n * The decorator provides both removal and destruction methods with different purposes:\n *\n * **removeModel(id) / removeAll(ids)** - Removes from container WITHOUT destroying:\n * - Use when moving models between containers\n * - Use when temporarily hiding models that may be re-added\n * - Use when model lifecycle is managed elsewhere\n * - Container handles cleanup of observers and metadata\n * - Model remains in memory and can be used elsewhere\n *\n * **removeAndDestroy(id) / removeAndDestroyAll(ids)** - Removes AND destroys:\n * - Use when permanently removing models from the system\n * - Use when models should be fully cleaned up and disposed\n * - Calls destroyKosModel() automatically after removal\n * - Ensures proper cleanup of all model resources\n * - Model is removed from framework and memory\n *\n * ```typescript\n * // Example: Explicit lifecycle control\n * @kosTopicHandler({ topic: \"/device/sensor/removed\" })\n * handleSensorRemoved(id: string) {\n * // Permanently remove - sensor is gone from system\n * await this.removeAndDestroy(id);\n * }\n *\n * // Example: Reorganization without destruction\n * moveSensorToArchive(id: string) {\n * const sensor = this.getModel(id);\n * if (sensor) {\n * this.removeModel(id); // Remove from active container\n * this.archive.addModel(sensor); // Add to archive container\n * }\n * }\n * ```\n *\n * ## Configuration Options\n *\n * ```typescript\n * @kosContainerAware<UserModel>({\n * containerProperty: \"users\", // Custom property name (default: \"container\")\n * includeMethods: true, // Include convenience methods (default: true)\n * includeGetters: true, // Include reactive getters (default: true)\n * modelsProperty: \"userList\", // Custom models getter name (default: \"models\")\n * legacy: false, // Use \"_models\" property name (default: false)\n * containerOptions: {\n * parentId: \"custom-parent\", // Override automatic parentId inference\n * sortKey: \"name\", // Default sorting key\n * extensionId: \"my-extension\", // Extension identifier\n * indexMap: { // Automatic indexing for efficient queries\n * byRole: \"role\", // Property-based index\n * byStatus: (user) => user.active ? \"active\" : \"inactive\", // Function-based index\n * admins: (user) => user.role === \"admin\" // Boolean index\n * }\n * }\n * })\n * ```\n *\n * @param options Configuration options for the decorator\n * @returns A class decorator that modifies the target class prototype\n *\n * @see {@link KosContainerAware} - Interface for TypeScript merging\n * @see {@link KosContainerAwareOptions} - Configuration options interface\n *\n * @example\n * ```typescript\n * // Minimal configuration - parentId automatically inferred\n * interface ItemContainerModelImpl extends KosContainerAware<ItemModel> {}\n *\n * @kosContainerAware<ItemModel>()\n * class ItemContainerModelImpl implements IKosDataModel {\n * id: string;\n *\n * constructor(modelId: string, options: ContainerOptions, context: KosCreationContext) {\n * this.id = modelId;\n * // Container automatically created with parentId: modelId\n * }\n * }\n *\n * // With index configuration\n * interface UserContainerModelImpl extends KosContainerAware<UserModel> {}\n *\n * @kosContainerAware<UserModel>({\n * containerOptions: {\n * indexMap: {\n * byRole: \"role\",\n * byStatus: (user) => user.status\n * }\n * }\n * })\n * class UserContainerModelImpl implements IKosDataModel {\n * constructor(modelId: string, options: ContainerOptions, context: KosCreationContext) {\n * this.id = modelId;\n * }\n * }\n *\n * // Legacy mode for backward compatibility\n * interface LegacyContainerModelImpl extends KosContainerAware<LegacyModel> {}\n *\n * @kosContainerAware<LegacyModel>({\n * legacy: true, // Uses '_models' as property name\n * containerOptions: {\n * sortKey: \"name\"\n * }\n * })\n * class LegacyContainerModelImpl implements IKosDataModel {\n * // Container available as this._models for backward compatibility\n * }\n * ```\n *\n * @category KOS Model Decorator\n * @since 2.1.0\n * @kosService core.container-aware\n * @kosApiLevel 13\n */\nexport function kosContainerAware<T extends IKosDataModel = IKosDataModel>(\n options?: KosContainerAwareOptions<T>\n): ClassDecorator {\n return (target: any) => {\n const containerProperty = options?.legacy\n ? \"_models\"\n : options?.containerProperty || \"container\";\n const includeMethods = options?.includeMethods !== false;\n const includeGetters = options?.includeGetters !== false;\n const modelsProperty = options?.modelsProperty || \"models\";\n const containerOptions = options?.containerOptions || {};\n\n // Add the ContainerAwareSetup configuration to the prototype\n // This will be processed by kosModel.ts during model instantiation\n target.prototype[ContainerAwareSetup] = {\n containerProperty,\n includeMethods,\n includeGetters,\n modelsProperty,\n containerOptions,\n legacy: options?.legacy || false,\n };\n\n return target;\n };\n}\n","import type { HttpMethod, ServiceRequestExecutor } from \"./kos-service-request\";\nimport type { ClientResponse } from \"../../util/kos-service-request\";\n\n/**\n * Symbol used to uniquely identify KosExecutionContext objects.\n * Decorators use this to reliably detect if the last parameter is an execution context.\n * @internal\n */\nexport const KOS_EXECUTION_CONTEXT = Symbol(\"KosExecutionContext\");\n\n/**\n * Execution context passed to decorated methods for accessing decorator-injected functionality.\n *\n * This context provides a type-safe way for decorators to inject runtime functionality\n * into methods without polluting the class interface or relying on magic parameters.\n *\n * Currently used by @kosServiceRequest to inject the $request executor.\n * Designed to be extensible for future decorators that need to inject runtime functionality.\n *\n * @example Using with @kosServiceRequest\n * ```typescript\n * @kosServiceRequest({\n * path: PATH_VM_INSTALL,\n * method: 'post'\n * })\n * async createRelease(\n * path: string,\n * keysetId?: string,\n * ctx: KosExecutionContext<paths, typeof PATH_VM_INSTALL, 'post'>\n * ): Promise<void> {\n * const [error, response] = await ctx.$request({\n * queryParams: { keySetId: keysetId },\n * body: { path }\n * });\n * if (error) throw new Error(error);\n * return response?.data;\n * }\n * ```\n *\n * @kosService core.service-request\n * @kosApiLevel 15\n */\nexport interface KosExecutionContext<\n Paths extends Record<string, any> = Record<string, any>,\n Path extends keyof Paths = string,\n Method extends HttpMethod = \"get\",\n Transformed = ClientResponse<Paths, Path, Method>\n> {\n /**\n * Symbol marker to identify this as a KosExecutionContext\n * @internal\n */\n [KOS_EXECUTION_CONTEXT]: true;\n\n /**\n * Service request executor (injected by @kosServiceRequest)\n * Executes the service request defined in the decorator configuration.\n */\n $request?: ServiceRequestExecutor<Paths, Path, Method>;\n\n /**\n * What the request yields once the decorator's `transform` has run — the raw\n * response when it declares none.\n *\n * Type-only: never populated at runtime. It exists so `executeServiceRequest`\n * can read the shape off the context, while `$request` keeps returning `any`\n * on its data half, as it always has.\n */\n readonly $transformed?: Transformed;\n\n /**\n * Future tracker ID string (injected by @kosFuture when trackerPolicy is 'context')\n * This is the tracker ID that can be used with future management utilities.\n */\n $tracker?: string;\n\n /**\n * Name of the decorated method (injected by @kosServiceRequest).\n *\n * Lets helpers attribute a failure to its method without the caller passing\n * the name in — a hand-written label silently outlives the rename that\n * invalidates it, and a stale one points at code that no longer exists.\n */\n $name?: string;\n}\n\n/**\n * Type guard to check if an object is a KosExecutionContext\n * @internal\n */\nexport function isKosExecutionContext(obj: any): obj is KosExecutionContext {\n return obj && typeof obj === \"object\" && KOS_EXECUTION_CONTEXT in obj;\n}\n","/* eslint-disable no-param-reassign */\nimport type {\n FutureAwareContainer,\n IFutureModel,\n} from \"../../../models/models/future/future-types\";\nimport { FutureContainerSetup } from \"./propKeys\";\n\n/**\n * @kosService core.future-aware\n * @kosApiLevel 13\n */\nexport interface KosFutureAwareOptions {\n /** Setup mode: 'full' includes all UI properties, 'minimal' only futureHandler. Default: 'full' */\n mode?: \"full\" | \"minimal\";\n /** Custom futureHandler property name. Default: 'futureHandler' */\n handlerProperty?: string;\n}\n\n/**\n * Interface for models using @kosFutureAware in minimal mode.\n * Use TypeScript interface merging to add the futureHandler property to your model class.\n *\n * @example\n * Add ESLint disable comment at top of file, then:\n * ```typescript\n * interface BackgroundServiceModelImpl extends KosFutureAwareMinimal {}\n *\n * kosFutureAware({ mode: 'minimal' })\n * class BackgroundServiceModelImpl implements IKosDataModel {\n * // futureHandler is now available via interface merging\n * }\n * ```\n *\n * @kosService core.future-aware\n * @kosApiLevel 13\n */\nexport interface KosFutureAwareMinimal<\n T extends object = Record<string, unknown>\n> {\n /**\n * Core future management container that handles Future lifecycle operations.\n * Provides methods to add, remove, and query Future instances.\n * Automatically injected by @kosFutureAware decorator.\n */\n futureHandler: FutureAwareContainer<T>;\n}\n\n/**\n * Interface for models using @kosFutureAware in full mode (default).\n * Use TypeScript interface merging to add all Future Container properties to your model class.\n *\n * @example\n * Add ESLint disable comment at top of file, then:\n * ```typescript\n * interface CopyLogsModelImpl extends KosFutureAwareFull<CopyProgress> {}\n *\n * kosFutureAware() // defaults to full mode\n * class CopyLogsModelImpl implements IKosDataModel {\n * // All Future Container properties are now available automatically\n *\n * onFutureUpdate?(future: IFutureModel<CopyProgress>): void {\n * // Access typed clientData\n * }\n * }\n * ```\n *\n * @kosService core.future-aware\n * @kosApiLevel 13\n */\nexport interface KosFutureAwareFull<T extends object = Record<string, unknown>>\n extends KosFutureAwareMinimal<T> {\n /**\n * Current active Future model instance containing operation details.\n * Undefined when no operation is active. Automatically updated when\n * operations start, progress, complete, or fail.\n */\n future?: IFutureModel<T>;\n\n /**\n * Current operation progress as a percentage (0-100).\n * Returns 0 when no Future is active. Updates automatically as the\n * Future operation progresses via WebSocket events.\n */\n progress: number;\n\n /**\n * Current operation status string representation.\n * Common values: \"IDLE\", \"IN_PROGRESS\", \"SUCCESS\", \"ERROR\", \"CANCELLED\".\n * Returns \"IDLE\" when no Future is active.\n */\n status: string;\n\n /**\n * Whether an operation is currently actively executing.\n * True when Future exists and has not reached an end state.\n * False when no Future exists or operation has completed/failed/cancelled.\n */\n isRunning: boolean;\n\n /**\n * Whether the current or most recent operation was cancelled.\n * Remains true after cancellation for status tracking until a new\n * operation starts. False if operation completed normally or failed.\n */\n isCancelled: boolean;\n\n /**\n * Cancels the currently running Future operation.\n * Sends cancellation request to the backend service managing the Future.\n * No-op if no Future is currently active.\n * @returns Promise that resolves when cancellation is acknowledged\n * @throws Error if cancellation request fails\n */\n cancelFuture(): Promise<void>;\n}\n\n/**\n * Class decorator that automatically adds Future Container capabilities to a KOS model.\n *\n * This decorator eliminates the need for manual Future Container setup by:\n * - Adding a futureHandler property for managing Future operations\n * - Adding reactive getters for future, progress, status, isRunning, isCancelled (in full mode)\n * - Adding cancelFuture method for canceling operations (in full mode)\n *\n * **Important**: Use TypeScript interface merging to get proper type information:\n *\n * ```typescript\n * // Add ESLint disable comment at top of file, then:\n * interface MyModelImpl extends KosFutureAwareFull<MyDataType> {}\n *\n * kosFutureAware()\n * class MyModelImpl implements IKosDataModel {\n * // All Future properties are now available with full type safety\n * }\n * ```\n *\n * Note: This decorator supports single Future operations. For models that need to manage\n * multiple concurrent Futures, use @kosMultiFutureAware (coming soon).\n *\n * @param options Configuration options for the decorator\n * @returns A class decorator\n *\n * @example\n * ```typescript\n * // Full mode example\n * interface DeviceOperationsModelImpl extends KosFutureAwareFull<OperationData> {}\n *\n * kosFutureAware()\n * class DeviceOperationsModelImpl implements IKosDataModel {\n * onFutureUpdate?(future: IFutureModel<OperationData>): void {\n * // Handle Future updates\n * }\n *\n * kosFuture()\n * async performOperation(): Promise<OperationData> {\n * return { result: \"done\" };\n * }\n * }\n *\n * // Minimal mode example\n * interface BackgroundServiceModelImpl extends KosFutureAwareMinimal {}\n *\n * kosFutureAware({ mode: 'minimal' })\n * class BackgroundServiceModelImpl implements IKosDataModel {\n * kosFuture()\n * async backgroundTask() {\n * return \"done\";\n * }\n * }\n * ```\n *\n * @category KOS Model Decorator\n * @since 2.0.0\n * @kosService core.future-aware\n * @kosApiLevel 13\n */\nexport function kosFutureAware(\n options?: KosFutureAwareOptions\n): ClassDecorator {\n return (target: any) => {\n const mode = options?.mode || \"full\";\n const handlerProperty = options?.handlerProperty || \"futureHandler\";\n\n // Add the FutureContainerSetup configuration to the prototype\n // This will be processed by kosModel.ts during model instantiation\n target.prototype[FutureContainerSetup] = {\n mode,\n handlerProperty,\n };\n\n return target;\n };\n}\n","/**\n * @kosService core.dependency\n */\nexport enum DependencyLifecycle {\n INIT = \"init\",\n LOAD = \"load\",\n READY = \"ready\",\n ACTIVATE = \"activate\",\n ONLINE = \"online\",\n}\n\n/**\n * Policy for handling dependency resolution failures.\n *\n * @kosService core.dependency\n *\n * All policies follow a lookup-first approach: The framework first checks if a model\n * with the specified ID already exists. If found and the type matches, it returns the\n * existing instance. Only if no existing model is found does the framework apply the\n * resolution policy below.\n *\n * Resolution runs twice: when the dependent is constructed, and again at the\n * dependency's `lifecycle` phase, which waits for the dependency to be ready.\n */\nexport enum DependencyResolutionPolicy {\n /**\n * CREATE (default) - After lookup fails, attempt to create a new instance of the model.\n * If the model requires options (via optionsRequired flag) and none are provided,\n * it will fail with an exception.\n */\n CREATE = \"create\",\n /**\n * CONTINUE - After lookup fails, do not attempt to create a new instance.\n * The property will be set to undefined. Log the failure but allow execution to continue.\n * Use for optional dependencies that can degrade gracefully.\n */\n CONTINUE = \"continue\",\n /**\n * FAIL - After lookup fails, do not attempt to create a new instance. At construction\n * the property is left undefined; at the dependency's lifecycle phase the lookup failure\n * throws with detailed diagnostic logging, and the dependent model fails that phase.\n * Use for critical dependencies that something else must create first.\n */\n FAIL = \"fail\",\n}\n\n/**\n * The parameters for the kosDependency decorator.\n *\n * @kosService core.dependency\n * @kosApiLevel 2\n */\nexport interface KosDependencyParams<Options = unknown> {\n /** The type of the model to be injected. */\n modelType: string;\n /** The id of the model to be injected. */\n id?: string;\n /** The options to be passed to the model constructor. */\n options?: Options;\n /**\n * The lifecycle phase that resolves the dependency and waits for it to be ready.\n * ACTIVATE and ONLINE dependencies are resolved again each time the phase repeats.\n */\n lifecycle?: DependencyLifecycle;\n /**\n * Policy for handling dependency resolution failures.\n *\n * All policies first attempt to look up an existing model instance. If found and the type\n * matches, the existing instance is returned. Only if lookup fails does the policy apply:\n *\n * - CREATE (default): Attempts to create model instance after lookup fails\n * - CONTINUE: Returns undefined after lookup fails, allows graceful degradation\n * - FAIL: Creates nothing; throws with detailed logging at the dependency's lifecycle\n * phase if lookup still fails, failing the dependent model\n * @kosApiLevel 16\n */\n resolutionPolicy?: DependencyResolutionPolicy;\n}\n","import { DependencyLifecycle } from \"../../types/kos-dependency\";\nimport type {\n KosMethodTypes,\n KosRequest,\n KosResponse,\n} from \"../services/browser-router\";\nimport { DependencyModels } from \"./propKeys\";\n\n/**\n * Symbol to store HTTP route metadata on the model prototype\n */\nexport const HttpRouteHandlers = Symbol(\"HttpRouteHandlers\");\n\n/**\n * Internal property name for the auto-injected BrowserRouter dependency\n */\nconst BROWSER_ROUTER_DEPENDENCY_KEY = \"__httpBrowserRouter\";\n\n/**\n * Interface for HTTP route configuration\n *\n * @kosService core.http-route\n * @kosApiLevel 12\n */\nexport interface IHttpRouteConfig {\n method: KosMethodTypes;\n path: string;\n handler: string; // Method name\n middleware?: Array<\n (req: KosRequest, res: KosResponse, next: () => void) => void\n >;\n}\n\n/**\n * Base function for creating HTTP method decorators\n */\nfunction createHttpMethodDecorator(method: KosMethodTypes) {\n return function httpMethodDecorator(path: string) {\n return function (\n target: any,\n propertyKey: string,\n descriptor: PropertyDescriptor\n ) {\n // Ensure the HttpRouteHandlers property exists on the target object\n target[HttpRouteHandlers] = target[HttpRouteHandlers] || [];\n\n // Store the route configuration\n const routeConfig: IHttpRouteConfig = {\n method,\n path,\n handler: propertyKey,\n };\n\n target[HttpRouteHandlers].push(routeConfig);\n\n // Automatically add BrowserRouter as a dependency if not already present\n // This ensures the BrowserRouter is available when HTTP routes are registered\n target[DependencyModels] = target[DependencyModels] || {};\n\n // Only add if not already present (to avoid overwriting user-defined dependencies)\n if (!target[DependencyModels][BROWSER_ROUTER_DEPENDENCY_KEY]) {\n // We need to import BrowserRouter type here\n // Using a dynamic reference to avoid circular dependency\n target[DependencyModels][BROWSER_ROUTER_DEPENDENCY_KEY] = {\n modelType: \"browser-router-model\", // This is the MODEL_TYPE from BrowserRouter\n lifecycle: DependencyLifecycle.INIT,\n };\n }\n\n return descriptor;\n };\n };\n}\n\n/**\n * Decorator for GET endpoints\n * @param path - The route path (e.g., \"/api/users/:id\")\n *\n * Supports PropKeys for dynamic path segments:\n * - {MODEL_ID} - replaced with the model's ID\n * - {PROP_propertyName} - replaced with model.propertyName value\n *\n * @example Basic usage:\n * ```typescript\n * @get(\"/api/users/:id\")\n * async getUser(req: KosRequest<\"/api/users/:id\">, res: KosResponse) {\n * const userId = req.params.id;\n * const user = await this.userService.getUser(userId);\n * res.status(200).send(user);\n * }\n * ```\n *\n * @example With PropKeys:\n * ```typescript\n * class TenantApiModel {\n * tenantId = \"acme-corp\";\n *\n * @get(\"/api/tenants/{PROP_tenantId}/users\")\n * async getTenantUsers(req: KosRequest, res: KosResponse) {\n * // Route registered as: /api/tenants/acme-corp/users\n * }\n *\n * @get(\"/api/models/{MODEL_ID}/config\")\n * async getModelConfig(req: KosRequest, res: KosResponse) {\n * // Route registered as: /api/models/<actual-model-id>/config\n * }\n * }\n * ```\n *\n * @kosService core.http-route\n * @kosApiLevel 12\n */\nexport const get = createHttpMethodDecorator(\"GET\");\n\n/**\n * Decorator for POST endpoints\n * @param path - The route path\n *\n * @example\n * ```typescript\n * @post(\"/api/users\")\n * async createUser(req: KosRequest<\"/api/users\">, res: KosResponse) {\n * const userData = req.body;\n * const newUser = await this.userService.createUser(userData);\n * res.status(201).send(newUser);\n * }\n * ```\n *\n * @kosService core.http-route\n * @kosApiLevel 12\n */\nexport const post = createHttpMethodDecorator(\"POST\");\n\n/**\n * Decorator for PUT endpoints\n * @param path - The route path\n *\n * @example\n * ```typescript\n * @put(\"/api/users/:id\")\n * async updateUser(req: KosRequest<\"/api/users/:id\">, res: KosResponse) {\n * const userId = req.params.id;\n * const updates = req.body;\n * const updatedUser = await this.userService.updateUser(userId, updates);\n * res.status(200).send(updatedUser);\n * }\n * ```\n *\n * @kosService core.http-route\n * @kosApiLevel 12\n */\nexport const put = createHttpMethodDecorator(\"PUT\");\n\n/**\n * Decorator for DELETE endpoints\n * @param path - The route path\n *\n * @example\n * ```typescript\n * @del(\"/api/users/:id\")\n * async deleteUser(req: KosRequest<\"/api/users/:id\">, res: KosResponse) {\n * const userId = req.params.id;\n * await this.userService.deleteUser(userId);\n * res.status(204).send();\n * }\n * ```\n *\n * @kosService core.http-route\n * @kosApiLevel 12\n */\nexport const del = createHttpMethodDecorator(\"DELETE\");\n\n/**\n * Alias for del decorator\n */\nexport const httpDelete = del;\n\n/**\n * Check if a model has HTTP route handlers\n */\nexport function hasHttpRouteHandlers(model: any): boolean {\n return !!model?.[HttpRouteHandlers] && model[HttpRouteHandlers].length > 0;\n}\n\n/**\n * Get HTTP route handlers from a model\n */\nexport function getHttpRouteHandlers(model: any): IHttpRouteConfig[] {\n return model?.[HttpRouteHandlers] || [];\n}\n","import { KosLog } from \"../log\";\n\nexport interface LoggerOptions {\n modelId?: string;\n modelTypeName?: string;\n component?: string;\n}\n\nexport class KosLoggerFactory {\n static create({ modelId, modelTypeName, component }: LoggerOptions) {\n const nameParts = [component ?? \"kos\", modelTypeName, modelId]\n .filter(Boolean)\n .join(\".\");\n\n return KosLog.createLogger({ name: nameParts });\n }\n}\n","/* eslint-disable no-param-reassign */\nimport type { KosContextLogger } from \"../kosModel\";\nimport { KosLoggerFactory } from \"../model/kos-logger-factory\";\nimport { KosViewModelSymbol, LoggerSetup } from \"./propKeys\";\n\n/**\n * @kosService core.logger-aware\n * @kosApiLevel 13\n */\nexport interface KosLoggerAwareOptions {\n /** Logger property name. Default: 'logger' */\n loggerProperty?: string;\n /** Logger context/group name. If not provided, uses model type */\n loggerContext?: string;\n}\n\n/**\n * Interface for models using @kosLoggerAware decorator.\n * Use TypeScript interface merging to add the logger property to your model class.\n *\n * @example\n * ```typescript\n * interface MyModelImpl extends KosLoggerAware {}\n *\n * @kosModel(\"my-model\")\n * @kosLoggerAware()\n * export class MyModelImpl implements IKosDataModel {\n * id: string;\n *\n * constructor(modelId: string, options: any, context: KosCreationContext) {\n * this.id = modelId;\n * // No logger setup needed - automatically injected!\n * }\n *\n * async performOperation() {\n * this.logger.info(\"Starting operation\"); // Direct access to logger\n * }\n * }\n * ```\n *\n * @kosService core.logger-aware\n * @kosApiLevel 13\n */\nexport interface KosLoggerAware {\n /**\n * KOS context logger for this model instance.\n * Automatically injected by the @kosLoggerAware decorator.\n * Shared across all instances of the same model type for optimal performance.\n * Provides structured logging with debug(), info(), warn(), and error() methods.\n * Logger context is automatically set to the model type name unless overridden.\n */\n logger: KosContextLogger;\n}\n\n/**\n * Class decorator that automatically injects a shared logger into a KOS model.\n *\n * This decorator eliminates the need for manual logger setup in constructors by:\n * - Creating a single shared logger per model type (not per instance)\n * - Using the KosLoggerFactory for consistent logger creation\n * - Following KOS naming conventions for logger context\n * - Providing optimal performance through logger reuse\n *\n * **Performance Note**: Creates one logger per model type, shared across all instances\n * of that type. This is much more efficient than per-instance logger creation.\n *\n * **Important**: Use TypeScript interface merging to get proper type information:\n *\n * ```typescript\n * interface MyModelImpl extends KosLoggerAware {}\n *\n * @kosModel(\"my-model\")\n * @kosLoggerAware()\n * export class MyModelImpl implements IKosDataModel {\n * // logger property is now available with full type safety\n * async doSomething() {\n * this.logger.debug(\"Doing something...\");\n * }\n * }\n * ```\n *\n * @param options Configuration options for the logger injection\n * @returns A class decorator\n *\n * @example\n * ```typescript\n * // Basic usage with default logger property\n * @kosLoggerAware()\n * class MyModel { }\n *\n * // Custom logger property name\n * @kosLoggerAware({ loggerProperty: 'log' })\n * class MyModel {\n * // this.log is available instead of this.logger\n * }\n *\n * // Custom logger context for specialized logging\n * @kosLoggerAware({ loggerContext: 'analytics' })\n * class AnalyticsModel {\n * // Logger uses \"analytics\" context instead of model type\n * }\n * ```\n *\n * @category KOS Model Decorator\n * @since 2.1.0\n * @kosService core.logger-aware\n * @kosApiLevel 13\n */\nexport function kosLoggerAware(\n options?: KosLoggerAwareOptions\n): ClassDecorator {\n return (target: any) => {\n const loggerProperty = options?.loggerProperty || \"logger\";\n const loggerContext = options?.loggerContext;\n\n // Store configuration on prototype so kosModel.ts can detect it\n target.prototype[LoggerSetup] = {\n loggerProperty,\n loggerContext,\n };\n\n // @kosModel sets modelTypeId; @kosViewModel stores its type under KosViewModelSymbol.\n const getModelType = () =>\n target.prototype.modelTypeId ??\n target.prototype[KosViewModelSymbol]?.type;\n\n // Create logger once per model type (not per instance)\n let sharedLogger: KosContextLogger;\n\n // Define getter that creates logger lazily when first accessed\n Object.defineProperty(target.prototype, loggerProperty, {\n get() {\n if (!sharedLogger) {\n const modelType = getModelType();\n sharedLogger = KosLoggerFactory.create({\n modelTypeName: loggerContext || modelType,\n component: \"kos-model\",\n });\n }\n return sharedLogger;\n },\n enumerable: false,\n configurable: false,\n });\n\n return target;\n };\n}\n","/* eslint-disable no-param-reassign */\nimport { ModelEffects } from \"./propKeys\";\n\n/**\n * @kosService core.model-effect\n * @kosApiLevel 2\n */\ninterface KosModelEffectProps<T = any> {\n dependencies: (model: T) => any[];\n /**\n * @kosApiLevel 3\n */\n options?: {\n fireImmediately?: boolean;\n };\n}\n/**\n * Decorator for defining a Kos model effect function within a Kos Data Model class.\n *\n * @param props - An object containing configuration parameters for the topic handler.\n * @returns A decorator function.\n *\n * @example\n * ```typescript\n * class MyKosDataModel implements IKosDataModel {\n * // ...\n *\n * @kosModelEffect()\n * handleModelEffect() {\n * // Handle the received topic payload here.\n * }\n * }\n * ```\n * @category KOS Model Decorator\n * @kosService core.model-effect\n * @kosApiLevel 2\n */\nexport function kosModelEffect<T = any>(props?: KosModelEffectProps<T>) {\n return (target: T, _propertyKey: string, descriptor: PropertyDescriptor) => {\n target[ModelEffects] = target[ModelEffects] || {};\n\n target[ModelEffects][_propertyKey] = {\n dependencies: props?.dependencies,\n options: props?.options,\n value: descriptor.value,\n };\n descriptor.value = function () {\n throw new Error(`Method ${_propertyKey} cannot be called directly.`);\n };\n };\n}\n","/**\n * Symbol marker indicating a model manages its own reload lifecycle.\n * Models with this marker are skipped by KosCore's destructive\n * unload() + reload() cycle, allowing them to handle reconnection\n * and state refresh through their own mechanisms (e.g., model effects,\n * topic handlers, or application-specific decorators like @kosStudioStateAware).\n */\nexport const SelfManagedReload = Symbol(\"SelfManagedReload\");\n\n/**\n * Class decorator that marks a model as self-managing its reload lifecycle.\n *\n * When KOS Core performs a reload (e.g., after reconnection), it calls unload()\n * then reload() on every model with a reload() method. unload() unloads the\n * model's children with it: their subscriptions, effects and HTTP routes are\n * disposed, but the child instances stay in place. Whatever the model's\n * reload() then does to its children (for example clearing and re-adding a\n * container) shows in the UI as skeleton flashes or lost selection state.\n *\n * Models decorated with @kosReloadAware manage their own reload through\n * reactive mechanisms (model effects watching for state changes) and use\n * incremental strategies like resolveContainerDeltas to update in place.\n *\n * @example\n * ```typescript\n * @kosModel(\"my-container-model\")\n * @kosReloadAware()\n * class MyContainerModel {\n * async reload() {\n * // Called by the model's own effect/decorator, NOT by KOS Core\n * await this.loadItems(); // uses resolveContainerDeltas\n * }\n * }\n * ```\n *\n * @category Decorator\n */\nexport function kosReloadAware(): ClassDecorator {\n return (target: any) => {\n target.prototype[SelfManagedReload] = true;\n };\n}\n","/**\n * (C) Copyright 2025, TCCC, All rights reserved.\n */\n\n/**\n * Rich error class for service request failures.\n *\n * Extends `Error` so it is backward-compatible with any code that expects\n * a plain `Error`. Adds HTTP response context so `onError` handlers in\n * `@kosServiceRequest` can inspect status codes, response bodies, and headers.\n *\n * @example\n * ```typescript\n * errorHandler: {\n * strategy: 'log',\n * defaultValue: [],\n * onError: (error, model) => {\n * if (error instanceof ServiceRequestError) {\n * console.error('HTTP', error.status, error.responseBody);\n * }\n * }\n * }\n * ```\n *\n * @category Service Request\n * @kosService core.service-request\n * @kosApiLevel 22\n */\nexport class ServiceRequestError extends Error {\n /** HTTP status code (e.g. 404, 500) */\n readonly status: number;\n\n /** HTTP status text (e.g. \"Not Found\") */\n readonly statusText: string;\n\n /**\n * Parsed response body (JSON) or raw text.\n * `undefined` if the body could not be read.\n */\n readonly responseBody: unknown;\n\n /** Response headers as a plain key/value map */\n readonly responseHeaders: Record<string, string>;\n\n constructor(\n message: string,\n details: {\n status: number;\n statusText: string;\n responseBody?: unknown;\n responseHeaders?: Record<string, string>;\n }\n ) {\n super(message);\n this.name = \"ServiceRequestError\";\n this.status = details.status;\n this.statusText = details.statusText;\n this.responseBody = details.responseBody;\n this.responseHeaders = details.responseHeaders ?? {};\n }\n}\n\n/**\n * Context captured from an HTTP error response.\n * Used internally to thread rich error info through the service request pipeline.\n * @internal\n * @kosService core.service-request\n * @kosApiLevel 22\n */\nexport interface ErrorResponseContext {\n status: number;\n statusText: string;\n responseBody: unknown;\n responseHeaders: Record<string, string>;\n}\n","import { KOS_MODEL_ID } from \"../../../common\";\nimport { KosLog } from \"../log\";\n\nconst log = KosLog.createLogger({ name: \"resolve-parameters\" });\ninterface ResolveParameterOptions {\n value: string | object;\n modelId: string;\n modelData: any;\n}\nexport const resolveParameters = ({\n value,\n modelId,\n modelData,\n}: ResolveParameterOptions) => {\n let _value = value;\n if (Array.isArray(_value)) {\n return [...(value as any)];\n } else if (typeof _value !== \"string\" && typeof _value !== \"object\") {\n return _value;\n } else if (typeof _value === \"object\") {\n _value = Object.keys(_value).reduce((acc, curr) => {\n acc[curr] = resolveParameters({\n value: _value[curr],\n modelId,\n modelData,\n });\n\n return acc;\n }, {});\n } else if (typeof _value === \"string\") {\n const propRegex = new RegExp(\"{PROP_(.+?)}\", \"g\");\n let _depId: string | undefined = _value?.includes(KOS_MODEL_ID)\n ? _value.replace(KOS_MODEL_ID, modelId)\n : _value;\n\n if (modelData) {\n let hasUnresolvedProp = false;\n const isOnlyPropKey = /^{PROP_.+?}$/.test(_depId);\n\n _depId = _depId.replace(propRegex, (match, propName) => {\n if (\n Object.getOwnPropertyNames(modelData).includes(propName) ||\n Object.getOwnPropertyNames(Object.getPrototypeOf(modelData)).includes(\n propName\n )\n ) {\n const prop = modelData[propName];\n if (prop !== null && prop !== undefined) {\n log.debug(`Resolved ${match} to ${prop}`);\n return prop;\n } else {\n const logLevel = isOnlyPropKey ? \"debug\" : \"warn\";\n log[logLevel](\n `Property ${propName} is null or undefined${\n isOnlyPropKey ? \"\" : \" in composite string\"\n }, marking for undefined return`\n );\n hasUnresolvedProp = true;\n return match;\n }\n }\n const logLevel = isOnlyPropKey ? \"debug\" : \"warn\";\n log[logLevel](\n `Property ${propName} not found in modelData${\n isOnlyPropKey ? \"\" : \" for composite string\"\n }`\n );\n return match;\n });\n\n if (hasUnresolvedProp) {\n return undefined;\n }\n }\n\n return _depId;\n } else {\n return _value;\n }\n\n return _value;\n};\n","import type { ErrorResponseContext } from \"../../util/service-request-error\";\nimport { ServiceRequestError } from \"../../util/service-request-error\";\nimport { KosLog } from \"../log\";\nimport { resolveParameters } from \"./resolve-parameters\";\n\nconst log = KosLog.createLogger({ name: \"ServiceRequestHelpers\" });\n/**\n * Helper functions for kosServiceRequest decorator.\n *\n * These functions are extracted to reduce complexity and improve maintainability\n * of the service request decorator implementation.\n */\n\n/**\n * Resolves all parameters for a service request.\n *\n * This helper function handles the complex parameter resolution logic including:\n * - Resolving PropKeys in path\n * - Calling function-valued pathParams, queryParams, body and requestOptions\n * with the model followed by the method's call arguments\n * - Merging decorator-defined params with runtime params\n * - Building the final API params object\n *\n * @param metadata - Service request metadata\n * @param modelInstance - The model instance (this context)\n * @param args - The arguments the decorated method was called with\n * @param runtimeOptions - Runtime execution options\n * @returns Resolved parameters for the API request\n */\nexport function resolveServiceRequestParameters(\n metadata: any,\n modelInstance: any,\n args: any[],\n runtimeOptions: any\n) {\n // Resolve PropKeys in path\n const resolvedPath = resolveParameters({\n value: metadata.path,\n modelId: modelInstance.id,\n modelData: modelInstance,\n }) as string;\n\n // Merge decorator-defined params with runtime params\n const finalPathParams = resolveParameters({\n modelId: modelInstance.id,\n modelData: modelInstance,\n value: {\n ...(typeof metadata.pathParams === \"function\"\n ? metadata.pathParams(modelInstance, ...args)\n : metadata.pathParams || {}),\n ...(runtimeOptions?.pathParams || {}),\n },\n });\n\n const finalQueryParams = resolveParameters({\n modelId: modelInstance.id,\n modelData: modelInstance,\n value: {\n ...(typeof metadata.queryParams === \"function\"\n ? metadata.queryParams(modelInstance, ...args)\n : metadata.queryParams || {}),\n ...(runtimeOptions?.queryParams || {}),\n },\n });\n\n const finalBody =\n runtimeOptions?.body ||\n (typeof metadata.body === \"function\"\n ? metadata.body(modelInstance, ...args)\n : metadata.body);\n\n // Merge decorator-defined requestOptions with runtime requestOptions\n const decoratorRequestOptions =\n typeof metadata.requestOptions === \"function\"\n ? metadata.requestOptions(modelInstance, ...args)\n : metadata.requestOptions;\n\n const finalRequestOptions = {\n ...(decoratorRequestOptions || {}),\n ...(runtimeOptions?.requestOptions || {}),\n };\n\n // Build params object for API client\n const apiParams: any = {};\n if (finalPathParams && Object.keys(finalPathParams).length > 0) {\n apiParams.path = finalPathParams;\n }\n if (finalQueryParams && Object.keys(finalQueryParams).length > 0) {\n apiParams.query = finalQueryParams;\n }\n\n return {\n resolvedPath,\n apiParams,\n finalBody,\n finalRequestOptions,\n };\n}\n\n/**\n * Executes an API method with the appropriate HTTP verb.\n *\n * This helper function handles the complexity of method selection and execution,\n * supporting GET, POST, PUT, and DELETE operations with proper parameter passing.\n *\n * @param API - The API client instance\n * @param method - HTTP method (get, post, put, delete)\n * @param path - Resolved API path\n * @param params - API parameters (path, query)\n * @param body - Request body (for POST, PUT, DELETE)\n * @param requestOptions - Additional request options\n * @returns Error-first tuple with response\n */\nexport async function executeApiMethod(\n API: any,\n method: string | undefined,\n path: string,\n params: any,\n body: any,\n requestOptions: any\n): Promise<[string | null, any, ErrorResponseContext?]> {\n const httpMethod = (method || \"get\").toLowerCase();\n const api = API as any;\n\n switch (httpMethod) {\n case \"get\":\n return await api.get(path, params, requestOptions);\n case \"post\":\n return await api.post(path, params, body, requestOptions);\n case \"put\":\n return await api.put(path, params, body, requestOptions);\n case \"delete\":\n return await api.delete(path, params, body, requestOptions);\n default:\n return await api.get(path, params, requestOptions);\n }\n}\n\n/**\n * Handles service request errors according to the configured error handling strategy.\n *\n * This helper function implements the error handling strategies defined in metadata:\n * - \"throw\": Return error tuple for caller to handle\n * - \"log\": Log error and return default value\n * - \"ignore\": Silently return default value\n * - \"default\": Return default value\n *\n * @param error - Error message from API call\n * @param response - API response (may contain status code)\n * @param errorHandler - Error handler configuration from metadata\n * @param modelInstance - The model instance (this context)\n * @returns Error-first tuple with default value or error\n */\nexport function handleServiceRequestError(\n error: string,\n response: any,\n errorHandler: any,\n modelInstance: any,\n errorContext?: ErrorResponseContext\n): [string | null, any] {\n if (!errorHandler) {\n return [error, null];\n }\n\n // Build a rich error object for the onError callback\n const richError = errorContext\n ? new ServiceRequestError(error, errorContext)\n : new ServiceRequestError(error, {\n status: response?.status ?? 0,\n statusText: error,\n });\n\n switch (errorHandler.strategy) {\n case \"log\":\n log.error(`Service request status ${richError.status} error: ${error}`);\n if (errorHandler.onError) {\n errorHandler.onError(richError, modelInstance);\n }\n return [null, errorHandler.defaultValue];\n case \"ignore\":\n if (errorHandler.onError) {\n errorHandler.onError(richError, modelInstance);\n }\n return [null, errorHandler.defaultValue];\n case \"default\":\n if (errorHandler.onError) {\n errorHandler.onError(richError, modelInstance);\n }\n return [null, errorHandler.defaultValue];\n case \"throw\":\n default:\n if (errorHandler.onError) {\n errorHandler.onError(richError, modelInstance);\n }\n return [error, null];\n }\n}\n","/**\n * (C) Copyright 2025, TCCC, All rights reserved.\n */\n\nimport { DependencyLifecycle } from \"../../types\";\nimport { ResponseCacheConfig } from \"../../types/service-response-store\";\nimport type { KosFetchOptions } from \"../../types/utils/kos-fetch\";\nimport type { ClientBody, ClientParams } from \"../../util/kos-service-request\";\nimport type { ServiceRequestError } from \"../../util/service-request-error\";\nimport { IKosDataModel } from \"../kosModel\";\nimport { type KosModelRegistrationType } from \"../registration/model-registration\";\nimport {\n type KosExecutionContext,\n KOS_EXECUTION_CONTEXT,\n isKosExecutionContext,\n} from \"./kos-execution-context\";\nimport {\n executeApiMethod,\n handleServiceRequestError,\n resolveServiceRequestParameters,\n} from \"./kos-service-request-helpers\";\n\n/**\n * @kosService core.service-request\n */\nexport type RequestOptions = Omit<KosFetchOptions, \"method\" | \"body\">;\n\n// Re-export for convenience\nexport type { KosExecutionContext };\n\n/**\n * Symbol for storing service request handlers metadata on model instances\n * @internal\n */\nexport const ServiceRequestHandlers = Symbol(\"ServiceRequestHandlers\");\n\n/**\n * WeakMap to store method-specific metadata for $serviceRequest\n * Key: The wrapped method function\n * Value: The service request metadata\n * @internal\n */\nconst methodMetadataMap = new WeakMap<\n // eslint-disable-next-line @typescript-eslint/ban-types\n Function,\n ServiceRequestMetadata<any, any, any, any, any>\n>();\n\n/**\n * HTTP methods supported by kosServiceRequest\n *\n * @kosService core.service-request\n */\nexport type HttpMethod =\n | \"get\"\n | \"GET\"\n | \"post\"\n | \"POST\"\n | \"put\"\n | \"PUT\"\n | \"delete\"\n | \"DELETE\";\n\n/**\n * API path type - string representing an API endpoint\n *\n * @kosService core.service-request\n */\nexport type ApiPath = string;\n\n/**\n * Configuration for field mapping in data transformation\n *\n * @kosService core.service-request\n * @kosApiLevel 15\n */\nexport interface FieldMapping {\n /**\n * Source field path (dot notation supported, e.g., 'data.user.name')\n */\n from: string;\n\n /**\n * Target field name in the model\n */\n to: string;\n\n /**\n * Optional transformation to apply\n * Built-in: 'string', 'number', 'boolean', 'date', 'json'\n * Custom: function name or transformer function\n */\n transform?: string | ((value: any) => any);\n\n /**\n * Whether this field is required\n */\n required?: boolean;\n\n /**\n * Default value if field is missing\n */\n default?: any;\n}\n\n/**\n * Configuration for error handling in service requests.\n *\n * Provides multiple strategies for handling request failures, enabling soft failures\n * with cached default values and error-first parameter patterns.\n *\n * @remarks\n * All strategies except 'throw' cache defaultValue in the response store, ensuring\n * consistency across model lifecycle. Lifecycle-triggered handlers receive error-first\n * parameters: (error, data), while method-driven requests use $request executor\n * returning tuple: [error, data].\n *\n * @example\n * ```typescript\n * // Soft failure with logging\n * @kosServiceRequest({\n * path: '/api/data',\n * errorHandler: {\n * strategy: 'log',\n * defaultValue: []\n * }\n * })\n * async loadData(error: string | null, data: DataType[]): Promise<void> {\n * if (error) {\n * this.logger.error(`Load failed: ${error}`);\n * }\n * this.processData(data); // Either real data or defaultValue\n * }\n * ```\n *\n * @category Service Request\n * @see {@link KosServiceRequestConfig} for complete decorator configuration\n * @kosService core.service-request\n * @kosApiLevel 15\n */\nexport interface ErrorHandlerConfig {\n /**\n * How to handle errors:\n *\n * - 'throw': Re-throw error (default) - handler not called, no caching\n *\n * - 'log': Log error, cache defaultValue, and call handler with (error, defaultValue)\n * Enables soft failure - log the error but continue processing with default data\n *\n * - 'ignore': Cache defaultValue and call handler with (error, defaultValue)\n * Soft failure without logging - silent recovery\n *\n * - 'default': Same as 'ignore' - cache defaultValue and call handler\n * (Kept for backward compatibility, behaves identically to 'ignore')\n *\n * All strategies except 'throw' cache defaultValue in response store for consistency.\n *\n * Note: For lifecycle requests, handler receives error-first parameters: (error, data)\n * For method-driven requests, $request executor returns tuple: [error, data]\n */\n strategy: \"throw\" | \"log\" | \"ignore\" | \"default\";\n\n /**\n * Default value to use when an error occurs.\n * Used with 'log', 'ignore', or 'default' strategies.\n * - Stored in response cache for subsequent access\n * - Passed to handler as second parameter: handler(errorMessage, defaultValue)\n */\n defaultValue?: any;\n\n /**\n * Custom error handler function called when a request fails.\n *\n * When the failure is an HTTP error response, `error` will be a\n * {@link ServiceRequestError} instance with `status`, `statusText`,\n * `responseBody`, and `responseHeaders` properties.\n *\n * For non-HTTP failures (network errors, timeouts), `error` is a\n * plain `Error`.\n *\n * @example\n * ```typescript\n * onError: (error, model) => {\n * if (error instanceof ServiceRequestError) {\n * console.error(`HTTP ${error.status}`, error.responseBody, error.responseHeaders);\n * }\n * }\n * ```\n */\n onError?: (error: Error | ServiceRequestError, model: IKosDataModel) => void;\n}\n\n/**\n * Configuration parameters for @kosServiceRequest decorator\n * Enables lifecycle-driven HTTP requests with declarative data transformation\n *\n * @typeparam Paths - The OpenAPI paths type (from your OpenAPI schema)\n * @typeparam Path - The specific API path being requested\n * @typeparam Method - The HTTP method type\n * @typeparam Response - The raw response type from the API\n * @typeparam TransformedResponse - The transformed response type after mappings\n *\n * @kosService core.service-request\n * @kosApiLevel 15\n */\nexport interface IKosServiceRequestParams<\n Paths extends Record<string, any> = Record<string, any>,\n Path extends keyof Paths = string,\n Method extends HttpMethod = \"get\",\n Response = any,\n TransformedResponse = Response\n> {\n /**\n * API path to request\n *\n * @example\n * path: '/api/kos/ingredients'\n * path: `/api/devices/${PROP_DEVICE_ID}/status` // with PropKey\n */\n path: Path;\n\n /**\n * HTTP method\n *\n * @default 'get'\n */\n method?: Method;\n\n /**\n * When to execute this request during model lifecycle\n *\n * If omitted, the request executes when the decorated method is called (method-driven).\n * If specified, the request executes automatically during the given lifecycle phase (lifecycle-driven).\n *\n * @example\n * // Lifecycle-driven (auto-execute during LOAD phase)\n * lifecycle: DependencyLifecycle.LOAD\n *\n * @example\n * // Method-driven (execute when method is called)\n * lifecycle: undefined // or omit entirely\n */\n lifecycle?: DependencyLifecycle;\n\n /**\n * Path parameters to expand in the URL\n * Strongly typed from OpenAPI schema\n * Can be static values, PropKey references, or a function. A function is\n * called with the model followed by the decorated method's call arguments;\n * a lifecycle-driven request has no call arguments, so it receives only the\n * model.\n *\n * @example\n * // Static value\n * pathParams: { deviceId: 'device-123' }\n *\n * @example\n * // PropKey reference (use PROP_ prefix)\n * pathParams: { deviceId: PROP_DEVICE_ID }\n *\n * @example\n * // From the method's call arguments: setStatus(deviceId, status)\n * pathParams: (model, deviceId, status) => ({ deviceId })\n */\n pathParams?:\n | (ClientParams<Paths, Path, Method> extends { path?: infer P } ? P : never)\n | ((\n model: IKosDataModel,\n ...args: any[]\n ) => ClientParams<Paths, Path, Method> extends { path?: infer P }\n ? P\n : never);\n\n /**\n * Query parameters\n * Strongly typed from OpenAPI schema\n * A function is called with the model followed by the decorated method's\n * call arguments; a lifecycle-driven request receives only the model.\n *\n * @example\n * // Static\n * queryParams: { includeMetadata: true, format: 'json' }\n *\n * @example\n * // From the method's call arguments: inspect(deviceId, debug)\n * queryParams: (model, deviceId, debug) => ({ debug })\n */\n queryParams?:\n | (ClientParams<Paths, Path, Method> extends { query?: infer Q }\n ? Q\n : never)\n | ((\n model: IKosDataModel,\n ...args: any[]\n ) => ClientParams<Paths, Path, Method> extends { query?: infer Q }\n ? Q\n : never);\n\n /**\n * Request body (for POST/PUT/DELETE)\n * Strongly typed from OpenAPI schema\n * A function is called with the model followed by the decorated method's\n * call arguments; a lifecycle-driven request receives only the model.\n *\n * @example\n * // Static body\n * body: { action: 'start' }\n *\n * @example\n * // From the method's call arguments: drive(vehicleType, speed)\n * body: (model, vehicleType, speed) => ({ vehicleType, speed })\n */\n body?:\n | ClientBody<Paths, Path, Method>\n | ((\n model: IKosDataModel,\n ...args: any[]\n ) => ClientBody<Paths, Path, Method>);\n\n /**\n * JSON path to iterate over in response\n * Creates models for each item in the array\n *\n * @example\n * iterateOver: 'data.ingredients' // Iterates response.data.ingredients array\n */\n iterateOver?: string;\n\n /**\n * Model registration object for creating instances from array items\n * Used with iterateOver to create child models using the builder pattern\n *\n * @example\n * modelFactory: IngredientModel // The registration object itself\n *\n * deprecated The old curried function signature is deprecated:\n * modelFactory?: (id: string) => (options: any) => IKosDataModel\n */\n modelFactory?:\n | KosModelRegistrationType<IKosDataModel, any>\n | ((id: string) => (options: any) => IKosDataModel); // Deprecated legacy signature\n\n /**\n * Function to extract the model ID from response data items\n * Required when using modelFactory if items don't have an 'id' field\n *\n * @example\n * idExtractor: (item) => item.ingredientId\n * idExtractor: (item) => `${item.type}-${item.index}`\n */\n idExtractor?: (item: any) => string;\n\n /**\n * Field mappings for data transformation\n * Same format as @kosTopicHandler mappings\n *\n * @example\n * mappings: [\n * { from: 'id', to: 'id' },\n * { from: 'ingredientId', to: 'ingredientId' },\n * { from: 'metadata.calories', to: 'calories', transform: 'number' }\n * ]\n */\n mappings?: FieldMapping[];\n\n /**\n * Transformation function for response data\n * Applied before mappings\n *\n * @example\n * transform: (response) => response.data\n */\n transform?: (response: Response) => TransformedResponse;\n\n /**\n * Condition to determine if request should execute\n *\n * @example\n * condition: (model) => model.isInitialized\n */\n condition?: (model: IKosDataModel) => boolean;\n\n /**\n * Error handling strategy\n *\n * @example\n * errorHandler: {\n * strategy: 'default',\n * defaultValue: [],\n * onError: (error, model) => model.logger.error('Failed to load', error)\n * }\n */\n errorHandler?: ErrorHandlerConfig;\n\n /**\n * Response caching configuration\n * Controls how long responses are stored and when they're cleaned up\n *\n * @default { retention: ResponseRetention.SINGLE }\n *\n * @example\n * // No caching - clear immediately after handler\n * cache: { retention: ResponseRetention.IMMEDIATE }\n *\n * @example\n * // Cache for 5 minutes\n * cache: { retention: ResponseRetention.TTL, ttl: 5 * 60 * 1000 }\n *\n * @example\n * // Keep for model lifetime\n * cache: { retention: ResponseRetention.PERMANENT }\n */\n cache?: ResponseCacheConfig;\n\n /**\n * Request options for controlling fetch behavior\n * These are merged with runtime options passed to ctx.$request()\n * Runtime options take precedence over decorator options\n *\n * @example\n * // Set default timeout and destination for all requests\n * requestOptions: {\n * destinationAddress: 'device-123',\n * timeout: 10000\n * }\n *\n * @example\n * // Dynamic from method arguments\n * requestOptions: (model, ...args) => ({\n * destinationAddress: model.deviceId,\n * headers: { 'X-Session': model.sessionId }\n * })\n * @kosApiLevel 18\n */\n requestOptions?:\n | RequestOptions\n | ((model: IKosDataModel, ...args: any[]) => RequestOptions);\n}\n\n/**\n * Metadata stored for each service request handler\n * @internal\n */\nexport interface ServiceRequestMetadata<\n Paths extends Record<string, any> = Record<string, any>,\n Path extends keyof Paths = string,\n Method extends HttpMethod = \"get\",\n Response = any,\n TransformedResponse = Response\n> extends IKosServiceRequestParams<\n Paths,\n Path,\n Method,\n Response,\n TransformedResponse\n > {\n /**\n * The method name that handles the response\n */\n handlerMethod: string;\n\n /**\n * The original handler function\n */\n // eslint-disable-next-line @typescript-eslint/ban-types\n originalHandler: Function;\n}\n\n/**\n * Runtime service request executor injected into method context\n * Allows imperative execution of the service request defined by the decorator\n *\n * @kosService core.service-request\n */\nexport interface ServiceRequestExecutor<\n Paths extends Record<string, any> = Record<string, any>,\n Path extends keyof Paths = string,\n Method extends HttpMethod = \"get\"\n> {\n (options?: {\n pathParams?: ClientParams<Paths, Path, Method> extends { path?: infer P }\n ? P\n : never;\n queryParams?: ClientParams<Paths, Path, Method> extends { query?: infer Q }\n ? Q\n : never;\n body?: ClientBody<Paths, Path, Method>;\n requestOptions?: RequestOptions;\n }): Promise<[string | null, any]>;\n}\n\n/**\n * Type alias for the service request executor function signature.\n * This executor is automatically passed as the last parameter to methods\n * decorated with @kosServiceRequest (without lifecycle).\n *\n * @example\n * ```typescript\n * type CreateReleaseExecutor = ServiceRequestExecutor<paths, typeof PATH_VM_INSTALL, 'post'>;\n * ```\n *\n * @kosService core.service-request\n */\nexport type ServiceRequestExecutorFn<\n Paths extends Record<string, any> = Record<string, any>,\n Path extends keyof Paths = string,\n Method extends HttpMethod = \"get\"\n> = ServiceRequestExecutor<Paths, Path, Method>;\n\n/**\n * Decorator for lifecycle-driven service requests within KOS models\n *\n * Eliminates service boilerplate by integrating HTTP requests directly into\n * the model lifecycle. Responses are cached in ServiceResponseStore for access\n * via utility functions, avoiding \"magic last parameter\" patterns.\n *\n * @param params - Configuration for the service request\n * @returns Method decorator\n *\n * @example Basic GET request during LOAD\n * ```typescript\n * @kosServiceRequest({\n * path: PATH_DEVICE_STATUS,\n * method: 'get',\n * lifecycle: DependencyLifecycle.LOAD,\n * cache: { retention: ResponseRetention.SINGLE }\n * })\n * private onStatusLoaded(): void {\n * const response = getServiceResponse(this, PATH_DEVICE_STATUS, 'get');\n * this.status = response?.status;\n * }\n * ```\n *\n * @example Method-driven request with execution context\n * ```typescript\n * @kosServiceRequest({\n * path: PATH_VM_INSTALL,\n * method: 'post',\n * requestOptions: {\n * timeout: 10000 // Decorator-level default timeout\n * }\n * })\n * async createRelease(\n * path: string,\n * keysetId?: string,\n * ctx: KosExecutionContext<paths, typeof PATH_VM_INSTALL, 'post'>\n * ): Promise<void> {\n * const [error, response] = await ctx.$request({\n * queryParams: { keySetId: keysetId },\n * body: { path },\n * requestOptions: {\n * destinationAddress: 'device-123', // Runtime options merged with decorator options\n * headers: { 'X-Custom-Header': 'value' }\n * }\n * });\n * if (error) throw new Error(error);\n * return response?.data;\n * }\n * ```\n *\n * @example Container model with iteration\n * ```typescript\n * @kosServiceRequest({\n * path: PATH_INGREDIENTS,\n * method: 'get',\n * lifecycle: DependencyLifecycle.LOAD,\n * iterateOver: 'data.ingredients',\n * modelFactory: Ingredient.factory,\n * mappings: [\n * { from: 'id', to: 'id' },\n * { from: 'name', to: 'name' }\n * ]\n * })\n * private onIngredientsLoaded(): void {\n * const response = getServiceResponse(this, PATH_INGREDIENTS, 'get');\n * // Mappings already applied to response data\n * response?.forEach(i => this.ingredients.addModel(i));\n * }\n * ```\n *\n * @category KOS Model Decorator\n * @kosService core.service-request\n * @kosApiLevel 15\n */\nexport function kosServiceRequest<\n Paths extends Record<string, any> = Record<string, any>,\n Path extends keyof Paths = string,\n Method extends HttpMethod = \"get\",\n Response = any,\n TransformedResponse = Response\n>(\n params: IKosServiceRequestParams<\n Paths,\n Path,\n Method,\n Response,\n TransformedResponse\n >\n) {\n return (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {\n // Ensure the ServiceRequestHandlers property exists on the target object\n target[ServiceRequestHandlers] = target[ServiceRequestHandlers] || {};\n\n const originalHandler = descriptor.value;\n\n // Store metadata for this service request\n const metadata: ServiceRequestMetadata<\n Paths,\n Path,\n Method,\n Response,\n TransformedResponse\n > = {\n ...params,\n handlerMethod: propertyKey,\n originalHandler,\n };\n\n // Keyed by method so a lifecycle handler and a reload may share one path.\n target[ServiceRequestHandlers][propertyKey] = metadata;\n\n // For method-driven requests (no lifecycle), wrap the handler to inject execution context\n if (!params.lifecycle) {\n const wrappedMethod = function (this: any, ...args: any[]) {\n const lastArg = args[args.length - 1];\n\n // Create executor bound to THIS SPECIFIC METHOD's metadata (inlined logic)\n const executor: ServiceRequestExecutor<Paths, Path, Method> = async (\n runtimeOptions\n ) => {\n // Get metadata for the CURRENT method (from WeakMap)\n const currentMetadata = methodMetadataMap.get(wrappedMethod);\n if (!currentMetadata) {\n throw new Error(\"Service request metadata not found for method\");\n }\n\n try {\n // Dynamically import API to avoid circular dependencies\n const { default: API } = await import(\n \"../../../models/utils/service\"\n );\n\n // Resolve all parameters using helper function\n const { resolvedPath, apiParams, finalBody, finalRequestOptions } =\n resolveServiceRequestParameters(\n currentMetadata,\n this,\n args,\n runtimeOptions\n );\n\n // Execute API request using helper function\n const result = await executeApiMethod(\n API,\n currentMetadata.method,\n resolvedPath,\n apiParams,\n finalBody,\n finalRequestOptions\n );\n const [error, response] = result;\n const errorContext = result[2];\n\n // Handle errors using helper function\n if (error) {\n return handleServiceRequestError(\n error,\n response,\n currentMetadata.errorHandler,\n this,\n errorContext\n );\n }\n\n // Apply transformation if specified\n let transformedResponse = response;\n if (currentMetadata.transform) {\n transformedResponse = currentMetadata.transform(response);\n }\n\n return [null, transformedResponse];\n } catch (error: any) {\n return [error.message || \"Unknown error\", null];\n }\n };\n\n // If last parameter is a KosExecutionContext, inject $request into it\n // Otherwise, create new context and append it\n if (isKosExecutionContext(lastArg)) {\n (lastArg as any).$request = executor;\n (lastArg as any).$name = String(propertyKey);\n return originalHandler.apply(this, args);\n } else {\n const context: any = {\n [KOS_EXECUTION_CONTEXT]: true,\n $request: executor,\n $name: String(propertyKey),\n };\n return originalHandler.apply(this, [...args, context]);\n }\n };\n\n // Store metadata in WeakMap keyed by wrapped method\n methodMetadataMap.set(wrappedMethod, metadata);\n\n descriptor.value = wrappedMethod;\n }\n\n // Return descriptor (modified for method-driven, unchanged for lifecycle-driven)\n // ServiceRequestManager will handle execution during lifecycle for lifecycle-driven requests\n return descriptor;\n };\n}\n","/**\n * Response retention policies for ServiceResponseStore\n * Controls how long service responses are cached and when they're cleaned up\n *\n * @kosService core.service-request\n */\nexport enum ResponseRetention {\n /**\n * Clear immediately after handler completes\n * Use for one-time operations with no caching needs\n *\n * Note: Response remains available during handler execution (including async handlers).\n * Cleanup happens AFTER the handler returns/resolves via ServiceRequestManager.\n */\n IMMEDIATE = \"immediate\",\n\n /**\n * Keep until next response for same path\n * Default behavior - previous response replaced on new request\n */\n SINGLE = \"single\",\n\n /**\n * Keep for specified duration (ms)\n * Automatic cleanup after TTL expires\n */\n TTL = \"ttl\",\n\n /**\n * Keep until model is destroyed\n * Use for data needed throughout model lifetime\n */\n PERMANENT = \"permanent\",\n\n /**\n * Keep until explicitly cleared\n * Manual cleanup required via clearServiceResponse()\n */\n MANUAL = \"manual\",\n}\n\n/**\n * Configuration for response caching behavior\n *\n * @kosService core.service-request\n * @kosApiLevel 15\n */\nexport interface ResponseCacheConfig {\n /**\n * Retention policy determining when response is cleaned up\n */\n retention: ResponseRetention;\n\n /**\n * Time-to-live in milliseconds (required for TTL retention)\n */\n ttl?: number;\n\n /**\n * For TTL retention: extend TTL instead of replacing data on new request\n *\n * When false (default): New request clears old data and stores new data with fresh TTL\n * When true: If cached data exists and hasn't expired, extend TTL without replacing data\n *\n * Use extendOnRefresh=true to avoid re-running expensive operations when cached data is still valid.\n *\n * @default false\n *\n * @example\n * // Replace on each request (default)\n * cache: { retention: ResponseRetention.TTL, ttl: 5 * 60 * 1000 }\n *\n * @example\n * // Extend TTL on refresh - avoid re-fetching if cache valid\n * cache: { retention: ResponseRetention.TTL, ttl: 5 * 60 * 1000, extendOnRefresh: true }\n */\n extendOnRefresh?: boolean;\n}\n\n/**\n * Replay strategy for baseline-delta race condition handling\n * Determines which queued events to replay after baseline loads\n *\n * @kosService core.topic-handler\n */\nexport enum ReplayStrategy {\n /**\n * Replay all queued events\n * Use for: State machines, audit trails requiring complete event history\n */\n ALL = \"all\",\n\n /**\n * Replay events received at or after baseline request was sent\n * Use for: High-frequency idempotent updates (quantities, sensor readings, status)\n */\n AFTER_REQUEST = \"after-request\",\n\n /**\n * Replay events received at or after baseline response was received\n * Use for: Low-frequency config where baseline likely includes recent changes\n */\n AFTER_RESPONSE = \"after-response\",\n\n /**\n * Discard all queued events\n * Use for: Baseline is always complete source of truth\n */\n NONE = \"none\",\n}\n\n/**\n * Baseline dependency configuration for topic handlers\n *\n * @kosService core.topic-handler\n * @kosApiLevel 15\n */\nexport interface BaselineDependency {\n /**\n * API path of the baseline request this handler depends on\n */\n path: string;\n\n /**\n * HTTP method of the baseline request\n * @default 'get'\n */\n method?: string;\n\n /**\n * Strategy for replaying queued events after baseline loads\n * @default ReplayStrategy.AFTER_REQUEST\n */\n replayStrategy?: ReplayStrategy;\n}\n\n/**\n * Cached response with metadata\n */\nexport interface CachedResponse<T = unknown> {\n /**\n * The response data\n */\n data: T;\n\n /**\n * When the response was cached (timestamp)\n * @deprecated Use requestedAt or receivedAt for temporal comparisons\n */\n timestamp: number;\n\n /**\n * When the HTTP request was sent (timestamp)\n * Used for baseline-delta temporal filtering\n */\n requestedAt: number;\n\n /**\n * When the HTTP response was received (timestamp)\n * Used for baseline-delta temporal filtering\n */\n receivedAt: number;\n\n /**\n * The API path this response came from\n */\n path: string;\n\n /**\n * The HTTP method used\n */\n method: string;\n\n /**\n * When this response expires (for TTL retention)\n */\n expiresAt?: number;\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable no-param-reassign */\nimport { DependencyLifecycle } from \"../../types\";\nimport { KosLog } from \"../log\";\nimport {\n StateEntryHandlers,\n StateExitHandlers,\n StateMachineSetup,\n} from \"./propKeys\";\n\nconst log = KosLog.createLogger({ name: \"kos-state-machine\" });\n/**\n * Configuration for a KOS state machine.\n *\n * @template TState Union type of valid state strings\n * @template TEvent Union type of valid event strings\n *\n * @example\n * ```typescript\n * const config: KosStateMachineConfig<'idle' | 'active', 'START' | 'STOP'> = {\n * initial: 'idle',\n * initializeAt: DependencyLifecycle.READY,\n * states: {\n * idle: { on: { START: 'active' } },\n * active: { on: { STOP: 'idle' } }\n * }\n * };\n * ```\n *\n * @kosService core.state-machine\n * @kosApiLevel 15\n */\nexport interface KosStateMachineConfig<\n TState extends string,\n TEvent extends string\n> {\n /**\n * The initial state when the state machine is initialized.\n * This state will be set when the FSM reaches its configured lifecycle phase.\n */\n initial: TState;\n\n /**\n * The lifecycle phase at which the state machine should be initialized.\n * Before this phase, the state property already holds `initial`, but\n * isFsmInitialized is false and transitions are refused.\n *\n * @default DependencyLifecycle.READY\n *\n * @example\n * ```typescript\n * // FSM initializes when model is ready (most common)\n * initializeAt: DependencyLifecycle.READY\n *\n * // FSM initializes only when UI activates the model\n * initializeAt: DependencyLifecycle.ACTIVATE\n *\n * // FSM initializes during model initialization (rare)\n * initializeAt: DependencyLifecycle.INIT\n *\n * // FSM initializes the first time the model goes online\n * initializeAt: DependencyLifecycle.ONLINE\n * ```\n */\n initializeAt?: DependencyLifecycle;\n\n /**\n * State machine definition mapping states to their allowed transitions.\n *\n * @example\n * ```typescript\n * states: {\n * idle: { on: { PREPARE: 'preparing' } },\n * preparing: { on: { READY: 'ready', ERROR: 'error' } },\n * ready: { on: { POUR: 'pouring' } },\n * pouring: { on: { COMPLETE: 'idle', ERROR: 'error' } },\n * error: { on: { RESET: 'idle' } }\n * }\n * ```\n */\n states: Record<\n TState,\n {\n /**\n * Mapping of events to target states.\n * When an event occurs in this state, transition to the target state.\n */\n on?: Partial<Record<TEvent, TState>>;\n\n /**\n * Event to auto-send when an async @kosStateEntry handler resolves.\n * Only triggers if the FSM is still in this state when the handler completes.\n *\n * @example\n * ```typescript\n * cancelling: {\n * on: { CANCELLED: 'cancelled', FAIL: 'error' },\n * onDone: 'CANCELLED', // auto-transition on success\n * onError: 'FAIL', // auto-transition on failure\n * }\n * ```\n */\n onDone?: TEvent;\n\n /**\n * Event to auto-send when an async @kosStateEntry handler rejects.\n * Only triggers if the FSM is still in this state when the handler fails.\n */\n onError?: TEvent;\n }\n >;\n}\n\n/**\n * Options for configuring state machine behavior.\n *\n * @kosService core.state-machine\n * @kosApiLevel 15\n */\nexport interface KosStateMachineOptions {\n /**\n * Property name for storing the current state.\n *\n * @default \"currentState\"\n */\n stateProperty?: string;\n\n /**\n * Whether to track state history.\n * When enabled, a stateHistory array is maintained with timestamps and events.\n *\n * @default false\n */\n trackHistory?: boolean;\n\n /**\n * Whether to throw errors on invalid transitions.\n * When false, invalid transitions are logged as warnings instead.\n *\n * @default true\n */\n throwOnInvalid?: boolean;\n\n /**\n * Optional function to compute the initial FSM state dynamically at instance creation time.\n * When provided, this function is called with the model instance and its return value\n * is used as the initial state instead of the static `initial` from the config.\n *\n * This is useful for ViewModels that wrap an existing model which may already be in\n * a non-default state (e.g., a connection that is already CONNECTED on app load).\n *\n * Note: Entry handlers are NOT called for the computed initial state since it\n * represents current state, not a transition.\n *\n * @param instance The model/ViewModel instance (after constructor, before makeAutoObservable)\n * @returns The initial FSM state to use\n *\n * @example\n * ```typescript\n * @kosStateMachine(fsmConfig, {\n * computeInitialState: (instance) => {\n * const state = instance.connection?.state;\n * return state === 'CONNECTED' ? 'connected' : 'inactive';\n * }\n * })\n * ```\n * @kosApiLevel 21\n */\n computeInitialState?: (instance: any) => string;\n}\n\n/**\n * Interface for models using the @kosStateMachine decorator.\n *\n * **IMPORTANT**: Use TypeScript interface merging to add FSM properties to your model class.\n * This provides full type safety and IntelliSense support for all injected FSM functionality.\n *\n * ## Interface Merging Pattern\n *\n * ```typescript\n * // 1. Define state and event types\n * type PourState = 'idle' | 'preparing' | 'ready' | 'pouring' | 'error';\n * type PourEvent = 'PREPARE' | 'READY' | 'POUR' | 'COMPLETE' | 'ERROR';\n *\n * // 2. Declare interface merging BEFORE the class\n * interface DispenserModelImpl extends KosStateMachineAware<PourState, PourEvent> {}\n *\n * // 3. Apply decorators and implement the class\n * @kosModel({ modelTypeId: \"dispenser-model\" })\n * @kosStateMachine<PourState, PourEvent>({\n * initial: 'idle',\n * initializeAt: DependencyLifecycle.READY,\n * states: {\n * idle: { on: { PREPARE: 'preparing' } },\n * preparing: { on: { READY: 'ready', ERROR: 'error' } },\n * ready: { on: { POUR: 'pouring' } },\n * pouring: { on: { COMPLETE: 'idle', ERROR: 'error' } },\n * error: {}\n * }\n * })\n * export class DispenserModelImpl implements IKosDataModel {\n * // All FSM properties are now available with full type safety\n * }\n * ```\n *\n * ## Lifecycle-Aware Initialization\n *\n * The FSM is uninitialized until the configured lifecycle phase:\n * - From construction: `currentState === initial`, `isFsmInitialized === false`;\n * `transition()` is refused and `canTransition()`, `isInState()` and\n * `allowedTransitions` report nothing\n * - At the phase: `isFsmInitialized === true` and the entry handler for\n * `initial` runs\n * - After `unload()`: `currentState === undefined` and `isFsmInitialized === false`\n * until the phase runs again\n *\n * ```typescript\n * @kosStateMachine({\n * initial: 'idle',\n * initializeAt: DependencyLifecycle.READY, // FSM starts when model is ready\n * states: { ... }\n * })\n * class MyModel {\n * async ready(): Promise<void> {\n * // Before this completes: this.currentState === 'idle', this.isFsmInitialized === false\n * // After this completes: this.isFsmInitialized === true\n * }\n * }\n * ```\n *\n * ## Injected Properties and Methods\n *\n * The decorator automatically injects the following members:\n *\n * - **`currentState`**: Current state (holds `initial` from construction, observable)\n * - **`isFsmInitialized`**: Boolean indicating if FSM has been initialized\n * - **`isTransitioning`**: Boolean indicating if a transition is in progress\n * - **`allowedTransitions`**: Computed array of valid events for current state\n * - **`transition(event)`**: Method to trigger state transitions\n * - **`canTransition(event)`**: Check if a transition is valid from current state\n * - **`isInState(state)`**: Check if currently in a specific state\n * - **`stateHistory`**: Array of historical states (if trackHistory enabled)\n *\n * All properties are reactive and will automatically update UI components when state changes.\n *\n * @template TState Union type of valid state strings\n * @template TEvent Union type of valid event strings\n *\n * @see {@link kosStateMachine} - The decorator function\n * @see {@link KosStateMachineConfig} - Configuration interface\n * @see {@link KosStateMachineOptions} - Options interface\n *\n * @kosService core.state-machine\n * @kosApiLevel 15\n */\nexport interface KosStateMachineAware<\n TState extends string,\n TEvent extends string\n> {\n /**\n * Current state of the state machine.\n * Observable property that updates automatically via @kosModel.\n * Always initialized to the initial state immediately.\n */\n currentState: TState;\n\n /**\n * Indicates whether the state machine has been initialized.\n * FSM initializes at the configured lifecycle phase (READY, ACTIVATE, ONLINE, etc.).\n *\n * - Before initialization: `false`, `currentState === initial`\n * - After initialization: `true`, and the entry handler for `initial` has run\n */\n readonly isFsmInitialized: boolean;\n\n /**\n * Indicates whether a state transition is currently in progress.\n * Observable property that updates during transitions.\n */\n isTransitioning: boolean;\n\n /**\n * Computed array of valid events that can be triggered from the current state.\n * Updates automatically when state changes.\n * Returns empty array if FSM is not initialized.\n */\n readonly allowedTransitions: TEvent[];\n\n /**\n * Trigger a state transition by event.\n *\n * @param event The event to trigger\n * @throws Error if FSM not initialized (unless `throwOnInvalid` is false)\n * @throws Error if transition is invalid (unless `throwOnInvalid` is false)\n *\n * @example\n * ```typescript\n * this.transition('START'); // idle -> active\n * this.transition('STOP'); // active -> idle\n * ```\n */\n transition(event: TEvent): void;\n\n /**\n * Check if a transition is valid from the current state.\n * Returns false if FSM is not initialized.\n *\n * @param event The event to check\n * @returns true if the transition is valid, false otherwise\n *\n * @example\n * ```typescript\n * if (this.canTransition('START')) {\n * this.transition('START');\n * }\n * ```\n */\n canTransition(event: TEvent): boolean;\n\n /**\n * Check if the state machine is currently in a specific state.\n * Returns false if FSM is not initialized.\n *\n * @param state The state to check\n * @returns true if currently in the specified state, false otherwise\n *\n * @example\n * ```typescript\n * if (this.isInState('idle')) {\n * console.log('System is idle');\n * }\n * ```\n */\n isInState(state: TState): boolean;\n\n /**\n * History of state transitions (if trackHistory is enabled).\n * Each entry contains the state, timestamp, and optional event that caused the transition.\n *\n * Only available when `trackHistory: true` is set in options.\n */\n stateHistory?: Array<{\n state: TState;\n timestamp: Date;\n event?: TEvent;\n }>;\n}\n\n/**\n * Class decorator that adds finite state machine capabilities to a KOS model.\n *\n * This decorator eliminates manual state management boilerplate by:\n * - **Adding lifecycle-aware FSM initialization** at configured phase (READY, ACTIVATE, ONLINE, etc.)\n * - **Managing state transitions** automatically with validation\n * - **Providing observable state** that integrates with @kosModel reactive system\n * - **Supporting entry/exit handlers** via @kosStateEntry and @kosStateExit decorators\n * - **Enabling state guards** via @kosStateGuard decorator\n *\n * ## Two-Level State System\n *\n * **Framework Lifecycle (Universal, Not Customizable):**\n * - CREATED → INIT → LOAD → READY → ACTIVATE → UNLOAD → DESTROY\n * - Managed by KOS framework\n * - Same for all models\n *\n * **Application FSM (This Decorator):**\n * - Runs WITHIN an active model\n * - Application-specific business logic\n * - Different for each model type\n * - Examples: Pour states, connection states, workflow states\n *\n * ## Lifecycle Integration\n *\n * The FSM initializes at the configured lifecycle phase:\n *\n * ```typescript\n * @kosStateMachine({\n * initial: 'idle',\n * initializeAt: DependencyLifecycle.READY, // Default\n * states: { ... }\n * })\n * ```\n *\n * - **INIT**: FSM needs to be active during model initialization (rare)\n * - **READY**: FSM operational as soon as data loaded (most common)\n * - **ACTIVATE**: FSM only relevant when UI is active (UI-bound models)\n * - **ONLINE**: FSM starts the first time the model goes online; a reconnect does not restart it\n *\n * ## TypeScript Usage\n *\n * **IMPORTANT**: Use TypeScript interface merging to get proper type information:\n *\n * ```typescript\n * type MyState = 'idle' | 'active';\n * type MyEvent = 'START' | 'STOP';\n *\n * interface MyModelImpl extends KosStateMachineAware<MyState, MyEvent> {}\n *\n * @kosStateMachine<MyState, MyEvent>({ ... })\n * class MyModelImpl implements IKosDataModel {\n * // All FSM properties are now available with full type safety\n * }\n * ```\n *\n * @param config State machine configuration\n * @param options Optional configuration for FSM behavior\n * @returns A class decorator that modifies the target class prototype\n *\n * @see {@link KosStateMachineAware} - Interface for TypeScript merging\n * @see {@link KosStateMachineConfig} - Configuration interface\n * @see {@link KosStateMachineOptions} - Options interface\n *\n * @example\n * ```typescript\n * // Basic FSM with default READY initialization\n * type PourState = 'idle' | 'pouring' | 'complete';\n * type PourEvent = 'START' | 'FINISH';\n *\n * interface PourModelImpl extends KosStateMachineAware<PourState, PourEvent> {}\n *\n * @kosModel({ modelTypeId: \"pour-model\" })\n * @kosStateMachine<PourState, PourEvent>({\n * initial: 'idle',\n * states: {\n * idle: { on: { START: 'pouring' } },\n * pouring: { on: { FINISH: 'complete' } },\n * complete: {}\n * }\n * })\n * class PourModelImpl implements IKosDataModel {\n * async ready(): Promise<void> {\n * // After this completes, FSM is initialized to 'idle'\n * }\n *\n * startPour(): void {\n * this.transition('START'); // idle -> pouring\n * }\n * }\n * ```\n *\n * @example\n * ```typescript\n * // UI-bound FSM with ACTIVATE initialization\n * type WorkflowState = 'draft' | 'review' | 'approved';\n * type WorkflowEvent = 'SUBMIT' | 'APPROVE' | 'REJECT';\n *\n * interface DocumentModelImpl extends KosStateMachineAware<WorkflowState, WorkflowEvent> {}\n *\n * @kosModel({ modelTypeId: \"document-model\" })\n * @kosStateMachine<WorkflowState, WorkflowEvent>({\n * initial: 'draft',\n * initializeAt: DependencyLifecycle.ACTIVATE, // UI-bound\n * states: {\n * draft: { on: { SUBMIT: 'review' } },\n * review: { on: { APPROVE: 'approved', REJECT: 'draft' } },\n * approved: {}\n * }\n * })\n * class DocumentModelImpl implements IKosDataModel {\n * // FSM only initializes when UI activates this model\n * }\n * ```\n *\n * @example\n * ```typescript\n * // FSM with history tracking\n * interface HistoryModelImpl extends KosStateMachineAware<'idle' | 'active', 'TOGGLE'> {}\n *\n * @kosStateMachine<'idle' | 'active', 'TOGGLE'>(\n * {\n * initial: 'idle',\n * states: {\n * idle: { on: { TOGGLE: 'active' } },\n * active: { on: { TOGGLE: 'idle' } }\n * }\n * },\n * {\n * trackHistory: true,\n * stateProperty: 'status'\n * }\n * )\n * class HistoryModelImpl implements IKosDataModel {\n * // Access via this.stateHistory\n * }\n * ```\n *\n * @category KOS Model Decorator\n * @since 2.1.0\n * @kosService core.state-machine\n * @kosApiLevel 15\n */\nexport function kosStateMachine<TState extends string, TEvent extends string>(\n config: KosStateMachineConfig<TState, TEvent>,\n options?: KosStateMachineOptions\n): ClassDecorator {\n return (target: any) => {\n // Store configuration on prototype\n // This will be processed by kosModel.ts during model instantiation\n target.prototype[StateMachineSetup] = {\n config: {\n ...config,\n // Default to READY if not specified\n initializeAt: config.initializeAt || DependencyLifecycle.READY,\n },\n initializeAtExplicit: config.initializeAt !== undefined,\n options: {\n stateProperty: options?.stateProperty || \"currentState\",\n trackHistory: options?.trackHistory || false,\n throwOnInvalid: options?.throwOnInvalid !== false,\n computeInitialState: options?.computeInitialState,\n },\n };\n\n return target;\n };\n}\n\n/**\n * Method decorator that marks a method as a state entry handler.\n * The decorated method will be called when the state machine enters the specified state.\n *\n * @param state The state to handle entry for\n * @returns A method decorator\n *\n * @example\n * ```typescript\n * @kosStateEntry('pouring')\n * handlePouringStart(): void {\n * this.logger.info('Pour started');\n * EventBus.publish(TOPIC_POUR_STARTED, { id: this.id });\n * }\n * ```\n *\n * @kosService core.state-machine\n * @kosApiLevel 15\n */\nexport function kosStateEntry<TState extends string>(\n state: TState\n): MethodDecorator {\n return (target: any, propertyKey: string | symbol) => {\n // Initialize the handlers map if it doesn't exist\n if (!target[StateEntryHandlers]) {\n target[StateEntryHandlers] = new Map<string, string>();\n }\n\n // Store the handler method name for this state\n target[StateEntryHandlers].set(state, propertyKey as string);\n };\n}\n\n/**\n * Method decorator that marks a method as a state exit handler.\n * The decorated method will be called when the state machine exits the specified state.\n *\n * @param state The state to handle exit for\n * @returns A method decorator\n *\n * @example\n * ```typescript\n * @kosStateExit('pouring')\n * handlePouringEnd(): void {\n * this.logger.info('Pour ended');\n * EventBus.publish(TOPIC_POUR_ENDED, { id: this.id });\n * }\n * ```\n *\n * @kosService core.state-machine\n * @kosApiLevel 15\n */\nexport function kosStateExit<TState extends string>(\n state: TState\n): MethodDecorator {\n return (target: any, propertyKey: string | symbol) => {\n // Initialize the handlers map if it doesn't exist\n if (!target[StateExitHandlers]) {\n target[StateExitHandlers] = new Map<string, string>();\n }\n\n // Store the handler method name for this state\n target[StateExitHandlers].set(state, propertyKey as string);\n };\n}\n\n/**\n * Options for @kosStateGuard decorator.\n *\n * @kosService core.state-machine\n * @kosApiLevel 15\n */\nexport interface KosStateGuardOptions<TState extends string> {\n /**\n * Array of states in which the decorated method can be called.\n * The method will throw an error (or log a warning) if called from any other state.\n */\n allowedStates: TState[];\n\n /**\n * Whether to throw an error on invalid state.\n * When false, logs a warning instead.\n *\n * @default true (uses the FSM's throwOnInvalid setting)\n */\n throwOnInvalid?: boolean;\n}\n\n/**\n * Method decorator that guards a method with state validation.\n * The decorated method can only be called when the state machine is in one of the allowed states.\n * The guard reads the property named by the state machine's `stateProperty` option.\n *\n * **IMPORTANT**: This decorator gracefully handles uninitialized FSM:\n * - If FSM is not yet initialized, the guard allows the method to proceed\n * - Once FSM is initialized, the guard enforces state validation\n *\n * @param options Guard configuration\n * @returns A method decorator\n *\n * @example\n * ```typescript\n * @kosStateGuard({ allowedStates: ['ready'] })\n * async pourBeverage(bevId: string): Promise<void> {\n * // This method can only be called when currentState === 'ready'\n * this.transition('POUR');\n * await this.deviceService.dispense(bevId);\n * this.transition('COMPLETE');\n * }\n * ```\n *\n * @kosService core.state-machine\n * @kosApiLevel 15\n */\nexport function kosStateGuard<TState extends string>(\n options: KosStateGuardOptions<TState>\n): MethodDecorator {\n return (\n _target: any,\n propertyKey: string | symbol,\n descriptor: PropertyDescriptor\n ) => {\n const originalMethod = descriptor.value;\n\n descriptor.value = function (this: any, ...args: any[]) {\n // Check if FSM is initialized\n const isFsmInitialized = this.isFsmInitialized;\n\n // If FSM is not initialized, allow the method to proceed\n // This handles the case where methods are called during model initialization\n if (!isFsmInitialized) {\n return originalMethod.apply(this, args);\n }\n\n const stateProperty =\n this[StateMachineSetup]?.options?.stateProperty || \"currentState\";\n const currentState = this[stateProperty];\n\n // Check if current state is allowed\n const isAllowed = options.allowedStates.includes(currentState);\n\n if (!isAllowed) {\n const message = `Method ${String(\n propertyKey\n )} cannot be called from state \"${currentState}\". Allowed states: ${options.allowedStates.join(\n \", \"\n )}`;\n\n // Use FSM's throwOnInvalid setting if not explicitly overridden\n const shouldThrow =\n options.throwOnInvalid !== undefined\n ? options.throwOnInvalid\n : this[StateMachineSetup]?.options?.throwOnInvalid !== false;\n\n if (shouldThrow) {\n throw new Error(message);\n } else {\n log.warn(message);\n return undefined; // Don't execute the method when state is invalid\n }\n }\n\n return originalMethod.apply(this, args);\n };\n\n return descriptor;\n };\n}\n","/* eslint-disable no-param-reassign */\nimport {\n DependencyLifecycle,\n KosDependencyParams,\n} from \"../../types/kos-dependency\";\nimport { DependencyModels } from \"./propKeys\";\n\nexport * as KosDependencyTypes from \"../../types/kos-dependency\";\n\n/**\n * This decorator is used to define a dependency on a Kos model.\n *\n * @param params The parameters for the decorator.\n * @param params.modelType The type of the model to be injected.\n * @param params.id The id of the model to be injected.\n * @param params.options The options to be passed to the model constructor.\n * @param params.lifecycle The lifecycle phase that resolves the dependency and waits for it\n * to be ready (default INIT). ACTIVATE and ONLINE resolve again each time the phase repeats.\n * @param params.resolutionPolicy What to do when no model with the id exists: CREATE (default)\n * creates it, CONTINUE leaves the property undefined, FAIL fails the dependent at the phase.\n *\n * @category KOS Model Decorator\n * @kosService core.dependency\n * @kosApiLevel 2\n * */\nexport const kosDependency =\n <Options = unknown>({\n /** The type of the model to be injected. */\n modelType,\n id,\n options,\n\n lifecycle,\n resolutionPolicy,\n }: KosDependencyParams<Options>) =>\n (target: {} | any, name: PropertyKey): any => {\n target[DependencyModels] = target[DependencyModels] || {};\n // eslint-disable-next-line max-len\n target[DependencyModels][name] = {\n modelType,\n id,\n options,\n lifecycle: lifecycle || DependencyLifecycle.INIT,\n resolutionPolicy,\n };\n };\n","import {\n kosAutoEffect,\n KosLog,\n kosObservable,\n makeAutoObservable,\n} from \"../../../core\";\nimport {\n FutureAwareContainer,\n FutureContainer,\n IFutureModel,\n type MultiFutureAware,\n} from \"./future-types\";\n\n/**\n * Future handler for managing multiple concurrent long-running operations.\n *\n * Provides comprehensive lifecycle management for models that coordinate multiple\n * device operations simultaneously. Each Future is tracked with its own alias\n * and receives automatic progress updates and cleanup when operations complete.\n *\n * @example Managing Multiple Operations\n * ```typescript\n * @kosModel(\"device-maintenance-model\")\n * export class DeviceMaintenanceModel implements FutureContainer {\n * futureHandler: MultipleFutureHandler;\n *\n * constructor(modelId: string, options: any, context: KosCreationContext) {\n * this.id = modelId;\n * this.futureHandler = new MultipleFutureHandler(this);\n * }\n *\n * async startCalibration(deviceId: string): Promise<CalibrationResult> {\n * const future = await this.createFuture('/device/calibrate', { deviceId });\n * this.futureHandler.addFuture(future, `calibration-${deviceId}`);\n * return future;\n * }\n *\n * async startCleaning(deviceId: string): Promise<CleaningResult> {\n * const future = await this.createFuture('/device/clean', { deviceId });\n * this.futureHandler.addFuture(future, `cleaning-${deviceId}`);\n * return future;\n * }\n *\n * onFutureUpdate(future: IFutureModel): void {\n * // Handle progress updates from any managed Future\n * console.log(`${future.id}: ${future.progress}% complete`);\n * }\n * }\n * ```\n *\n * @group KOS Model\n * @category Asynchronous Operations\n */\nexport class MultipleFutureHandler<T extends {} = Record<string, unknown>>\n implements FutureAwareContainer<T>, MultiFutureAware<T>\n{\n private futures: Map<string, IFutureModel<T>>;\n private defaultContext: string;\n private context: string;\n private disposers = new Map<string, () => void>();\n private container?: FutureContainer<T>;\n constructor(container?: FutureContainer<T>, defaultContext?: string) {\n this.futures = kosObservable.map(new Map<string, IFutureModel<T>>());\n this.context = \"\";\n this.defaultContext = defaultContext || \"\";\n this.container = container;\n makeAutoObservable(this);\n }\n\n get allFutures() {\n return Array.from(this.futures.values());\n }\n\n get future() {\n return this.futures.get(this.defaultContext);\n }\n addFuture(future: IFutureModel<T>, alias?: string) {\n this.futures.set(alias || future.id, future);\n this.context = alias || future.id;\n // Capture alias in closure for callback\n const capturedAlias = alias;\n const disposer = kosAutoEffect(() => {\n if (future.endState || future.progress) {\n this.container?.onFutureUpdate?.(future, capturedAlias);\n }\n });\n this.disposers.set(alias || future.id, disposer);\n }\n\n removeFuture(alias?: string) {\n this.futures.delete(alias || this.context);\n this.disposers.get(alias || this.context)?.();\n this.disposers.delete(alias || this.context);\n }\n\n getFuture(alias?: string) {\n const future = this.futures.get(alias || this.context);\n return future;\n }\n\n get futureMap() {\n return this.futures;\n }\n}\n\n/**\n * Future handler for managing single long-running operations with simplified API.\n *\n * Provides streamlined lifecycle management for models that typically handle\n * one operation at a time. Automatically tracks progress and provides reactive\n * status information for UI integration.\n *\n * @example Single Operation Management\n * ```typescript\n * @kosModel(\"brewing-system-model\")\n * export class BrewingSystemModel implements FutureContainer {\n * futureHandler: FutureHandler;\n *\n * constructor(modelId: string, options: any, context: KosCreationContext) {\n * this.id = modelId;\n * this.futureHandler = new FutureHandler(this);\n * }\n *\n * async startBrewingCycle(recipe: Recipe): Promise<BrewingResult> {\n * const future = await this.createFuture('/brewing/start', { recipe });\n * this.futureHandler.addFuture(future);\n * return future;\n * }\n *\n * get isOperationActive(): boolean {\n * return this.futureHandler.status !== 'NOT_RESOLVED';\n * }\n *\n * get operationProgress(): number {\n * return this.futureHandler.progress;\n * }\n *\n * onFutureUpdate(future: IFutureModel): void {\n * // Handle progress updates from the active Future\n * console.log(`Brewing: ${future.progress}% complete`);\n * }\n * }\n * ```\n *\n * @group KOS Model\n * @category Asynchronous Operations\n */\nexport class FutureHandler<T extends object = Record<string, unknown>>\n implements FutureAwareContainer<T>\n{\n private disposer?: () => void;\n\n private _future?: IFutureModel<T>;\n private container?: FutureContainer<T>;\n constructor(container?: FutureContainer<T>) {\n this._future = undefined;\n this.container = container;\n makeAutoObservable(this);\n }\n removeFuture() {\n this._future = undefined;\n this.disposer?.();\n this.disposer = undefined;\n }\n\n get future() {\n return this._future;\n }\n getFuture(): IFutureModel<T> | undefined {\n return this._future;\n }\n\n addFuture(future: IFutureModel<T>) {\n this._future = future;\n\n const disposer = kosAutoEffect(() => {\n if (future.endState || future.progress) {\n this.container?.onFutureUpdate?.(future);\n }\n });\n this.disposer = disposer;\n }\n\n onFutureUpdate?: ((future: IFutureModel<T>) => void) | undefined;\n\n get allFutures() {\n return this._future ? [this._future] : [];\n }\n get timeRemaining() {\n return this._future?.timeRemaining || \"\";\n }\n\n get status() {\n return this._future?.status || \"NOT_RESOLVED\";\n }\n\n get progress() {\n return this._future?.progress || -1;\n }\n\n async cancel() {\n if (this._future) {\n try {\n await this._future.cancelFuture();\n } catch (e) {\n KosLog.error(e);\n throw e;\n }\n }\n }\n}\n","import type { TroubleModel } from \"../types\";\n\nexport const troubleByTypeReducer = (\n acc: Record<string, TroubleModel[]>,\n trouble: TroubleModel\n) => {\n const type = trouble.type;\n if (!acc[type]) {\n acc[type] = [];\n }\n acc[type].push(trouble);\n return acc;\n};\n","import { IAtom, action, createAtom, makeObservable, observable } from \"mobx\";\n\n/**\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport const KosObservableData = Symbol(\"KosObservableData\");\nconst REVISION = Symbol(\"revision\");\n\nclass ObservableDataMap<T extends Record<string | number | symbol, any>> {\n private map: Map<keyof T, T[keyof T]>;\n [REVISION] = 1;\n\n private atomMap: Map<keyof T, IAtom> = new Map();\n constructor() {\n this.map = observable.map(new Map<keyof T, T[keyof T]>());\n // Make revision observable using Symbol key\n makeObservable(this, { [REVISION]: observable });\n }\n\n // Set a value in the map\n setValue<K extends keyof T>(key: K, value: T[K]): void {\n const hadKey = this.map.has(key);\n this.map.set(key, value);\n if (!hadKey) {\n action(() => {\n this[REVISION]++;\n })();\n }\n }\n\n // Get a value from the map\n getValue<K extends keyof T>(key: K): T[K] | undefined {\n return this.map.get(key);\n }\n\n has(key: keyof T): boolean {\n return this.map.has(key);\n }\n\n get entries(): [keyof T, T[keyof T]][] {\n return Array.from(this.map.entries());\n }\n\n // Getter for keys in the map\n get keys(): string[] {\n // Access revision to make this getter reactive to structural changes\n // eslint-disable-next-line no-unused-expressions\n this[REVISION];\n return Array.from(this.map.keys()) as string[];\n }\n\n get values(): T[keyof T][] {\n return Array.from(this.map.values());\n }\n\n // Create a proxy handler to intercept property accesses\n private proxyHandler: ProxyHandler<ObservableDataMap<T>> = {\n get: (target, property: any) => {\n // Handle direct property access including revision symbol\n if (property === REVISION || target[property] !== undefined) {\n return target[property];\n }\n if (this.atomMap.has(property)) {\n if (this.atomMap.get(property)?.reportObserved()) {\n return this.getValue(property);\n }\n }\n return this.getValue(property);\n }, // Retrieve value from the map // Retrieve value from the map\n set: (_target, property: keyof T, value: T[keyof T]) => {\n const hadKey = this.map.has(property);\n this.setValue(property, value); // Set value in the map\n if (!this.atomMap.has(property)) {\n this.atomMap.set(property, createAtom(property.toString()));\n }\n this.atomMap.get(property)?.reportChanged(); // Notify MobX that the value has changed\n if (!hadKey) {\n // Revision was already incremented in setValue, no need to increment again\n }\n return true;\n },\n ownKeys: (_target) => {\n const mapKeys = Array.from(this.map.keys()) as (string | symbol)[];\n // Include REVISION symbol - it's an own property of the target\n return [...mapKeys, REVISION];\n },\n getOwnPropertyDescriptor: (_target, property) => {\n // Make all map keys appear as enumerable, configurable properties\n // This is required for Object.keys() to include them\n if (this.map.has(property as keyof T)) {\n return {\n enumerable: true,\n configurable: true,\n writable: true,\n value: this.getValue(property as keyof T),\n };\n }\n // Handle REVISION symbol\n if (property === REVISION) {\n return {\n enumerable: false,\n configurable: true,\n writable: true,\n value: _target[REVISION],\n };\n }\n return undefined;\n },\n };\n\n setValues(initialData?: T) {\n if (initialData) {\n Object.keys(initialData).forEach((key) => {\n this.setValue(key as keyof T, initialData[key]);\n });\n }\n }\n // Create a proxy for the class instance\n get proxy(): T {\n return new Proxy(this, this.proxyHandler) as unknown as KosData<T>;\n }\n}\n\nObservableDataMap.prototype[KosObservableData] = true;\n\ntype Constructor<T> = new (...args: any[]) => T;\n\nfunction createObservableData<T extends Record<string, any>>(\n BaseClass: Constructor<ObservableDataMap<T>>,\n initialData?: T\n): Constructor<ObservableDataMap<T>> {\n return new Proxy(BaseClass, {\n construct: (_target, args) => {\n const instance = new BaseClass(...args);\n instance.setValues(initialData);\n return instance.proxy as unknown as T & {\n setValues: (initialData?: T) => void;\n };\n },\n });\n}\n\n/**\n * @kosService core.utils\n */\nexport type KosData<T extends Record<any, any>> = T & {\n setValues: (initialData?: T) => void;\n keys: (keyof T)[];\n entries: [keyof T, T[keyof T]][];\n values: T[keyof T][];\n has: (key: keyof T) => boolean;\n};\n\n/**\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport const ObservableData = <T extends Record<string, any>>(\n initialData?: T\n): KosData<T> => {\n const od = createObservableData(ObservableDataMap<T>, initialData);\n return new od(initialData) as unknown as KosData<T>;\n};\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { RendererConstructor } from \"../../../models/models/canvas-dispatcher\";\nimport { IndexMapper } from \"../kos-container-index\";\nimport { IKosDataModel } from \"../kosModel\";\nimport { KosLog } from \"../log\";\n\n/**\n * @kosService core.extension\n */\nexport type ExtensionType = number | string | boolean;\n/**\n * @kosService core.extension\n */\nexport type FailurePolicy = \"throw\" | \"continue\";\n\n/**\n * @kosService core.extension\n * @kosApiLevel 20\n */\nexport interface ExtensionOptions {\n failurePolicy?: FailurePolicy;\n}\n\nconst DEFAULT_EXTENSION_OPTIONS: Required<ExtensionOptions> = {\n failurePolicy: \"throw\",\n};\n\n/**\n * @kosService core.extension\n * @kosApiLevel 20\n */\nexport class ExtensionException extends Error {\n public readonly extensionId: string;\n public readonly extensionType: string;\n public override readonly cause: unknown;\n\n constructor(\n extensionId: string,\n extensionType: string,\n cause: unknown,\n message?: string\n ) {\n super(\n message || `Extension failure in ${extensionType} for id \"${extensionId}\"`\n );\n this.name = \"ExtensionException\";\n this.extensionId = extensionId;\n this.extensionType = extensionType;\n this.cause = cause;\n }\n}\n\n/**\n * @kosService core.extension\n */\nexport type DataMapper<\n I extends object = any,\n O extends object = any,\n C extends object = any\n> = (input: I, context?: C) => Promise<O>;\n\ninterface RegisteredDataMapper {\n mapper: DataMapper;\n options: Required<ExtensionOptions>;\n}\n\n/**\n * @kosService core.extension\n */\nexport type PropertyMapper<\n I extends object = any,\n O extends ExtensionType = any,\n C extends object = any\n> = (input: I, context?: C) => O;\n\ninterface RegisteredPropertyMapper {\n mapper: PropertyMapper;\n options: Required<ExtensionOptions>;\n}\n\n/**\n * @kosService core.extension\n */\nexport type DataLoader<I extends object = any, O extends object = any> = (\n input: I\n) => Promise<O>;\n\ninterface RegisteredDataLoader {\n loader: DataLoader;\n options: Required<ExtensionOptions>;\n}\n\n/**\n * @kosService core.extension\n */\nexport type IndexExtension<T extends IKosDataModel = any> = Record<\n string,\n keyof T | IndexMapper<any>\n>;\n\n/**\n * @kosService core.extension\n * @kosApiLevel 10\n */\nexport const EXTENSION_CANVAS_RENDERER = \"canvas-renderer\";\n/**\n * @kosService core.extension\n * @kosApiLevel 22\n */\nexport const EXTENSION_FUTURE_LIFECYCLE_WRAPPER =\n \"kos.declarative.futureLifecycleWrapper\";\nconst dataMappers = new Map<string, RegisteredDataMapper[]>();\nconst dataLoaders = new Map<string, RegisteredDataLoader>();\nconst propertyMappers = new Map<string, RegisteredPropertyMapper>();\nconst indexExtensions = new Map<string, IndexExtension>();\n\n/**\n * @kosService core.extension\n * @kosApiLevel 2\n */\nexport interface ExtensionPoint<\n Data extends object = any,\n Output extends object = any,\n Context extends object = any\n> {\n register: (id: string, extension: any) => void;\n execute: (id: string, data: Data, context?: Context) => Output;\n}\n/**\n * @kosService core.extension\n * @kosApiLevel 2\n */\nexport const registerExtensionPoint = (\n id: string,\n extensionPoint: ExtensionPoint\n) => {\n _ExtensionManager[id] = extensionPoint;\n};\n\nconst _ExtensionManager = {\n indexExtension: {\n // Registrations under one id accumulate; a repeated index key takes the latest mapper.\n registerIndexExtension: (id: string, extension: IndexExtension) => {\n indexExtensions.set(id, { ...indexExtensions.get(id), ...extension });\n },\n\n loadIndexExtensions: (id: string) => indexExtensions.get(id) || {},\n },\n loader: {\n registerLoader: (\n id: string,\n loader: DataLoader,\n options?: ExtensionOptions\n ) => {\n dataLoaders.set(id, {\n loader,\n options: { ...DEFAULT_EXTENSION_OPTIONS, ...options },\n });\n },\n executeLoader: async <T extends object = any>(id: string, data: T) => {\n const registered = dataLoaders.get(id);\n if (!registered) {\n return undefined;\n }\n const { loader, options } = registered;\n try {\n return await loader(data);\n } catch (e) {\n if (options.failurePolicy === \"continue\") {\n KosLog.error(`Error executing data loader for id ${id}`);\n KosLog.error(e);\n return undefined;\n }\n throw new ExtensionException(id, \"dataLoader\", e);\n }\n },\n },\n propertyMapper: {\n registerPropertyMapper: (\n id: string,\n mapper: PropertyMapper,\n options?: ExtensionOptions\n ) => {\n propertyMappers.set(id, {\n mapper,\n options: { ...DEFAULT_EXTENSION_OPTIONS, ...options },\n });\n },\n hasMapper: (id: string) => propertyMappers.has(id),\n executeMapper: <\n T extends object = any,\n O extends ExtensionType = any,\n C extends object = any\n >(\n id: string,\n data: T,\n context?: C\n ) => {\n const registered = propertyMappers.get(id);\n if (!registered) {\n return \"\" as O;\n }\n const { mapper, options } = registered;\n try {\n return mapper(data, context) as O;\n } catch (e) {\n if (options.failurePolicy === \"continue\") {\n KosLog.error(`Error executing property mapper for id ${id}`);\n KosLog.error(e);\n return \"\" as O;\n }\n throw new ExtensionException(id, \"propertyMapper\", e);\n }\n },\n },\n dataMapper: {\n registerDataMapper: (\n id: string,\n mapper: DataMapper,\n options?: ExtensionOptions\n ) => {\n const mappers = dataMappers.get(id) || [];\n mappers.push({\n mapper,\n options: { ...DEFAULT_EXTENSION_OPTIONS, ...options },\n });\n\n dataMappers.set(id, mappers);\n },\n executeMapper: async <\n T extends object = any,\n O extends object = any,\n C extends object = any\n >(\n id: string,\n data: T,\n context?: C\n ): Promise<O> => {\n const mappers = dataMappers.get(id);\n if (!mappers) {\n return {} as O;\n }\n\n const result = {};\n for (const { mapper, options } of mappers) {\n try {\n const _interim = await mapper(data, context);\n Object.assign(result, _interim);\n } catch (e) {\n if (options.failurePolicy === \"continue\") {\n KosLog.error(`Error executing data mapper for id ${id}`);\n KosLog.error(e);\n continue;\n }\n throw new ExtensionException(id, \"dataMapper\", e);\n }\n }\n\n return result as O;\n },\n },\n canvas: {\n registerRenderer: (id: string, renderer: RendererConstructor) => {\n if (!ExtensionManager[EXTENSION_CANVAS_RENDERER]) {\n KosLog.warn(\n `Canvas renderer extension point is not registered. Cannot register renderer \"${id}\".`\n );\n return;\n }\n ExtensionManager[EXTENSION_CANVAS_RENDERER].register(id, renderer);\n },\n },\n};\n\n/**\n * @kosService core.extension\n */\nexport interface IExtensionManager {}\ntype ExtensionManagerType = typeof _ExtensionManager &\n IExtensionManager & {\n [key: string]: ExtensionPoint;\n };\n\n/**\n * @kosService core.extension\n * @kosApiLevel 2\n */\nexport const ExtensionManager = _ExtensionManager as ExtensionManagerType;\n","/**\n * EventBus topic constants for the kos-ui-sdk container indexing\n * system.\n *\n * `KosModelContainer` publishes ADDED and REMOVED directly when its\n * items are mutated. The `@kosIndexAware` decorator publishes CHANGED\n * via a model-effect over its declared fields. The\n * `@kosContainerIndexAware` decorator publishes SEED on demand and\n * PURGE on unload, and subscribes to REQUEST_SEED for late-attach\n * consumer handshakes.\n *\n * Topic naming is intentionally flat (`kos/model/container/index/<verb>`)\n * — the collection is carried in the payload, not the topic, so a\n * single subscribe gives a consumer visibility into the entire index.\n *\n * @kosService core.indexing\n * @kosApiLevel 22\n */\nexport enum KosContainerIndexEvents {\n /** A new item was added to an indexable collection. */\n ADDED = \"kos/model/container/index/added\",\n\n /** An item was removed from an indexable collection. */\n REMOVED = \"kos/model/container/index/removed\",\n\n /** An item's declared index fields changed. */\n CHANGED = \"kos/model/container/index/changed\",\n\n /**\n * A container's current contents as a single snapshot. Emitted in\n * response to REQUEST_SEED so late-attaching consumers can\n * re-establish their index without per-item events.\n */\n SEED = \"kos/model/container/index/seed\",\n\n /**\n * A container is being unloaded; the index should drop all records\n * matching the carried collection.\n */\n PURGE = \"kos/model/container/index/purge\",\n\n /**\n * Consumer-initiated request that all already-`ready()`\n * containers re-emit a SEED. Lets subscribe order stop mattering.\n */\n REQUEST_SEED = \"kos/model/container/index/request-seed\",\n}\n","/**\n * Type contracts for the kos-ui-sdk container indexing system.\n *\n * The contracts live here rather than alongside any particular\n * decorator so the decorators, the EventBus payloads, and downstream\n * consumers can all import the same shapes without circular\n * dependencies.\n *\n * @kosService core.indexing\n * @kosApiLevel 22\n */\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Symbol-keyed accessor on item models\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Property key used by `@kosIndexAware` to expose an item model's\n * current index record. Keyed by `Symbol.for` so cross-bundle\n * equality holds — the SDK is built separately from consumer code.\n *\n * Container-side publishers read this off each item they're about to\n * broadcast.\n */\nexport const INDEX_RECORD_SYMBOL = Symbol.for(\n \"@kosdev-code/kos-ui-sdk.indexRecord\"\n);\n\n/**\n * String key used by `@kosContainerIndexAware` to publish its\n * declared collection onto its own `KosContext`. Items inherit it\n * via `KosContext.get(INDEX_COLLECTION_KEY)`, which auto-walks the\n * parent chain.\n *\n * String-keyed because `KosContext.get/set` only accept strings.\n * Namespaced to avoid collision with any feature-level context value\n * an author might define.\n */\nexport const INDEX_COLLECTION_KEY = \"@kosdev-code/kos-ui-sdk.collection\";\n\n/**\n * Structural contract for any item model that participates in\n * indexing. The container-side publisher uses this shape to read\n * records off items at publish time.\n */\nexport interface IndexableItem {\n readonly [INDEX_RECORD_SYMBOL]: IndexRecordContribution;\n}\n\n/**\n * Runtime check used by `KosModelContainer` to decide whether to\n * publish for a given item.\n */\nexport function isIndexableItem(value: unknown): value is IndexableItem {\n return (\n typeof value === \"object\" && value !== null && INDEX_RECORD_SYMBOL in value\n );\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Index records\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * What an item contributes via `INDEX_RECORD_SYMBOL`. `collection`\n * is optional — when absent, the item resolves it from its\n * `KosContext` (auto-walking the parent chain).\n *\n * Additional fields beyond identity + collection are arbitrary and\n * driven by the item-level decorator's `fields` declaration.\n */\nexport interface IndexRecordContribution {\n /** Stable id of the indexed item. */\n id: string;\n /** Model type id (e.g. `\"virtual-machine-model\"`). */\n modelType: string;\n /** Per-item collection tag. Falls back to container declaration if absent. */\n collection?: string;\n /** Declared index-relevant fields. Shape is per-modelType. */\n [field: string]: unknown;\n}\n\n/**\n * What the container actually publishes on the EventBus. Identical\n * shape to `IndexRecordContribution`, but `collection` is required\n * — by publish time the fallback rule has already been applied.\n */\nexport interface IndexRecord extends IndexRecordContribution {\n collection: string;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// EventBus payloads\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Payload for `KosContainerIndexEvents.ADDED`. */\nexport interface IndexAddedEvent {\n record: IndexRecord;\n}\n\n/** Payload for `KosContainerIndexEvents.REMOVED`. */\nexport interface IndexRemovedEvent {\n id: string;\n modelType: string;\n collection: string;\n}\n\n/** Payload for `KosContainerIndexEvents.CHANGED`. Full record, not deltas. */\nexport interface IndexChangedEvent {\n record: IndexRecord;\n}\n\n/**\n * Payload for `KosContainerIndexEvents.SEED`. Emitted in response to\n * REQUEST_SEED. The items array may carry mixed collections\n * (heterogeneous containers where items are tagged by their own\n * properties). Subscribers route per record, not per top-level field.\n */\nexport interface IndexSeedEvent {\n modelType: string;\n items: IndexRecord[];\n}\n\n/**\n * Payload for `KosContainerIndexEvents.PURGE`. Collection-scoped;\n * the consumer drops all matching records.\n */\nexport interface IndexPurgeEvent {\n modelType: string;\n collection: string;\n}\n\n/**\n * Payload for `KosContainerIndexEvents.REQUEST_SEED`. Optional\n * `collections` filter lets a targeted consumer ask only for what it\n * cares about; an empty/absent filter means \"all\".\n */\nexport interface IndexRequestSeedEvent {\n /** Free-form id used for diagnostics (e.g. `\"index-service\"`). */\n requestedBy: string;\n /** Optional filter; undefined or empty means \"all collections\". */\n collections?: string[];\n}\n","import { autorun, makeAutoObservable, observable, runInAction } from \"mobx\";\nimport { KosLog } from \"../core/log\";\nimport { ObservableData, type KosData } from \"../util\";\nimport { IKosBaseContainer } from \"./kos-container-model\";\nimport type { IKosDataModel } from \"./kosModel\";\nimport { IKosIdentifiable } from \"./types/model\";\n\ninterface KosContainerIndexOptions<T extends IKosIdentifiable> {\n container: IKosBaseContainer<T>;\n key: keyof T | IndexMapper<T>;\n}\n\nexport interface IKosContainerIndex<T extends IKosIdentifiable> {\n index: Map<string, Set<T>>;\n keys: string[];\n data: KosData<Record<string, T[]>>;\n getByKey: (key: string) => T[];\n refresh: () => void;\n}\n\nexport interface IndexMapper<T extends IKosIdentifiable> {\n (model: T):\n | Promise<string | string[] | undefined>\n | string\n | string[]\n | undefined;\n}\n\nfunction isPromiseLike(value: unknown): value is PromiseLike<unknown> {\n return (\n typeof (value as PromiseLike<unknown> | undefined)?.then === \"function\"\n );\n}\n\nfunction arraysAreEqual<T extends IKosDataModel = IKosDataModel>(\n arr1: T[],\n arr2: T[]\n): boolean {\n // Check if both arrays have the same length\n if (arr1.length !== arr2.length) return false;\n\n return arr1.every((item1) => arr2.includes(item1));\n}\n\nexport class KosContainerIndex<T extends IKosIdentifiable>\n implements IKosContainerIndex<T>\n{\n private _container: IKosBaseContainer<T>;\n private _map: Map<string, Set<T>>;\n private _key: string | number | symbol | IndexMapper<T>;\n private _generation = 0;\n\n data: KosData<Record<string, T[]>>;\n constructor({ container, key }: KosContainerIndexOptions<T>) {\n this._container = container;\n this._map = observable.map(new Map());\n this._key = key;\n this.data = ObservableData();\n\n this.generateIndex();\n autorun(() => {\n if (this._container.revision) {\n this.generateIndex();\n }\n });\n makeAutoObservable(this);\n }\n\n refresh() {\n this.generateIndex();\n }\n\n private addItemToIndex(\n key: string,\n model: T,\n map = this._map,\n data: Record<string, T[]> = this.data\n ) {\n const currentValue = map.get(key) || new Set<T>();\n currentValue.add(model);\n map.set(key, currentValue);\n data[key] = Array.from(currentValue);\n }\n\n private resolveIndex(map, data: Record<string, T[]>) {\n const toRemove = this.data.keys.filter(\n (key) => !Object.keys(data).includes(key)\n );\n\n toRemove.forEach((key) => {\n delete this.data[key];\n this._map.delete(key);\n });\n Object.keys(data).forEach((key) => {\n const values = data[key];\n const existing = this.data[key] || [];\n if (!arraysAreEqual(values, existing)) {\n this.data[key] = values;\n const set = map.get(key) || new Set<T>();\n this._map.set(key, set);\n } else {\n KosLog.debug(`KosContainerIndex - Index ${key} is the same`);\n }\n });\n }\n /**\n * Rebuild the index from the container's current contents.\n *\n * Applied in the same action when every key resolves synchronously, so a\n * property key or a synchronous mapper updates the index before the\n * container mutation returns. When a mapper returns a promise, the rebuild\n * applies once they all settle, and only if no later rebuild has started:\n * the latest container contents always win.\n */\n private generateIndex() {\n runInAction(() => {\n const generation = ++this._generation;\n const models = [...this._container.data];\n const values = models.map((model) =>\n typeof this._key === \"function\" ? this._key(model) : model[this._key]\n );\n\n if (!values.some(isPromiseLike)) {\n this.applyIndex(models, values);\n return;\n }\n\n void Promise.all(values).then((resolved) => {\n if (generation === this._generation) {\n runInAction(() => this.applyIndex(models, resolved));\n }\n });\n });\n }\n\n private applyIndex(models: T[], values: unknown[]) {\n const tempMap = new Map<string, Set<T>>();\n const tempData: Record<string, T[]> = {};\n models.forEach((model, i) => {\n const value = values[i];\n if (Array.isArray(value)) {\n value.forEach((valueItem) => {\n this.addItemToIndex(valueItem, model, tempMap, tempData);\n });\n } else if (\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\"\n ) {\n this.addItemToIndex(String(value), model, tempMap, tempData);\n }\n });\n\n this.resolveIndex(tempMap, tempData);\n }\n\n get keys() {\n return Array.from(this._map.keys());\n }\n get index() {\n return this._map;\n }\n\n getByKey(key: string) {\n const models = this._map.get(key);\n if (models) {\n return Array.from(models);\n }\n return [];\n }\n}\n","/**\n * KosModelContainer - Container with automatic capacity management\n *\n * ## Capacity Management (Safety Net)\n *\n * Containers can automatically evict models when capacity is exceeded to prevent\n * memory overflow. This is particularly useful for event-driven containers that\n * accumulate models based on incoming events (logs, sensor data, transient records).\n *\n * ### Usage Examples\n *\n * **1. FIFO Strategy (Event Streams, Logs)**\n * ```typescript\n * @kosContainerAware<LogBlockModel>({\n * containerProperty: \"logs\",\n * containerOptions: {\n * maxCapacity: 1000, // Keep last 1000 log blocks\n * evictionStrategy: 'fifo', // Remove oldest first (default)\n * evictionBatchSize: 100, // Remove 100 at a time when exceeded\n * }\n * })\n * export class LogContainerModelImpl {\n * // No explicit cleanup needed - FIFO manages size automatically\n * }\n * ```\n *\n * **2. LRU Strategy (Caches)**\n * ```typescript\n * @kosContainerAware<CachedDataModel>({\n * containerOptions: {\n * maxCapacity: 500,\n * evictionStrategy: 'lru', // Remove least recently accessed\n * }\n * })\n * export class CacheContainerModelImpl {\n * // Frequently accessed models stay, unused ones are evicted\n * }\n * ```\n *\n * **3. Custom Strategy (Business Logic)**\n * ```typescript\n * @kosContainerAware<TroubleModel>({\n * containerProperty: \"troubles\",\n * containerOptions: {\n * maxCapacity: 5000, // Safety net - normally < 100\n * evictionStrategy: 'custom',\n * customEvictionFilter: (troubles) => {\n * // Evict resolved troubles older than 1 hour\n * return troubles.filter(t =>\n * t.status === 'resolved' &&\n * Date.now() - t.resolvedAt > 3600000\n * );\n * }\n * }\n * })\n * export class TroubleContainerModelImpl {\n * // Primary cleanup via explicit handlers\n * // Custom eviction as fallback for edge cases\n * }\n * ```\n *\n * **4. Safety Net (Prevent Crashes)**\n * ```typescript\n * @kosContainerAware<SensorReadingModel>({\n * containerOptions: {\n * maxCapacity: 10000, // Set higher than expected (normally ~100-1000)\n * // If this triggers, investigate upstream data inconsistency\n * }\n * })\n * ```\n *\n * ### Eviction Logging\n *\n * All evictions are logged at INFO level with details:\n * ```\n * INFO: Container capacity exceeded (1001/1000). Evicting 100 models using fifo strategy.\n * INFO: Evicting model: log-12345 (type: LogBlockModel)\n * INFO: Evicted 100 models. Current size: 901/1000\n * ```\n *\n * This allows for easy filtering of eviction messages while still providing\n * visibility into container capacity management.\n */\n\nimport {\n isComputedProp,\n runInAction as kosAction,\n makeAutoObservable,\n observable,\n observe,\n reaction,\n} from \"mobx\";\n\nimport * as EventBus from \"../../common/events/eventBus\";\nimport { destroyKosModel } from \"../util\";\nimport { ObservableData, type KosData } from \"../util/observable-proxy-map\";\nimport { KosContextManager } from \"./context/kos-context-manager\";\nimport { ExtensionManager } from \"./extension\";\nimport { KosContainerIndexEvents } from \"./indexing/topics\";\nimport {\n INDEX_RECORD_SYMBOL,\n isIndexableItem,\n type IndexAddedEvent,\n type IndexRecord,\n type IndexRemovedEvent,\n} from \"./indexing/types\";\nimport {\n IKosContainerIndex,\n IndexMapper,\n KosContainerIndex,\n} from \"./kos-container-index\";\nimport type { IKosDataModel } from \"./kosModel\";\nimport { KosLog } from \"./log\";\nimport { IKosIdentifiable } from \"./types/model\";\n\nexport interface IKosBaseContainer<T extends IKosIdentifiable> {\n revision: number;\n data: T[];\n idx: KosData<Record<string, Record<string, T[]>>>;\n index: Map<string, IKosContainerIndex<T>>;\n indexKeys: Record<string, string[] | undefined>;\n addModel: (model: T) => void;\n removeModel: (id: string) => void;\n addAll: (models: T[]) => void;\n removeAll: (ids: string[]) => void;\n getModel: (id: string) => T | undefined;\n increment: () => void;\n clear: () => Promise<void>;\n map: (typeof Array.prototype)[\"map\"];\n filter: (typeof Array.prototype)[\"filter\"];\n sort: (typeof Array.prototype)[\"sort\"];\n [Symbol.iterator](): IterableIterator<T>;\n}\n\nfunction observeComputedProperties(model, callback, keys: string[] = []) {\n // Get descriptors for all properties\n const descriptors = Object.getOwnPropertyDescriptors(model);\n\n // Filter to get only computed properties\n const computedProps = Object.keys(descriptors).filter((key) =>\n isComputedProp(model, key)\n );\n\n // Set up a reaction for each computed property\n const disposers = computedProps\n .filter((p) => keys.includes(p))\n .map((prop) =>\n reaction(\n () => model[prop], // Track the computed property\n (newValue, oldValue) => {\n // Call the callback with change details\n callback({ name: prop, newValue, oldValue });\n }\n )\n );\n\n // Return a function to dispose all reactions when needed\n return disposers;\n}\nexport interface IKosModelContainer<T extends IKosDataModel>\n extends IKosBaseContainer<T> {\n updateModel: (model: T) => void;\n getModel: (id: string) => T | undefined;\n getIndexByKey: (indexName: string, indexKey: string) => T[];\n getIndexKeys: (indexName: string) => string[];\n removeAndDestroy: (id: string) => Promise<void>;\n removeAndDestroyAll: (ids: string[]) => Promise<void>;\n toJSON?: () => object;\n}\nconst log = KosLog.createLogger({ name: \"kos-container-model\" });\ntype PropType = string | number | symbol | undefined;\n\n/**\n * Eviction strategy for container capacity management\n *\n * - **fifo**: First-In-First-Out - removes oldest models first (default for event streams)\n * - **lru**: Least Recently Used - removes models not accessed recently (good for caches)\n * - **custom**: Uses customEvictionFilter function to determine which models to evict\n *\n * @category Container Capacity Management\n * @see {@link ContainerOptions.maxCapacity}\n * @see {@link ContainerOptions.evictionStrategy}\n */\nexport type EvictionStrategy = \"fifo\" | \"lru\" | \"custom\";\n\ninterface ContainerOptions<T extends IKosDataModel> {\n sortKey?: keyof T;\n indexMap?: Record<string, keyof T | IndexMapper<T>>;\n parentId?: string;\n extensionId?: string;\n\n /**\n * SAFETY NET: Maximum number of models this container can hold.\n * When exceeded, models are automatically evicted and destroyed based on evictionStrategy.\n *\n * **Primary use case**: Prevent memory overflow when cleanup handlers are missing or\n * data becomes inconsistent. Set higher than normal usage to catch edge cases.\n *\n * **Eviction is logged**: All automatic evictions are logged at WARNING level\n * to aid in debugging and identifying data inconsistencies.\n *\n * @category Capacity Management\n * @see {@link EvictionStrategy}\n * @see {@link evictionBatchSize}\n *\n * @example\n * ```typescript\n * containerOptions: {\n * maxCapacity: 10000, // Safety net: expect ~100-1000 normally\n * evictionStrategy: 'fifo'\n * }\n * ```\n */\n maxCapacity?: number;\n\n /**\n * Strategy for selecting which models to evict when maxCapacity is exceeded.\n *\n * - **fifo** (default): Remove oldest models first - best for event streams, logs\n * - **lru**: Remove least recently accessed models - best for caches\n * - **custom**: Use customEvictionFilter to determine eviction candidates\n *\n * @category Capacity Management\n * @see {@link EvictionStrategy}\n * @see {@link maxCapacity}\n * @see {@link customEvictionFilter}\n *\n * @default 'fifo'\n */\n evictionStrategy?: EvictionStrategy;\n\n /**\n * Number of models to evict when maxCapacity is exceeded.\n * Removing in batches prevents thrashing at the capacity boundary.\n *\n * @category Capacity Management\n * @see {@link maxCapacity}\n *\n * @default Math.max(10, Math.ceil(maxCapacity * 0.1))\n */\n evictionBatchSize?: number;\n\n /**\n * Custom filter function for 'custom' eviction strategy.\n * Should return models that are candidates for eviction.\n * The container will evict up to evictionBatchSize models from the returned array.\n *\n * @category Capacity Management\n * @see {@link EvictionStrategy}\n * @see {@link maxCapacity}\n *\n * @example\n * ```typescript\n * // Evict resolved troubles older than 1 hour\n * customEvictionFilter: (models) => {\n * return models.filter(m =>\n * m.status === 'resolved' &&\n * Date.now() - m.resolvedAt > 3600000\n * );\n * }\n * ```\n */\n customEvictionFilter?: (models: T[]) => T[];\n}\nexport class KosModelContainer<T extends IKosDataModel>\n implements IKosModelContainer<T>\n{\n _data: Map<string, T>;\n private _sortKey?: PropType;\n private _revision: number;\n private _index: Map<string, IKosContainerIndex<T>>;\n private _optionsMap: ContainerOptions<T>[\"indexMap\"];\n private _disposerMap: Map<string, () => void> = new Map();\n private _parentId?: string;\n idx: KosData<Record<string, Record<string, T[]>>>;\n\n // Capacity management fields\n private _maxCapacity?: number;\n private _evictionStrategy: EvictionStrategy;\n private _evictionBatchSize: number;\n private _insertionOrder: string[] = []; // For FIFO strategy\n private _accessTimes?: Map<string, number>; // For LRU strategy\n private _customEvictionFilter?: (models: T[]) => T[];\n\n constructor(options?: ContainerOptions<T>) {\n this._data = observable.map(new Map());\n\n this._sortKey = options?.sortKey;\n this._revision = 1;\n const extensionOptions = options?.extensionId\n ? (ExtensionManager.indexExtension.loadIndexExtensions(\n options.extensionId\n ) as Record<string, keyof T | IndexMapper<T>>)\n : ({} as Record<string, keyof T | IndexMapper<T>>);\n const indexMap = options?.indexMap || {};\n this._optionsMap = { ...indexMap, ...extensionOptions };\n\n const tmp = options?.indexMap\n ? Object.keys(options.indexMap).reduce((acc, curr) => {\n acc[curr] = undefined;\n return acc;\n }, {})\n : {};\n this._index = observable.map(tmp);\n this.idx = ObservableData();\n this._parentId = options?.parentId;\n\n // Initialize capacity management\n this._maxCapacity = options?.maxCapacity;\n this._evictionStrategy = options?.evictionStrategy || \"fifo\";\n this._evictionBatchSize =\n options?.evictionBatchSize ??\n Math.max(10, Math.ceil((options?.maxCapacity ?? 100) * 0.1));\n this._customEvictionFilter = options?.customEvictionFilter;\n\n // Initialize LRU access tracking if needed\n if (this._evictionStrategy === \"lru\" && this._maxCapacity) {\n this._accessTimes = observable.map(new Map());\n }\n\n makeAutoObservable(this);\n this.init();\n }\n\n init() {\n Object.keys(this._optionsMap!).forEach((key) => {\n const modelKey = this._optionsMap![key];\n const idx = new KosContainerIndex<T>({\n container: this,\n key: modelKey,\n });\n this._index.set(key, idx);\n this.idx[key] = idx.data;\n });\n }\n [Symbol.iterator]() {\n return this.data[Symbol.iterator]();\n }\n\n get index() {\n return this._index;\n }\n get revision() {\n return this._revision;\n }\n\n get indexKeys() {\n return Array.from(this.index.keys()).reduce<\n Record<string, string[] | undefined>\n >((acc, curr) => {\n acc[curr] = this.index.get(curr)?.keys;\n return acc;\n }, {});\n }\n\n sortFn(a, b): number {\n const sortKey = this._sortKey;\n\n if (sortKey) {\n return String(a[sortKey]).localeCompare(String(b[sortKey]), undefined, {\n numeric: true,\n });\n }\n return 0;\n }\n\n get data() {\n const list = Array.from(this._data.values());\n\n if (this._sortKey) {\n list.sort(this.sortFn.bind(this));\n }\n return list;\n }\n\n increment() {\n kosAction(() => {\n this._revision = this._revision + 1;\n });\n }\n\n addAll(models: T[]) {\n kosAction(() => {\n models.forEach((model) => this.addModel(model, true));\n });\n this.increment();\n }\n\n removeAll(ids: string[]) {\n kosAction(() => {\n ids.forEach((id) => this.removeModel(id, true));\n this.increment();\n });\n }\n\n /**\n * Remove a model from the container and destroy it.\n * This is a convenience method that combines removeModel() and destroyKosModel().\n *\n * Use this when:\n * - The model is being permanently removed from the system\n * - The model should be cleaned up and disposed\n *\n * Use removeModel() alone when:\n * - Moving models between containers\n * - Temporarily removing without destroying\n * - Managing models that may be re-added later\n *\n * @param id - The unique identifier of the model to remove and destroy\n */\n async removeAndDestroy(id: string): Promise<void> {\n const model = this.getModel(id);\n if (!model) {\n log.debug(`Model ${id} not found in container, skipping destroy`);\n return;\n }\n\n this.removeModel(id);\n\n try {\n await destroyKosModel(model);\n } catch (error) {\n log.error(`Failed to destroy model ${id}:`, error);\n throw error;\n }\n }\n\n /**\n * Remove multiple models from the container and destroy them.\n * This is a convenience method that combines removeAll() and destroyKosModel().\n *\n * Operations are performed in parallel for efficiency, but each destruction\n * is independent - failures in one won't prevent others from being destroyed.\n *\n * @param ids - Array of unique identifiers of the models to remove and destroy\n * @returns Promise that resolves when all models have been removed and destroyed\n */\n async removeAndDestroyAll(ids: string[]): Promise<void> {\n const models = ids\n .map((id) => this.getModel(id))\n .filter((model): model is T => model !== undefined);\n\n if (models.length === 0) {\n log.debug(\"No models found to destroy\");\n return;\n }\n\n // Remove all from container first (synchronous)\n this.removeAll(ids);\n\n // Destroy in parallel, collecting errors\n const results = await Promise.allSettled(\n models.map((model) => destroyKosModel(model))\n );\n\n // Log any failures\n results.forEach((result, index) => {\n if (result.status === \"rejected\") {\n log.error(\n `Failed to destroy model ${models[index].id}:`,\n result.reason\n );\n }\n });\n\n // If any failures occurred, throw an aggregate error\n const failures = results.filter((r) => r.status === \"rejected\");\n if (failures.length > 0) {\n throw new Error(\n `Failed to destroy ${failures.length} of ${models.length} models`\n );\n }\n }\n\n /**\n * Add a model to the container (Zone 2: Workflow orchestration)\n *\n * @param model - The model to add\n * @param defer - If true, skip incrementing revision (for batch operations)\n */\n addModel(model: T, defer?: boolean) {\n // Zone 2: High-level workflow orchestration\n this._persistModel(model);\n this._trackModelMetadata(model);\n this._establishModelRelationships(model);\n this._enforceCapacityLimits();\n this._configureModelMonitoring(model);\n\n // Publishing happens AFTER relationship establishment so the\n // item's INDEX_RECORD_SYMBOL accessor can auto-walk to the\n // container's KosContext for an inherited collection.\n this._publishIndexAdded(model);\n\n if (!defer) {\n this.increment();\n }\n }\n\n /**\n * Persist model to container storage (Zone 3)\n * @private\n */\n private _persistModel(model: T): void {\n this._data.set(model.id || \"\", model);\n }\n\n /**\n * Track model metadata for capacity management (Zone 3)\n * @private\n */\n private _trackModelMetadata(model: T): void {\n if (!this._maxCapacity) return;\n\n // Track insertion order for FIFO eviction\n this._insertionOrder.push(model.id || \"\");\n\n // Track initial access time for LRU eviction\n if (this._accessTimes) {\n this._accessTimes.set(model.id || \"\", Date.now());\n }\n }\n\n /**\n * Establish parent-child relationships (Zone 3)\n * @private\n */\n private _establishModelRelationships(model: T): void {\n if (model.id && this._parentId) {\n KosContextManager.setParentContext(model.id, this._parentId);\n }\n }\n\n /**\n * Enforce capacity limits and trigger eviction if needed (Zone 3)\n * @private\n */\n private _enforceCapacityLimits(): void {\n if (!this._maxCapacity) return;\n\n if (this._data.size > this._maxCapacity) {\n this._evictModels();\n }\n }\n\n /**\n * Configure MobX observers for model property changes (Zone 3)\n * @private\n */\n private _configureModelMonitoring(model: T): void {\n // Clean up existing disposer if present\n const existingDisposer = this._disposerMap.get(model.id);\n if (existingDisposer) {\n existingDisposer();\n this._disposerMap.delete(model.id);\n }\n\n // Setup index mapping infrastructure\n const entries = Object.entries(this._optionsMap || {});\n const values = Object.values(this._optionsMap || {});\n const reverseMap = new Map(entries.map(([k, v]) => [v, k]));\n\n // Create change handler for index refresh\n const handler = (change) => {\n // Refresh specific index if indexed property changed\n if (values.includes(change.name as keyof T)) {\n this.index.get(reverseMap.get(change.name) as string)?.refresh();\n }\n\n // Refresh all function-based indexes\n const fnIndexes = entries.filter(\n ([, value]) => typeof value === \"function\"\n );\n for (const [key] of fnIndexes) {\n this.index.get(key)?.refresh();\n }\n };\n\n // Setup observers\n const computedDisposers = observeComputedProperties(\n model,\n handler,\n values.filter((v) => typeof v === \"string\") as string[]\n );\n const disposer = observe(model, handler);\n\n // Store combined disposer\n this._disposerMap.set(model.id || \"\", () =>\n [disposer, ...computedDisposers].forEach((d) => d())\n );\n }\n\n /**\n * Publish KosContainerIndexEvents.ADDED for an indexable item.\n * No-op when the model carries no INDEX_RECORD_SYMBOL (not opted\n * into indexing) or when the record has no resolvable collection\n * (item has no own tag and no inheritable container context).\n *\n * @private\n */\n private _publishIndexAdded(model: T): void {\n if (!isIndexableItem(model)) return;\n const contribution = model[INDEX_RECORD_SYMBOL];\n if (!contribution.collection) return;\n const payload: IndexAddedEvent = {\n record: contribution as IndexRecord,\n };\n EventBus.publish(KosContainerIndexEvents.ADDED, payload);\n }\n\n /**\n * Publish KosContainerIndexEvents.REMOVED for an indexable item.\n * Called with the model BEFORE it's deleted from the container so\n * the payload can carry modelType + collection.\n *\n * @private\n */\n private _publishIndexRemoved(model: T | undefined): void {\n if (!model || !isIndexableItem(model)) return;\n const contribution = model[INDEX_RECORD_SYMBOL];\n if (!contribution.collection) return;\n const payload: IndexRemovedEvent = {\n id: contribution.id,\n modelType: contribution.modelType,\n collection: contribution.collection,\n };\n EventBus.publish(KosContainerIndexEvents.REMOVED, payload);\n }\n\n removeModel(id: string, defer?: boolean) {\n // Capture the model BEFORE deleting it so the index payload can\n // carry the right modelType + collection; after delete, the\n // record is gone.\n const removedModel = this._data.get(id);\n this._publishIndexRemoved(removedModel);\n\n this._data.delete(id);\n\n // Clean up tracking data structures\n const orderIndex = this._insertionOrder.indexOf(id);\n if (orderIndex !== -1) {\n this._insertionOrder.splice(orderIndex, 1);\n }\n\n if (this._accessTimes) {\n this._accessTimes.delete(id);\n }\n\n if (!defer) {\n this.increment();\n }\n const disposer = this._disposerMap.get(id);\n if (disposer) {\n disposer();\n this._disposerMap.delete(id);\n }\n }\n\n updateModel(model: T) {\n this._data.set(model.id || \"\", model);\n this.increment();\n }\n\n getModel(id: string) {\n const model = this._data.get(id);\n\n // Track access time for LRU eviction strategy\n if (model && this._accessTimes) {\n this._accessTimes.set(id, Date.now());\n }\n\n return model;\n }\n\n getIndexKeys(indexName: string) {\n if (this.index.has(indexName)) {\n const idx = this.index.get(indexName)!;\n return idx.keys ?? [];\n } else {\n log.info(\n `index ${indexName} not found in ${Array.from(this.index.keys())}`\n );\n return [];\n }\n }\n getIndexByKey(indexName: string, indexKey: string) {\n if (this.index.has(indexName)) {\n const idx = this.index.get(indexName)!;\n if (idx.index.has(indexKey)) {\n return idx.getByKey(indexKey);\n } else {\n log.info(\n `key ${indexKey} not found in ${indexName} index: ${Array.from(\n idx.index.keys()\n )}`\n );\n return [];\n }\n } else {\n log.info(\n `index ${indexName} not found in ${Array.from(this.index.keys())}`\n );\n return [];\n }\n }\n\n /**\n * SAFETY NET: Evict models when capacity is exceeded (Zone 2: Workflow orchestration)\n * Logs all evictions at WARNING level for debugging.\n * @private\n */\n private async _evictModels() {\n if (!this._maxCapacity) return;\n\n const overCapacity = this._data.size - this._maxCapacity;\n if (overCapacity <= 0) return;\n\n const toEvict = Math.min(this._evictionBatchSize, overCapacity);\n\n // Zone 2: Workflow orchestration\n this._logCapacityWarning(toEvict);\n const modelsToEvict = this._selectModelsForEviction(toEvict);\n await this._removeEvictedModels(modelsToEvict);\n this._logEvictionComplete(modelsToEvict.length);\n\n this.increment();\n }\n\n /**\n * Log capacity exceeded info (Zone 3)\n * @private\n */\n private _logCapacityWarning(toEvict: number): void {\n log.info(\n `Container capacity exceeded (${this._data.size}/${this._maxCapacity}). ` +\n `Evicting ${toEvict} models using ${this._evictionStrategy} strategy.`,\n { parentId: this._parentId }\n );\n }\n\n /**\n * Select models for eviction based on strategy (Zone 3)\n * @private\n */\n private _selectModelsForEviction(count: number): T[] {\n switch (this._evictionStrategy) {\n case \"fifo\":\n return this._selectFifoModels(count);\n case \"lru\":\n return this._selectLruModels(count);\n case \"custom\":\n return this._selectCustomModels(count);\n default:\n return this._selectFifoModels(count);\n }\n }\n\n /**\n * Select oldest models for FIFO eviction (Zone 3)\n * @private\n */\n private _selectFifoModels(count: number): T[] {\n const models: T[] = [];\n for (let i = 0; i < count && this._insertionOrder.length > 0; i++) {\n const oldestId = this._insertionOrder.shift();\n if (!oldestId) continue;\n\n const model = this._data.get(oldestId);\n if (model) {\n models.push(model);\n }\n }\n return models;\n }\n\n /**\n * Select least recently used models for LRU eviction (Zone 3)\n * @private\n */\n private _selectLruModels(count: number): T[] {\n const models: T[] = [];\n\n if (this._accessTimes) {\n const sorted = Array.from(this._accessTimes.entries())\n .sort((a, b) => a[1] - b[1])\n .slice(0, count);\n\n sorted.forEach(([id]) => {\n const model = this._data.get(id);\n if (model) {\n models.push(model);\n }\n });\n }\n\n return models;\n }\n\n /**\n * Select models using custom filter for eviction (Zone 3)\n * @private\n */\n private _selectCustomModels(count: number): T[] {\n if (this._customEvictionFilter) {\n const candidates = this._customEvictionFilter(this.data);\n return candidates.slice(0, count);\n }\n\n log.error(\n \"Custom eviction strategy specified but no customEvictionFilter provided. \" +\n \"Falling back to FIFO.\",\n { parentId: this._parentId }\n );\n\n return this._selectFifoModels(count);\n }\n\n /**\n * Remove and destroy evicted models (Zone 3)\n * @private\n */\n private async _removeEvictedModels(models: T[]): Promise<void> {\n for (const model of models) {\n log.info(\n `Evicting model: ${model.id} (type: ${model.constructor.name})`,\n {\n modelId: model.id,\n parentId: this._parentId,\n strategy: this._evictionStrategy,\n }\n );\n\n this.removeModel(model.id, true);\n\n destroyKosModel(model).catch((e) =>\n log.error(`Failed to destroy evicted model ${model.id}:`, e)\n );\n }\n }\n\n /**\n * Log eviction completion (Zone 3)\n * @private\n */\n private _logEvictionComplete(evictedCount: number): void {\n log.info(\n `Evicted ${evictedCount} models. ` +\n `Current size: ${this._data.size}/${this._maxCapacity}`,\n { parentId: this._parentId }\n );\n }\n\n async clear() {\n this._data.forEach((model) => {\n const modelId = model.id;\n destroyKosModel(model)\n .then(() => {\n log.debug(`${modelId} destroyed, removing from map`);\n this.removeModel(modelId!, true);\n })\n .catch((e) => log.error(e));\n });\n this.increment();\n }\n\n filter<S extends any>(\n predicate: (value: any, index: number, array: any[]) => value is S,\n thisArg?: any\n ) {\n return this.data.filter(predicate, thisArg);\n }\n\n sort(compareFn?: ((a: any, b: any) => number) | undefined) {\n return this.data.sort(compareFn);\n }\n map<U>(\n callbackfn: (value: any, index: number, array: any[]) => U,\n thisArg?: any\n ) {\n return this.data.map(callbackfn, thisArg);\n }\n\n forEach(\n callbackfn: (value: any, index: number, array: any[]) => void,\n thisArg?: any\n ) {\n this.data.forEach(callbackfn, thisArg);\n }\n\n toJSON() {\n const indexes = this.indexKeys;\n return {\n indexes,\n data: this.data.map((model) => {\n return {\n id: model.id,\n type: model.constructor.name,\n };\n }),\n };\n }\n}\n","export enum KosModelState {\n CREATING = `creating`,\n CREATED = `created`,\n INITIALIZING = `initializing`,\n INITIALIZED = `initialized`,\n LOADING = `loading`,\n LOADED = `loaded`,\n ONLINE = `online`,\n READYING = `readying`,\n READY = `ready`,\n READY_FAILED = `ready_failed`,\n RESETTING = `resetting`,\n RESET = `reset`,\n OFFLINE = `offline`,\n UNLOADING = `unloading`,\n UNLOADED = `unloaded`,\n FAILED = `failed`,\n INACTIVE = \"inactive\",\n ACTIVE = \"active\",\n ACTIVATING = \"activating\",\n DEACTIVATING = \"deactivating\",\n}\n\nexport enum KosModelEvents {\n CREATE = `create`,\n INITIALIZE = `init`,\n LOAD = `load`,\n READY = `ready`,\n GO_ONLINE = `go_online`,\n GO_OFFLINE = `go_offline`,\n RESET = `reset`,\n UNLOAD = `unload`,\n FAILED = \"failed\",\n GO_ACTIVE = \"go_active\",\n GO_INACTIVE = \"go_inactive\",\n TIMEOUT = \"timeout\",\n}\n","import { KosCore } from \"../core/kosCore\";\nimport { IKosDataModel } from \"../core/kosModel\";\n/**\n * Asynchronously waits for a Kos Data Model to become ready for use.\n *\n * This utility function is used to ensure that a Kos Data Model is fully\n * loaded and ready to be accessed before performing any operations on it.\n *\n * @category Utility\n * @name whenReady\n * @version 1.0.0\n * @param dataModel - The Kos Data Model to wait for readiness.\n * @throws {Error} If the specified data model is not found or if it has no ID.\n * @returns A promise that resolves to the same data model when it becomes ready.\n *\n * @kosService core.utils\n *\n * @example\n * // Wait for the 'dataModel' to become ready before using it.\n * const dataModel = await whenReady(dataModel);\n * @kosApiLevel 2\n */\nexport const whenReady = async (dataModel: IKosDataModel) => {\n if (dataModel.id) {\n // Retrieve the model associated with the provided ID.\n const model = KosCore.getInstance().modelManager.getModelById(dataModel.id);\n\n // If the model is not found, throw an error.\n if (!model) {\n throw new Error(`Model with ID ${dataModel.id} not found`);\n }\n\n // Wait for the model to become ready before resolving the promise.\n await model?.whenReady();\n } else {\n // If the data model has no ID, throw an error.\n throw new Error(\"Data model must have a valid ID\");\n }\n\n // Return the same data model once it becomes ready.\n return dataModel;\n};\n","import { KosCore } from \"../core/kosCore\";\nimport { IKosDataModel, type IKosModel } from \"../core/kosModel\";\nimport { KosModelEvents, KosModelState } from \"../core/lifecycle\";\nimport { KosLog } from \"../core/log\";\nimport { whenReady } from \"./when-ready\";\n\n/**\n * Asynchronously destroys a KOS data model.\n *\n * @async\n * @param model - The KOS data model to destroy.\n * @throws An error if the model cannot be destroyed.\n *\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport const destroyKosModel = async (model: IKosDataModel) => {\n await KosCore.getInstance().whenReady();\n await KosCore.getInstance().modelManager.initiateDestroyModel(model);\n};\n\n/**\n * Asynchronously unloads a KOS data model without destroying it.\n *\n * @deprecated Never resolves: the UNLOADED state does not record itself on\n * the model, so the transition it waits on never completes. Unload happens\n * only as part of a Core reload or a destroy; call `destroyKosModel` to\n * release a model, or implement `reload()` to refresh one.\n *\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport const unloadKosModel = async (dataModel: IKosDataModel) => {\n KosLog.warn(\n `unloadKosModel(${dataModel?.id}) is deprecated and never resolves. ` +\n \"Use destroyKosModel() to release a model, or reload() to refresh it.\"\n );\n await KosCore.getInstance().whenReady();\n if (!dataModel.id) {\n throw new Error(\"Model ID is required\");\n }\n const model = KosCore.getInstance().modelManager.getModelById(dataModel.id);\n if (model) {\n await model.fsm.transitionTo(KosModelEvents.UNLOAD, KosModelState.UNLOADED);\n }\n};\n/**\n * Asynchronously resets a KOS data model.\n *\n * @deprecated Do not use to refresh a live model. The reset route re-runs\n * `load()` and `ready()` only, so topic handlers registered at INIT or ONLINE\n * (every handler without a `lifecycle`) are disposed and never re-registered.\n * Implement `reload()` on the model and refetch and reconcile in place; KOS\n * Core drives it and restores what it tore down.\n *\n * @async\n * @param model - The KOS data model to reset.\n * @throws An error if the model cannot be reset.\n *\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport const resetKosModel = async (model: IKosDataModel) => {\n KosLog.warn(\n `resetKosModel(${model?.id}) is deprecated: the reset route drops every ` +\n \"topic handler registered at INIT or with no lifecycle. Implement \" +\n \"reload() on the model and refetch and reconcile in place.\"\n );\n await KosCore.getInstance().whenReady();\n\n await KosCore.getInstance().modelManager.reloadModel(model);\n KosLog.debug(\n `reload model initiated for model ${\n model.id\n }, model ready: ${isKosModelReady(model)} - ${Date.now()} `\n );\n await whenReady(model);\n KosLog.debug(\n `reload model complete for model ${\n model.id\n }, model ready: ${isKosModelReady(model)} - ${Date.now()} `\n );\n};\n\n/**\n * Asynchronously retrieves the type of a KOS data model.\n *\n * @async\n * @param modelId - The ID of the KOS data model.\n * @returns The type of the KOS data model.\n * @throws An error if the model ID is not provided or the model cannot be found.\n *\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport const getKosModelType = async (modelId: string) => {\n await KosCore.getInstance().whenReady();\n if (!modelId) {\n throw new Error(\"Model ID is required\");\n }\n const model = KosCore.getInstance().modelManager.getModelById(modelId);\n\n return model?.modelTypeName;\n};\n\n/**\n * Asynchronously retrieves a KOS data model and its type.\n *\n * @async\n * @param modelId - The ID of the KOS data model.\n * @returns An object containing the KOS data model and its type.\n * @throws An error if the model ID is not provided or the model cannot be found.\n *\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport const getKosModel = async <T extends IKosDataModel = IKosDataModel>(\n modelId: string\n) => {\n await KosCore.getInstance().whenReady();\n if (!modelId) {\n throw new Error(\"Model ID is required\");\n }\n const model = KosCore.getInstance().modelManager.getModelById(modelId);\n\n return { model: model?.modelData as T, type: model?.modelTypeName };\n};\n\n/**\n * Synchronously retrieves a KOS data model and its type.\n *\n * @param modelId - The ID of the KOS data model.\n * @returns An object containing the KOS data model and its type.\n * @throws An error if the model ID is not provided or the model cannot be found.\n *\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport const getKosModelSync = <T extends IKosDataModel = IKosDataModel>(\n modelId: string\n) => {\n if (!modelId) {\n throw new Error(\"Model ID is required\");\n }\n const model = KosCore.getInstance().modelManager.getModelById(modelId);\n\n return { model: model?.modelData as T, type: model?.modelTypeName };\n};\n\n/**\n * Finds and filters KOS data models of a specific type based on a predicate.\n *\n * @param modelType - The type of the KOS data models to search for.\n * @param predicate - An object representing filter conditions.\n * @returns An array of filtered KOS data models.\n * @throws An error if the model type is not provided.\n *\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport const findModels = <T extends IKosDataModel>(\n modelType: string,\n predicate: { [k: string]: any }\n) => {\n if (!modelType) {\n throw new Error(\"Model type is required\");\n }\n const model = KosCore.getInstance().modelManager.getModelsByType(modelType);\n const filtered = model.filter((m) =>\n Object.keys(predicate).every((key) => m[key] === predicate[key])\n );\n return filtered as T[];\n};\n\n/**\n * Finds and retrieves the first KOS data model of a specific type based on a predicate.\n *\n * @param modelType - The type of the KOS data models to search for.\n * @param predicate - An object representing filter conditions.\n * @returns The first matching KOS data model, or undefined if none is found.\n * @throws An error if the model type is not provided.\n *\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport const findModel = <T extends IKosDataModel>(\n modelType: string,\n predicate: { [k: string]: any }\n) => findModels<T>(modelType, predicate)[0];\n\n/**\n * Retrieves a companion KOS data model of a specific type associated with a given model.\n *\n * @param model - The KOS data model for which to retrieve a companion model.\n * @param type - The type of the companion model.\n * @returns The companion KOS data model of the specified type.\n * @throws An error if the model ID is not provided, the model cannot be found, or the companion model does not exist.\n *\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport const getKosCompanionModel = <T extends IKosDataModel>(\n model: IKosDataModel,\n type: string\n) => {\n if (!model.id) {\n throw new Error(\"Model ID is required\");\n }\n const kosModel = KosCore.getInstance().modelManager.getModelById(model.id);\n if (!kosModel) {\n throw new Error(\"Model not found\");\n }\n\n const companionModel = kosModel.companionModels.get(type);\n return companionModel?.modelData as T;\n};\n\n/**\n * Retrieves all companion models for a given model.\n *\n * @param model - The KOS data model for which to retrieve a companion model.\n * @returns The list of companion KOS data models\n * @throws An error if the model ID is not provided, the model cannot be found, or the companion model does not exist.\n *\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport const getAllKosCompanionModels = (model: IKosDataModel) => {\n if (!model.id) {\n throw new Error(\"Model ID is required\");\n }\n const kosModel = KosCore.getInstance().modelManager.getModelById(model.id);\n if (!kosModel) {\n throw new Error(\"Model not found\");\n }\n\n const companionModels = Array.from(kosModel.companionModels.all()).map(\n (m) => m.modelData\n );\n\n return companionModels;\n};\n\n/**\n * @kosService core.utils\n * @kosApiLevel 5\n */\nexport const getObservableCompanions = (modelId: string) => {\n if (!modelId) {\n throw new Error(\"Model ID is required\");\n }\n const kosModel = KosCore.getInstance().modelManager.getModelById(modelId);\n if (!kosModel) {\n throw new Error(\"Model not found\");\n }\n\n const companionModels = kosModel.companionModels.data;\n\n return companionModels;\n};\n\n/**\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport const resolveKosCompanion = <T extends IKosDataModel>(\n modelId: string,\n resolver: (model: T) => boolean\n): IKosModel | undefined => {\n const model = KosCore.getInstance().modelManager.getModelById(modelId);\n if (!model) {\n KosLog.info(`Model not found for id ${modelId}`);\n return undefined;\n }\n const companionModel = Array.from(model.companionModels.all()).find((m) =>\n resolver(m.modelData as T)\n );\n\n return companionModel;\n};\n\n/**\n * Checks if an object is an instance of a specific KOS data model type.\n *\n * @param type - The type of the KOS data model to check against.\n * @returns A type guard function that checks if an object is an instance of the specified KOS data model type.\n *\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport const isKosModel =\n <T extends IKosDataModel>(type: string) =>\n (model: any): model is T =>\n Object.getPrototypeOf(model).modelTypeId === type;\n\n/**\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport const isKosModelReady = (model: IKosDataModel) => {\n const kosModel = KosCore.getInstance().modelManager.getModelById(model.id);\n if (!kosModel) {\n throw new Error(\"Model not found\");\n }\n return kosModel.isReady();\n};\n\n/**\n * An observable, read-only view of a model's activation lifecycle.\n *\n * Models that fetch lazily do so in `activate()`, so activation state — not\n * `loaded`, which tracks the `load()` lifecycle — is what tells a consumer\n * whether that fetch has settled and whether it succeeded. Exposing just this\n * lets a view react to activation without taking a dependency on the whole\n * {@link IKosModel}.\n */\nexport interface KosModelActivationState {\n /** The model's current activation state. */\n readonly activeStatus: KosModelState;\n /** Activation is in flight — nothing conclusive to render yet. */\n readonly isActivating: boolean;\n /** Activation completed; the model's activate() work is done. */\n readonly isActive: boolean;\n /** Activation threw — the model's data is absent, not empty. */\n readonly isFailed: boolean;\n}\n\n/**\n * Retrieves an observable view of a model's activation state.\n *\n * Every member is a getter, so reads happen at access time and stay tracked —\n * call this once and read its properties inside a `kosComponent` (or any MobX\n * reaction) to re-render as the model activates, succeeds, or fails.\n *\n * @param model - The KOS data model to observe.\n * @returns The activation view, or `undefined` when the model has no wrapper\n * yet (not created, or already destroyed).\n *\n * @example Distinguishing \"still loading\" from \"empty\" from \"failed\"\n * ```tsx\n * const activation = getKosModelActivationState(container);\n * if (!activation || activation.isActivating) return <Blank />;\n * if (activation.isFailed) return <LoadError />;\n * return <Versions items={container.items} />;\n * ```\n *\n * @kosService core.utils\n * @kosApiLevel 15\n */\nexport const getKosModelActivationState = (\n model: IKosDataModel | undefined\n): KosModelActivationState | undefined => {\n if (!model?.id) {\n return undefined;\n }\n const kosModel = KosCore.getInstance().modelManager.getModelById(model.id);\n if (!kosModel) {\n return undefined;\n }\n\n return {\n get activeStatus() {\n return kosModel.activeStatus;\n },\n get isActivating() {\n return kosModel.activeStatus === KosModelState.ACTIVATING;\n },\n get isActive() {\n return kosModel.activeStatus === KosModelState.ACTIVE;\n },\n get isFailed() {\n return kosModel.activeStatus === KosModelState.FAILED;\n },\n };\n};\n","import { ModelFactory } from \"../types\";\nimport { KosContextManager } from \"./context/kos-context-manager\";\nimport { KosCore } from \"./kosCore\";\nimport { IKosDataModel } from \"./kosModel\";\nimport { KosLog } from \"./log\";\n\nconst log = KosLog.createLogger({ name: \"kos-model-factory\" });\nexport const KosModelFactory = {\n byModelType: <T extends IKosDataModel, O extends {} = any>(\n modelType: string\n ) =>\n KosCore.getInstance().modelManager.getModelFactory<T>(\n modelType\n ) as ModelFactory<T, O>,\n getModelInstance: <T extends IKosDataModel, O extends {} = any>(\n id: string,\n modelType: string,\n options?: O\n ) => {\n const factory = KosModelFactory.byModelType<T, O>(modelType);\n if (!factory) {\n log.error(\n `No registered factory found for model type ${modelType}. Please register a factory for this model type. `\n );\n throw Error(`No factory found for model type ${modelType}`);\n }\n\n return factory.build(id, options);\n },\n};\n\nexport const Kos = {\n Factory: {\n create:\n <T extends IKosDataModel, O extends {} = any>(modelType: string) =>\n (id: string) =>\n (options?: O, parentId?: string) => {\n if (parentId) {\n KosContextManager.setParentContext(id, parentId);\n }\n const model = KosModelFactory.getModelInstance<T, O>(\n id,\n modelType,\n options\n );\n\n return model;\n },\n },\n\n Singleton: {\n create:\n <T extends IKosDataModel, O extends {} = any>(modelType: string) =>\n (options?: O, parentId?: string) => {\n if (parentId) {\n KosContextManager.setParentContext(modelType, parentId);\n }\n const model = KosModelFactory.getModelInstance<T, O>(\n modelType,\n modelType,\n options\n );\n\n return model;\n },\n },\n\n Model: {\n instance:\n <T extends IKosDataModel, O extends {} = any>(modelType: string) =>\n (id: string) =>\n KosModelFactory.getModelInstance<T, O>(id, modelType),\n },\n};\n","import type { BaseKosModelRegistrationBean } from \"../../types/model\";\nimport { KosCore } from \"../kosCore\";\nimport { KosLog } from \"../log\";\nimport type {\n IKosModelRegistration,\n IKosRegistry,\n KosCompanionModelType,\n} from \"../types/registration\";\nimport {\n isKosModelRegistration,\n type KosModelRegistrationType,\n} from \"./model-registration\";\n\ndeclare global {\n interface Window {\n KosRegistry: {\n coreModels: Map<string, IKosModelRegistration>;\n preloadModels: string[];\n companionModels: Map<string, KosCompanionModelType<any>[]>;\n models: Map<string, BaseKosModelRegistrationBean<any, any>>;\n };\n }\n}\nwindow.KosRegistry =\n (window.KosRegistry as any) ||\n ({\n coreModels: new Map<string, IKosModelRegistration>(),\n preloadModels: [],\n companionModels: new Map<string, KosCompanionModelType<any>>(),\n models: new Map<string, BaseKosModelRegistrationBean<any, any>>(),\n } as any);\nconst coreModels = window.KosRegistry.coreModels;\nconst preloadModels: string[] = window.KosRegistry.preloadModels;\nconst companionModels = window.KosRegistry.companionModels;\nconst models = window.KosRegistry.models;\n\nexport interface RegistrationResult<R> {\n preload: (type: string) => RegistrationResult<R>;\n model: (\n registration:\n | BaseKosModelRegistrationBean<any, any>\n | KosModelRegistrationType<any, any>,\n preload?: boolean\n ) => RegistrationResult<R>;\n companion: (\n parentType: string,\n companion: KosCompanionModelType<any>\n ) => RegistrationResult<R>;\n legacy: <T extends IKosModelRegistration>(\n type: string,\n registration: T\n ) => RegistrationResult<R>;\n root: R;\n}\nexport const RegistrationManager = {\n model: {\n registerLegacyModel:\n <R>(root: R) =>\n <T extends IKosModelRegistration>(\n type: string,\n registration: T\n ): RegistrationResult<R> => {\n coreModels.set(type, registration);\n return {\n preload: RegistrationManager.model.preloadModel(root),\n model: RegistrationManager.model.register(root),\n companion: RegistrationManager.companion.register(root),\n legacy: RegistrationManager.model.registerLegacyModel(root),\n root,\n };\n },\n preloadModel:\n <R>(root: R) =>\n (type: string): RegistrationResult<R> => {\n if (!preloadModels.includes(type)) {\n preloadModels.push(type);\n }\n return {\n preload: RegistrationManager.model.preloadModel(root),\n model: RegistrationManager.model.register(root),\n companion: RegistrationManager.companion.register(root),\n legacy: RegistrationManager.model.registerLegacyModel(root),\n root,\n };\n },\n register:\n <R>(root: R) =>\n <\n T extends\n | BaseKosModelRegistrationBean<any, any>\n | KosModelRegistrationType<any, any>\n >(\n registration: T,\n preload?: boolean\n ): RegistrationResult<R> => {\n const register: BaseKosModelRegistrationBean<any, any> =\n isKosModelRegistration(registration)\n ? registration.registration()\n : registration;\n models.set(register.type, register as any);\n\n if (isKosModelRegistration(registration)) {\n registration.relatedModels.forEach((model) =>\n models.set(model.type, model.registration() as any)\n );\n }\n\n if (KosCore.getInstance().isReady) {\n if (\n !KosCore.getInstance().modelManager.registry.models[register.type]\n ) {\n KosLog.info(\n `Model with type ${register.type} doesn't exist. Adding new registration`\n );\n KosCore.getInstance().modelManager.registry.models[register.type] =\n register.registration[register.type];\n if (isKosModelRegistration(registration)) {\n registration.relatedModels.forEach(\n (model) =>\n (KosCore.getInstance().modelManager.registry.models[\n model.type\n ] = model.registration().registration)\n );\n }\n }\n }\n if (preload) {\n RegistrationManager.model.preloadModel(root)(register.type);\n }\n return {\n preload: RegistrationManager.model.preloadModel(root),\n model: RegistrationManager.model.register(root),\n companion: RegistrationManager.companion.register(root),\n legacy: RegistrationManager.model.registerLegacyModel(root),\n root,\n };\n },\n get: (type: string) => models.get(type),\n getAll: () => Array.from(models.entries()),\n getPreloadModels: () => preloadModels,\n getLegacyModels: () =>\n Array.from(coreModels.entries()).reduce((acc, [key, value]) => {\n acc[key] = value;\n return acc;\n }, {} as IKosRegistry[\"models\"]),\n },\n companion: {\n register:\n <R>(root: R) =>\n (\n parentType: string,\n companion: KosCompanionModelType<any>\n ): RegistrationResult<R> => {\n const companions = companionModels.get(parentType) || [];\n companions.push(companion);\n companionModels.set(parentType, companions);\n return {\n preload: RegistrationManager.model.preloadModel(root),\n model: RegistrationManager.model.register(root),\n companion: RegistrationManager.companion.register(root),\n legacy: RegistrationManager.model.registerLegacyModel(root),\n root,\n };\n },\n getAll: () => Array.from(companionModels.entries()),\n },\n};\n\nexport const registerLegacyModel =\n RegistrationManager.model.registerLegacyModel;\nexport const registerKosModel = RegistrationManager.model.register;\nexport const registerCompanionModel = RegistrationManager.companion.register;\nexport const preloadKosModel = RegistrationManager.model.preloadModel;\n","import type { BaseKosModelRegistrationBean } from \"../../types/model\";\nimport { isKosModel } from \"../../util/kos-model-utils\";\nimport { Kos } from \"../kos-model-factory\";\nimport type {\n IKosDataModel,\n KosCreationContext,\n UpdateAware,\n} from \"../kosModel\";\nimport type { KosModelRegistrationFactory } from \"./base-kos-model-registration\";\nimport { RegistrationManager } from \"./registration-manager\";\nimport type { SingletonKosModelRegistrationFactory } from \"./singleton-kos-model-registration-factory\";\n\nexport const isUpdateable = (model: any): model is UpdateAware =>\n typeof model.updateModel === \"function\";\ninterface ModelRegistration<\n B extends boolean,\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> {\n singleton: boolean;\n class: new (modelId: string, options: O, context: KosCreationContext) => T;\n type: string;\n factory: FactoryType<B, T, O>;\n}\n\ntype FactoryType<\n B extends boolean,\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> = B extends true\n ? ReturnType<typeof Kos.Singleton.create<T, O>>\n : ReturnType<typeof Kos.Factory.create<T, O>>;\n\ntype KosOptionsFunction<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> = (options: O) => { build: () => T };\nexport interface KosInstance<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> {\n get: () => T;\n options: KosOptionsFunction<T, O>;\n forceUpdate: {\n options: KosOptionsFunction<T, O>;\n };\n}\n\nexport type KosModelRegistrationType<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> =\n | KosModelRegistrationFactory<T, O>\n | SingletonKosModelRegistrationFactory<T, O>;\n\n/**\n * The registration bean `@kosModel` injects for a given config, so a model's\n * `Registration` annotation follows its `singleton` flag instead of mirroring it.\n * A config without the flag resolves to `never`: no bean is injected, and the bean\n * comes from a separately generated registration file.\n */\nexport type KosRegistrationFor<\n Config,\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> = Config extends { singleton: true }\n ? SingletonKosModelRegistrationFactory<T, O>\n : Config extends { singleton: false }\n ? KosModelRegistrationFactory<T, O>\n : never;\n\nexport const isKosModelRegistration = (\n item: any\n): item is KosModelRegistrationType<any, any> =>\n item.registration !== undefined && typeof item.registration === \"function\";\nexport abstract class KosBaseModelRegistration<\n B extends boolean,\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> {\n singleton: boolean;\n type: string;\n loader: string;\n class: new (modelId: string, options: O, context: KosCreationContext) => T;\n guard: ReturnType<typeof isKosModel<T>>;\n factory: FactoryType<B, T, O>;\n relatedModels: KosModelRegistrationType<any, any>[] = [];\n constructor(props: ModelRegistration<B, T, O>) {\n this.singleton = props.singleton;\n this.guard = isKosModel(props.type);\n this.type = props.type;\n this.loader = `kos.extension.model.loader.${props.type}`;\n this.factory = props.factory;\n this.class = props.class;\n }\n\n addRelatedModel(model: KosModelRegistrationType<any, any>) {\n this.relatedModels.push(model);\n }\n\n registerRelatedModels() {\n this.relatedModels.forEach((model) => model.register());\n }\n\n abstract registration(): BaseKosModelRegistrationBean<T, O>;\n\n register() {\n RegistrationManager.model.register({})(this.registration());\n this.registerRelatedModels();\n }\n\n abstract instance(id?: string): KosInstance<T, O>;\n}\n\nexport type KosModelRegistrationProps<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> = Omit<ModelRegistration<false, T, O>, \"singleton\" | \"factory\">;\n","import type { BaseKosModelRegistrationBean } from \"../../types\";\nimport { getKosModelSync } from \"../../util/kos-model-utils\";\nimport { Kos } from \"../kos-model-factory\";\nimport type { IKosDataModel } from \"../kosModel\";\nimport {\n KosBaseModelRegistration,\n isUpdateable,\n type KosInstance,\n type KosModelRegistrationProps,\n} from \"./model-registration\";\n\nexport class KosModelRegistrationFactory<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> extends KosBaseModelRegistration<false, T, O> {\n constructor(props: KosModelRegistrationProps<T, O>) {\n super({\n ...props,\n singleton: false,\n factory: Kos.Factory.create<T, O>(props.type),\n });\n }\n\n instance(id: string): KosInstance<T, O> {\n const optionsFactory = this.factory(id);\n return {\n get: () => {\n const model = getKosModelSync(id);\n if (!model) {\n throw new Error(\"Model not found with id \" + id);\n }\n if (this.guard(model.model)) {\n return model.model;\n } else {\n throw new Error(\"Model is not of type \" + this.type);\n }\n },\n forceUpdate: {\n options: (options: O) => {\n return {\n build: () => {\n const model = optionsFactory(options);\n if (this.guard(model)) {\n if (isUpdateable(model)) {\n model.updateModel(options);\n } else {\n throw new Error(\n `Model ${this.type} is not updateable. Please implement UpdateAware interface`\n );\n }\n\n return model;\n } else {\n throw new Error(\"Model is not of type \" + this.type);\n }\n },\n };\n },\n },\n options: (options: O) => {\n return {\n build: () => {\n const model = optionsFactory(options);\n if (this.guard(model)) {\n return model;\n } else {\n throw new Error(\"Model is not of type \" + this.type);\n }\n },\n };\n },\n };\n }\n registration(): BaseKosModelRegistrationBean<T, O> {\n return {\n type: this.type,\n predicate: this.guard,\n registration: {\n [this.type]: {\n class: this.class,\n singleton: false,\n },\n },\n\n factory: this.factory,\n };\n }\n}\n","import type { BaseKosModelRegistrationBean } from \"../../types\";\nimport { getKosModelSync } from \"../../util/kos-model-utils\";\nimport { Kos } from \"../kos-model-factory\";\nimport type { IKosDataModel } from \"../kosModel\";\nimport {\n KosBaseModelRegistration,\n isUpdateable,\n type KosInstance,\n type KosModelRegistrationProps,\n} from \"./model-registration\";\n\nexport class SingletonKosModelRegistrationFactory<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> extends KosBaseModelRegistration<true, T, O> {\n constructor(props: KosModelRegistrationProps<T, O>) {\n super({\n ...props,\n singleton: true,\n factory: Kos.Singleton.create<T, O>(props.type),\n });\n }\n\n instance(): KosInstance<T, O> {\n const optionsFactory = this.factory;\n const result = {\n get: () => {\n const model = getKosModelSync(this.type);\n if (!model) {\n throw new Error(\"Model not found with id \" + this.type);\n }\n if (this.guard(model)) {\n return model;\n } else {\n throw new Error(\n `Model is not of type ${this.type}. Received type ${\n Object.getPrototypeOf(model).modelTypeId\n }`\n );\n }\n },\n forceUpdate: {\n options: (options: O) => {\n return {\n build: () => {\n const model = optionsFactory(options);\n if (this.guard(model)) {\n if (isUpdateable(model)) {\n model.updateModel(options);\n } else {\n throw new Error(\n `Model ${this.type} is not updateable. Please implement UpdateAware interface`\n );\n }\n\n return model;\n } else {\n throw new Error(\n `Model is not of type ${this.type}. Received type ${\n Object.getPrototypeOf(model).modelTypeId\n }`\n );\n }\n },\n };\n },\n },\n options: (options: O) => {\n return {\n build: () => {\n const model = optionsFactory(options);\n if (this.guard(model)) {\n return model;\n } else {\n throw new Error(\n `Model is not of type ${this.type}. Received type ${\n Object.getPrototypeOf(model).modelTypeId\n }`\n );\n }\n },\n };\n },\n };\n return result;\n }\n registration(): BaseKosModelRegistrationBean<T, O> {\n return {\n type: this.type,\n predicate: this.guard,\n registration: {\n [this.type]: {\n class: this.class,\n singleton: true,\n },\n },\n\n factory: this.factory,\n };\n }\n}\n","/* eslint-disable @typescript-eslint/no-unused-vars */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable max-len */\n/* eslint-disable no-param-reassign */\n/* eslint-disable max-classes-per-file */\nimport { makeAutoObservable } from \"mobx\";\nimport {\n FutureHandler,\n MultipleFutureHandler,\n} from \"../../../models/models/future/future-aware\";\nimport { troubleByTypeReducer } from \"../../../models/models/trouble/utils/trouble-reducer\";\nimport { KosContextManager } from \"../context/kos-context-manager\";\nimport { KosModelContainer } from \"../kos-container-model\";\nimport { KosCore } from \"../kosCore\";\nimport { IKosDataModel } from \"../kosModel\";\nimport { KosLog } from \"../log\";\nimport { KosModelRegistrationFactory } from \"../registration/base-kos-model-registration\";\nimport type { KosModelRegistrationType } from \"../registration/model-registration\";\nimport { SingletonKosModelRegistrationFactory } from \"../registration/singleton-kos-model-registration-factory\";\nimport { injectStateMachineSupport } from \"./fsm-injection-utils\";\nimport {\n ChildModels,\n CompanionParentModel,\n ContainerAwareSetup,\n DependencyModels,\n FutureAliases,\n FutureContainerSetup,\n FutureService,\n KosModelSymbol,\n LogConfig,\n LoggerSetup,\n MultipleFutureContainerSetup,\n OptionsRequired,\n ParentModel,\n ReloadAwareSetup,\n SubscriptionHandlers,\n TroubleAwareSetup,\n} from \"./propKeys\";\nimport { resolveParameters } from \"./resolve-parameters\";\nimport {\n DependencyResolutionPolicy,\n type KosDependencyParams,\n} from \"../../types/kos-dependency\";\n\nconst log = KosLog.createLogger({ group: \"decorators\", name: \"kos-model\" });\n\n/** The `FutureEndState.Canceled` value a cancelled future reports as its status. */\nconst FUTURE_CANCEL_END_STATE = \"CANCEL\";\n\nfunction resolveParentContext(\n TargetClass: any,\n modelId: string,\n modelData: any\n) {\n const parentIdRaw = TargetClass[ParentModel]?.parentId;\n if (!parentIdRaw) return;\n\n const parentId = resolveParameters({\n value: parentIdRaw,\n modelData,\n modelId,\n });\n\n if (parentId && typeof parentId === \"string\") {\n KosContextManager.setParentContext(modelId, parentId);\n }\n}\n\n// FSM injection and initialization functions moved to fsm-injection-utils.ts\n// for better maintainability and adherence to clean architecture principles\n\nfunction injectFutureServices(modelInstance: any) {\n const future: Record<string, { handler: (args: any) => any }> =\n modelInstance[FutureService];\n if (!future) return;\n\n Object.entries(future).forEach(([key, { handler }]) => {\n modelInstance[key] = handler;\n });\n}\n\n/**\n * Resolves a dependency while its dependent is constructed. CREATE creates the\n * model when the lookup misses; CONTINUE and FAIL only look it up and return\n * undefined on a miss, leaving FAIL to throw when the dependency's lifecycle\n * phase resolves it.\n */\nfunction resolveDependencyAtConstruction(\n dependency: KosDependencyParams<Record<string, any>>,\n resolvedId: string,\n options: Record<string, any>\n) {\n const modelManager = KosCore.getInstance().modelManager;\n const resolutionPolicy =\n dependency.resolutionPolicy || DependencyResolutionPolicy.CREATE;\n\n if (resolutionPolicy === DependencyResolutionPolicy.CREATE) {\n return modelManager.createModelInstance(\n dependency.modelType,\n resolvedId,\n options\n ).data;\n }\n\n const existing = modelManager.getModelById(resolvedId);\n return existing?.modelTypeName === dependency.modelType\n ? existing.modelData\n : undefined;\n}\n\nfunction injectDependencies(modelInstance: any, modelId: string) {\n const dependencies = modelInstance[DependencyModels] || {};\n\n Object.entries(dependencies).forEach(([key, dependency]: [string, any]) => {\n const resolvedId = resolveParameters({\n value: dependency.id || dependency.modelType,\n modelData: modelInstance,\n modelId,\n });\n\n const options = Object.entries(dependency?.options || {}).reduce(\n (acc, [optKey, optVal]) => {\n acc[optKey] = resolveParameters({\n value: optVal as any,\n modelData: modelInstance,\n modelId,\n });\n return acc;\n },\n {} as Record<string, any>\n );\n\n if (typeof resolvedId === \"string\") {\n if (!dependency.lazy) {\n modelInstance[key] = resolveDependencyAtConstruction(\n dependency,\n resolvedId,\n options\n );\n }\n\n KosCore.getInstance().modelManager.addDependency(modelId, resolvedId);\n }\n });\n}\n\nfunction injectFutureContainerSupport(modelInstance: any) {\n const futureSetup = modelInstance[FutureContainerSetup];\n if (!futureSetup) return;\n\n const { mode, handlerProperty } = futureSetup;\n\n // Create and add the futureHandler\n const futureHandler = new FutureHandler(modelInstance);\n modelInstance[handlerProperty] = futureHandler;\n\n // In full mode, add all the Future Container properties and methods\n if (mode === \"full\") {\n // Add future getter\n Object.defineProperty(modelInstance, \"future\", {\n get() {\n return futureHandler.future;\n },\n enumerable: true,\n configurable: true, // Allow MobX to make this observable\n });\n\n // Add progress getter\n Object.defineProperty(modelInstance, \"progress\", {\n get() {\n return futureHandler.future?.progress || 0;\n },\n enumerable: true,\n configurable: true,\n });\n\n // Add status getter\n Object.defineProperty(modelInstance, \"status\", {\n get() {\n return futureHandler.future?.status || \"IDLE\";\n },\n enumerable: true,\n configurable: true,\n });\n\n // Add isRunning getter\n Object.defineProperty(modelInstance, \"isRunning\", {\n get() {\n return futureHandler.future ? !futureHandler.future.endState : false;\n },\n enumerable: true,\n configurable: true,\n });\n\n // Add isCancelled getter\n Object.defineProperty(modelInstance, \"isCancelled\", {\n get() {\n return futureHandler.future?.status === FUTURE_CANCEL_END_STATE;\n },\n enumerable: true,\n configurable: true,\n });\n\n // Add cancelFuture method\n modelInstance.cancelFuture = async () => {\n if (futureHandler.future) {\n await futureHandler.future.cancelFuture();\n }\n };\n }\n}\n\nfunction injectMultipleFutureContainerSupport(modelInstance: any) {\n const setup = modelInstance[MultipleFutureContainerSetup];\n if (!setup) return;\n\n const { mode, handlerProperty } = setup;\n\n // Create and add the MultipleFutureHandler\n const futureHandler = new MultipleFutureHandler(modelInstance);\n modelInstance[handlerProperty] = futureHandler;\n\n // Dynamically add named future getters based on aliases\n const aliases = modelInstance[FutureAliases];\n if (aliases instanceof Map) {\n aliases.forEach((alias) => {\n const futureGetterName = `${alias}Future`;\n\n // Add the main future getter for this alias\n Object.defineProperty(modelInstance, futureGetterName, {\n get() {\n return futureHandler.futureMap.get(alias);\n },\n enumerable: true,\n configurable: true,\n });\n\n // In full mode, add progress, status, isRunning, isCancelled for each aliased future\n if (mode === \"full\") {\n // Add progress getter for this alias\n Object.defineProperty(modelInstance, `${alias}Progress`, {\n get() {\n const future = futureHandler.futureMap.get(alias);\n return future?.progress || 0;\n },\n enumerable: true,\n configurable: true,\n });\n\n // Add status getter for this alias\n Object.defineProperty(modelInstance, `${alias}Status`, {\n get() {\n const future = futureHandler.futureMap.get(alias);\n return future?.status || \"IDLE\";\n },\n enumerable: true,\n configurable: true,\n });\n\n // Add isRunning getter for this alias\n Object.defineProperty(modelInstance, `${alias}IsRunning`, {\n get() {\n const future = futureHandler.futureMap.get(alias);\n return future ? !future.endState : false;\n },\n enumerable: true,\n configurable: true,\n });\n\n // Add isCancelled getter for this alias\n Object.defineProperty(modelInstance, `${alias}IsCancelled`, {\n get() {\n const future = futureHandler.futureMap.get(alias);\n return future?.status === FUTURE_CANCEL_END_STATE;\n },\n enumerable: true,\n configurable: true,\n });\n\n // Add cancel method for this alias\n modelInstance[\n `cancel${alias.charAt(0).toUpperCase()}${alias.slice(1)}`\n ] = async () => {\n const future = futureHandler.futureMap.get(alias);\n if (future) {\n await future.cancelFuture();\n }\n };\n }\n });\n }\n}\n\nfunction injectTroubleAwareSupport(modelInstance: any) {\n const troubleSetup = modelInstance[TroubleAwareSetup];\n if (!troubleSetup) return;\n\n const { pathProperty } = troubleSetup;\n\n // troubleContainer dependency is already injected via DependencyModels\n // by the @kosTroubleAware decorator, so we just need to add the getters\n\n // Add troubles getter\n Object.defineProperty(modelInstance, \"troubles\", {\n get() {\n const pathValue = this[pathProperty];\n if (pathValue === undefined || pathValue === null) {\n const message = `@kosTroubleAware: Path property '${pathProperty}' is undefined on model ${\n this.id || \"unknown\"\n }. Returning empty troubles array.`;\n\n if (this.logger && typeof this.logger.warn === \"function\") {\n this.logger.warn(message);\n } else {\n console.warn(message);\n }\n\n return [];\n }\n\n return this.troubleContainer.troubles\n .getIndexByKey(\"byIface\", pathValue)\n .sort((a, b) => b.rank - a.rank);\n },\n enumerable: true,\n configurable: true,\n });\n\n // Add troubleStatus getter (returns empty string by default - deprecated but required by interface)\n Object.defineProperty(modelInstance, \"troubleStatus\", {\n get() {\n return \"\";\n },\n enumerable: true,\n configurable: true,\n });\n\n // Add troublesByType getter\n Object.defineProperty(modelInstance, \"troublesByType\", {\n get() {\n const troubles = this.troubles; // Will handle the undefined case\n return troubles.reduce(troubleByTypeReducer, {} as Record<string, any[]>);\n },\n enumerable: true,\n configurable: true,\n });\n}\n\nfunction injectContainerAwareSupport(modelInstance: any, modelId: string) {\n const containerSetup = modelInstance[ContainerAwareSetup];\n if (!containerSetup) return;\n\n const {\n containerProperty,\n includeMethods,\n includeGetters,\n modelsProperty,\n containerOptions,\n legacy,\n } = containerSetup;\n\n // Create container options with automatic parentId inference\n const finalContainerOptions = {\n ...containerOptions,\n // If parentId is not provided, use the modelId (first constructor parameter)\n parentId: containerOptions.parentId || modelId,\n };\n\n // Create and add the container\n const container = new KosModelContainer(finalContainerOptions);\n modelInstance[containerProperty] = container;\n\n // Register container as a kosChild for proper hierarchy management\n if (!modelInstance[ChildModels]) {\n modelInstance[ChildModels] = {};\n }\n modelInstance[ChildModels][containerProperty] = container;\n\n // Add convenience methods if requested\n if (includeMethods) {\n modelInstance.getModel = (id: string) => container.getModel(id);\n\n modelInstance.addModel = (model: any) => {\n container.addModel(model);\n };\n\n modelInstance.removeModel = (id: string) => {\n container.removeModel(id);\n };\n\n modelInstance.addAll = (models: any[]) => {\n container.addAll(models);\n };\n\n modelInstance.removeAll = (ids: string[]) => {\n container.removeAll(ids);\n };\n\n modelInstance.removeAndDestroy = async (id: string) =>\n container.removeAndDestroy(id);\n\n modelInstance.removeAndDestroyAll = async (ids: string[]) =>\n container.removeAndDestroyAll(ids);\n }\n\n // Add reactive getters if requested\n if (includeGetters) {\n // Add models getter - returns the container itself (compatible with IKosModelHolder)\n Object.defineProperty(modelInstance, modelsProperty, {\n get() {\n return container;\n },\n enumerable: true,\n configurable: true,\n });\n\n // Add data getter - returns the actual array (compatible with IKosModelHolder)\n Object.defineProperty(modelInstance, \"data\", {\n get() {\n return container.data;\n },\n enumerable: true,\n configurable: true,\n });\n }\n}\n\nfunction injectCompanionSupport(modelInstance: any, initialData: any) {\n const companionConfig =\n modelInstance.constructor.prototype[CompanionParentModel];\n if (!companionConfig) return;\n\n const { mode, parentProperty, excludeProperties } = companionConfig;\n\n // Get the parent model from initialData\n // The framework ALWAYS puts the parent in initialData.companionParent regardless of parentProperty\n const parentModel = initialData.companionParent;\n if (!parentModel) {\n log.warn(\n `Companion decorator configured but no parent model found in initialData.companionParent`\n );\n return;\n }\n\n // Add getCompanionParent method (available in both modes)\n modelInstance.getCompanionParent = () => parentModel;\n\n // Create immutable getter for the parent property (required for both modes)\n // This prevents accidental reassignment and ensures consistency\n Object.defineProperty(modelInstance, parentProperty, {\n get: () => parentModel,\n enumerable: true,\n configurable: true, // Allow MobX to make this observable if needed\n });\n\n // If composition mode, stop here - only getCompanionParent() and direct property access provided\n if (mode === \"composition\") {\n return;\n }\n\n // Lifecycle methods are never proxied (per-model type, parent executes first)\n const lifecycleMethods = [\n \"init\",\n \"load\",\n \"unload\",\n \"ready\",\n \"dispose\",\n \"destroy\",\n \"activate\",\n ];\n\n const internalMethods = [\n \"getDependencies\",\n \"getChildren\",\n \"update\",\n \"toJSON\",\n \"forceUpdate\",\n \"makeAutoObservable\",\n \"runInAction\",\n \"transaction\",\n \"observe\",\n \"unobserve\",\n \"intercept\",\n \"spy\",\n \"trace\",\n \"getCompanionParent\", // Don't override our own getCompanionParent\n ];\n\n // Check if a method is a topic handler by looking at the parent's SubscriptionHandlers\n const isTopicHandler = (name: string): boolean => {\n const subscriptionHandlers =\n parentModel.constructor.prototype[SubscriptionHandlers] || {};\n // Check if any registered handler function matches this method\n return Object.values(subscriptionHandlers).some((config: any) => {\n const handlerFunc = config?.handler;\n // Compare by function reference - the handler stored is the actual method\n return (\n handlerFunc === parentModel[name] ||\n handlerFunc === parentModel.constructor.prototype[name]\n );\n });\n };\n\n const shouldExclude = (name: string) =>\n name === \"constructor\" ||\n name.startsWith(\"_\") ||\n name.startsWith(\"__\") ||\n lifecycleMethods.includes(name) ||\n internalMethods.includes(name) ||\n excludeProperties.includes(name) ||\n isTopicHandler(name) || // Exclude topic handler methods in decorator mode\n name in modelInstance; // Don't override existing properties\n\n // Get all properties from parent and its prototype chain\n const properties = new Set<string>();\n\n // Get instance properties\n Object.getOwnPropertyNames(parentModel)\n .filter((name) => !shouldExclude(name))\n .forEach((name) => properties.add(name));\n\n // Get prototype properties\n let prototype = Object.getPrototypeOf(parentModel);\n while (prototype && prototype !== Object.prototype) {\n Object.getOwnPropertyNames(prototype)\n .filter((name) => !shouldExclude(name))\n .forEach((name) => properties.add(name));\n prototype = Object.getPrototypeOf(prototype);\n }\n\n // Create proxy properties on the companion\n for (const propertyName of properties) {\n try {\n const parentValue = (parentModel as any)[propertyName];\n\n if (typeof parentValue === \"function\") {\n // Create method proxy\n modelInstance[propertyName] = (...args: any[]) =>\n parentValue.apply(parentModel, args);\n } else {\n // Create property proxy with getter/setter\n // Since parent is already observable, these getters will automatically track parent changes\n Object.defineProperty(modelInstance, propertyName, {\n get: () => (parentModel as any)[propertyName],\n set: (value: any) => {\n (parentModel as any)[propertyName] = value;\n },\n enumerable: true,\n configurable: true, // Allow MobX to make this observable\n });\n }\n } catch (error) {\n // Skip properties that can't be accessed\n log.debug(\n `Skipping companion proxy for property ${propertyName}:`,\n error\n );\n }\n }\n}\n\nfunction injectReloadAwareSupport(modelInstance: any) {\n const setup = modelInstance[ReloadAwareSetup];\n if (!setup) return;\n\n const { reloadDependencies = [] } = setup;\n\n // Add _isReloading backing field on instance\n modelInstance._isReloading = false;\n\n // Add isReloading getter that aggregates across declared dependencies\n Object.defineProperty(modelInstance, \"isReloading\", {\n get() {\n if (this._isReloading) return true;\n for (const dep of reloadDependencies) {\n if (this[dep]?.isReloading) return true;\n }\n return false;\n },\n enumerable: true,\n configurable: true,\n });\n}\n\nfunction makeSafeObservable(instance: any) {\n try {\n return makeAutoObservable(instance);\n } catch (e) {\n log.error(\"Failed to make observable:\", e);\n return instance;\n }\n}\n\nconst modelConstructorProxy: ProxyHandler<any> = {\n construct(TargetClass, args) {\n const [modelId, initialData = {}] = args;\n const kosContext = KosContextManager.createContext(modelId);\n\n resolveParentContext(TargetClass, modelId, initialData);\n\n // Check if @kosLoggerAware decorator is present - skip logger creation if so\n const hasLoggerAware = !!TargetClass.prototype[LoggerSetup];\n\n const logger = hasLoggerAware\n ? null // @kosLoggerAware will handle logger creation\n : KosLog.createLogger({\n name: TargetClass.prototype.modelTypeId,\n group: TargetClass[LogConfig]?.group ?? \"kos-model\",\n });\n\n const modelInstance = new TargetClass(modelId, initialData, {\n logger,\n kosContext,\n });\n\n // Inject companion support immediately after construction, before any other setup\n // This ensures this.trouble is available before computed properties are accessed\n injectCompanionSupport(modelInstance, initialData);\n injectFutureServices(modelInstance);\n injectFutureContainerSupport(modelInstance);\n injectMultipleFutureContainerSupport(modelInstance);\n injectTroubleAwareSupport(modelInstance);\n injectContainerAwareSupport(modelInstance, modelId);\n injectStateMachineSupport(modelInstance);\n injectReloadAwareSupport(modelInstance);\n injectDependencies(modelInstance, modelId);\n\n return makeSafeObservable(modelInstance);\n },\n};\n\ninterface DecoratedKosModel<T extends IKosDataModel = IKosDataModel> {\n new (...args: any[]): T;\n}\n\ninterface KosModelConfig {\n modelTypeId: string;\n singleton?: boolean;\n autoRegister?: boolean;\n /**\n * Indicates whether this model requires options to be provided during instantiation.\n * When true, the framework will throw an error if an empty or undefined options object\n * is provided when creating a dependency with DependencyResolutionPolicy.CREATE.\n * @default false\n */\n optionsRequired?: boolean;\n}\n\n/**\n * Decorator for defining a Kos Data Model class.\n *\n * @param config - The model configuration. Can be a string (backward compatibility) or configuration object.\n * @returns A decorator function that transforms the class into a KOS-compatible model.\n * @kosService core.kos-model\n * @kosApiLevel 2\n */\nexport function kosModel<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n>(config: string | KosModelConfig): ClassDecorator {\n return (constructor: any) => {\n const typedCtor = constructor as DecoratedKosModel<T>;\n\n // Parse configuration - support both string (backward compatibility) and object\n const modelConfig =\n typeof config === \"string\"\n ? { modelTypeId: config, autoRegister: false }\n : { autoRegister: false, ...config };\n\n typedCtor.prototype.modelTypeId = modelConfig.modelTypeId;\n typedCtor.prototype[KosModelSymbol] = true;\n typedCtor.prototype[SubscriptionHandlers] ??= {};\n typedCtor.prototype[DependencyModels] ??= {};\n\n // Store optionsRequired flag for dependency resolution validation\n if (modelConfig.optionsRequired) {\n typedCtor.prototype[OptionsRequired] = true;\n }\n\n KosLog.ifDebug(() => {\n KosLog.debug(`Registering model with id ${modelConfig.modelTypeId}`);\n });\n\n const proxiedCtor = new Proxy(typedCtor, modelConstructorProxy);\n\n // NEW: Transparently inject .Registration property if singleton flag is provided\n if (modelConfig.singleton !== undefined) {\n let registration: KosModelRegistrationType<T, O>;\n\n if (modelConfig.singleton) {\n registration = new SingletonKosModelRegistrationFactory<T, O>({\n class: proxiedCtor as any,\n type: modelConfig.modelTypeId,\n });\n } else {\n registration = new KosModelRegistrationFactory<T, O>({\n class: proxiedCtor as any,\n type: modelConfig.modelTypeId,\n });\n }\n\n // Inject as static property on the proxied constructor\n Object.defineProperty(proxiedCtor, \"Registration\", {\n value: registration,\n writable: false,\n enumerable: true,\n configurable: false,\n });\n\n // Auto-register if requested (escape hatch for plugins)\n if (modelConfig.autoRegister) {\n registration.register();\n }\n }\n\n return proxiedCtor;\n };\n}\n","/* eslint-disable no-param-reassign */\nimport type { ApiCallback } from \"../../../common/events\";\nimport { DependencyLifecycle } from \"../../types\";\nimport type { BaselineDependency } from \"../../types/service-response-store\";\nimport { IKosDataModel } from \"../kosModel\";\nimport type { FlowControlOptions } from \"./kos-topic-handler-flow-control\";\nimport { SubscriptionHandlers } from \"./propKeys\";\n\n/**\n * Extended ApiCallback that includes wildcard capture data for handlers with trailing wildcards\n *\n * @kosService core.topic-handler\n * @kosApiLevel 12\n */\nexport interface ApiCallbackWithWildcard<T = string> extends ApiCallback<T> {\n /**\n * @kosApiLevel 8\n */\n wildcardCapture?: Record<string, string>;\n}\n\n/**\n * Zone 3: Parses wildcard segment from topic pattern and actual topic\n * @internal - exported for testing\n */\nexport function parseWildcardSegment(\n pattern: string,\n actualTopic: string,\n wildcardName?: string\n): Record<string, string> {\n const result: Record<string, string> = {};\n\n if (!pattern.endsWith(\"/*\")) {\n return result;\n }\n\n // Remove the /* from the pattern to get the prefix\n const prefix = pattern.slice(0, -2);\n\n // Check if the actual topic starts with the prefix\n if (actualTopic.startsWith(prefix)) {\n const captured = actualTopic.slice(prefix.length + 1); // +1 to skip the /\n const name = wildcardName || \"path\";\n result[name] = captured;\n }\n\n return result;\n}\n\n/**\n * Zone 3: Checks if topic pattern has trailing wildcard\n * @internal - exported for testing\n */\nexport function checkWildcardPattern(pattern: string): boolean {\n return pattern.endsWith(\"/*\");\n}\n\n/**\n * Configuration parameters for defining a Kos topic handler function within a Kos Data Model class.\n *\n * @typeparam Response - The type of the raw response payload received from the topic.\n * @typeparam Model - The type of the Kos Data Model to which the topic handler belongs.\n * @typeparam TransformedResponse - The type of the transformed response payload after applying the transformation function.\n *\n * @kosService core.topic-handler\n * @kosApiLevel 2\n */\nexport interface IKosTopicHandlerParams<\n Response = any,\n Model extends IKosDataModel = any,\n TransformedResponse = Response\n> {\n /**\n * The topic or array of topics to which the handler should respond.\n */\n topic: string | string[];\n\n /**\n * A conditional function that determines whether the handler should be invoked based on the received payload and the Kos Data Model instance.\n * If not provided, the handler will always be invoked when a matching topic is received.\n *\n * @param payload - The transformed payload received from the topic.\n * @param model - The Kos Data Model instance to which the topic handler belongs.\n * @returns `true` if the handler should be invoked, `false` otherwise.\n */\n condition?: (\n payload: TransformedResponse,\n model: Model,\n raw: Response\n ) => boolean;\n\n /**\n * A transformation function that converts the raw response payload into a desired format.\n * If not provided, the payload will be used as is.\n *\n * @param payload - The raw response payload received from the topic.\n * @returns The transformed payload in the desired format.\n */\n transform?: (payload: Response) => TransformedResponse;\n\n /**\n * Indicates whether the topic handler should listen for WebSocket messages.\n * If set to `true`, the handler will be invoked when WebSocket messages with matching topics are received.\n * Default is `false`.\n */\n websocket?: boolean;\n\n /**\n * @internal\n */\n fos?: boolean;\n\n /**\n * @internal\n */\n bridge?: boolean;\n\n lifecycle?: DependencyLifecycle;\n\n /**\n * @internal\n */\n skipParse?: boolean;\n\n /**\n * @kosApiLevel 6\n */\n destinationAddress?: string;\n\n /**\n * When true, the `destinationAddress` value is used exactly as provided\n * and the transport will NOT fall back to `connId` from query parameters\n * or kosBridge. Use this when a subscription intentionally targets\n * a specific (or empty) destination regardless of the current device context.\n * @kosApiLevel 22\n */\n explicitDestination?: boolean;\n\n // === FUNCTIONAL ENHANCEMENTS ===\n\n /**\n * Debounce events - only emit after a period of inactivity\n * @example debounce: 1000 // Wait 1 second after last event\n * @example debounce: { delay: 1000, discardIntermediate: true } // Only keep last value\n * @kosApiLevel 11\n */\n debounce?:\n | number\n | {\n delay: number;\n /** If true, only keeps the last value. If false (default), accumulates all values */\n discardIntermediate?: boolean;\n };\n\n /**\n * Throttle events - limit emissions to once per interval\n * @example throttle: 500 // At most once every 500ms\n * @example throttle: { interval: 500, discardIntermediate: true } // Only keep first value in window\n * @kosApiLevel 11\n */\n throttle?:\n | number\n | {\n interval: number;\n /** If true, only keeps the first value in window. If false (default), accumulates all values */\n discardIntermediate?: boolean;\n };\n\n /**\n * Buffer events and emit them as an array after time window or max size\n * @kosApiLevel 11\n */\n buffer?: {\n /** Time window to collect events (ms) */\n time: number;\n /** Maximum number of events to buffer */\n maxSize?: number;\n };\n\n /**\n * Filter events based on a predicate function\n * Note: This operates on the raw payload before transformation\n * @kosApiLevel 11\n */\n filter?: (payload: Response) => boolean;\n\n /**\n * Only handle the event once, then automatically unsubscribe\n * @kosApiLevel 11\n */\n once?: boolean;\n\n /**\n * Named wildcard capture for trailing /* patterns.\n * When enabled, the portion after the /* is parsed and passed to the handler.\n * You can optionally specify a name for the captured segment.\n *\n * @example\n * ```typescript\n * @kosTopicHandler({\n * topic: \"/config/system/*\",\n * websocket: true,\n * wildcardName: \"configPath\"\n * })\n * handleConfigUpdate(payload: ConfigData, raw: ApiCallbackWithWildcard<any>) {\n * // raw.wildcardCapture.configPath contains everything after \"/config/system/\"\n * }\n * ```\n * @kosApiLevel 12\n */\n wildcardName?: string;\n\n /**\n * Advanced flow control options using async iterators internally.\n * Enables event processing patterns like batching, on-the-fly transforms,\n * filtering and rate limiting.\n *\n * @example\n * ```typescript\n * @kosTopicHandler({\n * topic: 'sensor.data',\n * websocket: true,\n * flow: {\n * batch: { size: 50, window: 1000 },\n * transform: (events) => aggregateEvents(events),\n * }\n * })\n * handleProcessedEvents(aggregatedData) {\n * // Receives transformed, batched data\n * }\n * ```\n * @kosApiLevel 12\n */\n flow?: FlowControlOptions<Response, TransformedResponse>;\n\n /**\n * Baseline dependency configuration for baseline-delta race condition handling.\n * When specified, this handler will wait for the baseline service request to complete\n * before processing events, and will intelligently replay queued events based on\n * temporal comparison with the baseline request/response timing.\n *\n * @example\n * ```typescript\n * @kosTopicHandler({\n * topic: TOPIC_INGREDIENT_UPDATE,\n * websocket: true,\n * lifecycle: DependencyLifecycle.READY,\n * requiresBaseline: {\n * path: PATH_INGREDIENTS,\n * method: 'get',\n * replayStrategy: 'after-request'\n * }\n * })\n * handleIngredientUpdate(payload: IngredientUpdatePayload) {\n * // Framework guarantees:\n * // 1. Baseline loaded before this handler executes\n * // 2. Queued events replayed with temporal filtering\n * // 3. Only events newer than baseline are processed\n * }\n * ```\n * @kosApiLevel 15\n */\n requiresBaseline?: BaselineDependency;\n}\n\n/**\n * Decorator for defining a Kos topic handler function within a Kos Data Model class.\n *\n * @param params - An object containing configuration parameters for the topic handler.\n * @returns A decorator function.\n *\n * @example Basic usage:\n * ```typescript\n * @kosTopicHandler({\n * topic: 'temperature/update',\n * websocket: true\n * })\n * handleTemperature(payload: TemperatureData) { }\n * ```\n *\n * @example Debounced handling:\n * ```typescript\n * @kosTopicHandler({\n * topic: 'rapid/updates',\n * websocket: true,\n * debounce: 1000 // Wait 1 second after last event\n * })\n * handleRapidUpdates(payload: UpdateData) { }\n * ```\n *\n * @example Buffered batch processing:\n * ```typescript\n * @kosTopicHandler({\n * topic: 'log/entry',\n * websocket: true,\n * buffer: { time: 5000, maxSize: 100 }\n * })\n * handleLogBatch(entries: LogEntry[]) { }\n * ```\n *\n * @example Trailing wildcard with custom name:\n * ```typescript\n * @kosTopicHandler({\n * topic: '/config/system/*',\n * websocket: true,\n * wildcardName: 'configPath'\n * })\n * handleConfigUpdate(payload: ConfigData, raw: ApiCallbackWithWildcard<any>) {\n * // raw.wildcardCapture.configPath = \"network/timeout\" (everything after \"/config/system/\")\n * }\n * ```\n *\n * @example Trailing wildcard with PropKeys:\n * ```typescript\n * const DEVICE_ID = createPropKey<DeviceModel>('deviceId');\n *\n * @kosTopicHandler({\n * topic: `/devices/${DEVICE_ID}/sensors/*`,\n * websocket: true,\n * wildcardName: 'sensorPath'\n * })\n * handleSensorEvent(payload: SensorData, raw: ApiCallbackWithWildcard<any>) {\n * // raw.wildcardCapture.sensorPath = \"temperature/reading\" (everything after device-specific prefix)\n * }\n * ```\n * @category KOS Model Decorator\n * @kosService core.topic-handler\n * @kosApiLevel 2\n */\nexport function kosTopicHandler<\n Response = any,\n Model extends IKosDataModel = any,\n TransformedResponse = Response\n>(params: IKosTopicHandlerParams<Response, Model, TransformedResponse>) {\n return (\n target: any,\n _propertyKey: string,\n descriptor: PropertyDescriptor\n ) => {\n const configuration = prepareHandlerConfiguration(params, descriptor);\n registerTopicHandlers(target, params.topic, configuration);\n };\n}\n\n// === TYPE DEFINITIONS ===\n// Type definitions for handler functions\ntype TopicHandler<T = any> = (this: any, payload: T) => void | Promise<void>;\ntype BufferedHandler<T = any> = (\n this: any,\n payloads: T[]\n) => void | Promise<void>;\n\n/**\n * Zone 2: Prepares handler configuration by coordinating enhancement creation\n */\nfunction prepareHandlerConfiguration<\n Response = any,\n Model extends IKosDataModel = any,\n TransformedResponse = Response\n>(\n params: IKosTopicHandlerParams<Response, Model, TransformedResponse>,\n descriptor: PropertyDescriptor\n) {\n const {\n condition = (_payload, _model) => true,\n transform = (_payload) => _payload as any,\n websocket = false,\n fos = false,\n bridge = false,\n skipParse = false,\n lifecycle,\n destinationAddress,\n explicitDestination = false,\n debounce,\n throttle,\n buffer,\n filter,\n once,\n wildcardName,\n flow,\n requiresBaseline,\n } = params;\n\n const originalHandler = descriptor.value;\n const enhancedHandler = applyFunctionalEnhancements(originalHandler, {\n debounce,\n throttle,\n buffer,\n once,\n });\n const enhancedCondition = combineFilterWithCondition(filter, condition);\n\n return {\n websocket,\n fos,\n bridge,\n handler: enhancedHandler,\n condition: enhancedCondition,\n transform,\n lifecycle,\n skipParse,\n destinationAddress,\n explicitDestination,\n wildcardName,\n flow,\n requiresBaseline,\n once,\n };\n}\n\n/**\n * Zone 2: Applies functional enhancements to handler\n *\n * @kosService core.topic-handler\n * @kosApiLevel 15\n */\nexport function applyFunctionalEnhancements<T>(\n handler: TopicHandler<T>,\n enhancements: {\n debounce?: number | { delay: number; discardIntermediate?: boolean };\n throttle?: number | { interval: number; discardIntermediate?: boolean };\n buffer?: { time: number; maxSize?: number };\n once?: boolean;\n }\n): TopicHandler<T> {\n let enhancedHandler = handler;\n\n const debounceDelay =\n typeof enhancements.debounce === \"number\"\n ? enhancements.debounce\n : enhancements.debounce?.delay;\n const throttleInterval =\n typeof enhancements.throttle === \"number\"\n ? enhancements.throttle\n : enhancements.throttle?.interval;\n\n if (debounceDelay && debounceDelay > 0) {\n enhancedHandler = createDebouncedHandler(\n enhancedHandler,\n enhancements.debounce!\n );\n } else if (throttleInterval && throttleInterval > 0) {\n enhancedHandler = createThrottledHandler(\n enhancedHandler,\n enhancements.throttle!\n );\n } else if (enhancements.buffer) {\n // Adapt TopicHandler<T> to BufferedHandler<T>\n // The buffered handler receives an array and calls the original handler for each item\n // (bound here; enhancedHandler is reassigned to the buffered wrapper below).\n const inner = enhancedHandler;\n const adaptedHandler: BufferedHandler<T> = async function (\n this: any,\n payloads: T[]\n ) {\n for (const payload of payloads) {\n await inner.call(this, payload);\n }\n };\n enhancedHandler = createBufferedHandler(\n adaptedHandler,\n enhancements.buffer\n );\n } else if (enhancements.once) {\n enhancedHandler = createOnceHandler(enhancedHandler);\n }\n\n return enhancedHandler;\n}\n\n/**\n * Zone 2: Combines filter with existing condition function\n */\nfunction combineFilterWithCondition<\n Response = any,\n Model extends IKosDataModel = any,\n TransformedResponse = Response\n>(\n filter: ((payload: Response) => boolean) | undefined,\n condition: (\n payload: TransformedResponse,\n model: Model,\n raw: Response\n ) => boolean\n): (payload: TransformedResponse, model: Model, raw: Response) => boolean {\n if (!filter) {\n return condition;\n }\n\n return (payload: TransformedResponse, model: Model, raw: Response) => {\n if (!filter(raw)) {\n return false;\n }\n return condition(payload, model, raw);\n };\n}\n\n/**\n * Zone 3: Registers handler configuration for topics\n */\nfunction registerTopicHandlers(\n target: any,\n topic: string | string[],\n handlerConfig: any\n): void {\n target[SubscriptionHandlers] = target[SubscriptionHandlers] || {};\n\n if (Array.isArray(topic)) {\n topic.forEach((t) => {\n target[SubscriptionHandlers][t] = handlerConfig;\n });\n } else {\n target[SubscriptionHandlers][topic] = handlerConfig;\n }\n}\n\n// === HELPER FUNCTIONS FOR FUNCTIONAL PATTERNS ===\n\n/**\n * Zone 2: Creates debounced handler using appropriate strategy\n */\nfunction createDebouncedHandler<T>(\n originalHandler: TopicHandler<T> | BufferedHandler<T>,\n config: number | { delay: number; discardIntermediate?: boolean }\n): TopicHandler<T> {\n const delay = typeof config === \"number\" ? config : config.delay;\n const strategy = determineDebounceStrategy(config);\n\n return strategy === \"discard\"\n ? createDiscardingDebouncer(originalHandler as TopicHandler<T>, delay)\n : createAccumulatingDebouncer(originalHandler as BufferedHandler<T>, delay);\n}\n\n/**\n * Zone 3: Determines which debounce strategy to use\n */\nfunction determineDebounceStrategy(\n config: number | { delay: number; discardIntermediate?: boolean }\n): \"discard\" | \"accumulate\" {\n const discardIntermediate =\n typeof config === \"object\" ? config.discardIntermediate : false;\n return discardIntermediate ? \"discard\" : \"accumulate\";\n}\n\n/**\n * Zone 3: Creates handler that discards intermediate values\n */\nfunction createDiscardingDebouncer<T>(\n originalHandler: TopicHandler<T>,\n delay: number\n): TopicHandler<T> {\n let timeoutId: NodeJS.Timeout | null = null;\n\n return function (this: any, payload: T) {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n timeoutId = setTimeout(() => {\n originalHandler.call(this, payload);\n timeoutId = null;\n }, delay);\n };\n}\n\n/**\n * Zone 3: Creates handler that accumulates all values\n */\nfunction createAccumulatingDebouncer<T>(\n originalHandler: BufferedHandler<T>,\n delay: number\n): TopicHandler<T> {\n let timeoutId: NodeJS.Timeout | null = null;\n let accumulated: T[] = [];\n\n return function (this: any, payload: T) {\n accumulated.push(payload);\n\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n\n timeoutId = setTimeout(() => {\n const batch = [...accumulated];\n accumulated = [];\n originalHandler.call(this, batch);\n timeoutId = null;\n }, delay);\n };\n}\n\nfunction createThrottledHandler<T>(\n originalHandler: TopicHandler<T> | BufferedHandler<T>,\n config: number | { interval: number; discardIntermediate?: boolean }\n): TopicHandler<T> {\n const interval = typeof config === \"number\" ? config : config.interval;\n const discardIntermediate =\n typeof config === \"object\" ? config.discardIntermediate : false;\n\n let lastCall = 0;\n let timeoutId: NodeJS.Timeout | null = null;\n let accumulated: T[] = [];\n let pendingFlush = false;\n\n const flush = function (this: any) {\n if (accumulated.length > 0) {\n const batch = [...accumulated];\n accumulated = [];\n (originalHandler as BufferedHandler<T>).call(this, batch);\n }\n };\n\n return function (this: any, payload: T) {\n const now = Date.now();\n const timeSinceLastCall = now - lastCall;\n\n if (discardIntermediate) {\n // Original behavior - only process first value in window\n if (timeSinceLastCall >= interval) {\n lastCall = now;\n (originalHandler as TopicHandler<T>).call(this, payload);\n } else if (!timeoutId) {\n timeoutId = setTimeout(() => {\n lastCall = Date.now();\n (originalHandler as TopicHandler<T>).call(this, payload);\n timeoutId = null;\n }, interval - timeSinceLastCall);\n }\n } else {\n // New behavior - accumulate all values and emit batches at interval\n accumulated.push(payload);\n\n if (timeSinceLastCall >= interval) {\n lastCall = now;\n flush.call(this);\n } else if (!pendingFlush) {\n pendingFlush = true;\n timeoutId = setTimeout(() => {\n lastCall = Date.now();\n flush.call(this);\n timeoutId = null;\n pendingFlush = false;\n }, interval - timeSinceLastCall);\n }\n }\n };\n}\n\nfunction createBufferedHandler<T>(\n originalHandler: BufferedHandler<T>,\n bufferConfig: { time: number; maxSize?: number }\n): TopicHandler<T> {\n const buffer: T[] = [];\n let timeoutId: NodeJS.Timeout | null = null;\n const maxSize = bufferConfig.maxSize || 1000;\n\n const flush = (context: any) => {\n if (buffer.length > 0) {\n originalHandler.call(context, [...buffer]);\n buffer.length = 0;\n }\n };\n\n return function (this: any, payload: T) {\n buffer.push(payload);\n\n // Flush if buffer is full\n if (buffer.length >= maxSize) {\n if (timeoutId) {\n clearTimeout(timeoutId);\n timeoutId = null;\n }\n flush(this);\n return;\n }\n\n // Set timeout if not already set\n if (!timeoutId) {\n timeoutId = setTimeout(() => {\n flush(this);\n timeoutId = null;\n }, bufferConfig.time);\n }\n };\n}\n\nfunction createOnceHandler<T>(\n originalHandler: TopicHandler<T>\n): TopicHandler<T> {\n let called = false;\n\n return function (this: any, payload: T) {\n if (!called) {\n called = true;\n originalHandler.call(this, payload);\n }\n };\n}\n","/**\n * Zone 3 type guard utilities for KOS models\n */\n\nimport { ObservableMap } from \"mobx\";\nimport { DependencyModels } from \"../core/decorators\";\nimport { IKosModelContainer } from \"../core/kos-container-model\";\nimport type { IKosDataModel } from \"../core/kosModel\";\n\n/**\n * Type guard to check if a model has a toJSON method\n */\nexport const isPrintable = (model: any): model is { toJSON: () => object } =>\n typeof model.toJSON === \"function\";\n\n/**\n * Type guard to check if an object is a KOS data model\n */\nexport const isKosDataModel = (model: any): model is IKosDataModel =>\n model[DependencyModels] !== undefined;\n\n/**\n * Type guard to check if a model is a KOS model container\n */\nexport const isKosModelContainer = (\n model: any\n): model is IKosModelContainer<any> =>\n model.revision !== undefined && model.index !== undefined;\n\n/**\n * Resolves a child attribute to its data model representation.\n * Handles various collection types and extracts KOS data models.\n *\n * @param attribute - The attribute to resolve (can be a model, container, collection, or array)\n * @returns The resolved data model(s) or undefined\n */\nexport const resolveChild = (\n attribute: any\n): IKosDataModel | IKosDataModel[] | undefined => {\n if (!attribute) return undefined;\n if (isKosDataModel(attribute)) return attribute;\n if (isKosModelContainer(attribute)) return attribute.data;\n if (\n attribute instanceof Map ||\n attribute instanceof ObservableMap ||\n attribute instanceof Set\n ) {\n return Array.from(attribute.values()).filter(isKosDataModel);\n }\n if (Array.isArray(attribute)) {\n return attribute.filter(isKosDataModel);\n }\n return undefined;\n};\n","const deletionMap = new Map<string, NodeJS.Timeout[]>();\nexport const KosDeletionManager = {\n addToDeletionQueue: (modelId: string, timeout: NodeJS.Timeout) => {\n const timeouts = deletionMap.get(modelId) || [];\n timeouts.push(timeout);\n deletionMap.set(modelId, timeouts);\n },\n\n cancelDeletion: (modelId: string) => {\n const timeouts = deletionMap.get(modelId);\n if (timeouts) {\n timeouts.forEach((timeout) => {\n clearTimeout(timeout);\n });\n }\n },\n};\n","// dependency-manager.ts\n\nimport { KosDeletionManager } from \"./kos-deletion-manager\";\nimport { KosLog } from \"./log\";\n\nconst log = KosLog.createLogger({ name: \"kos-dependency-manager\" });\n\nexport class KosDependencyManager {\n private _usedByCache = new Map<string, string[]>();\n private _usesCache = new Map<string, string[]>();\n\n add(modelId: string, dependencyId: string) {\n KosDeletionManager.cancelDeletion(dependencyId);\n\n const usedBy = this._usedByCache.get(dependencyId) || [];\n if (!usedBy.includes(modelId)) usedBy.push(modelId);\n this._usedByCache.set(dependencyId, usedBy);\n\n const uses = this._usesCache.get(modelId) || [];\n if (!uses.includes(dependencyId)) uses.push(dependencyId);\n this._usesCache.set(modelId, uses);\n }\n\n remove(modelId: string, dependencyId: string) {\n const usedBy = this._usedByCache.get(dependencyId) || [];\n this._usedByCache.set(\n dependencyId,\n usedBy.filter((id) => id !== modelId)\n );\n\n const uses = this._usesCache.get(modelId) || [];\n this._usesCache.set(\n modelId,\n uses.filter((id) => id !== dependencyId)\n );\n }\n\n /**\n * Drops every edge into and out of a model. Called when the model is\n * destroyed, so its dependencies are not left pinned by a model that is\n * gone and can never release them.\n */\n removeAll(modelId: string) {\n for (const dependencyId of this._usesCache.get(modelId) ?? []) {\n const usedBy = this._usedByCache.get(dependencyId);\n if (usedBy) {\n this._usedByCache.set(\n dependencyId,\n usedBy.filter((id) => id !== modelId)\n );\n }\n }\n this._usesCache.delete(modelId);\n\n for (const dependentId of this._usedByCache.get(modelId) ?? []) {\n const uses = this._usesCache.get(dependentId);\n if (uses) {\n this._usesCache.set(\n dependentId,\n uses.filter((id) => id !== modelId)\n );\n }\n }\n this._usedByCache.delete(modelId);\n }\n\n canDestroy(modelId: string): boolean {\n const usedBy = this._usedByCache.get(modelId);\n if (usedBy?.length) {\n log.info(`Model ${modelId} is still used by: ${usedBy.join(\", \")}`);\n return false;\n }\n return true;\n }\n\n clear() {\n this._usedByCache.clear();\n this._usesCache.clear();\n }\n}\n","// model-cache.ts\n\nimport { observable, runInAction } from \"mobx\";\nimport type { IKosDataModel, IKosModel } from \"./kosModel\";\nimport { KosLog } from \"./log\";\n\nconst log = KosLog.createLogger({ name: \"kos-model-cache\" });\n\nexport type KosModelCacheHandler = Pick<\n KosModelCache,\n \"hasModel\" | \"restoreFromDeleteCache\" | \"addModel\" | \"getModelById\"\n>;\n\nexport class KosModelCache {\n private _modelsById = observable.map<string, IKosModel>(new Map());\n private _toDelete = new Map<string, IKosModel>();\n private _preloaded: IKosModel[] = [];\n private _isPreloaded = false;\n\n constructor(\n private preloadKeys: (\n | string\n | { modelType: string; modelId?: string; options?: Record<string, any> }\n )[] = []\n ) {}\n\n get models(): IKosModel[] {\n return Array.from(this._modelsById.values())\n .map((model) => model as IKosModel)\n .filter((model) => !this._toDelete.has(model.modelId));\n }\n getModelById<T extends IKosDataModel = IKosDataModel>(\n id: string\n ): IKosModel<T> | undefined {\n if (!id) return undefined;\n if (this._toDelete.has(id)) return undefined;\n return this._modelsById.get(id) as IKosModel<T>;\n }\n\n addModel<T extends IKosModel>(model: T): T {\n const existing = this.getModelById(model.modelId) || model;\n runInAction(() => {\n this._modelsById.set(existing.modelId, existing);\n });\n return existing as T;\n }\n\n removeModel(modelId: string): void {\n runInAction(() => {\n this._modelsById.delete(modelId);\n this._toDelete.delete(modelId);\n });\n }\n\n hasModel(modelId?: string): boolean {\n return (\n !!modelId && this._modelsById.has(modelId) && !this._toDelete.has(modelId)\n );\n }\n\n restoreFromDeleteCache(modelId?: string): void {\n if (modelId && this._toDelete.has(modelId)) {\n const model = this._toDelete.get(modelId);\n this._toDelete.delete(modelId);\n runInAction(() => {\n this._modelsById.set(modelId, model!);\n });\n }\n }\n\n markForDeletion(model: IKosModel): void {\n runInAction(() => {\n this._modelsById.delete(model.modelId);\n });\n this._toDelete.set(model.modelId, model);\n }\n\n preload(\n createFn: (\n key:\n | string\n | { modelType: string; modelId?: string; options?: Record<string, any> }\n ) => IKosModel | undefined\n ): IKosModel[] {\n if (this._isPreloaded) {\n log.debug(\"Returning cached preloaded models\");\n return this._preloaded;\n }\n this._preloaded = this.preloadKeys\n .map((key) => {\n log.debug(\n `Preloading model: ${typeof key === \"string\" ? key : key.modelType}`\n );\n return createFn(key);\n })\n .filter((model): model is IKosModel => !!model);\n this._isPreloaded = true;\n return this._preloaded;\n }\n}\n","/**\n * Suspense cache backing `useKosModel`.\n *\n * A `finished` entry never re-runs its fetcher, so it has to be evicted when\n * the model it stands for is destroyed. Otherwise the hook keeps resolving the\n * key against a model that no longer exists and the model is never rebuilt.\n *\n * It lives in core rather than beside the hook so the model manager can evict\n * on destroy without depending on the ui layer.\n */\n\nexport type ModelHookCacheEntry =\n | { status: \"pending\"; promise: Promise<unknown> }\n | { status: \"finished\"; key: string }\n | { status: \"error\"; error: unknown };\n\nconst cache = new Map<string, ModelHookCacheEntry>();\n\nexport const modelHookCache = {\n has: (key: string) => cache.has(key),\n get: (key: string) => cache.get(key),\n set: (key: string, entry: ModelHookCacheEntry) => cache.set(key, entry),\n delete: (key: string) => cache.delete(key),\n clear: () => cache.clear(),\n};\n\n/** Evicts a model's cache entry so the next render rebuilds it. */\nexport const clearModelHookCacheEntry = (modelId?: string): void => {\n if (modelId) {\n cache.delete(modelId);\n }\n};\n","/**\n * Utilities for enriching errors with model context throughout the lifecycle.\n * Provides consistent error formatting and context propagation without specific checks.\n */\n\nimport type { IKosDataModel, IKosModel } from \"../core/kosModel\";\nimport { KosLog } from \"../core/log\";\nimport { DependencyLifecycle } from \"../types/kos-dependency\";\n\n/**\n * Enhanced error class that preserves context through the model lifecycle.\n */\nexport class KosModelError extends Error {\n public readonly context: ModelErrorContext;\n public readonly originalCause?: Error;\n\n constructor(message: string, context: ModelErrorContext, cause?: Error) {\n super(message, { cause });\n this.name = \"KosModelError\";\n this.context = context;\n this.originalCause = cause;\n\n // Preserve stack trace\n if (cause?.stack) {\n this.stack = `${this.stack}\\nCaused by: ${cause.stack}`;\n }\n }\n\n /**\n * Format error with full context for logging.\n */\n toDetailedString(): string {\n const parts = [\n `KosModelError: ${this.message}`,\n ``,\n `Context:`,\n ` Model Type: ${this.context.modelType}`,\n ` Model ID: ${this.context.modelId}`,\n ];\n\n if (this.context.parentModel) {\n parts.push(\n ` Parent Model: ${this.context.parentModel.type} [${this.context.parentModel.id}]`\n );\n }\n\n if (this.context.lifecycle) {\n parts.push(` Lifecycle: ${this.context.lifecycle}`);\n }\n\n if (this.context.operation) {\n parts.push(` Operation: ${this.context.operation}`);\n }\n\n if (this.context.options && Object.keys(this.context.options).length > 0) {\n parts.push(` Options: ${JSON.stringify(this.context.options, null, 2)}`);\n }\n\n if (this.originalCause) {\n parts.push(``, `Original Error: ${this.originalCause.message}`);\n }\n\n return parts.join(\"\\n\");\n }\n}\n\n/**\n * Context information for model errors.\n */\nexport interface ModelErrorContext {\n /** Type of model involved */\n modelType: string;\n /** ID of model instance */\n modelId?: string;\n /** Parent model context if applicable */\n parentModel?: {\n type: string;\n id: string;\n };\n /** Lifecycle phase where error occurred */\n lifecycle?: DependencyLifecycle | string;\n /** Operation being performed */\n operation?: string;\n /** Options provided to the model */\n options?: Record<string, any>;\n /** Additional context-specific data */\n metadata?: Record<string, any>;\n}\n\n/**\n * Wraps an error with model context, preserving the original error as cause.\n */\nexport function enrichError(\n error: Error | unknown,\n context: ModelErrorContext\n): KosModelError {\n const originalError =\n error instanceof Error ? error : new Error(String(error));\n\n // If already a KosModelError, preserve and add context\n if (error instanceof KosModelError) {\n return new KosModelError(\n `${error.message} (enriched with additional context)`,\n { ...error.context, ...context },\n error.originalCause || originalError\n );\n }\n\n // Create new enriched error\n return new KosModelError(\n `Error in ${context.operation || \"model operation\"}: ${\n originalError.message\n }`,\n context,\n originalError\n );\n}\n\n/**\n * Safely executes an async operation with automatic error enrichment.\n */\nexport async function executeWithContext<T>(\n operation: () => Promise<T>,\n context: ModelErrorContext\n): Promise<T> {\n try {\n return await operation();\n } catch (error) {\n const enrichedError = enrichError(error, context);\n KosLog.error(enrichedError.toDetailedString());\n throw enrichedError;\n }\n}\n\n/**\n * Safely executes a sync operation with automatic error enrichment.\n */\nexport function executeSyncWithContext<T>(\n operation: () => T,\n context: ModelErrorContext\n): T {\n try {\n return operation();\n } catch (error) {\n const enrichedError = enrichError(error, context);\n KosLog.error(enrichedError.toDetailedString());\n throw enrichedError;\n }\n}\n\n/**\n * Creates context for a model from its data.\n */\nexport function createModelContext(\n model: IKosModel | IKosDataModel,\n operation?: string\n): ModelErrorContext {\n const modelData = \"modelData\" in model ? model.modelData : model;\n const modelId =\n \"modelId\" in model\n ? model.modelId\n : \"id\" in modelData\n ? modelData.id\n : undefined;\n const modelType =\n \"modelTypeName\" in model\n ? model.modelTypeName\n : modelData.constructor?.name || \"unknown\";\n\n return {\n modelType,\n modelId,\n operation,\n };\n}\n\n/**\n * Logs a collection of errors with summary and details.\n */\nexport function logErrorCollection(\n errors: Array<{ error: Error; context: ModelErrorContext }>,\n summary: string\n): void {\n if (errors.length === 0) return;\n\n KosLog.error(`${summary} - ${errors.length} error(s) occurred:`);\n\n errors.forEach(({ error, context }, index) => {\n const enriched =\n error instanceof KosModelError ? error : enrichError(error, context);\n\n KosLog.error(\n ` [${index + 1}/${errors.length}] ${enriched.toDetailedString()}`\n );\n });\n}\n","/**\n * Zone 3 utility for logging errors with structured context\n */\n\nexport interface ModelInstantiationErrorContext {\n modelType: string;\n options: any;\n registryId: string;\n}\n\n/**\n * Logs a model instantiation error with structured metadata.\n *\n * @param error - The error that occurred during instantiation\n * @param context - Contextual information about the failed instantiation\n */\nexport function logModelInstantiationError(\n error: unknown,\n context: ModelInstantiationErrorContext\n): void {\n console.error(\"Model instantiation failed\", {\n modelType: context.modelType,\n options: context.options,\n registryId: context.registryId,\n error: error instanceof Error ? error.message : String(error),\n stack: error instanceof Error ? error.stack : undefined,\n timestamp: new Date().toISOString(),\n });\n}\n","import type { DependencyLifecycle } from \"../../types\";\nimport { DataLoader, DataMapper, PropertyMapper } from \"../extension\";\nimport type {\n IKosDataModel,\n IKosDataModelBuilder,\n IKosDataModelCreator,\n IKosModel,\n} from \"../kosModel\";\n\nexport interface IKosSubscriptionSpecification {\n webSocket: boolean;\n handler: (payload: any, model: IKosModel) => void;\n}\n\nexport interface TroubleHandlerContext {\n title: string;\n subtitle: string;\n steps?: Record<string, { title: string; subtitle: string }>;\n canDismiss?: boolean;\n showTimeRemaining?: boolean;\n}\nexport interface TroubleHandler extends TroubleHandlerContext {\n type: string;\n context?: Record<string, TroubleHandlerContext>;\n}\n\nexport interface IKosModelRegistration {\n builder?: IKosDataModelBuilder<any, any>;\n create?: IKosDataModelCreator<any, any>;\n class?: new (...args) => IKosDataModel;\n\n singleton?: boolean;\n preload?: boolean;\n subscriptions?: Record<string, IKosSubscriptionSpecification>;\n}\n\nexport interface ExtensionRegistration {\n dataMapper?: Record<string, DataMapper | DataMapper[]>;\n propertyMapper?: Record<string, PropertyMapper>;\n contextLoader?: Record<string, DataLoader>;\n}\n\nexport type KosCompanionTypeFactory<T extends IKosDataModel = IKosDataModel> = (\n model: T,\n options: any\n) => string | undefined;\nexport type KosCompanionModelType<T extends IKosDataModel = IKosDataModel> =\n | string\n | KosCompanionTypeFactory<T>;\n\nexport const isKosCompanionTypeFactory = (\n obj: any\n): obj is KosCompanionTypeFactory => typeof obj === \"function\";\nexport interface IKosCompanionRegistration {\n type: KosCompanionModelType<any>;\n /**\n * Lifecycle phase at which this companion should be created.\n * Extracted from the @kosCompanion decorator metadata.\n * Defaults to undefined (treated as INIT - immediate creation).\n */\n lifecycle?: DependencyLifecycle;\n}\n\nexport type Preloaded =\n | string\n | { modelType: string; modelId: string; options?: any };\nexport interface IKosRegistry {\n alias?: string;\n models: Record<string, IKosModelRegistration>;\n companionModels?: Record<string, IKosCompanionRegistration[]>;\n troubleHandlers?: Record<string, TroubleHandler>;\n\n // eslint-disable-next-line no-use-before-define\n preloadModels: Preloaded[];\n\n extensions?: ExtensionRegistration;\n}\n","// companion-instantiator.ts\n\nimport type { DependencyLifecycle } from \"../types\";\nimport { CompanionParentModel } from \"./decorators\";\nimport type { IKosModel } from \"./kosModel\";\nimport { KosLog } from \"./log\";\nimport type { KosModelCacheHandler } from \"./model-cache\";\nimport { isKosCompanionTypeFactory, type IKosRegistry } from \"./types\";\n\nconst log = KosLog.createLogger({ name: \"kos-companion-instantiator\" });\n\n/**\n * Handles creation and lifecycle management of companion models.\n * Companions are models that extend or enhance parent models and can be\n * created at specific lifecycle phases based on decorator configuration.\n */\nexport class KosCompanionInstantiator {\n constructor(\n private registry: IKosRegistry,\n private cache: KosModelCacheHandler,\n private createModel: (\n typeId: string,\n id: string,\n options: Record<string, any>\n ) => any\n ) {}\n\n /**\n * Creates companion models for a parent model, optionally filtered by lifecycle phase.\n * Called automatically during instantiation for companions without lifecycle specified.\n * Can be called from lifecycle hooks to create lifecycle-deferred companions.\n *\n * @param model The parent model\n * @param options Options to pass to companion constructors\n * @param lifecycle Optional lifecycle filter - only create companions matching this phase\n */\n createCompanionModels(\n model: IKosModel,\n options: Record<string, any>,\n lifecycle?: DependencyLifecycle\n ) {\n const companionDefs = this.getCompanionDefinitions(model.modelTypeName);\n\n if (lifecycle !== undefined) {\n log.debug(\n `Creating ${lifecycle} lifecycle companions for ${model.modelTypeName} [${model.modelId}]`\n );\n }\n\n for (const companionDef of companionDefs) {\n const resolved = this.resolveCompanionType(\n companionDef,\n model,\n options,\n lifecycle\n );\n if (!resolved) continue;\n\n if (!this.shouldCreateCompanion(resolved.lifecycle, lifecycle)) continue;\n\n this.instantiateCompanion(resolved.type, model, options, lifecycle);\n }\n }\n\n /**\n * Get companion definitions for a parent model type\n */\n private getCompanionDefinitions(parentTypeId: string) {\n return this.registry.companionModels?.[parentTypeId] || [];\n }\n\n /**\n * Resolve companion type from definition and extract lifecycle metadata\n */\n private resolveCompanionType(\n companionDef: any,\n model: IKosModel,\n options: Record<string, any>,\n requestedLifecycle?: DependencyLifecycle\n ): { type: string; lifecycle?: DependencyLifecycle } | null {\n if (isKosCompanionTypeFactory(companionDef.type)) {\n return this.resolveFactoryCompanion(\n companionDef,\n model,\n options,\n requestedLifecycle\n );\n } else {\n return this.resolveStringCompanion(companionDef);\n }\n }\n\n /**\n * Resolve factory companion by calling factory and extracting lifecycle\n */\n private resolveFactoryCompanion(\n companionDef: any,\n model: IKosModel,\n options: Record<string, any>,\n requestedLifecycle?: DependencyLifecycle\n ): { type: string; lifecycle?: DependencyLifecycle } | null {\n const companionType = companionDef.type(model.modelData, options);\n\n if (!companionType) {\n log.debug(\n `Companion factory returned undefined for ${model.modelTypeName} at ${\n requestedLifecycle || \"INIT\"\n } phase`\n );\n return null;\n }\n\n const lifecycle = this.extractLifecycleFromType(companionType);\n return { type: companionType, lifecycle };\n }\n\n /**\n * Resolve string companion using pre-extracted lifecycle from registration\n */\n private resolveStringCompanion(companionDef: any): {\n type: string;\n lifecycle?: DependencyLifecycle;\n } {\n return {\n type: companionDef.type,\n lifecycle: companionDef.lifecycle,\n };\n }\n\n /**\n * Extract lifecycle metadata from companion model decorator\n */\n private extractLifecycleFromType(\n companionType: string\n ): DependencyLifecycle | undefined {\n const companionModelReg = this.registry.models[companionType];\n if (!companionModelReg?.class) return undefined;\n\n const companionMetadata =\n companionModelReg.class.prototype[CompanionParentModel];\n return companionMetadata?.lifecycle;\n }\n\n /**\n * Determine if companion should be created based on lifecycle filtering\n */\n private shouldCreateCompanion(\n companionLifecycle: DependencyLifecycle | undefined,\n requestedLifecycle: DependencyLifecycle | undefined\n ): boolean {\n if (requestedLifecycle !== undefined) {\n // Only create companions that match the specified lifecycle\n return companionLifecycle === requestedLifecycle;\n } else {\n // When no lifecycle filter, only create companions without lifecycle (INIT phase)\n return companionLifecycle === undefined;\n }\n }\n\n /**\n * Instantiate and attach companion to parent model\n */\n private instantiateCompanion(\n companionType: string,\n parentModel: IKosModel,\n options: Record<string, any>,\n lifecycle?: DependencyLifecycle\n ): void {\n const companionId = this.generateCompanionId(\n companionType,\n parentModel.modelId\n );\n\n if (\n this.companionAlreadyExists(\n companionId,\n companionType,\n parentModel.modelTypeName\n )\n ) {\n return;\n }\n\n const companion = this.createCompanionInstance(\n companionType,\n companionId,\n parentModel,\n options\n );\n\n if (companion) {\n this.attachCompanionToParent(companion, parentModel);\n log.debug(\n `Created ${lifecycle || \"INIT\"} companion ${companionType} for ${\n parentModel.modelTypeName\n } [${parentModel.modelId}]`\n );\n }\n }\n\n /**\n * Generate unique companion ID\n */\n private generateCompanionId(companionType: string, parentId: string): string {\n return `${companionType}-${parentId}`;\n }\n\n /**\n * Check if companion already exists in cache\n */\n private companionAlreadyExists(\n companionId: string,\n companionType: string,\n parentTypeName: string\n ): boolean {\n if (this.cache.hasModel(companionId)) {\n log.debug(\n `Companion ${companionType} already exists for ${parentTypeName}`\n );\n return true;\n }\n return false;\n }\n\n /**\n * Create companion model instance with parent context\n */\n private createCompanionInstance(\n companionType: string,\n companionId: string,\n parentModel: IKosModel,\n options: Record<string, any>\n ): IKosModel | null {\n const result = this.createModel(companionType, companionId, {\n data: options,\n companionParent: parentModel.modelData,\n kosParentId: parentModel.modelId,\n });\n\n return result?.model || null;\n }\n\n /**\n * Attach companion to parent model\n */\n private attachCompanionToParent(\n companion: IKosModel,\n parent: IKosModel\n ): void {\n companion[CompanionParentModel] = parent;\n parent.addCompanionModel(companion);\n }\n}\n","import { EVENT_KOS_MODEL_READY } from \"../../common\";\n\nexport function modelEventTopicFactory(modelType: string, modelId?: string) {\n return `${EVENT_KOS_MODEL_READY}${modelType}${\n modelId ? `/${modelId}` : `/${modelType}`\n }`;\n}\n\nexport function modelTypeEventTopicFactory(modelType: string) {\n return `${EVENT_KOS_MODEL_READY}${modelType}`;\n}\n","import { when } from \"mobx\";\n\nexport function awaitFirstMatchingWhen(\n conditions: {\n condition: () => boolean;\n onMatch?: () => void;\n }[]\n): Promise<void> {\n const disposers: (() => void)[] = [];\n\n return new Promise<void>((resolve, reject) => {\n for (const { condition, onMatch } of conditions) {\n const disposer = when(condition, () => {\n // clean up all watchers\n disposers.forEach((d) => d());\n\n try {\n onMatch?.();\n resolve();\n } catch (e) {\n reject(e);\n }\n });\n disposers.push(disposer);\n }\n });\n}\n","/**\n * Constants for KOS model lifecycle and operations\n */\n\n/**\n * Timeout in milliseconds for model lifecycle transitions.\n * Models that don't complete their transition within this time will reject.\n */\nexport const MODEL_PROMISE_TIMEOUT_MS = 5000;\n","/**\n * Zone 3 utilities for model lifecycle transitions\n */\n\nimport type { IKosModel } from \"../core/kosModel\";\nimport { KosModelEvents, KosModelState } from \"../core/lifecycle\";\n\n/**\n * Transition map type for lifecycle operations\n */\nexport type ModelPromiseResolver = (model: IKosModel) => Promise<void>;\n\n/**\n * Transitions a model to the ACTIVE state\n */\nexport const transitionToActive = (model: IKosModel): Promise<void> =>\n model.fsm.transitionTo(KosModelEvents.GO_ACTIVE, KosModelState.ACTIVE);\n\n/**\n * Transitions a model to the READY state\n */\nexport const transitionToReady = (model: IKosModel): Promise<void> =>\n model.whenReady();\n\n/**\n * Transitions a model to the LOADED state\n */\nexport const transitionToLoad = (model: IKosModel): Promise<void> =>\n model.fsm.transitionTo(KosModelEvents.LOAD, KosModelState.LOADED);\n\n/**\n * Transitions a model to the UNLOADED state\n */\nexport const transitionToUnload = (model: IKosModel): Promise<void> =>\n model.fsm.transitionTo(KosModelEvents.UNLOAD, KosModelState.UNLOADED);\n\n/**\n * Transitions a model to the INITIALIZED state\n */\nexport const transitionToInit = (model: IKosModel): Promise<void> =>\n model.fsm.transitionTo(KosModelEvents.INITIALIZE, KosModelState.INITIALIZED);\n\n/**\n * Enum defining available lifecycle transitions\n */\nexport enum Transitions {\n ACTIVE = \"active\",\n READY = \"ready\",\n LOAD = \"load\",\n UNLOAD = \"unload\",\n INIT = \"init\",\n}\n\n/**\n * Mapping of transition types to their corresponding transition functions\n */\nexport const TransitionMap: Record<Transitions, ModelPromiseResolver> = {\n [Transitions.ACTIVE]: transitionToActive,\n [Transitions.READY]: transitionToReady,\n [Transitions.LOAD]: transitionToLoad,\n [Transitions.UNLOAD]: transitionToUnload,\n [Transitions.INIT]: transitionToInit,\n};\n","/**\n * Zone 3 utility for promise timeout and race operations\n */\n\nimport { MODEL_PROMISE_TIMEOUT_MS } from \"../constants/model-constants\";\nimport type { IKosModel } from \"../core/kosModel\";\nimport { KosLog } from \"../core/log\";\n\n/**\n * Custom error for model timeout scenarios\n */\nexport class ModelError extends Error {\n model: IKosModel;\n constructor(message: string | undefined, model: IKosModel) {\n super(message);\n this.model = model;\n }\n}\n\n/**\n * Creates a promise that rejects after a specified delay with model context.\n * Provides a cancel function to prevent rejection if the operation completes.\n *\n * @param ms - Timeout duration in milliseconds\n * @param model - The model being operated on\n * @param status - Description of the operation status (e.g., \"ACTIVE\", \"INACTIVE\")\n * @returns Object containing the timeout promise and a cancel function\n *\n * @example\n * ```typescript\n * const { promise: timeoutPromise, cancel } = rejectAfterDelay(\n * MODEL_PROMISE_TIMEOUT_MS,\n * myModel,\n * 'ACTIVE'\n * );\n *\n * Promise.race([\n * myOperation().then(() => cancel()),\n * timeoutPromise\n * ]);\n * ```\n */\nexport const rejectAfterDelay = (\n ms: number,\n model: IKosModel,\n status: string\n): { promise: Promise<void>; cancel: () => void } => {\n let timeoutId: ReturnType<typeof setTimeout>;\n\n const promise = new Promise<void>((_, reject) => {\n timeoutId = setTimeout(() => {\n KosLog.error(\n `Model ${model.modelId} - ${model.modelTypeName} - ${status} timed out after ${ms}ms`\n );\n reject(\n new ModelError(\n `${model.modelId} - ${model.modelTypeName} - ${status}`,\n model\n )\n );\n }, ms);\n });\n\n const cancel = () => {\n if (timeoutId) clearTimeout(timeoutId);\n };\n\n return { promise, cancel };\n};\n\n/**\n * Races a promise against a timeout with automatic cleanup.\n * Useful for ensuring operations complete within a time limit.\n *\n * @param promise - The operation promise to race\n * @param timeoutMs - Timeout duration in milliseconds (defaults to MODEL_PROMISE_TIMEOUT_MS)\n * @param model - The model being operated on\n * @param status - Description of the operation\n * @returns Promise that resolves/rejects based on whichever completes first\n *\n * @example\n * ```typescript\n * await raceWithTimeout(\n * model.transitionToActive(),\n * MODEL_PROMISE_TIMEOUT_MS,\n * model,\n * 'ACTIVE'\n * );\n * ```\n */\nexport const raceWithTimeout = async <T>(\n promise: Promise<T>,\n timeoutMs: number = MODEL_PROMISE_TIMEOUT_MS,\n model: IKosModel,\n status: string\n): Promise<T> => {\n const { promise: timeoutPromise, cancel } = rejectAfterDelay(\n timeoutMs,\n model,\n status\n );\n\n try {\n const result = await Promise.race([promise, timeoutPromise]);\n cancel();\n return result as T;\n } catch (error) {\n cancel();\n throw error;\n }\n};\n","import { MODEL_PROMISE_TIMEOUT_MS } from \"../constants/model-constants\";\nimport { DependencyModels, OptionsRequired } from \"../core/decorators\";\nimport { resolveParameters } from \"../core/decorators/resolve-parameters\";\nimport { KosCore } from \"../core/kosCore\";\nimport type { IKosModel } from \"../core/kosModel\";\nimport { KosLog } from \"../core/log\";\nimport {\n DependencyLifecycle,\n DependencyResolutionPolicy,\n KosDependencyParams,\n} from \"../types/kos-dependency\";\nimport { enrichError, logErrorCollection } from \"./model-error-utils\";\nimport { TransitionMap, Transitions } from \"./model-transition-utils\";\nimport { rejectAfterDelay } from \"./promise-utils\";\n\n// Re-export for backward compatibility\nexport { TransitionMap, Transitions } from \"./model-transition-utils\";\nexport type { ModelPromiseResolver } from \"./model-transition-utils\";\nexport {\n isKosDataModel,\n isKosModelContainer,\n isPrintable,\n resolveChild,\n} from \"./model-type-guards\";\nexport { ModelError } from \"./promise-utils\";\n\n/**\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport interface ModelPromise {\n promise?: Promise<void>;\n modelId?: string;\n model?: IKosModel;\n type?: string;\n status?: string;\n}\n\n/**\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport const createModelDependency = (\n model: IKosModel,\n dependency: KosDependencyParams<any>\n) => {\n const _dataModelId = dependency.id || dependency.modelType;\n const dataModelId = resolveParameters({\n value: _dataModelId,\n modelData: model.modelData,\n modelId: model.modelId,\n }) as string;\n\n const resolutionPolicy =\n dependency.resolutionPolicy || DependencyResolutionPolicy.CREATE;\n\n KosLog.debug(\n `Resolving dependent model ${dependency.modelType} with id ${dataModelId} (policy: ${resolutionPolicy})`\n );\n\n const options = Object.keys(dependency?.options || {}).reduce((acc, curr) => {\n const value = dependency.options[curr];\n acc[curr] = resolveParameters({\n value: value,\n modelData: model.modelData,\n modelId: model.modelId,\n });\n return acc;\n }, {});\n\n // Validate model type is registered\n const modelManager = KosCore.getInstance().modelManager;\n const modelRegistry = modelManager.registry.models[dependency.modelType];\n\n if (!modelRegistry) {\n const errorMessage = `No model registered for type ${dependency.modelType}`;\n\n KosLog.error(\n `Failed to resolve dependency for model ${model.modelId}:\n - Dependency Type: ${dependency.modelType}\n - Dependency ID: ${dataModelId}\n - Resolution Policy: ${resolutionPolicy}\n - Parent Model: ${model.modelTypeName}\n - Parent Model ID: ${model.modelId}\n - Error: ${errorMessage}`\n );\n\n if (resolutionPolicy === DependencyResolutionPolicy.CONTINUE) {\n KosLog.warn(\n `Model type not registered (policy: CONTINUE) - Model ${model.modelId} will continue without dependency ${dependency.modelType} [${dataModelId}]`\n );\n return { dependentModel: null, dataModelId, success: false };\n }\n\n throw new Error(\n `Dependency resolution failed - Model ${model.modelId} cannot resolve dependency ${dependency.modelType} [${dataModelId}]: ${errorMessage}`\n );\n }\n\n // FIRST: Try to look up existing model instance\n const existingModel = modelManager.getModelById(dataModelId);\n\n if (existingModel) {\n // Verify the model type matches\n if (existingModel.modelTypeName !== dependency.modelType) {\n const errorMessage = `Model type mismatch: expected ${dependency.modelType}, found ${existingModel.modelTypeName}`;\n\n KosLog.error(\n `Failed to resolve dependency for model ${model.modelId}:\n - Dependency Type: ${dependency.modelType}\n - Dependency ID: ${dataModelId}\n - Resolution Policy: ${resolutionPolicy}\n - Parent Model: ${model.modelTypeName}\n - Parent Model ID: ${model.modelId}\n - Found Model Type: ${existingModel.modelTypeName}\n - Error: ${errorMessage}`\n );\n\n if (resolutionPolicy === DependencyResolutionPolicy.CONTINUE) {\n KosLog.warn(\n `Model type mismatch (policy: CONTINUE) - Model ${model.modelId} will continue without dependency`\n );\n return { dependentModel: null, dataModelId, success: false };\n }\n\n throw new Error(\n `Dependency resolution failed - Model ${model.modelId} cannot resolve dependency ${dependency.modelType} [${dataModelId}]: ${errorMessage}`\n );\n }\n\n KosLog.debug(\n `Found existing dependent model ${dependency.modelType} with id ${dataModelId}`\n );\n\n // Return in the same format as createModelInstance\n return {\n dependentModel: { model: existingModel, data: existingModel.modelData },\n dataModelId,\n success: true,\n };\n }\n\n // Model doesn't exist - check resolution policy to decide what to do\n KosLog.debug(\n `Model ${dependency.modelType} [${dataModelId}] does not exist. Applying resolution policy: ${resolutionPolicy}`\n );\n\n // If CONTINUE policy and model doesn't exist, return null without attempting creation\n if (resolutionPolicy === DependencyResolutionPolicy.CONTINUE) {\n KosLog.warn(\n `Model ${dependency.modelType} [${dataModelId}] not found (policy: CONTINUE) - Model ${model.modelId} will continue without this dependency`\n );\n return { dependentModel: null, dataModelId, success: false };\n }\n\n if (resolutionPolicy === DependencyResolutionPolicy.FAIL) {\n const errorMessage = `No ${dependency.modelType} model with id ${dataModelId} exists`;\n\n KosLog.error(\n `Failed to resolve dependency for model ${model.modelId}:\n - Dependency Type: ${dependency.modelType}\n - Dependency ID: ${dataModelId}\n - Resolution Policy: ${resolutionPolicy}\n - Parent Model: ${model.modelTypeName}\n - Parent Model ID: ${model.modelId}\n - Error: ${errorMessage}`\n );\n\n throw new Error(\n `Dependency resolution failed (policy: FAIL) - Model ${model.modelId} cannot resolve dependency ${dependency.modelType} [${dataModelId}]: ${errorMessage}`\n );\n }\n\n // CREATE policy: attempt to create the model\n // Check if the target model requires options but none (or empty) were provided\n const hasOptions = Object.keys(options).length > 0;\n const modelClass = modelRegistry.class || modelRegistry.create;\n const requiresOptions = modelClass?.prototype?.[OptionsRequired] === true;\n\n if (requiresOptions && !hasOptions) {\n const errorMessage = `Model ${dependency.modelType} requires options but none were provided`;\n\n KosLog.error(\n `Failed to resolve dependency for model ${model.modelId}:\n - Dependency Type: ${dependency.modelType}\n - Dependency ID: ${dataModelId}\n - Resolution Policy: ${resolutionPolicy}\n - Parent Model: ${model.modelTypeName}\n - Parent Model ID: ${model.modelId}\n - Provided Options: ${JSON.stringify(options, null, 2)}\n - Error: ${errorMessage}\n - Model requires options but dependency declaration provides none`\n );\n\n throw new Error(\n `Dependency resolution failed - Model ${model.modelId} cannot resolve dependency ${dependency.modelType} [${dataModelId}]: ${errorMessage}. Use resolutionPolicy: DependencyResolutionPolicy.CONTINUE if this dependency is optional.`\n );\n }\n\n try {\n const dependentModel =\n KosCore.getInstance().modelManager.createModelInstance(\n dependency.modelType,\n dataModelId,\n options\n );\n\n KosLog.debug(\n `Successfully created dependent model ${dependency.modelType} with id ${dataModelId}`\n );\n\n return { dependentModel, dataModelId, success: true };\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n\n KosLog.error(\n `Failed to create dependency for model ${model.modelId}:\n - Dependency Type: ${dependency.modelType}\n - Dependency ID: ${dataModelId}\n - Resolution Policy: ${resolutionPolicy}\n - Parent Model: ${model.modelTypeName}\n - Parent Model ID: ${model.modelId}\n - Provided Options: ${JSON.stringify(options, null, 2)}\n - Error: ${errorMessage}`\n );\n\n throw error;\n }\n};\n\n/**\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport const getDependenciesByLifecycle = (\n model: IKosModel,\n lifecycle: DependencyLifecycle = DependencyLifecycle.READY\n) => {\n const dependencies = model.modelData?.[DependencyModels] || {};\n if (Object.keys(dependencies).length === 0) {\n KosLog.debug(`${model.modelId} has no dependencies. Returning`);\n return [];\n }\n const dependenciesByLifecycle = Object.keys(dependencies)\n // find all the dependencies that match the lifecycle\n .filter((key) => dependencies[key].lifecycle === lifecycle)\n .map((key) => {\n const dependency = dependencies[key];\n const resolutionResult = createModelDependency(model, dependency);\n\n // Handle CONTINUE policy where dependency resolution failed\n if (!resolutionResult.success || !resolutionResult.dependentModel) {\n KosLog.debug(\n `Skipping dependency ${dependency.modelType} with id ${resolutionResult.dataModelId} - resolution failed with CONTINUE policy`\n );\n model.modelData[key] = undefined;\n return null;\n }\n\n const { dependentModel, dataModelId } = resolutionResult;\n\n model.modelData[key] = dependentModel.data;\n KosLog.debug(\n `waiting for dependent model ${dependency.modelType} with id ${dataModelId} - waiting for WHENREADY`\n );\n const readyFn = async (\n dependentModel: IKosModel,\n modelType: string,\n id: string\n ) => {\n await dependentModel.whenReady?.();\n KosLog.debug(`dependent model ${modelType} with id ${id} - READY`);\n };\n const { promise, cancel } = rejectAfterDelay(\n MODEL_PROMISE_TIMEOUT_MS,\n model,\n model.status\n );\n return Promise.race([\n readyFn(dependentModel.model, dependency.modelType, dataModelId)\n .then(() => {\n cancel();\n })\n .catch((err) => {\n const enrichedError = enrichError(err, {\n modelType: dependency.modelType,\n modelId: dataModelId,\n parentModel: {\n type: model.modelTypeName,\n id: model.modelId,\n },\n lifecycle: lifecycle,\n operation: \"dependency whenReady()\",\n });\n KosLog.error(enrichedError.toDetailedString());\n cancel();\n // Rethrow to ensure Promise.race can reject\n throw enrichedError;\n }),\n promise,\n ]);\n })\n .filter((p) => !!p);\n\n return dependenciesByLifecycle;\n};\n\n/**\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport const executeListLifecycle = async (\n sourceModel: IKosModel,\n models: (IKosModel | undefined)[],\n target: Transitions,\n sourceLifecycle: DependencyLifecycle\n) => {\n KosLog.debug(`Execute lifecycle with ${models.length} models`);\n if (models.length === 0) {\n KosLog.debug(`${sourceModel.modelId} has no children. Returning`);\n return;\n }\n if (!target) {\n KosLog.error(\n `${sourceModel.modelId} is not transitioning with a valid target ${target}`\n );\n return;\n }\n const childPromises = models\n .map<ModelPromise>((model) => {\n let p: Promise<void> | undefined;\n\n if (TransitionMap[target] && model) {\n p = TransitionMap[target](model);\n } else {\n if (!model) {\n KosLog.error(\"model is undefined. This shouldn't happen\");\n }\n\n if (!TransitionMap[target]) {\n KosLog.error(\n `There is no promise in the Transition Map for ${target}`\n );\n }\n }\n\n return {\n promise: p,\n modelId: model?.modelId,\n model,\n type: model?.modelTypeName,\n status: model?.status,\n };\n })\n .filter((modelPromise) => {\n if (!modelPromise.promise) {\n KosLog.error(`No promise found ${modelPromise.modelId}`);\n return false;\n }\n\n if (!modelPromise.model) {\n KosLog.error(`No model found ${modelPromise.modelId}`);\n return false;\n }\n return true;\n });\n\n const settledChildren = await Promise.allSettled(\n childPromises.map((promise) => {\n if (!promise.model || !promise.status) {\n return Promise.resolve();\n }\n\n const { promise: timeoutPromise, cancel: timeoutCancel } =\n rejectAfterDelay(\n MODEL_PROMISE_TIMEOUT_MS,\n promise.model,\n promise.status\n );\n return Promise.race([\n promise.promise\n ?.then(() => {\n timeoutCancel();\n })\n .catch((err) => {\n const enrichedError = enrichError(err, {\n modelType: promise.type || \"unknown\",\n modelId: promise.modelId,\n parentModel: {\n type: sourceModel.modelTypeName,\n id: sourceModel.modelId,\n },\n lifecycle: sourceLifecycle,\n operation: `transition to ${target}`,\n });\n KosLog.error(enrichedError.toDetailedString());\n timeoutCancel();\n // Rethrow to ensure Promise.race can reject\n throw enrichedError;\n }),\n timeoutPromise,\n ]);\n })\n );\n const failedChildren = settledChildren.filter((p) => p.status === \"rejected\");\n\n if (failedChildren.length > 0) {\n const errors = failedChildren.map((result) => {\n const promise = childPromises[settledChildren.indexOf(result)];\n return {\n error:\n result.status === \"rejected\"\n ? result.reason\n : new Error(\"Unknown error\"),\n context: {\n modelType: promise.type || \"unknown\",\n modelId: promise.modelId,\n parentModel: {\n type: sourceModel.modelTypeName,\n id: sourceModel.modelId,\n },\n lifecycle: sourceLifecycle,\n operation: `transition to ${target}`,\n },\n };\n });\n\n logErrorCollection(\n errors,\n `Model ${sourceModel.modelId} had ${failedChildren.length} failed child model(s) on ${sourceLifecycle}`\n );\n }\n};\n\n/**\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport const executeChildrenModelLifecycle = async (\n model: IKosModel,\n target: Transitions,\n sourceLifecycle: DependencyLifecycle\n) => {\n await executeListLifecycle(\n model,\n model.getChildren().filter((child) => !!child),\n target,\n sourceLifecycle\n );\n};\n\n/**\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport const executeDependentModelLifecycle = async (\n model: IKosModel,\n lifecycle: DependencyLifecycle\n) => {\n // wait for all non-lazy dependencies to be ready\n const settled = await Promise.allSettled(\n getDependenciesByLifecycle(model, lifecycle)\n );\n const failed = settled.filter((p) => p.status === \"rejected\");\n if (failed.length) {\n KosLog.error(\n `There were ${failed.length} failed dependent models on ${lifecycle}`\n );\n KosLog.error(failed);\n }\n};\n\n// Type guards are now imported from ./model-type-guards.ts and re-exported above\n","import { isKosDataModel, isKosModelContainer } from \"../../util\";\nimport { DependencyModels } from \"../decorators\";\nimport { SubscriptionHandlers } from \"../decorators/propKeys\";\n\n// kos-devtools-utils.ts\nexport function applyKosModelDevtoolsSupport(model: any) {\n const name = `KosModel(${model.modelTypeName}:${model.modelId})`;\n\n // Tag the model instance\n try {\n Object.defineProperty(model, Symbol.toStringTag, {\n value: name,\n configurable: true,\n });\n } catch {\n // Fallback for environments that don't support Symbol.toStringTag\n model.toString = () => name;\n }\n\n // Update constructor name for React DevTools\n try {\n Object.defineProperty(model.constructor, \"name\", {\n value: `KosModel_${model.modelTypeName}`,\n configurable: true,\n });\n } catch {\n // Fallback for environments that don't support changing constructor name\n model.constructor.name = `KosModel_${model.modelTypeName}`;\n }\n\n // Hide internal manager fields from console\n const hiddenFields = [\n \"fsm\",\n \"effectManager\",\n \"subscriptionManager\",\n \"onlineLifecycleManager\",\n \"companionManager\",\n \"childResolver\",\n \"_offlineQueue\",\n ];\n for (const key of hiddenFields) {\n if (key in model) {\n Object.defineProperty(model, key, { enumerable: false });\n }\n }\n\n // Add a non-enumerable debug snapshot\n Object.defineProperty(model, \"debugState\", {\n enumerable: false,\n configurable: true,\n get() {\n return {\n id: model.modelId,\n type: model.modelTypeName,\n initialized: model.initialized,\n loaded: model.loaded,\n status: model.status,\n onlineStatus: model.onlineStatus,\n activeStatus: model.activeStatus,\n companions: model.companionManager?.all()?.map((m) => m.modelTypeName),\n children: model.getChildren?.().map((m) => m.modelId),\n effects: !!model.effectManager,\n subscriptions: !!model.subscriptionManager,\n };\n },\n });\n\n // Enhance modelData for DevTools\n enhanceModelDataForDevtools(\n model.modelData,\n model.modelTypeName,\n model.modelId,\n model\n );\n}\n\nfunction enhanceModelDataForDevtools(\n modelData: any,\n modelTypeName: string,\n modelId: string,\n model: any\n) {\n // Label in Chrome DevTools\n Object.defineProperty(modelData, Symbol.toStringTag, {\n value: `KosModelData(${modelTypeName}:${modelId})`,\n configurable: true,\n });\n\n // Optional: Update constructor name for React DevTools\n try {\n Object.defineProperty(modelData.constructor, \"name\", {\n value: `${modelTypeName}ModelData`,\n configurable: true,\n });\n } catch {\n // Fallback for environments that don't support changing constructor name\n modelData.constructor.name = `${modelTypeName}ModelData`;\n }\n\n Object.defineProperty(modelData, \"debugState\", {\n enumerable: false,\n configurable: true,\n get() {\n const children = model.getChildren?.() || [];\n const companions = model.companionManager?.all() || [];\n const dependencies: Record<string, any> =\n model.modelData[DependencyModels] || {};\n return {\n id: modelId,\n type: modelTypeName,\n companions: {\n count: companions.length,\n data: companions.map((m) => {\n return { type: m.modelTypeName, id: m.modelId };\n }),\n },\n dependencies: {\n count: Object.keys(dependencies).length,\n data: Object.values(dependencies).map((dependency) => {\n return {\n id: dependency.id || dependency.modelType,\n type: dependency.modelType,\n options: dependency.options,\n lifecycle: dependency.lifecycle,\n };\n }),\n },\n children: {\n count: children.length,\n data: children.map((m) => {\n return { id: m.modelId, type: m.modelTypeName };\n }),\n },\n data: modelData.toJSON?.() || {},\n subscriptions: (() => {\n const handlers = modelData[SubscriptionHandlers] || {};\n const topics = Object.keys(handlers);\n if (topics.length === 0) return { count: 0, data: [] };\n return {\n count: topics.length,\n data: topics.map((topic) => {\n const config = handlers[topic];\n return {\n topic,\n websocket: !!config.websocket,\n ...(config.lifecycle && { lifecycle: config.lifecycle }),\n ...(config.fos && { fos: true }),\n ...(config.bridge && { bridge: true }),\n ...(config.destinationAddress && {\n destinationAddress: config.destinationAddress,\n }),\n ...(config.wildcardName && {\n wildcardName: config.wildcardName,\n }),\n ...(config.flow && { flow: true }),\n ...(config.requiresBaseline && { requiresBaseline: true }),\n };\n }),\n };\n })(),\n };\n },\n });\n\n Object.defineProperty(modelData, \"toJSON\", {\n configurable: true,\n enumerable: false,\n writable: true,\n value: () => {\n const json: Record<string, any> = {};\n\n for (const key of Object.keys(modelData)) {\n if (key.startsWith(\"_\") || typeof modelData[key] === \"function\")\n continue;\n\n try {\n const value = modelData[key];\n\n if (isKosDataModel(value)) {\n // Prefer that model’s toJSON, or fallback to id + type\n json[`[KOS Model] ${key}`] =\n typeof value.toJSON === \"function\"\n ? value.toJSON()\n : { id: value.id, type: value.constructor.name };\n } else if (isKosModelContainer(value)) {\n json[`[KOS Container] ${key}`] =\n typeof value.toJSON === \"function\"\n ? value.toJSON()\n : [\"Container\"];\n } else if (Array.isArray(value)) {\n json[key] = `[Array(${value.length})]`;\n } else if (typeof value === \"object\" && value !== null) {\n json[key] = JSON.parse(JSON.stringify(value));\n } else {\n json[key] = value;\n }\n } catch {\n json[key] = \"[unreadable]\";\n }\n }\n\n return json;\n },\n });\n}\n","import { resolveChild } from \"../../util/model-utils\";\nimport { KosContextManager } from \"../context/kos-context-manager\";\nimport { ChildModels } from \"../decorators\";\nimport { IKosDataModel, IKosModel } from \"../kosModel\";\nimport { KosModelState } from \"../lifecycle\";\nimport type { IKosIdentifiable } from \"../types\";\n\nexport class KosChildResolver {\n constructor(private readonly model: IKosModel) {}\n\n resolve(): IKosModel[] {\n const uniqueChildren = new Set<IKosIdentifiable>([\n ...this.getResolvedDecoratedChildren(),\n ...this.getAdditionalChildren(),\n ...this.model.companionModels.all(),\n ] as IKosIdentifiable[]);\n\n const resolvedModels = Array.from(uniqueChildren)\n .map((child) => this.model.modelManager.getModelById(child.id || \"\"))\n .filter((model) => model && model.status !== KosModelState.FAILED)\n .filter((model): model is IKosModel => !!model);\n\n resolvedModels.forEach((childModel) => {\n try {\n KosContextManager.setParentContext(\n childModel.modelId,\n this.model.modelId\n );\n } catch (e) {\n console.error(\n `Failed to set parent context for ${childModel.modelId} under ${this.model.modelId}`,\n e\n );\n }\n });\n\n return resolvedModels;\n }\n\n private getResolvedDecoratedChildren(): IKosDataModel[] {\n const rawChildren = this.model.modelData?.[ChildModels] || {};\n return Object.keys(rawChildren)\n .map((key) => resolveChild(this.model.modelData[key]))\n .filter((m) => !!m)\n .flat() as IKosDataModel[];\n }\n\n private getAdditionalChildren(): IKosDataModel[] {\n return this.model.modelData?.getChildren?.() || [];\n }\n}\n","// kos-companion-model-manager.ts\nimport { ObservableMap } from \"mobx\";\nimport type { IKosModel } from \"../kosModel\";\n\nexport class KosCompanionModelManager {\n private readonly companions = new ObservableMap<string, IKosModel>();\n\n constructor(private readonly hostModel: IKosModel) {}\n\n add(model: IKosModel): void {\n this.companions.set(model.modelTypeName, model);\n }\n\n clear(): void {\n this.companions.clear();\n }\n\n get(modelTypeName: string): IKosModel | undefined {\n return this.companions.get(modelTypeName);\n }\n\n all(): IKosModel[] {\n return [...this.companions.values()];\n }\n\n get data() {\n return this.companions;\n }\n}\n","import { autorun, reaction, runInAction } from \"mobx\";\nimport { ModelEffects } from \"../decorators/propKeys\"; // adjust path if needed\nimport type { KosOfflineQueueLogger } from \"./kos-offline-queue\";\n\nexport class KosEffectManager {\n private disposers: VoidFunction[] = [];\n\n constructor(\n private modelTypeName: string,\n private modelId: string,\n private modelData: any, // typically IKosDataModel\n private log: KosOfflineQueueLogger\n ) {}\n\n setup(): void {\n const modelEffects = this.modelData?.[ModelEffects] || {};\n\n for (const effectName of Object.keys(modelEffects)) {\n const { value, dependencies, options } = modelEffects[effectName];\n const handler = value.bind(this.modelData);\n\n const autoRunHandler = () => {\n this.log.info(\n `Running effect ${effectName} for ${this.modelTypeName} (${this.modelId})`\n );\n runInAction(() => handler());\n };\n\n const disposer = dependencies\n ? reaction(() => dependencies(this.modelData), autoRunHandler, {\n fireImmediately: !!options?.fireImmediately,\n })\n : autorun(autoRunHandler);\n\n this.disposers.push(disposer);\n }\n }\n\n disposeAll(): void {\n for (const dispose of this.disposers) {\n try {\n dispose();\n } catch (e) {\n this.log.info(`Failed to dispose effect for ${this.modelId}`, e);\n }\n }\n this.disposers = [];\n }\n}\n","import {\n action,\n createMachine,\n interpret,\n invoke,\n state,\n transition,\n} from \"robot3\";\nimport { IKosModel } from \"../kosModel\";\nimport { KosLog } from \"../log\";\nimport { KosModelEvents, KosModelState } from \"./constants\";\n\nconst log = KosLog.createLogger({ name: \"model-active-machine\" });\n\nexport const activeMachine = (model: IKosModel) => {\n const machine = createMachine(KosModelState.INACTIVE, {\n [KosModelState.FAILED]: state(\n transition(KosModelEvents.GO_ACTIVE, KosModelState.ACTIVATING)\n ),\n [KosModelState.INACTIVE]: state(\n transition(KosModelEvents.GO_ACTIVE, KosModelState.ACTIVATING)\n ),\n [KosModelState.ACTIVATING]: invoke(\n () => {\n model.activeStatus = KosModelState.ACTIVATING;\n return model.activate!();\n },\n transition(\n `done`,\n KosModelState.ACTIVE,\n action(() => {\n model.activeStatus = KosModelState.ACTIVE;\n })\n ),\n transition(\n `error`,\n KosModelState.FAILED,\n action(() => {\n model.activeStatus = KosModelState.FAILED;\n })\n )\n ),\n [KosModelState.ACTIVE]: state(\n transition(KosModelEvents.GO_INACTIVE, KosModelState.DEACTIVATING)\n ),\n [KosModelState.DEACTIVATING]: invoke(\n () => {\n model.activeStatus = KosModelState.DEACTIVATING;\n return model.deactivate!();\n },\n transition(\n `done`,\n KosModelState.INACTIVE,\n action(() => {\n model.activeStatus = KosModelState.INACTIVE;\n })\n ),\n transition(\n `error`,\n KosModelState.FAILED,\n action(() => {\n model.activeStatus = KosModelState.FAILED;\n })\n )\n ),\n });\n const service = interpret(machine, (_service) =>\n log.debug(_service.machine.current)\n );\n\n return { service, machine };\n};\n","import { action, createMachine, interpret, state, transition } from \"robot3\";\nimport { IKosModel } from \"../kosModel\";\nimport { KosLog } from \"../log\";\nimport { KosModelEvents, KosModelState } from \"./constants\";\n\nconst log = KosLog.createLogger({ name: \"model-online-machine\" });\nexport const onlineMachine = (model: IKosModel) => {\n const machine = createMachine(KosModelState.OFFLINE, {\n [KosModelState.ONLINE]: state(\n transition(\n KosModelEvents.GO_OFFLINE,\n KosModelState.OFFLINE,\n action(async () => {\n await model.offline!();\n model.onlineStatus = KosModelState.OFFLINE;\n })\n )\n ),\n [KosModelState.OFFLINE]: state(\n transition(\n KosModelEvents.GO_ONLINE,\n KosModelState.ONLINE,\n action(async () => {\n log.debug(`Going online with model ${model.modelId}`);\n await model.online!();\n model.onlineStatus = KosModelState.ONLINE;\n await model.fsm.transitionTo(\n KosModelEvents.INITIALIZE,\n KosModelState.INITIALIZED\n );\n })\n )\n ),\n });\n\n const service = interpret(machine, (_service) =>\n log.debug(_service.machine.current)\n );\n\n return { machine, service };\n};\n","import {\n action,\n createMachine,\n immediate,\n invoke,\n state,\n transition,\n} from \"robot3\";\nimport { kosAction, KosLog } from \"../..\";\nimport { IKosModel } from \"../kosModel\";\nimport { KosModelEvents, KosModelState } from \"./constants\";\nimport { activeMachine } from \"./model-active-machine\";\nimport { onlineMachine } from \"./model-online-machine\";\n\nexport const machine = (model: IKosModel) => {\n const active = activeMachine(model).service;\n const online = onlineMachine(model).service;\n return createMachine(KosModelState.CREATING, {\n [KosModelState.CREATING]: state(\n transition(KosModelEvents.CREATE, KosModelState.CREATED)\n ),\n [KosModelState.CREATED]: state(immediate(KosModelState.INITIALIZING)),\n [KosModelState.INITIALIZING]: invoke(\n () => {\n kosAction(() => {\n model.status = KosModelState.INITIALIZING;\n });\n return model.init!();\n },\n transition(\n `done`,\n KosModelState.INITIALIZED,\n action(() => {\n model.status = KosModelState.INITIALIZED;\n })\n ),\n transition(\n `error`,\n KosModelState.FAILED,\n\n action(() => {\n KosLog.error(\n `Model ${model.modelId} - ${model.modelTypeName} failed to initialize. Transitioning to FAILED state.`\n );\n model.status = KosModelState.FAILED;\n })\n )\n ),\n [KosModelState.INITIALIZED]: state(immediate(KosModelState.LOADING)),\n [KosModelState.LOADING]: invoke(\n () => {\n kosAction(() => {\n model.status = KosModelState.LOADING;\n });\n return model.load!();\n },\n transition(\n `done`,\n KosModelState.LOADED,\n action(() => {\n model.status = KosModelState.LOADED;\n })\n ),\n transition(\n `error`,\n KosModelState.FAILED,\n action(() => {\n model.status = KosModelState.FAILED;\n })\n )\n ),\n [KosModelState.LOADED]: state(\n immediate(KosModelState.READYING),\n transition(KosModelEvents.UNLOAD, KosModelState.UNLOADING)\n ),\n [KosModelState.RESETTING]: invoke(\n () => {\n kosAction(() => {\n model.status = KosModelState.RESETTING;\n });\n\n model.unload?.();\n return model.load!();\n },\n transition(\n `done`,\n KosModelState.LOADED,\n action(() => {\n model.status = KosModelState.LOADED;\n })\n )\n ),\n\n [KosModelState.READYING]: invoke(\n () => {\n kosAction(() => {\n model.status = KosModelState.READYING;\n });\n return model.ready!();\n },\n\n transition(\n `done`,\n KosModelState.READY,\n action(() => {\n kosAction(() => {\n model.status = KosModelState.READY;\n });\n online.send(KosModelEvents.GO_ONLINE);\n })\n ),\n transition(\n `error`,\n KosModelState.FAILED,\n action(() => {\n model.status = KosModelState.FAILED;\n })\n )\n ),\n\n [KosModelState.READY]: state(\n transition(\n KosModelEvents.UNLOAD,\n KosModelState.UNLOADED,\n action(model.unload?.bind(model))\n ),\n transition(KosModelEvents.RESET, KosModelState.RESETTING),\n transition(\n KosModelEvents.GO_ONLINE,\n KosModelState.READY,\n action(() => {\n online.send(KosModelEvents.GO_ONLINE);\n })\n ),\n transition(\n KosModelEvents.GO_OFFLINE,\n KosModelState.READY,\n action(() => {\n online.send(KosModelEvents.GO_OFFLINE);\n })\n ),\n transition(\n KosModelEvents.GO_ACTIVE,\n KosModelState.READY,\n action(() => {\n active.send(KosModelEvents.GO_ACTIVE);\n })\n ),\n transition(\n KosModelEvents.GO_INACTIVE,\n KosModelState.READY,\n action(() => {\n active.send(KosModelEvents.GO_INACTIVE);\n })\n )\n ),\n\n [KosModelState.UNLOADED]: state(),\n [KosModelState.FAILED]: state(),\n });\n};\n","/* eslint-disable max-classes-per-file */\n\nimport { interpret } from \"robot3\";\nimport type { IKosModel } from \"../kosModel\";\nimport { KosLog } from \"../log\";\nimport { machine } from \"./model-machine\";\n\nconst log = KosLog.createLogger({ name: \"kos-model-lifecycle\" });\nexport interface KosOn {\n [k: string]: string;\n}\n\nexport interface KosInvoke<Context> {\n id: string;\n src: (context: Context) => Promise<any>;\n onDone: {\n target: string;\n };\n}\nexport interface KosLifecycleState {\n on: KosOn;\n}\nexport interface KosLifecycleStateContainer<Context> {\n [k: string]: {\n initial?: string;\n states?: KosLifecycleStateContainer<Context>;\n on?: KosOn;\n invoke?: KosInvoke<Context>;\n };\n}\n\nexport interface KosLifecycle<Context = any> {\n id: string;\n initial: string;\n states: KosLifecycleStateContainer<Context>;\n context: Context;\n}\n\nexport const fsm = (model: IKosModel) => {\n const service = interpret(machine(model), (_service) =>\n log.debug(\n `state machine for model ${model.modelId}: ${_service.machine.current});`\n )\n );\n\n return { service };\n};\n","import { IReactionDisposer, when } from \"mobx\";\nimport type { IKosModel } from \"../kosModel\";\nimport { KosModelEvents, KosModelState } from \"../lifecycle/constants\";\nimport { fsm } from \"../lifecycle/kosModelLifecycle\";\nimport type { KosOfflineQueueLogger } from \"./kos-offline-queue\";\n\nexport class KosFSMManager {\n private disposer?: IReactionDisposer;\n private readonly service: ReturnType<typeof fsm>[\"service\"];\n\n constructor(private model: IKosModel, private log: KosOfflineQueueLogger) {\n const machine = fsm(model);\n this.service = machine.service;\n this.service.send(KosModelEvents.CREATE);\n }\n\n /**\n * Returns the current raw state of the FSM\n */\n get current(): KosModelState {\n return this.service.machine.current;\n }\n\n /**\n * Waits for a transition to complete to the target state (or fails if error state reached)\n */\n async transitionTo(\n event: KosModelEvents,\n target: KosModelState,\n error: KosModelState = KosModelState.FAILED\n ): Promise<void> {\n const current = this.getTransitionStatusFor(target);\n\n if (current === target) {\n this.log.debug(\n `Model ${this.model.modelId} already in state ${target}, skipping transition`\n );\n return Promise.resolve();\n }\n\n this.log.debug(\n `Transitioning model ${this.model.modelId} with event ${event} toward target ${target}`\n );\n\n return new Promise<void>((resolve, reject) => {\n // Protect against multiple disposers being created\n this.disposer?.();\n\n this.disposer = when(\n () => {\n const status = this.getTransitionStatusFor(target);\n return status === target || status === error;\n },\n () => {\n const status = this.getTransitionStatusFor(target);\n if (status === error) {\n this.log.error(\n `Model ${this.model.modelId} entered error state ${error} during transition`\n );\n reject(\n new Error(\n `FSM transition failed for model ${this.model.modelId} with event ${event}`\n )\n );\n } else {\n this.log.debug(\n `Model ${this.model.modelId} reached target state ${target}`\n );\n resolve();\n }\n }\n );\n\n this.service.send(event);\n }).finally(() => {\n this.disposer?.();\n this.disposer = undefined;\n });\n }\n\n /**\n * Checks if a given target maps to status, activeStatus, or onlineStatus.\n * Online/offline transitions are tracked on model.onlineStatus because the\n * main FSM keeps status at READY when GO_ONLINE / GO_OFFLINE fire; reading\n * model.status for those targets would hang the transition forever.\n */\n private getTransitionStatusFor(target: KosModelState): KosModelState {\n if ([KosModelState.ACTIVE, KosModelState.INACTIVE].includes(target)) {\n return this.model.activeStatus;\n }\n if ([KosModelState.ONLINE, KosModelState.OFFLINE].includes(target)) {\n return this.model.onlineStatus;\n }\n return this.model.status;\n }\n}\n","// Avoiding direct import to prevent circular dependency\n// import type { KosBrowserRouter } from \"../../../models/models/browser-router\";\nimport { getKosModelSync } from \"../../util\";\nimport {\n getHttpRouteHandlers,\n hasHttpRouteHandlers,\n type IHttpRouteConfig,\n} from \"../decorators/kos-http-decorators\";\nimport type { IKosDataModel, KosContextLogger } from \"../kosModel\";\nimport type { KosRequest, KosResponse } from \"../services/browser-router\";\n\n// Browser router model type - using string to avoid circular dependency\nconst BROWSER_ROUTER_MODEL_TYPE = \"browser-router-model\";\n\n// Generic browser router interface to avoid importing the actual type\ninterface IBrowserRouter extends IKosDataModel {\n use(\n method: string,\n path: string,\n handler: (req: KosRequest, res: KosResponse) => Promise<void>\n ): void;\n remove(method: string, path: string): number;\n removeAllForPath(path: string): number;\n getRoutes(): Array<{ method: string; path: string }>;\n}\n\nexport interface KosHttpRouteLogger {\n info: (...args: any[]) => void;\n warn: (...args: any[]) => void;\n error: (...args: any[]) => void;\n debug: (...args: any[]) => void;\n}\n/**\n * Manager for registering HTTP route handlers from decorators with the browser router\n */\nexport class KosHttpRouteManager {\n private logger: KosHttpRouteLogger;\n private model: any;\n private router: IBrowserRouter | null = null;\n private registered = false;\n private registeredRoutes: Array<{ method: string; path: string }> = [];\n\n constructor(model: any, logger: KosHttpRouteLogger) {\n this.model = model;\n this.logger = logger;\n }\n\n /**\n * Register all HTTP routes during the load lifecycle\n * This is called automatically by the KOS model lifecycle\n */\n registerAll(): void {\n if (!hasHttpRouteHandlers(this.model)) {\n return;\n }\n\n // First try to get the auto-injected router from the model\n let router: IBrowserRouter | undefined = this.model.__httpBrowserRouter;\n\n // If not found via auto-injection, try to find any router property on the model\n if (!router) {\n // Check for any property that is a BrowserRouter\n for (const key of Object.keys(this.model)) {\n const prop = this.model[key];\n if (\n prop &&\n typeof prop === \"object\" &&\n \"use\" in prop &&\n typeof prop.use === \"function\"\n ) {\n router = prop as IBrowserRouter;\n break;\n }\n }\n }\n\n // Finally, fallback to global lookup\n if (!router) {\n router = getKosModelSync<IBrowserRouter>(\n BROWSER_ROUTER_MODEL_TYPE\n )?.model;\n }\n\n if (!router) {\n this.logger.error(\n `Cannot register HTTP routes: BrowserRouter not found. ` +\n `The HTTP decorators should have auto-injected it, but something went wrong.`\n );\n throw new Error(\n `BrowserRouter is required for HTTP route decorators but was not found. ` +\n `This should not happen as HTTP decorators auto-inject the dependency.`\n );\n }\n\n this.setRouter(router);\n }\n\n /**\n * Set the browser router instance\n */\n setRouter(router: IBrowserRouter): void {\n this.router = router;\n if (!this.registered) {\n this.registerRoutes();\n }\n }\n\n /**\n * Check if the model has HTTP route handlers\n */\n hasRoutes(): boolean {\n return hasHttpRouteHandlers(this.model);\n }\n\n /**\n * Register all HTTP route handlers with the browser router\n */\n private registerRoutes(): void {\n if (!this.router) {\n this.logger.warn(\"Cannot register routes: router not set\");\n return;\n }\n\n if (this.registered) {\n this.logger.debug(\"Routes already registered\");\n return;\n }\n\n const routes = getHttpRouteHandlers(this.model);\n\n if (routes.length === 0) {\n return;\n }\n\n this.logger.debug(`Registering ${routes.length} HTTP routes`);\n\n routes.forEach((route: IHttpRouteConfig) => {\n this.registerRoute(route);\n });\n\n this.registered = true;\n }\n\n /**\n * Resolve PropKeys in a path template\n * Supports:\n * - {MODEL_ID} - replaced with the model's ID\n * - {PROP_propertyName} - replaced with the value of model.propertyName\n *\n * @example\n * \"/api/models/{MODEL_ID}/data\" -> \"/api/models/my-model-123/data\"\n * \"/api/{PROP_tenantId}/users\" -> \"/api/tenant-456/users\"\n */\n private resolvePropKey(pathTemplate: string): string {\n const propRegex = /\\{PROP_([^}]+)\\}/g;\n let resolvedPath = pathTemplate;\n\n // Replace {MODEL_ID} with the actual model ID\n if (resolvedPath.includes(\"{MODEL_ID}\")) {\n const modelId = this.model.id || this.model._id || \"unknown\";\n resolvedPath = resolvedPath.replace(/\\{MODEL_ID\\}/g, modelId);\n }\n\n // Replace {PROP_xxx} with the actual property values\n let match: RegExpExecArray | null;\n while ((match = propRegex.exec(pathTemplate)) !== null) {\n const propName = match[1];\n if (propName in this.model) {\n const propValue = this.model[propName];\n resolvedPath = resolvedPath.replace(match[0], String(propValue));\n } else {\n this.logger.warn(\n `Property '${propName}' not found on model for PropKey resolution in path: ${pathTemplate}`\n );\n }\n }\n\n return resolvedPath;\n }\n\n /**\n * Register a single route with the browser router\n */\n private registerRoute(route: IHttpRouteConfig): void {\n if (!this.router) {\n return;\n }\n\n const handler = this.model[route.handler];\n\n if (!handler || typeof handler !== \"function\") {\n this.logger.error(`Handler method '${route.handler}' not found on model`);\n return;\n }\n\n // Resolve any PropKeys in the path\n const resolvedPath = this.resolvePropKey(route.path);\n\n this.logger.debug(\n `Registering ${route.method} ${resolvedPath} -> ${route.handler}` +\n (resolvedPath !== route.path ? ` (resolved from ${route.path})` : \"\")\n );\n\n // Create a wrapper that binds the handler to the model instance\n const boundHandler = async (req: KosRequest, res: KosResponse) => {\n try {\n await handler.call(this.model, req, res);\n } catch (error) {\n this.logger.error(\n `Error in route handler ${route.method} ${resolvedPath}:`,\n error\n );\n res.status?.(500).send({\n error: \"Internal server error\",\n message: error instanceof Error ? error.message : String(error),\n });\n }\n };\n\n // Check for duplicate routes before registering\n this.checkForDuplicateRoute(route.method, resolvedPath);\n\n // Register with the router using the resolved path\n this.router.use(route.method, resolvedPath, boundHandler);\n\n // Track the registered route for cleanup\n this.registeredRoutes.push({ method: route.method, path: resolvedPath });\n }\n\n /**\n * Check for duplicate routes and warn if found\n */\n private checkForDuplicateRoute(method: string, path: string): void {\n if (!this.router) {\n return;\n }\n\n // Get all currently registered routes from the router\n const existingRoutes = this.router.getRoutes();\n const duplicate = existingRoutes.find(\n (route) => route.method === method && route.path === path\n );\n\n if (duplicate) {\n this.logger.warn(\n `Duplicate route detected: ${method} ${path}. ` +\n `This route is already registered by another model. ` +\n `The new handler from model '${\n this.model.id || \"unknown\"\n }' will override the existing one. ` +\n `Only the last registered handler will receive requests. ` +\n `Consider using different paths or namespacing to avoid conflicts.`\n );\n }\n }\n\n /**\n * Dispose of the route manager and cleanup all registered routes\n */\n dispose(): void {\n if (this.router && this.registeredRoutes.length > 0) {\n this.logger.debug(\n `Removing ${this.registeredRoutes.length} HTTP routes for model ${\n this.model.id || \"unknown\"\n }`\n );\n\n let totalRemoved = 0;\n for (const route of this.registeredRoutes) {\n const removed = this.router.remove(route.method, route.path);\n totalRemoved += removed;\n\n if (removed > 0) {\n this.logger.debug(`Removed route: ${route.method} ${route.path}`);\n } else {\n this.logger.warn(\n `Failed to remove route: ${route.method} ${route.path} (not found)`\n );\n }\n }\n\n this.logger.debug(\n `Successfully removed ${totalRemoved} routes from browser router`\n );\n }\n\n // Clean up state\n this.registered = false;\n this.registeredRoutes = [];\n this.router = null;\n }\n\n /**\n * Get all routes registered by this manager (for debugging)\n */\n getRegisteredRoutes(): Array<{ method: string; path: string }> {\n return [...this.registeredRoutes];\n }\n}\n\n/**\n * Helper function to automatically register HTTP routes during model load\n * This is called automatically by the KOS model lifecycle if HTTP route handlers are detected\n *\n * @internal\n */\nexport function registerHttpRoutes(model: any, logger: KosContextLogger): void {\n if (!hasHttpRouteHandlers(model)) {\n return;\n }\n\n // Get the BrowserRouter instance automatically\n const router = getKosModelSync<IBrowserRouter>(BROWSER_ROUTER_MODEL_TYPE);\n\n if (!router?.model) {\n logger.error(\n `Cannot register HTTP routes: BrowserRouter not found. ` +\n `Make sure to include BrowserRouter in your model dependencies or create an instance.`\n );\n throw new Error(\n `BrowserRouter is required for HTTP route decorators but was not found. ` +\n `Add it as a dependency using @kosDependency or ensure an instance exists.`\n );\n }\n\n const manager = new KosHttpRouteManager(model, logger);\n manager.setRouter(router.model);\n}\n","import { ReplayStrategy } from \"../../types/service-response-store\";\n\nexport interface KosOfflineQueueLogger {\n info: (...args: any[]) => void;\n warn: (...args: any[]) => void;\n error: (...args: any[]) => void;\n debug: (...args: any[]) => void;\n}\n\n/**\n * Queued event with temporal metadata\n */\nexport interface QueuedEvent {\n /**\n * Event handler function\n */\n handler: () => void;\n\n /**\n * When this event was received at the framework (timestamp)\n * Used for baseline-delta temporal filtering\n */\n receivedAt: number;\n\n /**\n * Topic this event was received on (for debugging)\n */\n topic?: string;\n\n /**\n * Event payload (for debugging)\n */\n payload?: any;\n}\n\n/**\n * Statistics about queued events\n */\nexport interface QueueStatistics {\n /**\n * Total events in queue\n */\n total: number;\n\n /**\n * Oldest event timestamp\n */\n oldestEventAt?: number;\n\n /**\n * Newest event timestamp\n */\n newestEventAt?: number;\n\n /**\n * Events that would be replayed with AFTER_REQUEST strategy\n */\n afterRequest?: number;\n\n /**\n * Events that would be replayed with AFTER_RESPONSE strategy\n */\n afterResponse?: number;\n}\n\nexport class KosOfflineQueue {\n private queue: QueuedEvent[] = [];\n\n constructor(private log: KosOfflineQueueLogger) {}\n\n /**\n * Enqueue an event handler with temporal tracking\n *\n * @param handler - Event handler function\n * @param topic - Optional topic for debugging\n * @param payload - Optional payload for debugging\n */\n enqueue(handler: () => void, topic?: string, payload?: any): void {\n this.queue.push({\n handler,\n receivedAt: Date.now(),\n topic,\n payload,\n });\n }\n\n /**\n * Flush all queued events (original behavior for backward compatibility)\n */\n flush(): void {\n if (this.queue.length === 0) return;\n\n this.log.warn(`Processing ${this.queue.length} offline message(s)`);\n for (const event of this.queue) {\n try {\n event.handler();\n } catch (e) {\n this.log.error(\"Error while processing offline message:\", e);\n }\n }\n\n this.queue = [];\n this.log.info(\"Offline queue flushed\");\n }\n\n /**\n * Flush queued events with temporal filtering strategy\n * Used for baseline-delta race condition handling\n *\n * @param strategy - Replay strategy to use\n * @param baselineRequestedAt - When baseline request was sent (for AFTER_REQUEST)\n * @param baselineReceivedAt - When baseline response received (for AFTER_RESPONSE)\n */\n flushWithStrategy(\n strategy: ReplayStrategy,\n baselineRequestedAt?: number,\n baselineReceivedAt?: number\n ): void {\n if (this.queue.length === 0) return;\n\n const totalQueued = this.queue.length;\n const eventsToReplay = this.filterEventsByStrategy(\n strategy,\n baselineRequestedAt,\n baselineReceivedAt\n );\n const discarded = totalQueued - eventsToReplay.length;\n\n this.log.warn(\n `Processing ${eventsToReplay.length}/${totalQueued} offline message(s) with strategy: ${strategy}`\n );\n\n for (const event of eventsToReplay) {\n try {\n event.handler();\n } catch (e) {\n this.log.error(\n `Error while processing offline message for topic ${event.topic}:`,\n e\n );\n }\n }\n\n this.queue = [];\n this.log.info(\n `Offline queue flushed with strategy ${strategy}. Replayed: ${eventsToReplay.length}, Discarded: ${discarded}`\n );\n }\n\n /**\n * Filter events based on replay strategy\n * @private\n */\n private filterEventsByStrategy(\n strategy: ReplayStrategy,\n baselineRequestedAt?: number,\n baselineReceivedAt?: number\n ): QueuedEvent[] {\n switch (strategy) {\n case ReplayStrategy.ALL:\n return [...this.queue];\n\n case ReplayStrategy.AFTER_REQUEST:\n if (baselineRequestedAt === undefined) {\n this.log.warn(\n \"AFTER_REQUEST strategy requires baselineRequestedAt, replaying all events\"\n );\n return [...this.queue];\n }\n return this.queue.filter(\n (event) => event.receivedAt >= baselineRequestedAt\n );\n\n case ReplayStrategy.AFTER_RESPONSE:\n if (baselineReceivedAt === undefined) {\n this.log.warn(\n \"AFTER_RESPONSE strategy requires baselineReceivedAt, replaying all events\"\n );\n return [...this.queue];\n }\n return this.queue.filter(\n (event) => event.receivedAt >= baselineReceivedAt\n );\n\n case ReplayStrategy.NONE:\n return [];\n\n default:\n this.log.warn(`Unknown replay strategy: ${strategy}, replaying all`);\n return [...this.queue];\n }\n }\n\n /**\n * Get queue statistics for monitoring\n */\n getStatistics(\n baselineRequestedAt?: number,\n baselineReceivedAt?: number\n ): QueueStatistics {\n if (this.queue.length === 0) {\n return { total: 0 };\n }\n\n const timestamps = this.queue.map((e) => e.receivedAt);\n const stats: QueueStatistics = {\n total: this.queue.length,\n oldestEventAt: Math.min(...timestamps),\n newestEventAt: Math.max(...timestamps),\n };\n\n if (baselineRequestedAt !== undefined) {\n stats.afterRequest = this.queue.filter(\n (e) => e.receivedAt >= baselineRequestedAt\n ).length;\n }\n\n if (baselineReceivedAt !== undefined) {\n stats.afterResponse = this.queue.filter(\n (e) => e.receivedAt >= baselineReceivedAt\n ).length;\n }\n\n return stats;\n }\n\n clear(): void {\n this.queue = [];\n }\n\n get length(): number {\n return this.queue.length;\n }\n\n get isEmpty(): boolean {\n return this.queue.length === 0;\n }\n}\n","import { EventBus } from \"../../../common\";\nimport type { IKosModel } from \"../kosModel\";\nimport { KosModelEvents, KosModelState } from \"../lifecycle\";\nimport type { KosOfflineQueueLogger } from \"./kos-offline-queue\";\n\nexport class KosOnlineLifecycleManager {\n private unsubscribers: VoidFunction[] = [];\n\n constructor(private model: IKosModel, private log: KosOfflineQueueLogger) {}\n\n register(): void {\n // Idempotent: drop any prior subscriptions before re-adding, so callers\n // can register() on reconnect without doubling up /kosCore/online+offline subs.\n this.dispose();\n const modelId = this.model.modelId;\n\n const onlineUnsub = EventBus.subscribe(\"/kosCore/online\", async () => {\n this.log.debug(\n `Online event received for ${modelId}, waiting for readiness...`\n );\n await this.model.whenReady();\n this.log.debug(`${modelId} is ready — sending GO_ONLINE`);\n await this.model.fsm.transitionTo(\n KosModelEvents.GO_ONLINE,\n KosModelState.ONLINE\n );\n });\n\n const offlineUnsub = EventBus.subscribe(\"/kosCore/offline\", async () => {\n this.log.debug(\n `Offline event received for ${modelId} — sending GO_OFFLINE`\n );\n await this.model.fsm.transitionTo(\n KosModelEvents.GO_OFFLINE,\n KosModelState.OFFLINE\n );\n });\n\n this.unsubscribers.push(onlineUnsub.unsubscribe);\n this.unsubscribers.push(offlineUnsub.unsubscribe);\n }\n\n dispose(): void {\n this.unsubscribers.forEach((unsub) => unsub());\n this.unsubscribers = [];\n }\n}\n","/**\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport function uuid() {\n return `xxxxxxxx-xxxx-4xxx-2xxx-xxxxxxxxxxxx`.replace(/[xy]/g, function (c) {\n const r = (Math.random() * 16) | 0;\n const v = c == `x` ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n}\n","/**\n * Utility functions for handling binary data in KOS WebSocket transport\n */\n\n/**\n * Convert ArrayBuffer to base64 string for WebSocket transport\n */\nexport function arrayBufferToBase64(buffer: ArrayBuffer): string {\n const bytes = new Uint8Array(buffer);\n let binary = \"\";\n for (let i = 0; i < bytes.byteLength; i++) {\n binary += String.fromCharCode(bytes[i]);\n }\n return btoa(binary);\n}\n\n/**\n * Convert base64 string back to ArrayBuffer\n */\nexport function base64ToArrayBuffer(base64: string): ArrayBuffer {\n const binary = atob(base64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes.buffer;\n}\n\n/**\n * Convert Blob to ArrayBuffer\n */\nexport async function blobToArrayBuffer(blob: Blob): Promise<ArrayBuffer> {\n return await blob.arrayBuffer();\n}\n\n/**\n * Convert ArrayBuffer to Blob\n */\nexport function arrayBufferToBlob(buffer: ArrayBuffer, type?: string): Blob {\n return new Blob([buffer], { type: type || \"application/octet-stream\" });\n}\n\n/**\n * Convert FormData to a serializable format\n */\nexport async function serializeFormData(formData: FormData): Promise<{\n fields: Record<string, string>;\n files: Array<{ name: string; filename: string; type: string; data: string }>;\n}> {\n const fields: Record<string, string> = {};\n const files: Array<{\n name: string;\n filename: string;\n type: string;\n data: string;\n }> = [];\n\n // Use forEach if entries() is not available\n const entries: Array<[string, FormDataEntryValue]> = [];\n formData.forEach((value, key) => {\n entries.push([key, value]);\n });\n\n for (const [key, value] of entries) {\n if (value instanceof File) {\n const buffer = await value.arrayBuffer();\n files.push({\n name: key,\n filename: value.name,\n type: value.type,\n data: arrayBufferToBase64(buffer),\n });\n } else {\n fields[key] = value.toString();\n }\n }\n\n return { fields, files };\n}\n\n/**\n * Create a ReadableStream from chunks\n */\nexport function createChunkedStream(\n onPull: (\n controller: ReadableStreamDefaultController<Uint8Array>\n ) => Promise<void>\n): ReadableStream<Uint8Array> {\n return new ReadableStream({\n async start() {\n // Initial setup\n },\n async pull(controller) {\n await onPull(controller);\n },\n cancel() {\n // Cleanup on stream cancellation\n },\n });\n}\n\n/**\n * Process body for WebSocket transport\n */\nexport async function processRequestBody(\n body: string | ArrayBuffer | Blob | FormData | Uint8Array | undefined\n): Promise<{ data: string; contentType: string; encoding?: string }> {\n if (!body) {\n return { data: \"\", contentType: \"text/plain\" };\n }\n\n if (typeof body === \"string\") {\n return { data: body, contentType: \"text/plain\" };\n }\n\n if (body instanceof ArrayBuffer || body instanceof Uint8Array) {\n let buffer: ArrayBuffer;\n if (body instanceof Uint8Array) {\n // Create a new ArrayBuffer with just the Uint8Array's data\n buffer = new ArrayBuffer(body.byteLength);\n new Uint8Array(buffer).set(body);\n } else {\n buffer = body;\n }\n return {\n data: arrayBufferToBase64(buffer),\n contentType: \"application/octet-stream\",\n encoding: \"base64\",\n };\n }\n\n if (body instanceof Blob) {\n const buffer = await blobToArrayBuffer(body);\n return {\n data: arrayBufferToBase64(buffer),\n contentType: body.type || \"application/octet-stream\",\n encoding: \"base64\",\n };\n }\n\n if (body instanceof FormData) {\n const serialized = await serializeFormData(body);\n return {\n data: JSON.stringify(serialized),\n contentType: \"multipart/form-data\",\n encoding: \"json\",\n };\n }\n\n throw new Error(\"Unsupported body type\");\n}\n","import {\n HEADER_CACHE_CONTROL,\n HEADER_CONTENT_TYPE,\n HEADER_DESTINATION_ADDR,\n HEADER_FOS_REQUEST_ID,\n HEADER_METHOD,\n HEADER_ORDERED,\n HEADER_REQUEST_ID,\n HEADER_REQUEST_TYPE,\n HEADER_RESPONSE_ID,\n HEADER_SOURCE_ADDR,\n HEADER_TOPIC,\n HEADER_URL,\n HEADER_WORK_TRACKER,\n STATUS,\n} from \"../../common\";\nimport { KosCore } from \"../core/kosCore\";\nimport { KosLog } from \"../core/log\";\nimport {\n KosBroadcastRequest,\n KosFetchReqeust,\n KosFetchResponseParams,\n KosMessageOptions,\n type KosHttpMessageOptions,\n type KosMessageRequest,\n} from \"../types\";\n\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport const createStudioMessage = ({\n path,\n requestId,\n method,\n destinationAddress,\n}: KosFetchReqeust) => {\n let msg = `${HEADER_METHOD}:${method}\\n`;\n msg += `topic:${path}\\n`;\n msg += `${HEADER_URL}:${path}\\n`;\n msg += `${HEADER_REQUEST_ID}:${requestId}\\n`;\n if (destinationAddress) {\n msg += `${HEADER_DESTINATION_ADDR}:${destinationAddress}\\n`;\n }\n\n msg += `${HEADER_REQUEST_TYPE}:kos.studio.request\\n`;\n msg += `\\n`;\n return msg;\n};\n\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport const createFosBaseMessage = ({\n path,\n requestId,\n method,\n destinationAddress,\n ordered,\n tracker,\n}: KosFetchReqeust) => {\n let msg = `${HEADER_TOPIC}:/http${path}\\n`;\n msg += `${HEADER_METHOD}:${method}\\n`;\n msg += `${HEADER_URL}:${path}\\n`;\n msg += `${HEADER_FOS_REQUEST_ID}:${requestId}\\n`;\n if (destinationAddress) {\n msg += `${HEADER_DESTINATION_ADDR}:${destinationAddress}\\n`;\n }\n if (ordered) {\n msg += `${HEADER_ORDERED}:true\\n`;\n }\n if (tracker) {\n msg += `${HEADER_WORK_TRACKER}:${tracker}\\n`;\n }\n msg += `${HEADER_REQUEST_TYPE}:fos.http.request\\n`;\n msg += `\\n`;\n return msg;\n};\n\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport const createBaseMessage = ({\n path,\n requestId,\n method,\n destinationAddress,\n ordered,\n tracker,\n bridge,\n headers,\n}: KosFetchReqeust) => {\n let msg = `${HEADER_METHOD}:${method}\\n`;\n msg += `${HEADER_URL}:${path}\\n`;\n msg += `${HEADER_REQUEST_ID}:${requestId}\\n`;\n if (destinationAddress) {\n msg += `${HEADER_DESTINATION_ADDR}:${destinationAddress}\\n`;\n }\n if (ordered) {\n msg += `${HEADER_ORDERED}:true\\n`;\n }\n if (tracker) {\n msg += `${HEADER_WORK_TRACKER}:${tracker}\\n`;\n }\n\n if (headers) {\n Object.keys(headers).forEach((key) => {\n msg += `${key}:${headers[key]}\\n`;\n });\n }\n msg += `${HEADER_REQUEST_TYPE}:${bridge ? \"fos\" : \"kos\"}.http.request\\n`;\n msg += `\\n`;\n return msg;\n};\n\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport const createMessageBody = (msg: string, body?: string) => {\n let _msg = msg;\n if (body) {\n _msg += body;\n }\n return _msg;\n};\n\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport function createHeaders(headers: Record<string, string>): Headers {\n const _headers = { ...headers };\n return {\n append(name: string, value: string) {\n _headers[name] = value;\n },\n delete(name: string) {\n delete _headers[name];\n },\n get(name: string) {\n return _headers[name];\n },\n forEach(callbackFn) {\n Object.keys(_headers).forEach((key) =>\n callbackFn(_headers[key], key, this)\n );\n },\n has(name) {\n return Object.hasOwn(_headers, name);\n },\n set(name: string, value: string) {\n _headers[name] = value;\n },\n keys() {\n return Object.keys(_headers);\n },\n values() {\n return Object.values(_headers);\n },\n entries() {\n return Object.entries(_headers);\n },\n } as unknown as Headers;\n}\n\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport function createReadableStream(\n msg: string\n): ReadableStream<Uint8Array> | null {\n let sent = false;\n if (window.ReadableStream) {\n const stream = new ReadableStream({\n start(controller) {\n // The following function handles each data chunk\n function push() {\n // \"done\" is a Boolean and value a \"Uint8Array\"\n return Promise.resolve({ done: sent, value: msg }).then(\n ({ done, value }) => {\n // Is there no more data to read?\n if (done) {\n // Tell the browser that we have finished sending data\n controller.close();\n return;\n }\n\n // Get the data and send it to the browser via the controller\n controller.enqueue(value);\n sent = true;\n push();\n }\n );\n }\n\n push();\n },\n });\n return stream;\n }\n return msg as any;\n}\n\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport const createStudioMessageRequest = ({\n path,\n requestId,\n destinationAddress,\n}: KosFetchReqeust) => {\n let msg = `topic:${path}\\n`;\n msg += `${HEADER_URL}:${path}\\n`;\n msg += `${HEADER_REQUEST_ID}:${requestId}\\n`;\n msg += `${HEADER_DESTINATION_ADDR}:${destinationAddress}\\n`;\n msg += `${HEADER_REQUEST_TYPE}:kos.studio.request\\n`;\n msg += `\\n`;\n return msg;\n};\n\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport const createKosMessage = ({\n requestId,\n destinationAddress,\n requestType,\n headers,\n}: KosMessageRequest) => {\n let msg = `${HEADER_REQUEST_ID}:${requestId}\\n`;\n msg += `${HEADER_DESTINATION_ADDR}:${destinationAddress}\\n`;\n msg += `${HEADER_REQUEST_TYPE}:${requestType}\\n`;\n if (headers) {\n Object.keys(headers).forEach((key) => {\n msg += `${key}:${headers[key]}\\n`;\n });\n }\n msg += `\\n`;\n return msg;\n};\n\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport const sendKosMessage = <T extends object>(\n msg: T,\n options: KosMessageRequest\n) => {\n const wrappedMsg = msg;\n\n const _msg = createMessageBody(\n createKosMessage(options),\n typeof wrappedMsg === \"string\" ? wrappedMsg : JSON.stringify(wrappedMsg)\n );\n\n const socketTransport = KosCore.getInstance().transport.socket;\n if (socketTransport) {\n KosLog.debug(\"Sending message\", _msg);\n socketTransport.socket.send(_msg);\n } else {\n KosLog.error(\"socket transport is not initialized\");\n }\n};\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport const createStudioMessageResponse = ({\n path,\n responseId,\n status,\n destinationAddress,\n}: KosFetchResponseParams) => {\n let msg = `topic:${path}\\n`;\n msg += `${HEADER_URL}:${path}\\n`;\n if (responseId) msg += `${HEADER_RESPONSE_ID}:${responseId}\\n`;\n msg += `${STATUS}:${status}\\n`;\n msg += `${HEADER_DESTINATION_ADDR}:${destinationAddress}\\n`;\n\n msg += `${HEADER_REQUEST_TYPE}:kos.studio.response\\n`;\n msg += `\\n`;\n return msg;\n};\n\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport const sendStudioMessageRequest = <T extends object>(\n msg: T,\n options: KosFetchReqeust\n) => {\n const wrappedMsg = msg;\n\n const _msg = createMessageBody(\n createStudioMessageRequest(options),\n JSON.stringify(wrappedMsg)\n );\n\n const socketTransport = KosCore.getInstance().transport.socket;\n if (socketTransport) {\n socketTransport.socket.send(_msg);\n } else {\n KosLog.error(\"socket transport is not initialized\");\n }\n};\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport const sendStudioMessage = <T extends object>(\n msg: T,\n options: KosFetchResponseParams\n) => {\n const wrappedMsg = options.responseId\n ? { status: options.status, data: msg }\n : msg;\n\n const _msg = createMessageBody(\n createStudioMessageResponse(options),\n JSON.stringify(wrappedMsg)\n );\n\n const socketTransport = KosCore.getInstance().transport.socket;\n if (socketTransport) {\n socketTransport.socket.send(_msg);\n } else {\n KosLog.error(\"socket transport is not initialized\");\n }\n};\n\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport const createBroadcastMessageResponse = ({\n topic,\n}: KosBroadcastRequest) => {\n let msg = `topic:${topic}\\n`;\n msg += `${HEADER_REQUEST_TYPE}:kos.broker.send\\n`;\n msg += `\\n`;\n return msg;\n};\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport const createKosHtpMessageResponse = ({\n responseId,\n destinationAddress,\n type,\n sourceAddress,\n status,\n}: KosHttpMessageOptions) => {\n let msg = `${HEADER_RESPONSE_ID}:${responseId}\\n`;\n msg += `${HEADER_DESTINATION_ADDR}:${destinationAddress}\\n`;\n msg += `${HEADER_SOURCE_ADDR}:${sourceAddress}\\n`;\n msg += `${HEADER_REQUEST_TYPE}:${type ?? \"kos.message.request\"}\\n`;\n msg += `${STATUS}:${status}\\n`;\n msg += `${HEADER_CONTENT_TYPE}:application/json\\n`;\n msg += `${HEADER_CACHE_CONTROL}:no-cache\\n`;\n msg += `\\n`;\n return msg;\n};\n\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport const createKosMessageResponse = ({\n topic,\n responseId,\n destinationAddress,\n type,\n}: KosMessageOptions) => {\n let msg = `topic:${topic}\\n`;\n if (responseId) msg += `${HEADER_RESPONSE_ID}:${responseId}\\n`;\n msg += `${HEADER_DESTINATION_ADDR}:${destinationAddress}\\n`;\n msg += `${HEADER_REQUEST_TYPE}:${type ?? \"kos.message.request\"}\\n`;\n msg += `\\n`;\n return msg;\n};\n\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport interface KosBroadcastRequestParams<T extends object> {\n msg: T;\n options: KosBroadcastRequest;\n}\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport const sendBroadcastMessage = <T extends object>({\n msg,\n options,\n}: KosBroadcastRequestParams<T>) => {\n const wrappedMsg = msg;\n\n const _msg = createMessageBody(\n createBroadcastMessageResponse(options),\n JSON.stringify(wrappedMsg)\n );\n\n const socketTransport = KosCore.getInstance().transport.socket;\n\n if (socketTransport) {\n socketTransport.socket.send(_msg);\n } else {\n KosLog.error(\"socket transport is not initialized\");\n }\n};\n\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport interface KosMessageResponseParams<T extends object> {\n msg: T;\n options: KosMessageOptions;\n}\n\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport interface KosHttpMessageResponseParams<T extends object> {\n msg: T;\n options: KosHttpMessageOptions;\n}\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport const sendKosMessageResponse = <T extends object>({\n msg,\n options,\n}: KosMessageResponseParams<T>) => {\n const wrappedMsg = msg;\n\n const _msg = createMessageBody(\n createKosMessageResponse(options),\n JSON.stringify(wrappedMsg)\n );\n\n const socketTransport = KosCore.getInstance().transport.socket;\n if (socketTransport) {\n socketTransport.socket.send(_msg);\n } else {\n KosLog.error(\"socket transport is not initialized\");\n }\n};\n\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport const sendKosHttpMessageResponse = <T extends object>({\n msg,\n options,\n}: KosHttpMessageResponseParams<T>) => {\n const wrappedMsg = msg;\n\n const _msg = createMessageBody(\n createKosHtpMessageResponse(options),\n JSON.stringify(wrappedMsg)\n );\n\n const socketTransport = KosCore.getInstance().transport.socket;\n if (socketTransport) {\n socketTransport.socket.send(_msg);\n } else {\n KosLog.error(\"socket transport is not initialized\");\n }\n};\n\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport const getMessageBody = (payload, skipParse) => {\n try {\n return skipParse ? payload.body ?? payload : JSON.parse(payload.body);\n } catch {\n return payload.body || payload;\n }\n};\n","/**\n * Discriminator carried by every {@link TransportNotReadyError}.\n *\n * Prefer checking `error.code === TRANSPORT_NOT_READY` over `instanceof` when\n * the error may have crossed a bundle boundary (an app and the SDK can end up\n * with separate copies of the class).\n *\n * @category Service Request\n * @kosService core.fetch\n * @kosApiLevel 23\n */\nexport const TRANSPORT_NOT_READY = \"TRANSPORT_NOT_READY\";\n\n/**\n * Raised when a request's timeout budget expires while waiting for the KOS\n * transport to become ready — the socket is closed, reconnecting, or not yet\n * authorized — so the request was never sent.\n *\n * This is deliberately distinct from the `TimeoutError` `DOMException` raised\n * when the request itself times out. The two call for different reactions:\n *\n * - `TimeoutError` — the request reached the service and the service was slow.\n * Retrying later is usually reasonable.\n * - `TransportNotReadyError` — connectivity is down. Retrying the same request\n * will fail the same way until the socket comes back; surface a connectivity\n * state to the user or trigger a reconnect/reload instead.\n *\n * @example\n * ```typescript\n * try {\n * await api.get(\"/api/device/status\", { timeout: 3000 });\n * } catch (error) {\n * if (isTransportNotReadyError(error)) {\n * // websocket is down — show the offline UI\n * }\n * }\n * ```\n *\n * @category Service Request\n * @kosService core.fetch\n * @kosApiLevel 23\n */\nexport class TransportNotReadyError extends Error {\n /** Stable discriminator; see {@link TRANSPORT_NOT_READY}. */\n readonly code = TRANSPORT_NOT_READY;\n\n /**\n * The budget, in milliseconds, that expired while waiting. `undefined` when\n * the wait was cut short by a caller-supplied timeout signal rather than by\n * the request's own budget.\n */\n readonly timeout?: number;\n\n /** The URL of the request that was never sent. */\n readonly url?: string;\n\n constructor(details: { timeout?: number; url?: string } = {}) {\n super(\n `Transport not ready${\n details.timeout === undefined ? \"\" : ` after ${details.timeout}ms`\n }${details.url ? ` - url: ${details.url}` : \"\"}`\n );\n this.name = \"TransportNotReadyError\";\n this.timeout = details.timeout;\n this.url = details.url;\n }\n}\n\n/**\n * Type guard for {@link TransportNotReadyError} that works across bundle\n * boundaries by checking the `code` discriminator rather than the prototype.\n *\n * @category Service Request\n * @kosService core.fetch\n * @kosApiLevel 23\n */\nexport const isTransportNotReadyError = (\n error: unknown\n): error is TransportNotReadyError =>\n !!error && (error as TransportNotReadyError).code === TRANSPORT_NOT_READY;\n","import { EventBus } from \"../../common\";\nimport { KosCore } from \"../core/kosCore\";\nimport { KosLog } from \"../core/log\";\nimport { KosFetchOptions, Response } from \"../types/utils/kos-fetch\";\nimport { uuid } from \"./api-request-id\";\nimport {\n arrayBufferToBlob,\n base64ToArrayBuffer,\n createChunkedStream,\n processRequestBody,\n} from \"./binary-utils\";\nimport {\n createBaseMessage,\n createFosBaseMessage,\n createHeaders,\n createMessageBody,\n createReadableStream,\n createStudioMessage,\n} from \"./kos-message-utils\";\nimport { TransportNotReadyError } from \"./transport-not-ready-error\";\n\nconst log = KosLog.createLogger({ name: \"kos-fetch\" });\n\n/**\n * Represents the response data received from a Kos service.\n *\n * @typeparam T - The type of data in the response.\n *\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport interface KosServiceResponse<T> {\n data: T;\n status: number;\n}\n\nconst DEFAULT_WS_TIMEOUT = 30000;\n\n/**\n * The WebSocket timeout duration in milliseconds. An unparseable\n * `KOS_WS_TIMEOUT` falls back to the default rather than disabling the budget.\n */\nconst WS_TIMEOUT = (() => {\n const configured = process.env.KOS_WS_TIMEOUT\n ? parseInt(process.env.KOS_WS_TIMEOUT)\n : DEFAULT_WS_TIMEOUT;\n return Number.isNaN(configured) ? DEFAULT_WS_TIMEOUT : configured;\n})();\n\n/**\n * Resolves the timeout budget for a request.\n *\n * The budget covers the whole call — waiting for the transport to become ready\n * *and* the request itself — not just the request. A non-positive or\n * non-finite value (`0`, `Infinity`) opts out of the budget entirely and\n * restores the pre-budget behavior of queuing until the transport recovers.\n *\n * @param timeout - The caller-supplied timeout, if any.\n * @returns The budget in milliseconds, or `undefined` for no budget.\n */\nconst resolveTimeoutBudget = (timeout?: number): number | undefined => {\n const budget = timeout ?? WS_TIMEOUT;\n return Number.isFinite(budget) && budget > 0 ? budget : undefined;\n};\n\n/**\n * A delay function used to resolve promises with a delay.\n *\n * @returns A promise that resolves after a minimal delay.\n */\nconst delay = () =>\n new Promise((resolve) => {\n setTimeout(() => {\n resolve(true);\n }, 0);\n });\n\n/**\n * Creates an AbortSignal that will abort after the specified timeout.\n * Falls back to manual implementation for environments without AbortSignal.timeout.\n *\n * @param ms - Timeout in milliseconds\n * @returns An AbortSignal that aborts after the timeout\n */\nconst createTimeoutSignal = (ms: number): AbortSignal => {\n if (\"timeout\" in AbortSignal) {\n return AbortSignal.timeout(ms);\n }\n // Fallback for older environments\n const controller = new AbortController();\n setTimeout(() => {\n controller.abort(\n new DOMException(`Request timed out after ${ms}ms`, \"TimeoutError\")\n );\n }, ms);\n return controller.signal;\n};\n\n/**\n * Combines multiple AbortSignals into one that aborts when any of them abort.\n * Falls back to manual implementation for environments without AbortSignal.any.\n *\n * @param signals - Array of AbortSignals to combine\n * @returns A combined AbortSignal\n */\nconst combineSignals = (signals: AbortSignal[]): AbortSignal => {\n if (\"any\" in AbortSignal) {\n return (\n AbortSignal as unknown as { any: (signals: AbortSignal[]) => AbortSignal }\n ).any(signals);\n }\n // Fallback for older environments\n const controller = new AbortController();\n for (const signal of signals) {\n if (signal.aborted) {\n controller.abort(signal.reason);\n return controller.signal;\n }\n signal.addEventListener(\"abort\", () => controller.abort(signal.reason), {\n once: true,\n });\n }\n return controller.signal;\n};\n\n/**\n * Builds the single signal that governs a request: the caller's signal (if\n * any) combined with the timeout budget (if any).\n *\n * Always returns a signal so the request path has one code path. With no\n * budget and no caller signal the returned signal simply never aborts.\n *\n * @param budget - The timeout budget in milliseconds, or `undefined` for none.\n * @param callerSignal - The caller-supplied abort signal, if any.\n * @returns The signal covering readiness wait and request.\n */\nconst createRequestSignal = (\n budget: number | undefined,\n callerSignal?: AbortSignal\n): AbortSignal => {\n const timeoutSignal = budget ? createTimeoutSignal(budget) : undefined;\n if (timeoutSignal && callerSignal) {\n return combineSignals([callerSignal, timeoutSignal]);\n }\n return timeoutSignal ?? callerSignal ?? new AbortController().signal;\n};\n\n/**\n * True when an abort reason represents an expired timeout rather than an\n * explicit caller abort.\n */\nconst isTimeoutReason = (reason: unknown): boolean =>\n (reason as DOMException | undefined)?.name === \"TimeoutError\";\n\n/**\n * Determines the appropriate message factory function based on the provided options.\n *\n * @param options - The Kos fetch options.\n * @returns A message factory function.\n */\nconst fetchMessageFactory = (options?: KosFetchOptions) => {\n if (options?.studio) {\n return createStudioMessage;\n } else if (options?.fos) {\n return createFosBaseMessage;\n } else {\n return createBaseMessage;\n }\n};\n\n/**\n * Performs a Kos WebSocket fetch operation, providing fetch-like behavior over a WebSocket transport.\n *\n * The timeout is a budget for the **entire call** — waiting for the transport\n * to become ready plus the request itself — so a request issued while the\n * socket is down or reconnecting settles within the budget instead of parking\n * forever on transport readiness. If the transport becomes ready with budget\n * left, the remainder applies to the request; the clock is not restarted.\n *\n * @async\n * @param url - The URL to fetch from.\n * @param options - The Kos fetch options.\n * @returns A promise that resolves to the response from the server.\n * @throws {TransportNotReadyError} if the budget expires before the transport\n * is ready, meaning the request was never sent.\n * @throws {DOMException} TimeoutError if the request itself times out.\n * @throws {DOMException} AbortError if the request is aborted via signal.\n */\nconst kosFetchWs = async (\n url: string,\n options?: KosFetchOptions\n): Promise<Response> => {\n const transport = KosCore.getInstance().transport;\n const requestId = uuid();\n const urlObj = new URL(url);\n const path = `${urlObj.pathname}${urlObj.search}`;\n log.debug(`path: ${path}`);\n const budget = resolveTimeoutBudget(options?.timeout);\n const messageFactory = fetchMessageFactory(options);\n\n // Create the unified abort signal (timeout + caller signal) BEFORE waiting on\n // the transport. The readiness wait is part of the budget: `whenReady()` has\n // no timeout of its own and `connectionEstablished` goes false on socket\n // close, so a signal created after the wait would never start ticking for a\n // request issued while the transport is down.\n const signal = createRequestSignal(budget, options?.signal);\n\n try {\n await transport.whenReady({ signal });\n } catch (error) {\n if (isTimeoutReason(error)) {\n log.error(\n `Transport not ready${\n budget === undefined ? \"\" : ` after ${budget}ms`\n } - request not sent - url: ${url}`\n );\n throw new TransportNotReadyError({ timeout: budget, url });\n }\n log.debug(`Request aborted while waiting for transport - url: ${url}`);\n throw error;\n }\n\n // Process body and get content type\n const processedBody = await processRequestBody(options?.body);\n const additionalHeaders: Record<string, string> = {};\n\n if (processedBody.contentType) {\n additionalHeaders[\"content-type\"] = processedBody.contentType;\n }\n if (processedBody.encoding) {\n additionalHeaders[\"content-encoding\"] = processedBody.encoding;\n }\n\n const msg = createMessageBody(\n messageFactory({\n path,\n requestId,\n method: options?.method || `GET`,\n destinationAddress: options?.destinationAddress || \"\",\n ordered: options?.ordered,\n tracker: options?.tracker,\n bridge: options?.bridge,\n headers: { ...options?.headers, ...additionalHeaders },\n }),\n processedBody.data\n );\n\n return new Promise((resolve, reject) => {\n let unsubscribe: (() => void) | null = null;\n\n // Check if already aborted before starting\n if (signal.aborted) {\n const reason = signal.reason;\n if (reason?.name === \"TimeoutError\") {\n log.error(`Timeout occurred - url: ${url}`);\n } else {\n log.debug(`Request aborted - url: ${url}`);\n }\n reject(reason || new DOMException(\"Aborted\", \"AbortError\"));\n return;\n }\n\n // Single abort handler for both user abort and timeout\n const onAbort = () => {\n if (unsubscribe) unsubscribe();\n\n const reason = signal.reason;\n if (reason?.name === \"TimeoutError\") {\n log.error(`Timeout occurred - url: ${url}`);\n } else {\n log.debug(`Request aborted - url: ${url}`);\n }\n\n reject(reason || new DOMException(\"Aborted\", \"AbortError\"));\n };\n\n signal.addEventListener(\"abort\", onAbort, { once: true });\n\n const subscription = EventBus.subscribe(requestId, (responseMsg) => {\n // Remove abort listener on successful response\n signal.removeEventListener(\"abort\", onAbort);\n\n const responseHeaders = responseMsg?.headers || {};\n const contentType = responseHeaders[\"content-type\"] || \"text/plain\";\n const encoding = responseHeaders[\"content-encoding\"];\n const responseBody = responseMsg?.body || \"\";\n\n // Handle binary data based on encoding\n let bodyData: string | ArrayBuffer = responseBody;\n if (encoding === \"base64\" && responseBody) {\n try {\n bodyData = base64ToArrayBuffer(responseBody);\n } catch (e) {\n log.error(\"Failed to decode base64 response\", e);\n }\n }\n\n const response: Response = {\n headers: createHeaders(responseHeaders),\n status:\n (responseHeaders[`status`] && parseInt(responseHeaders[`status`])) ||\n 200,\n ok: responseHeaders[`status`] === `200`,\n\n json: async <T>(): Promise<T | null> => {\n try {\n if (typeof bodyData === \"string\") {\n return bodyData.length ? (JSON.parse(bodyData) as T) : null;\n } else {\n // Convert ArrayBuffer to string for JSON parsing\n const decoder = new TextDecoder();\n const text = decoder.decode(bodyData);\n return text.length ? (JSON.parse(text) as T) : null;\n }\n } catch (e) {\n throw Error(`Not a JSON response`);\n }\n },\n\n text: async (): Promise<string> => {\n if (typeof bodyData === \"string\") {\n return bodyData;\n } else {\n const decoder = new TextDecoder();\n return decoder.decode(bodyData);\n }\n },\n\n arrayBuffer: async (): Promise<ArrayBuffer> => {\n if (bodyData instanceof ArrayBuffer) {\n return bodyData;\n } else {\n const encoder = new TextEncoder();\n return encoder.encode(bodyData).buffer;\n }\n },\n\n blob: async (): Promise<Blob> => {\n if (bodyData instanceof ArrayBuffer) {\n return arrayBufferToBlob(bodyData, contentType);\n } else {\n return new Blob([bodyData], { type: contentType });\n }\n },\n\n formData: async (): Promise<FormData> => {\n // This is a simplified implementation\n // In a real scenario, you'd need to parse multipart/form-data\n const formData = new FormData();\n if (\n contentType === \"multipart/form-data\" &&\n typeof bodyData === \"string\"\n ) {\n try {\n const parsed = JSON.parse(bodyData);\n if (parsed.fields) {\n Object.entries(parsed.fields).forEach(([key, value]) => {\n formData.append(key, value as string);\n });\n }\n if (parsed.files) {\n // Files would need special handling\n log.warn(\n \"File reconstruction in FormData not fully implemented\"\n );\n }\n } catch (e) {\n throw new Error(\"Failed to parse FormData\");\n }\n }\n return formData;\n },\n\n body: options?.stream\n ? createChunkedStream(async (controller) => {\n // For streaming support, you'd need to handle chunked messages\n // This is a placeholder for future implementation\n if (bodyData instanceof ArrayBuffer) {\n controller.enqueue(new Uint8Array(bodyData));\n } else {\n const encoder = new TextEncoder();\n controller.enqueue(encoder.encode(bodyData));\n }\n controller.close();\n })\n : createReadableStream(typeof bodyData === \"string\" ? bodyData : \"\"),\n\n redirected: false,\n statusText: ``,\n type: `basic`,\n url: ``,\n clone: function (): Response {\n // Implement a basic clone\n return { ...this };\n },\n bodyUsed: false,\n };\n\n // Clean up the subscription\n subscription.unsubscribe();\n delay().then(() => resolve(response));\n });\n\n // Store unsubscribe function for cleanup\n unsubscribe = subscription.unsubscribe;\n\n const socket = options?.fos ? transport.fosSocket : transport.socket;\n if (!socket) {\n throw Error(`No web socket transport available: ${options}`);\n }\n socket?.send(msg);\n });\n};\n\n/**\n * Represents the base URL for Kos fetch requests.\n *\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nlet BASE_URL = `kos:`;\n/**\n * KOS fetch function — WebSocket-based fetch implementation for KOS transport.\n *\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nlet kosFetch = kosFetchWs;\n// Check if mocking of fetch requests is enabled.\n// Deprecated: KOS_MOCK_FETCH is a compile-time switch that bypasses the KOS\n// transport entirely. Prefer the KosMock facility (core/core/transport/mock),\n// which mocks at the transport layer with runtime control.\nif (process.env.KOS_MOCK_FETCH === `true`) {\n const PORT = process.env.KOS_PORT || \"9999\";\n kosFetch = fetch as typeof kosFetch; // Use the standard fetch for mocking\n BASE_URL = `http://localhost:${PORT}`;\n}\n\n// Export the kosFetch function and BASE_URL for use in other modules\nexport { BASE_URL, kosFetch };\n","import { KosLog } from \"../core/log\";\nimport type { KosFetchOptions, RetryConfig } from \"../types\";\nimport type { Response } from \"../types/utils/kos-fetch\";\nimport { BASE_URL, kosFetch } from \"./kos-fetch\";\nimport type { ErrorResponseContext } from \"./service-request-error\";\nimport { isTransportNotReadyError } from \"./transport-not-ready-error\";\n\nexport type { ErrorResponseContext };\n\n/**\n * Resolves the service URL configuration.\n * @param _service - The optional service name (not used).\n * @returns An object with `isMock` and `URL` properties.\n *\n * @kosService core.service-request\n * @kosApiLevel 2\n */\nexport const resolveBaseUrl = () => {\n const MOCK = false;\n const URL = BASE_URL;\n return { isMock: MOCK, URL };\n};\n\nconst log = KosLog.createLogger({ name: \"kos-service-request\" });\nconst ERROR_UNKNOWN = \"errUnknown\";\n\n/**\n * Error string returned when the transport never became ready inside the\n * request's timeout budget, so the request was never sent. Distinct from\n * `\"Request timed out\"`, which means the request was sent and the service was\n * slow.\n *\n * @kosService core.service-request\n * @kosApiLevel 23\n */\nexport const ERROR_TRANSPORT_NOT_READY = \"Transport not ready\";\ntype NonNeverKeys<T> = {\n [K in keyof T]-?: T[K] extends never | undefined ? never : K;\n}[keyof T];\n\n/**\n * @kosService core.service-request\n */\nexport type AvailableMethods<T> = Exclude<\n NonNeverKeys<T>,\n \"parameters\" | \"requestBody\"\n>;\n\n/**\n * @kosService core.service-request\n */\nexport type PathsByMethod<T> = {\n [Method in \"get\" | \"put\" | \"post\" | \"delete\"]: {\n [K in keyof T]: Method extends AvailableMethods<T[K]> ? K : never;\n }[keyof T & keyof { [K in keyof T]: Method extends keyof T[K] ? K : never }];\n};\n\ntype ClientGetParams<\n Paths extends Record<string, any>,\n K extends keyof Paths\n> = Paths[K][\"get\"] extends { parameters: infer P } ? P : never;\n\ntype ClientPostParams<\n Paths extends Record<string, any>,\n K extends keyof Paths\n> = Paths[K][\"post\"] extends { parameters: infer P } ? P : never;\n\ntype ClientPutParams<\n Paths extends Record<string, any>,\n K extends keyof Paths\n> = Paths[K][\"put\"] extends { parameters: infer P } ? P : never;\n\ntype ClientDeleteParams<\n Paths extends Record<string, any>,\n K extends keyof Paths\n> = Paths[K][\"delete\"] extends { parameters: infer P } ? P : never;\n\ntype _ClientGetBody<\n Paths extends Record<string, any>,\n K extends keyof Paths\n> = Paths[K][\"get\"] extends { requestBody: { content: infer B } }\n ? B[keyof B]\n : never;\n\ntype ClientPostBody<\n Paths extends Record<string, any>,\n K extends keyof Paths\n> = Paths[K][\"post\"] extends { requestBody: { content: infer B } }\n ? B[keyof B]\n : never;\n\ntype ClientPutBody<\n Paths extends Record<string, any>,\n K extends keyof Paths\n> = Paths[K][\"put\"] extends { requestBody: { content: infer B } }\n ? B[keyof B]\n : never;\n\ntype _ClientDeleteBody<\n Paths extends Record<string, any>,\n K extends keyof Paths\n> = Paths[K][\"delete\"] extends { requestBody: { content: infer B } }\n ? B[keyof B]\n : never;\n\n/**\n * @kosService core.service-request\n */\nexport type ClientResponse<\n Paths extends Record<string, any>,\n K extends keyof Paths,\n M extends AvailableMethods<Paths[K]> | string\n> = Paths[K][M] extends { responses: { 200: { content: infer R } } }\n ? R[keyof R]\n : unknown;\n\n/**\n * @kosService core.service-request\n */\nexport type ClientParams<\n Paths extends Record<string, any>,\n K extends keyof Paths,\n M extends AvailableMethods<Paths[K]> | string\n> = Paths[K][M] extends { parameters: infer P } ? P : never;\n\n/**\n * @kosService core.service-request\n */\nexport type ClientBody<\n Paths extends Record<string, any>,\n K extends keyof Paths,\n M extends AvailableMethods<Paths[K]> | string\n> = Paths[K][M] extends { requestBody: { content: infer B } }\n ? B[keyof B]\n : never;\n\n/**\n * @kosService core.service-request\n */\n/** Transport facts about a response, alongside its parsed body. */\nexport interface ResponseContext {\n status: number;\n headers: Record<string, string>;\n}\n\nexport type ServiceResponse<T> =\n | [error: string, data: null, errorContext?: ErrorResponseContext]\n | [error: null, data: T, context?: ResponseContext];\n\n/**\n * @kosService core.service-request\n */\nexport type DeepRequired<T> = {\n [K in keyof T]-?: T[K] extends object\n ? DeepRequired<T[K]>\n : T[K] extends Array<infer U>\n ? Array<DeepRequired<U>>\n : T[K];\n};\n/**\n * @kosService core.service-request\n */\nexport type ElementType<T> = T extends (infer U)[] ? U : never;\n\n/** Methods considered mutating — skipped by retry unless `retryMutations` is true */\nconst MUTATING_METHODS = new Set([\"POST\", \"PUT\", \"DELETE\", \"PATCH\"]);\n\n/** Default retry settings applied when `retry: true` or partial config */\nconst RETRY_DEFAULTS: Required<Omit<RetryConfig, \"retryOn\">> = {\n maxAttempts: 3,\n baseDelayMs: 350,\n backoffFactor: 2,\n retryMutations: false,\n};\n\n/**\n * Resolves a `retry` option into a fully-populated config or `undefined`.\n * @internal\n */\nfunction resolveRetryConfig(\n retry: boolean | RetryConfig | undefined\n):\n | (Required<Omit<RetryConfig, \"retryOn\">> & Pick<RetryConfig, \"retryOn\">)\n | undefined {\n if (!retry) return undefined;\n if (retry === true) return { ...RETRY_DEFAULTS };\n return { ...RETRY_DEFAULTS, ...retry };\n}\n\n// Define a generic request function using your custom transport layer\nasync function clientRequest<\n Paths extends Record<string, any>,\n K extends keyof Paths,\n M extends AvailableMethods<Paths[K]> | string\n>(\n endpoint: K,\n method: M,\n options?: RequestOptions,\n params?: ClientParams<Paths, K, M>,\n body?: ClientBody<Paths, K, M>\n): Promise<ServiceResponse<ClientResponse<Paths, K, M>>> {\n const url = (params as any)?.path\n ? Object.keys((params as any).path).reduce<string>(\n (acc, key) =>\n String(acc).replace(`{${key}}`, (params as any)?.path[key]),\n String(endpoint)\n )\n : String(endpoint);\n\n const query = (params as any)?.query\n ? Object.keys((params as any).query)\n .map(\n (key) =>\n `${encodeURIComponent(key)}=${encodeURIComponent(\n (params as any).query[key]\n )}`\n )\n .join(\"&\")\n : \"\";\n\n const fullUrl = `${resolveBaseUrl().URL}${url}${query ? `?${query}` : \"\"}`;\n\n log.debug(`fullUrl: ${fullUrl}`);\n const fetchOptions = {\n method: String(method).toUpperCase() as any,\n body: null as any,\n ...options,\n };\n if (body) {\n fetchOptions.body = JSON.stringify(body);\n }\n\n const retryConfig = resolveRetryConfig(options?.retry);\n\n // If retry is disabled or method is mutating and retryMutations is false, single attempt\n const shouldRetry =\n retryConfig &&\n (retryConfig.retryMutations || !MUTATING_METHODS.has(fetchOptions.method));\n\n if (!shouldRetry) {\n return executeFetch(fullUrl, fetchOptions);\n }\n\n return executeFetchWithRetry(fullUrl, fetchOptions, retryConfig);\n}\n\n/**\n * The transport facts a caller may need: `dst-addr` names the client the\n * response was sent to, which is how a window learns its own address.\n * @internal\n */\nfunction responseContext(response: Response): ResponseContext {\n const headers: Record<string, string> = {};\n response.headers.forEach((value, key) => {\n headers[key] = value;\n });\n return { status: response.status, headers };\n}\n\n/**\n * Executes a single fetch attempt and returns a service response tuple.\n * @internal\n */\nasync function executeFetch(fullUrl: string, fetchOptions: any): Promise<any> {\n try {\n const response = await kosFetch(fullUrl, fetchOptions);\n\n if (response.status < 200 || response.status >= 400) {\n const errorContext = await captureErrorResponseContext(response);\n return [`${response.statusText || ERROR_UNKNOWN}`, null, errorContext];\n }\n\n const payload = await response.json();\n return [null, payload.data ?? payload, responseContext(response)];\n } catch (error) {\n // Transport down — the request was never sent. Distinct from a timeout so\n // callers can react to connectivity rather than to a slow service.\n if (isTransportNotReadyError(error)) {\n log.error(`Transport not ready, request not sent: ${fullUrl}`);\n return [ERROR_TRANSPORT_NOT_READY, null];\n }\n if (error instanceof DOMException) {\n if (error.name === \"TimeoutError\") {\n log.error(`Request timed out: ${fullUrl}`);\n return [\"Request timed out\", null];\n }\n if (error.name === \"AbortError\") {\n log.debug(`Request aborted: ${fullUrl}`);\n return [\"Request aborted\", null];\n }\n }\n log.error(`Unexpected error during fetch: ${error}`);\n return [error instanceof Error ? error.message : ERROR_UNKNOWN, null];\n }\n}\n\n/**\n * Executes a fetch with retry and exponential backoff.\n *\n * Retries are attempted when:\n * 1. The response has an error status (< 200 or >= 400)\n * 2. The `retryOn` predicate (if provided) returns `true` for that response\n * 3. We haven't exceeded `maxAttempts`\n *\n * Network-level errors (timeouts, aborts) are NOT retried — they indicate\n * transport problems, not transient server errors.\n *\n * @internal\n */\nasync function executeFetchWithRetry(\n fullUrl: string,\n fetchOptions: any,\n config: Required<Omit<RetryConfig, \"retryOn\">> & Pick<RetryConfig, \"retryOn\">\n): Promise<any> {\n let lastResult: any;\n\n for (let attempt = 1; attempt <= config.maxAttempts; attempt++) {\n try {\n const response: Response = await kosFetch(fullUrl, fetchOptions);\n\n // Success — return immediately\n if (response.status >= 200 && response.status < 400) {\n const payload = await response.json();\n return [null, payload.data ?? payload, responseContext(response)];\n }\n\n // Error response — check if we should retry\n const errorContext = await captureErrorResponseContext(response);\n lastResult = [\n `${response.statusText || ERROR_UNKNOWN}`,\n null,\n errorContext,\n ];\n\n // If predicate says don't retry, stop immediately\n if (config.retryOn && !config.retryOn(response)) {\n log.debug(\n `Retry predicate returned false for ${fullUrl} (status ${response.status}), stopping`\n );\n return lastResult;\n }\n\n if (attempt < config.maxAttempts) {\n const delayMs =\n config.baseDelayMs * Math.pow(config.backoffFactor, attempt - 1);\n log.warn(\n `Request to ${fullUrl} failed (status ${response.status}), ` +\n `retrying in ${delayMs}ms (attempt ${attempt}/${config.maxAttempts})`\n );\n await new Promise((resolve) => setTimeout(resolve, delayMs));\n }\n } catch (error) {\n // Network-level errors are not retried — return immediately\n if (isTransportNotReadyError(error)) {\n log.error(`Transport not ready, request not sent: ${fullUrl}`);\n return [ERROR_TRANSPORT_NOT_READY, null];\n }\n if (error instanceof DOMException) {\n if (error.name === \"TimeoutError\") {\n log.error(`Request timed out: ${fullUrl}`);\n return [\"Request timed out\", null];\n }\n if (error.name === \"AbortError\") {\n log.debug(`Request aborted: ${fullUrl}`);\n return [\"Request aborted\", null];\n }\n }\n log.error(`Unexpected error during fetch: ${error}`);\n return [error instanceof Error ? error.message : ERROR_UNKNOWN, null];\n }\n }\n\n // All attempts exhausted — return last error result\n log.error(`All ${config.maxAttempts} attempts failed for ${fullUrl}`);\n return lastResult;\n}\n\n/**\n * Reads the response body and headers from an HTTP error response.\n * Best-effort: if the body cannot be parsed as JSON it falls back to text,\n * and if that fails the body is left undefined.\n * @internal\n */\nasync function captureErrorResponseContext(\n response: Response\n): Promise<ErrorResponseContext> {\n let responseBody: unknown;\n try {\n const text = await response.text();\n try {\n responseBody = JSON.parse(text);\n } catch {\n responseBody = text;\n }\n } catch {\n responseBody = undefined;\n }\n\n const responseHeaders: Record<string, string> = {};\n response.headers.forEach((value, key) => {\n responseHeaders[key] = value;\n });\n\n return {\n status: response.status,\n statusText: response.statusText,\n responseBody,\n responseHeaders,\n };\n}\n\ntype RequestOptions = Omit<KosFetchOptions, \"method\" | \"body\">;\n/**\n * @kosService core.service-request\n * @kosApiLevel 2\n */\nexport function createClient<Paths extends Record<string, any>>() {\n // Extract valid paths for each method\n type ValidPaths = PathsByMethod<Paths>;\n\n return {\n get: <K extends ValidPaths[\"get\"]>(\n endpoint: K,\n params?: ClientGetParams<Paths, K>,\n options?: RequestOptions\n ) => clientRequest<Paths, K, \"get\">(endpoint, \"get\", options, params),\n\n post: <K extends ValidPaths[\"post\"]>(\n endpoint: K,\n params?: ClientPostParams<Paths, K>,\n body?: ClientPostBody<Paths, K>,\n options?: RequestOptions\n ) =>\n clientRequest<Paths, K, \"post\">(endpoint, \"post\", options, params, body),\n\n put: <K extends ValidPaths[\"put\"]>(\n endpoint: K,\n params?: ClientPutParams<Paths, K>,\n body?: ClientPutBody<Paths, K>,\n options?: RequestOptions\n ) => clientRequest<Paths, K, \"put\">(endpoint, \"put\", options, params, body),\n\n delete: <K extends ValidPaths[\"delete\"]>(\n endpoint: K,\n params?: ClientDeleteParams<Paths, K>,\n body?: ClientPutBody<Paths, K>,\n options?: RequestOptions\n ) =>\n clientRequest<Paths, K, \"delete\">(\n endpoint,\n \"delete\",\n options,\n params,\n body\n ),\n };\n}\n","import {\n kosServiceRequest as baseKosServiceRequest,\n type HttpMethod,\n type IKosServiceRequestParams,\n type KosExecutionContext,\n type RequestOptions,\n} from \"../../core/core/decorators/kos-service-request\";\nimport {\n createClient,\n type ClientResponse,\n type PathsByMethod,\n} from \"../../core/util/kos-service-request\";\nimport { paths } from \"./openapi\";\n\nconst api = createClient<paths>();\n\nexport type KosApi = paths;\nexport type ApiPath = keyof paths;\nexport type ValidPaths = PathsByMethod<paths>;\n\nexport type GetPaths = ValidPaths[\"get\"];\nexport type PostPaths = ValidPaths[\"post\"];\nexport type PutPaths = ValidPaths[\"put\"];\nexport type DeletePaths = ValidPaths[\"delete\"];\n\nexport type ApiResponse<\n Path extends ApiPath,\n Method extends \"get\" | \"post\" | \"put\" | \"delete\" = \"get\"\n> = ClientResponse<KosApi, Path, Method>;\n\n/**\n * Request options for controlling fetch behavior\n * Includes destinationAddress, headers, timeout, and other transport options\n *\n * @example\n * ```typescript\n * const options: KosRequestOptions = {\n * destinationAddress: 'device-123',\n * headers: { 'X-Custom-Header': 'value' },\n * timeout: 5000\n * };\n * ```\n */\nexport type { RequestOptions as KosRequestOptions };\n\n/**\n * Type alias for strongly-typed execution context.\n * The context is automatically injected as the last parameter to methods\n * decorated with @kosServiceRequest (without lifecycle) or @kosFuture.\n *\n * @example With @kosServiceRequest\n * ```typescript\n * @kosServiceRequest({\n * path: PATH_DEVICE_STATUS,\n * method: 'get'\n * })\n * async refreshStatus(\n * ctx: ExecutionContext<typeof PATH_DEVICE_STATUS, 'get'>\n * ): Promise<void> {\n * const [error, response] = await ctx.$request({\n * queryParams: { includeMetadata: true }, // ← Fully typed!\n * requestOptions: {\n * destinationAddress: 'device-123',\n * timeout: 5000\n * }\n * });\n * if (error) throw new Error(error);\n * this.status = response?.status;\n * }\n * ```\n *\n * @example With @kosFuture (context-based tracker)\n * ```typescript\n * @kosFuture({ trackerPolicy: 'context' })\n * async loadData(filter: string, ctx: ExecutionContext): Promise<Data> {\n * const data = await fetchData(filter);\n * ctx.$tracker?.complete();\n * return data;\n * }\n * ```\n */\nexport type ExecutionContext<\n Path extends ApiPath = ApiPath,\n Method extends HttpMethod = \"get\"\n> = KosExecutionContext<paths, Path, Method>;\n\n/**\n * Typed decorator factory for @kosServiceRequest with KOS SDK OpenAPI types\n *\n * Provides full IntelliSense and type safety for path, query params, and body\n * based on the KOS SDK OpenAPI schema.\n *\n * @example\n * ```typescript\n * import { kosServiceRequest, PATH_DEVICE_STATUS } from '../../utils/service';\n *\n * @kosServiceRequest({\n * path: PATH_DEVICE_STATUS,\n * method: 'get',\n * lifecycle: DependencyLifecycle.LOAD,\n * queryParams: { includeMetadata: true } // ← Fully typed!\n * })\n * private onStatusLoaded(): void {\n * const response = getServiceResponse(this, PATH_DEVICE_STATUS, 'get');\n * }\n * ```\n */\nexport function kosServiceRequest<\n Path extends ApiPath,\n Method extends HttpMethod = \"get\",\n Response = any,\n TransformedResponse = Response\n>(\n params: IKosServiceRequestParams<\n paths,\n Path,\n Method,\n Response,\n TransformedResponse\n >\n) {\n return baseKosServiceRequest<\n paths,\n Path,\n Method,\n Response,\n TransformedResponse\n >(params);\n}\n\nexport default api;\n","import API from \"../../../models/utils/service\";\nimport { DependencyLifecycle } from \"../../types\";\nimport { ResponseRetention } from \"../../types/service-response-store\";\nimport type { ServiceResponse } from \"../../util/kos-service-request\";\nimport type { ErrorResponseContext } from \"../../util/service-request-error\";\nimport { ServiceRequestError } from \"../../util/service-request-error\";\nimport {\n ServiceRequestHandlers,\n type HttpMethod,\n type ServiceRequestMetadata,\n} from \"../decorators/kos-service-request\";\nimport { resolveParameters } from \"../decorators/resolve-parameters\";\nimport type { IKosDataModel } from \"../kosModel\";\nimport { KosLog } from \"../log\";\nimport { ServiceResponseStore } from \"./service-response-store\";\n\nconst log = KosLog.createLogger({\n name: \"kos-service-request-manager\",\n group: \"Model\",\n});\n\n// ============================================================================\n// Zone 3: Low-level helper functions\n// ============================================================================\n\n/**\n * Checks if request should execute based on condition\n * @internal\n */\nfunction shouldExecuteRequest(\n metadata: ServiceRequestMetadata,\n model: IKosDataModel\n): boolean {\n return !metadata.condition || metadata.condition(model);\n}\n\n/**\n * Resolves path parameters from metadata\n * @internal\n */\nfunction resolvePathFromMetadata(\n metadata: ServiceRequestMetadata,\n model: IKosDataModel\n): string {\n return resolveParameters({\n value: metadata.path,\n modelId: model.id,\n modelData: model,\n }) as string;\n}\n\n/**\n * Resolves path params from metadata\n * @internal\n */\nfunction resolvePathParams(\n metadata: ServiceRequestMetadata,\n model: IKosDataModel\n): Record<string, any> | undefined {\n if (!metadata.pathParams) return undefined;\n\n return resolveParameters({\n value:\n typeof metadata.pathParams === \"function\"\n ? metadata.pathParams(model)\n : metadata.pathParams,\n modelId: model.id,\n modelData: model,\n }) as Record<string, any> | undefined;\n}\n\n/**\n * Resolves query params from metadata\n * @internal\n */\nfunction resolveQueryParams(\n metadata: ServiceRequestMetadata,\n model: IKosDataModel\n): Record<string, any> | undefined {\n if (!metadata.queryParams) return undefined;\n\n return resolveParameters({\n value:\n typeof metadata.queryParams === \"function\"\n ? metadata.queryParams(model)\n : metadata.queryParams,\n modelId: model.id,\n modelData: model,\n }) as Record<string, any> | undefined;\n}\n\n/**\n * Resolves body from metadata\n * @internal\n */\nfunction resolveBodyParams(\n metadata: ServiceRequestMetadata,\n model: IKosDataModel\n): any {\n if (!metadata.body) return undefined;\n\n return resolveParameters({\n value:\n typeof metadata.body === \"function\"\n ? metadata.body(model)\n : metadata.body,\n modelId: model.id,\n modelData: model,\n });\n}\n\n/**\n * Resolves request options from metadata\n * @internal\n */\nfunction resolveRequestOptions(\n metadata: ServiceRequestMetadata,\n model: IKosDataModel\n): any {\n if (!metadata.requestOptions) return undefined;\n\n return typeof metadata.requestOptions === \"function\"\n ? metadata.requestOptions(model)\n : metadata.requestOptions;\n}\n\n/**\n * Normalizes HTTP method to lowercase\n * @internal\n */\nfunction normalizeHttpMethod(\n method: HttpMethod | undefined\n): \"get\" | \"post\" | \"put\" | \"delete\" {\n return (method || \"get\").toLowerCase() as \"get\" | \"post\" | \"put\" | \"delete\";\n}\n\n/**\n * Creates storage key for response store\n * @internal\n */\nfunction createStorageKey(path: string, method: HttpMethod): string {\n return `${method.toUpperCase()}:${path}`;\n}\n\n/**\n * Checks if value is missing (undefined or null)\n * @internal\n */\nfunction isValueMissing(value: any): boolean {\n return value === undefined || value === null;\n}\n\n/**\n * Validates required field and logs warning if missing\n * @internal\n */\nfunction validateRequiredField(\n value: any,\n fieldName: string,\n path: string,\n isRequired: boolean\n): void {\n if (isRequired && isValueMissing(value)) {\n log.warn(\n `Required field '${fieldName}' is missing in response for ${path}`\n );\n }\n}\n\n/**\n * Applies default value if current value is missing\n * @internal\n */\nfunction applyDefaultIfMissing(value: any, defaultValue: any): any {\n return isValueMissing(value) && defaultValue !== undefined\n ? defaultValue\n : value;\n}\n\n/**\n * Manages lifecycle-driven service requests for KOS models\n *\n * The ServiceRequestManager executes @kosServiceRequest decorated methods\n * during the appropriate lifecycle phase (INIT, LOAD, READY, ACTIVATE, ONLINE).\n * ACTIVATE and ONLINE requests are sent again each time the phase repeats.\n *\n * @internal\n */\nexport class ServiceRequestManager {\n private model: IKosDataModel;\n private responseStore: ServiceResponseStore;\n private handlers: Map<DependencyLifecycle, ServiceRequestMetadata[]>;\n /** Topic handlers waiting on a baseline live on the KosModel, not the data model. */\n private baselineListener?: { flushQueueForBaseline(path: string): void };\n\n constructor(\n model: IKosDataModel,\n responseStore: ServiceResponseStore,\n baselineListener?: { flushQueueForBaseline(path: string): void }\n ) {\n this.model = model;\n this.baselineListener = baselineListener;\n this.responseStore = responseStore;\n this.handlers = new Map();\n\n this.discoverHandlers();\n }\n\n /**\n * Discover and organize service request handlers by lifecycle phase\n */\n private discoverHandlers(): void {\n const prototype = Object.getPrototypeOf(this.model);\n const handlerMetadata = prototype[ServiceRequestHandlers] || {};\n\n // Group handlers by lifecycle phase\n Object.values(handlerMetadata).forEach((metadata: any) => {\n const lifecycle = metadata.lifecycle;\n\n if (!this.handlers.has(lifecycle)) {\n this.handlers.set(lifecycle, []);\n }\n\n this.handlers.get(lifecycle)!.push(metadata);\n });\n\n if (Object.keys(handlerMetadata).length > 0) {\n log.debug(\n `Discovered ${\n Object.keys(handlerMetadata).length\n } service request handlers for model ${this.model.id}`\n );\n }\n }\n\n /**\n * Execute all service requests for a specific lifecycle phase\n *\n * @param lifecycle - The lifecycle phase to execute\n */\n async executeForLifecycle(lifecycle: DependencyLifecycle): Promise<void> {\n const handlers = this.handlers.get(lifecycle);\n\n if (!handlers || handlers.length === 0) {\n return;\n }\n\n log.debug(\n `Executing ${handlers.length} service requests for lifecycle ${lifecycle}`\n );\n\n // Execute all handlers for this lifecycle phase\n await Promise.all(handlers.map((handler) => this.executeHandler(handler)));\n }\n\n /**\n * Zone 1: Orchestrates the entire service request flow\n */\n private async executeHandler(\n metadata: ServiceRequestMetadata\n ): Promise<void> {\n let failure:\n | { error: Error; errorContext?: ErrorResponseContext }\n | undefined;\n try {\n if (!this.shouldProcessRequest(metadata)) {\n return;\n }\n\n const requestContext = await this.prepareAndExecuteRequest(metadata);\n if (requestContext.error) {\n failure = {\n error: new Error(requestContext.error),\n errorContext: requestContext.errorContext,\n };\n } else {\n await this.processAndStoreResponse(requestContext, metadata);\n }\n } catch (err) {\n failure = { error: err instanceof Error ? err : new Error(String(err)) };\n }\n\n // Outside the try: strategy \"throw\" rethrows, and a catch would report the failure twice.\n if (failure) {\n await this.handleError(failure.error, metadata, failure.errorContext);\n }\n }\n\n /**\n * Zone 2: Validates request preconditions\n */\n private shouldProcessRequest(metadata: ServiceRequestMetadata): boolean {\n if (!shouldExecuteRequest(metadata, this.model)) {\n log.debug(`Skipping request ${metadata.path} - condition returned false`);\n return false;\n }\n return true;\n }\n\n /**\n * Zone 2: Coordinates request preparation, execution, and timing capture\n */\n private async prepareAndExecuteRequest(metadata: ServiceRequestMetadata) {\n const requestContext = this.prepareRequest(metadata);\n const timing = this.captureRequestTiming();\n const result = await this.performRequest(requestContext);\n const [error, response] = result;\n const errorContext = result[2] as ErrorResponseContext | undefined;\n const responseTiming = this.captureResponseTiming();\n\n return {\n requestContext,\n error,\n response,\n errorContext,\n requestedAt: timing.requestedAt,\n receivedAt: responseTiming.receivedAt,\n };\n }\n\n /**\n * Zone 3: Captures request timestamp\n */\n private captureRequestTiming() {\n return { requestedAt: Date.now() };\n }\n\n /**\n * Zone 3: Captures response timestamp\n */\n private captureResponseTiming() {\n return { receivedAt: Date.now() };\n }\n\n /**\n * Zone 2: Coordinates response processing and storage\n */\n private async processAndStoreResponse(\n context: {\n requestContext: {\n resolvedPath: string;\n method: \"get\" | \"post\" | \"put\" | \"delete\";\n pathParams?: Record<string, any>;\n queryParams?: Record<string, any>;\n body?: any;\n };\n response: any;\n requestedAt: number;\n receivedAt: number;\n },\n metadata: ServiceRequestMetadata\n ): Promise<void> {\n const transformedData = await this.processResponse(\n context.response,\n metadata\n );\n await this.storeAndInvokeHandler(\n transformedData,\n metadata,\n context.requestContext.resolvedPath,\n context.requestedAt,\n context.receivedAt\n );\n }\n\n /**\n * Zone 2: Prepares request parameters by coordinating parameter resolution\n * @internal\n */\n private prepareRequest(metadata: ServiceRequestMetadata) {\n const resolvedPath = resolvePathFromMetadata(metadata, this.model);\n const pathParams = resolvePathParams(metadata, this.model);\n const queryParams = resolveQueryParams(metadata, this.model);\n const body = resolveBodyParams(metadata, this.model);\n const requestOptions = resolveRequestOptions(metadata, this.model);\n const method = normalizeHttpMethod(metadata.method);\n\n return {\n resolvedPath,\n method,\n pathParams,\n queryParams,\n body,\n requestOptions,\n };\n }\n\n /**\n * Zone 3: Performs the HTTP request\n * @internal\n */\n private async performRequest(context: {\n resolvedPath: string;\n method: \"get\" | \"post\" | \"put\" | \"delete\";\n pathParams?: Record<string, any>;\n queryParams?: Record<string, any>;\n body?: any;\n requestOptions?: any;\n }): Promise<ServiceResponse<any>> {\n return await this.makeRequest(\n context.resolvedPath,\n context.method,\n {\n path: context.pathParams as any,\n query: context.queryParams as any,\n },\n context.body,\n context.requestOptions\n );\n }\n\n /**\n * Zone 2: Processes response by coordinating transformations\n * @internal\n */\n private async processResponse(\n response: any,\n metadata: ServiceRequestMetadata\n ): Promise<any> {\n let transformedData = response;\n\n // Apply custom transform function if provided\n if (metadata.transform) {\n transformedData = metadata.transform(response);\n }\n\n // Apply mappings if provided; with iterateOver they apply per item in handleIteration.\n if (\n metadata.mappings &&\n metadata.mappings.length > 0 &&\n !metadata.iterateOver\n ) {\n transformedData = this.applyMappings(transformedData, metadata);\n }\n\n // Handle array iteration and model creation\n if (metadata.iterateOver) {\n transformedData = await this.handleIteration(transformedData, metadata);\n }\n\n return transformedData;\n }\n\n /**\n * Zone 2: Stores response and invokes handler with cleanup\n * @internal\n */\n private async storeAndInvokeHandler(\n transformedData: any,\n metadata: ServiceRequestMetadata,\n resolvedPath: string,\n requestedAt: number,\n receivedAt: number\n ): Promise<void> {\n // Store response with temporal tracking\n const cacheConfig = metadata.cache || {\n retention: ResponseRetention.SINGLE,\n };\n const storageKey = createStorageKey(resolvedPath, metadata.method || \"get\");\n this.responseStore.set(\n storageKey,\n transformedData,\n cacheConfig,\n requestedAt,\n receivedAt\n );\n\n // Invoke handler with error-first parameters (error, data)\n await metadata.originalHandler.call(this.model, null, transformedData);\n\n // Trigger baseline-aware queue flush if subscription manager exists\n // This allows queued events to be replayed with temporal filtering\n this.triggerBaselineQueueFlush(resolvedPath);\n\n // Cleanup if needed\n if (this.responseStore.shouldCleanupAfterHandler(storageKey)) {\n this.responseStore.delete(storageKey);\n }\n }\n\n /**\n * Trigger queue flush for topic handlers waiting on this baseline\n * @private\n */\n private triggerBaselineQueueFlush(baselinePath: string): void {\n this.baselineListener?.flushQueueForBaseline(baselinePath);\n }\n\n /**\n * Make HTTP request using existing KOS API client\n */\n private async makeRequest(\n path: string,\n method: \"get\" | \"post\" | \"put\" | \"delete\",\n params?: { path?: Record<string, string>; query?: Record<string, any> },\n body?: any,\n requestOptions?: any\n ): Promise<ServiceResponse<any>> {\n // Cast API to any to bypass strict OpenAPI typing for dynamic paths\n // This is safe because we're validating paths at runtime\n const api = API as any;\n\n switch (method) {\n case \"get\":\n return await api.get(path, params, requestOptions);\n case \"post\":\n return await api.post(path, params, body, requestOptions);\n case \"put\":\n return await api.put(path, params, body, requestOptions);\n case \"delete\":\n return await api.delete(path, params, body, requestOptions);\n default:\n return [\n `Unsupported HTTP method: ${method}`,\n null,\n ] as ServiceResponse<any>;\n }\n }\n\n /**\n * Zone 2: Applies field mappings to response data by coordinating extraction, transformation, and validation\n */\n private applyMappings(data: any, metadata: ServiceRequestMetadata): any {\n if (!metadata.mappings || metadata.mappings.length === 0) {\n return data;\n }\n\n const mapped: any = {};\n\n metadata.mappings.forEach((mapping) => {\n // Zone 3: Extract source value\n const sourceValue = this.getNestedValue(data, mapping.from);\n\n // Zone 3: Apply transformation if specified\n const transformedValue = mapping.transform\n ? this.applyTransform(sourceValue, mapping.transform)\n : sourceValue;\n\n // Zone 3: Validate required fields\n validateRequiredField(\n transformedValue,\n mapping.from,\n metadata.path,\n mapping.required || false\n );\n\n // Zone 3: Apply default value if needed\n const finalValue = applyDefaultIfMissing(\n transformedValue,\n mapping.default\n );\n\n mapped[mapping.to] = finalValue;\n });\n\n return mapped;\n }\n\n /**\n * Get nested value from object using dot notation\n */\n private getNestedValue(obj: any, path: string): any {\n return path.split(\".\").reduce((current, key) => current?.[key], obj);\n }\n\n /**\n * Apply transformation to a value\n */\n private applyTransform(\n value: any,\n transform: string | ((val: any) => any)\n ): any {\n if (typeof transform === \"function\") {\n return transform(value);\n }\n\n // Built-in transformers\n switch (transform) {\n case \"string\":\n return String(value);\n case \"number\":\n return Number(value);\n case \"boolean\":\n return Boolean(value);\n case \"date\":\n return value ? new Date(value) : undefined;\n case \"json\":\n return typeof value === \"string\" ? JSON.parse(value) : value;\n default:\n log.warn(`Unknown transformer: ${transform}`);\n return value;\n }\n }\n\n /**\n * Handle array iteration and model creation\n */\n private async handleIteration(\n data: any,\n metadata: ServiceRequestMetadata\n ): Promise<any[]> {\n if (!metadata.iterateOver) return data;\n\n // Get the array to iterate over\n const array = this.getNestedValue(data, metadata.iterateOver);\n\n if (!Array.isArray(array)) {\n log.warn(\n `iterateOver path '${metadata.iterateOver}' did not resolve to an array`\n );\n return [];\n }\n\n // If modelFactory is provided, create model instances\n if (metadata.modelFactory) {\n return array.map((item) => {\n // Apply mappings to transform item into model options\n const options =\n metadata.mappings && metadata.mappings.length > 0\n ? this.applyMappings(item, metadata)\n : item;\n\n // Extract ID using provided extractor or default to 'id' field\n const id = metadata.idExtractor\n ? metadata.idExtractor(options)\n : options.id;\n\n if (!id) {\n throw new Error(\n `Cannot create model instance: no ID found in response data. ` +\n `Provide an 'idExtractor' function or ensure response items have an 'id' field.`\n );\n }\n\n // Check if using new registration object or legacy curried function\n // Non-null assertion safe here because we're inside the if (metadata.modelFactory) block\n const factory = metadata.modelFactory!;\n if (typeof factory === \"function\") {\n // Legacy curried function: (id: string) => (options: any) => IKosDataModel\n const instanceFactory = factory(id);\n return instanceFactory(options);\n } else {\n // New registration object: Model.instance(id).options(opts).build()\n return factory.instance(id).options(options).build();\n }\n });\n }\n\n // Otherwise return mapped array items\n return array.map((item) => {\n if (metadata.mappings && metadata.mappings.length > 0) {\n return this.applyMappings(item, metadata);\n }\n return item;\n });\n }\n\n /**\n * Handle errors according to configured strategy\n */\n private async handleError(\n error: Error,\n metadata: ServiceRequestMetadata,\n errorContext?: ErrorResponseContext\n ): Promise<void> {\n const errorHandler = metadata.errorHandler || { strategy: \"throw\" };\n\n // Build a rich error for the onError callback\n const richError = errorContext\n ? new ServiceRequestError(error.message, errorContext)\n : error;\n\n // Call custom error handler if provided\n if (errorHandler.onError) {\n errorHandler.onError(richError, this.model);\n }\n\n switch (errorHandler.strategy) {\n case \"throw\":\n throw error;\n\n case \"log\":\n log.error(\n `Service request failed for ${metadata.path}:`,\n error.message\n );\n // Store default value and call handler (consistent with 'default' strategy)\n if (errorHandler.defaultValue !== undefined) {\n const storageKey = createStorageKey(\n resolvePathFromMetadata(metadata, this.model),\n metadata.method || \"get\"\n );\n this.responseStore.set(\n storageKey,\n errorHandler.defaultValue,\n metadata.cache || { retention: ResponseRetention.SINGLE }\n );\n await metadata.originalHandler.call(\n this.model,\n error.message,\n errorHandler.defaultValue\n );\n }\n break;\n\n case \"ignore\":\n // Silently ignore, store default value and call handler\n if (errorHandler.defaultValue !== undefined) {\n const storageKey = createStorageKey(\n resolvePathFromMetadata(metadata, this.model),\n metadata.method || \"get\"\n );\n this.responseStore.set(\n storageKey,\n errorHandler.defaultValue,\n metadata.cache || { retention: ResponseRetention.SINGLE }\n );\n await metadata.originalHandler.call(\n this.model,\n error.message,\n errorHandler.defaultValue\n );\n }\n break;\n\n case \"default\":\n // Store default value in response store\n if (errorHandler.defaultValue !== undefined) {\n const storageKey = createStorageKey(\n resolvePathFromMetadata(metadata, this.model),\n metadata.method || \"get\"\n );\n this.responseStore.set(\n storageKey,\n errorHandler.defaultValue,\n metadata.cache || { retention: ResponseRetention.SINGLE }\n );\n // Call handler with error and default value (error-first parameters)\n await metadata.originalHandler.call(\n this.model,\n error.message,\n errorHandler.defaultValue\n );\n }\n break;\n }\n }\n}\n","import log from \"loglevel\";\nimport {\n subscribe as originalSubscribe,\n publish as originalPublish,\n once as originalOnce,\n waitFor as originalWaitFor,\n hasEventSubscriptions,\n reset,\n type EventCallback,\n type ApiCallback,\n type PublishResponse,\n} from \"./eventBus\";\n\n/**\n * Re-export existing EventBus functionality\n */\nexport {\n hasEventSubscriptions,\n reset,\n type EventCallback,\n type ApiCallback,\n type PublishResponse,\n};\n\n/**\n * Enhanced subscribe that maintains backward compatibility\n */\nexport const subscribe = originalSubscribe;\nexport const publish = originalPublish;\nexport const once = originalOnce;\nexport const waitFor = originalWaitFor;\n\n/**\n * AsyncIterator support for EventBus\n */\ninterface AsyncSubscription<T> {\n queue: T[];\n resolvers: Array<(result: IteratorResult<T>) => void>;\n closed: boolean;\n}\n\n/**\n * Async iterator over one event type. Closing it with `return()` or `throw()`\n * ends it: it unsubscribes, drops queued events, resolves every waiting read\n * with `{ done: true }`, and every later read is done.\n */\nclass AsyncEventIterator<T = ApiCallback> {\n private subscription: AsyncSubscription<T>;\n private unsubscribe: () => void;\n private eventType: string;\n\n constructor(eventType: string) {\n this.eventType = eventType;\n this.subscription = {\n queue: [],\n resolvers: [],\n closed: false,\n };\n\n // Subscribe to the event using the original EventBus\n const sub = originalSubscribe<T>(eventType, (msg?: T) => {\n if (this.subscription.closed) return;\n\n if (msg !== undefined) {\n // If there's a waiting resolver, resolve it immediately\n const resolver = this.subscription.resolvers.shift();\n if (resolver) {\n resolver({ done: false, value: msg });\n } else {\n // Otherwise queue the message\n this.subscription.queue.push(msg);\n }\n }\n });\n\n this.unsubscribe = sub.unsubscribe;\n }\n\n async next(): Promise<IteratorResult<T>> {\n if (this.subscription.closed) {\n return { done: true, value: undefined };\n }\n\n // If there are queued messages, return the oldest one\n if (this.subscription.queue.length > 0) {\n return {\n done: false,\n value: this.subscription.queue.shift()!,\n };\n }\n\n // Wait for the next message\n return new Promise<IteratorResult<T>>((resolve) => {\n this.subscription.resolvers.push(resolve);\n });\n }\n\n async return(): Promise<IteratorResult<T>> {\n this.close();\n return { done: true, value: undefined };\n }\n\n async throw(error: Error): Promise<IteratorResult<T>> {\n this.close();\n throw error;\n }\n\n private close(): void {\n if (this.subscription.closed) return;\n this.subscription.closed = true;\n this.subscription.queue = [];\n this.unsubscribe();\n\n const resolvers = this.subscription.resolvers;\n this.subscription.resolvers = [];\n resolvers.forEach((resolve) => resolve({ done: true, value: undefined }));\n }\n\n [Symbol.asyncIterator]() {\n return this;\n }\n}\n\n/**\n * Create an async iterator for an event type\n *\n * @example\n * ```typescript\n * for await (const message of iterate(\"user.events\")) {\n * console.log(\"Received:\", message);\n * }\n * ```\n */\nexport function iterate<T = ApiCallback>(\n eventType: string\n): AsyncEventIterator<T> {\n return new AsyncEventIterator<T>(eventType);\n}\n\n/**\n * Create an async generator that yields events\n *\n * @example\n * ```typescript\n * for await (const message of stream(\"user.events\")) {\n * console.log(\"Received:\", message);\n * }\n * ```\n */\nexport async function* stream<T = ApiCallback>(\n eventType: string,\n options?: {\n filter?: (msg: T) => boolean;\n transform?: (msg: T) => any;\n bufferSize?: number;\n }\n): AsyncGenerator<T, void, unknown> {\n const iterator = iterate<T>(eventType);\n const buffer: T[] = [];\n const maxBufferSize = options?.bufferSize ?? Infinity;\n\n try {\n for await (const message of iterator) {\n // Apply filter if provided\n if (options?.filter && !options.filter(message)) {\n continue;\n }\n\n // Apply transform if provided\n const output = options?.transform ? options.transform(message) : message;\n\n // Buffer management\n if (buffer.length >= maxBufferSize) {\n buffer.shift(); // Remove oldest if buffer is full\n }\n\n yield output;\n }\n } finally {\n await iterator.return();\n }\n}\n\n/**\n * Create a filtered stream of events\n */\nexport async function* filter<T = ApiCallback>(\n eventType: string,\n predicate: (msg: T) => boolean\n): AsyncGenerator<T, void, unknown> {\n for await (const message of iterate<T>(eventType)) {\n if (predicate(message)) {\n yield message;\n }\n }\n}\n\n/**\n * Map/transform events in a stream\n */\nexport async function* map<T = ApiCallback, R = any>(\n eventType: string,\n transform: (msg: T) => R\n): AsyncGenerator<R, void, unknown> {\n for await (const message of iterate<T>(eventType)) {\n yield transform(message);\n }\n}\n\n/**\n * Batch events with time window or count limit\n */\nexport async function* batch<T = ApiCallback>(\n eventType: string,\n options: {\n maxSize?: number;\n maxWait?: number;\n } = {}\n): AsyncGenerator<T[], void, unknown> {\n const maxSize = options.maxSize ?? 10;\n const maxWait = options.maxWait ?? 1000;\n\n const iterator = iterate<T>(eventType);\n let currentBatch: T[] = [];\n let batchTimer: NodeJS.Timeout | null = null;\n let batchPromise: Promise<void> | null = null;\n\n const startBatchTimer = () => {\n if (batchTimer) clearTimeout(batchTimer);\n\n batchPromise = new Promise<void>((resolve) => {\n batchTimer = setTimeout(() => {\n resolve();\n }, maxWait);\n });\n };\n\n try {\n startBatchTimer();\n\n while (true) {\n // Race between next message and batch timeout\n const result = await Promise.race([\n iterator.next(),\n batchPromise!.then(() => ({ done: false, timeout: true } as any)),\n ]);\n\n if (result.done) {\n // Iterator finished, yield remaining batch if any\n if (currentBatch.length > 0) {\n yield currentBatch;\n }\n break;\n }\n\n if (result.timeout) {\n // Timeout reached, yield current batch\n if (currentBatch.length > 0) {\n yield currentBatch;\n currentBatch = [];\n }\n startBatchTimer();\n } else {\n // New message received\n currentBatch.push(result.value);\n\n if (currentBatch.length >= maxSize) {\n // Batch size reached\n yield currentBatch;\n currentBatch = [];\n startBatchTimer();\n }\n }\n }\n } finally {\n if (batchTimer) clearTimeout(batchTimer);\n await iterator.return();\n }\n}\n\n/**\n * Merge multiple event streams\n */\nexport async function* merge<T = ApiCallback>(\n ...eventTypes: string[]\n): AsyncGenerator<{ eventType: string; message: T }, void, unknown> {\n const iterators = eventTypes.map((type) => {\n return {\n type,\n iterator: iterate<T>(type),\n done: false,\n };\n });\n\n const pendingPromises = new Map<string, Promise<IteratorResult<T>>>();\n\n try {\n // Start all iterators\n for (const item of iterators) {\n if (!item.done) {\n pendingPromises.set(item.type, item.iterator.next());\n }\n }\n\n while (pendingPromises.size > 0) {\n // Wait for any iterator to produce a value\n const [eventType, result] = await Promise.race(\n Array.from(pendingPromises.entries()).map(\n async ([type, promise]) =>\n [type, await promise] as [string, IteratorResult<T>]\n )\n );\n\n pendingPromises.delete(eventType);\n\n const iterator = iterators.find((it) => it.type === eventType)!;\n\n if (result.done) {\n iterator.done = true;\n } else {\n yield { eventType, message: result.value };\n\n // Queue next value from this iterator\n if (!iterator.done) {\n pendingPromises.set(eventType, iterator.iterator.next());\n }\n }\n }\n } finally {\n // Clean up all iterators\n await Promise.all(iterators.map((item) => item.iterator.return()));\n }\n}\n\n/**\n * Process events with backpressure control\n */\nexport async function processWithBackpressure<T = ApiCallback>(\n eventType: string,\n processor: (msg: T) => Promise<void>,\n maxConcurrent = 5\n): Promise<void> {\n const processing = new Set<Promise<void>>();\n\n for await (const message of iterate<T>(eventType)) {\n // Wait if at max concurrent\n if (processing.size >= maxConcurrent) {\n await Promise.race(processing);\n }\n\n // Start processing\n const processPromise = processor(message)\n .catch((err) => {\n log.error(`Error processing ${eventType}:`, err);\n })\n .finally(() => {\n processing.delete(processPromise);\n });\n\n processing.add(processPromise);\n }\n\n // Wait for remaining processing\n await Promise.all(processing);\n}\n\n/**\n * Take only the first N events\n */\nexport async function* take<T = ApiCallback>(\n eventType: string,\n count: number\n): AsyncGenerator<T, void, unknown> {\n let taken = 0;\n for await (const message of iterate<T>(eventType)) {\n if (taken >= count) break;\n yield message;\n taken++;\n }\n}\n\n/**\n * Skip the first N events\n */\nexport async function* skip<T = ApiCallback>(\n eventType: string,\n count: number\n): AsyncGenerator<T, void, unknown> {\n let skipped = 0;\n for await (const message of iterate<T>(eventType)) {\n if (skipped < count) {\n skipped++;\n continue;\n }\n yield message;\n }\n}\n\n/**\n * Debounce events (only emit after a period of inactivity)\n */\nexport async function* debounce<T = ApiCallback>(\n eventType: string,\n delay: number\n): AsyncGenerator<T, void, unknown> {\n const iterator = iterate<T>(eventType);\n let lastValue: T | undefined;\n let timer: NodeJS.Timeout | null = null;\n let timerPromise: Promise<void> | null = null;\n\n try {\n while (true) {\n if (timerPromise) {\n // Wait for either next message or timer\n const result = await Promise.race([\n iterator.next(),\n timerPromise.then(() => ({ done: false, timeout: true } as any)),\n ]);\n\n if (result.done) {\n // Iterator finished\n if (lastValue !== undefined) {\n yield lastValue;\n }\n break;\n }\n\n if (result.timeout) {\n // Timer expired, emit last value\n if (lastValue !== undefined) {\n yield lastValue;\n lastValue = undefined;\n }\n timerPromise = null;\n } else {\n // New message, reset timer\n lastValue = result.value;\n if (timer) clearTimeout(timer);\n\n timerPromise = new Promise<void>((resolve) => {\n timer = setTimeout(() => resolve(), delay);\n });\n }\n } else {\n // First message\n const result = await iterator.next();\n if (result.done) break;\n\n lastValue = result.value;\n timerPromise = new Promise<void>((resolve) => {\n timer = setTimeout(() => resolve(), delay);\n });\n }\n }\n } finally {\n if (timer) clearTimeout(timer);\n await iterator.return();\n }\n}\n\n/**\n * Throttle events (limit emission rate)\n */\nexport async function* throttle<T = ApiCallback>(\n eventType: string,\n interval: number\n): AsyncGenerator<T, void, unknown> {\n let lastEmit = 0;\n\n for await (const message of iterate<T>(eventType)) {\n const now = Date.now();\n const timeSinceLastEmit = now - lastEmit;\n\n if (timeSinceLastEmit < interval) {\n // Wait for remaining interval\n await new Promise((resolve) =>\n setTimeout(resolve, interval - timeSinceLastEmit)\n );\n }\n\n lastEmit = Date.now();\n yield message;\n }\n}\n\n/**\n * Combine latest values from multiple event streams\n */\nexport async function* combineLatest<T = ApiCallback>(\n ...eventTypes: string[]\n): AsyncGenerator<Record<string, T | undefined>, void, unknown> {\n const latest: Record<string, T | undefined> = {};\n const hasEmitted: Set<string> = new Set();\n\n // Initialize with undefined\n eventTypes.forEach((type) => {\n latest[type] = undefined;\n });\n\n for await (const { eventType, message } of merge<T>(...eventTypes)) {\n latest[eventType] = message;\n hasEmitted.add(eventType);\n\n // Only emit once all streams have emitted at least once\n if (hasEmitted.size === eventTypes.length) {\n yield { ...latest };\n }\n }\n}\n","import type { IKosDataModel } from \"../kosModel\";\nimport type { IKosTopicHandlerParams } from \"./kosTopicHandler\";\n\n/**\n * Advanced flow control options for kosTopicHandler\n *\n * @kosService core.topic-handler\n * @kosApiLevel 12\n */\nexport interface FlowControlOptions<T = any, R = T> {\n /**\n * Batching configuration. A batch is delivered when it reaches `size` or\n * when `window` ms have passed since its first event, whichever comes first.\n */\n batch?: {\n /** Maximum number of events in a batch */\n size?: number;\n /**\n * Time in ms from a batch's first event until the batch is delivered,\n * full or not\n */\n window?: number;\n };\n\n /**\n * Transform function to apply to batched events\n * @param events - Array of events in the batch\n * @returns Transformed data to pass to handler\n */\n transform?: (events: T[]) => R;\n\n /**\n * Advanced filtering with state awareness\n */\n filter?: {\n /** Predicate function for filtering events */\n predicate: (event: T, context: FilterContext) => boolean;\n /** Remember last N events for stateful filtering */\n historySize?: number;\n };\n\n /**\n * Rate limiting options. The limit applies to each event that passes the\n * filter, before it joins a batch.\n */\n rateLimit?: {\n /** Maximum events to process per time window */\n maxEvents: number;\n /** Time window in milliseconds */\n windowMs: number;\n /**\n * What to do when rate limit is exceeded: `\"drop\"` discards the event;\n * `\"delay\"` holds it until the next window and counts it there\n *\n * @defaultValue \"drop\"\n */\n onExceeded?: \"drop\" | \"delay\";\n };\n\n /**\n * Error handling strategy for the flow\n */\n errorHandling?: {\n /** Retry failed events */\n retry?: {\n attempts: number;\n backoffMs: number;\n };\n /** Continue processing other events if one fails */\n continueOnError?: boolean;\n };\n}\n\n/**\n * @kosService core.topic-handler\n * @kosApiLevel 12\n */\nexport interface FilterContext {\n /** Previous events in the filter history */\n history: any[];\n /** Current batch being processed */\n currentBatch: any[];\n /** Timestamp when filtering started */\n startTime: number;\n}\n\n/**\n * Enhanced kosTopicHandler params with flow control\n *\n * @kosService core.topic-handler\n * @kosApiLevel 12\n */\nexport interface IKosTopicHandlerFlowParams<\n T = any,\n Model extends IKosDataModel = any,\n R = T\n> extends IKosTopicHandlerParams<T, Model, R> {\n /**\n * Advanced flow control options using async iterators internally\n */\n flow?: FlowControlOptions<T, R>;\n}\n\n/**\n * Statistics for monitoring flow control performance\n *\n * @kosService core.topic-handler\n * @kosApiLevel 12\n */\nexport interface FlowControlStats {\n /** Total events received */\n eventsReceived: number;\n /** Total batches processed */\n batchesProcessed: number;\n /** Events dropped by rate limiting */\n eventsDropped: number;\n /** Average batch size */\n averageBatchSize: number;\n /** Processing rate (events/second) */\n processingRate: number;\n /** Last processing timestamp */\n lastProcessedAt: number;\n}\n\nconst ABORTED = Symbol(\"aborted\");\n\n/**\n * Settles with `promise`, or with `ABORTED` as soon as `signal` aborts,\n * whichever comes first.\n */\nfunction untilAborted<V>(\n promise: Promise<V>,\n signal?: AbortSignal\n): Promise<V | typeof ABORTED> {\n if (!signal) return promise;\n if (signal.aborted) return Promise.resolve(ABORTED);\n return new Promise((resolve, reject) => {\n const onAbort = () => resolve(ABORTED);\n signal.addEventListener(\"abort\", onAbort, { once: true });\n promise\n .then(resolve, reject)\n .finally(() => signal.removeEventListener(\"abort\", onAbort));\n });\n}\n\n/**\n * Internal flow control manager\n *\n * @kosService core.topic-handler\n * @kosApiLevel 12\n */\nexport class FlowControlManager<T = any, R = T> {\n private config: FlowControlOptions<T, R>;\n private stats: FlowControlStats;\n private filterHistory: T[] = [];\n private rateLimitWindow = new Map<number, number>();\n\n constructor(config: FlowControlOptions<T, R>) {\n this.config = config;\n this.stats = {\n eventsReceived: 0,\n batchesProcessed: 0,\n eventsDropped: 0,\n averageBatchSize: 0,\n processingRate: 0,\n lastProcessedAt: Date.now(),\n };\n }\n\n /**\n * Runs `eventStream` through the configured filter, rate limit, batching\n * and transform. Aborting `signal` ends the flow without an error: an event\n * still awaited from the source is abandoned, a partial batch is discarded,\n * and the source is returned.\n */\n async *processEvents(\n eventStream: AsyncIterable<T>,\n signal?: AbortSignal\n ): AsyncGenerator<R, void, unknown> {\n const batchConfig = this.config.batch || { size: 1, window: 0 };\n\n if (batchConfig.size === 1 && !batchConfig.window) {\n yield* this.processSingleEvents(eventStream, signal);\n } else {\n yield* this.processBatchedEvents(eventStream, batchConfig, signal);\n }\n }\n\n private async *processSingleEvents(\n eventStream: AsyncIterable<T>,\n signal?: AbortSignal\n ): AsyncGenerator<R, void, unknown> {\n const iterator = eventStream[Symbol.asyncIterator]();\n let sourceDone = false;\n\n try {\n while (true) {\n const next = await untilAborted(iterator.next(), signal);\n if (next === ABORTED) return;\n if (next.done) {\n sourceDone = true;\n return;\n }\n yield* this.processSingleEvent(next.value, signal);\n }\n } finally {\n if (!sourceDone) {\n void iterator.return?.();\n }\n }\n }\n\n private async *processSingleEvent(\n event: T,\n signal?: AbortSignal\n ): AsyncGenerator<R, void, unknown> {\n this.stats.eventsReceived++;\n\n // Apply filtering\n if (this.config.filter && !this.shouldProcessEvent(event)) {\n return;\n }\n\n if (!(await this.admitRateLimited()) || signal?.aborted) {\n return;\n }\n\n const transformed = this.config.transform\n ? this.config.transform([event])\n : ([event] as unknown as R);\n\n yield transformed;\n this.updateProcessingStats([event]);\n }\n\n /**\n * Collects admitted events into batches. A batch is delivered when it\n * reaches `size`, when `window` ms have passed since its first event, or\n * when the stream ends. Aborting `signal` discards the open batch. The\n * window timer is cleared on every flush and when the generator finishes,\n * is returned or is aborted.\n */\n private async *processBatchedEvents(\n eventStream: AsyncIterable<T>,\n batchConfig: { size?: number; window?: number },\n signal?: AbortSignal\n ): AsyncGenerator<R, void, unknown> {\n const maxSize = batchConfig.size || 100;\n const maxWait = batchConfig.window || 1000;\n const iterator = eventStream[Symbol.asyncIterator]();\n\n let batch: T[] = [];\n let windowTimer: ReturnType<typeof setTimeout> | undefined;\n let windowElapsed: Promise<\"window\"> | undefined;\n let elapsed = false;\n let pending: Promise<IteratorResult<T>> | undefined;\n let sourceDone = false;\n\n const openWindow = () => {\n windowElapsed = new Promise((resolve) => {\n windowTimer = setTimeout(() => {\n elapsed = true;\n resolve(\"window\");\n }, maxWait);\n });\n };\n\n const closeWindow = () => {\n clearTimeout(windowTimer);\n windowTimer = undefined;\n windowElapsed = undefined;\n elapsed = false;\n };\n\n const flushBatch = (): R => {\n const currentBatch = batch;\n batch = [];\n closeWindow();\n\n const transformed = this.config.transform\n ? this.config.transform(currentBatch)\n : (currentBatch as unknown as R);\n\n this.stats.batchesProcessed++;\n this.updateProcessingStats(currentBatch);\n\n return transformed;\n };\n\n try {\n while (true) {\n pending ??= iterator.next();\n const next = await untilAborted(\n windowElapsed ? Promise.race([pending, windowElapsed]) : pending,\n signal\n );\n\n if (next === ABORTED) return;\n if (next === \"window\") {\n yield flushBatch();\n continue;\n }\n\n pending = undefined;\n if (next.done) {\n sourceDone = true;\n break;\n }\n\n const event = next.value;\n this.stats.eventsReceived++;\n\n if (this.config.filter && !this.shouldProcessEvent(event)) {\n continue;\n }\n\n if (!(await this.admitRateLimited())) {\n continue;\n }\n if (signal?.aborted) return;\n\n batch.push(event);\n if (batch.length === 1) {\n openWindow();\n }\n\n if (batch.length >= maxSize || elapsed) {\n yield flushBatch();\n }\n }\n\n if (batch.length > 0) {\n yield flushBatch();\n }\n } finally {\n closeWindow();\n if (!sourceDone) {\n void iterator.return?.();\n }\n }\n }\n\n private shouldProcessEvent(event: T): boolean {\n if (!this.config.filter) return true;\n\n const context: FilterContext = {\n history: [...this.filterHistory],\n currentBatch: [],\n startTime: Date.now(),\n };\n\n const shouldProcess = this.config.filter.predicate(event, context);\n\n // Update filter history\n if (this.config.filter.historySize) {\n this.filterHistory.push(event);\n if (this.filterHistory.length > this.config.filter.historySize) {\n this.filterHistory.shift();\n }\n }\n\n return shouldProcess;\n }\n\n /**\n * Counts an event against the rate limit. Resolves false when the event is\n * dropped; with `onExceeded: \"delay\"` it waits for a window with room and\n * counts the event there.\n */\n private async admitRateLimited(): Promise<boolean> {\n const rateLimit = this.config.rateLimit;\n if (!rateLimit) return true;\n\n while (!this.checkRateLimit()) {\n if (rateLimit.onExceeded !== \"delay\") {\n this.stats.eventsDropped++;\n return false;\n }\n await this.waitForRateLimit();\n }\n return true;\n }\n\n private checkRateLimit(): boolean {\n if (!this.config.rateLimit) return true;\n\n const now = Date.now();\n const windowStart = Math.floor(now / this.config.rateLimit.windowMs);\n const currentCount = this.rateLimitWindow.get(windowStart) || 0;\n\n if (currentCount >= this.config.rateLimit.maxEvents) {\n return false;\n }\n\n this.rateLimitWindow.set(windowStart, currentCount + 1);\n\n // Clean up old windows\n for (const [window] of this.rateLimitWindow) {\n if (window < windowStart - 1) {\n this.rateLimitWindow.delete(window);\n }\n }\n\n return true;\n }\n\n private async waitForRateLimit(): Promise<void> {\n if (!this.config.rateLimit) return;\n\n const now = Date.now();\n const windowStart = Math.floor(now / this.config.rateLimit.windowMs);\n const nextWindow = (windowStart + 1) * this.config.rateLimit.windowMs;\n const waitTime = nextWindow - now;\n\n if (waitTime > 0) {\n await new Promise((resolve) => setTimeout(resolve, waitTime));\n }\n }\n\n private updateProcessingStats(batch: T[]): void {\n const now = Date.now();\n const timeSinceLastProcessed = now - this.stats.lastProcessedAt;\n\n this.stats.averageBatchSize =\n (this.stats.averageBatchSize * this.stats.batchesProcessed +\n batch.length) /\n (this.stats.batchesProcessed + 1);\n\n this.stats.processingRate =\n timeSinceLastProcessed > 0\n ? batch.length / (timeSinceLastProcessed / 1000)\n : this.stats.processingRate;\n\n this.stats.lastProcessedAt = now;\n }\n\n getStats(): FlowControlStats {\n return { ...this.stats };\n }\n}\n","import { when } from \"mobx\";\n\n/**\n * Resolves the reason an `AbortSignal` carries, falling back to a generic\n * `AbortError` for signals aborted without one.\n */\nconst abortReason = (signal: AbortSignal): unknown =>\n signal.reason ?? new DOMException(\"Aborted\", \"AbortError\");\n\n/**\n * Waits for a MobX predicate to become `true`, but gives up as soon as the\n * supplied signal aborts.\n *\n * MobX's `when()` waits forever by design. That is the right default for\n * lifecycle code, but a caller working against a deadline needs the wait to be\n * cancellable — and, more importantly, needs the underlying reaction disposed\n * when it gives up. Without disposal, every abandoned waiter leaves a live\n * reaction observing the predicate for the lifetime of the process.\n *\n * @param predicate - The reactive condition to wait for.\n * @param signal - Optional signal that cancels the wait. When omitted the wait\n * is indefinite, matching plain `when()`.\n * @returns A promise that resolves once the predicate holds.\n * @throws The signal's abort reason (a `TimeoutError` or `AbortError`\n * `DOMException` for signals created by the SDK) if it aborts first.\n *\n * @internal\n */\nexport const abortableWhen = async (\n predicate: () => boolean,\n signal?: AbortSignal\n): Promise<void> => {\n if (predicate()) {\n return;\n }\n\n if (!signal) {\n await when(predicate);\n return;\n }\n\n if (signal.aborted) {\n throw abortReason(signal);\n }\n\n const pending = when(predicate);\n let onAbort: (() => void) | undefined;\n\n try {\n await Promise.race([\n // `cancel()` below rejects this promise with MobX's WHEN_CANCELLED\n // sentinel. That rejection *is* the cancellation, never a real failure,\n // so it is swallowed here; the abort branch supplies the thrown reason.\n pending.catch(() => undefined),\n new Promise<never>((_, reject) => {\n onAbort = () => reject(abortReason(signal));\n signal.addEventListener(\"abort\", onAbort, { once: true });\n }),\n ]);\n } finally {\n if (onAbort) {\n signal.removeEventListener(\"abort\", onAbort);\n }\n // Disposes the underlying reaction. Required on the abort path so\n // abandoned waiters do not accumulate, and harmless once the predicate has\n // already resolved.\n pending.cancel();\n }\n};\n","// Wire-frame encoding/decoding for the KosMock facility. The frame format is\n// the transport's own: `header:value` lines, a blank line, then an optional\n// JSON body (see processKosMessage). Encoders here must stay byte-compatible\n// with what BaseTransport.onMessage and kosFetchWs expect: the response-id\n// header routes the frame to the awaiting request, the `status` header must be\n// a string (kosFetchWs compares it to the literal \"200\"), and service-layer\n// consumers read a `{status, data}` envelope from the body JSON.\nimport {\n HEADER_METHOD,\n HEADER_ORDERED,\n HEADER_REQUEST_ID,\n HEADER_REQUEST_TYPE,\n HEADER_RESPONSE_ID,\n HEADER_TOPIC,\n HEADER_URL,\n HEADER_WORK_TRACKER,\n STATUS,\n} from \"../../../../common\";\nimport { processKosMessage } from \"../base-message-transport\";\n\nexport const KOS_HTTP_REQUEST_TYPE = \"kos.http.request\";\nexport const KOS_HTTP_RESPONSE_TYPE = \"kos.http.response\";\nexport const KOS_FUTURE_TYPE = \"kos.future\";\nexport const KOS_BROKER_SUBSCRIBE_TYPE = \"kos.broker.subscribe\";\nexport const KOS_BROKER_UNSUBSCRIBE_TYPE = \"kos.broker.unsubscribe\";\nexport const KOS_ADDR_ALIAS_TYPE = \"kos.addr.alias\";\n\n/** Wire header stamped on every response the mock layer generates. */\nexport const KOS_MOCKED_HEADER = \"kos-mocked\";\n/** Optional wire header naming the fixture a mocked response came from. */\nexport const KOS_MOCK_FIXTURE_HEADER = \"kos-mock-fixture\";\n/** Wire header stamped on responses a transformer modified in flight. */\nexport const KOS_MOCK_TRANSFORMED_HEADER = \"kos-mock-transformed\";\n\nconst CONTENT_TYPE_HEADER = \"content-type\";\nconst MESSAGE_SEPARATOR = \"\\n\\n\";\n\nexport interface KosMockRequestFrame {\n method: string;\n url: string;\n requestId: string;\n tracker?: string;\n ordered: boolean;\n headers: Record<string, string>;\n rawBody?: string;\n}\n\nexport interface KosMockResponseFrameInput {\n requestId: string;\n status?: number;\n data?: unknown;\n headers?: Record<string, string>;\n /** Verbatim body override — skips the `{status, data}` envelope. */\n raw?: string;\n}\n\nconst toTransportString = (\n data: string | ArrayBufferLike | Blob | ArrayBufferView\n): string | undefined => (typeof data === \"string\" ? data : undefined);\n\n/** Frame `type` header, or undefined for non-string/unparseable data. */\nexport function peekFrameType(\n data: string | ArrayBufferLike | Blob | ArrayBufferView\n): string | undefined {\n const text = toTransportString(data);\n if (!text) {\n return undefined;\n }\n try {\n return processKosMessage(text).headers[HEADER_REQUEST_TYPE];\n } catch {\n return undefined;\n }\n}\n\n/**\n * Decodes an outbound `kos.http.request` frame. Returns undefined for\n * anything else (binary data, topic subscribes, FOS frames, ...).\n */\nexport function decodeRequestFrame(\n data: string | ArrayBufferLike | Blob | ArrayBufferView\n): KosMockRequestFrame | undefined {\n const text = toTransportString(data);\n if (!text) {\n return undefined;\n }\n let headers: Record<string, string>;\n let body: string;\n try {\n ({ headers, body } = processKosMessage(text));\n } catch {\n return undefined;\n }\n if (headers[HEADER_REQUEST_TYPE] !== KOS_HTTP_REQUEST_TYPE) {\n return undefined;\n }\n const method = headers[HEADER_METHOD];\n const url = headers[HEADER_URL];\n const requestId = headers[HEADER_REQUEST_ID];\n if (!method || !url || !requestId) {\n return undefined;\n }\n return {\n method,\n url,\n requestId,\n tracker: headers[HEADER_WORK_TRACKER],\n ordered: headers[HEADER_ORDERED] === \"true\",\n headers,\n rawBody: body || undefined,\n };\n}\n\n/**\n * Decodes the topic list from a `kos.broker.subscribe`/`unsubscribe` frame.\n * Returns undefined when the frame is not a broker frame.\n */\nexport function decodeSubscribeTopics(\n data: string | ArrayBufferLike | Blob | ArrayBufferView\n): { type: \"subscribe\" | \"unsubscribe\"; topics: string[] } | undefined {\n const text = toTransportString(data);\n if (!text) {\n return undefined;\n }\n let headers: Record<string, string>;\n let body: string;\n try {\n ({ headers, body } = processKosMessage(text));\n } catch {\n return undefined;\n }\n const frameType = headers[HEADER_REQUEST_TYPE];\n if (\n frameType !== KOS_BROKER_SUBSCRIBE_TYPE &&\n frameType !== KOS_BROKER_UNSUBSCRIBE_TYPE\n ) {\n return undefined;\n }\n let topics: string[] = [];\n try {\n const parsed = JSON.parse(body);\n if (Array.isArray(parsed)) {\n topics = parsed.filter(\n (topic): topic is string => typeof topic === \"string\"\n );\n }\n } catch {\n // A malformed broker frame still identifies as one; report no topics.\n }\n return {\n type: frameType === KOS_BROKER_SUBSCRIBE_TYPE ? \"subscribe\" : \"unsubscribe\",\n topics,\n };\n}\n\nconst assertHeaderSafe = (name: string, value: string) => {\n if (value.includes(\"\\n\")) {\n throw new Error(`KosMock frame ${name} must not contain newlines`);\n }\n};\n\nconst encodeFrame = (\n headers: Array<[string, string]>,\n body: string\n): string => {\n const lines = headers.map(([name, value]) => {\n assertHeaderSafe(name, value);\n return `${name}:${value}`;\n });\n return `${lines.join(\"\\n\")}${MESSAGE_SEPARATOR}${body}`;\n};\n\n/**\n * Re-encodes a frame from already-parsed headers and a body — used when a\n * transformer patches an inbound frame's body while preserving its headers.\n */\nexport function encodeRawFrame(\n headers: Record<string, string>,\n body: string\n): string {\n return encodeFrame(Object.entries(headers), body);\n}\n\n/**\n * Encodes an inbound HTTP response frame for a pending request. The default\n * body is the `{status, data}` envelope service consumers expect.\n */\nexport function encodeHttpResponseFrame({\n requestId,\n status = 200,\n data,\n headers = {},\n raw,\n}: KosMockResponseFrameInput): string {\n const body = raw ?? JSON.stringify({ status, data: data ?? {} });\n return encodeFrame(\n [\n [HEADER_RESPONSE_ID, requestId],\n [STATUS, `${status}`],\n [CONTENT_TYPE_HEADER, \"application/json\"],\n ...Object.entries(headers),\n [HEADER_REQUEST_TYPE, KOS_HTTP_RESPONSE_TYPE],\n ],\n body\n );\n}\n\n/** Encodes an inbound topic push frame. */\nexport function encodeTopicFrame(\n topic: string,\n body: unknown,\n headers: Record<string, string> = {}\n): string {\n return encodeFrame(\n [[HEADER_TOPIC, topic], ...Object.entries(headers)],\n typeof body === \"string\" ? body : JSON.stringify(body ?? {})\n );\n}\n\n/**\n * Encodes an inbound future push frame. Dispatches on the `type` header alone\n * — it must NOT carry topic/subscription/response-id headers or\n * BaseTransport.onMessage would route it elsewhere.\n */\nexport function encodeFutureFrame(future: unknown): string {\n return encodeFrame(\n [[HEADER_REQUEST_TYPE, KOS_FUTURE_TYPE]],\n JSON.stringify(future)\n );\n}\n","// Generic future lifecycle simulator. Emits `type:kos.future` frames through\n// the inbound transport path, so FutureContainerModel republishes them on\n// `kos.future/{tracker||id}` and the real future plumbing (progress, end\n// states, cancellation) runs unmodified. Progress is advanced by accumulated\n// interval ticks, not wall-clock reads, so simulations are deterministic under\n// fake timers.\nimport { uuid } from \"../../../util/api-request-id\";\nimport { KosLog } from \"../../log\";\nimport { encodeFutureFrame } from \"./mock-frames\";\nimport type {\n IKosMockFutureHandle,\n IKosMockFutureSimulator,\n KosMockFutureEndState,\n KosMockFutureFrame,\n KosMockFutureOptions,\n KosMockRequest,\n} from \"./mock-types\";\n\nexport interface FutureSimulatorDeps {\n emitFrame(frame: string): void;\n /** Called on the first future needing them; registers shared cancel routes. */\n ensureCancelRoutes(): void;\n}\n\nconst DEFAULT_DURATION_MS = 5000;\nconst DEFAULT_INTERVAL_MS = 250;\n\nclass KosMockFutureHandle implements IKosMockFutureHandle {\n readonly id: string;\n readonly tracker?: string;\n\n progress = 0;\n done = false;\n\n private remainingTimeMs: number;\n private elapsedMs = 0;\n private endStateValue?: KosMockFutureEndState;\n private reasonValue?: string;\n private timer?: ReturnType<typeof setInterval>;\n private started = false;\n\n private readonly durationMs: number;\n private readonly intervalMs: number;\n private readonly targetEndState: KosMockFutureEndState;\n private readonly targetReason?: string;\n private readonly clientData?: Record<string, unknown>;\n\n constructor(\n options: KosMockFutureOptions,\n private readonly emitFrame: (frame: string) => void\n ) {\n this.id = options.id ?? uuid();\n this.tracker = options.tracker;\n this.durationMs = options.durationMs ?? DEFAULT_DURATION_MS;\n this.intervalMs = options.intervalMs ?? DEFAULT_INTERVAL_MS;\n this.targetEndState = options.endState ?? \"SUCCESS\";\n this.targetReason = options.reason;\n this.clientData = options.clientData;\n this.remainingTimeMs = this.durationMs;\n }\n\n snapshot(): KosMockFutureFrame {\n return {\n id: this.id,\n tracker: this.tracker,\n progress: this.progress,\n remainingTimeMs: this.remainingTimeMs,\n endState: this.endStateValue,\n reason: this.reasonValue,\n clientData: this.clientData,\n };\n }\n\n start(): void {\n if (this.started || this.done) {\n return;\n }\n this.started = true;\n this.timer = setInterval(() => this.tick(), this.intervalMs);\n }\n\n private tick(): void {\n this.elapsedMs += this.intervalMs;\n if (this.elapsedMs >= this.durationMs) {\n this.complete(this.targetEndState, this.targetReason);\n } else {\n this.emitProgress(\n this.elapsedMs / this.durationMs,\n this.durationMs - this.elapsedMs\n );\n }\n }\n\n emitProgress(progress: number, remainingTimeMs?: number): void {\n if (this.done) {\n return;\n }\n this.progress = progress;\n if (remainingTimeMs !== undefined) {\n this.remainingTimeMs = remainingTimeMs;\n }\n this.emitFrame(encodeFutureFrame(this.snapshot()));\n }\n\n complete(endState: KosMockFutureEndState = \"SUCCESS\", reason?: string): void {\n if (this.done) {\n return;\n }\n this.stopTimer();\n this.done = true;\n this.endStateValue = endState;\n this.reasonValue = reason;\n this.remainingTimeMs = 0;\n if (endState === \"SUCCESS\") {\n this.progress = 1;\n }\n this.emitFrame(encodeFutureFrame(this.snapshot()));\n }\n\n cancel(): void {\n this.complete(\"CANCEL\", this.reasonValue ?? \"canceled by mock\");\n }\n\n dispose(): void {\n this.stopTimer();\n this.done = true;\n }\n\n private stopTimer(): void {\n if (this.timer !== undefined) {\n clearInterval(this.timer);\n this.timer = undefined;\n }\n }\n}\n\nexport class KosMockFutureSimulator implements IKosMockFutureSimulator {\n private readonly futures = new Map<string, KosMockFutureHandle>();\n\n constructor(private readonly deps: FutureSimulatorDeps) {}\n\n create(options: KosMockFutureOptions = {}): IKosMockFutureHandle {\n const handle = new KosMockFutureHandle(options, this.deps.emitFrame);\n this.futures.set(handle.id, handle);\n if (options.registerCancelRoute !== false) {\n this.deps.ensureCancelRoutes();\n }\n if (!options.tracker) {\n KosLog.warn(\n `KosMock future ${handle.id} has no tracker — models will not link it to their request; prefer futures.fromRequest`\n );\n }\n if (options.autoStart !== false) {\n handle.start();\n }\n return handle;\n }\n\n fromRequest(\n req: KosMockRequest,\n options: KosMockFutureOptions = {}\n ): IKosMockFutureHandle {\n return this.create({ tracker: req.tracker, ...options });\n }\n\n get(idOrTracker: string): IKosMockFutureHandle | undefined {\n const byId = this.futures.get(idOrTracker);\n if (byId) {\n return byId;\n }\n for (const handle of this.futures.values()) {\n if (handle.tracker === idOrTracker) {\n return handle;\n }\n }\n return undefined;\n }\n\n get active(): IKosMockFutureHandle[] {\n return [...this.futures.values()].filter((handle) => !handle.done);\n }\n\n clear(): void {\n this.futures.forEach((handle) => handle.dispose());\n this.futures.clear();\n }\n}\n","// Out-of-band fixture library. Two backends behind one facade:\n//\n// - browser: IndexedDB (`kos-mock-fixtures` database) — per-browser,\n// per-origin persistence with zero infrastructure.\n// - server: a `kosui fixtures serve` directory over localhost HTTP —\n// committable, shareable, never bundled into the app.\n//\n// When a server is configured it is preferred for saves and lookups; the\n// browser store is the fallback, so the console workflow is identical with\n// or without the server running.\nimport { KosLog } from \"../../log\";\nimport type { KosMockRegistry } from \"./mock-registry\";\nimport type {\n IKosMockFixtureStore,\n KosMockFixture,\n KosMockFixtureSummary,\n KosMockPlaybackHandle,\n KosMockPlaybackOptions,\n} from \"./mock-types\";\n\n/** Default `kosui fixtures serve` address (port 5676 — \"KOSM\" on a keypad). */\nexport const DEFAULT_FIXTURE_SERVER_URL = \"http://localhost:5676\";\n\nconst DB_NAME = \"kos-mock-fixtures\";\nconst STORE_NAME = \"fixtures\";\n\ninterface FixtureBackend {\n save(name: string, fixture: KosMockFixture): Promise<void>;\n load(name: string): Promise<KosMockFixture | undefined>;\n list(): Promise<Omit<KosMockFixtureSummary, \"source\">[]>;\n delete(name: string): Promise<boolean>;\n}\n\nconst summarize = (\n name: string,\n fixture: KosMockFixture\n): Omit<KosMockFixtureSummary, \"source\"> => {\n return {\n name,\n capturedAt: fixture.capturedAt,\n exchanges: fixture.exchanges.length,\n pushes: fixture.pushes.length,\n };\n};\n\n// -- browser backend (IndexedDB) ---------------------------------------------\n\nconst openDb = (): Promise<IDBDatabase> =>\n new Promise((resolve, reject) => {\n const request = indexedDB.open(DB_NAME, 1);\n request.onupgradeneeded = () => {\n if (!request.result.objectStoreNames.contains(STORE_NAME)) {\n request.result.createObjectStore(STORE_NAME);\n }\n };\n request.onsuccess = () => resolve(request.result);\n request.onerror = () => reject(request.error);\n });\n\nconst withStore = async <T>(\n mode: IDBTransactionMode,\n operation: (store: IDBObjectStore) => IDBRequest<T>\n): Promise<T> => {\n const db = await openDb();\n try {\n return await new Promise<T>((resolve, reject) => {\n const request = operation(\n db.transaction(STORE_NAME, mode).objectStore(STORE_NAME)\n );\n request.onsuccess = () => resolve(request.result);\n request.onerror = () => reject(request.error);\n });\n } finally {\n db.close();\n }\n};\n\nclass BrowserFixtureBackend implements FixtureBackend {\n private get available(): boolean {\n return typeof indexedDB !== \"undefined\";\n }\n\n async save(name: string, fixture: KosMockFixture): Promise<void> {\n if (!this.available) {\n throw new Error(\"IndexedDB is not available in this environment\");\n }\n await withStore(\"readwrite\", (store) => store.put(fixture, name));\n }\n\n async load(name: string): Promise<KosMockFixture | undefined> {\n if (!this.available) {\n return undefined;\n }\n return withStore<KosMockFixture | undefined>(\"readonly\", (store) =>\n store.get(name)\n );\n }\n\n async list(): Promise<Omit<KosMockFixtureSummary, \"source\">[]> {\n if (!this.available) {\n return [];\n }\n const [keys, values] = await Promise.all([\n withStore<IDBValidKey[]>(\"readonly\", (store) => store.getAllKeys()),\n withStore<KosMockFixture[]>(\"readonly\", (store) => store.getAll()),\n ]);\n return keys.map((key, index) => summarize(String(key), values[index]));\n }\n\n async delete(name: string): Promise<boolean> {\n if (!this.available) {\n return false;\n }\n const existing = await this.load(name);\n if (!existing) {\n return false;\n }\n await withStore(\"readwrite\", (store) => store.delete(name));\n return true;\n }\n}\n\n// -- server backend (kosui fixtures serve) -----------------------------------\n\nexport class ServerFixtureBackend implements FixtureBackend {\n constructor(private readonly baseUrl: string) {}\n\n private url(name?: string): string {\n const base = this.baseUrl.replace(/\\/$/, \"\");\n return name\n ? `${base}/fixtures/${encodeURIComponent(name)}`\n : `${base}/fixtures`;\n }\n\n async save(name: string, fixture: KosMockFixture): Promise<void> {\n const response = await fetch(this.url(name), {\n method: \"PUT\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(fixture),\n });\n if (!response.ok) {\n throw new Error(`Fixture server rejected save: ${response.status}`);\n }\n }\n\n async load(name: string): Promise<KosMockFixture | undefined> {\n const response = await fetch(this.url(name));\n if (!response.ok) {\n return undefined;\n }\n return (await response.json()) as KosMockFixture;\n }\n\n async list(): Promise<Omit<KosMockFixtureSummary, \"source\">[]> {\n const response = await fetch(this.url());\n if (!response.ok) {\n return [];\n }\n const payload = (await response.json()) as {\n fixtures: Omit<KosMockFixtureSummary, \"source\">[];\n };\n return payload.fixtures ?? [];\n }\n\n async delete(name: string): Promise<boolean> {\n const response = await fetch(this.url(name), { method: \"DELETE\" });\n return response.ok;\n }\n}\n\n// -- facade -------------------------------------------------------------------\n\nexport interface FixtureStoreDeps {\n browserBackend?: FixtureBackend;\n serverBackendFactory?: (url: string) => FixtureBackend;\n}\n\nexport function createFixtureStore(\n registry: KosMockRegistry,\n deps: FixtureStoreDeps = {}\n): IKosMockFixtureStore {\n const browser = deps.browserBackend ?? new BrowserFixtureBackend();\n const serverFactory =\n deps.serverBackendFactory ??\n ((url: string) => new ServerFixtureBackend(url));\n\n let server: FixtureBackend | undefined;\n let serverUrl: string | undefined;\n\n const resolveName = (fixture: KosMockFixture, name?: string): string => {\n const resolved = name ?? fixture.name;\n if (!resolved) {\n throw new Error(\n \"Fixture has no name — pass one: fixtures.save(fixture, {name})\"\n );\n }\n return resolved;\n };\n\n const store: IKosMockFixtureStore = {\n get serverUrl() {\n return serverUrl;\n },\n\n useServer(url) {\n if (url === undefined) {\n server = undefined;\n serverUrl = undefined;\n return;\n }\n serverUrl = url === true ? DEFAULT_FIXTURE_SERVER_URL : url;\n server = serverFactory(serverUrl);\n },\n\n async save(fixture, options = {}) {\n const name = resolveName(fixture, options.name);\n const named = { ...fixture, name };\n const target =\n options.to === \"browser\"\n ? browser\n : options.to === \"server\"\n ? server\n : server ?? browser;\n if (!target) {\n throw new Error(\n \"No fixture server configured — useServer() or save to the browser\"\n );\n }\n await target.save(name, named);\n KosLog.info(`KosMock fixture \"${name}\" saved`);\n return name;\n },\n\n saveRecording(name) {\n return store.save(registry.recorder.toFixture(), { name });\n },\n\n async load(name) {\n if (server) {\n const fromServer = await server\n .load(name)\n .catch(() => undefined as KosMockFixture | undefined);\n if (fromServer) {\n return fromServer;\n }\n }\n return browser.load(name).catch(() => undefined);\n },\n\n async list() {\n const summaries: KosMockFixtureSummary[] = [];\n if (server) {\n try {\n (await server.list()).forEach((summary) =>\n summaries.push({ ...summary, source: \"server\" })\n );\n } catch {\n KosLog.warn(`KosMock fixture server unreachable at ${serverUrl}`);\n }\n }\n try {\n (await browser.list()).forEach((summary) =>\n summaries.push({ ...summary, source: \"browser\" })\n );\n } catch {\n // IndexedDB unavailable — server results (if any) still stand.\n }\n return summaries;\n },\n\n async delete(name) {\n let deleted = false;\n if (server) {\n deleted = (await server.delete(name).catch(() => false)) || deleted;\n }\n deleted = (await browser.delete(name).catch(() => false)) || deleted;\n return deleted;\n },\n\n async import() {\n if (typeof document === \"undefined\") {\n KosLog.warn(`KosMock fixture import requires a browser environment`);\n return undefined;\n }\n return new Promise((resolve) => {\n const input = document.createElement(\"input\");\n input.type = \"file\";\n input.accept = \".json,application/json\";\n input.onchange = async () => {\n const file = input.files?.[0];\n if (!file) {\n resolve(undefined);\n return;\n }\n try {\n const fixture = JSON.parse(await file.text()) as KosMockFixture;\n const name = await store.save(fixture, {\n name: fixture.name ?? file.name.replace(/\\.json$/, \"\"),\n });\n resolve(name);\n } catch (error: any) {\n KosLog.error(`KosMock fixture import failed`, error?.message);\n resolve(undefined);\n }\n };\n input.click();\n });\n },\n\n async play(name, options?: KosMockPlaybackOptions) {\n const fixture = await store.load(name);\n if (!fixture) {\n throw new Error(\n `No fixture named \"${name}\" in the store${\n serverUrl ? ` or at ${serverUrl}` : \"\"\n }`\n );\n }\n return registry.loadFixture(fixture, options) as KosMockPlaybackHandle;\n },\n };\n\n return store;\n}\n","// Pure route-pattern matching for the KosMock facility. No transport imports —\n// keep this module trivially unit-testable.\n\nexport interface KosMockCompiledRoute {\n pattern: string;\n regex: RegExp;\n paramNames: string[];\n}\n\nconst REGEX_SPECIALS = /[.*+?^${}()|[\\]\\\\]/g;\n\nconst escapeLiteral = (segment: string) =>\n segment.replace(REGEX_SPECIALS, \"\\\\$&\");\n\n/** Strips a trailing slash so `/a/b/` and `/a/b` compare equal (root `/` kept). */\nexport const normalizePath = (path: string) =>\n path.length > 1 && path.endsWith(\"/\") ? path.slice(0, -1) : path;\n\n/**\n * Compiles a route pattern into a regex.\n *\n * Syntax:\n * - `:name` matches one path segment and captures it under `name`\n * - `*` as a non-final segment matches one segment (uncaptured)\n * - `*` as the final segment matches the rest of the path (captured as `*`)\n */\nexport function compileRoutePattern(pattern: string): KosMockCompiledRoute {\n const paramNames: string[] = [];\n const segments = normalizePath(pattern).split(\"/\");\n\n const parts = segments.map((segment, index) => {\n if (segment.startsWith(\":\") && segment.length > 1) {\n paramNames.push(segment.slice(1));\n return \"([^/]+)\";\n }\n if (segment === \"*\") {\n if (index === segments.length - 1) {\n paramNames.push(\"*\");\n return \"(.*)\";\n }\n return \"[^/]+\";\n }\n return escapeLiteral(segment);\n });\n\n return {\n pattern,\n regex: new RegExp(`^${parts.join(\"/\")}$`),\n paramNames,\n };\n}\n\n/** Returns captured params on match, undefined otherwise. */\nexport function matchRoutePattern(\n compiled: KosMockCompiledRoute,\n path: string\n): Record<string, string> | undefined {\n const result = compiled.regex.exec(normalizePath(path));\n if (!result) {\n return undefined;\n }\n const params: Record<string, string> = {};\n compiled.paramNames.forEach((name, index) => {\n params[name] = result[index + 1];\n });\n return params;\n}\n\n/** Splits a wire `url` header into pathname and decoded query params. */\nexport function splitUrl(url: string): {\n path: string;\n query: Record<string, string>;\n} {\n const queryIndex = url.indexOf(\"?\");\n if (queryIndex === -1) {\n return { path: url, query: {} };\n }\n const path = url.slice(0, queryIndex);\n const query: Record<string, string> = {};\n for (const pair of url.slice(queryIndex + 1).split(\"&\")) {\n if (!pair) {\n continue;\n }\n const [key, value] = pair.split(\"=\");\n query[decodeURIComponent(key)] = decodeURIComponent(value || \"\");\n }\n return { path, query };\n}\n\nexport function methodMatches(\n routeMethod: string,\n requestMethod: string\n): boolean {\n return (\n routeMethod === \"*\" ||\n routeMethod.toUpperCase() === requestMethod.toUpperCase()\n );\n}\n","// Fixture playback: turns a recorded KosMockFixture back into live behavior\n// with captured timings intact.\n//\n// - Captured exchanges become routes replaying their responses in captured\n// order (per endpoint), each delayed by its captured request→response\n// latency.\n// - Multiplexed endpoints (many operations over one path) replay correctly\n// via body discriminators: a dotted path (or function) extracts the\n// operation from each request body, captured exchanges are bucketed by\n// that value, and every incoming request is served from its own bucket —\n// so calls needn't repeat the captured order. Unknown values decline.\n// - The consume policy decides what a served exchange leaves behind:\n// \"once\" retires it (a dry endpoint declines, passing through to the real\n// backend in hybrid mode — captured responses never shadow live reality\n// twice); \"repeat-last\" keeps re-serving the final response (the default\n// for standalone, where there is no backend to fall through to).\n// - Future pushes whose tracker matches a captured exchange are ANCHORED to\n// that exchange: when the replayed request comes in, its frames are\n// scheduled at the captured request→frame deltas — so a pour replayed at\n// any moment gets its progress cadence exactly as the device produced it.\n// - Everything else (topics, unmatched futures) replays on the absolute\n// captured timeline (\"scheduled\") or on `startPushes()` (\"manual\").\n//\n// Future linkage across replay: a replayed pour generates a fresh tracker,\n// so playback maintains a captured→live tracker map (populated as requests\n// are served) and rewrites trackers in response bodies and future-frame\n// bodies. Trackers are uuids — plain string substitution is collision-safe.\nimport { KosLog } from \"../../log\";\nimport { encodeTopicFrame, KOS_FUTURE_TYPE } from \"./mock-frames\";\nimport type { KosMockRegistry } from \"./mock-registry\";\nimport type {\n KosMockFixture,\n KosMockFixtureExchange,\n KosMockFixturePush,\n KosMockHandle,\n KosMockPlaybackHandle,\n KosMockPlaybackOptions,\n} from \"./mock-types\";\nimport { splitUrl } from \"./route-matcher\";\n\ntype DiscriminatorSpec = string | ((body: unknown) => unknown);\n\nconst rewriteTrackers = (\n raw: string,\n trackerMap: Map<string, string>\n): string => {\n let out = raw;\n trackerMap.forEach((liveTracker, capturedTracker) => {\n out = out.split(capturedTracker).join(liveTracker);\n });\n return out;\n};\n\n/** Discriminator value as a bucket key; errors and misses become \"undefined\". */\nconst discriminatorKey = (spec: DiscriminatorSpec, body: unknown): string => {\n try {\n if (typeof spec === \"function\") {\n return String(spec(body));\n }\n let current: unknown = body;\n for (const part of spec.split(\".\")) {\n if (current === null || typeof current !== \"object\") {\n return String(undefined);\n }\n current = (current as Record<string, unknown>)[part];\n }\n return String(current);\n } catch {\n return String(undefined);\n }\n};\n\ninterface ServeQueue {\n queue: KosMockFixtureExchange[];\n served: number;\n}\n\nexport function installFixturePlayback(\n registry: KosMockRegistry,\n fixture: KosMockFixture,\n options: KosMockPlaybackOptions = {}\n): KosMockPlaybackHandle {\n const name = options.name ?? fixture.name;\n const speed = options.speed ?? 1;\n const consume =\n options.consume ?? (registry.standalone ? \"repeat-last\" : \"once\");\n const discriminators: Record<string, DiscriminatorSpec> = {\n ...fixture.discriminators,\n ...options.discriminators,\n };\n const trackerMap = new Map<string, string>();\n const timers = new Set<ReturnType<typeof setTimeout>>();\n let stopped = false;\n\n const schedule = (delayMs: number, fire: () => void) => {\n const timer = setTimeout(() => {\n timers.delete(timer);\n fire();\n }, Math.max(0, delayMs));\n timers.add(timer);\n };\n\n const firePush = (push: KosMockFixturePush) => {\n if (push.kind === \"topic\" && push.topic) {\n registry.publishFrame(encodeTopicFrame(push.topic, push.body));\n } else if (push.kind === \"future\") {\n // Rewrite at fire time — the live tracker may only become known once\n // the replayed request has been served.\n registry.publishFrame(\n `type:${KOS_FUTURE_TYPE}\\n\\n${rewriteTrackers(push.body, trackerMap)}`\n );\n }\n };\n\n // Split pushes: futures whose tracker matches a captured exchange anchor to\n // that exchange; the rest live on the absolute timeline.\n const capturedTrackers = new Set(\n fixture.exchanges\n .map((exchange) => exchange.tracker)\n .filter((tracker): tracker is string => !!tracker)\n );\n const anchoredByTracker = new Map<string, KosMockFixturePush[]>();\n const unanchored: KosMockFixturePush[] = [];\n for (const push of fixture.pushes) {\n if (\n push.kind === \"future\" &&\n push.tracker &&\n capturedTrackers.has(push.tracker)\n ) {\n const list = anchoredByTracker.get(push.tracker) ?? [];\n list.push(push);\n anchoredByTracker.set(push.tracker, list);\n } else {\n unanchored.push(push);\n }\n }\n\n // Group captured exchanges per (method, path); each group replays in order,\n // or per discriminator bucket when one is configured for the endpoint.\n const groups = new Map<\n string,\n { method: string; path: string; queue: KosMockFixtureExchange[] }\n >();\n for (const exchange of fixture.exchanges) {\n const { path } = splitUrl(exchange.url);\n const key = `${exchange.method.toUpperCase()} ${path}`;\n const group = groups.get(key) ?? {\n method: exchange.method.toUpperCase(),\n path,\n queue: [],\n };\n group.queue.push(exchange);\n groups.set(key, group);\n }\n\n const anchorsScheduled = new Set<string>();\n const routeHandles: KosMockHandle[] = [];\n groups.forEach((group, groupKey) => {\n const spec = discriminators[groupKey];\n const wholeGroup: ServeQueue = { queue: group.queue, served: 0 };\n let buckets: Map<string, ServeQueue> | undefined;\n if (spec !== undefined) {\n buckets = new Map();\n for (const exchange of group.queue) {\n let parsedBody: unknown;\n try {\n parsedBody = exchange.requestBody\n ? JSON.parse(exchange.requestBody)\n : undefined;\n } catch {\n parsedBody = undefined;\n }\n const key = discriminatorKey(spec, parsedBody);\n const bucket = buckets.get(key) ?? { queue: [], served: 0 };\n bucket.queue.push(exchange);\n buckets.set(key, bucket);\n }\n }\n\n routeHandles.push(\n registry.route(\n group.method as never,\n group.path,\n (req) => {\n if (stopped) {\n return undefined;\n }\n let serveQueue: ServeQueue | undefined;\n if (buckets && spec !== undefined) {\n serveQueue = buckets.get(discriminatorKey(spec, req.json()));\n if (!serveQueue) {\n return undefined; // Uncaptured operation — decline.\n }\n } else {\n serveQueue = wholeGroup;\n }\n if (serveQueue.served >= serveQueue.queue.length) {\n if (consume === \"once\") {\n return undefined; // Retired — hybrid falls through to reality.\n }\n serveQueue.served = serveQueue.queue.length - 1; // repeat last\n }\n const exchange = serveQueue.queue[serveQueue.served];\n serveQueue.served += 1;\n\n if (exchange.tracker && req.tracker) {\n trackerMap.set(exchange.tracker, req.tracker);\n }\n // Anchored frames fire relative to this request, at the captured\n // request→frame deltas.\n if (exchange.tracker && !anchorsScheduled.has(exchange.tracker)) {\n anchorsScheduled.add(exchange.tracker);\n const anchored = anchoredByTracker.get(exchange.tracker) ?? [];\n anchored.forEach((push) =>\n schedule((push.tMs - exchange.tMs) / speed, () => firePush(push))\n );\n }\n return {\n status: exchange.status,\n raw: rewriteTrackers(exchange.responseBody, trackerMap),\n delayMs: options.ignoreLatency\n ? 0\n : (exchange.latencyMs ?? 0) / speed,\n };\n },\n {\n fixture: name,\n description: `fixture replay: ${group.method} ${group.path} (${\n group.queue.length\n } captured${spec !== undefined ? \", discriminated\" : \"\"})`,\n }\n )\n );\n });\n\n // Absolute timeline for unanchored pushes.\n let pushesStarted = false;\n const startPushes = () => {\n if (pushesStarted) {\n return;\n }\n pushesStarted = true;\n unanchored.forEach((push) =>\n schedule(push.tMs / speed, () => firePush(push))\n );\n };\n\n if ((options.pushes ?? \"scheduled\") === \"scheduled\") {\n startPushes();\n }\n\n KosLog.info(\n `KosMock fixture${name ? ` \"${name}\"` : \"\"} loaded: ${\n groups.size\n } routes, ${fixture.pushes.length} pushes (${\n fixture.pushes.length - unanchored.length\n } anchored), consume: ${consume}`\n );\n\n return {\n name,\n startPushes,\n stop: () => {\n stopped = true;\n routeHandles.forEach((handle) => handle.remove());\n timers.forEach((timer) => clearTimeout(timer));\n timers.clear();\n },\n };\n}\n","// Live-traffic recorder. The interceptor tees every outbound frame and every\n// inbound frame (real, mocked, or injected) through here; while recording,\n// request/response pairs become fixture \"exchanges\" (matched by request-id)\n// and topic/future frames become fixture \"pushes\" with their timeline\n// offsets. The result is a plain-JSON KosMockFixture that\n// `KosMock.loadFixture` can replay for offline testing.\nimport { KosLog } from \"../../log\";\nimport { processKosMessage } from \"../base-message-transport\";\nimport {\n decodeRequestFrame,\n KOS_FUTURE_TYPE,\n KOS_MOCKED_HEADER,\n} from \"./mock-frames\";\nimport type {\n IKosMockRecorder,\n KosMockFixture,\n KosMockFixtureExchange,\n KosMockFixturePush,\n KosMockFixtureSend,\n} from \"./mock-types\";\n\ninterface PendingRequest {\n tMs: number;\n method: string;\n url: string;\n tracker?: string;\n requestBody?: string;\n requestHeaders?: Record<string, string>;\n}\n\nexport class KosMockRecorder implements IKosMockRecorder {\n private recording = false;\n private name?: string;\n private startedAt = 0;\n private capturedAt?: string;\n private readonly pending = new Map<string, PendingRequest>();\n private exchanges: KosMockFixtureExchange[] = [];\n private pushes: KosMockFixturePush[] = [];\n private sends: KosMockFixtureSend[] = [];\n\n get isRecording(): boolean {\n return this.recording;\n }\n\n start(options: { name?: string } = {}): void {\n this.recording = true;\n this.name = options.name;\n this.startedAt = Date.now();\n this.capturedAt = new Date().toISOString();\n this.pending.clear();\n this.exchanges = [];\n this.pushes = [];\n this.sends = [];\n KosLog.info(\n `KosMock recorder started${options.name ? ` (${options.name})` : \"\"}`\n );\n }\n\n stop(): KosMockFixture {\n const fixture = this.toFixture();\n this.recording = false;\n KosLog.info(\n `KosMock recorder stopped: ${fixture.exchanges.length} exchanges, ${\n fixture.pushes.length\n } pushes, ${fixture.sends?.length ?? 0} sends`\n );\n return fixture;\n }\n\n toFixture(): KosMockFixture {\n return {\n version: 1,\n name: this.name,\n capturedAt: this.capturedAt,\n exchanges: [...this.exchanges],\n pushes: [...this.pushes],\n sends: [...this.sends],\n };\n }\n\n download(filename?: string): void {\n if (typeof document === \"undefined\") {\n KosLog.warn(`KosMock recorder download requires a browser environment`);\n return;\n }\n const fixture = this.toFixture();\n const blob = new Blob([JSON.stringify(fixture, null, 2)], {\n type: \"application/json\",\n });\n const url = URL.createObjectURL(blob);\n const anchor = document.createElement(\"a\");\n anchor.href = url;\n anchor.download = filename ?? `${fixture.name ?? \"kos-mock-fixture\"}.json`;\n anchor.click();\n URL.revokeObjectURL(url);\n }\n\n private elapsed(): number {\n return Date.now() - this.startedAt;\n }\n\n /** Interceptor tap: every outbound frame. Internal. */\n noteOutbound(data: string | ArrayBufferLike | Blob | ArrayBufferView): void {\n if (!this.recording) {\n return;\n }\n const frame = decodeRequestFrame(data);\n if (!frame) {\n this.noteSend(data);\n return;\n }\n this.pending.set(frame.requestId, {\n tMs: this.elapsed(),\n method: frame.method,\n url: frame.url,\n tracker: frame.tracker,\n requestBody: frame.rawBody,\n requestHeaders: frame.headers,\n });\n }\n\n /**\n * Everything else a window sends: alias registration, broker subscribes,\n * client-sent futures. What a window asked for is not recoverable from the\n * responses it got back, so it is captured rather than discarded.\n */\n private noteSend(\n data: string | ArrayBufferLike | Blob | ArrayBufferView\n ): void {\n if (typeof data !== \"string\") {\n return;\n }\n let headers: Record<string, string>;\n let body: string;\n try {\n ({ headers, body } = processKosMessage(data));\n } catch {\n return;\n }\n this.sends.push({\n tMs: this.elapsed(),\n type: headers[\"type\"],\n headers: headers,\n ...(body ? { body } : {}),\n });\n }\n\n /** Interceptor tap: every inbound frame (real, mocked, injected). Internal. */\n noteInbound(frame: string): void {\n if (!this.recording) {\n return;\n }\n let headers: Record<string, string>;\n let body: string;\n try {\n ({ headers, body } = processKosMessage(frame));\n } catch {\n return;\n }\n\n const responseId = headers[\"response-id\"];\n if (responseId) {\n const request = this.pending.get(responseId);\n if (!request) {\n return; // Response to a request sent before recording started.\n }\n this.pending.delete(responseId);\n this.exchanges.push({\n ...request,\n status: parseInt(headers[\"status\"] ?? \"200\", 10) || 200,\n responseBody: body ?? \"\",\n responseHeaders: headers,\n latencyMs: Math.max(0, this.elapsed() - request.tMs),\n ...(headers[KOS_MOCKED_HEADER] === \"true\" ? { mocked: true } : {}),\n });\n return;\n }\n\n const topic = headers[\"subscription\"] || headers[\"topic\"];\n if (topic) {\n this.pushes.push({\n tMs: this.elapsed(),\n kind: \"topic\",\n topic,\n body: body ?? \"\",\n headers: headers,\n });\n return;\n }\n\n if (headers[\"type\"] === KOS_FUTURE_TYPE) {\n let tracker: string | undefined;\n try {\n tracker = JSON.parse(body)?.tracker;\n } catch {\n // Unparseable future body — keep the push without tracker linkage.\n }\n this.pushes.push({\n tMs: this.elapsed(),\n kind: \"future\",\n tracker,\n body: body ?? \"\",\n headers: headers,\n });\n }\n }\n}\n","// Out-of-band imperative setups. Fixtures carry data; a setup module carries\n// code — transformers, custom route handlers, config injections, observers —\n// authored against the KosMock instance and served read-only by\n// `kosui fixtures serve` from its `setups/` directory:\n//\n// // fixtures/setups/agitation-choreo.mjs\n// export default (kosMock) => {\n// const observer = kosMock.observe({ onFuture: (f) => { ... } });\n// return () => observer(); // teardown\n// };\n//\n// The default export may be sync or async and may return a teardown. Modules\n// import nothing (the KosMock instance is passed in / on window.KosMock), so\n// they load from any origin without a bundler.\nimport { KosLog } from \"../../log\";\nimport { DEFAULT_FIXTURE_SERVER_URL } from \"./mock-fixtures\";\nimport type { KosMockRegistry } from \"./mock-registry\";\nimport type {\n IKosMockSetupStore,\n KosMockSetupHandle,\n KosMockSetupModule,\n} from \"./mock-types\";\n\nexport interface SetupStoreDeps {\n /** Module loader seam — tests inject a fake; default is dynamic import. */\n loadModule?: (url: string) => Promise<{ default?: KosMockSetupModule }>;\n}\n\n// The ignore comments keep bundlers (vite/webpack) from trying to resolve a\n// runtime URL at build time.\nconst dynamicImport = (url: string) =>\n import(/* @vite-ignore */ /* webpackIgnore: true */ url);\n\nexport function createSetupStore(\n registry: KosMockRegistry,\n deps: SetupStoreDeps = {}\n): IKosMockSetupStore {\n const loadModule = deps.loadModule ?? dynamicImport;\n const activeSetups = new Map<\n string,\n { handle: KosMockSetupHandle; teardown?: () => void }\n >();\n\n const serverBase = () =>\n (registry.fixtures.serverUrl ?? DEFAULT_FIXTURE_SERVER_URL).replace(\n /\\/$/,\n \"\"\n );\n\n const resolve = (nameOrUrl: string): { name: string; url: string } => {\n if (/^https?:\\/\\//.test(nameOrUrl)) {\n const stem = nameOrUrl.split(\"/\").pop() ?? nameOrUrl;\n return { name: stem.replace(/\\.mjs$/, \"\"), url: nameOrUrl };\n }\n const name = nameOrUrl.replace(/\\.mjs$/, \"\");\n return {\n name,\n url: `${serverBase()}/setups/${encodeURIComponent(name)}.mjs`,\n };\n };\n\n const runTeardown = (name: string): boolean => {\n const entry = activeSetups.get(name);\n if (!entry) {\n return false;\n }\n activeSetups.delete(name);\n try {\n entry.teardown?.();\n } catch (error: any) {\n KosLog.error(`KosMock setup \"${name}\" teardown threw`, error?.message);\n }\n return true;\n };\n\n const store: IKosMockSetupStore = {\n async load(nameOrUrl) {\n const { name, url } = resolve(nameOrUrl);\n const module = await loadModule(url);\n const setup = module?.default;\n if (typeof setup !== \"function\") {\n throw new Error(\n `Setup module ${url} has no default-export function (see KosMockSetupModule)`\n );\n }\n // Replace semantics: unwind a previous load of the same name first.\n runTeardown(name);\n\n const result = await setup(registry);\n const handle: KosMockSetupHandle = {\n name,\n url,\n unload: () => {\n runTeardown(name);\n },\n };\n activeSetups.set(name, {\n handle,\n teardown: typeof result === \"function\" ? result : undefined,\n });\n KosLog.info(`KosMock setup \"${name}\" installed from ${url}`);\n return handle;\n },\n\n async list() {\n const response = await fetch(`${serverBase()}/setups`);\n if (!response.ok) {\n return [];\n }\n const payload = (await response.json()) as {\n setups: Array<{ name: string }>;\n };\n return payload.setups ?? [];\n },\n\n active() {\n return [...activeSetups.values()].map((entry) => entry.handle);\n },\n\n unload(name) {\n return runTeardown(name);\n },\n\n clear() {\n [...activeSetups.keys()].forEach((name) => runTeardown(name));\n },\n };\n\n return store;\n}\n","// Config-property simulation over the standard config-bean wire surface:\n//\n// read GET /api/kos/config/details/{beanId}/{depth}\n// → {status, data: {scopes, details: [{bean, scopes, schema: {paths, schema}}]}}\n// write POST /api/kos/config/{beanId} body {prop: value}\n// change WS topic /kos/config/{beanId}\n// → {changes: [{attr, currentValue, previousValue}], scopedChanges, errors}\n//\n// (Shapes per models/services/config-bean and the config-bean model's topic\n// handler. Values ride the change topic as strings.)\n//\n// `update` simulates a change by publishing the topic — pure injection, works\n// against a live device. `inject` goes further: it overlays properties (and\n// their schema nodes) that the backend does not implement yet, transforming\n// reads in flight and absorbing writes that touch only injected props.\nimport { KosLog } from \"../../log\";\nimport type { KosMockRegistry } from \"./mock-registry\";\nimport type {\n KosMockConfigFacade,\n KosMockConfigInjectionHandle,\n} from \"./mock-types\";\n\nconst asWireValue = (value: unknown): string =>\n typeof value === \"string\" ? value : JSON.stringify(value);\n\nconst configTopic = (beanId: string) => `/kos/config/${beanId}`;\n\nconst changeEnvelope = (\n props: Record<string, unknown>,\n previousValues: Record<string, unknown> = {}\n) => {\n return {\n changes: Object.entries(props).map(([attr, value]) => {\n return {\n attr,\n currentValue: asWireValue(value),\n previousValue:\n previousValues[attr] === undefined\n ? \"\"\n : asWireValue(previousValues[attr]),\n };\n }),\n scopedChanges: [],\n errors: [],\n };\n};\n\nexport function createConfigFacade(\n registry: KosMockRegistry\n): KosMockConfigFacade {\n const update: KosMockConfigFacade[\"update\"] = (\n beanId,\n props,\n options = {}\n ) => {\n registry.publishTopic(\n configTopic(beanId),\n changeEnvelope(props, options.previousValues)\n );\n };\n\n const inject: KosMockConfigFacade[\"inject\"] = (beanId, injection) => {\n const current: Record<string, unknown> = { ...injection.props };\n const schema = injection.schema ?? {};\n\n // Reads: merge injected props + schema into the details response.\n const transformerHandle = registry.transformResponse(\n \"GET\",\n `/api/kos/config/details/${beanId}/:depth`,\n (body: any) => {\n if (!body || typeof body !== \"object\") {\n return undefined;\n }\n const details = Array.isArray(body.data?.details)\n ? body.data.details\n : undefined;\n if (!details) {\n return undefined;\n }\n const detail = details[0] ?? {};\n details[0] = {\n ...detail,\n bean: { ...detail.bean, ...current },\n schema: {\n paths: [\n ...(detail.schema?.paths ?? []),\n ...Object.keys(schema).filter(\n (key) => !(detail.schema?.paths ?? []).includes(key)\n ),\n ],\n schema: { ...detail.schema?.schema, ...schema },\n },\n };\n return body;\n },\n { description: `config.inject ${beanId}` }\n );\n\n // Writes: absorb modifications that touch only injected props; anything\n // else passes through to the real backend untouched.\n const routeHandle = registry.post(\n `/api/kos/config/${beanId}`,\n (req) => {\n const requested = req.json<Record<string, unknown>>();\n if (!requested) {\n return undefined;\n }\n const keys = Object.keys(requested);\n const injectedKeys = keys.filter((key) => key in current);\n if (injectedKeys.length === 0) {\n return undefined;\n }\n if (injectedKeys.length < keys.length) {\n KosLog.warn(\n `KosMock config.inject ${beanId}: mixed write passes through; injected props will be rejected by the backend: ${injectedKeys.join(\n \", \"\n )}`\n );\n return undefined;\n }\n const previousValues = { ...current };\n Object.assign(current, requested);\n update(beanId, requested, { previousValues });\n return { data: {} };\n },\n { description: `config.inject ${beanId} writes` }\n );\n\n const handle: KosMockConfigInjectionHandle = {\n id: routeHandle.id,\n set: (props) => {\n const previousValues = { ...current };\n Object.assign(current, props);\n update(beanId, props, { previousValues });\n },\n remove: () => {\n transformerHandle.remove();\n routeHandle.remove();\n },\n enable: () => undefined,\n disable: () => {\n transformerHandle.remove();\n routeHandle.remove();\n },\n };\n return handle;\n };\n\n return { update, inject };\n}\n","// The KosMock registry: single source of truth for mock routes, topic\n// emitters, simulated futures, and scenario state. The transport interceptor\n// and the standalone socket both consult it per frame, so registrations take\n// effect on the next request — statically at startup or dynamically on a live\n// connection.\nimport { uuid } from \"../../../util/api-request-id\";\nimport { getQueryParams } from \"../../../util/get-query-params\";\nimport {\n hasKosProfile,\n resolveKosProfiles,\n} from \"../../../util/kos-config-init\";\nimport { KosLog } from \"../../log\";\nimport { KosMockFutureSimulator } from \"./future-simulator\";\nimport { createFixtureStore } from \"./mock-fixtures\";\nimport { installFixturePlayback } from \"./mock-playback\";\nimport { KosMockRecorder } from \"./mock-recorder\";\nimport { createSetupStore } from \"./mock-setups\";\nimport { processKosMessage } from \"../base-message-transport\";\nimport { createConfigFacade } from \"./mock-config\";\nimport {\n decodeRequestFrame,\n decodeSubscribeTopics,\n encodeHttpResponseFrame,\n encodeRawFrame,\n encodeTopicFrame,\n KOS_FUTURE_TYPE,\n KOS_MOCK_FIXTURE_HEADER,\n KOS_MOCK_TRANSFORMED_HEADER,\n KOS_MOCKED_HEADER,\n} from \"./mock-frames\";\nimport type {\n IKosMockControl,\n KosMockConfig,\n KosMockFixture,\n KosMockHandle,\n KosMockMethod,\n KosMockObserver,\n KosMockPlaybackHandle,\n KosMockPlaybackOptions,\n KosMockRequest,\n KosMockRequestObservation,\n KosMockResponse,\n KosMockResponseTransformer,\n KosMockRouteHandler,\n KosMockRouteInfo,\n KosMockRouteOptions,\n KosMockScenario,\n} from \"./mock-types\";\nimport {\n compileRoutePattern,\n KosMockCompiledRoute,\n matchRoutePattern,\n methodMatches,\n splitUrl,\n} from \"./route-matcher\";\n\n/** Frame delivery seam handed to the registry by a transport integration. */\nexport interface KosMockFrameIO {\n /** Injects an inbound frame through the real receive path. */\n deliver(frame: string): void;\n /** Sends the original outbound frame onward (hybrid pass-through). */\n forward(): void;\n}\n\ninterface RegisteredRoute {\n id: string;\n method: KosMockMethod;\n pattern: string;\n compiled: KosMockCompiledRoute;\n handler: KosMockRouteHandler;\n description?: string;\n once: boolean;\n enabled: boolean;\n delayMs?: number;\n fixture?: string;\n when?: (req: KosMockRequest) => boolean;\n hitCount: number;\n}\n\ninterface RegisteredTransformer {\n id: string;\n method: KosMockMethod;\n pattern: string;\n compiled: KosMockCompiledRoute;\n transform: KosMockResponseTransformer;\n description?: string;\n}\n\n/** Outbound requests kept for response correlation (transformers). */\nconst PENDING_REQUEST_CAP = 500;\n\nconst sleep = (ms: number) =>\n new Promise<void>((resolve) => setTimeout(resolve, ms));\n\nconst asHandler = (\n handler: KosMockRouteHandler | KosMockResponse\n): KosMockRouteHandler =>\n typeof handler === \"function\" ? handler : () => handler;\n\nexport class KosMockRegistry implements IKosMockControl {\n private routes: RegisteredRoute[] = [];\n private settings: KosMockConfig = {};\n private enabledFlag = false;\n private readonly injectors = new Set<(frame: string) => void>();\n private readonly subscribedTopicSet = new Set<string>();\n private readonly emitters = new Map<string, ReturnType<typeof setInterval>>();\n private readonly scenarioTeardowns = new Map<string, () => void>();\n private cancelRoutesRegistered = false;\n\n readonly state = new Map<string, unknown>();\n\n readonly futures = new KosMockFutureSimulator({\n emitFrame: (frame) => this.publishFrame(frame),\n ensureCancelRoutes: () => this.ensureFutureCancelRoutes(),\n });\n\n readonly recorder = new KosMockRecorder();\n\n readonly config = createConfigFacade(this);\n\n readonly fixtures = createFixtureStore(this);\n\n readonly setups = createSetupStore(this);\n\n /**\n * Internal: when set (a boot fixture is loading), the standalone socket\n * delays its open until this settles, so replayed routes exist before the\n * app's boot requests fire. Always resolves (errors are logged upstream).\n */\n bootGate?: Promise<void>;\n\n private readonly observers = new Set<KosMockObserver>();\n\n private transformers: RegisteredTransformer[] = [];\n\n private readonly pendingRequests = new Map<\n string,\n KosMockRequestObservation\n >();\n\n transformResponse(\n method: KosMockMethod,\n pattern: string,\n transform: KosMockResponseTransformer,\n options: { id?: string; description?: string } = {}\n ): KosMockHandle {\n const registered: RegisteredTransformer = {\n id: options.id ?? uuid(),\n method,\n pattern,\n compiled: compileRoutePattern(pattern),\n transform,\n description: options.description,\n };\n this.transformers.push(registered);\n const remove = () => {\n this.transformers = this.transformers.filter(\n (candidate) => candidate.id !== registered.id\n );\n };\n return {\n id: registered.id,\n remove,\n enable: () => undefined,\n disable: remove,\n };\n }\n\n /**\n * Interceptor seam: patches a matching inbound response frame through the\n * transformer chain before it reaches the app. Returns the (possibly\n * modified) frame. Internal.\n */\n transformInboundFrame(frame: string): string {\n if (this.transformers.length === 0) {\n return frame;\n }\n let headers: Record<string, string>;\n let body: string;\n try {\n ({ headers, body } = processKosMessage(frame));\n } catch {\n return frame;\n }\n const responseId = headers[\"response-id\"];\n if (!responseId) {\n return frame;\n }\n const request = this.pendingRequests.get(responseId);\n this.pendingRequests.delete(responseId);\n if (!request) {\n return frame;\n }\n\n const matching = this.transformers.filter(\n (transformer) =>\n methodMatches(transformer.method, request.method) &&\n matchRoutePattern(transformer.compiled, request.path) !== undefined\n );\n if (matching.length === 0) {\n return frame;\n }\n\n let parsed: unknown;\n try {\n parsed = body ? JSON.parse(body) : undefined;\n } catch {\n return frame; // Non-JSON body: transformers don't apply.\n }\n\n const info = {\n request,\n headers,\n status: parseInt(headers[\"status\"] ?? \"200\", 10) || 200,\n mocked: headers[KOS_MOCKED_HEADER] === \"true\",\n };\n let current = parsed;\n let changed = false;\n for (const transformer of matching) {\n try {\n const result = transformer.transform(current, info);\n if (result !== undefined) {\n current = result;\n changed = true;\n }\n } catch (error: any) {\n KosLog.error(\n `KosMock transformer for ${transformer.method} ${transformer.pattern} threw`,\n error?.message\n );\n }\n }\n if (!changed) {\n return frame;\n }\n return encodeRawFrame(\n { ...headers, [KOS_MOCK_TRANSFORMED_HEADER]: \"true\" },\n JSON.stringify(current)\n );\n }\n\n private readonly playbacks = new Set<KosMockPlaybackHandle>();\n\n observe(observer: KosMockObserver): () => void {\n this.observers.add(observer);\n return () => this.observers.delete(observer);\n }\n\n /**\n * Transport-integration tap: every outbound frame passes through here\n * (recorder + observers), independent of the enabled flag. Internal.\n */\n noteOutboundFrame(\n data: string | ArrayBufferLike | Blob | ArrayBufferView\n ): void {\n this.recorder.noteOutbound(data);\n const hasRequestObservers = [...this.observers].some(\n (observer) => observer.onRequest\n );\n if (!hasRequestObservers && this.transformers.length === 0) {\n return;\n }\n const frame = decodeRequestFrame(data);\n if (!frame) {\n return;\n }\n const { path, query } = splitUrl(frame.url);\n const observation = {\n method: frame.method,\n url: frame.url,\n path,\n query,\n requestId: frame.requestId,\n tracker: frame.tracker,\n rawBody: frame.rawBody,\n };\n if (this.transformers.length > 0) {\n // Correlation store for transformInboundFrame; capped so unanswered\n // requests can't grow it unbounded.\n if (this.pendingRequests.size >= PENDING_REQUEST_CAP) {\n const oldest = this.pendingRequests.keys().next().value;\n if (oldest !== undefined) {\n this.pendingRequests.delete(oldest);\n }\n }\n this.pendingRequests.set(frame.requestId, observation);\n }\n if (hasRequestObservers) {\n this.observers.forEach((observer) =>\n this.notifyObserver(() => observer.onRequest?.(observation))\n );\n }\n }\n\n /**\n * Transport-integration tap: every inbound frame (real, mocked, injected)\n * passes through here. Internal.\n */\n noteInboundFrame(frame: string): void {\n this.recorder.noteInbound(frame);\n if (this.observers.size === 0) {\n return;\n }\n let headers: Record<string, string>;\n let body: string;\n try {\n ({ headers, body } = processKosMessage(frame));\n } catch {\n return;\n }\n\n const responseId = headers[\"response-id\"];\n if (responseId) {\n const observation = {\n requestId: responseId,\n status: parseInt(headers[\"status\"] ?? \"200\", 10) || 200,\n mocked: headers[KOS_MOCKED_HEADER] === \"true\",\n fixture: headers[KOS_MOCK_FIXTURE_HEADER],\n body: body ?? \"\",\n headers,\n };\n this.observers.forEach((observer) =>\n this.notifyObserver(() => observer.onResponse?.(observation))\n );\n return;\n }\n\n const topic = headers[\"subscription\"] || headers[\"topic\"];\n if (topic) {\n const observation = { topic, body: body ?? \"\", headers };\n this.observers.forEach((observer) =>\n this.notifyObserver(() => observer.onTopic?.(observation))\n );\n return;\n }\n\n if (headers[\"type\"] === KOS_FUTURE_TYPE) {\n let future: unknown;\n try {\n future = JSON.parse(body);\n } catch {\n return;\n }\n this.observers.forEach((observer) =>\n this.notifyObserver(() => observer.onFuture?.(future as never))\n );\n }\n }\n\n /** An observer throwing must never disturb transport flow. */\n private notifyObserver(notify: () => void): void {\n try {\n notify();\n } catch (error: any) {\n KosLog.error(`KosMock observer threw`, error?.message);\n }\n }\n\n loadFixture(\n fixture: KosMockFixture,\n options?: KosMockPlaybackOptions\n ): KosMockPlaybackHandle {\n const inner = installFixturePlayback(this, fixture, options);\n const handle: KosMockPlaybackHandle = {\n name: inner.name,\n startPushes: inner.startPushes,\n stop: () => {\n this.playbacks.delete(handle);\n inner.stop();\n },\n };\n this.playbacks.add(handle);\n return handle;\n }\n\n // -- activation ------------------------------------------------------------\n\n get enabled(): boolean {\n return this.enabledFlag;\n }\n\n enable(): void {\n if (!this.enabledFlag) {\n this.enabledFlag = true;\n KosLog.info(`KosMock enabled`);\n }\n }\n\n disable(): void {\n if (this.enabledFlag) {\n this.enabledFlag = false;\n KosLog.info(`KosMock disabled`);\n }\n }\n\n get standalone(): boolean {\n return !!this.settings.standalone;\n }\n\n /** Internal: whether the standalone socket self-authorizes on open. */\n get authorizeOnOpen(): boolean {\n return this.settings.authorize !== false;\n }\n\n configure(config: KosMockConfig): void {\n this.settings = { ...this.settings, ...config };\n if (config.standalone) {\n this.enable();\n }\n }\n\n // -- routes ----------------------------------------------------------------\n\n route(\n method: KosMockMethod,\n pattern: string,\n handler: KosMockRouteHandler | KosMockResponse,\n options: KosMockRouteOptions = {}\n ): KosMockHandle {\n const registered: RegisteredRoute = {\n id: options.id ?? uuid(),\n method,\n pattern,\n compiled: compileRoutePattern(pattern),\n handler: asHandler(handler),\n description: options.description,\n once: !!options.once,\n enabled: options.enabled !== false,\n delayMs: options.delayMs,\n fixture: options.fixture,\n when: options.when,\n hitCount: 0,\n };\n this.routes.push(registered);\n // Registering a mock is the intent to use it.\n this.enable();\n return {\n id: registered.id,\n remove: () => this.removeRoute(registered.id),\n enable: () => this.setRouteEnabled(registered.id, true),\n disable: () => this.setRouteEnabled(registered.id, false),\n };\n }\n\n get(\n pattern: string,\n handler: KosMockRouteHandler | KosMockResponse,\n options?: KosMockRouteOptions\n ): KosMockHandle {\n return this.route(\"GET\", pattern, handler, options);\n }\n\n post(\n pattern: string,\n handler: KosMockRouteHandler | KosMockResponse,\n options?: KosMockRouteOptions\n ): KosMockHandle {\n return this.route(\"POST\", pattern, handler, options);\n }\n\n put(\n pattern: string,\n handler: KosMockRouteHandler | KosMockResponse,\n options?: KosMockRouteOptions\n ): KosMockHandle {\n return this.route(\"PUT\", pattern, handler, options);\n }\n\n del(\n pattern: string,\n handler: KosMockRouteHandler | KosMockResponse,\n options?: KosMockRouteOptions\n ): KosMockHandle {\n return this.route(\"DELETE\", pattern, handler, options);\n }\n\n private removeRoute(id: string): void {\n this.routes = this.routes.filter((route) => route.id !== id);\n }\n\n private setRouteEnabled(id: string, enabled: boolean): void {\n const route = this.routes.find((candidate) => candidate.id === id);\n if (route) {\n route.enabled = enabled;\n }\n }\n\n // -- inbound injection -----------------------------------------------------\n\n /**\n * Transport integrations register how inbound frames reach the receive\n * path. Internal — not part of IKosMockControl.\n */\n registerInjector(inject: (frame: string) => void): () => void {\n this.injectors.add(inject);\n return () => this.injectors.delete(inject);\n }\n\n publishTopic(\n topic: string,\n body: unknown,\n headers?: Record<string, string>\n ): void {\n this.publishFrame(encodeTopicFrame(topic, body, headers));\n }\n\n publishFrame(rawFrame: string): void {\n if (this.injectors.size === 0) {\n KosLog.warn(\n `KosMock.publishFrame: no active transport to deliver the frame`\n );\n return;\n }\n this.injectors.forEach((inject) => inject(rawFrame));\n }\n\n topicEmitter(\n topic: string,\n options: { intervalMs: number; body: (tick: number) => unknown }\n ): KosMockHandle {\n const id = uuid();\n let tick = 0;\n const start = () => {\n const timer = setInterval(() => {\n this.publishTopic(topic, options.body(tick));\n tick += 1;\n }, options.intervalMs);\n this.emitters.set(id, timer);\n };\n const stop = () => {\n const timer = this.emitters.get(id);\n if (timer !== undefined) {\n clearInterval(timer);\n this.emitters.delete(id);\n }\n };\n start();\n return {\n id,\n remove: stop,\n enable: () => {\n if (!this.emitters.has(id)) {\n start();\n }\n },\n disable: stop,\n };\n }\n\n // -- scenarios ---------------------------------------------------------------\n\n scenario(scenario: KosMockScenario): KosMockHandle {\n const id = `scenario:${scenario.name}:${uuid()}`;\n const teardown = scenario.setup(this);\n if (teardown) {\n this.scenarioTeardowns.set(id, teardown);\n }\n KosLog.info(`KosMock scenario \"${scenario.name}\" installed`);\n const remove = () => {\n const dispose = this.scenarioTeardowns.get(id);\n this.scenarioTeardowns.delete(id);\n dispose?.();\n };\n return { id, remove, enable: () => undefined, disable: remove };\n }\n\n // -- introspection -----------------------------------------------------------\n\n list(): KosMockRouteInfo[] {\n return this.routes.map((route) => {\n return {\n id: route.id,\n method: route.method,\n pattern: route.pattern,\n description: route.description,\n enabled: route.enabled,\n hitCount: route.hitCount,\n };\n });\n }\n\n describe() {\n return {\n enabled: this.enabled,\n standalone: this.standalone,\n routes: this.list(),\n transformers: this.transformers.map((transformer) => {\n return {\n id: transformer.id,\n method: transformer.method,\n pattern: transformer.pattern,\n description: transformer.description,\n };\n }),\n setups: this.setups.active().map((setup) => {\n return { name: setup.name, url: setup.url };\n }),\n activeFutures: this.futures.active.map((future) => future.id),\n subscribedTopics: this.subscribedTopics,\n };\n }\n\n get subscribedTopics(): string[] {\n return [...this.subscribedTopicSet];\n }\n\n clear(): void {\n this.setups.clear();\n [...this.playbacks].forEach((playback) => playback.stop());\n this.routes = [];\n this.transformers = [];\n this.pendingRequests.clear();\n this.cancelRoutesRegistered = false;\n this.emitters.forEach((timer) => clearInterval(timer));\n this.emitters.clear();\n this.scenarioTeardowns.forEach((teardown) => teardown());\n this.scenarioTeardowns.clear();\n this.futures.clear();\n this.state.clear();\n this.subscribedTopicSet.clear();\n }\n\n // -- frame handling (internal seam for transport integrations) --------------\n\n /**\n * Inspects an outbound frame. Returns true when the registry takes\n * ownership (it will deliver a response or forward asynchronously); false\n * means the caller sends the frame as usual. Internal — not part of\n * IKosMockControl.\n */\n handleOutboundFrame(\n data: string | ArrayBufferLike | Blob | ArrayBufferView,\n io: KosMockFrameIO\n ): boolean {\n if (!this.enabledFlag) {\n return false;\n }\n\n const subscription = decodeSubscribeTopics(data);\n if (subscription) {\n subscription.topics.forEach((topic) => {\n if (subscription.type === \"subscribe\") {\n this.subscribedTopicSet.add(topic);\n } else {\n this.subscribedTopicSet.delete(topic);\n }\n });\n return false;\n }\n\n const frame = decodeRequestFrame(data);\n if (!frame) {\n return false;\n }\n\n const { path, query } = splitUrl(frame.url);\n const candidates = this.routes\n .map((route) => {\n return {\n route,\n params:\n route.enabled && methodMatches(route.method, frame.method)\n ? matchRoutePattern(route.compiled, path)\n : undefined,\n };\n })\n .filter(\n (\n candidate\n ): candidate is typeof candidate & {\n params: Record<string, string>;\n } => candidate.params !== undefined\n );\n\n const policy = this.unmatchedPolicy();\n if (candidates.length === 0) {\n if (policy === \"respond404\") {\n this.deliverResponse(io, frame.requestId, {\n status: 404,\n data: { message: `KosMock: no route for ${frame.method} ${path}` },\n });\n return true;\n }\n if (policy === \"warn\") {\n KosLog.warn(`KosMock: unmatched ${frame.method} ${path}`);\n }\n return false;\n }\n\n const request: Omit<KosMockRequest, \"params\"> = {\n method: frame.method,\n url: frame.url,\n path,\n query,\n headers: frame.headers,\n requestId: frame.requestId,\n tracker: frame.tracker,\n ordered: frame.ordered,\n rawBody: frame.rawBody,\n json: <T>() => {\n if (!frame.rawBody) {\n return undefined;\n }\n try {\n return JSON.parse(frame.rawBody) as T;\n } catch {\n return undefined;\n }\n },\n };\n\n void this.resolve(request, candidates, io, policy);\n return true;\n }\n\n private async resolve(\n request: Omit<KosMockRequest, \"params\">,\n candidates: Array<{\n route: RegisteredRoute;\n params: Record<string, string>;\n }>,\n io: KosMockFrameIO,\n policy: \"passthrough\" | \"respond404\" | \"warn\"\n ): Promise<void> {\n for (const { route, params } of candidates) {\n const scopedRequest = { ...request, params };\n if (route.when) {\n let accepted = false;\n try {\n accepted = route.when(scopedRequest);\n } catch (error: any) {\n KosLog.error(\n `KosMock \\`when\\` guard for ${route.method} ${route.pattern} threw`,\n error?.message\n );\n }\n if (!accepted) {\n continue;\n }\n }\n let response: KosMockResponse | undefined;\n try {\n response = await route.handler(scopedRequest, this.context());\n } catch (error: any) {\n KosLog.error(\n `KosMock handler for ${route.method} ${route.pattern} threw`,\n error?.message\n );\n response = {\n status: 500,\n data: { message: `KosMock handler error: ${error?.message}` },\n };\n }\n if (!response) {\n continue;\n }\n const delayMs =\n response.delayMs ?? route.delayMs ?? this.settings.defaultDelayMs;\n if (delayMs) {\n await sleep(delayMs);\n }\n route.hitCount += 1;\n if (route.once) {\n this.removeRoute(route.id);\n }\n this.deliverResponse(io, request.requestId, response, route);\n return;\n }\n\n // Every candidate declined.\n if (policy === \"respond404\") {\n this.deliverResponse(io, request.requestId, {\n status: 404,\n data: {\n message: `KosMock: all routes declined ${request.method} ${request.path}`,\n },\n });\n return;\n }\n if (policy === \"warn\") {\n KosLog.warn(\n `KosMock: all routes declined ${request.method} ${request.path}`\n );\n }\n io.forward();\n }\n\n /**\n * Every mock-origin response is stamped `kos-mocked: true` (plus\n * `kos-mock-fixture` when the route belongs to a fixture) so mocked traffic\n * is detectable in devtools and on the fetch response headers.\n */\n private deliverResponse(\n io: KosMockFrameIO,\n requestId: string,\n response: KosMockResponse,\n route?: RegisteredRoute\n ): void {\n io.deliver(\n encodeHttpResponseFrame({\n requestId,\n status: response.status,\n data: response.data,\n raw: response.raw,\n headers: {\n [KOS_MOCKED_HEADER]: \"true\",\n ...(route?.fixture\n ? { [KOS_MOCK_FIXTURE_HEADER]: route.fixture }\n : {}),\n ...response.headers,\n },\n })\n );\n }\n\n private context() {\n return {\n state: this.state,\n futures: this.futures,\n publishTopic: (\n topic: string,\n body: unknown,\n headers?: Record<string, string>\n ) => this.publishTopic(topic, body, headers),\n };\n }\n\n private unmatchedPolicy(): \"passthrough\" | \"respond404\" | \"warn\" {\n return (\n this.settings.onUnmatched ??\n (this.standalone ? \"respond404\" : \"passthrough\")\n );\n }\n\n /**\n * Shared cancel routes for simulated futures. They decline unknown ids, so\n * in hybrid mode cancellation of real futures still reaches the device.\n */\n private ensureFutureCancelRoutes(): void {\n if (this.cancelRoutesRegistered) {\n return;\n }\n this.cancelRoutesRegistered = true;\n const cancelHandler: KosMockRouteHandler = (req) => {\n const future = this.futures.get(req.params.id);\n if (!future || future.done) {\n return undefined;\n }\n future.cancel();\n return { data: {} };\n };\n this.route(\"POST\", \"/api/kos/future/:id/cancel\", cancelHandler, {\n id: \"kos-mock-future-cancel\",\n description: \"KosMock simulated future cancel\",\n });\n this.route(\"DELETE\", \"/api/kos/future/:id\", cancelHandler, {\n id: \"kos-mock-future-delete\",\n description: \"KosMock simulated future delete\",\n });\n }\n}\n\nconst resolveSingleton = (): KosMockRegistry => {\n if (typeof window !== \"undefined\") {\n const existing = (window as any).KosMock;\n if (existing instanceof KosMockRegistry) {\n return existing;\n }\n const registry = new KosMockRegistry();\n (window as any).KosMock = registry;\n return registry;\n }\n return new KosMockRegistry();\n};\n\n/**\n * The singleton typed as the concrete registry — internal seam for the\n * transport interceptor and the standalone socket, which need\n * `handleOutboundFrame`/`registerInjector`.\n */\nexport const kosMockRegistry: KosMockRegistry = resolveSingleton();\n\n/**\n * The KosMock singleton — also exposed as `window.KosMock` for runtime\n * (agent/Studio/devtools) control.\n *\n * @kosService core.mock\n * @kosApiLevel 24\n */\nexport const KosMock: IKosMockControl = kosMockRegistry;\n\n// Startup activation, from a query param or a KOS profile. The query param\n// mirrors the `?host=`/`?alias=` convention; the profile form covers hosts\n// that own the URL (the SWT window), where `globalThis.getKosConfig` is the\n// only channel available. A query param wins over a profile.\n//\n// `?kosMock=standalone` / `studio.mock.standalone` boots against the loopback\n// socket; `?kosMock=on` / `studio.mock` merely arms the interceptor for hybrid\n// mocking. `?kosRecord` / `studio.mock.record` (optionally `=<name>`) starts\n// the recorder at module init — before the transport exists — so a capture\n// includes the boot exchanges (assemblies, availability, ...) that offline\n// playback needs; starting from the dev console after boot would miss them.\nconst PROFILE_MOCK = \"studio.mock\";\nconst PROFILE_MOCK_STANDALONE = \"studio.mock.standalone\";\nconst PROFILE_MOCK_RECORD = \"studio.mock.record\";\nconst PROFILE_MOCK_FIXTURE_SERVER = \"studio.mock.fixtureServer\";\nconst PROFILE_MOCK_FIXTURE = \"studio.mock.fixture\";\nconst PROFILE_MOCK_SETUP = \"studio.mock.setup\";\n\n/**\n * A profile carries its value the way the query param does: bare for a flag,\n * `name=value` when it needs one. Returns undefined when absent, \"\" when bare.\n */\nconst profileValue = (name: string): string | undefined => {\n const match = resolveKosProfiles().find(\n (profile) => profile === name || profile.startsWith(`${name}=`)\n );\n return match === undefined ? undefined : match.slice(name.length + 1);\n};\n\nif (typeof window !== \"undefined\") {\n const params = (window.location?.search ? getQueryParams() : {}) as Record<\n string,\n string | undefined\n >;\n\n const setting = (param: string, profile: string): string | undefined =>\n params[param] !== undefined ? params[param] : profileValue(profile);\n\n const mock =\n params[\"kosMock\"] !== undefined\n ? params[\"kosMock\"]\n : hasKosProfile(PROFILE_MOCK_STANDALONE)\n ? \"standalone\"\n : hasKosProfile(PROFILE_MOCK)\n ? \"on\"\n : undefined;\n const record = setting(\"kosRecord\", PROFILE_MOCK_RECORD);\n const fixtureServer = setting(\n \"kosFixtureServer\",\n PROFILE_MOCK_FIXTURE_SERVER\n );\n const fixture = setting(\"kosFixture\", PROFILE_MOCK_FIXTURE);\n const setups = setting(\"kosSetup\", PROFILE_MOCK_SETUP);\n\n if (mock === \"standalone\") {\n KosMock.configure({ standalone: true });\n } else if (mock === \"on\") {\n KosMock.enable();\n }\n if (record !== undefined) {\n KosMock.recorder.start({ name: record || undefined });\n }\n // `?kosFixtureServer` (bare = default URL) connects the out-of-band fixture\n // library; `?kosFixture=<name>` plays a fixture at boot and\n // `?kosSetup=<a,b>` installs setup modules — the standalone socket holds\n // its open until everything named here is in place.\n if (fixtureServer !== undefined) {\n KosMock.fixtures.useServer(fixtureServer || true);\n }\n const bootLoads: Promise<void>[] = [];\n if (fixture) {\n bootLoads.push(\n KosMock.fixtures\n .play(fixture)\n .then(() => undefined)\n .catch((error: any) =>\n KosLog.error(\n `KosMock: boot fixture \"${fixture}\" failed to load`,\n error?.message\n )\n )\n );\n }\n if (setups) {\n for (const name of setups.split(\",\").filter(Boolean)) {\n bootLoads.push(\n KosMock.setups\n .load(name)\n .then(() => undefined)\n .catch((error: any) =>\n KosLog.error(\n `KosMock: boot setup \"${name}\" failed to load`,\n error?.message\n )\n )\n );\n }\n }\n if (bootLoads.length > 0) {\n kosMockRegistry.bootGate = Promise.all(bootLoads).then(() => undefined);\n }\n}\n","// The always-present interception layer. BaseTransport wraps its raw socket\n// with installMockInterceptor at construction; the wrapper is inert until the\n// KosMock registry is enabled, then answers matched requests locally and lets\n// everything else through — which is what makes hybrid mocking against a live\n// device possible.\n//\n// Two wiring constraints this wrapper exists to satisfy:\n// - Both send paths (BaseTransport.send AND direct socket.socket.send calls\n// from subscription/offline-queue code) bottom out on the raw Transport's\n// send, so wrapping the raw Transport catches everything.\n// - BaseTransport.onOpen reassigns `this.socket = event.currentTarget`, so\n// open events must be re-fired with the wrapper as currentTarget or the\n// wrapper would be silently dropped after the first open.\nimport type { Transport } from \"../transport\";\nimport { KosMockRegistry, kosMockRegistry } from \"./mock-registry\";\n\nclass MockInterceptorTransport implements Transport {\n private messageHandler: ((ev: MessageEvent) => any) | null = null;\n private openHandler: ((ev: Event) => any) | null = null;\n private closeHandler: ((ev: CloseEvent) => any) | null = null;\n private errorHandler: ((ev: Event) => any) | null = null;\n private readonly unregisterInjector: () => void;\n\n constructor(\n private readonly inner: Transport,\n private readonly registry: KosMockRegistry\n ) {\n this.unregisterInjector = registry.registerInjector((frame) =>\n this.deliver(frame)\n );\n inner.onmessage = (ev) => {\n // Frames from the real socket run the transformer chain (in-flight\n // response patching), then deliver, then observe. deliver() applies\n // the same sequence to injected and mocked frames.\n if (typeof ev.data === \"string\") {\n this.deliver(ev.data);\n } else {\n this.messageHandler?.(ev);\n }\n };\n inner.onopen = () => {\n // Re-fire with the wrapper as currentTarget (see header comment).\n const ev = { currentTarget: this } as unknown as Event;\n this.openHandler?.(ev);\n };\n inner.onclose = (ev) => {\n this.unregisterInjector();\n this.closeHandler?.(ev);\n };\n inner.onerror = (ev) => this.errorHandler?.(ev);\n }\n\n /**\n * Every inbound frame's path to the app: transform → deliver → observe.\n * Observation runs last so a reacting observer's injections land AFTER the\n * frame that caused them, as a real backend's consequences would; observers\n * and the recorder see the transformed frame — what the app saw.\n */\n private deliver(frame: string): void {\n const transformed = this.registry.transformInboundFrame(frame);\n this.messageHandler?.({ data: transformed } as MessageEvent);\n this.registry.noteInboundFrame(transformed);\n }\n\n get onmessage() {\n return this.messageHandler;\n }\n set onmessage(handler: ((ev: MessageEvent) => any) | null) {\n this.messageHandler = handler;\n }\n\n get onopen() {\n return this.openHandler;\n }\n set onopen(handler: ((ev: Event) => any) | null) {\n this.openHandler = handler;\n }\n\n get onclose() {\n return this.closeHandler;\n }\n set onclose(handler: ((ev: CloseEvent) => any) | null) {\n this.closeHandler = handler;\n }\n\n get onerror() {\n return this.errorHandler;\n }\n set onerror(handler: ((ev: Event) => any) | null) {\n this.errorHandler = handler;\n }\n\n send(data: string | ArrayBufferLike | Blob | ArrayBufferView): void {\n this.registry.noteOutboundFrame(data);\n const owned = this.registry.handleOutboundFrame(data, {\n deliver: (frame) => this.deliver(frame),\n forward: () => this.inner.send(data),\n });\n if (!owned) {\n this.inner.send(data);\n }\n }\n\n close(): void {\n this.unregisterInjector();\n return this.inner.close();\n }\n\n addEventListener(\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | AddEventListenerOptions\n ): void {\n this.inner.addEventListener(type, listener, options);\n }\n\n removeEventListener(\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | EventListenerOptions\n ): void {\n this.inner.removeEventListener(type, listener, options);\n }\n\n dispatchEvent(event: Event): boolean {\n return this.inner.dispatchEvent(event);\n }\n}\n\n/** Wraps a raw transport with the KosMock interception layer. */\nexport function installMockInterceptor(\n inner: Transport,\n registry: KosMockRegistry = kosMockRegistry\n): Transport {\n return new MockInterceptorTransport(inner, registry);\n}\n","import type { Transport } from \"./transport\";\n\nexport class WebSocketBridgeTransport extends WebSocket implements Transport {\n constructor(address: string) {\n super(address);\n }\n}\n","import { makeObservable, observable, runInAction } from \"mobx\";\nimport { EventBus, KosWsEvents } from \"../../../common\";\nimport { KosLog } from \"../log\";\nimport { installMockInterceptor } from \"./mock/mock-interceptor\";\nimport { Transport } from \"./transport\";\nimport { WebSocketBridgeTransport } from \"./web-socket-transport-adapter\";\n\nexport enum WebSocketEvents {\n CONNECTED = `websocket.connected`,\n DISCONNECTED = `websocket.disconnected`,\n ERROR = `websocket.error`,\n MAX_RETRIES_EXCEEDED = `websocket.max_retries_exceeded`,\n RELOAD = `websocket.reload`,\n}\nexport interface TransportParams {\n host: string;\n port: number;\n protocol: string;\n alias?: string;\n onConnectionEstablished?: () => void;\n onConnectionLost?: () => void;\n Transport?: new (url: string) => Transport;\n}\nexport interface MessageTransport {\n socket: Transport;\n send: (data: string | ArrayBufferLike | Blob | ArrayBufferView) => void;\n connectionEstablished: boolean;\n addOfflineMessage: (msg: string) => void;\n}\n\nexport interface KosInternalEvent {\n headers: Record<string | `topic` | `http-request-id`, string>;\n body: string;\n}\n\ninterface OfflineMessage {\n msg: string;\n fos?: boolean;\n}\n\nexport function processKosMessage(data: string): KosInternalEvent {\n const MESSAGE_SEPARATOR = `\\n\\n`;\n const SEPARATOR = `\\n`;\n const HEADER_SEPARATOR = /:(.*)/s;\n\n const [headerText, body] = data\n .split(MESSAGE_SEPARATOR)\n .map((line: string) => line.trim());\n const headers = headerText\n .split(SEPARATOR)\n .reduce((acc: any, curr: string) => {\n const [header, value] = curr\n .split(HEADER_SEPARATOR)\n .map((raw: string) => raw.trim());\n if (header && value) {\n acc[header] = value;\n }\n return acc;\n }, {});\n\n return {\n headers,\n body: body,\n };\n}\nexport function processKosSnifferMessage(data: string): KosInternalEvent {\n const MESSAGE_SEPARATOR = `\\n\\n`;\n const SEPARATOR = `\\n`;\n const HEADER_SEPARATOR = /:(.*)/s;\n\n const [, headerText, body] = data\n .split(MESSAGE_SEPARATOR)\n .map((line: string) => line.trim());\n const headers = headerText\n .split(SEPARATOR)\n .reduce((acc: any, curr: string) => {\n const [header, value] = curr\n .split(HEADER_SEPARATOR)\n .map((raw: string) => raw.trim());\n if (header && value) {\n acc[header] = value;\n }\n return acc;\n }, {});\n\n return {\n headers,\n body: body,\n };\n}\n\nexport abstract class BaseTransport implements MessageTransport {\n protected host: string;\n protected port: number;\n protected protocol: string;\n public socket: Transport;\n public connectionEstablished: boolean;\n private alias?: string;\n private onConnectionEstablished?: () => void;\n private onConnectionLost?: () => void;\n protected offlineMessages: OfflineMessage[] = [];\n protected abstract RESPONSE_ID_HEADER: string;\n private oldSend: (\n data: string | ArrayBufferLike | Blob | ArrayBufferView\n ) => void;\n\n constructor({\n host,\n port,\n protocol,\n alias,\n onConnectionEstablished,\n onConnectionLost,\n Transport = WebSocketBridgeTransport,\n }: TransportParams) {\n this.host = host;\n this.port = port;\n this.protocol = protocol;\n this.onConnectionEstablished = onConnectionEstablished;\n this.onConnectionLost = onConnectionLost;\n this.alias = alias;\n // The KosMock interception layer wraps every raw transport; it is inert\n // until the registry is enabled.\n this.socket = installMockInterceptor(\n new Transport(`${this.protocol}${this.host}:${this.port}/events`)\n );\n this.socket.onmessage = this.onMessage.bind(this);\n this.socket.onopen = this.onOpen.bind(this);\n this.socket.onclose = this.onClose.bind(this);\n this.socket.onerror = this.onError.bind(this);\n this.oldSend = this.socket.send;\n this.connectionEstablished = false;\n\n makeObservable(this, {\n connectionEstablished: observable,\n });\n }\n\n addOfflineMessage(msg: string) {\n this.offlineMessages.push({ msg });\n }\n processMessageEvent(msg: MessageEvent): KosInternalEvent {\n const { data } = msg;\n return processKosMessage(data);\n }\n\n onMessage(event: Event) {\n try {\n // parsing the message payload\n KosLog.debug(\"webSocketTransport: onMessage received\");\n\n const { headers, body } = this.processMessageEvent(event as MessageEvent);\n KosLog.wsReceive((event as MessageEvent).data);\n const subscriptionTopic =\n headers[\"subscription\"] ||\n headers[this.RESPONSE_ID_HEADER] ||\n headers[\"topic\"] ||\n headers[\"type\"];\n if (subscriptionTopic) {\n let msgBody = body;\n let msgHeaders = headers;\n\n if (subscriptionTopic === \"kos.sniffer.msg\") {\n const { headers: snifferHeaders, body: snifferBody } =\n processKosSnifferMessage((event as MessageEvent).data);\n msgBody = snifferBody;\n msgHeaders = {\n ...headers,\n ...snifferHeaders,\n };\n }\n\n EventBus.publish(subscriptionTopic, msgBody, msgHeaders);\n }\n } catch (ex: any) {\n KosLog.error(`onMessage exception`, ex.message, ex.stack);\n }\n }\n\n onOpen(event: Event) {\n KosLog.info(`websocket connection opened`);\n\n this.socket = event.currentTarget as Transport;\n runInAction(() => {\n this.connectionEstablished = true;\n if (this.alias) {\n this.socket.send(`type:kos.addr.alias\\nalias:${this.alias}\\n\\n`);\n }\n KosLog.debug(\n `sending ${this.offlineMessages.length} offline FOS messages`\n );\n this.offlineMessages.forEach((msg) => {\n KosLog.debug(`sending offline message ${msg.msg}`);\n this.socket?.send(msg.msg);\n });\n\n this.offlineMessages = [];\n this.onConnectionEstablished?.();\n });\n }\n\n onClose(event: CloseEvent) {\n const { code, reason, wasClean } = event;\n KosLog.warn(\n `WebSocket closed: code=${code}, reason=${\n reason || \"none\"\n }, wasClean=${wasClean}`\n );\n\n runInAction(() => {\n this.connectionEstablished = false;\n });\n\n // Publish disconnection event with details\n EventBus.publish(WebSocketEvents.DISCONNECTED, { code, reason, wasClean });\n\n if (this.shouldAttemptReconnection(code)) {\n this.onConnectionLost?.();\n } else {\n KosLog.info(\n `Not reconnecting due to close code ${code} (intentional close or configuration error)`\n );\n }\n }\n\n onError(ev: Event) {\n KosLog.error(`websocket error: `, ev);\n\n // Publish error event for application awareness\n // Note: onerror is typically followed by onclose, but this allows\n // faster detection of connection issues\n EventBus.publish(WebSocketEvents.ERROR, { event: ev });\n }\n\n /**\n * Determines whether to attempt reconnection based on WebSocket close code.\n * @param code - The WebSocket close code\n * @returns true if reconnection should be attempted\n */\n private shouldAttemptReconnection(code: number): boolean {\n // Close codes reference: https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent/code\n switch (code) {\n case 1000: // Normal closure - server-initiated on loopback is still an outage, reconnect\n return true;\n case 1001: // Going away - server shutting down, reconnect with backoff\n return true;\n case 1002: // Protocol error - likely a bug, don't reconnect\n return false;\n case 1003: // Unsupported data - likely a bug, don't reconnect\n return false;\n case 1005: // No status received - abnormal, try to reconnect\n return true;\n case 1006: // Abnormal closure - connection dropped, reconnect\n return true;\n case 1007: // Invalid frame payload - likely a bug, don't reconnect\n return false;\n case 1008: // Policy violation - don't reconnect\n return false;\n case 1009: // Message too big - configuration issue, don't reconnect\n return false;\n case 1010: // Mandatory extension - negotiation failed, don't reconnect\n return false;\n case 1011: // Internal server error - temporary, reconnect with backoff\n return true;\n case 1012: // Service restart - reconnect with backoff\n return true;\n case 1013: // Try again later - reconnect with backoff\n return true;\n case 1014: // Bad gateway - reconnect with backoff\n return true;\n case 1015: // TLS handshake failure - configuration issue, don't reconnect\n return false;\n default:\n // For unknown codes, attempt reconnection\n return true;\n }\n }\n\n send(data: string | ArrayBufferLike | Blob | ArrayBufferView) {\n KosLog.wsSend(data);\n if (window.kosLogEvents) {\n const { headers, body } = processKosMessage(String(data));\n EventBus.publish(KosWsEvents.SEND, { headers, body });\n }\n this.oldSend.call(this.socket, data);\n }\n}\n","import log from \"loglevel\";\nimport type { Transport } from \"./transport\";\n\ntype MessageType = string | ArrayBufferLike | Blob | ArrayBufferView;\nexport class BridgeTransport implements Transport {\n addEventListener!: () => any;\n dispatchEvent!: () => any;\n removeEventListener!: () => any;\n private _onclose!: ((ev: CloseEvent) => any) | null;\n private _onerror!: ((ev: Event) => any) | null;\n private _onmessage!: ((ev: MessageEvent) => any) | null;\n private _onopen!: ((ev: Event) => any) | null;\n private messageQueue: MessageType[] = [];\n private isSending = false;\n\n constructor(addr: string) {\n log.debug(`called Bridge Transport with addr ${addr}`);\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const that = this;\n globalThis.kosWindowWebsocketRecv = (msg: string) => {\n if (that.onmessage) {\n const data: MessageEvent = { data: msg } as unknown as MessageEvent;\n that.onmessage(data);\n }\n };\n // initalize the transport\n log.debug(\"Opening bridge transport\");\n globalThis.kosWindowWebsocketOpen();\n log.debug(\"Opened bridge transport\");\n\n this._onclose = null;\n this._onerror = null;\n this._onmessage = null;\n this._onopen = null;\n this.addEventListener = () => log.debug(\"not implemented\");\n this.dispatchEvent = () => log.debug(\"not implemented\");\n this.removeEventListener = () => log.debug(\"not implemented\");\n }\n\n close() {\n log.debug(\"closing\");\n }\n\n private sendNextMessage() {\n if (this.messageQueue.length > 0) {\n const message = this.messageQueue.shift();\n globalThis.kosWindowWebsocketSend(message);\n setTimeout(() => this.sendNextMessage(), 1);\n } else {\n this.isSending = false;\n }\n }\n enqueueMessage(message: MessageType) {\n this.messageQueue.push(message);\n if (!this.isSending) {\n this.isSending = true;\n this.sendNextMessage();\n }\n }\n send(data: string | ArrayBufferLike | Blob | ArrayBufferView) {\n globalThis.kosWindowWebsocketSend(data);\n }\n\n get onmessage() {\n return this._onmessage;\n }\n set onmessage(fn: ((ev: MessageEvent) => any) | null) {\n this._onmessage = fn;\n }\n\n get onopen() {\n return this._onopen;\n }\n set onopen(fn: ((ev: Event) => any) | null) {\n this._onopen = fn;\n }\n\n get onclose() {\n return this._onclose;\n }\n set onclose(fn: ((ev: CloseEvent) => any) | null) {\n this._onclose = fn;\n }\n\n get onerror() {\n return this._onerror;\n }\n set onerror(fn: ((ev: Event) => any) | null) {\n this._onerror = fn;\n }\n}\n","import { BaseTransport, TransportParams } from \"./base-message-transport\";\nimport { BridgeTransport } from \"./bridge-transport\";\n\nexport class BridgeMessageTransport extends BaseTransport {\n protected RESPONSE_ID_HEADER: string;\n constructor({ host, port, alias }: TransportParams) {\n super({\n host,\n port,\n Transport: BridgeTransport,\n alias,\n protocol: \"kos://\",\n });\n this.RESPONSE_ID_HEADER = `response-id`;\n }\n}\n","import { BaseTransport, TransportParams } from \"./base-message-transport\";\n\nexport class FosTransport extends BaseTransport {\n protected RESPONSE_ID_HEADER: string;\n constructor({ host, port }: TransportParams) {\n super({ host, port, protocol: `ws://` });\n this.RESPONSE_ID_HEADER = `requestId`;\n }\n}\n","import { BaseTransport, TransportParams } from \"./base-message-transport\";\n\nexport class KosTransport extends BaseTransport {\n protected RESPONSE_ID_HEADER: string;\n constructor({\n host,\n port,\n protocol,\n onConnectionEstablished,\n onConnectionLost,\n alias,\n }: TransportParams) {\n super({\n host,\n port,\n onConnectionEstablished,\n onConnectionLost,\n alias,\n protocol,\n });\n this.RESPONSE_ID_HEADER = `response-id`;\n }\n}\n","// Fully-offline mode: a loopback Transport that \"opens\" without a server and\n// a BaseTransport flavor that uses it. TransportFactory selects\n// MockMessageTransport when `KosMock.standalone` is set (code or\n// `?kosMock=standalone`), so a demo app boots the complete KosCore lifecycle\n// with zero build flags and zero hardware.\n//\n// The socket itself is nearly inert: request interception already happened in\n// the interceptor wrapper (BaseTransport wraps every raw transport, this one\n// included), and in standalone mode the registry's default onUnmatched policy\n// is \"respond404\", so no request frame should ever reach this sink.\nimport { KosLog } from \"../../log\";\nimport type { Transport } from \"../transport\";\nimport { BaseTransport, TransportParams } from \"../base-message-transport\";\nimport { KOS_HTTP_REQUEST_TYPE, peekFrameType } from \"./mock-frames\";\nimport { kosMockRegistry } from \"./mock-registry\";\n\n/**\n * The frame that authorizes the transport. KosCore subscribes to this topic\n * and flips `transport.authorized`, which `whenReady()` gates on — delivering\n * it through the real receive path means standalone boot needs no\n * KOS_ALLOW_ANONYMOUS build flag. The auth handler's RELOAD side effect is\n * ignored outside the READY lifecycle state, so firing it at boot is safe.\n */\nconst LOGGED_IN_FRAME = `topic:/studioServer/auth/LOGGED_IN\\ntype:kos.broker.topic\\n\\n{}`;\n\nexport class StandaloneMockSocket implements Transport {\n onclose: ((ev: CloseEvent) => any) | null = null;\n onerror: ((ev: Event) => any) | null = null;\n onmessage: ((ev: MessageEvent) => any) | null = null;\n onopen: ((ev: Event) => any) | null = null;\n\n constructor(url: string) {\n KosLog.info(`KosMock standalone socket replacing ${url}`);\n // A macrotask, not a microtask: the open must fire after the surrounding\n // boot code has finished wiring handlers and subscriptions. When a boot\n // fixture is loading (?kosFixture=), also wait for its routes to exist —\n // otherwise the app's boot requests would 404 before the replay installs.\n setTimeout(async () => {\n await kosMockRegistry.bootGate;\n this.onopen?.({ currentTarget: this } as unknown as Event);\n if (kosMockRegistry.authorizeOnOpen) {\n this.onmessage?.({ data: LOGGED_IN_FRAME } as MessageEvent);\n }\n }, 0);\n }\n\n send(data: string | ArrayBufferLike | Blob | ArrayBufferView): void {\n // Broker subscribes and alias frames are expected and swallowed. A\n // request frame arriving here means the unmatched policy was overridden\n // to \"passthrough\" with no real socket behind it — that request will\n // hang, so say so.\n if (peekFrameType(data) === KOS_HTTP_REQUEST_TYPE) {\n KosLog.warn(\n `KosMock standalone: unmatched request reached the loopback socket and will hang — add a route or use onUnmatched: \"respond404\"`,\n String(data).split(\"\\n\", 2).join(\" \")\n );\n }\n }\n\n close(): void {\n // Nothing to close; reconnect logic never engages.\n }\n\n addEventListener(): void {\n // Not used by BaseTransport.\n }\n\n removeEventListener(): void {\n // Not used by BaseTransport.\n }\n\n dispatchEvent(): boolean {\n return true;\n }\n}\n\nexport class MockMessageTransport extends BaseTransport {\n protected RESPONSE_ID_HEADER: string;\n\n constructor({\n host,\n port,\n protocol,\n alias,\n onConnectionEstablished,\n onConnectionLost,\n }: TransportParams) {\n super({\n host,\n port,\n protocol,\n alias,\n onConnectionEstablished,\n onConnectionLost,\n Transport: StandaloneMockSocket,\n });\n this.RESPONSE_ID_HEADER = `response-id`;\n }\n}\n","// eslint-disable-next-line spaced-comment, @typescript-eslint/triple-slash-reference\n/// <reference path=\"../../types/global.d.ts\" />\nimport { KosLog } from \"../log\";\nimport { BridgeMessageTransport } from \"./bridge-message-transport\";\nimport { FosTransport } from \"./fos-message-transport\";\nimport { KosTransport } from \"./kos-message-transport\";\nimport { KosMock } from \"./mock/mock-registry\";\nimport { MockMessageTransport } from \"./mock/standalone-mock-socket\";\n\nwindow.kosLogEvents = process.env.KOS_LOG_WS === \"true\";\n\ninterface FactoryParams {\n host: string;\n port: number;\n protocol: string;\n fos?: boolean;\n alias?: string;\n onConnectionEstablished?: () => void;\n onConnectionLost?: () => void;\n}\n\n/**\n *\n * @description\n * Extend event to get access to the data property.\n */\nexport interface KosInternalEvent {\n headers: Record<string | `topic` | `http-request-id`, string>;\n body: string;\n}\n\nexport class TransportFactory {\n static build({\n host,\n port,\n protocol,\n fos,\n alias,\n onConnectionEstablished,\n onConnectionLost,\n }: FactoryParams) {\n KosLog.debug(`initializing websocket connection`);\n KosLog.warn(\n `kosWindowWebsocketOpen: ${\n globalThis.kosWindowWebsocketOpen ? `true` : `false`\n }`\n );\n KosLog.warn(`fos: ${fos ? `true` : `false`}`);\n if (KosMock.standalone && !fos) {\n KosLog.warn(`Using KosMock standalone transport`);\n return new MockMessageTransport({\n host,\n port,\n protocol,\n alias,\n onConnectionEstablished,\n onConnectionLost,\n });\n }\n if (globalThis.kosWindowWebsocketOpen && !fos) {\n KosLog.warn(`Using bridged message transport`);\n const transport = new BridgeMessageTransport({\n host,\n port,\n protocol,\n onConnectionEstablished,\n onConnectionLost,\n alias,\n });\n return transport;\n }\n if (fos) {\n const transport = new FosTransport({\n host,\n port,\n protocol,\n alias,\n onConnectionEstablished,\n onConnectionLost,\n });\n return transport;\n } else {\n const transport = new KosTransport({\n host,\n port,\n protocol,\n alias,\n onConnectionEstablished,\n onConnectionLost,\n });\n return transport;\n }\n }\n}\n","import Logger from \"loglevel\";\nimport { action, computed, makeObservable, observable, reaction } from \"mobx\";\nimport { EventBus, EventCallback } from \"../../../common\";\n\nimport { abortableWhen } from \"../../util/abortable-when\";\nimport { getQueryParams } from \"../../util/get-query-params\";\nimport { KosLog } from \"../log\";\nimport { MessageTransport, WebSocketEvents } from \"./base-message-transport\";\nimport { TransportFactory } from \"./transport-factory\";\n\nconst params = getQueryParams();\nif ((params as any).fos) {\n window.kosUseFos = true;\n}\nconst fosPort = process.env.KOS_FOS_PORT;\nwindow.kosUseFos = !!(window.kosUseFos || process.env.KOS_USE_FOS === \"true\");\nwindow.kosFosPort = fosPort ? parseInt(fosPort) : 0;\n\nconst log = Logger.getLogger(\"web-socket-transport\");\nexport enum KosWSTransportStatus {\n NOT_INITIALIZED = \"not_initialized\",\n INITIALIZED = \"initialized\",\n OFFLINE = \"OFFLINE\",\n ONLINE = \"ONLINE\",\n}\nexport interface IKosMessage {\n [k: string]: string | number | boolean;\n}\n\nexport interface IKosConnectionStatus {\n status: string;\n message?: string;\n}\n\n/**\n * Options for {@link IKosServiceTransport.whenReady}.\n *\n * @kosService core.transport\n * @kosApiLevel 23\n */\nexport interface KosTransportReadyOptions {\n /**\n * Cancels the readiness wait when it aborts. Without one the wait is\n * indefinite, which is correct for startup/lifecycle code but not for a\n * request working against a deadline.\n *\n * When the signal aborts, `whenReady` rejects with the signal's reason and\n * disposes the underlying reactive waiter.\n */\n signal?: AbortSignal;\n}\n\nexport interface KosSubscriptionParams {\n topic: string;\n callback: EventCallback;\n fos?: boolean;\n bridge?: boolean;\n destinationAddress?: string | null;\n explicitDestination?: boolean;\n}\nexport interface IKosServiceTransport {\n host: string;\n port: number;\n protocol: string;\n token?: string;\n alias?: string;\n connectionEstablished: boolean;\n authorized: boolean;\n socket?: MessageTransport;\n init(): IKosServiceTransport;\n subscribeTopic(params: KosSubscriptionParams): VoidFunction;\n whenReady(options?: KosTransportReadyOptions): Promise<IKosConnectionStatus>;\n fosSocket?: MessageTransport;\n}\n\nexport type KosCallback = (msg: IKosMessage) => void;\n\n// WebSocketEvents is imported from base-message-transport.ts\nexport { WebSocketEvents } from \"./base-message-transport\";\n\ninterface WebSocketTransportParams {\n host?: string;\n port?: number;\n protocol?: string;\n token?: string;\n initialize?: boolean;\n alias?: string;\n fos?: {\n port: number;\n };\n}\n\nexport class WebSocketTransport implements IKosServiceTransport {\n private static _instance: IKosServiceTransport;\n\n host: string;\n\n port: number;\n\n protocol: string;\n\n private _token?: string;\n\n private webSocketSupported = !!globalThis.WebSocket;\n\n authorized: boolean;\n\n alias?: string;\n\n socket?: MessageTransport;\n\n fosSocket?: MessageTransport;\n\n fosPort?: number;\n\n useFosTransport: boolean;\n\n // Reconnection state (persists across BaseTransport re-creation in init())\n private reconnectAttempts = 0;\n private static readonly MAX_RECONNECT_ATTEMPTS = 10;\n private static readonly BASE_DELAY_MS = 1000;\n private static readonly MAX_DELAY_MS = 30000;\n\n constructor({\n host = `localhost`,\n port = 8080,\n protocol = \"ws://\",\n token,\n initialize,\n alias,\n fos,\n }: WebSocketTransportParams) {\n this.host = host;\n this.port = port;\n this.protocol = protocol;\n this._token = token;\n this.alias = alias;\n this.authorized = process.env.KOS_ALLOW_ANONYMOUS === \"true\" ? true : false;\n\n this.useFosTransport = !!fos;\n this.fosPort = fos?.port;\n this.socket = undefined;\n this.fosSocket = undefined;\n\n let initialized = false;\n makeObservable(this, {\n authorized: observable,\n socket: observable,\n fosSocket: observable,\n init: action,\n connectionEstablished: computed,\n });\n\n reaction(\n () => this.connectionEstablished,\n (connectionEstablished) => {\n if (connectionEstablished) {\n log.warn(\"Connection Established\");\n this.reconnectAttempts = 0;\n\n EventBus.publish(\n WebSocketEvents.CONNECTED,\n WebSocketEvents.CONNECTED\n );\n if (initialized) {\n // reload only if the websocket has been initialized once\n EventBus.publish(WebSocketEvents.RELOAD, WebSocketEvents.RELOAD);\n }\n initialized = true;\n }\n }\n );\n\n if (initialize) {\n this.init();\n }\n }\n\n get connectionEstablished() {\n if (!this.webSocketSupported) {\n return false;\n }\n if (!this.socket) {\n return false;\n }\n\n if (this.useFosTransport && !this.fosSocket) {\n return false;\n }\n\n if (this.useFosTransport && this.fosSocket) {\n return (\n this.socket.connectionEstablished &&\n this.fosSocket.connectionEstablished\n );\n }\n if (!this.useFosTransport && this.socket) {\n return this.socket.connectionEstablished;\n }\n return false;\n }\n\n init() {\n KosLog.warn(`Initializing WebSocketTransport on ${this.host}:${this.port}`);\n if (this.useFosTransport) {\n this.fosSocket = TransportFactory.build({\n host: this.host,\n port: this.fosPort || 9854,\n protocol: this.protocol,\n fos: true,\n });\n }\n this.socket = TransportFactory.build({\n host: this.host,\n port: this.port,\n protocol: this.protocol,\n alias: this.alias,\n\n onConnectionLost: () => {\n log.error(`Connection Lost`);\n this.scheduleReconnect();\n },\n });\n\n if (globalThis.kosWindowWebsocketOpen) {\n const ev: Event = {\n currentTarget: this.socket.socket,\n } as unknown as Event;\n this.socket.socket?.onopen?.(ev);\n }\n return this;\n }\n\n /**\n * Schedules a reconnect attempt using exponential backoff with jitter.\n * Counter persists across BaseTransport re-creation, so the cap actually\n * fires after MAX_RECONNECT_ATTEMPTS consecutive failures rather than\n * resetting on every new BaseTransport instance.\n */\n private scheduleReconnect() {\n if (this.reconnectAttempts >= WebSocketTransport.MAX_RECONNECT_ATTEMPTS) {\n KosLog.error(\n `Max reconnection attempts (${WebSocketTransport.MAX_RECONNECT_ATTEMPTS}) reached. Giving up.`\n );\n EventBus.publish(WebSocketEvents.MAX_RETRIES_EXCEEDED, {\n attempts: this.reconnectAttempts,\n });\n return;\n }\n\n const delay = this.calculateBackoffDelay();\n KosLog.debug(\n `Reconnecting in ${delay}ms (attempt ${this.reconnectAttempts + 1}/${\n WebSocketTransport.MAX_RECONNECT_ATTEMPTS\n })`\n );\n\n setTimeout(() => {\n this.reconnectAttempts++;\n this.init();\n }, delay);\n }\n\n private calculateBackoffDelay(): number {\n const exponentialDelay = Math.min(\n WebSocketTransport.BASE_DELAY_MS * Math.pow(2, this.reconnectAttempts),\n WebSocketTransport.MAX_DELAY_MS\n );\n // ±25% jitter to prevent thundering herd on multi-client restarts\n const jitter = exponentialDelay * 0.25 * (Math.random() * 2 - 1);\n return Math.floor(exponentialDelay + jitter);\n }\n\n private _sendSubscriptionMessage(\n topic: string,\n type: \"subscribe\" | \"unsubscribe\",\n fos = false,\n bridge = false,\n connectionId?: string | null,\n explicitDestination = false\n ) {\n log.debug(`${type} to topic ${topic}`);\n let connId: string | null | undefined;\n if (explicitDestination) {\n connId = connectionId;\n } else {\n const params = getQueryParams();\n const connectionParam = (params as any)?.connId;\n connId =\n connectionId ??\n connectionParam ??\n (window as any)?.kosBridge?.(\"connId\");\n }\n log.debug(`subscribing with connId ${connId}`);\n\n const dstAddr = connId ? `dst-addr:${connId}\\n` : \"\";\n const msg = fos\n ? `subscribe:${topic}`\n : bridge\n ? `type:fos.broker\\ncmd:${type}\\n${dstAddr}topics:${topic}\\n`\n : `${dstAddr}type:kos.broker.${type}\\n\\n[\"${topic}\"]`;\n const established = fos\n ? this.fosSocket?.connectionEstablished\n : this.socket?.connectionEstablished;\n if (established) {\n const socket = fos ? this.fosSocket : this.socket;\n socket?.socket?.send(msg);\n } else {\n log.debug(`no connection adding to offline messages`);\n const socket = fos ? this.fosSocket : this.socket;\n socket?.addOfflineMessage(msg);\n }\n }\n\n subscribeTopic({\n topic,\n callback,\n fos,\n bridge,\n destinationAddress,\n explicitDestination,\n }: KosSubscriptionParams) {\n const { unsubscribe, count } = EventBus.subscribe(topic, callback);\n log.debug(`Topic ${topic} currently has ${count} subscribers`);\n this._sendSubscriptionMessage(\n topic,\n \"subscribe\",\n fos,\n bridge,\n destinationAddress,\n explicitDestination\n );\n\n return () => {\n const { count } = unsubscribe();\n log.debug(`Topic ${topic} currently has ${count} subscribers`);\n if (count === 0) {\n this._sendSubscriptionMessage(\n topic,\n \"unsubscribe\",\n fos,\n bridge,\n destinationAddress,\n explicitDestination\n );\n }\n };\n }\n\n /**\n * Resolves once the transport can carry requests: the socket (and the FOS\n * socket, when used) is connected and the connection is authorized.\n *\n * Pass `options.signal` to bound the wait. `connectionEstablished` flips back\n * to `false` on socket close, so an unbounded wait parks indefinitely while\n * the transport is down — callers with a deadline must supply a signal.\n *\n * @param options - See {@link KosTransportReadyOptions}.\n * @throws The signal's abort reason if it aborts before the transport is ready.\n */\n async whenReady(options?: KosTransportReadyOptions) {\n if (!this.webSocketSupported) {\n return {\n status: `not supported`,\n };\n }\n await abortableWhen(\n () =>\n !!this.socket?.connectionEstablished &&\n (!this.useFosTransport || !!this.fosSocket?.connectionEstablished) &&\n this.authorized,\n options?.signal\n );\n return {\n status: `success`,\n };\n }\n\n get token() {\n return this._token!;\n }\n set token(token: string) {\n this._token = token;\n this.init();\n }\n public static host(host = `localhost`) {\n this.getInstance().host = host;\n return this;\n }\n\n public static port(port = 8080) {\n this.getInstance().port = port;\n return this;\n }\n\n public static alias(alias: string) {\n this.getInstance().alias = alias;\n }\n\n public static getInstance(port = 8080, token?: string) {\n if (!this._instance) {\n const fos = window.kosUseFos\n ? { port: window.kosFosPort || 8081 }\n : undefined;\n this._instance = new this({ port, token, fos });\n }\n return this._instance;\n }\n}\n","import { EventBus } from \"../../../common\";\nimport * as AsyncEventBus from \"../../../common/events/async-event-bus\";\nimport { DependencyLifecycle } from \"../../types\";\nimport type { BaselineDependency } from \"../../types/service-response-store\";\nimport { ReplayStrategy } from \"../../types/service-response-store\";\n\nimport { getMessageBody } from \"../../util/kos-message-utils\";\nimport { FlowControlManager } from \"../decorators/kos-topic-handler-flow-control\";\nimport {\n checkWildcardPattern,\n parseWildcardSegment,\n} from \"../decorators/kosTopicHandler\";\nimport { SubscriptionHandlers } from \"../decorators/propKeys\";\nimport { IKosDataModel, IKosModel } from \"../kosModel\";\nimport { KosModelState } from \"../lifecycle\";\nimport { WebSocketTransport } from \"../transport\";\nimport type {\n KosOfflineQueue,\n KosOfflineQueueLogger,\n} from \"./kos-offline-queue\";\nimport type { ServiceResponseStore } from \"./service-response-store\";\n\nexport class KosSubscriptionManager {\n private disposers: VoidFunction[] = [];\n private activatableDisposers: VoidFunction[] = [];\n private flowControllers = new Map<string, FlowControlManager>();\n private baselineDependencies = new Map<string, BaselineDependency>();\n private registeredTopics = new Set<string>();\n private onceTopics = new Set<string>();\n\n constructor(\n private model: IKosModel,\n private modelData: IKosDataModel,\n private modelId: string,\n private offlineQueue: KosOfflineQueue,\n private log: KosOfflineQueueLogger\n ) {}\n\n registerAll(lifecycle?: string): void {\n const subscriptions = this.modelData?.[SubscriptionHandlers] || {};\n const keys = Object.keys(subscriptions);\n\n this.log.debug(\n `Found ${keys.length} subscriptions in ${this.modelId} (lifecycle: ${\n lifecycle ?? \"any\"\n })`\n );\n\n keys.forEach((topic) => {\n const config = subscriptions[topic];\n const topicLifecycle = config.lifecycle;\n\n if (lifecycle && lifecycle !== topicLifecycle) return;\n\n // ACTIVATE-phase handlers belong to activate()/deactivate(); the\n // unfiltered pass (online, reload) only restores them while active.\n if (\n !lifecycle &&\n topicLifecycle === DependencyLifecycle.ACTIVATE &&\n this.model.activeStatus !== KosModelState.ACTIVE\n )\n return;\n\n const resolvedTopic = this.resolvePropKey(topic);\n\n // Once topics are permanently consumed — never re-subscribe\n if (this.onceTopics.has(resolvedTopic)) {\n this.log.debug(`Skipping once topic (already fired): ${resolvedTopic}`);\n return;\n }\n\n // Skip if already subscribed to this resolved topic\n if (this.registeredTopics.has(resolvedTopic)) {\n this.log.debug(`Skipping duplicate subscription for ${resolvedTopic}`);\n return;\n }\n this.registeredTopics.add(resolvedTopic);\n\n // Track once topics so they persist across dispose cycles\n if (config.once) {\n this.onceTopics.add(resolvedTopic);\n }\n\n this.log.debug(`Resolved topic: ${topic} → ${resolvedTopic}`);\n\n // Register baseline dependency if specified\n if (config.requiresBaseline) {\n this.baselineDependencies.set(resolvedTopic, config.requiresBaseline);\n this.log.debug(\n `Registered baseline dependency for ${resolvedTopic}: ${config.requiresBaseline.path}`\n );\n }\n\n // Check if this subscription uses flow control\n if (config.flow) {\n this.subscribeWithFlowControl(config, resolvedTopic, topicLifecycle);\n } else {\n // Standard subscription path\n const handler = this.createHandler(resolvedTopic, config);\n this.subscribe(\n config,\n resolvedTopic,\n handler,\n topicLifecycle === DependencyLifecycle.ACTIVATE\n );\n }\n });\n }\n\n deactivate(): void {\n this.log.debug(`Deactivating subscriptions for ${this.modelId}`);\n\n for (const dispose of this.activatableDisposers) {\n try {\n dispose();\n } catch (e) {\n this.log.error(\"Error during subscription disposal\", e);\n }\n }\n this.activatableDisposers = [];\n\n // Remove activatable topics from the dedup set so they can re-register\n const subscriptions = this.modelData?.[SubscriptionHandlers] || {};\n for (const [topic, config] of Object.entries<any>(subscriptions)) {\n if (config.lifecycle === DependencyLifecycle.ACTIVATE) {\n const resolvedTopic = this.resolvePropKey(topic);\n this.registeredTopics.delete(resolvedTopic);\n }\n }\n }\n\n disposeAll(): void {\n const allDisposers = [...this.disposers, ...this.activatableDisposers];\n this.log.debug(\n `Disposing ${allDisposers.length} subscriptions for ${this.modelId}`\n );\n\n // Dispose flow controllers\n for (const [topic, _controller] of this.flowControllers) {\n this.log.debug(`Disposing flow controller for ${topic}`);\n }\n this.flowControllers.clear();\n\n for (const dispose of allDisposers) {\n try {\n dispose();\n } catch (e) {\n this.log.error(\"Error during subscription disposal\", e);\n }\n }\n this.disposers = [];\n this.activatableDisposers = [];\n this.registeredTopics.clear();\n }\n\n private subscribe(\n subscription: any,\n topic: string,\n handler: (payload: any) => void,\n activatable: boolean\n ): void {\n const { destinationAddress, explicitDestination } =\n this.resolveDestination(subscription);\n if (subscription.websocket) {\n this.log.debug(`Subscribing to WebSocket topic: ${topic}`);\n const socketSub = WebSocketTransport.getInstance().subscribeTopic({\n topic,\n callback: handler,\n fos: subscription.fos,\n bridge: subscription.bridge,\n destinationAddress,\n explicitDestination,\n });\n if (activatable) {\n this.activatableDisposers.push(socketSub);\n } else {\n this.disposers.push(socketSub);\n }\n } else {\n this.log.debug(`Subscribing to EventBus topic: ${topic}`);\n const { unsubscribe } = EventBus.subscribe(topic, handler);\n if (activatable) {\n this.activatableDisposers.push(unsubscribe);\n } else {\n this.disposers.push(unsubscribe);\n }\n }\n }\n\n private createHandler(\n resolvedTopic: string,\n subscription: any\n ): (payload: any) => void {\n return async (payload: any) => {\n try {\n // Extract wildcard capture if applicable\n const wildcardCapture = this.extractWildcardCapture(\n resolvedTopic,\n payload,\n subscription\n );\n\n // Check baseline readiness if required\n const baselineReady = this.isBaselineReady(resolvedTopic);\n\n if (!this.model.isReady() || !baselineReady) {\n if (!baselineReady) {\n this.log.warn(\n `Baseline not ready for ${resolvedTopic}. Queuing message.`\n );\n } else {\n this.log.warn(\n `Model ${this.modelId} not ready. Queuing message for ${resolvedTopic}`\n );\n }\n\n const offlineHandler = () => {\n const body = getMessageBody(payload, subscription.skipParse);\n const data = subscription.transform(body);\n if (subscription.condition(data, this.modelData, payload)) {\n return this.callHandlerWithWildcard(\n subscription,\n data,\n wildcardCapture,\n payload\n );\n }\n return undefined;\n };\n this.offlineQueue.enqueue(offlineHandler, resolvedTopic, payload);\n } else {\n const body = getMessageBody(payload, subscription.skipParse);\n const data = subscription.transform(body);\n if (subscription.condition(data, this.modelData, payload)) {\n return this.callHandlerWithWildcard(\n subscription,\n data,\n wildcardCapture,\n payload\n );\n }\n }\n } catch (e) {\n this.log.error(`Error handling subscription for ${resolvedTopic}`, e);\n }\n return undefined;\n };\n }\n\n private extractWildcardCapture(\n resolvedTopic: string,\n payload: any,\n subscription: any\n ): Record<string, string> | null {\n // Check if subscription has wildcardName parameter and topic has trailing wildcard\n if (!subscription.wildcardName || !checkWildcardPattern(resolvedTopic)) {\n return null;\n }\n\n const actualTopic = payload?.headers?.topic || \"\";\n return parseWildcardSegment(\n resolvedTopic,\n actualTopic,\n subscription.wildcardName\n );\n }\n\n private callHandlerWithWildcard(\n subscription: any,\n data: any,\n wildcardCapture: Record<string, string> | null,\n payload: any\n ): any {\n // Extend payload with wildcard capture if available\n if (wildcardCapture && Object.keys(wildcardCapture).length > 0) {\n const extendedPayload = {\n ...payload,\n wildcardCapture,\n };\n return subscription.handler.call(\n this.modelData,\n data,\n extendedPayload,\n this.modelData\n );\n } else {\n // Call without wildcard capture (original behavior)\n return subscription.handler.call(\n this.modelData,\n data,\n payload,\n this.modelData\n );\n }\n }\n\n // A destination template whose model property is unset names no destination:\n // it resolves to null and is not treated as explicit, so the transport keeps\n // its connId fallback for that model.\n private resolveDestination(subscription: {\n destinationAddress?: string;\n explicitDestination?: boolean;\n }): { destinationAddress: string | null; explicitDestination: boolean } {\n const template = subscription.destinationAddress;\n const explicitDestination = subscription.explicitDestination ?? false;\n if (!template) {\n return { destinationAddress: null, explicitDestination };\n }\n const match = template.match(/{PROP_(.+?)}/);\n if (match) {\n const value = this.modelData?.[match[1]];\n if (value === null || value === undefined) {\n return { destinationAddress: null, explicitDestination: false };\n }\n }\n return {\n destinationAddress: this.resolvePropKey(template),\n explicitDestination,\n };\n }\n\n private resolvePropKey(template: string): string {\n const propRegex = /.*({PROP_(.+)})/;\n let topic = template.includes(\"{MODEL_ID}\")\n ? template.replace(\"{MODEL_ID}\", this.modelId)\n : template;\n\n const match = topic.match(propRegex);\n if (match && match[2] in this.modelData) {\n topic = topic.replace(match[1], this.modelData[match[2]]);\n }\n\n return topic;\n }\n\n // ===== FLOW CONTROL METHODS =====\n\n private async subscribeWithFlowControl(\n config: any,\n resolvedTopic: string,\n lifecycle: string\n ): Promise<void> {\n this.log.debug(`Setting up flow control for topic: ${resolvedTopic}`);\n\n // Create flow control manager\n const flowManager = new FlowControlManager(config.flow);\n this.flowControllers.set(resolvedTopic, flowManager);\n\n // Create the enhanced handler\n const enhancedHandler = this.createFlowControlHandler(\n resolvedTopic,\n config\n );\n\n // Start the async flow processing\n const flowProcessor = this.startFlowProcessing(\n config,\n resolvedTopic,\n enhancedHandler,\n flowManager\n );\n\n // Track the processor for cleanup\n const cleanup = () => {\n this.flowControllers.delete(resolvedTopic);\n flowProcessor.then((controller) => controller?.abort());\n };\n\n if (lifecycle === DependencyLifecycle.ACTIVATE) {\n this.activatableDisposers.push(cleanup);\n } else {\n this.disposers.push(cleanup);\n }\n }\n\n private async startFlowProcessing(\n config: any,\n resolvedTopic: string,\n handler: Function,\n flowManager: FlowControlManager\n ): Promise<AbortController | null> {\n const controller = new AbortController();\n\n try {\n let unsubscribeTopic: VoidFunction | undefined;\n if (config.websocket) {\n const { destinationAddress, explicitDestination } =\n this.resolveDestination(config);\n\n unsubscribeTopic = WebSocketTransport.getInstance().subscribeTopic({\n topic: resolvedTopic,\n callback: () => {}, // Empty callback, we'll use async iteration\n fos: config.fos,\n bridge: config.bridge,\n destinationAddress,\n explicitDestination,\n });\n }\n\n const eventSource = AsyncEventBus.iterate(resolvedTopic);\n\n // The iterator is a listener on the topic too; the transport releases the\n // broker subscription only once the last listener leaves, so close it first.\n controller.signal.addEventListener(\"abort\", () => {\n void eventSource.return();\n unsubscribeTopic?.();\n });\n\n // Process events through flow control\n (async () => {\n try {\n for await (const processedData of flowManager.processEvents(\n eventSource,\n controller.signal\n )) {\n if (controller.signal.aborted) break;\n\n // Execute handler with processed data\n const handlerPromise = handler(processedData);\n\n // Track promise for backpressure if it's async\n if (handlerPromise instanceof Promise) {\n await handlerPromise;\n }\n }\n } catch (error) {\n this.log.error(`Flow control error for ${resolvedTopic}:`, error);\n }\n })();\n\n return controller;\n } catch (error) {\n this.log.error(\n `Failed to start flow processing for ${resolvedTopic}:`,\n error\n );\n return null;\n }\n }\n\n private createFlowControlHandler(\n resolvedTopic: string,\n config: any\n ): (processedData: any) => void | Promise<void> {\n return async (processedData: any) => {\n try {\n // Apply additional filtering and conditions\n if (\n config.condition &&\n !config.condition(processedData, this.modelData, processedData)\n ) {\n return undefined;\n }\n\n if (!this.model.isReady()) {\n this.log.warn(\n `Model ${this.modelId} not ready. Queuing flow-controlled message for ${resolvedTopic}`\n );\n\n const offlineHandler = () =>\n config.handler.call(\n this.modelData,\n processedData,\n processedData,\n this.modelData\n );\n this.offlineQueue.enqueue(\n offlineHandler,\n resolvedTopic,\n processedData\n );\n } else {\n // Execute the handler with flow-controlled data\n return config.handler.call(\n this.modelData,\n processedData,\n processedData,\n this.modelData\n );\n }\n } catch (error) {\n this.log.error(\n `Error in flow control handler for ${resolvedTopic}:`,\n error\n );\n\n // Apply retry logic if configured\n if (config.flow?.errorHandling?.retry) {\n await this.retryHandler(config, processedData, error);\n } else if (!config.flow?.errorHandling?.continueOnError) {\n throw error;\n }\n }\n return undefined;\n };\n }\n\n private async retryHandler(\n config: any,\n data: any,\n originalError: any\n ): Promise<void> {\n const retryConfig = config.flow.errorHandling.retry;\n let lastError = originalError;\n\n for (let attempt = 1; attempt <= retryConfig.attempts; attempt++) {\n try {\n this.log.debug(\n `Retry attempt ${attempt}/${retryConfig.attempts} for handler`\n );\n await new Promise((resolve) =>\n setTimeout(resolve, retryConfig.backoffMs * attempt)\n );\n\n return config.handler.call(this.modelData, data, data, this.modelData);\n } catch (error) {\n lastError = error;\n this.log.warn(`Retry attempt ${attempt} failed:`, error);\n }\n }\n\n this.log.error(\n `All retry attempts failed, throwing last error:`,\n lastError\n );\n throw lastError;\n }\n\n /**\n * Get flow control statistics for monitoring\n */\n public getFlowControlStats(): Record<string, any> {\n const stats: Record<string, any> = {};\n\n for (const [topic, manager] of this.flowControllers) {\n stats[topic] = manager.getStats();\n }\n\n return stats;\n }\n\n // ===== BASELINE-DELTA HELPERS =====\n\n /**\n * Get ServiceResponseStore from model\n * @private\n */\n private getResponseStore(): ServiceResponseStore | undefined {\n return (this.modelData as any).serviceResponses;\n }\n\n /**\n * Check if baseline is ready for a topic handler\n * @private\n */\n private isBaselineReady(topic: string): boolean {\n const baseline = this.baselineDependencies.get(topic);\n if (!baseline) return true; // No baseline required\n\n const store = this.getResponseStore();\n if (!store) {\n this.log.warn(\n `ServiceResponseStore not found for baseline check on topic: ${topic}`\n );\n return false;\n }\n\n const method = baseline.method || \"get\";\n const key = `${method.toUpperCase()}:${baseline.path}`;\n\n return store.has(key);\n }\n\n /**\n * Trigger smart queue flush with baseline temporal filtering\n * Called after baseline loads to replay queued events\n *\n * @param path - Path of the baseline request that completed\n */\n public flushQueueForBaseline(path: string): void {\n const [topic, baseline] =\n [...this.baselineDependencies].find(([, b]) => b.path === path) ?? [];\n if (!baseline) {\n this.log.debug(`No baseline dependency on path: ${path}`);\n return;\n }\n\n const store = this.getResponseStore();\n if (!store) {\n this.log.warn(\n `ServiceResponseStore not found, falling back to standard flush`\n );\n this.offlineQueue.flush();\n return;\n }\n\n const method = baseline.method || \"get\";\n const temporal = store.getTemporalMetadataByPath(baseline.path, method);\n\n if (!temporal) {\n this.log.warn(\n `Baseline temporal metadata not found for ${baseline.path}, falling back to standard flush`\n );\n this.offlineQueue.flush();\n return;\n }\n\n const strategy = baseline.replayStrategy || ReplayStrategy.AFTER_REQUEST;\n\n this.log.info(\n `Flushing queue with strategy ${strategy} for topic: ${topic}`\n );\n this.log.debug(\n `Baseline timing - requested: ${temporal.requestedAt}, received: ${temporal.receivedAt}`\n );\n\n this.offlineQueue.flushWithStrategy(\n strategy,\n temporal.requestedAt,\n temporal.receivedAt\n );\n }\n}\n","type Logger = {\n debug: (...args: any[]) => void;\n info: (...args: any[]) => void;\n warn: (...args: any[]) => void;\n error: (...args: any[]) => void;\n};\n\nexport function createTaggedLogger(base: Logger, tag: string): Logger {\n const prefix = `[Model:${tag}]`;\n\n return {\n debug: (...args) => base.debug(prefix, ...args),\n info: (...args) => base.info(prefix, ...args),\n warn: (...args) => base.warn(prefix, ...args),\n error: (...args) => base.error(prefix, ...args),\n };\n}\n","import { HttpRouteHandlers } from \"../decorators/kos-http-decorators\";\nimport { ServiceRequestHandlers } from \"../decorators/kos-service-request\";\nimport { ModelEffects, SubscriptionHandlers } from \"../decorators/propKeys\";\nimport type { IKosDataModel } from \"../kosModel\";\n\nexport function hasModelEffects(modelData: IKosDataModel): boolean {\n return (\n !!modelData?.[ModelEffects] &&\n Object.keys(modelData[ModelEffects]).length > 0\n );\n}\n\nexport function hasSubscriptionHandlers(modelData: IKosDataModel): boolean {\n return (\n !!modelData?.[SubscriptionHandlers] &&\n Object.keys(modelData[SubscriptionHandlers]).length > 0\n );\n}\n\nexport function hasHttpRouteHandlers(modelData: IKosDataModel): boolean {\n return (\n !!modelData?.[HttpRouteHandlers] && modelData[HttpRouteHandlers].length > 0\n );\n}\n\nexport function hasServiceRequestHandlers(modelData: IKosDataModel): boolean {\n const prototype = Object.getPrototypeOf(modelData);\n return (\n !!prototype?.[ServiceRequestHandlers] &&\n Object.keys(prototype[ServiceRequestHandlers]).length > 0\n );\n}\n","import {\n CachedResponse,\n ResponseCacheConfig,\n ResponseRetention,\n} from \"../../types/service-response-store\";\n\n// ============================================================================\n// Zone 3: Low-level helper functions\n// ============================================================================\n\n/**\n * Checks TTL extension preconditions\n * @internal\n */\nfunction checkTTLExtensionPreconditions(config: ResponseCacheConfig): boolean {\n return (\n config.retention === ResponseRetention.TTL &&\n config.extendOnRefresh === true &&\n config.ttl !== undefined\n );\n}\n\n/**\n * Checks if response exists in cache\n * @internal\n */\nfunction hasExistingResponse(\n responses: Map<string, CachedResponse>,\n key: string\n): boolean {\n return responses.has(key);\n}\n\n/**\n * Checks if cached response has not expired\n * @internal\n */\nfunction isResponseNotExpired(cached: CachedResponse): boolean {\n return !cached.expiresAt || Date.now() < cached.expiresAt;\n}\n\n/**\n * Schedules cleanup timer for response\n * @internal\n */\nfunction scheduleCleanup(\n key: string,\n ttl: number,\n cleanupTimers: Map<string, NodeJS.Timeout>,\n deleteCallback: (key: string) => void\n): void {\n const timer = setTimeout(() => deleteCallback(key), ttl);\n cleanupTimers.set(key, timer);\n}\n\n/**\n * ServiceResponseStore manages keyed storage of service responses with flexible retention policies.\n *\n * Responses are stored by `{method}:{path}` key (e.g., 'GET:/api/ingredients')\n * and can be configured with different retention policies to control caching behavior.\n *\n * @example\n * const store = new ServiceResponseStore();\n *\n * // Store with TTL (replaces on each request)\n * store.set('GET:/api/status', statusData, {\n * retention: ResponseRetention.TTL,\n * ttl: 5 * 60 * 1000\n * });\n *\n * // Store with TTL extension (keeps existing data, extends TTL)\n * const stored = store.set('GET:/api/expensive', expensiveData, {\n * retention: ResponseRetention.TTL,\n * ttl: 5 * 60 * 1000,\n * extendOnRefresh: true\n * });\n * // stored === false if cache was extended, true if new data stored\n *\n * // Retrieve\n * const status = store.get('GET:/api/status');\n */\nexport class ServiceResponseStore {\n private responses = new Map<string, CachedResponse>();\n private retentionPolicies = new Map<string, ResponseCacheConfig>();\n private cleanupTimers = new Map<string, NodeJS.Timeout>();\n\n /**\n * Store a response with retention policy\n *\n * @param key - Storage key (typically `{method}:{path}`)\n * @param response - Response data to cache\n * @param config - Caching configuration (defaults to SINGLE retention)\n * @param requestedAt - When the request was sent (for temporal tracking)\n * @param receivedAt - When the response was received (for temporal tracking)\n * @returns true if response was stored, false if refresh extended existing TTL\n */\n set<T>(\n key: string,\n response: T,\n config: ResponseCacheConfig = { retention: ResponseRetention.SINGLE },\n requestedAt = Date.now(),\n receivedAt = Date.now()\n ): boolean {\n if (this.shouldExtendTTL(key, config)) {\n this.extendExistingTTL(key, config.ttl!);\n return false; // TTL extended\n }\n\n const cached = this.createCachedResponse(\n response,\n key,\n config,\n requestedAt,\n receivedAt\n );\n this.storeResponse(key, cached, config);\n return true; // New data stored\n }\n\n /**\n * Get response if not expired\n *\n * @param key - Storage key\n * @returns Response data or undefined if not found/expired\n */\n get<T = any>(key: string): T | undefined {\n const cached = this.responses.get(key);\n\n if (!cached) return undefined;\n\n // Check expiration\n if (cached.expiresAt && Date.now() > cached.expiresAt) {\n this.delete(key);\n return undefined;\n }\n\n return cached.data as T;\n }\n\n /**\n * Get response by path and method\n *\n * @param path - API path\n * @param method - HTTP method (defaults to 'get')\n * @returns Response data or undefined if not found/expired\n */\n getByPath<T = any>(path: string, method = \"get\"): T | undefined {\n return this.get(this.makeKey(path, method));\n }\n\n /**\n * Check if response exists and is not expired\n *\n * @param key - Storage key\n * @returns true if valid response exists\n */\n has(key: string): boolean {\n return this.get(key) !== undefined;\n }\n\n /**\n * Manually delete a response\n *\n * @param key - Storage key\n */\n delete(key: string): void {\n this.responses.delete(key);\n this.retentionPolicies.delete(key);\n\n const timer = this.cleanupTimers.get(key);\n if (timer) {\n clearTimeout(timer);\n this.cleanupTimers.delete(key);\n }\n }\n\n /**\n * Clear all responses for a path (all methods)\n *\n * @param path - API path to clear\n */\n clearPath(path: string): void {\n const keys = Array.from(this.responses.keys()).filter(\n (key) => this.extractPath(key) === path\n );\n\n keys.forEach((key) => this.delete(key));\n }\n\n /**\n * Clear all responses\n */\n clear(): void {\n this.cleanupTimers.forEach((timer) => clearTimeout(timer));\n this.responses.clear();\n this.retentionPolicies.clear();\n this.cleanupTimers.clear();\n }\n\n /**\n * Get count of cached responses\n */\n get size(): number {\n return this.responses.size;\n }\n\n /**\n * Check if a response should be cleaned up after handler completes\n *\n * @param key - Storage key\n * @returns true if response has IMMEDIATE retention policy\n */\n shouldCleanupAfterHandler(key: string): boolean {\n const config = this.retentionPolicies.get(key);\n return config?.retention === ResponseRetention.IMMEDIATE;\n }\n\n /**\n * Zone 2: Evaluates if TTL should be extended instead of replacing data\n */\n private shouldExtendTTL(key: string, config: ResponseCacheConfig): boolean {\n // Zone 3: Check configuration preconditions\n if (!checkTTLExtensionPreconditions(config)) {\n return false;\n }\n\n // Zone 3: Check if non-expired response exists\n if (!hasExistingResponse(this.responses, key)) {\n return false;\n }\n\n const existing = this.responses.get(key)!;\n return isResponseNotExpired(existing);\n }\n\n /**\n * Extend TTL for existing cached response\n */\n private extendExistingTTL(key: string, ttl: number): void {\n const existing = this.responses.get(key)!;\n existing.expiresAt = Date.now() + ttl;\n this.resetCleanupTimer(key, ttl);\n }\n\n /**\n * Zone 3: Reset cleanup timer for a cached response\n */\n private resetCleanupTimer(key: string, ttl: number): void {\n this.clearTimerIfExists(key);\n scheduleCleanup(key, ttl, this.cleanupTimers, (k) => this.delete(k));\n }\n\n /**\n * Clear cleanup timer if it exists\n */\n private clearTimerIfExists(key: string): void {\n const timer = this.cleanupTimers.get(key);\n if (timer) {\n clearTimeout(timer);\n this.cleanupTimers.delete(key);\n }\n }\n\n /**\n * Create cached response object with metadata\n */\n private createCachedResponse<T>(\n response: T,\n key: string,\n config: ResponseCacheConfig,\n requestedAt: number,\n receivedAt: number\n ): CachedResponse<T> {\n return {\n data: response,\n timestamp: receivedAt, // Backward compatibility\n requestedAt,\n receivedAt,\n path: this.extractPath(key),\n method: this.extractMethod(key),\n expiresAt: this.calculateExpiresAt(config),\n };\n }\n\n /**\n * Calculate expiration timestamp based on config\n */\n private calculateExpiresAt(config: ResponseCacheConfig): number | undefined {\n return config.retention === ResponseRetention.TTL && config.ttl\n ? Date.now() + config.ttl\n : undefined;\n }\n\n /**\n * Store response with retention policy, cancelling the cleanup timer of the\n * response it replaces\n */\n private storeResponse(\n key: string,\n cached: CachedResponse,\n config: ResponseCacheConfig\n ): void {\n this.clearTimerIfExists(key);\n this.responses.set(key, cached);\n this.retentionPolicies.set(key, config);\n this.applyRetentionPolicy(key, config);\n }\n\n /**\n * Zone 2: Configures retention policy for a stored response\n */\n private applyRetentionPolicy(key: string, config: ResponseCacheConfig): void {\n switch (config.retention) {\n case ResponseRetention.IMMEDIATE:\n // Note: IMMEDIATE cleanup is NOT done here automatically.\n // The ServiceRequestManager will call delete() after the handler completes\n // to ensure async handlers have access to the response during execution.\n // Check via shouldCleanupAfterHandler() to determine if cleanup is needed.\n break;\n\n case ResponseRetention.TTL:\n if (config.ttl) {\n // Zone 3: Schedule cleanup timer\n scheduleCleanup(key, config.ttl, this.cleanupTimers, (k) =>\n this.delete(k)\n );\n }\n break;\n\n case ResponseRetention.SINGLE:\n // Previous response for same path already handled by set()\n // No additional cleanup needed\n break;\n\n case ResponseRetention.PERMANENT:\n case ResponseRetention.MANUAL:\n // No automatic cleanup\n break;\n }\n }\n\n /**\n * Make storage key from path and method\n */\n private makeKey(path: string, method: string): string {\n return `${method.toUpperCase()}:${path}`;\n }\n\n /**\n * Extract path from storage key\n */\n private extractPath(key: string): string {\n return key.split(\":\", 2)[1] || key;\n }\n\n /**\n * Extract method from storage key\n */\n private extractMethod(key: string): string {\n return key.split(\":\", 2)[0] || \"get\";\n }\n\n /**\n * Get temporal metadata for a cached response\n * Used for baseline-delta race condition handling\n *\n * @param key - Storage key\n * @returns Temporal metadata or undefined if not found\n */\n getTemporalMetadata(\n key: string\n ): { requestedAt: number; receivedAt: number } | undefined {\n const cached = this.responses.get(key);\n if (!cached) return undefined;\n\n return {\n requestedAt: cached.requestedAt,\n receivedAt: cached.receivedAt,\n };\n }\n\n /**\n * Get temporal metadata by path and method\n *\n * @param path - API path\n * @param method - HTTP method (defaults to 'get')\n * @returns Temporal metadata or undefined if not found\n */\n getTemporalMetadataByPath(\n path: string,\n method = \"get\"\n ): { requestedAt: number; receivedAt: number } | undefined {\n return this.getTemporalMetadata(this.makeKey(path, method));\n }\n\n /**\n * Cleanup expired responses (called periodically if needed)\n */\n cleanup(): void {\n const now = Date.now();\n const expired = Array.from(this.responses.entries())\n .filter(([_, cached]) => cached.expiresAt && now > cached.expiresAt)\n .map(([key]) => key);\n\n expired.forEach((key) => this.delete(key));\n }\n}\n","// kos-model-component-factory.ts\nimport type { IKosDataModel, IKosModel } from \"../kosModel\";\nimport { KosChildResolver } from \"./kos-child-resolver\";\nimport { KosCompanionModelManager } from \"./kos-companion-model-manager\";\nimport { KosEffectManager } from \"./kos-effects-manager\";\nimport { KosFSMManager } from \"./kos-fsm-manager\";\nimport { KosHttpRouteManager } from \"./kos-http-route-manager\";\nimport { KosLoggerFactory } from \"./kos-logger-factory\";\nimport { KosOfflineQueue } from \"./kos-offline-queue\";\nimport { KosOnlineLifecycleManager } from \"./kos-online-lifecycle-manager\";\nimport { ServiceRequestManager } from \"./kos-service-request-manager\";\nimport { KosSubscriptionManager } from \"./kos-subscription-manager\";\nimport { createTaggedLogger } from \"./logger-utils\";\nimport {\n hasHttpRouteHandlers,\n hasModelEffects,\n hasServiceRequestHandlers,\n hasSubscriptionHandlers,\n} from \"./model-introspection-utils\";\nimport { ServiceResponseStore } from \"./service-response-store\";\n\ninterface KosModelComponents {\n fsm: KosFSMManager;\n offlineQueue: KosOfflineQueue;\n subscriptionManager?: KosSubscriptionManager;\n effectManager?: KosEffectManager;\n onlineLifecycleManager: KosOnlineLifecycleManager;\n httpRouteManager?: KosHttpRouteManager;\n serviceResponseStore: ServiceResponseStore;\n serviceRequestManager?: ServiceRequestManager;\n companionManager: KosCompanionModelManager;\n childResolver: KosChildResolver;\n}\n\nexport class KosModelComponentFactory {\n static createAll<T extends IKosDataModel>(\n model: IKosModel<T>\n ): KosModelComponents {\n const { modelId, modelTypeName, modelData } = model;\n\n // Single shared logger\n const log = KosLoggerFactory.create({\n modelId,\n modelTypeName,\n });\n\n const fsm = new KosFSMManager(model, createTaggedLogger(log, \"fsm\"));\n const offlineQueue = new KosOfflineQueue(\n createTaggedLogger(log, \"offline-queue\")\n );\n const companionManager = new KosCompanionModelManager(model);\n const childResolver = new KosChildResolver(model);\n\n // Always create ServiceResponseStore (needed for response caching)\n const serviceResponseStore = new ServiceResponseStore();\n\n // Attach store to modelData so getServiceResponse() can access it\n (modelData as any).serviceResponses = serviceResponseStore;\n\n // Every model runs online() at boot, so every model follows later\n // disconnects and reconnects, with or without topic handlers.\n const onlineLifecycleManager = new KosOnlineLifecycleManager(\n model,\n createTaggedLogger(log, \"online\")\n );\n\n const components: KosModelComponents = {\n fsm,\n offlineQueue,\n onlineLifecycleManager,\n serviceResponseStore,\n companionManager,\n childResolver,\n };\n\n if (hasModelEffects(modelData)) {\n components.effectManager = new KosEffectManager(\n modelTypeName,\n modelId,\n modelData,\n createTaggedLogger(log, \"effect\")\n );\n }\n\n if (hasSubscriptionHandlers(modelData)) {\n const subLogger = createTaggedLogger(log, \"subscription\");\n\n components.subscriptionManager = new KosSubscriptionManager(\n model,\n modelData,\n modelId,\n offlineQueue,\n subLogger\n );\n }\n\n if (hasHttpRouteHandlers(modelData)) {\n components.httpRouteManager = new KosHttpRouteManager(\n modelData,\n createTaggedLogger(log, \"http-routes\")\n );\n }\n\n if (hasServiceRequestHandlers(modelData)) {\n components.serviceRequestManager = new ServiceRequestManager(\n modelData,\n serviceResponseStore,\n components.subscriptionManager\n );\n }\n\n return components;\n }\n}\n","/* eslint-disable max-len */\nimport logger from \"loglevel\";\nimport { makeAutoObservable } from \"mobx\";\n\nimport { KosOfflineQueue } from \"./model/kos-offline-queue\";\n\nimport { EventBus } from \"../../common\";\n\n// import { KosModelManager } from \"./kosModelManager\";\n\nimport { ExtensionManager } from \"../core/extension/extension-manager\";\n\nimport { kosAction } from \"..\";\nimport {\n modelEventTopicFactory,\n modelTypeEventTopicFactory,\n} from \"../../models/utils/model-event-utils\";\nimport { DependencyLifecycle } from \"../types/kos-dependency\";\nimport { awaitFirstMatchingWhen } from \"../util/await-first-matching-when\";\nimport {\n Transitions,\n executeChildrenModelLifecycle,\n executeDependentModelLifecycle,\n} from \"../util/model-utils\";\nimport {\n KosContext,\n KosContextBean,\n KosContextManager,\n} from \"./context/kos-context-manager\";\nimport { CompanionParentModel, initializeStateMachine } from \"./decorators\";\nimport type { KosModelManager } from \"./kosModelManager\";\nimport { KosModelState } from \"./lifecycle/constants\";\nimport { KosLog } from \"./log\";\nimport { applyKosModelDevtoolsSupport } from \"./model/apply-kos-dev-tool-support\";\nimport { KosChildResolver } from \"./model/kos-child-resolver\";\nimport { KosCompanionModelManager } from \"./model/kos-companion-model-manager\";\nimport { KosEffectManager } from \"./model/kos-effects-manager\";\nimport { KosFSMManager } from \"./model/kos-fsm-manager\";\nimport { KosHttpRouteManager } from \"./model/kos-http-route-manager\";\nimport { KosModelComponentFactory } from \"./model/kos-model-component-factory\";\nimport { KosOnlineLifecycleManager } from \"./model/kos-online-lifecycle-manager\";\nimport { KosSubscriptionManager } from \"./model/kos-subscription-manager\";\nimport type { KosParentAware } from \"./types\";\n\nconst log = logger.getLogger(\"kos-model\");\n\nconst MODEL_LOADER = \"kos.extension.model.loader\";\n/**\n * @kosService core.kos-model\n * @kosApiLevel 2\n */\nexport interface IKosModelLifecycle {\n init?(context?: KosContext): Promise<void>;\n load?(context?: KosContext): Promise<void>;\n ready?(context?: KosContext): Promise<void>;\n online?(context?: KosContext): Promise<void>;\n offline?(context?: KosContext): Promise<void>;\n unload?(context?: KosContext): void;\n activate?(context?: KosContext): Promise<void>;\n deactivate?(context?: KosContext): Promise<void>;\n}\n\nexport interface IKosVisitor<T extends IKosDataModel | IKosModel> {\n visit: (model: T) => void;\n}\n\nexport interface IKosVisitorHost<T extends IKosDataModel | IKosModel> {\n accept?: (visitor: IKosVisitor<T>) => void;\n}\n\nexport type KosContextLogger = ReturnType<typeof KosLog.getLogger>;\nexport interface IKosModelLogger {\n logger: KosContextLogger;\n}\n\n/**\n * @kosService core.kos-model\n * @kosApiLevel 2\n */\nexport interface KosCreationContext extends IKosModelLogger {\n kosContext: KosContextBean;\n [key: string]: any;\n}\n\n/**\n * @kosService core.kos-model\n * @kosApiLevel 2\n */\nexport interface IKosDataModel\n extends IKosModelLifecycle,\n IKosVisitorHost<IKosDataModel> {\n id: string;\n getDependencies?(): void;\n getChildren?: () => IKosDataModel[];\n update?: (values) => Promise<void>;\n /**\n * @kosApiLevel 5\n */\n toJSON?: () => object;\n}\n\n/**\n * @kosService core.companion\n * @kosApiLevel 2\n */\nexport interface IKosCompanionOptions<\n T extends IKosDataModel = IKosDataModel,\n O extends object = object\n> extends KosParentAware {\n companionParent: T;\n data?: O;\n}\n\n/**\n * @kosService core.container-aware\n * @kosApiLevel 2\n */\nexport interface IKosContainerModel<\n T extends IKosDataModel,\n R extends object = Record<string, unknown>\n> {\n models: T[];\n createModel?: (request: R) => Promise<unknown>;\n deleteModel?: (id: string) => Promise<void>;\n getModel?: (id: string) => T | undefined;\n}\n\n/**\n * @kosService core.kos-model\n * @kosApiLevel 2\n */\nexport interface ReloadAware {\n reload: () => Promise<void>;\n /**\n * @kosApiLevel 20\n */\n readonly isReloading?: boolean;\n}\n\n/**\n * @kosService core.kos-model\n * @kosApiLevel 2\n */\nexport interface UnloadAware {\n unload: () => Promise<void>;\n}\n\n/**\n * @kosService core.kos-model\n * @kosApiLevel 2\n */\nexport interface UpdateAware<O extends object = Record<string, any>> {\n updateModel: (options: O) => void;\n}\n\nexport interface IKosModel<DataDef extends IKosDataModel = IKosDataModel>\n extends IKosCompanionModelContainer,\n IKosModelLifecycle,\n IKosVisitorHost<IKosModel> {\n modelId: string;\n status: KosModelState;\n onlineStatus: KosModelState;\n activeStatus: KosModelState;\n modelTypeName: string;\n loaded: boolean;\n fsm: KosFSMManager;\n isReady(): boolean;\n isActive(): boolean;\n isOnline(): boolean;\n whenReady(): Promise<void>;\n whenInitialized(): Promise<void>;\n whenLoaded(): Promise<void>;\n registerSubscribers(): Promise<void>;\n /**\n * Re-attach everything `unload()` disposed, after the data model's `reload()`.\n * @internal\n */\n restoreAfterReload(): void;\n getChildren(): IKosModel[];\n modelData: DataDef;\n modelManager: KosModelManager;\n onlineLifecycleManager?: KosOnlineLifecycleManager;\n}\n\ninterface KosModelParameters<DataType extends IKosDataModel> {\n modelTypeName: string;\n id?: string | number;\n modelData: DataType;\n}\n\ninterface IKosCreateParam<Options extends object = Record<string, any>> {\n id?: string;\n modelTypeId: string;\n options?: Options;\n}\n\nexport type IKosDataModelBuilder<D, M extends IKosDataModel> = (data: D) => M;\n\nexport type IKosDataModelCreator<\n M extends IKosDataModel = IKosDataModel,\n O extends object = Record<string, any>\n> = (params: IKosCreateParam<O>) => M;\n\nexport interface IKosDataModelFactory<D, M extends IKosDataModel> {\n build?: IKosDataModelBuilder<D, M>;\n create?: IKosDataModelCreator<M>;\n}\n\ninterface IKosCompanionModelContainer {\n clearCompanionModels: () => void;\n addCompanionModel: (model: IKosModel) => void;\n companionModels: KosCompanionModelManager;\n}\nexport class KosModel<DataDef extends IKosDataModel = IKosDataModel>\n implements IKosModel<DataDef>, IKosCompanionModelContainer\n{\n private _id: string;\n\n private _status: KosModelState;\n\n private _activeStatus: KosModelState;\n private _onlineStatus: KosModelState;\n\n modelData: DataDef;\n\n modelTypeName: string;\n\n initialized: boolean;\n\n loaded: boolean;\n private _isLoadExecuting: boolean;\n offlineQueue: KosOfflineQueue;\n subscriptionManager?: KosSubscriptionManager;\n effectManager?: KosEffectManager;\n httpRouteManager?: KosHttpRouteManager;\n onlineLifecycleManager?: KosOnlineLifecycleManager;\n serviceResponses: any; // ServiceResponseStore\n serviceRequestManager?: any; // ServiceRequestManager\n companionManager: KosCompanionModelManager;\n childResolver: KosChildResolver;\n fsm: KosFSMManager;\n\n constructor({ modelTypeName, id, modelData }: KosModelParameters<DataDef>) {\n this._id = typeof id !== \"undefined\" ? `${id}` : modelTypeName;\n this.modelTypeName = modelTypeName;\n this.initialized = false;\n this.loaded = false;\n this._isLoadExecuting = false;\n this.modelData = modelData;\n this._status = KosModelState.CREATED;\n this._activeStatus = KosModelState.INACTIVE;\n this._onlineStatus = KosModelState.OFFLINE;\n const components = KosModelComponentFactory.createAll(this);\n\n this.fsm = components.fsm;\n this.offlineQueue = components.offlineQueue;\n this.companionManager = components.companionManager;\n this.childResolver = components.childResolver;\n this.serviceResponses = components.serviceResponseStore;\n\n if (components.effectManager) {\n this.effectManager = components.effectManager;\n }\n if (components.subscriptionManager) {\n this.subscriptionManager = components.subscriptionManager;\n }\n if (components.httpRouteManager) {\n this.httpRouteManager = components.httpRouteManager;\n }\n if (components.onlineLifecycleManager) {\n this.onlineLifecycleManager = components.onlineLifecycleManager;\n }\n if (components.serviceRequestManager) {\n this.serviceRequestManager = components.serviceRequestManager;\n }\n makeAutoObservable(this, {\n fsm: false,\n effectManager: false,\n subscriptionManager: false,\n onlineLifecycleManager: false,\n serviceRequestManager: false,\n serviceResponses: false,\n companionManager: false,\n childResolver: false,\n offlineQueue: false,\n });\n\n applyKosModelDevtoolsSupport(this);\n }\n\n get companionModels() {\n return this.companionManager;\n }\n\n set status(status: KosModelState) {\n this._status = status;\n }\n\n get status() {\n return this._status;\n }\n get modelId() {\n return this._id;\n }\n\n get id() {\n return this._id;\n }\n get activeStatus() {\n return this._activeStatus;\n }\n set activeStatus(activeStatus: KosModelState) {\n this._activeStatus = activeStatus;\n }\n\n get onlineStatus() {\n return this._onlineStatus;\n }\n set onlineStatus(onlineStatus: KosModelState) {\n this._onlineStatus = onlineStatus;\n }\n\n get modelManager() {\n return globalThis.kos.modelManager;\n }\n\n isActive() {\n return this._status === KosModelState.ACTIVE;\n }\n\n isOnline() {\n return this._onlineStatus === KosModelState.ONLINE;\n }\n\n isReady() {\n return this._status === KosModelState.READY;\n }\n\n async deactivate(): Promise<void> {\n log.debug(\n `deactivating model ${this.modelTypeName} with id ${this.modelId}`\n );\n try {\n const context = KosContextManager.getContext(this.modelId);\n await this.modelData?.deactivate?.(context);\n log.debug(\n `Model ${this.modelTypeName} with id ${this.modelId} deactivated`\n );\n this.subscriptionManager?.deactivate();\n } catch (e) {\n log.debug(`Model ${this.modelId} failed to deactivated`);\n throw e;\n }\n }\n\n async activate(): Promise<void> {\n log.debug(`activating model ${this.modelTypeName} with id ${this.modelId}`);\n await executeDependentModelLifecycle(this, DependencyLifecycle.ACTIVATE);\n\n try {\n // Execute service requests for ACTIVATE lifecycle before user's activate() method\n await this.serviceRequestManager?.executeForLifecycle(\n DependencyLifecycle.ACTIVATE\n );\n\n const context = KosContextManager.getContext(this.modelId);\n await this.modelData?.activate?.(context);\n\n // Initialize FSM if configured for ACTIVATE lifecycle\n this.initializeStateMachineForLifecycle(DependencyLifecycle.ACTIVATE);\n\n log.debug(\n `Model ${this.modelTypeName} with id ${this.modelId} subscribing to all topics`\n );\n this.subscriptionManager?.registerAll(DependencyLifecycle.ACTIVATE);\n\n // Create companions configured for ACTIVATE lifecycle\n this.createLifecycleCompanions(DependencyLifecycle.ACTIVATE);\n\n log.debug(\n `Model ${this.modelTypeName} with id ${this.modelId} activated`\n );\n } catch (e) {\n log.debug(`Model ${this.modelId} failed to activate`);\n throw e;\n }\n\n return;\n }\n\n async whenLoaded(): Promise<void> {\n await awaitFirstMatchingWhen([\n {\n condition: () => this.status === KosModelState.FAILED,\n onMatch: () => {\n throw new Error(`Failed to initialize model ${this.modelId}`);\n },\n },\n {\n condition: () => this.loaded,\n onMatch: () => {\n log.debug(`Model ${this.modelId} is loaded`);\n },\n },\n ]);\n }\n\n async whenInitialized(): Promise<void> {\n await awaitFirstMatchingWhen([\n {\n condition: () => this.status === KosModelState.FAILED,\n onMatch: () => {\n throw new Error(`Failed to initialize model ${this.modelId}`);\n },\n },\n {\n condition: () => this.initialized,\n onMatch: () => {\n log.debug(`Model ${this.modelId} is initialized`);\n },\n },\n ]);\n }\n async whenReady(): Promise<void> {\n await awaitFirstMatchingWhen([\n {\n condition: () => this.status === KosModelState.FAILED,\n onMatch: () => {\n throw new Error(`Failed to ready model ${this.modelId}`);\n },\n },\n {\n condition: () => this.status === KosModelState.READY,\n onMatch: () => {\n log.debug(`Model ${this.modelId} is ready`);\n },\n },\n ]);\n }\n\n async ready() {\n if (this.fsm.current === KosModelState.READY) {\n log.debug(\n `already readying model ${this.modelTypeName} with id ${this.modelId} returning`\n );\n return;\n }\n\n try {\n log.debug(`readying model ${this.modelTypeName} with id ${this.modelId}`);\n // wait for all non-lazy dependencies to be ready\n await executeDependentModelLifecycle(this, DependencyLifecycle.READY);\n\n await executeChildrenModelLifecycle(\n this,\n Transitions.READY,\n DependencyLifecycle.READY\n );\n\n // Execute service requests for READY lifecycle before user's ready() method\n await this.serviceRequestManager?.executeForLifecycle(\n DependencyLifecycle.READY\n );\n\n const context = KosContextManager.getContext(this.modelId);\n await this.modelData?.ready?.(context);\n\n this.offlineQueue.flush();\n\n // Initialize FSM if configured for READY lifecycle\n this.initializeStateMachineForLifecycle(DependencyLifecycle.READY);\n\n this.subscriptionManager?.registerAll(DependencyLifecycle.READY);\n\n // Create companions configured for READY lifecycle\n this.createLifecycleCompanions(DependencyLifecycle.READY);\n\n log.debug(`Model ${this.modelId} is ready`);\n\n const payload = {\n modelId: this.modelId,\n modelType: this.modelTypeName,\n };\n EventBus.publish(\n modelEventTopicFactory(this.modelTypeName, this.modelId),\n payload\n );\n\n EventBus.publish(modelTypeEventTopicFactory(this.modelTypeName), payload);\n } catch (e) {\n log.error(e);\n throw Error(e as any);\n }\n }\n\n async load(): Promise<void> {\n const companionParent = this[CompanionParentModel];\n if (companionParent) {\n await companionParent.whenLoaded();\n }\n const { modelTypeName, modelId } = this;\n\n // Check if already loaded\n if (this.fsm.current === KosModelState.LOADED) {\n log.debug(`Model ${modelTypeName} with id ${modelId} already loaded`);\n return;\n }\n\n // Prevent concurrent execution\n if (this._isLoadExecuting) {\n log.debug(\n `Model ${modelTypeName} with id ${modelId} is currently executing load`\n );\n return;\n }\n\n this._isLoadExecuting = true;\n\n try {\n log.debug(`Loading model ${modelTypeName} with id ${modelId}`);\n\n await executeDependentModelLifecycle(this, DependencyLifecycle.LOAD);\n\n const context = KosContextManager.getContext(modelId);\n const MODEL_LOADER_TYPE = `${MODEL_LOADER}.${modelTypeName}`;\n const loadedContext = await ExtensionManager.loader.executeLoader(\n MODEL_LOADER_TYPE,\n {}\n );\n if (loadedContext) {\n log.info(\n `Setting loaded context for ${modelId}, type: ${modelTypeName}`\n );\n context?.set(MODEL_LOADER_TYPE, loadedContext);\n }\n\n // Execute service requests for LOAD lifecycle before user's load() method\n await this.serviceRequestManager?.executeForLifecycle(\n DependencyLifecycle.LOAD\n );\n\n await this.modelData?.load?.(context);\n\n kosAction(() => {\n this.loaded = true;\n });\n log.debug(\n `Model ${modelTypeName} with id ${modelId} successfully loaded`\n );\n\n // Initialize FSM if configured for LOAD lifecycle\n this.initializeStateMachineForLifecycle(DependencyLifecycle.LOAD);\n\n this.subscriptionManager?.registerAll(DependencyLifecycle.LOAD);\n this.httpRouteManager?.registerAll();\n this.effectManager?.setup();\n\n // Create companions configured for LOAD lifecycle\n this.createLifecycleCompanions(DependencyLifecycle.LOAD);\n } catch (e) {\n log.error(`Model ${modelId} failed to load`, e);\n throw e;\n } finally {\n this._isLoadExecuting = false;\n }\n }\n\n async unload(): Promise<void> {\n log.debug(`unloading model ${this.modelTypeName} with id ${this.modelId}`);\n try {\n const childrenUnload = this.getChildren()\n .map((child) => child.unload?.())\n .filter((p) => !!p);\n await Promise.allSettled(childrenUnload);\n const context = KosContextManager.getContext(this.modelId);\n await this.modelData?.unload?.(context);\n this.loaded = false;\n this.onlineLifecycleManager?.dispose();\n\n // Cleanup FSM state\n if (this.modelData) {\n const modelData = this.modelData as any;\n modelData._fsmInitialized = false;\n if (modelData._fsmConfig) {\n const stateProperty =\n modelData._fsmOptions?.stateProperty || \"currentState\";\n modelData[stateProperty] = undefined;\n }\n if (modelData.stateHistory) {\n modelData.stateHistory = [];\n }\n }\n\n log.debug(`Model ${this.modelTypeName} with id ${this.modelId} unloaded`);\n this.effectManager?.disposeAll();\n this.subscriptionManager?.disposeAll();\n this.httpRouteManager?.dispose();\n } catch (e) {\n log.debug(`Model ${this.modelId} failed to unload`);\n throw e;\n }\n }\n async init(): Promise<void> {\n const companionParent = this[CompanionParentModel];\n if (companionParent) {\n await companionParent.whenInitialized();\n }\n const { modelId, modelTypeName } = this;\n const context = KosContextManager.getContext(modelId);\n\n log.debug(`Initializing model ${modelTypeName} with id ${modelId}`);\n await executeDependentModelLifecycle(this, DependencyLifecycle.INIT);\n\n try {\n // Execute service requests for INIT lifecycle before user's init() method\n await this.serviceRequestManager?.executeForLifecycle(\n DependencyLifecycle.INIT\n );\n\n await this.modelData?.init?.(context);\n this.initialized = true;\n log.debug(`Model ${modelTypeName} with id ${modelId} initialized`);\n\n this.onlineLifecycleManager?.register();\n\n // Initialize FSM if configured for INIT lifecycle\n this.initializeStateMachineForLifecycle(DependencyLifecycle.INIT);\n\n this.registerSubscribers(DependencyLifecycle.INIT);\n\n // Create companions configured for INIT lifecycle\n this.createLifecycleCompanions(DependencyLifecycle.INIT);\n } catch (e) {\n log.error(`Model ${modelId} failed to initialize`, e);\n throw e;\n }\n }\n\n async registerSubscribers(lifecycle?: DependencyLifecycle) {\n log.debug(\n `registering subscribers in ${this.modelTypeName} with id ${this.modelId}`\n );\n\n this.subscriptionManager?.registerAll(lifecycle);\n }\n\n /**\n * The counterpart of `unload()` for a reload that keeps the instance: every\n * manager `unload()` disposed comes back, not only the subscriptions.\n * @internal\n */\n restoreAfterReload(): void {\n this.onlineLifecycleManager?.register();\n this.subscriptionManager?.registerAll();\n this.httpRouteManager?.registerAll();\n this.effectManager?.setup();\n kosAction(() => {\n this.loaded = true;\n });\n }\n\n /**\n * Initialize the state machine for a specific lifecycle phase.\n * Called from lifecycle hooks (init, load, ready, activate).\n * @internal\n */\n initializeStateMachineForLifecycle(lifecycle: DependencyLifecycle) {\n if (this.modelData) {\n initializeStateMachine(this.modelData, lifecycle);\n }\n }\n\n /**\n * Creates lifecycle-deferred companion models at the appropriate phase.\n * Called from lifecycle hooks (init, load, ready, activate, online).\n * @internal\n */\n private createLifecycleCompanions(lifecycle: DependencyLifecycle) {\n // Pass empty options object - companions get their data from parent\n this.modelManager.createLifecycleCompanions(this, {}, lifecycle);\n }\n\n /**\n * Runs on every transition to online, including each reconnect, so the\n * ONLINE dependencies and service requests are resolved and sent again\n * each time. A state machine with `initializeAt: ONLINE` starts once.\n */\n async online() {\n log.debug(`online model ${this.modelTypeName} with id ${this.modelId}`);\n this.registerSubscribers();\n await executeDependentModelLifecycle(this, DependencyLifecycle.ONLINE);\n\n // Execute service requests for ONLINE lifecycle before user's online() method\n await this.serviceRequestManager?.executeForLifecycle(\n DependencyLifecycle.ONLINE\n );\n\n const context = KosContextManager.getContext(this.modelId);\n await this.modelData?.online?.(context);\n\n // Initialize FSM if configured for ONLINE lifecycle\n this.initializeStateMachineForLifecycle(DependencyLifecycle.ONLINE);\n\n // Create companions configured for ONLINE lifecycle\n this.createLifecycleCompanions(DependencyLifecycle.ONLINE);\n }\n\n async offline() {\n log.debug(`offline model ${this.modelTypeName} with id ${this.modelId}`);\n this.subscriptionManager?.disposeAll();\n const context = KosContextManager.getContext(this.modelId);\n await this.modelData?.offline?.(context);\n }\n\n accept(visitor: IKosVisitor<IKosModel>) {\n visitor.visit(this);\n }\n getChildren(): IKosModel[] {\n return this.childResolver.resolve();\n }\n\n addCompanionModel(model: IKosModel<IKosDataModel>) {\n this.companionManager.add(model);\n }\n\n clearCompanionModels() {\n this.companionManager.clear();\n }\n}\n","// model-instantiator.ts\n\nimport type { DependencyLifecycle } from \"../types\";\nimport { enrichError } from \"../util/model-error-utils\";\nimport { logModelInstantiationError } from \"../util/error-logger\";\nimport { KosCompanionInstantiator } from \"./companion-instantiator\";\nimport { OptionsRequired } from \"./decorators/propKeys\";\nimport { KosModel, type IKosDataModel, type IKosModel } from \"./kosModel\";\nimport { KosLog } from \"./log\";\nimport type { KosModelCacheHandler } from \"./model-cache\";\nimport type { IKosRegistry } from \"./types\";\n\nconst log = KosLog.createLogger({ name: \"kos-model-instantiator\" });\n\n/**\n * Responsible for creating KOS model instances.\n * Delegates companion model creation to KosCompanionInstantiator.\n */\nexport class KosModelInstantiator {\n private companionInstantiator: KosCompanionInstantiator;\n\n constructor(\n private registry: IKosRegistry,\n private cache: KosModelCacheHandler\n ) {\n this.companionInstantiator = new KosCompanionInstantiator(\n registry,\n cache,\n this.createModelInstance.bind(this)\n );\n }\n\n createModelInstance<DataDef extends IKosDataModel>(\n typeId: string,\n id?: string,\n options: Record<string, any> = {}\n ): { model: IKosModel<DataDef>; data: DataDef } {\n const modelRegistry = this.registry.models[typeId];\n if (!modelRegistry) {\n const errorMessage = `No model registered for type ${typeId}`;\n log.error(errorMessage, {\n modelType: typeId,\n requestedId: id,\n providedOptions: options,\n availableModelTypes: Object.keys(this.registry.models),\n });\n throw enrichError(new Error(errorMessage), {\n modelType: typeId,\n modelId: id,\n operation: \"model instantiation - registry lookup\",\n options,\n metadata: {\n availableModelTypes: Object.keys(this.registry.models),\n },\n });\n }\n\n const modelId = modelRegistry.singleton ? typeId : id;\n this.cache.restoreFromDeleteCache(modelId);\n\n if (!this.cache.hasModel(modelId)) {\n log.debug(`Creating model instance: ${typeId} [${modelId}]`);\n\n // Validate options requirement before attempting creation\n const hasOptions = options && Object.keys(options).length > 0;\n const modelClass = modelRegistry.class || modelRegistry.create;\n const requiresOptions = modelClass?.prototype?.[OptionsRequired] === true;\n\n if (requiresOptions && !hasOptions) {\n const error = new Error(\n `Model ${typeId} requires options but none were provided`\n );\n logModelInstantiationError(error, {\n modelType: typeId,\n options,\n registryId: this.registry.alias || \"unknown\",\n });\n throw enrichError(error, {\n modelType: typeId,\n modelId,\n operation: \"model instantiation - options validation\",\n options,\n metadata: { requiresOptions: true, hasOptions: false },\n });\n }\n\n try {\n const dataInstance = modelRegistry.create\n ? modelRegistry.create({ modelTypeId: typeId, id: modelId, options })\n : new modelRegistry.class!(modelId, options);\n\n const model = new KosModel<DataDef>({\n modelTypeName: typeId,\n id: modelId,\n modelData: dataInstance,\n });\n\n this.cache.addModel(model);\n // Create companions without lifecycle specified (defaults to INIT phase)\n this._createCompanionModels(model, options);\n } catch (error) {\n logModelInstantiationError(error, {\n modelType: typeId,\n options,\n registryId: this.registry.alias || \"unknown\",\n });\n throw enrichError(error, {\n modelType: typeId,\n modelId,\n operation: \"model instantiation\",\n options,\n });\n }\n }\n\n const activeModel = this.cache.getModelById<DataDef>(modelId!);\n\n if (!activeModel) {\n log.error(`Model ${typeId} [${modelId}] not found in cache`);\n throw new Error(`Model ${typeId} [${modelId}] not found in cache`);\n }\n return { model: activeModel, data: activeModel.modelData };\n }\n\n /**\n * Creates companion models for a parent model, optionally filtered by lifecycle phase.\n * Delegates to KosCompanionInstantiator for all companion-related logic.\n *\n * @param model The parent model\n * @param options Options to pass to companion constructors\n * @param lifecycle Optional lifecycle filter - only create companions matching this phase\n */\n createCompanionModels(\n model: IKosModel,\n options: Record<string, any>,\n lifecycle?: DependencyLifecycle\n ) {\n this.companionInstantiator.createCompanionModels(model, options, lifecycle);\n }\n\n /**\n * @deprecated Use createCompanionModels instead\n * @private\n */\n private _createCompanionModels(\n model: IKosModel,\n options: Record<string, any>\n ) {\n this.createCompanionModels(model, options);\n }\n}\n","// model-registry.ts\n\nimport type { BaseKosModelRegistrationBean, ModelFactory } from \"../types\";\nimport { modelFactory } from \"../util\";\nimport type { IKosDataModel, IKosDataModelBuilder } from \"./kosModel\";\nimport { IKosRegistry, KosCompanionModelType } from \"./types/registration\";\n\nexport class KosModelRegistry {\n constructor(private _registry: IKosRegistry) {}\n\n get registry(): IKosRegistry {\n return this._registry;\n }\n getModelTypeRegistry(typeId: string) {\n const modelRegistry = this.registry.models[typeId];\n if (!modelRegistry)\n throw new Error(`No registration for model type ${typeId}`);\n return modelRegistry;\n }\n\n registerModel<T extends BaseKosModelRegistrationBean<any, any>>(reg: T) {\n const typeId = reg.type;\n if (!this.registry.models[typeId]) {\n this.registry.models = { ...this.registry.models, ...reg.registration };\n }\n }\n\n registerCompanionModel(\n typeId: string,\n companion: KosCompanionModelType<any>\n ) {\n this.registry.companionModels ??= {};\n this.registry.companionModels[typeId] ??= [];\n if (\n !this.registry.companionModels[typeId].some((c) => c.type === companion)\n ) {\n this.registry.companionModels[typeId].push({ type: companion });\n }\n }\n\n getModelSubscriptions(typeId: string) {\n return this.getModelTypeRegistry(typeId)?.subscriptions || {};\n }\n\n getDataModelBuilder<D, M extends IKosDataModel>(\n typeId: string\n ): IKosDataModelBuilder<D, M> {\n const builder = this.getModelTypeRegistry(typeId)?.builder;\n if (!builder) {\n throw new Error(`No builder found for model type ${typeId}`);\n }\n return builder;\n }\n\n getModelFactory<T extends IKosDataModel>(modelType: string): ModelFactory<T> {\n return modelFactory<T>(modelType);\n }\n}\n","/* eslint-disable max-len */\n\nimport {\n DependencyLifecycle,\n type BaseKosModelRegistrationBean,\n} from \"../types\";\nimport { modelFactory } from \"../util\";\nimport { isKosModelContainer } from \"../util/model-type-guards\";\nimport { ChildModels } from \"./decorators/propKeys\";\nimport { KosDependencyManager } from \"./dependency-manager\";\nimport { KosDeletionManager } from \"./kos-deletion-manager\";\nimport { IKosDataModel, IKosDataModelBuilder, IKosModel } from \"./kosModel\";\nimport { KosModelEvents, KosModelState } from \"./lifecycle\";\nimport { KosLog } from \"./log\";\nimport { KosModelCache } from \"./model-cache\";\nimport { clearModelHookCacheEntry } from \"./model/model-hook-cache\";\nimport { KosModelInstantiator } from \"./model-instantiator\";\nimport { KosModelRegistry } from \"./model-registry\";\nimport { IKosModelManager } from \"./types/kos-model-manager-types\";\nimport { IKosRegistry, type KosCompanionModelType } from \"./types/registration\";\n\nexport const MODEL_DELETION_DELAY = 10;\n\nconst log = KosLog.createLogger({ name: \"kos-model-manager\" });\n\nexport class KosModelManager implements IKosModelManager {\n private cache!: KosModelCache;\n private instantiator!: KosModelInstantiator;\n private dependencies: KosDependencyManager;\n private _registry!: KosModelRegistry;\n private constructor() {\n globalThis.kos = globalThis.kos || {};\n this.dependencies = new KosDependencyManager();\n globalThis.kos.modelManager = this;\n globalThis.kos.resolveKosModel = (modelId: string) => {\n const model = this.getModelById(modelId);\n if (model) {\n return model.modelData || {};\n }\n return undefined;\n };\n globalThis.kos.kosModelJson = (modelId: string) => {\n const model = this.getModelById(modelId);\n if (model) {\n return model.modelData.toJSON?.() || {};\n }\n return undefined;\n };\n\n globalThis.kos.kosModelDebug = (modelId: string) => {\n const model = this.getModelById(modelId);\n if (model) {\n return (model.modelData as any)?.debugState || {};\n }\n return undefined;\n };\n\n globalThis.kos.kmd = globalThis.kos.kosModelDebug;\n globalThis.kos.kmj = globalThis.kos.kosModelJson;\n }\n\n static create(registry: IKosRegistry, reset?: boolean) {\n const instance = this.getInstance(reset);\n instance._registry = new KosModelRegistry(registry);\n instance.cache = new KosModelCache(registry.preloadModels);\n instance.instantiator = new KosModelInstantiator(registry, instance.cache);\n return instance;\n }\n\n static getInstance(reset?: boolean): KosModelManager {\n if (!globalThis.kos?.modelManager || reset) {\n log.debug(\"Creating new instance of KosModelManager\");\n new this();\n }\n return globalThis.kos?.modelManager;\n }\n\n get registry() {\n return this._registry.registry;\n }\n\n /**\n * Retrieves the preloaded models from the registry. If the models have already been\n * preloaded, it returns the cached preloaded models. Otherwise, it initializes and\n * preloads the models based on the registry's `preloadModels` configuration.\n *\n * @returns An array of preloaded model instances.\n *\n * @remarks\n * - Logs debug information during the preloading process.\n * - Logs an error if returning cached preloaded models.\n * - Supports both string-based model keys and object-based model configurations.\n */\n get preloadedModels() {\n return this.cache.preload((modelKey) => {\n log.debug(`preloading ${modelKey}`);\n if (typeof modelKey === \"string\") {\n return this.createModelInstance(modelKey).model;\n } else {\n return this.createModelInstance(\n modelKey.modelType,\n modelKey.modelId,\n modelKey.options\n ).model;\n }\n });\n }\n\n get models() {\n return this.cache.models;\n }\n\n /**\n * Retrieves a model by its unique identifier.\n *\n * @template T - The type of the data model extending `IKosDataModel`.\n * @param id - The unique identifier of the model to retrieve.\n * @returns The model associated with the given ID as `IKosModel<T>`, or `undefined` if the model is marked for deletion.\n */\n getModelById<T extends IKosDataModel>(id: string): IKosModel<T> {\n return this.cache.getModelById(id) as IKosModel<T>;\n }\n\n /**\n * Adds a model to the manager. If a model with the same ID already exists,\n * it returns the existing model instead of adding the new one.\n *\n * @template T - The type of the data model extending `IKosDataModel`.\n * @param model - The model to be added, implementing `IKosModel<T>`.\n * @returns The active model, either the existing one with the same ID or the newly added model.\n */\n addModel<T extends IKosDataModel>(model: IKosModel<T>): IKosModel<T> {\n return this.cache.addModel(model) as IKosModel<T>;\n }\n\n /**\n * Removes a model from the manager and performs cleanup operations.\n *\n * This method traverses the model hierarchy, invoking the `accept` method\n * on each child model to allow for recursive processing. During traversal,\n * it performs the following actions:\n * - Calls the `offline` method on the model, if defined.\n * - Clears any companion models associated with the model.\n * - Deletes the model's context from the `KosContextManager`.\n * - Removes the model from the internal `_modelsById` and `_toDelete` maps.\n *\n * @param model - The model to be removed. Must implement the `IKosModel` interface.\n */\n removeModel(model: IKosModel): void {\n this.cache.removeModel(model.modelId);\n }\n\n /**\n * Checks if a model with the specified ID exists.\n *\n * @param modelId - The unique identifier of the model to check. Optional.\n * @returns `true` if the model ID is provided and a model with the given ID exists; otherwise, `false`.\n */\n hasModel(modelId?: string) {\n return this.cache.hasModel(modelId);\n }\n\n /**\n * Retrieves a list of models of a specific type that satisfy the provided filter criteria.\n *\n * @template T - The type of the data model extending `IKosDataModel`.\n * @param typeId - The identifier of the model type to filter by.\n * @param modelFilter - A callback function used to filter models. It receives a model of type `T` and should return `true` if the model passes the filter, or `false` otherwise.\n * @returns An array of models of type `T` that match the specified type and filter criteria.\n */\n getModelsByType<T extends IKosDataModel>(\n typeId: string,\n modelFilter: (model: T) => boolean\n ) {\n return Array.from(this.models)\n .filter((model) => model.modelTypeName === typeId)\n .filter((model) =>\n modelFilter ? modelFilter(model.modelData as T) : true\n )\n .map((model) => model.modelData as T);\n }\n\n /**\n * Retrieves the subscriptions associated with a specific model type.\n *\n * @param typeId - The unique identifier of the model type.\n * @returns An object containing the subscriptions for the specified model type,\n * or an empty object if the model type is not registered.\n */\n getModelSubscriptions(typeId: string) {\n return this._registry.getModelSubscriptions(typeId);\n }\n\n /**\n * Retrieves the data model builder for a specified model type.\n *\n * @template D - The type of the data used by the model.\n * @template M - The type of the data model that extends `IKosDataModel`.\n * @param typeId - The unique identifier for the model type.\n * @returns An instance of `IKosDataModelBuilder` for the specified model type,\n * or `undefined` if the model type is not registered.\n */\n getDataModelBuilder<D, M extends IKosDataModel>(\n typeId: string\n ): IKosDataModelBuilder<D, M> {\n return this._registry.getDataModelBuilder(typeId);\n }\n\n /**\n * Retrieves a model factory function for the specified model type.\n *\n * @template T - The type of the data model that extends `IKosDataModel`.\n * @param modelType - A string representing the type of the model.\n * @returns A factory function for creating instances of the specified model type.\n */\n getModelFactory<T extends IKosDataModel>(modelType: string) {\n return modelFactory<T>(modelType);\n }\n\n /**\n * Adds a dependency relationship between two models.\n *\n * This method establishes a \"uses\" relationship where the model identified\n * by `modelId` depends on the model identified by `dependencyId`. It ensures\n * that the dependency is not marked for deletion and restores it from the\n * delete cache if necessary. The relationship is then recorded in both the\n * `_usedByCache` and `_usesCache` for efficient lookup.\n *\n * @param modelId - The identifier of the model that depends on the dependency.\n * @param dependencyId - The identifier of the model being depended upon.\n */\n addDependency(modelId: string, dependencyId: string) {\n this.cache.restoreFromDeleteCache(dependencyId);\n this.dependencies.add(modelId, dependencyId);\n }\n\n /**\n * Removes a dependency relationship between two models.\n *\n * This method updates the internal caches to reflect that the specified\n * `modelId` no longer depends on the `dependencyId`. It removes the\n * `modelId` from the list of models that use the `dependencyId` and\n * removes the `dependencyId` from the list of dependencies used by the\n * `modelId`.\n *\n * @param modelId - The ID of the model that has the dependency.\n * @param dependencyId - The ID of the dependency to be removed.\n */\n removeDependency(modelId: string, dependencyId: string) {\n this.dependencies.remove(modelId, dependencyId);\n }\n\n /**\n * Reloads the specified model by its ID. If the model exists and is found\n * by its ID, it transitions the model to the RESETTING state using the\n * RESET event.\n *\n * @deprecated The reset route re-runs load() and ready() only and loses the\n * handlers registered at INIT or with no lifecycle. Models refresh through\n * `reload()`, driven by KOS Core.\n *\n * @param model - The data model to be reloaded. Must implement the `IKosDataModel` interface.\n * The `id` property of the model is used to locate the corresponding model.\n *\n * @returns A promise that resolves once the model has been transitioned, or does nothing\n * if the model ID is not provided or the model is not found.\n */\n async reloadModel(model: IKosDataModel) {\n if (model.id) {\n const kosModel = this.getModelById(model.id);\n if (kosModel) {\n await kosModel.fsm.transitionTo(\n KosModelEvents.RESET,\n KosModelState.RESETTING\n );\n }\n }\n }\n\n /**\n * Initiates the destruction process for a given model.\n *\n * This method checks if the model can be destroyed and, if so, schedules it for deletion.\n * The model is removed from the internal `_modelsById` map and added to the `_toDelete` map.\n * A deletion task is then queued with a delay, during which the model will be destroyed.\n *\n * @param model - The model to be destroyed. Must implement the `IKosDataModel` interface.\n * @throws {Error} If the model does not have a valid `id`.\n */\n async initiateDestroyModel(model: IKosDataModel) {\n if (!model.id) throw new Error(\"Model ID is required\");\n if (!this.dependencies.canDestroy(model.id)) return;\n\n const kosModel = this.getModelById(model.id);\n if (kosModel) {\n this.cache.markForDeletion(kosModel);\n KosDeletionManager.addToDeletionQueue(\n model.id,\n setTimeout(() => this.destroyModel(kosModel), MODEL_DELETION_DELAY)\n );\n }\n }\n\n /**\n * Destroys the specified model if it meets the criteria for destruction.\n *\n * @param model - The model to be destroyed, implementing the `IKosModel` interface.\n *\n * @remarks\n * This method checks if the model has a valid `modelId` and if it can be destroyed\n * by invoking the `canDestroyModel` method. If the conditions are met, it performs\n * the following actions:\n * 1. Calls the `unload` method on the model, if it exists.\n * 2. Removes the model from the manager using the `removeModel` method.\n * 3. Releases the model's children (decorated children, container members,\n * companions) from the manager the same way, recursively.\n *\n * @throws This method does not explicitly throw errors, but any errors occurring\n * during the `unload` or `removeModel` operations will propagate to the caller.\n */\n async destroyModel(model: IKosModel) {\n if (model?.modelId && this.dependencies.canDestroy(model.modelId)) {\n // Resolved before unload(), which is what walks the children's own unload().\n const children = model.getChildren();\n await model.unload?.();\n this.removeModel(model);\n this.dependencies.removeAll(model.modelId);\n clearModelHookCacheEntry(model.modelId);\n this.emptyContainersOf(model);\n children.forEach((child) => this.releaseUnloadedChild(child));\n }\n }\n\n // Each container held as a child is emptied with one bulk removal, so its\n // indexes are recalculated once and its per-member observers are released.\n private emptyContainersOf(model: IKosModel) {\n const data = model.modelData as any;\n const childKeys = Object.keys(data?.[ChildModels] || {});\n for (const key of childKeys) {\n const container = data[key];\n if (!isKosModelContainer(container)) continue;\n const ids = container.data.map((member: IKosDataModel) => member.id);\n if (ids.length) container.removeAll(ids);\n }\n }\n\n // A destroyed model's unload() has already unloaded its children; only the\n // registry half of destruction is left for them. Never walks dependencies:\n // a child something else depends on stays registered, and a child already\n // removed or queued for deletion is left to that path.\n private releaseUnloadedChild(child: IKosModel) {\n const { modelId } = child;\n if (!this.getModelById(modelId)) return;\n if (!this.dependencies.canDestroy(modelId)) return;\n const grandchildren = child.getChildren();\n this.removeModel(child);\n this.dependencies.removeAll(modelId);\n clearModelHookCacheEntry(modelId);\n this.emptyContainersOf(child);\n grandchildren.forEach((grandchild) =>\n this.releaseUnloadedChild(grandchild)\n );\n }\n\n /**\n * Creates an instance of a model based on the specified type ID and optional model ID.\n * If the model already exists, it retrieves the existing instance; otherwise, it creates a new one.\n *\n * @template DataDef - The type of the data model, extending `IKosDataModel`.\n * @param typeId - The unique identifier for the type of model to create.\n * @param id - An optional unique identifier for the specific model instance. If not provided,\n * the `typeId` is used for singleton models.\n * @param options - An optional record of additional options to pass to the model creation process.\n * @returns An object containing the created or retrieved model instance and its associated data.\n */\n createModelInstance<DataDef extends IKosDataModel>(\n typeId: string,\n id?: string,\n options: Record<string, any> = {}\n ) {\n return this.instantiator.createModelInstance<DataDef>(typeId, id, options);\n }\n\n /**\n * Creates lifecycle-deferred companion models for a parent model.\n * Used by KosModel lifecycle hooks to instantiate companions at the appropriate phase.\n *\n * @param model The parent model\n * @param options Options to pass to companion constructors\n * @param lifecycle The lifecycle phase to create companions for\n * @internal\n */\n createLifecycleCompanions(\n model: IKosModel,\n options: Record<string, any>,\n lifecycle: DependencyLifecycle\n ) {\n this.instantiator.createCompanionModels(model, options, lifecycle);\n }\n\n /**\n * Registers a companion model for a specific type identifier.\n *\n * This method ensures that the companion model is added to the registry\n * for the given `typeId`. If a companion model of the same type already\n * exists for the `typeId`, it will not be added again.\n *\n * @param typeId - The unique identifier for the type to which the companion model belongs.\n * @param companionRegistration - The companion model type to register.\n */\n registerCompanionModel(\n typeId: string,\n companionRegistration: KosCompanionModelType<any>\n ) {\n this._registry.registerCompanionModel(typeId, companionRegistration);\n }\n\n /**\n * Registers a new model type in the model manager if it is not already registered.\n *\n * @template T - A type that extends `BaseKosModelRegistrationBean` with specific type and registration details.\n * @param reg - The registration object containing the type identifier and registration details for the model.\n *\n * @remarks\n * - If the model type is not already present in the registry, it logs the registration\n * and updates the registry with the new model type.\n * - The `type` property of the registration object is used as the unique identifier for the model type.\n */\n registerModel<T extends BaseKosModelRegistrationBean<any, any>>(reg: T) {\n this._registry.registerModel(reg);\n }\n}\n","import log from \"loglevel\";\nimport { runInAction } from \"mobx\";\nimport {\n action,\n createMachine,\n immediate,\n interpret,\n invoke,\n state,\n transition,\n} from \"robot3\";\nimport type { IKosCoreManager } from \"../kosCore\";\n\nexport enum KosCoreState {\n CREATING = `creating`,\n CREATED = `created`,\n INITIALIZING = `initializing`,\n INITIALIZED = `initialized`,\n LOADING = `loading`,\n LOADED = `loaded`,\n ONLINE = `online`,\n READYING = `readying`,\n READY = `ready`,\n OFFLINE = `offline`,\n UNLOADING = `unloading`,\n UNLOADED = `unloaded`,\n RELOADING = `reloading`,\n FAILED = `failed`,\n}\n\nexport enum KosCoreEvents {\n CREATE = `create`,\n INITIALIZE = `init`,\n READY = `ready`,\n GO_ONLINE = `go_online`,\n GO_OFFLINE = `go_offline`,\n UNLOAD = `unload`,\n RELOAD = `reload`,\n}\n\nexport interface KosOn {\n [k: string]: string;\n}\n\nexport interface KosInvoke<Context> {\n id: string;\n src: (context: Context) => Promise<any>;\n onDone: {\n target: string;\n };\n}\nexport interface KosLifecycleState {\n on: KosOn;\n}\nexport interface KosLifecycleStateContainer<Context> {\n [k: string]: {\n initial?: string;\n states?: KosLifecycleStateContainer<Context>;\n on?: KosOn;\n invoke?: KosInvoke<Context>;\n };\n}\n\nexport interface KosLifecycle<Context = any> {\n id: string;\n initial: string;\n states: KosLifecycleStateContainer<Context>;\n context: Context;\n}\n\n/** Logs a lifecycle step's rejection before re-throwing it. */\nconst reportFailure = async <T>(\n step: KosCoreState,\n run: () => Promise<T>\n): Promise<T> => {\n try {\n return await run();\n } catch (error) {\n // Interpolated: an Error passed as a log argument serializes to `{}`.\n const detail =\n error instanceof Error\n ? error.stack ?? `${error.name}: ${error.message}`\n : String(error);\n log.error(`KOS Core lifecycle step \"${step}\" failed. ${detail}`);\n throw error;\n }\n};\n\nexport const coreFsm = (core: IKosCoreManager) => {\n const onlineMachine = createMachine(KosCoreState.OFFLINE, {\n [KosCoreState.ONLINE]: state(\n transition(\n KosCoreEvents.GO_OFFLINE,\n KosCoreState.OFFLINE,\n action(() => {\n core.offline!();\n runInAction(() => {\n core.isOnline = false;\n });\n })\n )\n ),\n [KosCoreState.OFFLINE]: state(\n transition(\n KosCoreEvents.GO_ONLINE,\n KosCoreState.ONLINE,\n action(() => {\n core.online!();\n runInAction(() => {\n core.isOnline = true;\n });\n })\n )\n ),\n });\n const online = interpret(onlineMachine, (_service) =>\n log.debug(_service.machine.current)\n );\n\n // Without this, a rejected invoke leaves the machine parked in the state\n // that threw, indistinguishable from one still running.\n const failed = transition(\n `error`,\n KosCoreState.FAILED,\n action(() => {\n runInAction(() => {\n core.status = KosCoreState.FAILED;\n });\n })\n );\n\n const machine = createMachine({\n [KosCoreState.CREATING]: state(\n transition(KosCoreEvents.CREATE, KosCoreState.CREATED)\n ),\n [KosCoreState.CREATED]: state(immediate(KosCoreState.INITIALIZING)),\n [KosCoreState.INITIALIZING]: invoke(\n () => reportFailure(KosCoreState.INITIALIZING, () => core.init!()),\n transition(`done`, KosCoreState.INITIALIZED),\n failed\n ),\n [KosCoreState.INITIALIZED]: state(immediate(KosCoreState.LOADING)),\n [KosCoreState.LOADING]: invoke(\n () => reportFailure(KosCoreState.LOADING, () => core.load!()),\n transition(`done`, KosCoreState.LOADED),\n failed\n ),\n [KosCoreState.LOADED]: state(\n immediate(KosCoreState.READYING),\n transition(KosCoreEvents.UNLOAD, KosCoreState.UNLOADING)\n ),\n\n [KosCoreState.READYING]: invoke(\n () => reportFailure(KosCoreState.READYING, () => core.ready!()),\n transition(\n `done`,\n KosCoreState.READY,\n action(() => {\n runInAction(() => {\n core.status = KosCoreState.READY;\n });\n })\n ),\n failed\n ),\n [KosCoreState.RELOADING]: invoke(\n () => reportFailure(KosCoreState.RELOADING, () => core.reload!()),\n transition(`done`, KosCoreState.LOADING),\n failed\n ),\n [KosCoreState.FAILED]: state(),\n [KosCoreState.READY]: state(\n transition(KosCoreEvents.RELOAD, KosCoreState.RELOADING),\n transition(\n KosCoreEvents.UNLOAD,\n KosCoreState.UNLOADED,\n action(core.unload.bind(core))\n ),\n transition(\n KosCoreEvents.GO_ONLINE,\n KosCoreState.READY,\n action(() => {\n online.send(KosCoreEvents.GO_ONLINE);\n })\n ),\n transition(\n KosCoreEvents.GO_OFFLINE,\n KosCoreState.READY,\n action(() => {\n online.send(KosCoreEvents.GO_OFFLINE);\n })\n )\n ),\n\n [KosCoreState.UNLOADED]: state(),\n });\n\n const service = interpret(machine, (_service) =>\n log.debug(_service.machine.current)\n );\n\n return { service, online };\n};\n","import { makeAutoObservable, when } from \"mobx\";\nimport { DependencyLifecycle } from \"../types\";\nimport { CompanionParentModel } from \"./decorators\";\nimport { KosModelManager } from \"./kosModelManager\";\nimport {\n IKosServiceTransport,\n WebSocketEvents,\n WebSocketTransport,\n} from \"./transport/webSocketTransport\";\nimport { IKosRegistry } from \"./types/registration\";\n\nimport { runInAction as kosAction } from \"mobx\";\nimport { EventBus } from \"../../common\";\nimport { getQueryParams } from \"../util/get-query-params\";\nimport \"../util/kos-config-init\";\nimport { ExtensionManager } from \"./extension\";\nimport { SelfManagedReload } from \"./decorators/kos-reload-aware\";\nimport { IKosModel, ReloadAware, UnloadAware } from \"./kosModel\";\nimport {\n KosCoreEvents,\n KosCoreState,\n coreFsm,\n} from \"./lifecycle/kosCoreLifecycle\";\nimport { KosLog } from \"./log\";\nimport { RegistrationManager } from \"./registration\";\nimport { IKosModelManager } from \"./types/kos-model-manager-types\";\n\nconst log = KosLog.createLogger({ name: \"kos-core\" });\n\ndeclare global {\n interface Window {\n KosCore: IKosCoreManager;\n }\n}\n\nconst getConnectionAlias = () => {\n const params = getQueryParams();\n const alias = (params as any)?.alias;\n const envAlias = process.env.KOS_CONNECTION_ALIAS;\n return alias || envAlias || undefined;\n};\n\nconst resolveAliasTemplate = (alias: string) =>\n alias.replace(\"{{TIMESTAMP}}\", Date.now().toString());\n\nconst getDefaultProtocol = () => {\n const defaultProtocol = window.location.protocol;\n\n const params = getQueryParams();\n const hostUrl = (params as any)?.host;\n let protocol;\n try {\n const _url = new URL(hostUrl);\n protocol = _url.protocol === \"https:\" ? \"wss://\" : \"ws://\";\n } catch {\n // ignore errors\n }\n\n const result = protocol\n ? protocol\n : defaultProtocol === \"https:\"\n ? \"wss://\"\n : \"ws://\";\n return result;\n};\n\nconst getDefaultHost = () => {\n const defaultHost = window.location.hostname;\n const envHost = process.env.KOS_HOST;\n const params = getQueryParams();\n const hostUrl = (params as any)?.host;\n let host;\n try {\n const _url = new URL(hostUrl);\n host = _url.hostname;\n } catch {\n // ignore errors\n }\n\n const result = host ?? envHost ?? defaultHost;\n return result;\n};\n\nconst getDefaultPort = () => {\n const defaultPort = window.location.port;\n const envPort = process.env.KOS_PORT;\n const params = getQueryParams();\n const hostUrl = (params as any)?.host;\n let port;\n try {\n const _url = new URL(hostUrl);\n port = _url.port;\n } catch {\n // ignore errors\n }\n\n const result = port ?? envPort ?? defaultPort;\n return result;\n};\n\nconst rejectAfterDelay = (\n ms: number,\n model: IKosModel\n): { promise: Promise<void>; cancel: () => void } => {\n let timeoutId: ReturnType<typeof setTimeout>;\n\n const promise = new Promise<void>((_, reject) => {\n timeoutId = setTimeout(() => {\n if (model) {\n KosLog.error(\n `Model ${model.modelId} - ${model.modelTypeName} preloading - timed out after ${ms}ms`\n );\n } else {\n KosLog.error(`KOS Core preloading timed out after ${ms}ms`);\n }\n reject(\n new Error(\n `Model ${model?.modelId} - ${model?.modelTypeName} - timed out after ${ms}ms`\n )\n );\n }, ms);\n });\n\n const cancel = () => {\n if (timeoutId) clearTimeout(timeoutId);\n };\n\n return { promise, cancel };\n};\nconst isReloadable = (model: any): model is ReloadAware =>\n typeof model.reload === \"function\";\n\nconst isSelfManagedReload = (model: any): boolean => !!model[SelfManagedReload];\n\nconst isUnloadable = (model: any): model is UnloadAware =>\n typeof model.unload === \"function\";\nexport interface IKosCoreLifecycle {\n /**\n * Starts the lifecycle state machine. Idempotent; called by `create()` once\n * the core has a model manager.\n */\n startLifecycle(): void;\n\n /**\n * lifecycle function to initialize the core and provide initial values that\n * will be used by the system. For example, loading the logger, setting up\n * internationialization or performing any capability validation would occur here\n */\n init(): Promise<void>;\n\n load(): Promise<void>;\n\n unload(): Promise<void>;\n\n ready(): Promise<void>;\n\n online(): Promise<void>;\n\n offline(): Promise<void>;\n\n whenReady(): Promise<void>;\n\n reload(): Promise<void>;\n\n isReady: boolean;\n}\nexport interface IKosWebSocketTransportContainer {\n transport: IKosServiceTransport;\n connectionAlias?: string;\n}\nexport interface IKosModelManagerContainer {\n status: KosCoreState;\n isOnline: boolean;\n onlineStatus: boolean;\n modelManager: IKosModelManager;\n}\n\nexport type IKosCoreManager = IKosCoreLifecycle &\n IKosModelManagerContainer &\n IKosWebSocketTransportContainer & { reloading: boolean };\n\nexport enum AuthState {\n LOGGED_IN = \"logged_in\",\n LOGGED_OUT = \"logged_out\",\n}\nexport class KosCore implements IKosCoreManager {\n fsmService: ReturnType<typeof coreFsm>;\n\n private static _instance: IKosCoreManager;\n\n status: KosCoreState;\n\n private initialized: boolean;\n\n private loaded: boolean;\n\n private _transport: IKosServiceTransport;\n\n public modelManager!: IKosModelManager;\n\n public authState: AuthState;\n public isOnline: boolean;\n\n private _reloading: boolean;\n private _unloading: boolean;\n private lifecycleStarted = false;\n connectionAlias?: string;\n\n private constructor(connectionAlias?: string) {\n this.initialized = false;\n this.connectionAlias = connectionAlias;\n this.loaded = false;\n this.isOnline = false;\n this.status = KosCoreState.CREATED;\n this.authState = AuthState.LOGGED_OUT;\n this._reloading = false;\n this._unloading = false;\n makeAutoObservable(this);\n\n EventBus.subscribe(\"token\", (data) => {\n if (data) {\n this.transport.token = data.body;\n }\n });\n\n // Connection changes reach every model through its online lifecycle\n // manager and its own online machine, which runs offline()/online() once\n // and owns onlineStatus. Calling the hooks directly here would run them a\n // second time and leave the status behind.\n EventBus.subscribe(WebSocketEvents.DISCONNECTED, () => {\n this.fsmService.service.send(KosCoreEvents.GO_OFFLINE);\n });\n\n EventBus.subscribe(WebSocketEvents.CONNECTED, async () => {\n await this.whenReady();\n // register() is idempotent; it covers a manager an earlier unload dropped.\n this.modelManager.models.forEach((model) =>\n model.onlineLifecycleManager?.register()\n );\n this.fsmService.service.send(KosCoreEvents.GO_ONLINE);\n });\n EventBus.subscribe(\"/studioServer/auth/LOGGED_IN\", () => {\n kosAction(() => {\n this.authState = AuthState.LOGGED_IN;\n this.transport.authorized = true;\n });\n this.fsmService.service.send(KosCoreEvents.RELOAD);\n });\n EventBus.subscribe(\"/studioServer/auth/LOGIN_REQUIRED\", () => {\n kosAction(() => {\n this.authState = AuthState.LOGGED_OUT;\n this.transport.authorized = false;\n });\n });\n\n EventBus.subscribe(WebSocketEvents.RELOAD, () => {\n log.warn(\"WebSocket requested reload\");\n this.fsmService.service.send(KosCoreEvents.RELOAD);\n });\n\n EventBus.subscribe(\"/studio/project/reload\", () => {\n log.warn(\"Project requested reload\");\n this.fsmService.service.send(KosCoreEvents.RELOAD);\n });\n\n // EventBus.subscribe(\"/studioServer/auth/LOGGED_OUT\", () => {\n // this.fsmService.service.send(KosCoreEvents.UNLOAD);\n // });\n const ws = WebSocketTransport.getInstance();\n\n const host = getDefaultHost();\n const port = getDefaultPort();\n const protocol = getDefaultProtocol();\n ws.host = host;\n\n ws.port = Number.parseInt(port);\n\n ws.protocol = protocol;\n if (process.env.KOS_ALLOW_ANONYMOUS === \"true\") {\n ws.authorized = true;\n }\n\n const alias = getConnectionAlias() ?? connectionAlias;\n if (alias) {\n ws.alias = resolveAliasTemplate(alias);\n }\n\n this._transport = ws.init();\n this.fsmService = coreFsm(this);\n }\n\n /**\n * Registers `connectionAlias` on a core whose transport has no alias yet:\n * the alias frame goes out now on an open connection, or first thing when\n * the connection opens, and every reconnect carries it. A transport that\n * already has an alias keeps it.\n */\n private applyConnectionAlias(connectionAlias: string): void {\n if (this._transport.alias) {\n if (this.connectionAlias && this.connectionAlias !== connectionAlias) {\n log.warn(\n `Connection alias ${connectionAlias} ignored; the connection already uses ${this._transport.alias}`\n );\n }\n return;\n }\n this.connectionAlias = connectionAlias;\n const alias = resolveAliasTemplate(connectionAlias);\n this._transport.alias = alias;\n const frame = `type:kos.addr.alias\\nalias:${alias}\\n\\n`;\n const socket = this._transport.socket;\n if (socket?.connectionEstablished) {\n socket.socket.send(frame);\n } else {\n socket?.addOfflineMessage(frame);\n }\n }\n\n startLifecycle() {\n if (this.lifecycleStarted) {\n return;\n }\n this.lifecycleStarted = true;\n this.fsmService.service.send(KosCoreEvents.CREATE);\n }\n\n get onlineStatus() {\n return this.isOnline && !this._reloading && !this._unloading;\n }\n get reloading() {\n return this._reloading;\n }\n\n get unloading() {\n return this._unloading;\n }\n async reload(): Promise<void> {\n const currentTime = Date.now();\n if (this._reloading) {\n log.info(\"reload already in progress\");\n return;\n }\n this._reloading = true;\n log.warn(\"reloading KOS Core\");\n log.warn(\"reloading preloaded models\");\n const modelManager = this.modelManager;\n for (const model of modelManager.preloadedModels) {\n if (isReloadable(model.modelData)) {\n if (isSelfManagedReload(model.modelData)) {\n log.info(`skipping self-managed model ${model.modelId}`);\n continue;\n }\n log.info(`reloading model ${model.modelId}`);\n await this.reloadModel(model, model.modelData);\n log.info(`reloading model ${model.modelId} complete`);\n }\n }\n\n for (const model of modelManager.models) {\n // only reload models that are not preloaded\n if (\n !modelManager.preloadedModels.includes(model) &&\n isReloadable(model.modelData)\n ) {\n if (isSelfManagedReload(model.modelData)) {\n log.info(`skipping self-managed model ${model.modelId}`);\n continue;\n }\n log.warn(`reloading model ${model.modelId}`);\n await this.reloadModel(model, model.modelData);\n }\n }\n const elapsed = Date.now() - currentTime;\n setTimeout(() => {\n kosAction(() => {\n log.warn(\"reloading KOS Core complete\");\n this._reloading = false;\n });\n }, 1000 - elapsed);\n }\n\n // unload() must finish before reload() starts, and whatever it disposed must\n // come back afterwards; the data model's reload() only refreshes data.\n private async reloadModel(\n model: IKosModel,\n data: ReloadAware\n ): Promise<void> {\n await model.unload?.();\n await data.reload();\n model.restoreAfterReload?.();\n }\n\n async online(): Promise<void> {\n log.debug(\"KOS Core going online\");\n await this._transport.whenReady();\n log.debug(\"KOS Transport Ready. Calling online() for models\");\n EventBus.publish(\"/kosCore/online\", \"/kosCore/online\");\n console.timeEnd(\"kosCore:startup\");\n }\n async offline(): Promise<void> {\n log.debug(\"KOS Core going offline\");\n EventBus.publish(\"/kosCore/offline\", \"/kosCore/offline\");\n }\n\n async unload(): Promise<void> {\n log.debug(\"Unloading KOS Core\");\n const currentTime = Date.now();\n this._unloading = true;\n log.debug(\"unloading KOS Core\");\n const modelManager = this.modelManager;\n for (const model of modelManager.models) {\n if (isUnloadable(model.modelData)) {\n model.unload?.();\n }\n }\n const elapsed = Date.now() - currentTime;\n setTimeout(() => {\n kosAction(() => {\n this._unloading = false;\n });\n }, 1000 - elapsed);\n }\n\n async whenReady() {\n await when(() => this.status === KosCoreState.READY);\n }\n async ready(): Promise<void> {\n log.debug(\"Readying KOS Core\");\n await this._transport.whenReady();\n log.debug(\"KOS Transport ready. Preloading models\");\n\n if (!this.modelManager) {\n throw new Error(\n \"KOS Core reached ready() with no model manager. Its lifecycle was \" +\n \"started without a registry.\"\n );\n }\n\n const promises = this.modelManager.preloadedModels.map((model) => {\n return {\n modelId: model.modelId,\n model,\n promise: model.whenReady!(),\n };\n });\n log.debug(`Preloaded ${promises.length} models`);\n\n const settled = await Promise.allSettled(\n promises.map((promise) => {\n const { promise: timeoutPromise, cancel: timeoutCancel } =\n rejectAfterDelay(5000, promise.model);\n Promise.race([\n promise.promise.then(() => {\n timeoutCancel();\n }),\n timeoutPromise,\n ]);\n })\n );\n const failed = settled.filter((p) => p.status === \"rejected\");\n if (failed.length) {\n log.error(\n `There were ${failed.length} failed models on model preloading`\n );\n\n throw Error(\n `There were ${failed.length} failed models on model preloading`\n );\n }\n\n log.debug(`leaving kos-core ready() `);\n }\n\n get isReady() {\n return this.status === KosCoreState.READY;\n }\n set transport(transport: IKosServiceTransport) {\n this._transport = transport;\n }\n get transport() {\n return this._transport;\n }\n\n get coreInitialized() {\n return this.initialized;\n }\n\n get modelsLoaded() {\n return this.loaded;\n }\n\n async init(): Promise<void> {\n log.debug(\"entering kos-core init()\");\n\n console.time(\"kosCore:startup\");\n console.time(\"kosCore:init\");\n await this._transport.whenReady();\n\n this.initialized = true;\n log.debug(\"initialized - leaving kos-core init()\");\n console.timeEnd(\"kosCore:init\");\n }\n\n async load(): Promise<void> {\n log.debug(\"entering kos-core load()\");\n console.time(\"kosCore:load\");\n\n this.loaded = true;\n log.debug(\"loaded - leaving kos-core load()\");\n console.timeEnd(\"kosCore:load\");\n }\n\n public static create(\n registry: IKosRegistry,\n reset?: boolean,\n connectionAlias?: string\n ) {\n const instance = this.getInstance({ reset, connectionAlias });\n\n if (registry.extensions?.dataMapper) {\n Object.keys(registry.extensions.dataMapper).forEach((key) => {\n const dataMapper = registry.extensions?.dataMapper?.[key];\n if (dataMapper) {\n if (Array.isArray(dataMapper)) {\n dataMapper.forEach((mapper) => {\n ExtensionManager.dataMapper.registerDataMapper(key, mapper);\n });\n } else {\n ExtensionManager.dataMapper.registerDataMapper(key, dataMapper);\n }\n }\n });\n }\n\n if (registry.extensions?.propertyMapper) {\n Object.keys(registry.extensions.propertyMapper).forEach((key) => {\n const propertyMapper = registry.extensions?.propertyMapper?.[key];\n if (propertyMapper) {\n ExtensionManager.propertyMapper.registerPropertyMapper(\n key,\n propertyMapper\n );\n }\n });\n }\n\n if (registry.extensions?.contextLoader) {\n Object.keys(registry.extensions.contextLoader).forEach((key) => {\n const loader = registry.extensions?.contextLoader?.[key];\n if (loader) {\n ExtensionManager.loader.registerLoader(key, loader);\n }\n });\n }\n\n RegistrationManager.model.getAll().forEach(([, value]) => {\n registry.models = { ...registry.models, ...value.registration };\n });\n\n registry.models = {\n ...registry.models,\n ...RegistrationManager.model.getLegacyModels(),\n };\n\n RegistrationManager.companion.getAll().forEach(([key, value]) => {\n registry.companionModels = { ...registry.companionModels };\n registry.companionModels[key] = registry.companionModels[key] || [];\n for (const companion of value) {\n // Extract lifecycle from companion model decorator if it's a string type\n let lifecycle: DependencyLifecycle | undefined;\n if (typeof companion === \"string\") {\n const companionModelReg = registry.models[companion];\n if (companionModelReg?.class) {\n const companionMetadata =\n companionModelReg.class.prototype[CompanionParentModel];\n lifecycle = companionMetadata?.lifecycle;\n }\n }\n registry.companionModels[key].push({ type: companion, lifecycle });\n }\n });\n\n RegistrationManager.model.getPreloadModels().forEach((preload) => {\n if (registry.preloadModels.includes(preload)) {\n return;\n }\n registry.preloadModels.push(preload);\n });\n const modelManager = KosModelManager.create(registry, reset);\n instance.modelManager = modelManager;\n // ready() dereferences the model manager, so the machine cannot start\n // before it is attached.\n instance.startLifecycle();\n return instance;\n }\n\n /**\n * Returns the process-wide core, constructing it on first use or when\n * `reset` is set.\n *\n * `connectionAlias` applies to an existing core too, provided its transport\n * has no alias yet: registering a model reaches this method, so a\n * registration chain can construct the core before the alias is known.\n */\n public static getInstance(data?: {\n reset?: boolean;\n connectionAlias?: string;\n }): IKosCoreManager {\n this._instance = window.KosCore as any;\n // Do you need arguments? Make it a regular static method instead.\n if (!this._instance || data?.reset) {\n // Inert until create() starts its lifecycle: callers reading isReady\n // reach here before any registry exists.\n window.KosCore = new this(data?.connectionAlias) as any;\n this._instance = window.KosCore as any;\n } else if (data?.connectionAlias && this._instance instanceof KosCore) {\n this._instance.applyConnectionAlias(data.connectionAlias);\n }\n return this._instance;\n }\n}\n","import { KosCore } from \"../core/kosCore\";\nimport { IKosDataModel, IKosModel, IKosVisitor } from \"../core/kosModel\";\nimport { KosLog } from \"../core/log\";\n\nconst log = KosLog.createLogger({\n name: \"kos-model-visitor\",\n group: \"kos-ui-core\",\n});\n\n/**\n * Represents a base class for visiting and processing Kos data models.\n *\n * @abstract\n * @implements IKosVisitor<IKosModel>\n * @category Core\n * @kosService core.kos-model\n * @kosApiLevel 2\n */\nexport abstract class KosModelVisitor implements IKosVisitor<IKosModel> {\n /**\n * A set to keep track of visited model IDs to prevent redundant visits.\n */\n visitedModels: Set<string> = new Set();\n\n /**\n * Initializes a new instance of the KosModelVisitor class.\n */\n constructor() {\n this.visitedModels = new Set();\n }\n\n /**\n * Starts the visiting process from a root Kos data model.\n *\n * @param rootModel - The root Kos data model to start visiting from.\n * @throws An error if the rootModel does not have an ID or if it cannot be found.\n */\n start(rootModel: IKosDataModel): void {\n if (rootModel.id === undefined) {\n throw new Error(\"rootModel must have an id\");\n }\n\n const kosModel = KosCore.getInstance().modelManager.getModelById(\n rootModel.id\n );\n\n if (!kosModel) {\n throw new Error(`Could not find rootModel with id: ${rootModel.id}`);\n }\n\n this.visitedModels.clear();\n kosModel.accept?.(this);\n }\n\n /**\n * Visits and processes a Kos model.\n *\n * @param model - The Kos model to visit and process.\n */\n visit(model: IKosModel): void {\n if (this.visitedModels.has(model.modelId)) {\n log.info(`model ${model.modelId} already visited`);\n return;\n }\n\n // Call the visitModel method to allow custom processing of the model.\n const stopVisiting = !!this.visitModel(model.modelData, this);\n\n this.visitedModels.add(model.modelId);\n\n if (stopVisiting) {\n return;\n }\n\n // Visit and process the children of the current model.\n model.getChildren?.().forEach((child) => {\n child.accept?.(this);\n });\n }\n\n /**\n * Abstract method to visit and process a Kos data model.\n *\n * @param model - The Kos data model to visit and process.\n * @param context - The KosModelVisitor instance for context.\n * @returns `true` to stop visiting further models, or `false` or `undefined` to continue visiting.\n */\n abstract visitModel<T extends IKosDataModel = IKosDataModel>(\n model: T,\n context: KosModelVisitor\n ): boolean | void;\n}\n","import { registerExtensionPoint } from \"../core/extension\";\nimport { KosLog } from \"../core/log\";\n\n/**\n * @kosService core.utils\n * @kosApiLevel 12\n */\nexport const EXTENSION_FEATURE_FLAG_RESOLVER = \"featureFlagResolver\";\n/**\n * @kosService core.utils\n */\nexport type FlagResolver<T = any> = (input: T) => Promise<string[]>;\nconst flagResolvers = new Map<string, FlagResolver<any>[]>();\nregisterExtensionPoint(EXTENSION_FEATURE_FLAG_RESOLVER, {\n register: (id: string, mapper: FlagResolver) => {\n if (!flagResolvers.has(id)) {\n flagResolvers.set(id, []);\n }\n flagResolvers.get(id)?.push(mapper);\n },\n execute: async <T>(id: string, input: T) => {\n const resolver = flagResolvers.get(id);\n if (!resolver) {\n return [];\n }\n const promises = resolver.map((m) => m(input));\n const results = await Promise.allSettled(promises);\n const paths = results\n\n .map((r) => {\n if (r.status === \"fulfilled\") {\n return r.value;\n } else {\n KosLog.info(`Feature flag resolver ${id} failed: ${r.reason}`);\n return [];\n }\n })\n .flat();\n const uniquePaths = Array.from(new Set(paths)).reduce<FeatureFlags>(\n (acc, path) => {\n acc[path] = true;\n return acc;\n },\n {}\n );\n\n KosFeatureFlags.updateFlags(uniquePaths);\n return Object.keys(uniquePaths) as string[];\n },\n});\ntype FeatureFlags = Record<string, boolean>;\n/**\n * @kosService core.utils\n * @kosApiLevel 12\n */\nexport const LOADER_FEATURE_FLAG = \"kos.loader.featureFlag\";\n/**\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport class FeatureFlagService {\n private flags: Record<string, boolean> = {};\n\n constructor(initialFlags: FeatureFlags = {}) {\n this.flags = initialFlags;\n }\n\n // Check if a feature is enabled\n isFeatureEnabled(flag: string): boolean {\n return !!this.flags[flag];\n }\n\n // Enable a feature\n enableFeature(flag: string): void {\n this.flags[flag] = true;\n }\n\n // Disable a feature\n disableFeature(flag: string): void {\n this.flags[flag] = false;\n }\n\n // Toggle a feature\n toggleFeature(flag: string): void {\n this.flags[flag] = !this.flags[flag];\n }\n\n // Update multiple features at once\n updateFlags(newFlags: FeatureFlags): void {\n this.flags = { ...this.flags, ...newFlags };\n }\n}\n\nwindow.KosFeatureFlags = window.KosFeatureFlags ?? new FeatureFlagService();\n\n/**\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport const KosFeatureFlags = window.KosFeatureFlags;\n","import { runInAction as kosAction } from \"mobx\";\nimport { IKosDataModel } from \"../core/kosModel\";\n\n/**\n * @kosService core.utils\n */\nexport type KosDataMapper<\n D extends object = any,\n T extends IKosDataModel = IKosDataModel\n> = (data: D, model: T) => Partial<Omit<T, keyof IKosDataModel>>;\n\n/**\n * @kosService core.utils\n */\nexport type KosDataMapperUtils<\n D extends object,\n T extends IKosDataModel\n> = KosDataMapper<D, T>;\nconst defaultMapper = <D extends object, T extends IKosDataModel>(\n data: D,\n _model: T\n) => {\n const parsedData = { ...data };\n if ((parsedData as any).id) {\n delete (parsedData as any).id;\n }\n\n return parsedData;\n};\n\n/**\n * Utility function that can be used to map an arbitrary data object to a model.\n *\n * @param data - the input data for the mapping function\n * @param model - the target model to map the data to\n * @param mapper - a mapping function that takes the input data and the target model and returns a partial of the target model. The\n * results will be applied to the model.\n *\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport const mapDataToModel = <D extends object, T extends IKosDataModel>(\n data: D,\n model: T,\n mapper: KosDataMapperUtils<D, T> = defaultMapper\n) => {\n const partial = mapper(data, model);\n kosAction(() => {\n Object.assign(model, partial);\n });\n};\n","import { KosCore } from \"../core/kosCore\";\nimport { IKosDataModel } from \"../core/kosModel\";\nimport { ModelFactory } from \"../types/model\";\n\n/**\n * @kosService core.kos-model\n * @kosApiLevel 2\n */\nexport const modelFactory = <T extends IKosDataModel, O extends Object = {}>(\n typeId: string\n): ModelFactory<T, O> => {\n return {\n type: typeId,\n build: (modelId?: string, options?: O) =>\n KosCore.getInstance().modelManager.createModelInstance<T, O>(\n typeId,\n modelId,\n options\n ).data,\n\n buildAsync: async (modelId?: string, options?: O) => {\n const response = KosCore.getInstance().modelManager.createModelInstance<\n T,\n O\n >(typeId, modelId, options);\n await response.model.whenInitialized();\n return response.data;\n },\n };\n};\n","type PipeFn = (arg: any) => any;\n/**\n * @kosService core.pipe\n * @kosApiLevel 2\n */\nexport const pipe =\n (...fns: PipeFn[]) =>\n (x: any) =>\n fns.reduce((v, f) => f(v), x);\n","/**\n * @module ServiceFactory\n * @description\n * The ServiceFactory module provides functions for interacting with Kos services, such as retrieving, modifying, and deleting entities.\n * These functions communicate with the server and handle various service operations.\n *\n * @example\n * // Create a Kos service instance for managing entities.\n * const entityService = ServiceFactory.build({\n * basePath: \"/api/entities\",\n * getAllPath: \"/list\",\n * getOnePath: \"/get\",\n * deleteModelPath: \"/delete\",\n * addModelPath: \"/add\",\n * modifyModelPath: \"/modify\",\n * });\n *\n * // Fetch a list of entities.\n * const entities = await entityService.getAll({ ordered: true });\n *\n * // Get details of a specific entity by ID.\n * const entityDetails = await entityService.getModelById({ id: \"entity123\" });\n *\n * // Add a new entity to the server.\n * const newEntity = { name: \"New Entity\" };\n * await entityService.addModel({ model: newEntity });\n *\n * // Modify an existing entity.\n * const updatedEntity = { id: \"entity123\", name: \"Updated Entity\" };\n * await entityService.modifyModel({ model: updatedEntity });\n */\n\nimport { KosLog } from \"../core/log\";\nimport type {\n KosFetchOptions,\n Response as KosFetchResponse,\n} from \"../types/utils/kos-fetch\";\nimport type { KosServiceResponse } from \"./kos-fetch\";\nimport { BASE_URL, kosFetch } from \"./kos-fetch\";\n\nconst log = KosLog.createLogger({ name: \"kos-service-request\" });\n/**\n * Resolves the service URL configuration.\n * @param _service - The optional service name (not used).\n * @returns An object with `isMock` and `URL` properties.\n *\n * @kosService core.service-request\n * @kosApiLevel 2\n */\nexport const resolveServiceUrl = (_service?: string) => {\n const MOCK = false;\n const URL = BASE_URL;\n return { isMock: MOCK, URL };\n};\n\n/**\n * Represents a function that can be used for fetching data.\n * Note: Native fetch is cast to this type in mock mode - not all body types are compatible.\n */\ntype FetchType = (\n url: string,\n options?: KosFetchOptions\n) => Promise<KosFetchResponse>;\n\n/**\n * Represents parameters for deleting an entity from the server.\n */\ninterface DeleteModelParams extends CommonParams {\n id: string;\n urlOverride?: string;\n tracker?: string;\n}\n\n/**\n * Removes an entity from the server based on its ID.\n * @param destinationAddress - The destination address for the request.\n * @param url - The base URL for the service.\n * @param _fetch - The fetch function to use.\n * @returns An empty response with status 200.\n */\nconst deleteModel =\n (destinationAddress: string, url: string, _fetch: FetchType) =>\n async <ResponseType = unknown>({\n id,\n tracker,\n urlOverride,\n ordered,\n studio,\n fos,\n bridge,\n timeout,\n signal,\n destinationAddress: destinationAddressOverride,\n }: DeleteModelParams) => {\n const options: KosFetchOptions = {\n method: `DELETE`,\n };\n\n if (destinationAddress) {\n options.destinationAddress = destinationAddress;\n }\n\n if (tracker) {\n options.tracker = tracker;\n }\n\n addCommonParams(options, {\n ordered,\n studio,\n fos,\n bridge,\n timeout,\n signal,\n destinationAddress: destinationAddressOverride,\n });\n\n try {\n const response = await _fetch(urlOverride || `${url}/${id}`, options);\n\n if (!response.ok) {\n throw Error(\n `There was a problem deleting the model; returned status ${response.status}`\n );\n }\n\n const configResponse:\n | KosServiceResponse<ResponseType>\n | undefined\n | null = await response.json();\n\n return configResponse ?? undefined;\n } catch (error) {\n if (error instanceof DOMException) {\n if (error.name === \"TimeoutError\") {\n throw new FetchError(`Request timed out while deleting model`);\n }\n if (error.name === \"AbortError\") {\n throw new FetchError(`Request was cancelled while deleting model`);\n }\n }\n throw error;\n }\n };\n\n/**\n * Represents common parameters shared across different service operations.\n */\ntype CommonParams = Partial<Orderable> &\n Partial<StudioRequest> &\n Partial<FosRequest> &\n Partial<RoutableRequest> &\n Partial<TimeoutAware> &\n Partial<AbortableRequest>;\n\n/**\n * Represents parameters for fetching a list of entities.\n */\ninterface GetAllParams extends CommonParams {\n urlOverride?: string;\n tracker?: string;\n}\n\n/**\n * Represents parameters for fetching a single entity by ID.\n */\ninterface GetModelByIdParams extends GetAllParams {\n id: string;\n}\n\n/**\n * Adds common parameters to a KosFetchOptions object.\n * @param options - The KosFetchOptions object to modify.\n * @param param1 - The common parameters to add.\n * @returns The modified KosFetchOptions object.\n */\nconst addCommonParams = (\n options: KosFetchOptions,\n {\n ordered,\n studio,\n fos,\n destinationAddress,\n bridge,\n timeout,\n signal,\n }: CommonParams\n) => {\n if (timeout) {\n options.timeout = timeout;\n }\n if (signal) {\n options.signal = signal;\n }\n if (ordered) {\n options.ordered = ordered;\n }\n\n if (studio) {\n options.studio = studio;\n }\n\n if (fos) {\n options.fos = fos;\n }\n\n if (bridge) {\n options.bridge = bridge;\n }\n\n if (destinationAddress || destinationAddress === \"\") {\n options.destinationAddress = destinationAddress;\n }\n\n return options;\n};\n\n/**\n * Retrieves a list of entities managed by the KOS Server.\n * @param destinationAddress - The destination address for the request.\n * @param url - The base URL for the service.\n * @param _fetch - The fetch function to use.\n * @returns The list of entities.\n */\nconst getAll =\n (destinationAddress: string, url: string, _fetch: FetchType) =>\n async <Response>({\n urlOverride,\n ordered,\n studio,\n fos,\n bridge,\n timeout,\n signal,\n destinationAddress: destinationAddressOverride,\n }: GetAllParams) => {\n const options: KosFetchOptions = {\n method: `GET`,\n };\n\n if (destinationAddress) {\n options.destinationAddress = destinationAddress;\n }\n\n addCommonParams(options, {\n timeout,\n ordered,\n studio,\n fos,\n bridge,\n signal,\n destinationAddress: destinationAddressOverride,\n });\n\n const resolvedUrl = urlOverride || url;\n\n try {\n const response = await _fetch(resolvedUrl, options);\n\n if (!response.ok) {\n let payload: KosServiceResponse<Response> | undefined | null;\n try {\n payload = await response.json();\n } catch (error) {\n // silently ignore parsing error\n }\n throw new FetchError(\n `There was a problem retrieving the model; returned status ${response.status}`,\n payload ?? undefined\n );\n }\n\n const configResponse: KosServiceResponse<Response[]> | undefined | null =\n await response.json();\n\n return configResponse ?? undefined;\n } catch (error) {\n if (error instanceof DOMException) {\n if (error.name === \"TimeoutError\") {\n throw new FetchError(`Request timed out while retrieving models`);\n }\n if (error.name === \"AbortError\") {\n throw new FetchError(`Request was cancelled while retrieving models`);\n }\n }\n throw error;\n }\n };\n\n/**\n * Represents parameters for fetching a single entity.\n */\nconst getOne =\n (destinationAddress: string, url: string, _fetch: FetchType) =>\n async <Response>({\n urlOverride,\n ordered,\n studio,\n fos,\n bridge,\n tracker,\n timeout,\n signal,\n destinationAddress: destinationAddressOverride,\n }: GetAllParams) => {\n const options: KosFetchOptions = {\n method: `GET`,\n };\n\n if (destinationAddress) {\n options.destinationAddress = destinationAddress;\n }\n\n if (tracker) {\n options.tracker = tracker;\n }\n\n addCommonParams(options, {\n timeout,\n ordered,\n studio,\n fos,\n bridge,\n signal,\n destinationAddress: destinationAddressOverride,\n });\n\n const resolvedUrl = urlOverride || url;\n log.debug(`resolvedUrl: ${resolvedUrl}`);\n try {\n const response = await _fetch(resolvedUrl, options);\n if (!response.ok) {\n let payload: KosServiceResponse<Response> | undefined | null;\n try {\n payload = await response.json();\n } catch (error) {\n // silently ignore parsing error\n }\n throw new FetchError(\n `There was a problem retrieving the model; returned status ${response.status}`,\n payload ?? undefined\n );\n }\n const configResponse: KosServiceResponse<Response> | undefined | null =\n await response.json();\n return configResponse ?? undefined;\n } catch (error) {\n if (error instanceof DOMException) {\n if (error.name === \"TimeoutError\") {\n throw new FetchError(`Request timed out while retrieving model`);\n }\n if (error.name === \"AbortError\") {\n throw new FetchError(`Request was cancelled while retrieving model`);\n }\n }\n throw error;\n }\n };\n\nconst getModelById =\n (destinationAddress: string, url: string, _fetch: FetchType) =>\n async <Response>({\n urlOverride,\n id,\n ordered,\n studio,\n fos,\n bridge,\n timeout,\n signal,\n destinationAddress: destinationAddressOverride,\n }: GetModelByIdParams) => {\n const options: KosFetchOptions = {\n method: `GET`,\n };\n if (destinationAddress) {\n options.destinationAddress = destinationAddress;\n }\n\n addCommonParams(options, {\n timeout,\n ordered,\n studio,\n fos,\n bridge,\n signal,\n destinationAddress: destinationAddressOverride,\n });\n\n const resolvedUrl = urlOverride || `${url}/${id}`;\n try {\n const response = await _fetch(resolvedUrl, options);\n if (!response.ok) {\n let payload: KosServiceResponse<Response> | undefined | null;\n try {\n payload = await response.json();\n } catch (error) {\n // silently ignore parsing error\n }\n throw new FetchError(\n `There was a problem retrieving the model; returned status ${response.status}`,\n payload ?? undefined\n );\n }\n const configResponse: KosServiceResponse<Response> | undefined | null =\n await response.json();\n return configResponse ?? undefined;\n } catch (error) {\n if (error instanceof DOMException) {\n if (error.name === \"TimeoutError\") {\n throw new FetchError(\n `Request timed out while retrieving model by ID`\n );\n }\n if (error.name === \"AbortError\") {\n throw new FetchError(\n `Request was cancelled while retrieving model by ID`\n );\n }\n }\n throw error;\n }\n };\n\ninterface Orderable {\n ordered: boolean;\n}\n\ninterface TimeoutAware {\n timeout: number;\n}\n\ninterface AbortableRequest {\n signal: AbortSignal;\n}\n\ninterface FosRequest {\n fos: boolean;\n bridge: boolean;\n}\n\ninterface StudioRequest {\n studio: boolean;\n}\n\ninterface RoutableRequest {\n destinationAddress: string;\n}\ninterface AddModelParams<Request>\n extends Partial<Orderable>,\n Partial<StudioRequest>,\n Partial<FosRequest>,\n Partial<RoutableRequest>,\n Partial<TimeoutAware>,\n Partial<AbortableRequest> {\n model: Request;\n urlOverride?: string;\n tracker?: string;\n}\n\ninterface ModifyModelParams<Request>\n extends Partial<Orderable>,\n Partial<StudioRequest>,\n Partial<FosRequest>,\n Partial<RoutableRequest>,\n Partial<TimeoutAware>,\n Partial<AbortableRequest> {\n model?: Request;\n id: string;\n urlOverride?: string;\n}\n\n/**\n * @kosService core.service-request\n * @kosApiLevel 2\n */\nexport class FetchError<\n T extends Record<string, any> | string = { error: string }\n> extends Error {\n payload?: T;\n constructor(message: string, payload?: T) {\n super(message);\n this.name = \"FetchException\";\n this.payload = payload;\n }\n}\n/**\n * Adds a new Entity to the server.\n *\n * Only members of the `kos.freestyle` org have permissions to invoke this operation.\n *\n * While the immediate response to the request is empty, and additions will be broadcast\n * to all interested listeners on the corresponding event channel.\n *\n * @param model - the model to be added\n * @returns an empty response with status 200.\n */\nconst add =\n (destinationAddress: string, url: string, _fetch: FetchType) =>\n async <Request>({\n model,\n urlOverride,\n ordered,\n tracker,\n studio,\n fos,\n bridge,\n timeout,\n signal,\n destinationAddress: destinationAddressOverride,\n }: AddModelParams<Request>) => {\n const options: KosFetchOptions = {\n method: `POST`,\n body: typeof model === \"string\" ? model : JSON.stringify(model),\n };\n if (destinationAddress) {\n options.destinationAddress = destinationAddress;\n }\n if (tracker) {\n options.tracker = tracker;\n }\n addCommonParams(options, {\n timeout,\n ordered,\n studio,\n fos,\n bridge,\n signal,\n destinationAddress: destinationAddressOverride,\n });\n\n try {\n const response = await _fetch(urlOverride || url, options);\n if (!response.ok) {\n let payload: KosServiceResponse<Response> | undefined | null;\n try {\n payload = await response.json();\n } catch (error) {\n // silently ignore parsing error\n }\n throw new FetchError(\n `There was a problem sending the POST data; returned status ${response.status}`,\n payload ?? undefined\n );\n }\n const configResponse: KosServiceResponse<any> | undefined | null =\n await response.json();\n return configResponse ?? undefined;\n } catch (error) {\n if (error instanceof DOMException) {\n if (error.name === \"TimeoutError\") {\n throw new FetchError(`Request timed out while adding model`);\n }\n if (error.name === \"AbortError\") {\n throw new FetchError(`Request was cancelled while adding model`);\n }\n }\n throw error;\n }\n };\n\n/**\n * Modifies an existing model on the server.\n * @param method - The HTTP method to use for the modification operation (default is \"POST\").\n * @param destinationAddress - The destination address for the request.\n * @param url - The base URL for the service.\n * @param _fetch - The fetch function to use.\n * @returns An empty response with status 200.\n */\nconst modifyModel =\n (\n method: \"PUT\" | \"POST\" = \"POST\",\n destinationAddress: string,\n url: string,\n _fetch: FetchType\n ) =>\n async <Request>({\n // Reqeust should be Request = unknown...\n model,\n id,\n urlOverride,\n ordered,\n studio,\n fos,\n bridge,\n timeout,\n signal,\n destinationAddress: destinationAddressOverride,\n }: ModifyModelParams<Request>) => {\n const options: KosFetchOptions = {\n method,\n };\n if (model) {\n options.body = JSON.stringify(model);\n }\n if (destinationAddress) {\n options.destinationAddress = destinationAddress;\n }\n\n addCommonParams(options, {\n timeout,\n ordered,\n studio,\n fos,\n bridge,\n signal,\n destinationAddress: destinationAddressOverride,\n });\n\n try {\n const response = await _fetch(urlOverride || `${url}/${id}`, options);\n if (!response.ok) {\n let payload: KosServiceResponse<Response> | undefined | null;\n try {\n payload = await response.json();\n } catch (error) {\n // silently ignore parsing error\n }\n throw new FetchError(\n `There was a problem modifying the model; returned status ${response.status}`,\n payload ?? undefined\n );\n }\n const configResponse: KosServiceResponse<any> | undefined | null = // <--- KosServiceResponse<any> should be KosServiceResponse<Request>...\n await response.json();\n return configResponse ?? undefined;\n } catch (error) {\n if (error instanceof DOMException) {\n if (error.name === \"TimeoutError\") {\n throw new FetchError(`Request timed out while modifying model`);\n }\n if (error.name === \"AbortError\") {\n throw new FetchError(`Request was cancelled while modifying model`);\n }\n }\n throw error;\n }\n };\n/**\n * Represents parameters for creating a service instance.\n */\ninterface ServiceFactoryParams {\n destinationAddress?: string;\n basePath: string;\n getAllPath?: string;\n getOnePath?: string;\n deleteModelPath?: string;\n addModelPath?: string;\n modifyModelPath?: string;\n mock?: boolean;\n}\n\n/**\n * A factory for creating service instances with common configurations.\n *\n * @deprecated Use `@kosServiceRequest` with `createClient`, which is typed\n * from the OpenAPI paths and carries the response context.\n * @kosService core.service-request\n * @kosApiLevel 2\n */\nexport const ServiceFactory = {\n /**\n * Builds a service instance with the specified configuration.\n *\n * @param params - The configuration parameters for the service instance.\n * @returns An object with service methods for interacting with the server.\n *\n * @example\n * // Create a Kos service instance for managing entities.\n * const entityService = ServiceFactory.build({\n * basePath: \"/api/entities\",\n * getAllPath: \"/list\",\n * getOnePath: \"/get\",\n * deleteModelPath: \"/delete\",\n * addModelPath: \"/add\",\n * modifyModelPath: \"/modify\",\n * });\n *\n * // Fetch a list of entities.\n * const entities = await entityService.getAll({ ordered: true });\n *\n * // Get details of a specific entity by ID.\n * const entityDetails = await entityService.getModelById({ id: \"entity123\" });\n *\n * // Add a new entity to the server.\n * const newEntity = { name: \"New Entity\" };\n * await entityService.addModel({ model: newEntity });\n *\n * // Modify an existing entity.\n * const updatedEntity = { id: \"entity123\", name: \"Updated Entity\" };\n * await entityService.modifyModel({ model: updatedEntity });\n */\n build: ({\n destinationAddress = \"\",\n basePath,\n getAllPath,\n getOnePath,\n deleteModelPath,\n addModelPath,\n modifyModelPath,\n mock = false,\n }: ServiceFactoryParams) => {\n const _fetch: FetchType = mock ? (fetch as FetchType) : kosFetch;\n return {\n /**\n * Retrieves a list of entities managed by the KOS Server.\n *\n * @param params - The parameters for the request, including common options.\n * @returns The list of entities.\n */\n getAll: getAll(destinationAddress, getAllPath || basePath, _fetch),\n\n /**\n * Retrieves details of a specific entity by its ID.\n *\n * @param params - The parameters for the request, including common options and the entity ID.\n * @returns Details of the requested entity.\n */\n getModelById: getModelById(\n destinationAddress,\n getOnePath || basePath,\n _fetch\n ),\n\n /**\n * Retrieves details of a single entity.\n *\n * @param params - The parameters for the request, including common options.\n * @returns Details of the requested entity.\n */\n getOne: getOne(destinationAddress, getOnePath || basePath, _fetch),\n\n /**\n * Adds a new entity to the server.\n *\n * @param params - The parameters for the request, including common options and the new entity model.\n * @returns An empty response with status 200.\n */\n addModel: add(destinationAddress, addModelPath || basePath, _fetch),\n\n /**\n * Deletes an entity from the server based on its ID.\n *\n * @param params - The parameters for the request, including common options and the entity ID.\n * @returns An empty response with status 200.\n */\n deleteModel: deleteModel(\n destinationAddress,\n deleteModelPath || basePath,\n _fetch\n ),\n\n /**\n * Modifies an existing entity on the server.\n *\n * @param params - The parameters for the request, including common options and the entity model.\n * @returns An empty response with status 200.\n */\n modifyModel: modifyModel(\n \"POST\",\n destinationAddress,\n modifyModelPath || basePath,\n _fetch\n ),\n\n /**\n * Modifies an existing entity on the server using the HTTP PUT method.\n *\n * @param params - The parameters for the request, including common options and the entity model.\n * @returns An empty response with status 200.\n */\n putModel: modifyModel(\n \"PUT\",\n destinationAddress,\n modifyModelPath || basePath,\n _fetch\n ),\n\n /**\n * Adds a new entity to the server using the HTTP POST method.\n *\n * @param params - The parameters for the request, including common options and the new entity model.\n * @returns An empty response with status 200.\n */\n postModel: add(destinationAddress, addModelPath || basePath, _fetch),\n };\n },\n};\n","import { uuid } from \"./api-request-id\";\n\nconst _sessionKey = uuid();\n\n/**\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport const getKosSessionKey = (): string => `kos-${_sessionKey}`;\n\n/**\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport const isLocalRefId = (id?: string): boolean =>\n !!id && !id.includes(\"VM_SERVICE\") && id.startsWith(getKosSessionKey());\n","import { ObservableMap, makeAutoObservable } from \"mobx\";\nimport { kosAction } from \"../..\";\nimport { getAllKosCompanionModels, getKosModelSync } from \"../../util\";\nimport { IKosDataModel } from \"../kosModel\";\nconst contextMap = new Map<string, KosContextBean>();\n\nexport interface KosContext {\n get(key: string): any;\n set(key: string, value: any): void;\n}\nexport class KosContextBean implements KosContext {\n private _context: ObservableMap<string, any>;\n private _parent?: string | undefined;\n private _id: string;\n constructor(id: string) {\n this._id = id;\n this._context = new ObservableMap({});\n this._parent = \"\";\n makeAutoObservable(this);\n }\n\n setParent(parent: string) {\n kosAction(() => {\n this._parent = parent;\n });\n }\n get id() {\n return this._id;\n }\n\n get context() {\n return this._context;\n }\n\n get parentModel() {\n if (!this._parent) {\n return undefined;\n }\n return getKosModelSync(this._parent)?.model;\n }\n\n get companionModels() {\n const model = getKosModelSync(this._id);\n if (!model?.model) {\n return [];\n }\n return getAllKosCompanionModels(model.model);\n }\n\n get(key: string) {\n if (this._context.has(key)) {\n return this._context.get(key);\n }\n\n if (this.companionModels.length > 0) {\n const value = this.companionModels.find((companion: IKosDataModel) => {\n if (!companion.id) {\n return false;\n }\n if (!contextMap.has(companion.id)) {\n return false;\n }\n return contextMap.get(companion.id)?.context.has(key);\n });\n if (value) {\n return contextMap.get(value.id)?.get(key);\n }\n }\n\n if (this._parent) {\n return contextMap.get(this._parent)?.get(key);\n }\n return undefined;\n }\n set(key: string, value: any) {\n this._context.set(key, value);\n }\n remove(key: string) {\n this._context.delete(key);\n }\n clear() {\n this._context.clear();\n }\n}\n\nexport const KosContextManager = {\n createContext: (id: string, parentId?: string) => {\n const context = contextMap.get(id) ?? new KosContextBean(id);\n if (parentId) {\n if (!contextMap.has(parentId)) {\n throw new Error(`Parent context ${parentId} does not exist`);\n }\n context.setParent(parentId);\n } else if (id !== \"root\") {\n context.setParent(\"root\");\n }\n contextMap.set(id, context);\n return context;\n },\n getContext: (id: string) => contextMap.get(id),\n deleteContext: (id: string) => {\n contextMap.delete(id);\n },\n setParentContext: (id: string, parentId: string) => {\n if (!contextMap.has(parentId)) {\n throw new Error(`Parent context ${parentId} does not exist`);\n }\n contextMap.get(id)?.setParent(parentId);\n },\n rootContext: () => contextMap.get(\"root\"),\n};\n\nKosContextManager.createContext(\"root\");\n\nexport const resolveKosContext = (model: IKosDataModel) =>\n KosContextManager.getContext(model.id);\n","import {\n isObservable,\n runInAction as kosAction,\n makeAutoObservable,\n observable,\n observe,\n} from \"mobx\";\n\nimport { ObservableData, type KosData } from \"../util/observable-proxy-map\";\nimport {\n IKosContainerIndex,\n IndexMapper,\n KosContainerIndex,\n} from \"./kos-container-index\";\nimport {\n IKosBaseContainer,\n type EvictionStrategy,\n} from \"./kos-container-model\";\nimport { KosLog } from \"./log\";\nimport { IKosIdentifiable } from \"./types/model\";\n\nexport interface IKosDataContainer<T extends IKosIdentifiable>\n extends IKosBaseContainer<T> {\n updateModel: (model: T) => void;\n getModel: (id: string) => T | undefined;\n getIndexByKey: (indexName: string, indexKey: string) => T[];\n getIndexKeys: (indexName: string) => string[];\n}\nconst log = KosLog.createLogger({ name: \"kos-data-container\" });\ntype PropType = string | number | symbol | undefined;\n\ninterface ContainerOptions<T extends IKosIdentifiable> {\n sortKey?: keyof T;\n indexMap?: Record<string, keyof T | IndexMapper<T>>;\n\n /** SAFETY NET: Maximum capacity before eviction */\n maxCapacity?: number;\n\n /** Eviction strategy when maxCapacity is exceeded */\n evictionStrategy?: EvictionStrategy;\n\n /** Number of items to evict when capacity exceeded */\n evictionBatchSize?: number;\n\n /** Custom eviction filter for 'custom' strategy */\n customEvictionFilter?: (models: T[]) => T[];\n}\nexport class KosDataContainer<T extends IKosIdentifiable>\n implements IKosDataContainer<T>\n{\n _data: Map<string, T>;\n private _sortKey?: PropType;\n private _revision: number;\n private _index: Map<string, IKosContainerIndex<T>>;\n private _optionsMap: ContainerOptions<T>[\"indexMap\"];\n private _disposerMap: Map<string, () => void> = new Map();\n idx: KosData<Record<string, Record<string, T[]>>>;\n\n // Capacity management fields\n private _maxCapacity?: number;\n private _evictionStrategy: EvictionStrategy;\n private _evictionBatchSize: number;\n private _insertionOrder: string[] = []; // For FIFO strategy\n private _accessTimes?: Map<string, number>; // For LRU strategy\n private _customEvictionFilter?: (models: T[]) => T[];\n\n constructor(options?: ContainerOptions<T>) {\n this._data = observable.map(new Map());\n this._sortKey = options?.sortKey;\n this._revision = 1;\n this._optionsMap = options?.indexMap || {};\n const tmp = options?.indexMap\n ? Object.keys(options.indexMap).reduce((acc, curr) => {\n acc[curr] = undefined;\n return acc;\n }, {})\n : {};\n this._index = observable.map(tmp);\n this.idx = ObservableData();\n\n // Initialize capacity management\n this._maxCapacity = options?.maxCapacity;\n this._evictionStrategy = options?.evictionStrategy || \"fifo\";\n this._evictionBatchSize =\n options?.evictionBatchSize ??\n Math.max(10, Math.ceil((options?.maxCapacity ?? 100) * 0.1));\n this._customEvictionFilter = options?.customEvictionFilter;\n\n // Initialize LRU access tracking if needed\n if (this._evictionStrategy === \"lru\" && this._maxCapacity) {\n this._accessTimes = observable.map(new Map());\n }\n\n makeAutoObservable(this, {});\n this.init();\n }\n\n init() {\n Object.keys(this._optionsMap!).forEach((key) => {\n const modelKey = this._optionsMap![key];\n const idx = new KosContainerIndex<T>({\n container: this,\n key: modelKey,\n });\n this._index.set(key, idx);\n this.idx[key] = idx.data;\n });\n }\n\n [Symbol.iterator]() {\n return this.data[Symbol.iterator]();\n }\n\n get index() {\n return this._index;\n }\n\n get indexKeys() {\n return Array.from(this.index.keys()).reduce<\n Record<string, string[] | undefined>\n >((acc, curr) => {\n acc[curr] = this.index.get(curr)?.keys;\n return acc;\n }, {});\n }\n\n get revision() {\n return this._revision;\n }\n\n addAll(models: T[]) {\n kosAction(() => {\n models.forEach((model) => this.addModel(model));\n });\n }\n\n removeAll(ids: string[]) {\n kosAction(() => {\n ids.forEach((id) => this.removeModel(id));\n });\n }\n\n sortFn(a, b): number {\n const sortKey = this._sortKey;\n\n if (sortKey) {\n return String(a[sortKey]).localeCompare(String(b[sortKey]), undefined, {\n numeric: true,\n });\n }\n return 0;\n }\n\n get data() {\n const list = Array.from(this._data.values());\n\n if (this._sortKey) {\n list.sort(this.sortFn.bind(this));\n }\n return list;\n }\n\n increment() {\n kosAction(() => {\n this._revision = this._revision + 1;\n });\n }\n /**\n * Add a data object to the container (Zone 2: Workflow orchestration)\n *\n * @param model - The data object to add\n * @param defer - If true, skip incrementing revision (for batch operations)\n */\n addModel(model: T, defer?: boolean) {\n // Zone 2: High-level workflow orchestration\n const observableData = this._ensureObservable(model);\n this._cleanupExistingDisposer(model.id);\n this._persistData(observableData);\n this._trackDataMetadata(observableData);\n this._enforceCapacityLimits();\n this._configureDataMonitoring(observableData);\n\n if (!defer) {\n this.increment();\n }\n }\n\n /**\n * Ensure data is observable (Zone 3)\n * @private\n */\n private _ensureObservable(model: T): T {\n return isObservable(model) ? model : observable.object(model);\n }\n\n /**\n * Clean up existing disposer if present (Zone 3)\n * @private\n */\n private _cleanupExistingDisposer(id: string | undefined): void {\n if (!id) return;\n\n const disposer = this._disposerMap.get(id);\n if (disposer) {\n disposer();\n this._disposerMap.delete(id);\n }\n }\n\n /**\n * Persist data to container storage (Zone 3)\n * @private\n */\n private _persistData(data: T): void {\n this._data.set(data.id || \"\", data);\n }\n\n /**\n * Track data metadata for capacity management (Zone 3)\n * @private\n */\n private _trackDataMetadata(data: T): void {\n if (!this._maxCapacity) return;\n\n // Track insertion order for FIFO eviction\n this._insertionOrder.push(data.id || \"\");\n\n // Track initial access time for LRU eviction\n if (this._accessTimes) {\n this._accessTimes.set(data.id || \"\", Date.now());\n }\n }\n\n /**\n * Enforce capacity limits and trigger eviction if needed (Zone 3)\n * @private\n */\n private _enforceCapacityLimits(): void {\n if (!this._maxCapacity) return;\n\n if (this._data.size > this._maxCapacity) {\n this._evictModels();\n }\n }\n\n /**\n * Configure MobX observers for data property changes (Zone 3)\n * @private\n */\n private _configureDataMonitoring(data: T): void {\n const disposer = observe(data, (change) => {\n if (\n Object.values(this._optionsMap || {}).includes(change.name as keyof T)\n ) {\n this.increment();\n }\n });\n this._disposerMap.set(data.id || \"\", disposer);\n }\n\n removeModel(id: string) {\n this._data.delete(id);\n\n // Clean up tracking data structures\n const orderIndex = this._insertionOrder.indexOf(id);\n if (orderIndex !== -1) {\n this._insertionOrder.splice(orderIndex, 1);\n }\n\n if (this._accessTimes) {\n this._accessTimes.delete(id);\n }\n\n this.increment();\n const disposer = this._disposerMap.get(id);\n if (disposer) {\n disposer();\n this._disposerMap.delete(id);\n }\n }\n\n updateModel(model: T) {\n const observableData = observable.object(model);\n this._data.set(observableData.id || \"\", observableData);\n this.increment();\n }\n\n getModel(id: string) {\n const model = this._data.get(id);\n\n // Track access time for LRU eviction strategy\n if (model && this._accessTimes) {\n this._accessTimes.set(id, Date.now());\n }\n\n return model;\n }\n\n getIndexKeys(indexName: string) {\n if (this.index.has(indexName)) {\n const idx = this.index.get(indexName)!;\n return idx.keys ?? [];\n } else {\n log.info(\n `index ${indexName} not found in ${Array.from(this.index.keys())}`\n );\n return [];\n }\n }\n\n getIndexByKey(indexName: string, indexKey: string) {\n if (this.index.has(indexName)) {\n const idx = this.index.get(indexName)!;\n if (idx.index.has(indexKey)) {\n return idx.getByKey(indexKey);\n } else {\n log.info(\n `key ${indexKey} not found in ${indexName} index: ${Array.from(\n idx.index.keys()\n )}`\n );\n return [];\n }\n } else {\n log.info(\n `index ${indexName} not found in ${Array.from(this.index.keys())}`\n );\n return [];\n }\n }\n\n /**\n * SAFETY NET: Evict data models when capacity is exceeded (Zone 2: Workflow orchestration)\n * Logs all evictions at WARNING level for debugging.\n * Note: Data models are not destroyed (no lifecycle), only removed from container.\n * @private\n */\n private _evictModels() {\n if (!this._maxCapacity) return;\n\n const overCapacity = this._data.size - this._maxCapacity;\n if (overCapacity <= 0) return;\n\n const toEvict = Math.min(this._evictionBatchSize, overCapacity);\n\n // Zone 2: Workflow orchestration\n this._logDataCapacityWarning(toEvict);\n const idsToEvict = this._selectDataForEviction(toEvict);\n this._removeEvictedData(idsToEvict);\n this._logDataEvictionComplete(idsToEvict.length);\n }\n\n /**\n * Log capacity exceeded warning for data container (Zone 3)\n * @private\n */\n private _logDataCapacityWarning(toEvict: number): void {\n log.info(\n `Data container capacity exceeded (${this._data.size}/${this._maxCapacity}). ` +\n `Evicting ${toEvict} items using ${this._evictionStrategy} strategy. ` +\n `This may indicate missing cleanup handlers or data inconsistency.`\n );\n }\n\n /**\n * Select data for eviction based on strategy (Zone 3)\n * @private\n */\n private _selectDataForEviction(count: number): string[] {\n switch (this._evictionStrategy) {\n case \"fifo\":\n return this._selectFifoData(count);\n case \"lru\":\n return this._selectLruData(count);\n case \"custom\":\n return this._selectCustomData(count);\n default:\n return this._selectFifoData(count);\n }\n }\n\n /**\n * Select oldest data IDs for FIFO eviction (Zone 3)\n * @private\n */\n private _selectFifoData(count: number): string[] {\n const ids: string[] = [];\n for (let i = 0; i < count && this._insertionOrder.length > 0; i++) {\n const oldestId = this._insertionOrder.shift();\n if (!oldestId) continue;\n\n if (this._data.has(oldestId)) {\n ids.push(oldestId);\n }\n }\n return ids;\n }\n\n /**\n * Select least recently used data IDs for LRU eviction (Zone 3)\n * @private\n */\n private _selectLruData(count: number): string[] {\n const ids: string[] = [];\n\n if (this._accessTimes) {\n const sorted = Array.from(this._accessTimes.entries())\n .sort((a, b) => a[1] - b[1])\n .slice(0, count);\n\n sorted.forEach(([id]) => {\n if (this._data.has(id)) {\n ids.push(id);\n }\n });\n }\n\n return ids;\n }\n\n /**\n * Select data using custom filter for eviction (Zone 3)\n * @private\n */\n private _selectCustomData(count: number): string[] {\n if (this._customEvictionFilter) {\n const candidates = this._customEvictionFilter(this.data);\n return candidates.slice(0, count).map((item) => item.id);\n }\n\n log.error(\n \"Custom eviction strategy specified but no customEvictionFilter provided. \" +\n \"Falling back to FIFO.\"\n );\n\n return this._selectFifoData(count);\n }\n\n /**\n * Remove evicted data items (Zone 3)\n * @private\n */\n private _removeEvictedData(ids: string[]): void {\n ids.forEach((id) => {\n const item = this._data.get(id);\n log.info(`Evicting data item: ${id}`, {\n itemId: id,\n itemType: item ? item.constructor?.name : \"unknown\",\n strategy: this._evictionStrategy,\n });\n\n this.removeModel(id);\n });\n }\n\n /**\n * Log eviction completion for data container (Zone 3)\n * @private\n */\n private _logDataEvictionComplete(evictedCount: number): void {\n log.info(\n `Evicted ${evictedCount} data items. ` +\n `Current size: ${this._data.size}/${this._maxCapacity}`\n );\n }\n\n async clear() {\n this._data.clear();\n this.increment();\n }\n\n filter<S extends any>(\n predicate: (value: any, index: number, array: any[]) => value is S,\n thisArg?: any\n ) {\n return this.data.filter(predicate, thisArg);\n }\n\n sort(compareFn?: ((a: any, b: any) => number) | undefined) {\n return this.data.sort(compareFn);\n }\n map<U>(\n callbackfn: (value: any, index: number, array: any[]) => U,\n thisArg?: any\n ) {\n return this.data.map(callbackfn, thisArg);\n }\n\n forEach(\n callbackfn: (value: any, index: number, array: any[]) => void,\n thisArg?: any\n ) {\n this.data.forEach(callbackfn, thisArg);\n }\n\n toJSON() {\n const indexes = this.indexKeys;\n return {\n indexes,\n data: this.data.map((model) => {\n return {\n id: model.id,\n };\n }),\n };\n }\n}\n","// Extracts route parameter names from a path like \"/user/:id/profile/:section\"\ntype ExtractParams<T extends string> =\n T extends `${infer _Start}/:${infer Param}/${infer Rest}`\n ? { [K in Param | keyof ExtractParams<`/${Rest}`>]: string }\n : T extends `${infer _Start}/:${infer Param}`\n ? { [K in Param]: string }\n : {};\n\nexport type KosMethodTypes = \"GET\" | \"POST\" | \"PUT\" | \"DELETE\";\nexport type KosRequest<TPath extends string = string> = {\n id: string;\n method: string;\n path: TPath;\n params: ExtractParams<TPath>;\n query?: Record<string, string>;\n body?: any;\n headers?: Record<string, string>;\n};\n\nexport type KosResponse = {\n send: (data: any) => void;\n status?: (code: number) => KosResponse;\n};\n\nexport type RouteMetadata = {\n method: string;\n path: string;\n description?: string;\n parameters?: any[]; // OpenAPI-compliant parameter definitions\n};\n\nexport type KosMiddleware<TPath extends string = string> = (\n req: KosRequest<TPath>,\n res: KosResponse,\n next: () => Promise<void> | void\n) => Promise<void> | void;\n\nexport class BrowserKosRouter {\n private routes: {\n method: string;\n path: string;\n middlewares: KosMiddleware<any>[];\n }[] = [];\n private openApiRoutes: RouteMetadata[] = [];\n\n use<TPath extends string = string>(\n method: string,\n path: TPath,\n ...middlewares: KosMiddleware<TPath>[]\n ) {\n this.routes.push({ method, path, middlewares });\n\n // Extract route parameters for OpenAPI\n const params = this.extractOpenApiParams(path);\n\n this.openApiRoutes.push({\n method,\n path,\n parameters: params,\n });\n }\n\n /**\n * Remove routes matching the given method and path\n * @param method HTTP method (GET, POST, etc.)\n * @param path Route path pattern\n * @returns Number of routes removed\n */\n remove(method: string, path: string): number {\n const initialRoutesLength = this.routes.length;\n\n // Remove from routes array\n this.routes = this.routes.filter(\n (route) => !(route.method === method && route.path === path)\n );\n\n // Remove from OpenAPI routes\n this.openApiRoutes = this.openApiRoutes.filter(\n (route) => !(route.method === method && route.path === path)\n );\n\n return initialRoutesLength - this.routes.length;\n }\n\n /**\n * Remove all routes matching a path pattern (regardless of method)\n * @param path Route path pattern\n * @returns Number of routes removed\n */\n removeAllForPath(path: string): number {\n const initialRoutesLength = this.routes.length;\n\n // Remove from routes array\n this.routes = this.routes.filter((route) => route.path !== path);\n\n // Remove from OpenAPI routes\n this.openApiRoutes = this.openApiRoutes.filter(\n (route) => route.path !== path\n );\n\n return initialRoutesLength - this.routes.length;\n }\n\n /**\n * Get all registered routes (for debugging/monitoring)\n */\n getRoutes(): Array<{ method: string; path: string }> {\n return this.routes.map((route) => {\n return {\n method: route.method,\n path: route.path,\n };\n });\n }\n\n async handle(rawReq: Omit<KosRequest, \"params\" | \"query\">, res: KosResponse) {\n const { path, query, params } = this.extractPathParams(rawReq.path);\n const req: KosRequest = { ...rawReq, params, query };\n\n for (const route of this.routes) {\n const match = this.matchRoute(route.path, path);\n if (route.method === rawReq.method && match) {\n req.params = match; // Inject extracted path parameters\n let index = 0;\n\n const next = async () => {\n if (index < route.middlewares.length) {\n const middleware = route.middlewares[index++];\n await middleware(req, res, next);\n }\n };\n\n await next();\n return;\n }\n }\n\n res.status?.(404).send({ error: \"Route not found\" });\n }\n\n private extractOpenApiParams(routePath: string) {\n return routePath\n .split(\"/\")\n .filter((part) => part.startsWith(\":\"))\n .map((param) => {\n return {\n name: param.slice(1),\n in: \"path\",\n required: true,\n schema: { type: \"string\" },\n };\n });\n }\n\n generateOpenApiSpec() {\n const paths: Record<string, any> = {};\n\n for (const route of this.openApiRoutes) {\n if (!paths[route.path]) paths[route.path] = {};\n\n paths[route.path][route.method.toLowerCase()] = {\n summary: route.description || `Handles ${route.method} ${route.path}`,\n parameters: route.parameters || [],\n responses: {\n \"200\": {\n description: \"Successful response\",\n },\n },\n };\n }\n\n return {\n openapi: \"3.0.0\",\n info: {\n title: \"Kos Router API\",\n version: \"1.0.0\",\n description: \"Dynamically generated OpenAPI documentation\",\n },\n paths,\n };\n }\n\n private extractPathParams(requestPath: string) {\n const [path, queryString] = requestPath.split(\"?\");\n const query = this.parseQueryParams(queryString);\n\n for (const route of this.routes) {\n const match = this.matchRoute(route.path, path);\n if (match) {\n return { path, query, params: match };\n }\n }\n\n return { path, query, params: {} };\n }\n\n private matchRoute(\n routePath: string,\n requestPath: string\n ): Record<string, string> | null {\n const routeParts = routePath.split(\"/\").filter(Boolean);\n const requestParts = requestPath.split(\"/\").filter(Boolean);\n\n if (routeParts.length !== requestParts.length) return null;\n\n const params: Record<string, string> = {};\n for (let i = 0; i < routeParts.length; i++) {\n if (routeParts[i].startsWith(\":\")) {\n params[routeParts[i].slice(1)] = decodeURIComponent(requestParts[i]);\n } else if (routeParts[i] !== requestParts[i]) {\n return null;\n }\n }\n return params;\n }\n\n private parseQueryParams(queryString?: string): Record<string, string> {\n if (!queryString) return {};\n return queryString.split(\"&\").reduce((acc, param) => {\n const [key, value] = param.split(\"=\").map(decodeURIComponent);\n acc[key] = value ?? \"\";\n return acc;\n }, {} as Record<string, string>);\n }\n}\n","/**\n * @file intent-service.ts\n * @description\n * Provides a simple API for sending and handling \"intents\"—structured messages that allow decoupled communication between different parts of your application.\n * Utilizes the EventBus to publish and subscribe to intent events, supporting both fire-and-forget and request/response (async) patterns.\n *\n * Example usage:\n *\n * // Listening for an intent in a model:\n * @kosTopicHandler({\n * topic: `/kos/intent/studio.start.vm`,\n * })\n * async handleIntent(payload: any) {\n * this.logger.warn(payload);\n * return { test: \"foo\" };\n * }\n *\n * // Sending an intent:\n * sendIntent({\n * type: \"studio.start.vm\",\n * options: { imageId: id },\n * });\n *\n * // Sending an async intent and handling the response:\n * sendAsyncIntent({\n * type: \"studio.start.vm\",\n * options: { imageId: id },\n * }).then(([error, data]) => {\n * if (error) {\n * log.error(`Error starting VM: ${error}`);\n * } else if (data) {\n * log.warn(`result: ${JSON.stringify(data, null, 2)}`);\n * }\n * });\n */\n\nimport { EventBus, type ApiCallback } from \"../../../common/events\";\nimport { uuid, type ServiceResponse } from \"../../util\";\nimport { KosLog } from \"../log\";\n\nconst log = KosLog.createLogger({ name: \"intent-service\" });\n\n/**\n * Represents an intent message.\n * @template T - The payload/options type for the intent.\n * @property {string} type - The intent type (e.g., \"studio.start.vm\").\n * @property {T} options - The payload/options for the intent.\n */\nexport interface Intent<T extends Record<string, any> = Record<string, any>> {\n type: string;\n options: T;\n}\n\n/**\n * Sends an intent as a fire-and-forget event.\n * If there are subscribers for the intent type, the event is published; otherwise, a log message is emitted.\n *\n * @param {Intent} intent - The intent to send.\n * @returns {void}\n *\n * @example\n * sendIntent({\n * type: \"studio.start.vm\",\n * options: { imageId: id },\n * });\n */\nconst sendIntent = (intent: Intent): void => {\n if (EventBus.hasEventSubscriptions(`/kos/intent/${intent.type}`)) {\n EventBus.publish(`/kos/intent/${intent.type}`, intent.options, {\n \"kos.intent.type\": intent.type,\n });\n } else {\n log.info(`No subscribers for intent ${intent.type}. Intent not sent.`);\n }\n};\n\n/**\n * Sends an intent and waits for a response. Returns a promise that resolves with the response or a timeout error after 1 second.\n *\n * - If there are subscribers, a unique request ID is generated and used for the response channel.\n * - If no subscribers, resolves with `body: undefined`.\n *\n * @template R - The expected response body type.\n * @param {Intent} intent - The intent to send.\n * @returns {Promise<ServiceResponse<{ body: R | undefined; payload: ApiCallback<R> | undefined }>>}\n *\n * @example\n * sendAsyncIntent({\n * type: \"studio.start.vm\",\n * options: { imageId: id },\n * }).then(([error, data]) => {\n * if (error) {\n * log.error(`Error starting VM: ${error}`);\n * } else if (data) {\n * log.warn(`result: ${JSON.stringify(data, null, 2)}`);\n * }\n * });\n */\nconst sendAsyncIntent = async <R = any>(\n intent: Intent\n): Promise<\n ServiceResponse<{ body: R | undefined; payload: ApiCallback<R> | undefined }>\n> =>\n new Promise((resolve) => {\n const { type, options: payload } = intent;\n if (EventBus.hasEventSubscriptions(`/kos/intent/${intent.type}`)) {\n const requestId = uuid();\n\n const { unsubscribe } = EventBus.subscribe(\n requestId,\n (response: ApiCallback<R> | undefined) => {\n clearTimeout(timeout);\n unsubscribe();\n if (response) {\n response.headers = response.headers || {};\n response.headers[\"kos.intent.type\"] = type;\n response.headers[\"responseId\"] = requestId;\n }\n\n resolve([null, { body: response?.body, payload: response }]);\n }\n );\n const timeout = setTimeout(() => {\n unsubscribe();\n resolve([`Intent ${type} timed out after 1 second`, null]);\n console.warn(`Intent ${type} timed out after 1 second`);\n }, 1000);\n EventBus.publish(`/kos/intent/${type}`, payload, {\n \"kos.intent.type\": type,\n sync: requestId,\n });\n } else {\n log.info(`No subscribers for intent ${intent.type}. Intent not sent.`);\n resolve([null, { body: undefined, payload: undefined }]);\n }\n });\n\nexport { sendAsyncIntent, sendIntent };\n","/**\n * Service for waiting for KOS applications to start\n * Provides utilities to wait for specific apps before proceeding with initialization\n */\n\nimport { EventBusState } from \"../../../common/events\";\n\nimport { kosFetch, type KosServiceResponse } from \"../../util/kos-fetch\";\nimport { KosLog } from \"../log\";\n\nconst log = KosLog.createLogger({ name: \"app-startup-service\" });\n\n/**\n * Interface representing a started KOS application\n */\nexport interface KosStartedApp {\n stopped: boolean;\n appId: string;\n started: boolean;\n sectionName: string;\n postStarted: boolean;\n parentAppId: string;\n}\n\n/**\n * Options for waiting for app startup\n */\nexport interface WaitForAppsOptions {\n /** Timeout in milliseconds (default: 30000) */\n timeout?: number;\n /** Whether to throw error if apps don't start (default: true) */\n throwOnTimeout?: boolean;\n /** Whether apps must be fully post-started (default: false) */\n requirePostStarted?: boolean;\n}\n\n/**\n * Wait for specific KOS applications to be started\n *\n * @param appIds - Array of application IDs to wait for\n * @param options - Configuration options\n * @returns Promise that resolves when all apps are started\n *\n * @example\n * ```typescript\n * // Wait for single app\n * await waitForAppsToStart(['kosdev.ddk']);\n *\n * // Wait for multiple apps with custom timeout\n * await waitForAppsToStart([\n * 'kosdev.ddk',\n * 'com.kondra.summer.2025.controlledPourPlugin'\n * ], { timeout: 60000 });\n *\n * // Wait without throwing on timeout\n * const success = await waitForAppsToStart(['kosdev.ddk'], {\n * throwOnTimeout: false\n * });\n * ```\n */\nexport async function waitForAppsToStart(\n appIds: string[],\n options: WaitForAppsOptions = {}\n): Promise<boolean> {\n const {\n timeout = 30000,\n throwOnTimeout = true,\n requirePostStarted = false,\n } = options;\n\n if (appIds.length === 0) {\n log.warn(\"No app IDs provided to waitForAppsToStart\");\n return true;\n }\n\n log.debug(`Waiting for apps to start: ${appIds.join(\", \")}`);\n\n try {\n // Generate event topics for each app\n const eventTopics = appIds.map((appId) => `/kos/app/started/${appId}`);\n\n const startedApps = await EventBusState.waitForAllWithState<\n KosStartedApp[]\n >(eventTopics, {\n getCurrentState: async () => {\n try {\n const { default: api } = await import(\n \"../../../models/utils/service\"\n );\n\n const [error, data] = await api.get(\"/api/kos/apps/started\");\n if (error) {\n log.error(\"Error fetching started apps:\", error);\n return [];\n }\n return data as KosStartedApp[];\n\n // const response = await kosFetch(\"kos:///api/kos/apps/started\");\n // if (response.ok) {\n // const result: KosServiceResponse<KosStartedApp[]> | null =\n // await response.json();\n // return result?.data ?? [];\n // }\n } catch (error) {\n log.error(\"Failed to fetch app startup status:\", error);\n }\n return [];\n },\n shouldUseFetchedState: (apps) =>\n appIds.every((appId) => {\n const app = apps.find((a) => a.appId === appId);\n if (!app) return false;\n\n // Check if app is started\n if (!app.started) return false;\n\n // Check post-started if required\n if (requirePostStarted && !app.postStarted) return false;\n\n return true;\n }),\n timeout,\n });\n\n // Verify all apps are properly started\n const notStartedApps = appIds.filter((appId) => {\n const app = startedApps.find((a) => a.appId === appId);\n if (!app) return true;\n if (!app.started) return true;\n if (requirePostStarted && !app.postStarted) return true;\n return false;\n });\n\n if (notStartedApps.length > 0) {\n const message = `Apps not started: ${notStartedApps.join(\", \")}`;\n log.error(message);\n\n if (throwOnTimeout) {\n throw new Error(`App startup timeout: ${message}`);\n }\n return false;\n }\n\n log.info(`All apps started successfully: ${appIds.join(\", \")}`);\n return true;\n } catch (error) {\n const message = `Failed to wait for apps to start: ${appIds.join(\", \")}`;\n log.error(message, error);\n\n if (throwOnTimeout) {\n throw new Error(\n `${message} - ${error instanceof Error ? error.message : String(error)}`\n );\n }\n return false;\n }\n}\n\n/**\n * Wait for a single KOS application to start (convenience function)\n *\n * @param appId - Application ID to wait for\n * @param options - Configuration options\n * @returns Promise that resolves when app is started\n */\nexport async function waitForAppToStart(\n appId: string,\n options: WaitForAppsOptions = {}\n): Promise<boolean> {\n return waitForAppsToStart([appId], options);\n}\n\n/**\n * Check if specific apps are currently started (no waiting)\n *\n * @param appIds - Array of application IDs to check\n * @param requirePostStarted - Whether to require post-started status\n * @returns Promise resolving to status of each app\n */\nexport async function checkAppsStarted(\n appIds: string[],\n requirePostStarted = false\n): Promise<Record<string, boolean>> {\n const result: Record<string, boolean> = {};\n\n try {\n const response = await kosFetch(\"kos:///api/kos/apps/started\");\n if (!response.ok) {\n appIds.forEach((appId) => (result[appId] = false));\n return result;\n }\n\n const serviceResponse: KosServiceResponse<KosStartedApp[]> | null =\n await response.json();\n const apps = serviceResponse?.data ?? [];\n\n appIds.forEach((appId) => {\n const app = apps.find((a) => a.appId === appId);\n result[appId] =\n app?.started === true &&\n (!requirePostStarted || app?.postStarted === true);\n });\n } catch (error) {\n log.error(\"Failed to check app startup status:\", error);\n appIds.forEach((appId) => (result[appId] = false));\n }\n\n return result;\n}\n\n/**\n * Get all currently started apps\n *\n * @returns Promise resolving to array of started apps\n */\nexport async function getStartedApps(): Promise<KosStartedApp[]> {\n try {\n const response = await kosFetch(\"kos:///api/kos/apps/started\");\n if (!response.ok) {\n return [];\n }\n\n const result: KosServiceResponse<KosStartedApp[]> | null =\n await response.json();\n return result?.data ?? [];\n } catch (error) {\n log.error(\"Failed to fetch started apps:\", error);\n return [];\n }\n}\n","import {\n autorun,\n computed,\n makeAutoObservable,\n makeObservable,\n observable,\n reaction,\n runInAction,\n when,\n} from \"mobx\";\nexport * from \"./core/api\";\nexport * from \"./core/context\";\nexport * from \"./core/decorators\";\nexport * from \"./core/extension\";\nexport * from \"./core/indexing\";\nexport * from \"./core/kos-container-index\";\nexport * from \"./core/kos-container-model\";\nexport * from \"./core/kos-data-container\";\nexport * from \"./core/kos-model-factory\";\nexport * from \"./core/kos-registration\";\nexport * from \"./core/kos-singleton-registration\";\nexport * from \"./core/kosCore\";\nexport * from \"./core/kosModel\";\nexport * from \"./core/kosModelManager\";\nexport { KosModelEvents, KosModelState } from \"./core/lifecycle\";\nexport * from \"./core/log\";\nexport { KosLoggerFactory } from \"./core/model/kos-logger-factory\";\nexport {\n clearModelHookCacheEntry,\n modelHookCache,\n type ModelHookCacheEntry,\n} from \"./core/model/model-hook-cache\";\nexport * from \"./core/models\";\nexport { default as KosToken } from \"./core/models/kos-token\";\nexport {\n KosModelRegistrationFactory,\n preloadKosModel,\n registerCompanionModel,\n registerKosModel,\n registerLegacyModel,\n RegistrationManager,\n SingletonKosModelRegistrationFactory,\n type KosModelRegistrationType,\n type KosRegistrationFor,\n type RegistrationResult,\n} from \"./core/registration\";\nexport * from \"./core/services\";\nexport * from \"./core/transport\";\nexport * from \"./core/types\";\nexport * from \"./types\";\nexport * from \"./util\";\nexport {\n kosAction,\n kosAutoEffect,\n kosComputed,\n kosEffect,\n kosObservable,\n kosWhen,\n makeAutoObservable,\n makeObservable,\n};\n\n/**\n * {@inheritDoc when}\n * @category Utility\n */\nconst kosWhen = when;\n\n/**\n * {@inheritDoc computed}\n * @category Utility\n */\nconst kosComputed = computed;\n/**\n * {@inheritDoc runInAction}\n * @category Utility\n */\nconst kosAction = runInAction;\n\n/**\n * Creates a named reactive view and keeps it alive, so that the view is always updated if one of the dependencies changes, even when the view is not further used by something else.\n *\n * @param view — The reactive view\n *\n * @returns — disposer function, which can be used to stop the view from being updated in the future.\n * @category Utility\n */\nconst kosAutoEffect = autorun;\n\n/**\n * {@inheritDoc reaction}\n * @category Utility\n */\nconst kosEffect = reaction;\n\n/**\n * {@inheritDoc observable}\n * @category Utility\n */\nconst kosObservable = observable;\n","export {};\n\nexport const FUTURE_NOT_ASSIGNED = \"Not Assigned\";\nexport const EVENT_TROUBLE_ADDED = \"kos.trouble.added\";\nexport const EVENT_TROUBLE_REMOVED = \"kos.trouble.removed\";\nexport enum KosCoreModelPropertyMapper {\n TroubleRank = \"kos.trouble.rank.mapper\",\n TroubleColor = \"kos.trouble.color.mapper\",\n TroubleRole = \"kos.trouble.role.mapper\",\n RegionServicePath = \"kos.region.service_path.mapper\",\n ConfigServicePath = \"kos.config.service_path.mapper\",\n}\n\n/**\n * Enum for the different message bus topics that are used in the KOS system.\n */\nexport enum Topics {\n TIME_CHANGE = \"/kos/internal/time/time\",\n DAY_CHANGE = \"/kos/internal/time/day\",\n TIMEZONE_CHANGE = \"/kos/internal/time/timezone\",\n}\n","import { BASE_URL, KosLog, ServiceFactory } from \"../../../core\";\nimport { ConfigPropertyTypes } from \"../../models\";\n\nconst log = KosLog.createLogger({\n name: \"config-bean-service\",\n group: \"Services\",\n});\n\nconst URL = BASE_URL;\n\n/**\n * @category Service Module\n * @name /services/config-bean\n * @version 1.0.0\n * @author Mark Pomerant <mpomerant@coca-cola.com>\n *\n * Services that can be invoked to perform operations on Config Beans\n */\n\n/**\n * The response from the server when an organization is\n * created or updated\n */\nexport interface ConfigBeanResponse {\n scopes: string[];\n details: ConfigBeanDetailsResponse[];\n}\n\nexport interface ConfigScope {\n scope: string;\n overrides?: Record<string, ConfigPropertyTypes>;\n}\n\nexport interface ConfigBeanDetailsResponse {\n bean: {\n [key: string]: ConfigPropertyTypes;\n };\n scopes: ConfigScope[];\n schema: SchemaResponse;\n}\n\nexport interface ConfigBeanRequest {\n [k: string]: ConfigPropertyTypes;\n}\n\nexport interface DecimalOption {\n decimals: number;\n}\n\nexport const hasDecimals = (option?: any): option is DecimalOption =>\n (option as DecimalOption)?.decimals !== undefined;\nexport type SchemaNodeType = \"String\" | \"int\" | \"boolean\" | \"double\";\nexport interface UnitSystemKeypadOptions {\n unitSystems: {\n [k: string]: {\n min: number;\n max: number;\n decimals: number;\n };\n };\n type: \"unitSystemKeypad\";\n}\n\nexport interface UnitSystemListOptions {\n type: \"unitSystemList\";\n unitSystems: {\n [k: string]: {\n list: string[];\n };\n };\n}\n\nexport interface UnitSystemRangeCountOptions {\n type: \"unitSystemRangeCount\";\n unitSystems: {\n [k: string]: {\n start: number;\n end: number;\n count: number;\n decimals: number;\n };\n };\n}\n\nexport interface UnitSystemRangeIntervalOptions {\n type: \"unitSystemRangeInterval\";\n unitSystems: {\n [k: string]: {\n start: number;\n end: number;\n interval: number;\n decimals: number;\n };\n };\n}\nexport interface KeypadOptions {\n min: number;\n max: number;\n decimals: number;\n type: \"keypad\";\n}\n\nexport interface RangeCountOptions {\n type: \"rangeCount\";\n start: number;\n end: number;\n count: number;\n decimals: number;\n}\n\nexport interface RangeIntervalOptions {\n type: \"rangeInterval\";\n start: number;\n end: number;\n interval: number;\n decimals: number;\n}\nexport interface ListOptions {\n type: \"list\";\n list: string[];\n}\n\nexport type SchemaOptionsType =\n | KeypadOptions\n | RangeCountOptions\n | RangeIntervalOptions\n | ListOptions\n | UnitSystemKeypadOptions\n | UnitSystemListOptions\n | UnitSystemRangeCountOptions\n | UnitSystemRangeIntervalOptions;\n\nexport interface SchemaNode {\n type: SchemaNodeType;\n format?: string;\n options: SchemaOptionsType;\n}\n\nexport interface EnumSchemaNode {\n type: \"enum\";\n format?: string;\n values: string[];\n}\n\nexport type SchemaNodeDef = SchemaNode | EnumSchemaNode;\nexport interface SchemaResponse {\n paths: string[];\n schema: {\n [key: string]: SchemaNodeDef;\n };\n}\n\nconst { postModel, getOne } = ServiceFactory.build({\n destinationAddress: \"\",\n basePath: `${URL}/kos/config/`,\n});\n\nexport interface ConfigBeanUpdateRecord {\n attr: string;\n currentValue: string;\n previousValue: string;\n}\n\nexport interface ConfigBeanUpdateResponse {\n changes: ConfigBeanUpdateRecord[];\n scopedChanges: ConfigBeanUpdateRecord[];\n errors: string[];\n}\n/**\n * Modifies an ConfigBean from the server based on the id.\n *\n * @param id - the id of the ConfigBean to be modified\n * @returns an empty response with status 200.\n */\nexport const modifyConfigBean = async (\n id: string,\n model: ConfigBeanRequest,\n path = `/api/kos/config`,\n destinationAddress = \"\"\n) => {\n log.debug(`sending modify request for ConfigBean: ${id}`);\n const response = postModel({\n model,\n urlOverride: `${URL}${path}/${id}`,\n destinationAddress,\n });\n return response;\n};\n\n/**\n * Modifies an ConfigBean from the server based on the id.\n *\n * @param id - the id of the ConfigBean to be modified\n * @returns an empty response with status 200.\n */\nexport const getConfigBean = async (\n id: string,\n path = `/api/kos/config`,\n destinationAddress = \"\"\n) => {\n log.debug(`sending get request for ConfigBean: ${id}`);\n const response = await getOne<ConfigBeanResponse>({\n urlOverride: `${URL}${path}/details/${id}/15`,\n destinationAddress,\n });\n return response;\n};\n","export const isBoolean = (val: string) =>\n val.toLowerCase() === \"true\" || val.toLowerCase() === \"false\";\n\nexport const isNumber = (val: string) => {\n try {\n const result = Number(val);\n return !isNaN(result);\n } catch (e) {\n return false;\n }\n};\n","import { runInAction } from \"mobx\";\nimport { ModelFactory } from \"../../../core\";\nimport {\n ConfigBeanRequest,\n ConfigBeanResponse,\n ConfigBeanUpdateResponse,\n type ConfigBeanUpdateRecord,\n type ConfigScope,\n} from \"../../services/config-bean\";\nimport { isBoolean, isNumber } from \"../../utils/prop-utils\";\nimport { ConfigPropertyTypes } from \"../types\";\nimport type { IConfigBeanModel } from \"./config-bean-model\";\nimport type { IConfigBeanModelOptions } from \"./config-bean-types\";\n\nexport function evaluateScopes(scopes: ConfigScope[] = []) {\n return scopes.reverse().reduce((acc, curr) => {\n const { overrides } = curr;\n if (overrides) {\n acc = { ...acc, ...overrides };\n }\n return acc;\n }, {});\n}\nfunction flattenObject(obj: any, parentKey = \"\", result = {}) {\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n // Construct new key for the flattened object\n const newKey = parentKey ? `${parentKey}.${key}` : key;\n\n if (\n typeof obj[key] === \"object\" &&\n obj[key] !== null &&\n !Array.isArray(obj[key])\n ) {\n // Recursively flatten for nested objects\n flattenObject(obj[key], newKey, result);\n } else {\n // Assign value to the new key in the flattened object\n result[newKey] = obj[key];\n }\n }\n }\n return result;\n}\n/**\n * Maps a `ConfigBeanResponse` DTO to an `IConfigBeanModel` object.\n *\n * @remarks\n * This function will run as a mobx action ensuring that all observers are notified\n * if any changes are made.\n *\n * @params dto - the Data Transfer Object received from the backend\n * @params model - the IModel to be update\n *\n * @internal\n * @category Config Bean\n */\nexport const mapDtoToConfigBeanModel = (\n dto: ConfigBeanResponse,\n model: IConfigBeanModel\n) => {\n const bean = dto.details[0].bean || evaluateScopes(dto.details[0].scopes);\n const flattened = flattenObject(bean);\n runInAction(() => {\n const values = {\n ...flattened,\n };\n\n model.props.setValues(values);\n });\n};\n\nexport const mapUpdateDtoToConfigBeanModel = (\n dto: ConfigBeanUpdateResponse,\n model: IConfigBeanModel\n) => {\n runInAction(() => {\n const changesMap = dto.changes.reduce<\n Record<string, ConfigBeanUpdateRecord>\n >((acc, change) => {\n acc[change.attr] = change;\n return acc;\n }, {});\n\n const scopedChangesMap = dto.scopedChanges.reduce<\n Record<string, ConfigBeanUpdateRecord>\n >((acc, change) => {\n const c = acc[change.attr];\n if (c) {\n // If there's already a change for this attribute, we need to merge them\n acc[change.attr] = {\n ...c,\n currentValue: change.currentValue ?? c.currentValue, // The most recent value should be the current value\n previousValue: change.previousValue ?? c.previousValue, // The original previous value should be preserved\n };\n }\n return acc;\n }, changesMap);\n const allChanges = Object.values(scopedChangesMap);\n allChanges.forEach((change) => {\n const key = change.attr;\n let val: ConfigPropertyTypes = change.currentValue;\n let previousValue: ConfigPropertyTypes = change.previousValue;\n\n if (typeof val === \"string\" && isBoolean(val)) {\n val = val.toLowerCase() == \"true\";\n previousValue = (previousValue as string)?.toLowerCase() == \"true\";\n }\n\n if (typeof val === \"string\" && isNumber(val)) {\n val = Number(val);\n previousValue = Number(previousValue);\n }\n\n model.props[key] = val;\n model.prevProps[key] = previousValue;\n });\n });\n};\n\n/**\n * Maps a `IConfigBeanModel` to a `ConfigBeanRequest` DTO that can be sent to the\n * server as part of a service request.\n *\n * @remarks\n * This function will perform any type conversion or data mapping required\n * by the `ConfigBeanRequest`.\n *\n * @params model - instance of the `IConfigBeanModel`\n * @returns - a valid `ConfigBeanRequest` that can be used to\n * instantiate a new model.\n *\n * @internal\n * @group KOS Model\n * @category Configuration\n */\nexport const mapConfigBeanModelToDto = (model: IConfigBeanModel) => {\n const dto: ConfigBeanRequest = Object.fromEntries(model.props.entries);\n\n return dto;\n};\n\n/**\n * Curried function that will produce a function that can be used to retreive or create\n * new instances of a `IConfigBeanModel` given an ID and options.\n *\n * @remarks\n * This serves as a conveinience allowing for models to consumers to use a shorthand method when\n * multiple models need to be created.\n * The first level of function will accept a KOS Model Factory and return a function that can accept a single\n * model ID parameeter. This will return a factory function that can accept a model options parameter and\n * instantiate a new instance of a model or retreive a an existing model.\n *\n * @param factory - the model factory to be used\n * @returns - an instance of the `IConfigBeanModel` that was either created\n * or retrieved from the KOS Model framework if already existing.\n *\n * @internal\n * @group KOS Model\n * @category Configuration\n */\nexport const buildConfigBeanModel =\n (factory: ModelFactory<IConfigBeanModel, IConfigBeanModelOptions>) =>\n (modelId: string) =>\n (configBeanOptions: IConfigBeanModelOptions) => {\n const configBeanModel = factory.build(modelId, configBeanOptions);\n return configBeanModel;\n };\n","import type {\n IKosDataModel,\n KosData,\n PublicModelInterface,\n} from \"../../../core\";\nimport {\n createPropKey,\n ExtensionManager,\n kosAction,\n kosModel,\n KosModelRegistrationFactory,\n kosTopicHandler,\n ObservableData,\n} from \"../../../core\";\nimport type {\n ConfigBeanKeys,\n IConfigBeanModelOptions,\n} from \"./config-bean-types\";\n\nimport { KosLog as Logger } from \"../../../core\";\nimport { KosCoreModelPropertyMapper } from \"../../constants\";\nimport {\n getConfigBean as getConfigBeanService,\n modifyConfigBean as modifyConfigBeanService,\n type ConfigBeanUpdateResponse,\n type SchemaResponse,\n} from \"../../services/config-bean\";\nimport { ConfigPropertyTypes } from \"../types\";\nimport {\n mapConfigBeanModelToDto,\n mapDtoToConfigBeanModel,\n mapUpdateDtoToConfigBeanModel,\n} from \"./config-bean-model-builder\";\n\n/**\n * ConfigBean - Reactive hierarchical configuration management for KOS devices.\n *\n * The ConfigBean model provides reactive access to hierarchical configuration data from KOS devices\n * with real-time synchronization via WebSocket topics, schema-based validation, and transactional\n * updates. Essential for building configuration interfaces and managing device operational parameters.\n *\n * ## Key Features\n * - **Hierarchical Configuration** - Access nested configuration structures using path notation\n * - **Real-Time Synchronization** - Automatic updates via `/kos/config/{path}` WebSocket topic\n * - **Schema-Based Validation** - Built-in validation using device configuration schemas\n * - **Transactional Updates** - Atomic configuration changes with rollback support\n * - **Type-Safe Access** - Strongly typed property access with TypeScript support\n * - **Reactive Properties** - Automatic UI updates when configuration changes\n *\n * ## Configuration Path Patterns\n * ConfigBean supports hierarchical paths that mirror device system organization:\n * - **System Level**: `system:app` - Machine identity, operational modes\n * - **Service Level**: `kos:service:CANPumpMgr` - KOS service configurations\n * - **Hardware Level**: `assembly:core:board:macro:pump:water` - Component settings\n * - **Application Level**: `app:scheduling:dayWiseLockConfigMap` - Application-specific settings\n *\n * ## Common Use Cases\n * - **Configuration Interfaces** - Build reactive configuration management screens\n * - **Operational Parameter Control** - Real-time adjustment of device behavior\n * - **Schema-Driven Forms** - Generate configuration UIs from device schemas\n * - **System Administration** - Centralized device configuration management\n * - **Bulk Configuration Updates** - Transactional updates across multiple properties\n *\n * @example Basic Configuration Management\n * ```typescript\n * const systemConfig = ConfigBean.instance('system-config')\n * .options({ path: 'system:app' })\n * .build();\n *\n * // Access current configuration values\n * const machineId = systemConfig.values.machineId;\n * const debugMode = systemConfig.values.debugMode;\n *\n * // Update configuration properties\n * await systemConfig.updateProperty('debugMode', true);\n * await systemConfig.updateProperty('machineId', 'MACHINE-001');\n * ```\n *\n * @interface\n * @group KOS Model\n * @category Configuration\n * @useDeclaredType\n *\n * @see {@link IConfigBeanModelOptions} - Configuration options for ConfigBean instances\n * @see {@link ConfigBeanKeys} - Type-safe property key access\n * @see {@link ConfigPropertyTypes} - Supported configuration property types\n */\nexport type IConfigBeanModel<T extends {} = any> = PublicModelInterface<\n ConfigBeanModelImpl<T>\n>;\n\nfunction matchValue(patterns: string[], value: string): string | undefined {\n for (const pattern of patterns) {\n // Convert the pattern to a RegExp object\n const regex = new RegExp(`^${pattern}$`);\n if (regex.test(value)) {\n return pattern; // Return the matching pattern\n }\n }\n return undefined; // No match found\n}\nexport const CONFIG_BEAN_MODEL_TYPE = \"config-bean-model\";\nconst log = Logger.getLogger(CONFIG_BEAN_MODEL_TYPE);\n\nconst PATH_PROP = createPropKey<IConfigBeanModel>(\"path\");\nconst DESTINATION_PROP = createPropKey<IConfigBeanModel>(\"destinationAddress\");\n\n/**\n * Model id of the bean for a config path; the destination is part of the id\n * so the same path on two devices never shares one bean.\n * @ignore\n * @internal\n */\nexport function configBeanModelId(\n path: string,\n destinationAddress?: string\n): string {\n return destinationAddress\n ? `${CONFIG_BEAN_MODEL_TYPE}-${destinationAddress}-${path}`\n : `${CONFIG_BEAN_MODEL_TYPE}-${path}`;\n}\n\nfunction servicePathMapper<T extends {}>(\n configBeanModel: IConfigBeanModel<T>\n): string {\n const hasMapper = ExtensionManager.propertyMapper.hasMapper(\n KosCoreModelPropertyMapper.ConfigServicePath\n );\n if (hasMapper) {\n return ExtensionManager.propertyMapper.executeMapper(\n KosCoreModelPropertyMapper.ConfigServicePath,\n configBeanModel\n );\n }\n return \"/api/kos/config\";\n}\n\n/**\n * @ignore\n * @internal\n */\n@kosModel(CONFIG_BEAN_MODEL_TYPE)\nclass ConfigBeanModelImpl<T extends {} = any> implements IKosDataModel {\n /** Service function for modifying configuration beans */\n private _modifyConfigBean: typeof modifyConfigBeanService;\n\n /** Service function for retrieving configuration beans */\n private _getConfigBean: typeof getConfigBeanService;\n\n /** Schema response containing configuration property definitions */\n private _schema?: SchemaResponse;\n /** Unique identifier for this configuration model instance */\n id: string;\n /** Hierarchical configuration path (e.g., 'system:app', 'kos:service:CANPumpMgr') */\n path: string;\n /** Observable configuration properties with current values */\n props: KosData<Record<ConfigBeanKeys<T>, ConfigPropertyTypes>>;\n\n /** Observable configuration properties with previous values (before last update) */\n prevProps: KosData<Record<ConfigBeanKeys<T>, ConfigPropertyTypes>>;\n\n /** Optional custom base path for configuration service endpoints */\n serviceBasePath?: string;\n /** Connection the bean's requests and topic subscription are routed to */\n destinationAddress?: string;\n /**\n * @category Constructor\n *\n * @param modelId - the unique modelId for this Config Bean\n * @param options - any options that should be merged into the Config Bean\n * @params options.id - the unique id of the Config Bean\n * @params options.name - the name of the Config Bean\n *\n */\n constructor(modelId: string, options: IConfigBeanModelOptions) {\n Object.assign(this, options);\n\n // assign the id from the passed in model id\n this.id = modelId;\n this.path = options.path;\n this.serviceBasePath = options.serviceBasePath || servicePathMapper(this);\n this.destinationAddress = options.destinationAddress;\n // assign private methods from options\n const {\n modifyConfigBean = modifyConfigBeanService,\n getConfigBean = getConfigBeanService,\n } = options;\n this._modifyConfigBean = modifyConfigBean;\n this._getConfigBean = getConfigBean;\n\n this.props =\n ObservableData<Record<ConfigBeanKeys<T>, ConfigPropertyTypes>>();\n this.prevProps =\n ObservableData<Record<ConfigBeanKeys<T>, ConfigPropertyTypes>>();\n }\n\n /**\n * Gets current configuration property values.\n *\n * @returns Object containing all configuration properties with their current values\n *\n * @example Access Configuration Values\n * ```typescript\n * const currentValues = systemConfig.values;\n * console.log('Machine ID:', currentValues.machineId);\n * console.log('Debug Mode:', currentValues.debugMode);\n * ```\n */\n get values() {\n return this.props.values;\n }\n\n /**\n * @internal\n */\n async ready() {\n log.debug(`readying config bean ${this.path}`);\n log.debug(`complete readying config bean ${this.path}`);\n }\n /**\n * @internal\n *\n * @remarks\n * No action is taken as part of the load lifecycle method.\n *\n * In future additional information about the workspace could be loaded\n */\n async load() {\n log.debug(`loading config bean ${this.path}`);\n const response = await this._getConfigBean(\n this.path,\n this.serviceBasePath,\n this.destinationAddress\n );\n if (response?.data) {\n const data = response.data;\n mapDtoToConfigBeanModel(data, this as IConfigBeanModel<T>);\n log.debug(this.values);\n const schemaResponse = response?.data.details[0].schema;\n kosAction(() => {\n if (schemaResponse) {\n this._schema = schemaResponse;\n }\n });\n }\n }\n\n /**\n * Gets all available schema property keys.\n *\n * @returns Array of property keys from the configuration schema\n */\n get schemaKeys() {\n return Object.keys(this._schema?.schema || {});\n }\n\n /**\n * Retrieves schema definition for a specific property.\n *\n * @param key - Property key to get schema for\n * @returns Schema definition if found, undefined otherwise\n *\n * @example Get Property Schema\n * ```typescript\n * const schema = systemConfig.getSchemaForProperty('debugMode');\n * if (schema) {\n * console.log('Type:', schema.type);\n * console.log('Description:', schema.description);\n * }\n * ```\n */\n getSchemaForProperty(key: string) {\n if (this.schemaKeys.includes(key)) {\n return this._schema?.schema[key];\n }\n const match = matchValue(this.schemaKeys, key);\n if (match) {\n return this._schema?.schema[match];\n }\n return undefined;\n }\n\n // -------------------ACTIONS----------------------------\n\n /**\n * Updates a specific configuration property value.\n *\n * @category Action\n *\n * @param key - The configuration property key to update\n * @param value - The new value to set for the property\n *\n * @example Update Configuration Property\n * ```typescript\n * await systemConfig.updateProperty('debugMode', true);\n * await systemConfig.updateProperty('machineId', 'MACHINE-001');\n * ```\n */\n async updateProperty(key: ConfigBeanKeys<T>, value: ConfigPropertyTypes) {\n this.props[key as string] = value;\n await this.updateConfigBean();\n }\n /**\n * @category Action\n *\n * @remark\n * Updates the current Config Bean representation in the backend.\n *\n * If a service was passed in as part of the options in the constructor\n * then it will be used. Otherwise the default services will be invoked.\n *\n * @see modifyConfigBeanService\n */\n async updateConfigBean() {\n const request = mapConfigBeanModelToDto(this as IConfigBeanModel<T>);\n await this._modifyConfigBean(\n this.path,\n request,\n this.serviceBasePath,\n this.destinationAddress\n );\n }\n\n // ------------------SUBSCRIPTIONS----------------------\n\n /**\n * @category Subscription\n * Updates the Config Bean model when a `/kos/config/{path}` event\n * is received from the server.\n *\n * @param configBean - the Config Bean that was updated.\n * @see ConfigBeanResponse\n */\n @kosTopicHandler({\n topic: `/kos/config/${PATH_PROP}`,\n websocket: true,\n destinationAddress: DESTINATION_PROP,\n explicitDestination: true,\n })\n handleConfigBeanUpdated(configBean: ConfigBeanUpdateResponse) {\n mapUpdateDtoToConfigBeanModel(configBean, this as IConfigBeanModel<T>);\n }\n}\n\nexport const ConfigBean = new KosModelRegistrationFactory<\n IConfigBeanModel,\n IConfigBeanModelOptions\n>({\n class: ConfigBeanModelImpl<any>,\n type: CONFIG_BEAN_MODEL_TYPE,\n});\n","/**\n * @internal\n */\nimport { ServiceFactory, resolveServiceUrl } from \"../../../../core\";\nconst { URL } = resolveServiceUrl(\"REGION_INFO_SERVICE\");\nconst { getOne, getAll } = ServiceFactory.build({\n basePath: `${URL}/api/kos/regions/info`,\n});\n\nexport interface DateFormat {\n id: string;\n format: string;\n order: string;\n}\nexport interface TimeFormat {\n id: string;\n format: string;\n ampm: boolean;\n}\nexport interface Unit {\n measure: string;\n name: string;\n scale: number;\n offset: number;\n decimals: number;\n alias: string;\n def: boolean;\n}\nexport interface UnitSystem {\n id: string;\n units: Unit[];\n}\nexport interface RegionInfoResponse {\n unitSystems: UnitSystem[];\n timeFormats: TimeFormat[];\n dateFormats: DateFormat[];\n}\n\nexport interface BaseRegionResponse {\n id: string;\n country: string;\n timeFormatId: string;\n dateFormatId: string;\n unitSystemId: string;\n timeZones: string[];\n hidden: boolean;\n}\nexport type RegionsResponse<\n AdditionalData extends BaseRegionResponse = BaseRegionResponse\n> = BaseRegionResponse & {\n [key in keyof AdditionalData]: AdditionalData[key];\n};\n/**\n * @category Service\n * @internal\n * Retrieves the initial Region Info data.\n */\nexport const getRegionInfo = async (\n baseServicePath: string,\n destinationAddress = \"\"\n) => {\n try {\n const response = await getOne<RegionInfoResponse>({\n urlOverride: `${URL}${baseServicePath}/info`,\n destinationAddress,\n });\n return response;\n } catch (error) {\n return undefined;\n }\n};\n\nexport const getRegions = async (\n baseServicePath: string,\n destinationAddress = \"\"\n) => {\n try {\n const response = await getAll<RegionsResponse>({\n urlOverride: `${URL}${baseServicePath}`,\n destinationAddress,\n });\n return response;\n } catch (error) {\n return undefined;\n }\n};\n","import { IKosDataModel } from \"../../../../core\";\nimport { BaseRegionResponse, RegionsResponse, Unit } from \"../services\";\n\n/**\n * Unit conversion source specification for the conversion system.\n *\n * Flexible specification allowing conversion by specific unit name or by\n * measurement system with automatic unit selection. The conversion system\n * intelligently selects appropriate default units when only system/measure is provided.\n *\n * @example Specific Unit Conversion\n * ```typescript\n * const fahrenheitSource: UnitSource = { unit: 'fahrenheit' };\n * const celsiusSource: UnitSource = { unit: 'celsius' };\n *\n * const result = regionModel.convert(72, fahrenheitSource, celsiusSource);\n * console.log(result); // '22.22'\n * ```\n *\n * @example System-Based Conversion (Auto Unit Selection)\n * ```typescript\n * const imperialLength: UnitSource = { measure: 'length', system: 'imperial' };\n * const metricLength: UnitSource = { measure: 'length', system: 'metric' };\n *\n * // Automatically uses miles → kilometers\n * const result = regionModel.convert(5, imperialLength, metricLength);\n * console.log(result); // '8.047'\n * ```\n *\n * @kosService core.region-info\n * @group KOS Model\n * @category Region Info\n * @kosApiLevel 2\n */\nexport interface UnitSource {\n /** Measurement system identifier (e.g., 'metric', 'imperial', 'us') */\n system?: string;\n /** Type of measurement (e.g., 'length', 'weight', 'temperature', 'volume') */\n measure?: string;\n /** Specific unit name (e.g., 'meter', 'kilogram', 'fahrenheit') */\n unit?: string;\n}\n\n/**\n * Key type for measure maps — a string or the literal 'default'.\n *\n * @kosService core.region-info\n */\nexport type MeasureMapKeys = string | \"default\";\n\n/**\n * Record mapping MeasureMapKeys to Unit, defining units for each measurement system.\n *\n * @kosService core.region-info\n */\nexport type SystemMeasureMap = Record<MeasureMapKeys, Unit>;\n\n/**\n * Record mapping measurement types to their respective SystemMeasureMap.\n *\n * @kosService core.region-info\n */\nexport type MeasureMap = Record<string, SystemMeasureMap>;\n\n/**\n * Record mapping strings, typically used for default settings.\n *\n * @kosService core.region-info\n */\nexport type SystemDefaultMap = Record<string, string>;\n\n/**\n * Record mapping unit systems to their default settings.\n *\n * @kosService core.region-info\n */\nexport type DefaultMeasureMap = Record<string, SystemDefaultMap>;\n\n/**\n * Configuration options for creating RegionInfoModel instances.\n *\n * Currently an empty interface but reserved for future regional configuration\n * options such as default locale preferences, custom unit mappings, or\n * regional API endpoints.\n *\n * @example\n * ```typescript\n * const options: RegionInfoOptions = {\n * // Future options will be defined here\n * };\n * const regionModel = RegionInfo.instance().options(options).build();\n * ```\n *\n * @kosService core.region-info\n * @group KOS Model\n * @category Region Info\n */\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface RegionInfoOptions {\n /**\n * Connection the region services and settings beans are routed to.\n *\n * Set it when one window shows several devices; the instance is then keyed\n * by device and the default, unrouted instance is left untouched.\n */\n readonly destinationAddress?: string;\n}\n\n// Base interface for options requiring an id.\ninterface BaseOptions {\n id: string; // Unique identifier\n}\n\n// Interface extending BaseOptions with a format property.\ninterface FormatOptions extends BaseOptions {\n format: string; // Format specifier (e.g., date or time format)\n}\n\n/**\n * Time format configuration options for regional time display.\n *\n * Defines available time formats including 12-hour (AM/PM) and 24-hour formats\n * with their display patterns and behavior.\n *\n * @example\n * ```typescript\n * const timeFormats: TimeFormatOptions[] = [\n * { id: '12h', format: 'hh:mm:ss a', ampm: true }, // 3:45:30 PM\n * { id: '24h', format: 'HH:mm:ss', ampm: false } // 15:45:30\n * ];\n * ```\n *\n * @kosService core.region-info\n * @group KOS Model\n * @category Region Info\n * @kosApiLevel 2\n */\nexport interface TimeFormatOptions extends FormatOptions {\n /** True if using 12-hour format with AM/PM, false for 24-hour format */\n ampm: boolean;\n}\n\n/**\n * Date format configuration options for regional date display.\n *\n * Defines available date formats including different component ordering\n * (Day/Month/Year vs Month/Day/Year) and display patterns.\n *\n * @example\n * ```typescript\n * const dateFormats: DateFormatOptions[] = [\n * { id: 'us', format: 'MM/DD/YYYY', order: 'MDY' }, // 03/15/2024\n * { id: 'eu', format: 'DD/MM/YYYY', order: 'DMY' }, // 15/03/2024\n * { id: 'iso', format: 'YYYY-MM-DD', order: 'YMD' } // 2024-03-15\n * ];\n * ```\n *\n * @kosService core.region-info\n * @group KOS Model\n * @category Region Info\n * @kosApiLevel 2\n */\nexport interface DateFormatOptions extends FormatOptions {\n /** Order of date components: 'MDY', 'DMY', 'YMD', etc. */\n order: string;\n}\n\n/**\n * Unit system configuration options for measurement standards.\n *\n * Defines available unit systems (metric, imperial, etc.) with their\n * display names and identification.\n *\n * @example\n * ```typescript\n * const unitSystems: UnitSystemOptions[] = [\n * { id: 'metric', name: 'Metric System' },\n * { id: 'imperial', name: 'Imperial System' },\n * { id: 'us', name: 'US Customary System' }\n * ];\n * ```\n *\n * @kosService core.region-info\n * @group KOS Model\n * @category Region Info\n * @kosApiLevel 2\n */\nexport interface UnitSystemOptions extends BaseOptions {\n /** Display name of the unit system (e.g., 'Metric System', 'Imperial System') */\n name: string;\n}\n\n/**\n * Region Info Model - Comprehensive regional localization and unit conversion system for KOS applications.\n *\n * This singleton model provides centralized management of regional settings including time formats,\n * date formats, unit systems, time zones, and intelligent unit conversion. Essential for building\n * internationally-aware applications that adapt to local preferences and measurement standards.\n *\n * ## Key Features\n * - **Time & Date Formatting** - Configurable 12/24-hour time and various date order formats\n * - **Unit System Management** - Complete metric/imperial conversion with precision control\n * - **Time Zone Support** - Full time zone management with regional associations\n * - **Dynamic Configuration** - Live updates through KOS configuration system\n * - **Type Safety** - Generic support for additional regional data\n * - **Singleton Pattern** - Single instance manages all regional settings\n *\n * ## Unit Conversion System\n * The model provides intelligent unit conversion between different measurement systems:\n * - **Automatic scaling** - Handles complex conversions with proper scaling factors\n * - **Precision control** - Configurable decimal places per unit type\n * - **Family validation** - Prevents invalid conversions (e.g., length to weight)\n * - **Default unit resolution** - Automatic selection of appropriate units per system\n *\n * @template AdditionalData - Extends BaseRegionResponse for custom regional data requirements\n *\n * @interface\n * @example Basic Usage\n * ```typescript\n * const regionModel = RegionInfo.instance().build();\n *\n * // Unit conversion and regional settings\n * const celsius = regionModel.convert(72, { unit: 'fahrenheit' }, { unit: 'celsius' });\n * console.log(regionModel.selectedCountry); // 'us'\n * ```\n *\n * @kosService core.region-info\n * @group KOS Model\n * @category Region Info\n * @useDeclaredType\n *\n * @see {@link UnitSource} - Unit conversion source specification\n * @see {@link RegionInfoOptions} - Configuration options for RegionInfoModel instances\n * @kosApiLevel 2\n */\nexport interface RegionInfoModel<\n AdditionalData extends BaseRegionResponse = BaseRegionResponse\n> extends RegionInfoOptions,\n IKosDataModel {\n /** Unique identifier for the region model instance. */\n readonly id: string;\n\n /** The default unit system (e.g., metric or imperial) for the region. */\n readonly defaultUnitSystem: string;\n\n /** The currently selected unit system. */\n readonly selectedUnitSystem: string;\n\n /** The currently selected time format as a string. */\n readonly selectedTimeFormat: string;\n\n /** The currently selected date format as a string. */\n readonly selectedDateFormat: string;\n\n /** The order of date elements (e.g., day/month/year) for the selected format. */\n readonly selectedDateOrder: string;\n\n /** The currently selected country. */\n readonly selectedCountry: string;\n\n /** The currently selected time zone. */\n readonly selectedTimeZone: string;\n\n /**\n * @kosApiLevel 22\n */\n readonly serviceBasePath: string;\n\n /**\n * The detailed information of the selected region, extended with additional data.\n * The type of additional data is determined by the generic parameter `AdditionalData`.\n */\n selectedRegion: RegionsResponse<AdditionalData>;\n\n /** Flag indicating if the 12-hour time format (AM/PM) is used. */\n is12HourTimeFormat: boolean;\n\n /** An array of available regions as strings. */\n availableRegions: string[];\n\n /** Identifier of the region. */\n regionId: string;\n\n readonly dateFormatId: string;\n readonly timeFormatId: string;\n readonly unitSystemId: string;\n\n /** An array of available time zones as strings. */\n timeZones: string[];\n\n /** An array of all available time zones as strings. */\n allTimeZones: string[];\n\n /** Time format options available for selection. */\n readonly timeFormatOptions: TimeFormatOptions[];\n\n /** Date format options available for selection. */\n readonly dateFormatOptions: DateFormatOptions[];\n\n /** Unit system options available for selection. */\n readonly unitSystemOptions: UnitSystemOptions[];\n\n /**\n * Converts a value from one unit to another.\n *\n * @param value - The numerical value to convert.\n * @param from - The unit source to convert from.\n * @param to - The unit source to convert to.\n * @returns The converted value as a string.\n * @internal\n */\n convert(value: number, from: UnitSource, to: UnitSource): string;\n\n /**\n * Sets the selected time format.\n *\n * @param id - The identifier of the time format to select.\n */\n setSelectedTimeFormat(id: string): void;\n\n /**\n * Sets the selected date format.\n *\n * @param id - The identifier of the date format to select.\n */\n setSelectedDateFormat(id: string): void;\n\n /**\n * Sets the selected unit system.\n *\n * @param id - The identifier of the unit system to select.\n */\n setSelectedUnitSystem(id: string): void;\n\n /**\n * Retrieves the default unit for a given measure in a specified unit system.\n *\n * @param measure - The measure for which to get the default unit.\n * @param unitSystem - The unit system in which to find the default unit.\n * @returns The default unit for the specified measure and system.\n */\n getDefaultUnitForMeasure(measure: string, unitSystem: string): string;\n\n /**\n * Retrieves the measure associated with a given unit.\n *\n * @param unit - The unit for which to get the measure.\n * @returns The measure associated with the specified unit.\n *\n * @internal\n */\n getUnitMeasure: (unit: string) => string;\n\n /**\n *\n * @internal\n */\n getUnitSystem: (unit?: string) => string;\n\n /**\n * Retrieves the default number of decimal places for a unit in a given measure and system.\n *\n * @param measure - The measure to consider.\n * @param unitSystem - The unit system in which the unit is defined.\n * @param unit - Optional specific unit to consider.\n * @returns The number of decimal places for the unit.\n */\n getDefaultUnitDecimalPlaces(\n measure: string,\n unitSystem: string,\n unit?: string\n ): number;\n}\n\n/**\n * Enum for keys used in UnitTuple.\n *\n * @kosService core.region-info\n */\nexport enum UnitTupleKeys {\n family,\n scale,\n offset,\n decimals,\n alias,\n system,\n}\n\n/**\n * Tuple type for unit properties: family, scale, offset, decimals, alias.\n *\n * @kosService core.region-info\n */\nexport type UnitTuple = [\n family: string, // Unit family (e.g., length, volume)\n scale: number, // Scale factor for unit conversion\n offset: number, // Offset for unit conversion\n decimals: number, // Number of decimal places for precision\n alias: string, // Alternative name or alias for the unit\n system: string // Measurement system (e.g., metric, imperial)\n];\n","import { UnitTuple } from \"../types\";\nconst timeTuples = {\n s: [\"time\", 1, 0, 0],\n second: [\"time\", 1, 0, 0],\n m: [\"time\", 1 / 60, 0, 0],\n minute: [\"time\", 1 / 60, 0, 0],\n h: [\"time\", 1 / 3600, 0, 0],\n hour: [\"time\", 1 / 3600, 0, 0],\n day: [\"time\", 1 / 86400, 0, 0],\n week: [\"time\", 1 / 604800, 0, 0],\n month: [\"time\", 1 / 2628000, 0, 0],\n year: [\"time\", 1 / 31536000, 0, 0],\n default: [\"time\", 1 / 0.001, 0, 0],\n ms: [\"time\", 1 / 0.001, 0, 0],\n millisecond: [\"time\", 1 / 0.001, 0, 0],\n microsecond: [\"time\", 1 / 0.000001, 0, 0],\n nanosecond: [\"time\", 1 / 0.000000001, 0, 0],\n picosecond: [\"time\", 1 / 0.000000000001, 0, 0],\n};\nexport function unitSystemMapReducer(acc, unitSystem) {\n const system = unitSystem.id;\n const units = unitSystem.units.reduce(\n (acc, unit) => {\n const unitTuple: UnitTuple = [\n unit.measure,\n unit.scale,\n unit.offset,\n unit.decimals,\n unit.alias,\n system,\n ];\n acc[unit.name] = unitTuple;\n if (unit.alias) {\n acc[unit.alias] = unitTuple;\n }\n return acc;\n },\n {\n ...timeTuples,\n }\n );\n\n return { ...acc, ...units };\n}\n\nexport function measureMapReducer(systemAcc, unitSystem) {\n const system = unitSystem.id;\n\n const measures = unitSystem.units.reduce(\n (acc, unit) => {\n const measure = acc[unit.measure] || {};\n\n const systemMeasure = measure[system] || {};\n measure[system] = systemMeasure;\n\n const unitTuple: UnitTuple = [\n unit.measure,\n unit.scale,\n unit.offset,\n unit.decimals,\n unit.alias,\n system,\n ];\n systemMeasure[unit.name] = unitTuple;\n if (unit.alias) {\n systemMeasure[unit.alias] = unitTuple;\n }\n if (Object.hasOwn(unit, \"default\")) {\n Object.defineProperty(systemMeasure, \"default\", {\n value: unitTuple,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n }\n acc[unit.measure] = measure;\n\n return acc;\n },\n {\n time: {\n [system]: {\n ...timeTuples,\n },\n },\n }\n );\n Object.keys(measures).forEach((measure) => {\n systemAcc[measure] = {\n ...systemAcc[measure],\n ...measures[measure],\n };\n });\n\n return systemAcc;\n}\n\nexport function defaultMeasureMapReducer(systemAcc, unitSystem) {\n const system = unitSystem.id;\n\n const measures = unitSystem.units.reduce(\n (acc, unit) => {\n const measure = acc[unit.measure] || {};\n\n if (Object.hasOwn(unit, \"default\")) {\n measure[system] = unit.name;\n }\n acc[unit.measure] = measure;\n return acc;\n },\n {\n time: {\n [system]: \"millisecond\",\n },\n }\n );\n Object.keys(measures).forEach((measure) => {\n systemAcc[measure] = {\n ...systemAcc[measure],\n ...measures[measure],\n };\n });\n\n return systemAcc;\n}\n","import {\n createPropKey,\n ExtensionManager,\n Kos,\n kosDependency,\n KosLog,\n kosModel,\n} from \"../../../core\";\nimport { KosCoreModelPropertyMapper } from \"../../constants\";\n\nimport { ConfigBean } from \"../config-bean\";\nimport {\n configBeanModelId,\n type IConfigBeanModel,\n} from \"../config-bean/config-bean-model\";\nimport {\n BaseRegionResponse,\n DateFormat,\n getRegionInfo,\n getRegions,\n RegionsResponse,\n TimeFormat,\n} from \"./services\";\nimport {\n DateFormatOptions,\n DefaultMeasureMap,\n MeasureMap,\n RegionInfoModel,\n RegionInfoOptions,\n TimeFormatOptions,\n UnitSource,\n UnitSystemOptions,\n UnitTuple,\n UnitTupleKeys,\n} from \"./types\";\nimport {\n defaultMeasureMapReducer,\n measureMapReducer,\n unitSystemMapReducer,\n} from \"./utils/unit-system-utils\";\n\ninterface RegionSettingsService {\n unitSystemId: string;\n timeFormatId: string;\n dateFormatId: string;\n country: string;\n timeZone: string;\n}\n\ninterface RegionService {\n regionId: string;\n}\n\ntype RegionSettingsConfigBean = IConfigBeanModel<RegionSettingsService>;\n\ntype RegionConfigBean = IConfigBeanModel<RegionService>;\n\nconst MODEL_TYPE = \"region-info-model\";\n\nconst log = KosLog.createLogger({ name: \"region-info-model\" });\n\nfunction servicePathMapper(regionInfoModel: RegionInfoModel): string {\n const hasMapper = ExtensionManager.propertyMapper.hasMapper(\n KosCoreModelPropertyMapper.RegionServicePath\n );\n if (hasMapper) {\n return ExtensionManager.propertyMapper.executeMapper<\n RegionInfoModel,\n string\n >(KosCoreModelPropertyMapper.RegionServicePath, regionInfoModel);\n }\n return \"/api/kos/regions\";\n}\n\nconst REGION_SETTINGS_PATH = \"kos:service:region:settings\";\nconst REGION_PATH = \"kos:service:region\";\nconst DESTINATION_PROP =\n createPropKey<RegionInfoModelImpl>(\"destinationAddress\");\nconst REGION_SETTINGS_BEAN_ID_PROP = createPropKey<RegionInfoModelImpl>(\n \"regionSettingsBeanId\"\n);\nconst REGION_BEAN_ID_PROP = createPropKey<RegionInfoModelImpl>(\"regionBeanId\");\n\n/**\n * Model id of the region info for a destination; the default instance keeps\n * the type as its id, so existing lookups by type are unchanged.\n * @ignore\n * @internal\n */\nexport function regionInfoModelId(destinationAddress?: string): string {\n return destinationAddress\n ? `${MODEL_TYPE}-${destinationAddress}`\n : MODEL_TYPE;\n}\n/**\n * @ignore\n * @internal\n */\n@kosModel(MODEL_TYPE)\nexport class RegionInfoModelImpl<\n AdditionalData extends BaseRegionResponse = BaseRegionResponse\n> implements RegionInfoModel\n{\n id: string;\n private unitSystemMap: Record<string, UnitTuple>;\n private measureMap: MeasureMap;\n private defaultMeasureMap: DefaultMeasureMap;\n\n serviceBasePath: string;\n /** Connection the region services and beans are routed to */\n destinationAddress?: string;\n // An unset destination must keep the legacy bean ids, and a dependency id\n // template cannot drop a segment, so the bean ids are computed per instance.\n readonly regionSettingsBeanId: string;\n readonly regionBeanId: string;\n\n private regionMap: Record<string, RegionsResponse<AdditionalData>>;\n private timeFormats: Record<string, TimeFormat>;\n private dateFormats: Record<string, DateFormat>;\n private unitSystems: Record<string, UnitSystemOptions>;\n @kosDependency({\n modelType: ConfigBean.type,\n id: REGION_SETTINGS_BEAN_ID_PROP,\n options: {\n path: REGION_SETTINGS_PATH,\n destinationAddress: DESTINATION_PROP,\n },\n })\n regionSource!: RegionSettingsConfigBean;\n\n @kosDependency({\n modelType: ConfigBean.type,\n id: REGION_BEAN_ID_PROP,\n options: { path: REGION_PATH, destinationAddress: DESTINATION_PROP },\n })\n private region!: RegionConfigBean;\n\n private regions: string[] = [];\n private timeZoneMap: Record<string, string[]> = {};\n\n constructor(modelId: string, options?: RegionInfoOptions) {\n this.id = modelId;\n this.destinationAddress = options?.destinationAddress;\n this.regionSettingsBeanId = configBeanModelId(\n REGION_SETTINGS_PATH,\n this.destinationAddress\n );\n this.regionBeanId = configBeanModelId(REGION_PATH, this.destinationAddress);\n\n this.serviceBasePath = servicePathMapper(this);\n this.unitSystems = {};\n this.unitSystemMap = {};\n this.measureMap = {};\n this.defaultMeasureMap = {};\n\n this.timeFormats = {};\n this.regions = [];\n this.dateFormats = {};\n this.timeZoneMap = {};\n this.regionMap = {};\n }\n\n get availableRegions() {\n return this.regions;\n }\n get defaultUnitSystem() {\n return String(this.regionSource.props[\"unitSystemId\"]).toLowerCase() || \"\";\n }\n\n get unitSystemId() {\n return this.defaultUnitSystem;\n }\n\n get timeFormatId() {\n const _timeFormatId = this.regionSource.props[\"timeFormatId\"];\n if (!_timeFormatId) {\n return \"\";\n }\n const selectedTimeFormatId = String(_timeFormatId);\n\n const resolvedTimeFormatId = this.timeFormats[selectedTimeFormatId];\n return resolvedTimeFormatId ? String(resolvedTimeFormatId.id) : \"\";\n }\n\n get selectedTimeFormat() {\n const selectedTimeFormatId = this.timeFormatId;\n return selectedTimeFormatId\n ? String(this.timeFormats[selectedTimeFormatId].format)\n : \"HH:mm:ss\";\n }\n\n get is12HourTimeFormat() {\n const selectedTimeFormatId = this.timeFormatId;\n return selectedTimeFormatId\n ? this.timeFormats[selectedTimeFormatId].ampm\n : true;\n }\n\n get dateFormatId() {\n const _dateFormatId = this.regionSource.props[\"dateFormatId\"];\n if (!_dateFormatId) {\n return \"\";\n }\n const selectedDateFormatId = String(_dateFormatId);\n return selectedDateFormatId\n ? this.dateFormats[selectedDateFormatId].id\n : \"\";\n }\n\n get selectedDateFormat() {\n const selectedDateFormatId = this.dateFormatId;\n return selectedDateFormatId\n ? this.dateFormats[selectedDateFormatId].format\n : \"\";\n }\n\n get selectedDateOrder() {\n const selectedDateFormatId = this.dateFormatId;\n\n return selectedDateFormatId\n ? this.dateFormats[selectedDateFormatId].order.toLowerCase()\n : \"dmy\";\n }\n\n get selectedCountry() {\n return (this.regionSource.props[\"country\"] as string) || \"en\";\n }\n\n get selectedTimeZone() {\n return (this.regionSource.props[\"timeZone\"] as string) || \"\";\n }\n\n get timeZones() {\n return this.regionId ? this.timeZoneMap[this.regionId] || [] : [];\n }\n\n get allTimeZones() {\n // const allTimeZones = Object.values(this.timeZoneMap).flat();\n const allTimeZones = Intl.supportedValuesOf(\"timeZone\");\n\n return allTimeZones;\n }\n\n get regionId() {\n return (this.region.props[\"regionId\"] as string) || \"\";\n }\n\n get selectedRegion() {\n return this.regionMap[this.regionId];\n }\n\n get selectedUnitSystem() {\n return String(this.regionSource.props[\"unitSystemId\"]) || \"\";\n }\n\n get timeFormatOptions() {\n return Object.keys(this.timeFormats).map<TimeFormatOptions>((key) => {\n return {\n id: key,\n format: this.timeFormats[key].format,\n ampm: this.timeFormats[key].ampm,\n };\n });\n }\n\n get dateFormatOptions() {\n return Object.keys(this.dateFormats).map<DateFormatOptions>((key) => {\n return {\n id: key,\n format: this.dateFormats[key].format,\n order: this.dateFormats[key].order,\n };\n });\n }\n\n get unitSystemOptions() {\n return Object.keys(this.unitSystems).map<UnitSystemOptions>((key) => {\n return {\n id: key,\n name: key,\n };\n });\n }\n\n setSelectedTimeFormat(timeFormatId: string) {\n if (!this.timeFormatOptions.find((option) => option.id === timeFormatId)) {\n throw Error(\n `Invalid time format id. Must be one of ${this.timeFormatOptions\n .map((option) => option.id)\n .join(\", \")}`\n );\n }\n this.regionSource.updateProperty(\"timeFormatId\", timeFormatId);\n }\n\n setSelectedDateFormat(dateFormatId: string) {\n if (!this.dateFormatOptions.find((option) => option.id === dateFormatId)) {\n throw Error(\n `Invalid date format id. Must be one of ${this.dateFormatOptions\n .map((option) => option.id)\n .join(\", \")}`\n );\n }\n this.regionSource.updateProperty(\"dateFormatId\", dateFormatId);\n }\n\n setSelectedUnitSystem(unitSystemId: string) {\n if (!this.unitSystemOptions.find((option) => option.id === unitSystemId)) {\n throw Error(\n `Invalid date format id. Must be one of ${this.unitSystemOptions\n .map((option) => option.id)\n .join(\", \")}`\n );\n }\n this.regionSource.updateProperty(\"unitSystemId\", unitSystemId);\n }\n\n getUnitSystem(_unit?: string) {\n if (!_unit) {\n return this.defaultUnitSystem;\n }\n const unit = _unit === \"drt\" ? \"second\" : _unit;\n const unitTuple = this.unitSystemMap[unit];\n if (!unitTuple) {\n throw Error(\n `No unit found with name: ${unit}. Unit should be one of ${Object.keys(\n this.unitSystemMap\n ).join(\", \")}`\n );\n }\n return unitTuple[UnitTupleKeys.system];\n }\n getUnitMeasure(_unit: string) {\n const unit = _unit === \"drt\" ? \"second\" : _unit;\n const unitTuple = this.unitSystemMap[unit];\n if (!unitTuple) {\n throw Error(\n `No unit found with name: ${unit}. Unit should be one of ${Object.keys(\n this.unitSystemMap\n ).join(\", \")}`\n );\n }\n return unitTuple[UnitTupleKeys.family];\n }\n\n /**\n *@internal\n */\n getDefaultUnitDecimalPlaces(\n measure: string,\n unitSystem: string,\n _unit?: string\n ) {\n if (!measure || !unitSystem) {\n throw Error(\"Measure and unit system are required\");\n }\n const unit = _unit === \"drt\" ? \"second\" : _unit;\n const measureUnitSystems = this.measureMap[measure];\n if (!measureUnitSystems) {\n throw Error(\n `No unit systems found for measure: ${measure}. Measure should come from list of measures: ${Object.keys(\n this.measureMap\n ).join(\", \")}`\n );\n }\n\n const unitSystemUnits = measureUnitSystems[unitSystem.toLowerCase()];\n if (!unitSystemUnits) {\n throw Error(\n `No unit system found for measure: ${measure} and unit system: ${unitSystem}. Unit system should come form list of unit systems: ${Object.keys(\n measureUnitSystems\n ).join(\", \")}`\n );\n }\n\n const defaultUnit = unitSystemUnits[unit || \"default\"];\n if (!defaultUnit) {\n throw Error(\n `No unit \"${\n unit || \"default\"\n }\" found for measure: ${measure} and unit system: ${unitSystem}. Unit should come from list of units: ${Object.keys(\n unitSystemUnits\n ).join(\", \")}`\n );\n }\n return defaultUnit[UnitTupleKeys.decimals];\n }\n\n /**\n *@internal\n */\n getDefaultUnitForMeasure(measure: string, unitSystem: string) {\n if (!measure || !unitSystem) {\n throw Error(\"Measure and unit system are required\");\n }\n\n const measureUnitSystems = this.defaultMeasureMap[measure];\n if (!measureUnitSystems) {\n throw Error(\n `No unit systems found for measure: ${measure}. Measure should come from list of measures: ${Object.keys(\n this.measureMap\n ).join(\", \")}`\n );\n }\n\n const unitSystemUnits = measureUnitSystems[unitSystem.toLowerCase()];\n if (!unitSystemUnits) {\n throw Error(\n `No unit system found for measure: ${measure} and unit system: ${unitSystem}. Unit system should come form list of unit systems: ${Object.keys(\n measureUnitSystems\n ).join(\", \")}`\n );\n }\n return unitSystemUnits;\n }\n\n /**\n *@internal\n */\n\n convertByUnit(value: number, fromUnit: UnitTuple, toUnit: UnitTuple) {\n if (fromUnit[UnitTupleKeys.family] !== toUnit[UnitTupleKeys.family]) {\n throw new Error(\n `Cannot convert between units of different families: ${\n fromUnit[UnitTupleKeys.family]\n } and ${toUnit[UnitTupleKeys.family]}`\n );\n }\n\n const fromOffset = fromUnit[UnitTupleKeys.offset] as number;\n const fromScale = fromUnit[UnitTupleKeys.scale] as number;\n const toScale = toUnit[UnitTupleKeys.scale] as number;\n const toOffset = toUnit[UnitTupleKeys.offset] as number;\n const decimals = toUnit[UnitTupleKeys.decimals] as number;\n const convertedValue =\n (value - fromOffset) / (fromScale / toScale) + toOffset;\n\n return convertedValue.toFixed(decimals);\n }\n\n /**\n *@internal\n */\n convertByUnitName(value: number, from: string, to: string) {\n const fromUnit = this.unitSystemMap[from];\n const toUnit = this.unitSystemMap[to];\n if (!fromUnit || !toUnit) {\n throw new Error(\n `No unit found with name: ${from} or ${to}. Unit should be one of ${Object.keys(\n this.unitSystemMap\n ).join(\", \")}`\n );\n }\n return this.convertByUnit(value, fromUnit, toUnit);\n }\n\n /**\n * @internal\n */\n convert(value: number, from: UnitSource, to: UnitSource) {\n if (from.unit && to.unit) {\n return this.convertByUnitName(value, from.unit, to.unit);\n }\n\n const fromName = from.unit || \"\";\n const toName = to.unit || \"\";\n let fromUnit = this.unitSystemMap[fromName];\n let toUnit = this.unitSystemMap[toName];\n if (!toUnit && to.measure && to.system) {\n const measureSystems = this.measureMap[to.measure];\n if (!measureSystems) {\n throw Error(\n `Could not find measure ${\n to.measure\n }. Measure should be one of ${Object.keys(this.measureMap).join(\n \", \"\n )}`\n );\n }\n toUnit = measureSystems[to.system]?.[\"default\"];\n if (!toUnit) {\n log.info(\"Could not find default unit for measure\", to.measure);\n }\n }\n\n if (!fromUnit && from.measure && from.system) {\n const measureSystems = this.measureMap[from.measure];\n if (!measureSystems) {\n throw Error(\n `Could not find measure ${\n to.measure\n }. Measure should be one of ${Object.keys(this.measureMap).join(\n \", \"\n )}`\n );\n }\n fromUnit = measureSystems[from.system]?.[\"default\"];\n if (!fromUnit) {\n log.info(\"Could not find default unit for measure\", from.measure);\n }\n }\n\n if (!fromUnit || !toUnit) {\n log.warn(\"Could not find unit to convert to or from. Return value as is\");\n return String(value);\n }\n\n return this.convertByUnit(value, fromUnit, toUnit);\n }\n\n // -------------------LIFECYCLE----------------------------\n\n /**\n * @internal\n */\n async init(): Promise<void> {\n log.debug(\"initializing region info\");\n }\n\n /**\n * @internal\n */\n async load(): Promise<void> {\n log.debug(\"loading region info\");\n\n const regions = await getRegions(\n this.serviceBasePath,\n this.destinationAddress\n );\n if (regions) {\n this.regions = regions.data.map((region) => region.id);\n this.timeZoneMap = regions.data.reduce((acc, region) => {\n return { ...acc, [region.id]: region.timeZones };\n }, this.timeZoneMap);\n this.regionMap = regions.data.reduce((acc, region) => {\n return { ...acc, [region.id]: region };\n }, {});\n }\n\n const regionInfo = await getRegionInfo(\n this.serviceBasePath,\n this.destinationAddress\n );\n if (regionInfo) {\n this.unitSystems = regionInfo.data.unitSystems.reduce((acc, curr) => {\n const unitSystem = {\n id: curr.id,\n name: curr.id,\n };\n acc[curr.id] = unitSystem;\n return acc;\n }, this.unitSystems);\n this.unitSystemMap = regionInfo.data.unitSystems.reduce(\n unitSystemMapReducer,\n {}\n );\n\n this.measureMap = regionInfo.data.unitSystems.reduce(\n measureMapReducer,\n {}\n );\n\n this.defaultMeasureMap = regionInfo.data.unitSystems.reduce(\n defaultMeasureMapReducer,\n {}\n );\n\n this.timeFormats = regionInfo.data.timeFormats.reduce(\n (acc, timeFormat) => {\n return { ...acc, [timeFormat.id]: timeFormat };\n },\n {}\n );\n\n this.dateFormats = regionInfo.data.dateFormats.reduce(\n (acc, dateFormat) => {\n return { ...acc, [dateFormat.id]: dateFormat };\n },\n {}\n );\n }\n }\n\n /**\n * @internal\n */\n async ready(): Promise<void> {\n await this.regionSource.ready?.();\n }\n}\n\nconst Registration = {\n registration: {\n [MODEL_TYPE]: {\n class: RegionInfoModelImpl,\n singleton: false,\n },\n },\n type: MODEL_TYPE,\n factory: Kos.Singleton.create<RegionInfoModel, RegionInfoOptions>(MODEL_TYPE),\n};\nexport default Registration;\n","import { getKosModelSync, isKosModelReady } from \"../../core\";\nimport { RegionInfo } from \"../models/region-info\";\nimport { RegionInfoModel, UnitSource } from \"../models/region-info/types\";\n\nexport type UnitConversionSource = string | UnitSource;\n\ninterface CreateUnitSourceProps {\n source: UnitConversionSource;\n defaultSystem?: string;\n defaultMeasure?: string;\n}\nconst createUnitSource = ({\n source,\n defaultSystem = \"si\",\n defaultMeasure,\n}: CreateUnitSourceProps) => {\n let unit: UnitSource = { system: defaultSystem, measure: defaultMeasure };\n if (typeof source === \"string\") {\n unit = { ...unit, unit: source };\n } else {\n unit = { ...unit, ...source };\n }\n\n return unit;\n};\n\n/**\n * Region-aware unit conversion utility that can be used to convert between units of measure.\n *\n * When converting between units of measure, the source and target unit can be specified as a string or as a {@see UnitSource} object.\n * @example\n * in the simplest case, the source and target units can be specified as strings so long as they belong to the same measure (volume, length etc):\n *\n * ```typescript\n * import { convert } from \"@kosdev-code/kos-ui-sdk\";\n *\n * const value = convert(1000, \"milliliter\", \"fluid-ounce\");\n * ```\n *\n * The to unit can be omitted in which case the value will be converted to the default unit for the selected region measure:\n * @example\n * ```typescript\n * import { convert } from \"@kosdev-code/kos-ui-sdk\";\n *\n * // convert 1000 milliliters to the default unit for the region. If the region is set to US, the value will be converted to fluid ounces.\n * const value = convert(1000, \"milliliter\");\n * ```\n *\n * The source and target units can also be specified as {@see UnitSource} objects:\n * @example\n * ```typescript\n * import { convert } from \"@kosdev-code/kos-ui-sdk\";\n *\n * const value = convert(1000, {name: \"milliliter\", measure: \"volume\", system: \"si\"}, {name: \"fluid-ounce\", measure: \"volume\", system: \"us\"});\n * ```\n * In this case properties on the source and target are all optional so long as either the name or measure is specified.\n *\n * @param value - the value to convert\n * @param from - the source unit\n * @param to - the target unit. If omitted, the value will be converted to the default unit for the region measure.\n * @returns the converted value\n */\nexport const convert = (\n value: number,\n from: UnitConversionSource,\n to?: UnitConversionSource\n) => {\n const { model: regionInfo } = getKosModelSync<RegionInfoModel>(\n RegionInfo.type\n );\n if (!regionInfo) {\n throw new Error(\"RegionInfo model not found\");\n }\n\n if (!isKosModelReady(regionInfo)) {\n throw new Error(\"RegionInfo model not ready\");\n }\n const defaultToSource = { system: regionInfo.defaultUnitSystem };\n const fromUnit: UnitSource = createUnitSource({ source: from });\n\n const toUnit: UnitSource = createUnitSource({\n source: to || defaultToSource,\n defaultMeasure: regionInfo.getUnitMeasure(fromUnit.unit || \"\"),\n });\n\n return regionInfo.convert(value, fromUnit, toUnit);\n};\n\nfunction formatUnit(\n value: any,\n unit: string,\n format?: {\n mode: \"short\" | \"long\";\n minDecimals?: number;\n maxDecimals?: number;\n }\n) {\n const normalized = unit.toLowerCase().replace(/_/g, \"-\").replace(/s$/, \"\"); // naive singularization\n const locale = new Intl.NumberFormat().resolvedOptions().locale ?? \"en-US\";\n try {\n const mode = format?.mode || \"long\";\n const maxDecimals = format?.maxDecimals ?? 2;\n const minDecimals = format?.minDecimals ?? 0;\n return new Intl.NumberFormat(locale, {\n style: \"unit\",\n unit: normalized,\n unitDisplay: mode,\n minimumFractionDigits: minDecimals,\n maximumFractionDigits: maxDecimals,\n }).format(value);\n } catch (e) {\n // fallback\n return unit;\n }\n}\n/**\n * Converts a numeric value from one unit to another, formats the result, and returns\n * an object containing the converted value, display strings, and the unit.\n *\n * @example\n * convert and format a value, letting the region determine the target unit:\n *\n * ```typescript\n * import { convertWithUnits } from \"@kosdev-code/kos-ui-sdk\";\n *\n * // If the region is set to US, the value is converted to fluid ounces.\n * const result = convertWithUnits(1000, \"milliliter\");\n * // result.value -> the converted numeric value as a string\n * // result.display -> \"33.81 fluid ounces\" (long form)\n * // result.shortDisplay -> \"33.81 fl oz\" (short form)\n * // result.unit -> \"fluid-ounce\"\n * ```\n *\n * @example\n * specify the target unit and control the number of decimal places:\n *\n * ```typescript\n * import { convertWithUnits } from \"@kosdev-code/kos-ui-sdk\";\n *\n * const result = convertWithUnits(1000, \"milliliter\", \"fluid-ounce\", {\n * minDecimals: 1,\n * maxDecimals: 1,\n * });\n * ```\n *\n * @param value - The numeric value to convert.\n * @param from - The source unit or unit system to convert from.\n * @param to - (Optional) The target unit or unit system to convert to. If not provided, uses the default unit system.\n * @param format - (Optional) Formatting options for the output, including minimum and maximum decimal places.\n * @param format.minDecimals - (Optional) Minimum number of decimal places in the formatted output.\n * @param format.maxDecimals - (Optional) Maximum number of decimal places in the formatted output.\n * @returns An object containing:\n * - `value`: The converted value as a string.\n * - `display`: The formatted value with unit in long form.\n * - `shortDisplay`: The formatted value with unit in short form.\n * - `unit`: The unit used for the converted value.\n * @throws If the RegionInfo model is not found.\n */\nexport const convertWithUnits = (\n value: number,\n from: UnitConversionSource,\n to?: UnitConversionSource,\n format?: {\n minDecimals?: number;\n maxDecimals?: number;\n }\n): { value: string; display: string; shortDisplay: string; unit: string } => {\n const convertedValue = convert(value, from, to);\n const fromUnit = createUnitSource({ source: from });\n const { model: regionInfo } = getKosModelSync<RegionInfoModel>(\n RegionInfo.type\n );\n if (!regionInfo) {\n throw new Error(\"RegionInfo model not found\");\n }\n\n const measure = regionInfo.getUnitMeasure(fromUnit.unit || \"\");\n\n const defaultToSource = { system: regionInfo.defaultUnitSystem };\n\n const toUnit: UnitSource = createUnitSource({\n source: to || defaultToSource,\n defaultMeasure: regionInfo.getUnitMeasure(fromUnit.unit || \"\"),\n });\n\n const unit = regionInfo.getDefaultUnitForMeasure(measure, toUnit.system!);\n const defaultDecimals = regionInfo.getDefaultUnitDecimalPlaces(\n measure,\n toUnit.system!\n );\n\n const _format = {\n ...format,\n\n minDecimals: format?.minDecimals ?? defaultDecimals,\n maxDecimals: format?.maxDecimals ?? defaultDecimals,\n };\n return {\n value: convertedValue,\n unit: unit || fromUnit.unit || \"\",\n display: formatUnit(convertedValue as any, unit || fromUnit.unit || \"\", {\n ..._format,\n mode: \"long\",\n }),\n shortDisplay: formatUnit(\n convertedValue as any,\n unit || fromUnit.unit || \"\",\n { ..._format, mode: \"short\" }\n ),\n };\n};\n","import {\n KeypadOptions,\n ListOptions,\n RangeCountOptions,\n RangeIntervalOptions,\n SchemaNodeDef,\n} from \"../../services/config-bean\";\nimport { UnitConversionSource, convert } from \"../../utils/conversion-utils\";\nimport { isNumber } from \"../../utils/prop-utils\";\n\ninterface DistributionProps {\n start: number;\n end: number;\n count: number;\n decimals?: number;\n}\nfunction generateEvenlyDistributedArray({\n start,\n end,\n count,\n decimals = 0,\n}: DistributionProps) {\n if (\n typeof start !== \"number\" ||\n typeof end !== \"number\" ||\n typeof count !== \"number\"\n ) {\n throw new Error(\"All input values should be numbers.\");\n }\n\n if (count < 2) {\n throw new Error(\"Count should be at least 2 for distribution.\");\n }\n\n if (start >= end) {\n throw new Error(\"Start should be less than end.\");\n }\n\n const step = (end - start) / (count - 1);\n const result: string[] = [];\n\n for (let i = 0; i < count; i++) {\n const value = Math.round(start + i * step);\n result.push(value.toFixed(decimals));\n }\n\n return result;\n}\n\ninterface IntervalProps {\n start: number;\n end: number;\n interval: number;\n decimals?: number;\n}\n\nfunction generateIntervalArray({\n start,\n end,\n interval,\n decimals = 0,\n}: IntervalProps) {\n if (\n typeof start !== \"number\" ||\n typeof end !== \"number\" ||\n typeof interval !== \"number\"\n ) {\n throw new Error(\"All input values should be numbers.\");\n }\n\n if (interval <= 0) {\n throw new Error(\"Interval should be a positive number.\");\n }\n\n if (start >= end) {\n throw new Error(\"Start should be less than end.\");\n }\n\n const result: string[] = [];\n\n let currentValue = start;\n while (currentValue <= end) {\n result.push(currentValue.toFixed(decimals));\n currentValue += interval;\n }\n\n // Ensure that the last value is always the end value\n if (result[result.length - 1] !== end.toString()) {\n result.push(end.toString());\n }\n\n return result;\n}\n\nconst conversionMap =\n (from?: UnitConversionSource, to?: UnitConversionSource) =>\n (item: string) => {\n if (!from || !to) {\n return item;\n }\n const result = isNumber(item) ? convert(Number(item), from, to) : item;\n return result;\n };\nexport const configOptionsFactory = (\n schema?: SchemaNodeDef,\n unitSystem?: string,\n from?: UnitConversionSource,\n to?: UnitConversionSource\n): string[] => {\n if (schema?.type === \"enum\" || !schema?.options) {\n return [];\n }\n\n if (schema.options.type === \"rangeCount\") {\n return generateEvenlyDistributedArray(schema.options).map(\n conversionMap(from, to)\n );\n } else if (schema.options.type === \"rangeInterval\") {\n return generateIntervalArray(schema.options).map(conversionMap(from, to));\n } else if (schema.options.type === \"list\") {\n const { list } = schema.options;\n\n return list.map(conversionMap(from, to));\n } else if (schema.options.type === \"unitSystemRangeCount\" && unitSystem) {\n return generateEvenlyDistributedArray(\n schema.options.unitSystems[unitSystem]\n ).map(conversionMap(from, to));\n } else if (schema.options.type === \"unitSystemRangeInterval\" && unitSystem) {\n const list = generateIntervalArray(\n schema.options.unitSystems[unitSystem]\n ).map(conversionMap(from, to));\n return list;\n } else if (schema.options.type === \"unitSystemList\" && unitSystem) {\n const { list } = schema.options.unitSystems[unitSystem];\n\n return list.map(conversionMap(from, to));\n }\n\n return [];\n};\n\nexport const displayOptionsFactory = (\n schema?: SchemaNodeDef,\n unitSystem?: string\n) => {\n if (schema?.type === \"enum\" || !schema?.options) {\n return undefined;\n }\n if (schema.options.type === \"unitSystemRangeCount\" && unitSystem) {\n const result: RangeCountOptions = {\n type: \"rangeCount\",\n ...schema.options.unitSystems[unitSystem],\n };\n return result;\n } else if (schema.options.type === \"unitSystemRangeInterval\" && unitSystem) {\n const result: RangeIntervalOptions = {\n type: \"rangeInterval\",\n ...schema.options.unitSystems[unitSystem],\n };\n return result;\n } else if (schema.options.type === \"unitSystemList\" && unitSystem) {\n const result: ListOptions = {\n type: \"list\",\n ...schema.options.unitSystems[unitSystem],\n };\n return result;\n } else if (schema.options.type === \"unitSystemKeypad\" && unitSystem) {\n const result: KeypadOptions = {\n type: \"keypad\",\n ...schema.options.unitSystems[unitSystem],\n };\n return result;\n }\n\n return schema.options;\n};\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport {\n Kos,\n KosLog,\n createPropKey,\n kosDependency,\n kosModel,\n} from \"../../../core\";\nimport { ConfigBean } from \"../config-bean\";\nimport { configBeanModelId } from \"../config-bean/config-bean-model\";\nimport type { UnitConverter } from \"../../decorators/kos-config-bean-prop\";\n\nimport { format } from \"date-fns\";\nimport {\n hasDecimals,\n type EnumSchemaNode,\n type SchemaNodeDef,\n} from \"../../services/config-bean\";\n\nimport type { IConfigBeanModel } from \"../config-bean/config-bean-model\";\nimport { RegionInfo, type RegionInfoModel } from \"../region-info\";\nimport { regionInfoModelId } from \"../region-info/region-info-model\";\nimport type { UnitSource } from \"../region-info/types\";\nimport type { ConfigPropertyTypes } from \"../types\";\nimport {\n configOptionsFactory,\n displayOptionsFactory,\n} from \"./config-options-factory\";\nimport type {\n ConfigBeanPropOptions,\n ConfigPropConverter,\n FormatOptions,\n KosConfigProperty,\n OptionsExpander,\n OptionsType,\n} from \"./types\";\n\nfunction isEnum(schema?: SchemaNodeDef): schema is EnumSchemaNode {\n return schema?.type === \"enum\";\n}\n\nfunction convertFormats(format: string) {\n switch (format) {\n case \"s\":\n return \"second\";\n case \"ms\":\n return \"millisecond\";\n case \"min\":\n return \"minute\";\n case \"h\":\n return \"hour\";\n case \"d\":\n return \"day\";\n case \"w\":\n return \"week\";\n case \"m\":\n return \"month\";\n case \"y\":\n return \"year\";\n case \"ml\":\n return \"milliliter\";\n default:\n return format;\n }\n}\n\nfunction secondsToFormattedTime(\n secondsSinceMidnight: number,\n formatString: string\n): string {\n // Create a reference to the start of the day (midnight)\n const midnight = new Date();\n midnight.setHours(0, 0, 0, 0);\n\n // Add the seconds to the midnight time\n const time = new Date(midnight.getTime() + secondsSinceMidnight * 1000);\n\n return format(time, formatString);\n}\n\nconst MODEL_TYPE = \"config-bean-prop-model\";\nconst log = KosLog.createLogger({ name: \"config-bean-prop-model\" });\nconst PATH_PROP = createPropKey<KosConfigProperty>(\"path\");\n\nconst SERVICE_PATH_PROP = createPropKey<KosConfigProperty>(\"serviceBasePath\");\nconst DESTINATION_PROP = createPropKey<KosConfigProperty>(\"destinationAddress\");\nconst BEAN_ID_PROP = createPropKey<KosConfigPropertyImpl>(\"configBeanId\");\nconst REGION_INFO_ID_PROP =\n createPropKey<KosConfigPropertyImpl>(\"regionInfoId\");\n\n/**\n * @ignore\n * @internal\n */\n@kosModel(MODEL_TYPE)\nclass KosConfigPropertyImpl implements KosConfigProperty {\n id: string;\n path: string;\n attribute: string;\n converter?: ConfigPropConverter;\n formatter?: FormatOptions;\n optionsExpander?: OptionsExpander;\n serviceBasePath?: string;\n destinationAddress?: string;\n // An unset destination must keep the legacy bean id, and a dependency id\n // template cannot drop a segment, so the bean id is computed per instance.\n readonly configBeanId: string;\n readonly regionInfoId: string;\n @kosDependency({\n modelType: RegionInfo.type,\n id: REGION_INFO_ID_PROP,\n options: { destinationAddress: DESTINATION_PROP },\n })\n regionInfo!: RegionInfoModel;\n\n @kosDependency({\n modelType: ConfigBean.type,\n id: BEAN_ID_PROP,\n options: {\n path: PATH_PROP,\n serviceBasePath: SERVICE_PATH_PROP,\n destinationAddress: DESTINATION_PROP,\n },\n })\n bean!: IConfigBeanModel;\n\n constructor(modelId: string, options: ConfigBeanPropOptions) {\n this.id = modelId;\n this.path = options.path;\n this.attribute = options.attribute;\n this.converter = options.converter;\n this.formatter = options.formatter;\n this.serviceBasePath = options.serviceBasePath;\n this.destinationAddress = options.destinationAddress;\n this.optionsExpander = options.optionsExpander;\n this.configBeanId = configBeanModelId(this.path, this.destinationAddress);\n this.regionInfoId = regionInfoModelId(this.destinationAddress);\n }\n\n // -------------------LIFECYCLE----------------------------\n\n /**\n * For cases where the default unit system is used, this method will return\n * the number of decimal places to use for the given measure.\n * @param measure the measure to get the default decimal places for\n * @param unitSystem the unit system to use\n * @returns the number of decimal places to use for the given measure\n * @throws Error if measure is not provided\n **/\n getDefaultUnitDecimalPlaces(\n measure: string,\n unitSystem: string,\n unit?: string\n ) {\n if (!measure) {\n throw new Error(\"measure is required\");\n }\n\n if (!unitSystem) {\n throw new Error(\"unitSystem is required\");\n }\n\n const displayDecimals = hasDecimals(this.displayOptions)\n ? this.displayOptions.decimals\n : this.regionInfo.getDefaultUnitDecimalPlaces(measure, unitSystem, unit);\n return displayDecimals;\n }\n\n /**\n * For cases where the default unit system is used, this method will return\n * the default unit for the given measure.\n * @param measure the measure to get the default unit for\n * @param unitSystem the unit system to use\n * @returns the default unit for the given measure\n * @throws Error if measure is not provided\n * @throws Error if unitSystem is not provided\n * @throws Error if the default unit for the given measure is not found\n **/\n getDefaultUnitForMeasure(measure: string, unitSystem: string) {\n if (!measure) {\n throw new Error(\"measure is required\");\n }\n\n if (!unitSystem) {\n throw new Error(\"unitSystem is required\");\n }\n return this.regionInfo.getDefaultUnitForMeasure(measure, unitSystem);\n }\n\n /**\n * Gets the schema data type for this property.\n *\n * @returns Schema type string (e.g., \"String\", \"Number\", \"Boolean\", \"enum\")\n */\n get schemaType() {\n const schema = this.bean.getSchemaForProperty(this.attribute);\n if (schema?.type) {\n return schema.type;\n } else {\n return \"String\";\n }\n }\n\n /**\n * Gets the schema format hint for this property.\n *\n * @returns Format string (e.g., \"second\", \"milliliter\", \"hour\") or empty string if not specified\n */\n get schemaFormat() {\n const schema = this.bean.getSchemaForProperty(this.attribute);\n if (schema?.format) {\n return convertFormats(schema.format);\n }\n return \"\";\n }\n\n /**\n * Gets available options for enumerated properties.\n *\n * @returns Array of options with label/value pairs for dropdowns and selection controls\n *\n * @example Get Property Options\n * ```typescript\n * const options = statusProperty.options;\n * // Returns: [\n * // { label: \"Active\", value: \"active\" },\n * // { label: \"Inactive\", value: \"inactive\" }\n * // ]\n * ```\n */\n get options() {\n const defaultUnitSystem = this.regionInfo.defaultUnitSystem;\n const converter = this.getConverter();\n const system = converter?.to?.system ?? defaultUnitSystem;\n const schema = this.bean.getSchemaForProperty(this.attribute);\n const values = isEnum(schema)\n ? schema.values\n : configOptionsFactory(schema, system, converter?.from, converter?.to);\n\n const defaultOptions: OptionsType[] =\n values.length > 0\n ? values.map((value) => {\n return { label: value, value };\n })\n : [];\n\n if (this.optionsExpander) {\n if (typeof this.optionsExpander === \"function\") {\n return this.optionsExpander(system, values);\n } else {\n return this.optionsExpander;\n }\n }\n return defaultOptions;\n }\n\n convertUnit(\n converter?: UnitConverter,\n defaultSystem?: string,\n defaultMeasure?: string\n ) {\n const measure = converter?.measure || defaultMeasure;\n const system = converter?.system || defaultSystem;\n const unit = converter?.unit;\n\n return {\n measure,\n system,\n unit,\n };\n }\n\n getConverterUnits() {\n const defaultUnitSystem = this.regionInfo.defaultUnitSystem;\n const converter = this.getConverter();\n if (!converter) {\n throw Error(\"No converter defined\");\n }\n const measure = converter.measure;\n const backend: UnitSource = this.convertUnit(converter.from, \"si\", measure);\n const display = this.convertUnit(converter.to, defaultUnitSystem, measure);\n\n return { backend, display };\n }\n\n /**\n * Sets the configuration property value with automatic unit conversion.\n *\n * @param value - The new value to set (in regional units)\n *\n * @example Update Property Value\n * ```typescript\n * pumpRateProperty.value = 1.2; // Sets rate to 1.2 mL/s (converted to backend units)\n * ```\n */\n set value(value: ConfigPropertyTypes) {\n this.updateProperty(value);\n }\n\n /**\n * Gets the configuration property value converted to regional units.\n *\n * @returns Property value in regional display units\n *\n * @example Get Property Value\n * ```typescript\n * const currentRate = pumpRateProperty.value; // Gets rate in mL/s (regional units)\n * ```\n */\n get value() {\n return this.getValue(true);\n }\n\n /**\n * Gets the raw backend value without unit conversion.\n *\n * @returns Raw property value as stored in backend (typically SI units)\n */\n get rawValue() {\n return this.bean.props[this.attribute];\n }\n\n /**\n * Gets the property value with appropriate decimal precision for display.\n *\n * @returns Property value formatted with significant digits based on regional settings\n */\n get significantValue() {\n const _val = this.value;\n const defaultUnitSystem = this.regionInfo.defaultUnitSystem;\n const converter = this.getConverter();\n const measure = converter?.measure || converter?.to?.measure;\n\n if (!isNaN(_val as any) && converter && measure) {\n const decimals = this.getDefaultUnitDecimalPlaces(\n measure,\n converter?.to?.system || defaultUnitSystem,\n converter?.to?.unit\n );\n\n try {\n const formatter = this.getFormatterOptions(converter);\n if (formatter) {\n let result = String(_val);\n\n result = formatter.formatToParts(Number(_val))[0].value;\n\n return Number(result);\n }\n } catch (e) {\n log.info(`error formatting value ${_val}`, e);\n }\n const result = Number(_val).toFixed(decimals);\n return result;\n }\n\n return _val;\n }\n\n /**\n * Gets the previous property value before the last update.\n *\n * @returns Previous property value in regional display units\n *\n * @example Track Value Changes\n * ```typescript\n * const oldValue = pumpRateProperty.previousValue; // Previous rate value\n * const newValue = pumpRateProperty.value; // Current rate value\n * console.log(`Rate changed from ${oldValue} to ${newValue}`);\n * ```\n */\n get previousValue() {\n return this.getValue(false);\n }\n\n getValue(current: boolean) {\n const _val = this.bean[current ? \"props\" : \"prevProps\"][this.attribute];\n if (typeof _val === \"boolean\") {\n return _val;\n }\n\n const converter = this.getConverter();\n if (converter && !isNaN(_val as any)) {\n const { backend, display } = this.getConverterUnits();\n const result = this.regionInfo.convert(Number(_val), backend, display);\n return result;\n }\n return _val ?? \"\";\n }\n /**\n * @internal\n */\n async activate() {\n log.debug(`activating config bean ${this.id}`);\n }\n\n /**\n * Gets the formatted display string with units and localization.\n *\n * @returns Localized string representation with appropriate units (e.g., \"1.2 mL/s\", \"150 °F\")\n *\n * @example Display Formatted Value\n * ```typescript\n * const display = temperatureProperty.displayValue; // \"72.5 °F\"\n * const rate = pumpRateProperty.displayValue; // \"1.2 mL/s\"\n * ```\n */\n get displayValue() {\n const _val = this.value;\n if (typeof _val === \"boolean\") {\n return String(_val);\n }\n\n if (this.schemaFormat === \"drt\") {\n const is12Hr = this.regionInfo.is12HourTimeFormat;\n const timeFormatString = is12Hr ? \"h:mm:ss a\" : \"HH:mm:ss\";\n return secondsToFormattedTime(_val as number, timeFormatString);\n }\n if (!isNaN(_val as any)) {\n try {\n const converter = this.getConverter();\n const formatter = this.getFormatterOptions(converter);\n if (formatter) {\n let result = String(_val);\n\n result = formatter.format(Number(_val));\n\n return result;\n }\n } catch (e) {\n log.error(`error formatting value ${_val}`, e);\n }\n }\n return String(_val);\n }\n\n /**\n * Gets the unit of measure for the property value.\n *\n * @returns Unit string (e.g., \"°F\", \"mL/s\", \"seconds\") or empty string for unitless properties\n *\n * @example Get Property Unit\n * ```typescript\n * const unit = temperatureProperty.unit; // \"°F\" or \"°C\" based on regional settings\n * const rateUnit = pumpRateProperty.unit; // \"mL/s\"\n * ```\n */\n get unit() {\n const converter = this.getConverter();\n if (!isNaN(this.value as any)) {\n const formatter = this.getFormatterOptions(converter);\n if (formatter) {\n const parts = formatter.formatToParts(Number(this.value));\n const _unit = parts.find((part) => part.type === \"unit\");\n return _unit?.value ?? this.getDefaultUnit(converter);\n }\n }\n return this.getDefaultUnit(converter);\n }\n\n /**\n * Gets display formatting options from the backend schema.\n *\n * @returns Display options object with formatting preferences (decimals, style, etc.)\n */\n get displayOptions() {\n const schema = this.bean.getSchemaForProperty(this.attribute);\n const defaultUnitSystem = this.regionInfo.defaultUnitSystem;\n const converter = this.getConverter();\n const system = converter?.to?.system ?? defaultUnitSystem;\n return displayOptionsFactory(schema, system);\n }\n\n private getMeasureFromFormat() {\n const format = this.schemaFormat;\n if (format) {\n const measure = this.regionInfo.getUnitMeasure(format);\n return measure;\n }\n return \"\";\n }\n private getConverterFromFormat() {\n const measure = this.getMeasureFromFormat();\n if (measure) {\n const currentSystem = this.regionInfo.selectedUnitSystem;\n const unit =\n this.schemaFormat ||\n this.regionInfo.getDefaultUnitForMeasure(measure, currentSystem);\n return { unit, measure };\n }\n return {};\n }\n private getDefaultUnit(converter?: ConfigPropConverter) {\n const defaultUnitSystem = this.regionInfo.defaultUnitSystem;\n const measure = converter?.measure;\n if (measure) {\n const defaultUnit =\n converter?.to?.unit ||\n this.getDefaultUnitForMeasure(\n measure,\n converter?.to?.system || defaultUnitSystem\n );\n return defaultUnit;\n }\n\n return this.getConverterFromFormat().unit;\n }\n\n getFormatterOptions(converter?: ConfigPropConverter) {\n const defaultUnitSystem = this.regionInfo.defaultUnitSystem;\n\n const measure = converter?.measure;\n const locale = new Intl.NumberFormat().resolvedOptions().locale;\n let formatter: Intl.NumberFormat | null = null;\n\n if (measure || this.formatter) {\n const defaultFormatter: Intl.NumberFormatOptions | null = measure\n ? {\n style: \"unit\",\n unit: this.getDefaultUnit(converter),\n }\n : null;\n\n const _formatter = this.formatter || defaultFormatter;\n if (_formatter) {\n let formatOptions =\n typeof _formatter === \"function\"\n ? _formatter(converter?.to?.system || defaultUnitSystem)\n : _formatter;\n if (measure) {\n formatOptions = {\n unit: this.getDefaultUnit(converter),\n ...formatOptions,\n };\n\n if (formatOptions.style === \"unit\") {\n formatOptions.maximumFractionDigits =\n formatOptions.maximumFractionDigits ??\n this.getDefaultUnitDecimalPlaces(\n measure,\n converter?.to?.system || defaultUnitSystem,\n converter?.to?.unit\n );\n }\n }\n try {\n formatter = new Intl.NumberFormat(locale, { ...formatOptions });\n } catch (e) {\n log.error(\n `error creating formatter ${formatOptions}. Returning the raw value`,\n e\n );\n }\n } else {\n log.debug(\n `no formatter found for config bean prop ${this.id}. Returning the raw value`\n );\n }\n }\n\n return formatter;\n }\n\n private getConverter(): ConfigPropConverter | undefined {\n const { unit: _unit, measure } = this.getConverterFromFormat();\n\n // DRT is a display format, not a convertible unit\n if (this.schemaFormat === \"drt\") return undefined;\n const unit = _unit === \"drt\" ? \"second\" : _unit;\n if (this.converter) {\n const globalMeasure = this.converter?.measure;\n const toMeasure = this.converter?.to?.measure;\n const fromMeasure = this.converter?.from?.measure;\n const toUnitMeasure = this.converter?.to?.unit\n ? this.regionInfo.getUnitMeasure(this.converter.to.unit)\n : undefined;\n const _measure =\n globalMeasure || toMeasure || fromMeasure || toUnitMeasure || measure;\n\n const toUnit =\n this.converter?.to?.unit ||\n this.regionInfo.getDefaultUnitForMeasure(\n _measure!,\n this.converter?.to?.system ?? this.regionInfo.defaultUnitSystem\n );\n const toSystem =\n this.converter?.to?.system ?? this.regionInfo.getUnitSystem(toUnit);\n\n const fromUnit =\n this.schemaFormat === \"drt\" ? \"second\" : this.schemaFormat || unit;\n return {\n ...this.converter,\n from: {\n unit: fromUnit,\n ...this.converter.from,\n },\n\n to: {\n ...this.converter.to,\n unit: toUnit,\n system: toSystem,\n },\n measure: _measure,\n };\n }\n\n if (unit && measure) {\n const toUnit = this.regionInfo.getDefaultUnitForMeasure(\n measure,\n this.regionInfo.defaultUnitSystem\n );\n const fromSystem = this.regionInfo.getUnitSystem(unit);\n const toSystem = this.regionInfo.getUnitSystem(toUnit);\n\n const isSameSystem = fromSystem === toSystem;\n return {\n measure,\n to: {\n unit: isSameSystem ? unit : toUnit,\n },\n };\n }\n return undefined;\n }\n /**\n * Updates the configuration property value with automatic unit conversion.\n *\n * @param value - The new value to set (in regional display units)\n *\n * @example Update Property\n * ```typescript\n * // Set temperature in Fahrenheit (regional unit)\n * await temperatureProperty.updateProperty(75.5);\n *\n * // Set pump rate in mL/s (regional unit)\n * await pumpRateProperty.updateProperty(1.2);\n * ```\n */\n async updateProperty(value: ConfigPropertyTypes) {\n log.debug(`updating property ${this.attribute} with value ${value}`);\n let _value = value;\n\n const converter = this.getConverter();\n if (converter && !isNaN(_value as any)) {\n const { backend, display } = this.getConverterUnits();\n\n _value = this.regionInfo.convert(Number(_value), display, backend);\n }\n\n const updateValue = Array.isArray(_value)\n ? JSON.stringify(_value)\n : String(_value);\n await this.bean.updateProperty(this.attribute, updateValue);\n }\n}\n\nconst Registration = {\n registration: {\n [MODEL_TYPE]: {\n class: KosConfigPropertyImpl,\n singleton: false,\n },\n },\n type: MODEL_TYPE,\n factory: Kos.Factory.create<KosConfigProperty, ConfigBeanPropOptions>(\n MODEL_TYPE\n ),\n};\nexport default Registration;\n","import { runInAction } from \"mobx\";\nimport { KosLog, ModelFactory, kosAction, pipe } from \"../../../core\";\nimport type { FutureResponse } from \"../../services/future\";\nimport type { IFutureModel, IFutureModelOptions } from \"./future-types\";\n\n/**\n * Maps a `FutureResponse` DTO to an `IFutureModelOptions` object.\n *\n * @remarks\n * This function will perform any type conversion or data mapping required\n * by the IKosDataModel. For example, date conversion or changes in interfaces\n * can be managed at this layer rather than having the models deal with the\n * various versions of the interface directly.\n *\n * @params dto - the Data Transfer Object received from the backend\n * @returns - a valid `IFutureModelOptions` that can be used to\n * instantiate a new model.\n * @internal\n * @category future\n */\nexport const mapDtoToFutureOptions = (dto: FutureResponse) => {\n const options: IFutureModelOptions = {\n id: String(dto.id),\n progress: dto.progress,\n remainingTimeMs: dto.remainingTimeMs,\n endState: dto.endState,\n reason: dto.reason,\n clientData: dto.clientData,\n reasonData: dto.reasonData,\n note: dto.note,\n tracker: dto.tracker,\n };\n\n return options;\n};\n\n/**\n * Maps a `FutureResponse` DTO to an `IFutureModel` object.\n *\n * @remarks\n * This function will run as a mobx action ensuring that all observers are notified\n * if any changes are made.\n *\n * @params dto - the Data Transfer Object received from the backend\n * @params model - the IModel to be update\n * @internal\n * @category future\n */\nexport const mapDtoToFutureModel = (\n dto: FutureResponse,\n model: IFutureModel\n) => {\n KosLog.debug(`future dto ${dto.id} end state ${dto.endState}`);\n KosLog.debug(`future model ${model.id} end state ${model.endState}`);\n if (!model.endState) {\n KosLog.debug(`updating future model ${model.id}`);\n // This just maps to the new options and auto updates the model with the props\n runInAction(() => {\n const options = mapDtoToFutureOptions(dto);\n\n kosAction(() => {\n Object.keys(options).forEach((prop) => {\n if (prop === \"id\") {\n model[\"futureId\"] = options[\"id\"];\n if (!options[\"tracker\"]) {\n model.id = options[\"id\"];\n }\n } else if (prop === \"tracker\") {\n model.id = options[\"tracker\"]!;\n } else {\n // checked if the model is already in an if (!model.endState) {\n model[prop] = options[prop];\n }\n });\n });\n });\n } else {\n KosLog.debug(`future model ${model.id} is already complete`);\n }\n};\n\n/**\n * Curried function that will produce a function that can be used to retrieve or create\n * new instances of a `IFutureModel` given an ID and options.\n *\n * @remarks\n * This serves as a convenience allowing for models to consumers to use a shorthand method when\n * multiple models need to be created.\n * The first level of function will accept a KOS Model Factory and return a function that can accept a single\n * model ID parameter. This will return a factory function that can accept a model options parameter and\n * instantiate a new instance of a model or retrieve a an existing model.\n *\n * @param factory - the model factory to be used\n * @returns - an instance of the `IFutureModel` that was either created\n * or retrieved from the KOS Model framework if already existing.\n *\n * @internal\n * @category future\n */\nexport const buildFutureModel =\n (factory: ModelFactory<IFutureModel, IFutureModelOptions>) =>\n (modelId: string) =>\n (futureOptions: IFutureModelOptions) => {\n const futureModel = factory.build(String(modelId), futureOptions);\n return futureModel;\n };\n\n/**\n * Factory function that simplifies the creation of a new model\n *\n * @remarks\n * This method will map the response object to an `IFutureModelOptions` instance and\n * construct a new instance of a model using the provided factory. This will provide a shorthand\n * for consumers when creating instances of models and allows for additional operations to be performed\n * as part of the creation process.\n *\n * @example\n * // create a new (potentially static) instance of the factory that can be used throughout the code.\n * const buildFutureModel = buildFuture((FutureModel.Factory));\n *\n * // use the builder to create a new instance of the model from an options instance.\n * const future: IFutureResponse = someFunctionToGetResponseFromServer();\n * const futureModel = buildFutureModel(future);\n *\n * @param factory - The model factory that can be used to\n *\n * @internal\n * @category future\n */\nexport const buildFuture =\n (factory: ModelFactory<IFutureModel, IFutureModelOptions>) =>\n (future: FutureResponse) =>\n pipe(\n mapDtoToFutureOptions,\n buildFutureModel(factory)(future.tracker || future.id)\n )(future);\n","import { KosLog, resolveServiceUrl, ServiceFactory } from \"../../../core\";\n\nconst log = KosLog.createLogger({ name: \"future-service\", group: \"Services\" });\n\nconst { isMock, URL } = resolveServiceUrl(\"FUTURE_SERVICE\");\n\n/**\n * @category Service Module\n * @name /services/future\n * @version 1.0.0\n * @author Matthew Holman <maholman@coca-cola.com>\n *\n * Services that can be invoked to perform operations on Futures\n */\n\n/**\n * The possible endState codes returned by a Future\n */\nexport enum FutureEndState {\n Success = \"SUCCESS\",\n Fail = \"FAIL\",\n Aborted = \"ABORT\",\n Canceled = \"CANCEL\",\n}\n\n/**\n * The response from the server when an organization is\n * created or updated\n */\nexport interface FutureResponse {\n tracker?: string;\n /** the id of the Future */\n id: string;\n /** the remaining time of the Future */\n remainingTimeMs?: number;\n /** the progress of the Future */\n progress?: number;\n /** the end state of the Future */\n endState?: FutureEndState;\n /** the reason for a failure */\n reason?: string;\n /** object containing client data */\n clientData?: Record<string, unknown>;\n /** object containing reason data */\n reasonData?:\n | {\n name: string;\n version: string;\n }\n | {\n vmId: string;\n target: string;\n }\n | {\n vmId: string;\n target: string;\n }[];\n /** object containing client data */\n note?: string;\n}\n\nexport interface FutureRequest {\n /** the id of the Future to create */\n id: string;\n}\n\nconst { getAll, modifyModel, addModel, deleteModel, postModel } =\n ServiceFactory.build({\n destinationAddress: \"\",\n basePath: `${URL}/api/future`,\n mock: isMock,\n });\n\n// ------------------SERVICES----------------------\n\n/**\n * @category Service\n * Retrieves the list of Futures.\n */\nexport const getFutures = async () => {\n const response = await getAll<FutureResponse>({});\n return response;\n};\n\n/**\n * Removes an Future based on the id.\n *\n * While the immediate response to the request is empty, and additions will be broadcast\n * to all interested listeners on the `/future/delete` event channel.\n *\n * @param futureId - the id of the future to be deleted\n * @returns an empty response with status 200.\n */\nexport const deleteFuture = async (id: string, path = \"/api/kos/future\") => {\n log.info(`sending delete request for Future: ${id}`);\n const response = await deleteModel({\n id,\n urlOverride: `${URL}${path}/${id}`,\n });\n return response;\n};\n\n/**\n * Adds a new Future.\n *\n *\n * While the immediate response to the request is empty, and additions will be broadcast\n * to all interested listeners on the `/future/add` event channel.\n *\n * @param organization - the organization to be added\n * @returns an empty response with status 200.\n * @internal\n */\nexport const addFuture = async (\n future: FutureRequest,\n path = \"/api/kos/future\"\n) => {\n log.info(`sending add request for Future`);\n const response = await addModel({\n model: future,\n urlOverride: `${URL}${path}`,\n });\n return response;\n};\n\n/**\n * Modifies an Future from the server based on the id.\n *\n * While the immediate response to the request is empty, and additions will be broadcast\n * to all interested listeners on the `/future/update` event channel.\n *\n * @param id - the id of the Future to be modified\n * @returns an empty response with status 200.\n */\nexport const modifyFuture = async (\n id: string,\n model: FutureRequest,\n path = \"/api/kos/future\"\n) => {\n log.info(`sending modify request for Future: ${id}`);\n const response = modifyModel({\n model,\n id,\n urlOverride: `${URL}${path}/${id}`,\n });\n return response;\n};\n\n/**\n * Cancels a Future from the server based on the id.\n *\n * @param id - the id of the Future to be modified\n * @returns an empty response with status 200.\n */\nexport const cancelFuture = async (id: string, path = \"/api/kos/future\") => {\n log.info(`sending cancel request for Future: ${id}`);\n const response = postModel({\n urlOverride: `${URL}${path}/${id}/cancel`,\n ordered: true,\n model: {},\n });\n return response;\n};\n","import { modelFactory } from \"../../../core\";\n\nimport type { IFutureModel, IFutureModelOptions } from \"./future-types\";\n\nexport const FUTURE_MODEL_TYPE = \"future-model\";\nexport const FutureFactory = modelFactory<IFutureModel, IFutureModelOptions>(\n FUTURE_MODEL_TYPE\n);\n","import { modelFactory } from \"../../../core\";\n\nimport type {\n IFutureContainerModel,\n IFutureContainerModelOptions,\n} from \"./future-container-types\";\n\nexport const FUTURE_CONTAINER_MODEL_TYPE = \"future-container-model\";\nexport const FutureContainerFactory = modelFactory<\n IFutureContainerModel,\n IFutureContainerModelOptions\n>(FUTURE_CONTAINER_MODEL_TYPE);\n","import type { IFutureModel } from \"../../models/future/future-types\";\nimport { FutureFactory } from \"../../models/future/future-factory\";\nimport { buildFuture } from \"../../models/future/future-model-builder\";\nimport { FutureResponse } from \"../../services/future\";\nimport { FutureContainerFactory } from \"../../models/future-container/future-container-factory\";\n\nconst buildFutureModel = (payload: FutureResponse): IFutureModel => {\n /**\n * Handle all plumbing for creating a new Future.\n */\n const buildFutureModelFactory = buildFuture(FutureFactory);\n const newFutureModel = buildFutureModelFactory(payload);\n return newFutureModel;\n\n /** Callback where once an event comes it, we can immediately create the Future\n * and push it into the container.\n */\n /** Initiate Future - call the 'buildFuture' and then add it to the container */\n};\n\nconst initiateFuture = (payload: FutureResponse) => {\n const futureModel = buildFutureModel(payload);\n\n // get the Future container to add a model\n const futureContainer = FutureContainerFactory.build(\n FutureContainerFactory.type,\n {}\n );\n\n futureContainer.addFutureModel(futureModel);\n return futureModel;\n};\n\nconst getFuture = <T extends {}>(id: string) => {\n const futureContainer = FutureContainerFactory.build(\n FutureContainerFactory.type,\n {}\n );\n\n return futureContainer.getFuture(String(id)) as IFutureModel<T>;\n};\n\nexport const FutureManager = {\n buildFutureModel,\n initiateFuture,\n getFuture,\n};\n","import {\n EXTENSION_FUTURE_LIFECYCLE_WRAPPER,\n FutureAliases,\n FutureContainerSetup,\n FutureService,\n isKosExecutionContext,\n KOS_EXECUTION_CONTEXT,\n kosAction,\n kosAutoEffect,\n KosLog,\n MultipleFutureContainerSetup,\n registerExtensionPoint,\n uuid,\n whenReady,\n type KosServiceResponse,\n} from \"../../core\";\nimport { FUTURE_NOT_ASSIGNED } from \"../constants\";\nimport { mapDtoToFutureModel } from \"../models/future/future-model-builder\";\nimport {\n FutureAwareContainer,\n FutureContainer,\n} from \"../models/future/future-types\";\nimport { FutureResponse } from \"../services\";\nimport { FutureEndState } from \"../services/future\";\nimport { FutureManager } from \"../utils/future-manager\";\nexport interface FutureProps {\n alias?: string;\n namespace?: string;\n /**\n * Enable automatic AbortController integration\n * When true, the decorator will inject an AbortSignal as the last parameter\n * and set up bi-directional cancellation between Future and HTTP requests\n * @default true\n */\n abortController?: boolean;\n /**\n * Tracker injection policy\n * - 'id': Inject tracker ID as last string parameter (default, preserves existing behavior)\n * - 'context': Inject tracker ID into execution context object as $tracker property\n * @default 'id'\n */\n trackerPolicy?: \"id\" | \"context\";\n}\n\nconst isFutureResponse = (response: any): response is FutureResponse =>\n !response || !response.data;\n\n/**\n * Resolve the model's future handler by the property name it was injected\n * under.\n *\n * `@kosFutureAware` and `@kosMultipleFutureAware` accept `handlerProperty` and\n * record the chosen name on the model; `futureHandler` is only the default, so\n * the name has to be read back rather than assumed. Multiple-future setup wins\n * when a model carries both, matching the order kosModel injects them.\n */\nconst resolveFutureHandler = (model: any): FutureAwareContainer => {\n const handlerProperty =\n model?.[MultipleFutureContainerSetup]?.handlerProperty ??\n model?.[FutureContainerSetup]?.handlerProperty ??\n \"futureHandler\";\n\n return model[handlerProperty];\n};\ntype FutureHandler = (\n this: FutureContainer,\n ...args: Array<unknown>\n) => Promise<KosServiceResponse<FutureResponse> | undefined>;\n\n/**\n * Wrap an async function with Future lifecycle management.\n *\n * This is the core wrapper logic shared by the `@kosFuture` decorator\n * and the declarative model factory. It handles:\n * - Tracker ID generation and injection\n * - Future placeholder creation and readiness waiting\n * - AbortController integration (bi-directional cancellation)\n * - Future model mapping from the service response\n *\n * @param original - The raw async function to wrap.\n * @param methodName - Name of the method (used for logging).\n * @param props - Future configuration properties.\n * @returns A wrapped handler function suitable for the FutureService Symbol.\n */\nexport function wrapWithFutureLifecycle(\n original: (...args: any[]) => Promise<any>,\n methodName: string,\n props: FutureProps = {}\n): (\n this: FutureContainer,\n ...args: Array<unknown>\n) => Promise<FutureResponse | undefined> {\n const {\n alias,\n namespace,\n abortController = false,\n trackerPolicy = \"id\",\n } = props;\n\n return async function (\n this: FutureContainer,\n ...args: Array<unknown>\n ): Promise<FutureResponse | undefined> {\n // create a tracker id to track the future\n const tracker = uuid();\n KosLog.debug(\n `Calling future service ${methodName} with tracker ${tracker}`\n );\n\n // Set up AbortController if enabled\n let abortControllerInstance: AbortController | undefined;\n let effectDisposer: (() => void) | undefined;\n\n if (abortController) {\n abortControllerInstance = new AbortController();\n }\n\n // initialize a new future placeholder using the tracker id\n const future = FutureManager.initiateFuture({\n tracker,\n id: FUTURE_NOT_ASSIGNED,\n });\n if (namespace) {\n future.namespace = namespace;\n }\n KosLog.debug(`waiting for future ${future.id} to be ready`);\n await whenReady(future);\n KosLog.debug(`future ${future.id} is ready`);\n kosAction(() => {\n // eslint-disable-next-line no-invalid-this\n KosLog.debug(`Adding future ${future.id} to futureHandler`);\n resolveFutureHandler(this).addFuture(future, alias);\n });\n\n // Set up bi-directional cancellation if AbortController is enabled\n if (abortController && abortControllerInstance) {\n // 1. Future → AbortController: React to future cancellation\n effectDisposer = kosAutoEffect(() => {\n if (\n future.status === \"CANCELLED\" ||\n future.endState === FutureEndState.Canceled\n ) {\n KosLog.debug(`Future ${future.id} cancelled, aborting request`);\n abortControllerInstance?.abort();\n }\n });\n\n // 2. AbortController → Future: Listen for abort and cancel future\n abortControllerInstance.signal.addEventListener(\n \"abort\",\n async () => {\n if (\n future.status !== \"CANCELLED\" &&\n future.endState !== FutureEndState.Canceled &&\n !future.endState\n ) {\n KosLog.debug(\n `AbortController aborted, cancelling future ${future.id}`\n );\n try {\n await future.cancelFuture();\n } catch (error: any) {\n KosLog.error(`Failed to cancel future ${future.id}:`, error);\n }\n }\n },\n { once: true }\n );\n }\n\n const cleanup = () => {\n if (effectDisposer) {\n effectDisposer();\n effectDisposer = undefined;\n }\n };\n\n try {\n // Prepare arguments - inject AbortSignal if enabled\n const enhancedArgs = [...args];\n if (abortController && abortControllerInstance) {\n // Check if last argument is already an AbortSignal\n const lastArg = enhancedArgs[enhancedArgs.length - 1];\n if (lastArg && typeof lastArg === \"object\" && \"aborted\" in lastArg) {\n // Replace existing signal with our managed one\n enhancedArgs[enhancedArgs.length - 1] =\n abortControllerInstance.signal;\n } else {\n // Add signal as new parameter\n enhancedArgs.push(abortControllerInstance.signal);\n }\n }\n\n // Inject tracker based on policy\n if (trackerPolicy === \"context\") {\n // Check if last parameter is already a KosExecutionContext\n const lastArg = enhancedArgs[enhancedArgs.length - 1];\n\n if (isKosExecutionContext(lastArg)) {\n // Inject $tracker into existing context\n lastArg.$tracker = tracker;\n } else {\n // Create new context with $tracker\n const context: any = {\n [KOS_EXECUTION_CONTEXT]: true,\n $tracker: tracker,\n };\n enhancedArgs.push(context);\n }\n } else {\n // Default 'id' policy: Add tracker as final parameter (preserves existing behavior)\n enhancedArgs.push(tracker);\n }\n\n const futureResponse:\n | KosServiceResponse<FutureResponse>\n | FutureResponse\n | undefined =\n // eslint-disable-next-line no-invalid-this\n await original.apply(this, enhancedArgs);\n\n KosLog.debug(`received future response for ${tracker}`, futureResponse);\n const response = isFutureResponse(futureResponse)\n ? futureResponse\n : futureResponse?.data;\n\n if (response) {\n // hack to get the progress to show up immediately. This is a bug in the future model\n response.progress = 1;\n\n KosLog.debug(`mapping future response to future model`);\n // map the api response, which is a future response, to the future model\n // only map the response if the model has not already been completed.\n if (!future.endState) {\n mapDtoToFutureModel(response, future);\n } else {\n KosLog.debug(\n `future ${future.id} has already completed. Not updating the model`\n );\n }\n } else {\n resolveFutureHandler(this).removeFuture(alias);\n }\n\n cleanup();\n return response;\n } catch (e) {\n cleanup();\n\n // Convert abort errors to more user-friendly messages\n if (abortController && abortControllerInstance?.signal.aborted) {\n const cancelledError = new Error(\"Operation cancelled\");\n KosLog.debug(`Operation ${methodName} was cancelled`);\n throw cancelledError;\n }\n\n KosLog.error(e);\n throw e;\n }\n };\n}\n\n// Register wrapWithFutureLifecycle as an extension point so the\n// declarative model package can retrieve it without a direct import\n// (which would create a circular / wrong-direction dependency).\nregisterExtensionPoint(EXTENSION_FUTURE_LIFECYCLE_WRAPPER, {\n register: () => {\n /* single implementation, no dynamic registration needed */\n },\n execute: () => wrapWithFutureLifecycle,\n});\n\nexport function kosFuture(props: FutureProps = {}) {\n const { alias } = props;\n return (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {\n target[FutureService] = target[FutureService] || {};\n\n // Store alias metadata for @kosMultipleFutureAware decorator\n if (alias) {\n target[FutureAliases] = target[FutureAliases] || new Map();\n target[FutureAliases].set(propertyKey, alias);\n }\n\n const original: FutureHandler = descriptor.value;\n const handler = wrapWithFutureLifecycle(original, propertyKey, props);\n\n target[FutureService][propertyKey] = {\n handler,\n };\n };\n}\n","/**\n * @internal\n */\nimport { KosLog, ServiceFactory, resolveServiceUrl } from \"../../../../core\";\nconst { URL } = resolveServiceUrl(\"STATE-BEAN_SERVICE\");\nconst { getOne } = ServiceFactory.build({\n basePath: `${URL}/api/kos/state`,\n});\n\nconst log = KosLog.createLogger({\n name: \"state-bean-service\",\n group: \"Services\",\n});\nexport interface StateBeanResponse {\n [k: string]: string | number | boolean;\n}\n\ninterface StateBeanOptions {\n path: string;\n}\n/**\n * @category Service\n * @internal\n * Retrieves the initial state-bean data.\n */\nexport const getStateBeanData = async ({ path }: StateBeanOptions) => {\n log.debug(\"sending GET for state-bean\");\n const response = await getOne<StateBeanResponse>({\n urlOverride: `${URL}/api/kos/state/${path}`,\n });\n return response;\n};\n","import type {\n IKosModelLogger,\n KosContextLogger,\n KosCreationContext,\n} from \"../../../core\";\nimport {\n createPropKey,\n kosModel,\n kosObservable,\n kosTopicHandler,\n mapDataToModel,\n} from \"../../../core\";\nimport type { PublicModelInterface } from \"../../../core/types\";\nimport { isBoolean, isNumber } from \"../../utils/prop-utils\";\nimport { StatePropertyTypes } from \"../types\";\nimport { getStateBeanData, type StateBeanResponse } from \"./services\";\nimport type { StateBeanModel, StateBeanOptions, StatePropsMap } from \"./types\";\n\nexport const MODEL_TYPE = \"state-bean-model\";\n\n/**\n * StateBean - Reactive state management for KOS device state properties.\n *\n * The StateBean model provides real-time access to KOS device state information through\n * reactive properties that automatically synchronize with device state changes via WebSocket\n * topics. This model is essential for applications that need to monitor device state,\n * track property changes, or build reactive UIs that respond to device status updates.\n *\n * ## Key Features\n * - **Real-time Synchronization** - Automatic updates via `/kos/state/{path}` WebSocket topics\n * - **Type-safe Properties** - Strongly typed state properties with automatic type conversion\n * - **Observable State Map** - Reactive Map-based property storage for efficient updates\n * - **Automatic Type Conversion** - Smart conversion of string values to boolean/number types\n * - **Path-based Organization** - Hierarchical state organization using dot-notation paths\n * - **Lifecycle Management** - Proper initialization and loading of state data\n *\n * ## Topic-Based Reactivity\n * The model listens to KOS topics for real-time synchronization:\n * - **`/kos/state/{path}`** - Receives state updates for the specified path, triggering automatic property updates across all connected clients\n *\n * ## State Property Types\n * Supports all common KOS state property types:\n * - **string** - Text values, configuration strings, identifiers\n * - **number** - Numeric values, counters, measurements, percentages\n * - **boolean** - Status flags, enabled/disabled states, operational flags\n * - **object** - Complex state objects, nested configurations\n *\n * ## Common Use Cases\n * - **Device Status Monitoring** - Track operational states, error conditions, health metrics\n * - **Configuration State** - Monitor dynamic configuration changes and feature flags\n * - **System Status Dashboards** - Build real-time status displays and monitoring interfaces\n * - **Conditional UI Logic** - Show/hide UI elements based on device state\n * - **State-dependent Operations** - Enable/disable functionality based on device state\n * - **Multi-client Synchronization** - Keep multiple clients in sync with device state\n *\n * @interface\n * @example Basic Usage\n * ```typescript\n * const deviceState = StateBean.instance('device-status')\n * .options({ path: 'device.operational.status' })\n * .build();\n *\n * // Access reactive state properties\n * const isOnline = deviceState.props.get('online') as boolean;\n * const temperature = deviceState.props.get('temperature') as number;\n * ```\n *\n * @group KOS Model\n * @category State Management\n * @useDeclaredType\n *\n * @see {@link StateBeanOptions} - Configuration options for StateBean model\n * @see {@link StatePropertyTypes} - Supported state property value types\n * @see {@link StateProp} - Individual property access model\n * @see {@link getStateBeanData} - Service function for loading state data\n */\nexport type StateBean<\n T extends Record<string, StatePropertyTypes> = Record<\n string,\n StatePropertyTypes\n >\n> = PublicModelInterface<StateBeanModelImpl<T>>;\n\nconst PATH_PROP = createPropKey<StateBeanModel>(\"path\");\n\n/**\n * @ignore\n * @internal\n */\n@kosModel(MODEL_TYPE)\nexport class StateBeanModelImpl<\n T extends Record<string, StatePropertyTypes> = Record<\n string,\n StatePropertyTypes\n >\n> implements StateBeanModel<T>, IKosModelLogger\n{\n /** Unique identifier for the model instance */\n id: string;\n /** State path being monitored for updates */\n path!: string;\n /** Reactive Map of state properties with automatic type conversion */\n props: StatePropsMap<T>;\n /** Context logger for debugging and diagnostics */\n logger: KosContextLogger;\n constructor(\n modelId: string,\n options: StateBeanOptions,\n context: KosCreationContext\n ) {\n this.id = modelId;\n this.logger = context.logger;\n this.props = kosObservable.map(new Map());\n mapDataToModel(options, this);\n }\n\n /**\n * Updates the model configuration with new options.\n * @param options New configuration options to apply\n */\n updateModel(options: StateBeanOptions): void {\n mapDataToModel(options, this);\n }\n\n /**\n * Handles WebSocket state updates from the KOS topic system.\n * Automatically converts string values to appropriate types (boolean, number).\n * @param stateBean State data received from WebSocket topic\n * @internal\n */\n @kosTopicHandler({\n topic: `/kos/state/${PATH_PROP}`,\n websocket: true,\n })\n handleConfigBeanUpdated(stateBean: StateBeanResponse) {\n Object.entries(stateBean).forEach(([key, value]) => {\n let val = value;\n\n if (typeof val === \"string\" && isBoolean(val)) {\n val = val.toLowerCase() == \"true\";\n }\n\n if (typeof val === \"string\" && isNumber(val)) {\n val = Number(val);\n }\n\n this.props.set(key, val as T[keyof T]);\n });\n }\n\n // -------------------LIFECYCLE----------------------------\n\n /**\n * @internal\n */\n async init(): Promise<void> {\n this.logger.debug(`initializing state-bean ${this.id}`);\n }\n\n /**\n * Updates multiple properties at once with type conversion.\n * @param props Properties to update\n * @private\n */\n updateProps(props: Record<string, StatePropertyTypes>) {\n Object.entries(props).forEach(([key, value]) => {\n this.props.set(key, value);\n });\n }\n\n /**\n * @internal\n */\n async load(): Promise<void> {\n this.logger.debug(`loading state-bean ${this.id}`);\n const response = await getStateBeanData({ path: this.path });\n if (response?.data) {\n this.updateProps(response.data);\n }\n }\n}\n","import type { KosModelRegistrationBean } from \"../../../core\";\nimport { Kos, isKosModel } from \"../../../core\";\nimport { MODEL_TYPE, StateBeanModelImpl } from \"./state-bean-model\";\nimport type { StateBeanModel, StateBeanOptions } from \"./types\";\n\n/**\n * # StateBean\n *\n * The registration bean includes convenience methods for creating and working with StateBeanModel instances.\n *\n * ## type\n * The type property is a string that identifies the model type.\n * The type is used to identify the model type in the model registry and to narrow down the model type in type predicates. It's most frequently\n * used when declaring dependencies on models.\n *\n * @example\n * ```typescript\n *\n * @kosDependency({modelType: StateBean.type, id: \"stateBeanId\"})\n * private stateBeanModel: StateBeanModel;\n * ```\n *\n *\n * ## factory\n *\n * The factory method creates a factory function that can be used to create new StateBeanModel instances.\n *\n \n * The factory function is a curried function that takes the model id as the first argument and the options as the second argument.\n *\n * If a model with the specified id already exists, the factory function will return the existing model. The options will be ignored\n * in this case and the existing model will be returned in its current state.\n *\n * @example\n * ```typescript\n * const model = StateBean.factory(\"stateBeanId\")({\n * // Add option data\n * });\n * ```\n \n\n *\n * ## predicate\n *\n * [Typescript type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) function that will identify and narrow down a model to a StateBeanModel.\n *\n * @example\n * ```typescript\n *\n * const model: IKosDataModel = ...; // some model\n *\n * if (StateBean.predicate(model)) {\n * // if the function evaluates to true, the model is narrowed down to StateBeanModel\n * // and the compiler will know that the model has the StateBeanModel interface\n * model.updateAvailability(false);\n * }\n * ```\n *\n * ## registration\n *\n * The registration property is an object that can be used to simplify registration of the model with the model registry. The registration object\n * can be spread into the model registration and provides all of the required information to register the model implementation class against the model type.\n *\n *\n * @example\n *\n * In an application registration file you can declare the model registration as follows:\n *\n * **registration.ts**\n * ```typescript\n * import { StateBean } from \"@kosdev-code/kos-dispense-sdk\";\n * ...\n * import { ExtensionManager, IKosRegistry } from \"@kosdev-code/kos-ui-sdk\";\n * export const kosModels: IKosRegistry[\"models\"] = {\n * ...StateBean.registration,\n * };\n * ```\n *\n * ## registration.singleton\n \n * The stateBean model is NOT a singleton model. This means that each time the factory function is called with a unique ID, a new model instance will be created.\n * If the factory function is called with an ID that already exists, the existing model will be returned.\n \n * */\nexport const StateBean: Readonly<\n KosModelRegistrationBean<StateBeanModel, StateBeanOptions>\n> = {\n registration: {\n [MODEL_TYPE]: {\n class: StateBeanModelImpl,\n singleton: false,\n },\n },\n type: MODEL_TYPE,\n predicate: isKosModel(MODEL_TYPE),\n factory: Kos.Factory.create<StateBeanModel, StateBeanOptions>(MODEL_TYPE),\n};\n","import type {\n IKosModelLogger,\n KosContextLogger,\n KosCreationContext,\n} from \"../../../core\";\nimport { createPropKey, kosDependency, kosModel } from \"../../../core\";\nimport type { PublicModelInterface } from \"../../../core/types\";\nimport { StateBean } from \"../state-bean\";\nimport type { StateBeanModel, StateBeanOptions } from \"../state-bean/types\";\nimport type { StatePropertyTypes } from \"../types\";\nimport type { KosStateProp, StatePropOptions } from \"./types\";\n\nexport const MODEL_TYPE = \"state-prop-model\";\n\n/**\n * StateProp - Focused access to individual state properties with dependency on StateBean.\n *\n * The StateProp model provides targeted access to a single property within a StateBean,\n * offering a focused interface for components or services that only need to monitor\n * specific state values. This model automatically manages its dependency on the underlying\n * StateBean and provides reactive access to individual property values.\n *\n * ## Key Features\n * - **Single Property Focus** - Access one specific property from a StateBean path\n * - **Automatic StateBean Dependency** - Manages StateBean dependency transparently\n * - **Type-safe Value Access** - Strongly typed property value with generic support\n * - **Reactive Updates** - Automatically updates when underlying StateBean changes\n * - **Simplified Interface** - Clean `.value` accessor for property values\n * - **String Conversion** - Built-in `toString()` method for display purposes\n *\n * ## StateBean Integration\n * StateProp models automatically create and manage dependencies on StateBean models:\n * - **Automatic Dependency** - Creates StateBean with matching path automatically\n * - **Shared StateBean** - Multiple StateProp models can share the same StateBean\n * - **Lifecycle Management** - Proper initialization and cleanup of dependencies\n * - **Real-time Synchronization** - Inherits WebSocket updates from StateBean\n *\n * ## Common Use Cases\n * - **Single Value Components** - React components that only need one state property\n * - **Conditional Logic** - Enable/disable functionality based on specific state\n * - **Status Indicators** - Display individual status flags or measurements\n * - **Property Validation** - Monitor specific properties for validation rules\n * - **Focused Updates** - Reduce re-renders by tracking only needed properties\n * - **Service Dependencies** - Services that depend on specific state values\n *\n * @interface\n * @example Basic Usage\n * ```typescript\n * const deviceOnline = StateProp.instance('device-online')\n * .options({\n * path: 'device.operational.status',\n * attribute: 'online'\n * })\n * .build();\n *\n * // Access focused property value with type safety\n * const isOnline = deviceOnline.value as boolean;\n * console.log(`Status: ${deviceOnline.toString()}`);\n * ```\n *\n * @group KOS Model\n * @category State Management\n * @useDeclaredType\n *\n * @see {@link StatePropOptions} - Configuration options for StateProp model\n * @see {@link StatePropertyTypes} - Supported property value types\n * @see {@link StateBean} - Underlying state collection model\n * @see {@link StateBeanOptions} - StateBean configuration options\n */\nexport type StateProp<T extends StatePropertyTypes = StatePropertyTypes> =\n PublicModelInterface<StatePropModelImpl<T>>;\n\nconst PATH_PROP = createPropKey<StateBeanModel>(\"path\");\n\n/**\n * @ignore\n * @internal\n */\n@kosModel(MODEL_TYPE)\nexport class StatePropModelImpl<\n T extends StatePropertyTypes = StatePropertyTypes\n> implements KosStateProp<T>, IKosModelLogger\n{\n /** Unique identifier for the model instance */\n id: string;\n /** State path being monitored (same as dependent StateBean) */\n path: string;\n /** Specific attribute name to access within the state path */\n attribute: string;\n /** Context logger for debugging and diagnostics */\n logger: KosContextLogger;\n\n /** Automatic dependency on StateBean for the specified path */\n @kosDependency<StateBeanOptions>({\n modelType: StateBean.type,\n id: `${StateBean.type}-${PATH_PROP}`,\n options: { path: PATH_PROP },\n })\n stateBean!: StateBeanModel;\n\n constructor(\n modelId: string,\n options: StatePropOptions,\n context: KosCreationContext\n ) {\n this.id = modelId;\n this.logger = context.logger;\n this.path = options.path;\n this.attribute = options.attribute;\n if (options) {\n // Assign options properties here.\n }\n }\n\n /** The current value of the specific attribute, with type safety */\n get value(): T | undefined {\n return this.stateBean.props.get(this.attribute) as T;\n }\n\n // -------------------LIFECYCLE----------------------------\n\n /**\n * @internal\n */\n async init(): Promise<void> {\n this.logger.debug(`initializing state-prop ${this.id}`);\n }\n\n /**\n * @internal\n */\n async load(): Promise<void> {\n this.logger.debug(`loading state-prop ${this.id}`);\n }\n\n /**\n * Converts the current property value to string for display purposes.\n * @returns String representation of the property value, or empty string if undefined\n */\n toString(): string {\n return this.value?.toString() ?? \"\";\n }\n}\n","import type { KosModelRegistrationBean } from \"../../../core\";\nimport { Kos, isKosModel } from \"../../../core\";\nimport { MODEL_TYPE, StatePropModelImpl } from \"./state-prop-model\";\nimport type { KosStateProp, StatePropOptions } from \"./types\";\n\n/**\n * # StateProp\n *\n * The registration bean includes convenience methods for creating and working with StatePropModel instances.\n *\n * ## type\n * The type property is a string that identifies the model type.\n * The type is used to identify the model type in the model registry and to narrow down the model type in type predicates. It's most frequently\n * used when declaring dependencies on models.\n *\n * @example\n * ```typescript\n *\n * @kosDependency({modelType: StateProp.type, id: \"statePropId\"})\n * private statePropModel: StatePropModel;\n * ```\n *\n *\n * ## factory\n *\n * The factory method creates a factory function that can be used to create new StatePropModel instances.\n *\n \n * The factory function is a curried function that takes the model id as the first argument and the options as the second argument.\n *\n * If a model with the specified id already exists, the factory function will return the existing model. The options will be ignored\n * in this case and the existing model will be returned in its current state.\n *\n * @example\n * ```typescript\n * const model = StateProp.factory(\"statePropId\")({\n * // Add option data\n * });\n * ```\n \n\n *\n * ## predicate\n *\n * [Typescript type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) function that will identify and narrow down a model to a StatePropModel.\n *\n * @example\n * ```typescript\n *\n * const model: IKosDataModel = ...; // some model\n *\n * if (StateProp.predicate(model)) {\n * // if the function evaluates to true, the model is narrowed down to StatePropModel\n * // and the compiler will know that the model has the StatePropModel interface\n * model.updateAvailability(false);\n * }\n * ```\n *\n * ## registration\n *\n * The registration property is an object that can be used to simplify registration of the model with the model registry. The registration object\n * can be spread into the model registration and provides all of the required information to register the model implementation class against the model type.\n *\n *\n * @example\n *\n * In an application registration file you can declare the model registration as follows:\n *\n * **registration.ts**\n * ```typescript\n * import { StateProp } from \"@kosdev-code/kos-dispense-sdk\";\n * ...\n * import { ExtensionManager, IKosRegistry } from \"@kosdev-code/kos-ui-sdk\";\n * export const kosModels: IKosRegistry[\"models\"] = {\n * ...StateProp.registration,\n * };\n * ```\n *\n * ## registration.singleton\n \n * The stateProp model is NOT a singleton model. This means that each time the factory function is called with a unique ID, a new model instance will be created.\n * If the factory function is called with an ID that already exists, the existing model will be returned.\n \n * */\nexport const StateProp: Readonly<\n KosModelRegistrationBean<KosStateProp, StatePropOptions>\n> = {\n registration: {\n [MODEL_TYPE]: {\n class: StatePropModelImpl,\n singleton: false,\n },\n },\n type: MODEL_TYPE,\n predicate: isKosModel(MODEL_TYPE),\n factory: Kos.Factory.create<KosStateProp, StatePropOptions>(MODEL_TYPE),\n};\n","/**\n * @internal\n */\nimport { KosLog, ServiceFactory, resolveServiceUrl } from \"../../../../core\";\nconst { URL } = resolveServiceUrl(\"STATE-PROP_SERVICE\");\nconst { getAll } = ServiceFactory.build({\n basePath: `${URL}/api/state-prop`,\n});\n\nconst log = KosLog.createLogger({\n name: \"state-prop-service\",\n group: \"Services\",\n});\ninterface StatePropResponse {\n id: string;\n}\n/**\n * @category Service\n * @internal\n * Retrieves the initial state-prop data.\n */\nexport const getStateProps = async () => {\n log.debug(\"sending GET for state-prop\");\n const response = await getAll<StatePropResponse>({});\n return response;\n};\n","import {\n BrowserKosRouter,\n type IKosDataModel,\n type IKosIdentifiable,\n type KosContextLogger,\n type KosCreationContext,\n type KosMethodTypes,\n type KosMiddleware,\n kosModel,\n type KosRequest,\n type KosResponse,\n kosTopicHandler,\n type PublicModelInterface,\n sendKosHttpMessageResponse,\n} from \"../../../core\";\n\nimport type { BrowserRouterOptions } from \"./types\";\n\nexport const MODEL_TYPE = \"browser-router-model\";\n\nconst HTTP_REQUEST_TOPIC = \"kos.http.request\";\nconst HTTP_RESPONSE_TOPIC = \"kos.http.response\";\n\n/**\n * BrowserRouter - HTTP routing and middleware management for KOS web services.\n *\n * The BrowserRouter model provides a comprehensive HTTP routing system that handles incoming\n * requests via WebSocket topics and routes them through registered middleware and handlers.\n * It enables KOS applications to expose REST APIs, handle device communication, and manage\n * HTTP-based integrations with automatic OpenAPI specification generation.\n *\n * ## Key Features\n * - **Topic-Based HTTP Handling** - Processes HTTP requests via `kos.http.request` topic\n * - **Middleware Support** - Chain multiple middleware functions for request processing\n * - **Route Management** - Dynamic registration, removal, and inspection of routes\n * - **OpenAPI Generation** - Automatic API documentation at `/openapi.json`\n * - **Request/Response Abstraction** - Familiar Express.js-style request/response objects\n * - **Method Support** - Full HTTP method support (GET, POST, PUT, DELETE, PATCH)\n *\n * ## Topic-Based Reactivity\n * The model listens to these KOS topics for HTTP request handling:\n * - **`kos.http.request`** - Incoming HTTP requests from clients or other services\n * - **`kos.http.response`** - Outgoing HTTP responses with status codes and data\n *\n * ## Common Use Cases\n * - **REST API Endpoints** - Expose device data and control APIs\n * - **Webhook Handlers** - Process incoming webhooks from external services\n * - **Inter-Service Communication** - Handle requests between KOS services\n * - **Device Integration** - Bridge HTTP protocols with KOS messaging\n * - **API Gateway** - Route and transform requests to downstream services\n *\n * @interface\n * @example Basic Usage\n * ```typescript\n * const router = KosBrowserRouter.instance('main-router')\n * .options({})\n * .build();\n *\n * // Register HTTP endpoints with middleware support\n * router.use('GET', '/api/status', async (req, res) => {\n * res.send({ status: 'online' });\n * });\n *\n * router.use('POST', '/api/commands', validateAuth, async (req, res) => {\n * res.status(200).send({ success: true });\n * });\n * ```\n *\n * @group KOS Model\n * @category Browser Router\n * @category Service Integration\n * @useDeclaredType\n *\n * @see {@link BrowserRouterOptions} - Configuration options for BrowserRouter instances\n */\nexport type KosBrowserRouter = Omit<\n PublicModelInterface<BrowserRouterModelImpl>,\n \"load\" | \"init\"\n>;\n\n/**\n * @ignore\n * @internal\n */\n@kosModel(MODEL_TYPE)\nexport class BrowserRouterModelImpl implements IKosDataModel, IKosIdentifiable {\n /** Unique identifier for the router model instance */\n private _id: string;\n /** Context logger for debugging HTTP requests and routing */\n private logger: KosContextLogger;\n /** Internal HTTP router instance handling middleware chains */\n private router: BrowserKosRouter;\n constructor(\n modelId: string,\n _options: BrowserRouterOptions,\n context: KosCreationContext\n ) {\n this._id = modelId;\n this.logger = context.logger;\n this.router = new BrowserKosRouter();\n }\n\n /** Model instance identifier */\n get id(): string {\n return this._id;\n }\n\n /**\n * Handles incoming HTTP requests from WebSocket topics.\n * @param data Request body data\n * @param payload Request headers and metadata\n * @internal\n */\n @kosTopicHandler({\n topic: HTTP_REQUEST_TOPIC,\n })\n private async handleRequest(data, payload): Promise<void> {\n const destination = payload.headers[\"src-addr\"];\n const src = payload.headers[\"dst-addr\"];\n const url = payload.headers[\"url\"];\n const method = payload.headers[\"method\"];\n const requestId = payload.headers[\"request-id\"];\n const rawReq: Omit<KosRequest, \"params\" | \"query\"> = {\n id: requestId,\n method,\n path: url,\n body: data,\n headers: payload.headers,\n };\n\n let status = 200;\n const res: KosResponse = {\n send: (data: any) => {\n this.logger.debug(`sending response to ${src}`);\n this.logger.debug(data);\n sendKosHttpMessageResponse({\n msg: data,\n options: {\n responseId: requestId,\n destinationAddress: destination,\n type: HTTP_RESPONSE_TOPIC,\n sourceAddress: src,\n status: status,\n },\n });\n },\n status: function (code) {\n status = code;\n return this;\n },\n };\n\n if (rawReq.path === \"/openapi.json\") {\n res.send(this.router.generateOpenApiSpec());\n return;\n }\n await this.router.handle(rawReq, res);\n }\n\n /**\n * Registers a route with optional middleware chain.\n * @param method HTTP method (GET, POST, PUT, DELETE, PATCH)\n * @param path Route path pattern with parameter support\n * @param middlewares Middleware functions and final handler\n */\n use<TPath extends string = string>(\n method: KosMethodTypes,\n path: TPath,\n ...middlewares: KosMiddleware<TPath>[]\n ): void {\n this.router.use(method, path, ...middlewares);\n }\n\n /**\n * Remove routes matching the given method and path\n * @param method HTTP method (GET, POST, etc.)\n * @param path Route path pattern\n * @returns Number of routes removed\n */\n remove(method: KosMethodTypes, path: string): number {\n return this.router.remove(method, path);\n }\n\n /**\n * Remove all routes matching a path pattern (regardless of method)\n * @param path Route path pattern\n * @returns Number of routes removed\n */\n removeAllForPath(path: string): number {\n return this.router.removeAllForPath(path);\n }\n\n /**\n * Gets all registered routes for debugging and monitoring.\n * @returns Array of route objects with method and path\n */\n getRoutes(): Array<{ method: string; path: string }> {\n return this.router.getRoutes();\n }\n // -------------------LIFECYCLE----------------------------\n\n /**\n * @internal\n */\n async init(): Promise<void> {\n this.logger.debug(`initializing browser-router ${this.id}`);\n }\n\n /**\n * @internal\n */\n async load(): Promise<void> {\n this.logger.debug(`loading browser-router ${this.id}`);\n }\n}\n","import { SingletonKosModelRegistrationFactory } from \"../../../core\";\nimport type { KosBrowserRouter } from \"./browser-router-model\";\nimport { BrowserRouterModelImpl, MODEL_TYPE } from \"./browser-router-model\";\nimport type { BrowserRouterOptions } from \"./types\";\n\n/**\n * # BrowserRouter\n *\n * The registration bean includes convenience methods for creating and working with BrowserRouterModel instances.\n *\n * ## type\n * The type property is a string that identifies the model type.\n * The type is used to identify the model type in the model registry and to narrow down the model type in type predicates. It's most frequently\n * used when declaring dependencies on models.\n *\n * @example\n * ```typescript\n *\n * @kosDependency({modelType: BrowserRouter.type, id: \"browserRouterId\"})\n * private browserRouterModel: BrowserRouterModel;\n * ```\n *\n *\n * ## factory\n *\n * The factory method creates a factory function that can be used to create new BrowserRouterModel instances.\n *\n \n * As this is a singleton model, the factory function accepts the model options as its argument.\n *\n * If a model with the same model type already exists, the factory function will return the existing model. The options will be ignored\n * in this case and the existing model will be returned in its current state.\n *\n * @example\n * ```typescript\n * const model = BrowserRouter.factory({\n * // Add option data\n * });\n * ```\n \n\n *\n * ## predicate\n *\n * [Typescript type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) function that will identify and narrow down a model to a BrowserRouterModel.\n *\n * @example\n * ```typescript\n *\n * const model: IKosDataModel = ...; // some model\n *\n * if (BrowserRouter.predicate(model)) {\n * // if the function evaluates to true, the model is narrowed down to BrowserRouterModel\n * // and the compiler will know that the model has the BrowserRouterModel interface\n * model.updateAvailability(false);\n * }\n * ```\n *\n * ## registration\n *\n * The registration property is an object that can be used to simplify registration of the model with the model registry. The registration object\n * can be spread into the model registration and provides all of the required information to register the model implementation class against the model type.\n *\n *\n * @example\n *\n * In an application registration file you can declare the model registration as follows:\n *\n * **registration.ts**\n * ```typescript\n * import { BrowserRouter } from \"@kos-ui/project-models\";\n * import { KosModelRegistry } from \"@kosdev-code/kos-dispense-sdk\";\n *\n * import { initKosProvider } from \"@kosdev-code/kos-ui-sdk\";\n *\n * KosModelRegistry.dispense\n * .models()\n * .model(BrowserRouter);\n * ```\n *\n * ## registration.singleton\n \n * The browserRouter model is a singleton model. This means that each time the factory function is called , the same instance will be returned.\n * If the model does not yet exist, it will be created passing in the provided options to initialize it.\n *\n * Singleton models don't require an ID as they will use the model type as their ID to guarantee uniqueness throughout the system.\n \n * */\nexport const BrowserRouter = new SingletonKosModelRegistrationFactory<\n KosBrowserRouter,\n BrowserRouterOptions\n>({\n class: BrowserRouterModelImpl,\n type: MODEL_TYPE,\n});\n","/* eslint-disable @typescript-eslint/no-unsafe-declaration-merging */\nimport {\n KosLog,\n destroyKosModel,\n kosModel,\n kosTopicHandler,\n kosWhen,\n type KosContextLogger,\n type KosCreationContext,\n} from \"../../../core\";\nimport {\n FutureEndState,\n cancelFuture,\n cancelFuture as cancelFutureService,\n type FutureResponse,\n} from \"../../services/future\";\nimport { mapDtoToFutureModel } from \"./future-model-builder\";\nimport type { IFutureModel, IFutureModelOptions } from \"./future-types\";\n\nimport { KOS_MODEL_ID } from \"../../../common\";\nimport { FUTURE_NOT_ASSIGNED } from \"../../constants\";\nimport { FutureFactory } from \"./future-factory\";\n\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\ninterface FutureModel extends IFutureModel {}\ntype TimeUnits = \"year\" | \"month\" | \"day\" | \"hour\" | \"minute\" | \"second\";\nconst log = KosLog.getLogger(FutureFactory.type);\n\n/**\n * @category future\n * @name FutureModel\n * @version 1.0.0\n * @author Matthew Holman <maholman@coca-cola.com>\n *\n * Represents a future.\n */\n@kosModel(FutureFactory.type)\nclass FutureModel implements IFutureModel {\n private logger: KosContextLogger;\n private _cancelFuture: (\n id: string,\n path?: string\n ) => ReturnType<typeof cancelFutureService>;\n futureId: string;\n /**\n * @category Constructor\n *\n * @param modelId - the unique modelId for this Future\n * @param options - any options that should be merged into the Future\n * @params options.id - the unique id of the Future\n * @params options.name - the name of the Future\n *\n */\n constructor(\n modelId: string,\n options: IFutureModelOptions,\n context: KosCreationContext\n ) {\n Object.assign(this, options);\n\n this.logger = context.logger;\n // assign the id from the passed in model id\n this.id = modelId;\n this.futureId = options.id;\n this.namespace = options.namespace || \"kos\";\n // assign private methods from options\n\n this._cancelFuture = cancelFuture;\n\n kosWhen(\n () =>\n this.status === FutureEndState.Success ||\n this.status === FutureEndState.Fail,\n () => {\n log.info(`Future ${this.id} has completed with status ${this.status}`);\n destroyKosModel(this);\n }\n );\n }\n\n /**\n * @internal\n *\n * @remarks\n * No action is taken as part of the load lifecycle method.\n *\n * In future additional information about the workspace could be loaded\n */\n async load() {\n log.debug(`loading Future ${this.id}`);\n }\n\n /**\n * @internal\n */\n unload() {\n log.info(`unloading Future ${this.id}`);\n }\n\n // -------------------ACTIONS----------------------------\n\n /**\n * @category Action\n *\n * @remark\n * Cancels the current future.\n *\n * If a service was passed in as part of the options in the constructor\n * then it will be used. Otherwise the default services will be invoked.\n *\n * @see cancelFutureService\n */\n async cancelFuture() {\n const path =\n this.namespace === \"studio\"\n ? `/api/future`\n : `/api/${this.namespace}/future`;\n await kosWhen(() => this.futureId !== FUTURE_NOT_ASSIGNED);\n const response = await this._cancelFuture(this.futureId, path);\n if (response?.status !== 200) {\n log.error(\n `Failed to cancel Future ${this.id}. Response: ${JSON.stringify(\n response\n )}`\n );\n }\n }\n\n /**\n * Gets the current status of the future operation.\n *\n * @returns Status string: \"NOT_ACTIVE\", \"IN_PROGRESS\", \"Success\", or \"Fail\"\n *\n * @example Monitor Status\n * ```typescript\n * if (future.status === \"IN_PROGRESS\") {\n * console.log(`Operation running: ${future.progress}% complete`);\n * } else if (future.status === \"Success\") {\n * console.log(\"Operation completed successfully!\");\n * }\n * ```\n */\n get status() {\n return this.endState\n ? this.endState\n : this.progress > -1\n ? \"IN_PROGRESS\"\n : \"NOT_ACTIVE\";\n }\n\n /**\n * Gets human-readable time remaining for the operation.\n *\n * @returns Formatted time string (e.g., \"5 minutes\", \"30 seconds\") or empty string if unknown\n *\n * @example Display Time Remaining\n * ```typescript\n * const timeLeft = future.timeRemaining;\n * if (timeLeft) {\n * console.log(`${timeLeft} remaining`);\n * }\n * ```\n */\n get timeRemaining() {\n const remaining = this.remainingTimeMs || -1;\n\n if (remaining < 0) {\n return \"\";\n }\n\n const units: Record<TimeUnits, number> = {\n year: 1000 * 60 * 60 * 24 * 365,\n month: 1000 * 60 * 60 * 24 * 30,\n day: 1000 * 60 * 60 * 24,\n hour: 1000 * 60 * 60,\n minute: 1000 * 60,\n second: 1000,\n };\n\n let unit: Intl.RelativeTimeFormatUnit = \"second\",\n value = 0;\n for (const [key, milliseconds] of Object.entries(units)) {\n if (Math.abs(remaining) >= milliseconds) {\n unit = key as TimeUnits;\n value = Math.round(remaining / milliseconds);\n break;\n }\n }\n\n const rtf = new Intl.RelativeTimeFormat(\"en\", { numeric: \"auto\" });\n const parts = rtf.formatToParts(value, unit);\n\n // Step 6: Construct the custom \"remaining\" message\n const formattedTime =\n parts.length === 3\n ? `${parts[1]?.value ?? 0} ${parts[2]?.value ?? \"\"}`\n : \"0 seconds\";\n\n return formattedTime;\n }\n\n // ------------------SUBSCRIPTIONS----------------------\n\n /**\n * @internal\n * @category Subscription\n * Updates the Future model when a `kos.future/{ID}` event\n * is received from the server.\n *\n * @param future - the Future that was updated.\n * @see FutureResponse\n */\n @kosTopicHandler({\n topic: `kos.future/${KOS_MODEL_ID}`,\n })\n handleFutureUpdated(future: FutureResponse) {\n this.logger.debug(\n `Future ${this.id} updated. future: ${future.id} endState: ${future.endState} progress: ${future.progress} remainingTimeMs: ${future.remainingTimeMs}`\n );\n mapDtoToFutureModel(future, this);\n }\n}\n\nexport default FutureModel;\n","/**\n * @internal\n */\nimport {\n KosContextLogger,\n KosLog,\n KosModelContainer,\n kosChild,\n kosModel,\n kosTopicHandler,\n type IKosModelContainer,\n type KosCreationContext,\n type KosServiceResponse,\n} from \"../../../core\";\nimport type { FutureRequest, FutureResponse } from \"../../services/future\";\n\nimport { EventBus, type ApiCallback } from \"../../../common\";\nimport {\n addFuture as addFutureService,\n deleteFuture as deleteFutureService,\n} from \"../../services/future\";\nimport { FutureManager } from \"../../utils/future-manager\";\nimport type { IFutureModel } from \"../future\";\nimport { buildFuture } from \"../future\";\nimport { FutureFactory } from \"../future/future-factory\";\nimport { FutureContainerFactory } from \"./future-container-factory\";\nimport type {\n IFutureContainerModel,\n IFutureContainerModelOptions,\n} from \"./future-container-types\";\nconst log = KosLog.getLogger(FutureContainerFactory.type);\n\n/**\n * @category future\n * @name FutureContainerModel\n * @version 1.0.0\n * @author Matthew Holman <maholman@coca-cola.com>\n * @internal\n * Represents a list of Future\n */\n@kosModel(FutureContainerFactory.type)\nclass FutureContainerModel implements IFutureContainerModel {\n id: string;\n private logger: KosContextLogger;\n private _deleteFuture: (\n groupId: string\n ) => Promise<KosServiceResponse<unknown> | undefined>;\n private _addFuture: (\n future: FutureRequest\n ) => Promise<KosServiceResponse<any> | undefined>;\n\n @kosChild\n private _futures: IKosModelContainer<IFutureModel>;\n createModel: <T = void>(request: FutureRequest) => Promise<T>;\n deleteModel: (id: string) => Promise<void>;\n\n constructor(\n modelId: string,\n options: IFutureContainerModelOptions,\n context: KosCreationContext\n ) {\n const { deleteFuture = deleteFutureService, addFuture = addFutureService } =\n options;\n this.logger = context.logger;\n this._deleteFuture = deleteFuture;\n this._addFuture = addFuture;\n this.id = modelId;\n this._futures = new KosModelContainer();\n this.createModel = this.createFuture;\n this.deleteModel = this.removeFuture;\n }\n\n /**\n * @category Computed\n * @getter\n * Computed value that will recalculate automatically whenever Futures\n * are added or removed from the map.\n *\n * @returns the list of Futures\n *\n * @internal\n */\n get futures() {\n return this._futures.data;\n }\n\n get models() {\n return this.futures;\n }\n\n /**\n * Convenience function that will retrieve the IFutureModel based on\n * the id.\n *\n * @param futureId - the id of the future to be retrieved\n * @returns the `IFutureModel` or `undefined` if not available in the list\n * @internal\n */\n getFuture(futureId: string) {\n return this._futures.getModel(futureId);\n }\n\n /**\n * @category Action\n * Internally adds the provided Future to the map\n *\n * @param group - The Future model to add\n * @internal\n */\n addFutureModel(model: IFutureModel) {\n this._futures.addModel(model);\n }\n\n /**\n * @category Action\n * Internally adds the provided Future to the map\n *\n * @param group - The Future model to add\n * @internal\n */\n removeFutureModel(id: string) {\n this._futures.removeModel(id);\n }\n\n /**\n * This is the entry point which enables an this model to be “visited” by a visitor object.\n *\n * @remarks\n * Futures as part of a KOS Model Visitor pattern allowing clients\n * to traverse the KOS Model hierarchy and perform operations on elements\n * as they are \"visited\".\n *\n * Ths method serves as an entry point for visitors allowing them to dispatch\n * actions on elements in a collection without requiring the models to have\n * explicit knowledge of the operation being performed.\n *\n * @group KOS Model\n * @internal\n */\n\n /**\n * Gets the direct children of this Future collection.\n *\n * @remarks\n * Allows the KOS Model framework to operate off of a directed graph\n * and perform generic operations on collections of models by traversing\n * the hierarchy.\n *\n * This method will inform the framework of what child models exist in a containment\n * relationship.\n *\n * @returns - the collection of Future models maintained by this model.\n * @group KOS Model\n * @internal\n */\n\n // -------------------ACTIONS----------------------------\n /**\n * Removes a Future model from the collection.\n *\n * @remarks\n * If a remove service function was passed in as part of the options\n * in the constructor then it will be used. Otherwise the default\n * delete service will be invoked.\n *\n * @param id - the id of the Future to be removed\n *\n * @see deleteFutureService\n * @category Action\n * @internal\n */\n async removeFuture(id: string) {\n try {\n await this._deleteFuture(id);\n } catch (e) {\n log.error(`error deleting a Future`);\n log.error(e);\n }\n }\n /**\n * Adds a Future model into the collection.\n *\n * @remarks\n * If an add service function was passed in as part of the options\n * in the constructor then it will be used. Otherwise the default\n * add service will be invoked.\n *\n * @param model - the Future model to be added\n *\n * @see addFutureService\n * @category Action\n * @internal\n */\n async createFuture(model: FutureRequest) {\n try {\n const response = await this._addFuture(model);\n const data: FutureResponse | undefined = response?.data;\n if (data) {\n const model = buildFuture(FutureFactory)(data);\n this.addFutureModel(model);\n return model;\n }\n } catch (e) {\n log.error(`error creating a Future`);\n log.error(e);\n throw e;\n }\n return undefined;\n }\n\n // ------------------SUBSCRIPTIONS----------------------\n\n @kosTopicHandler({\n topic: \"kos.future\",\n })\n handleFutureUpdated(future: FutureResponse, payload: ApiCallback) {\n const newFutureModel = FutureManager.buildFutureModel(future);\n this.addFutureModel(newFutureModel);\n const topic = `kos.future/${future.tracker || future.id}`;\n this.logger.debug(`publishing future update to ${topic}`);\n EventBus.publish(topic, payload.body, payload.headers);\n }\n}\n\nexport default FutureContainerModel;\n","/**\n * @fileoverview Key-Value service functions for persistent data storage and retrieval.\n *\n * This module provides service functions for managing key-value pairs in KOS device storage.\n * Supports namespaced storage, CRUD operations, and typed value handling for configuration\n * data, user preferences, and application state persistence.\n *\n * @module KeyValueServices\n */\n\nimport { KosLog, ServiceFactory, resolveServiceUrl } from \"../../../../core\";\n\n/** Base URL for key-value service endpoints */\nconst { URL } = resolveServiceUrl(\"KEY_VALUE_SERVICE\");\n\n/** Pre-configured service methods for key-value operations */\nconst { getOne, postModel, deleteModel } = ServiceFactory.build({\n basePath: `${URL}/api/keyVal`,\n});\n\n/** Logger instance for key-value service operations */\nconst log = KosLog.createLogger({\n name: \"key-value-service\",\n group: \"Services\",\n});\n\n/**\n * Response format for key-value data retrieval.\n *\n * Represents the structure of data returned from key-value service endpoints,\n * supporting primitive types commonly used for configuration and state data.\n *\n * @group KOS Model\n * @category Key-Value Store\n */\ninterface KeyValueResponse {\n /** Key-value pairs with primitive values */\n [key: string]: string | number | boolean;\n}\n\n/**\n * Update request format for key-value operations.\n *\n * Defines the structure for updating individual key-value pairs within\n * specific namespaces, supporting targeted updates without affecting\n * other stored data.\n *\n * @group KOS Model\n * @category Key-Value Store\n */\nexport interface KeyValueUpdate {\n /** Namespace identifier for data organization */\n namespace: string;\n /** Specific key within the namespace */\n key: string;\n /** Value to store (as string for API compatibility) */\n value: string;\n}\n\n/**\n * Removes a specific key-value pair from storage.\n *\n * Permanently deletes a key and its associated value from the specified namespace.\n * This operation cannot be undone, so use with caution for critical data.\n *\n * @param namespace - Namespace containing the key to delete\n * @param key - Specific key to remove from storage\n *\n * @throws {Error} When deletion request fails or service is unavailable\n *\n * @example Delete User Preference\n * ```typescript\n * await deleteKeyValue('user-preferences', 'theme-mode');\n * console.log('Theme preference cleared');\n * ```\n *\n * @group KOS Model\n * @category Key-Value Store\n */\nexport const deleteKeyValue = async (namespace: string, key: string) => {\n await deleteModel({\n urlOverride: `${URL}/api/keyVal/${namespace}/${key}`,\n id: key,\n });\n};\n/**\n * Creates or updates a key-value pair in persistent storage.\n *\n * Stores a value under the specified key within the given namespace. If the key\n * already exists, its value will be overwritten. Supports primitive types with\n * automatic string conversion for API compatibility.\n *\n * @param namespace - Namespace for organizing related key-value pairs\n * @param key - Unique identifier within the namespace\n * @param value - Value to store (primitive types supported)\n * @returns Promise resolving to the stored value\n *\n * @throws {Error} When update request fails or service returns non-200 status\n *\n * @example Store Configuration Setting\n * ```typescript\n * await updateKeyValue('device-config', 'maxRetries', 5);\n * await updateKeyValue('user-prefs', 'darkMode', true);\n * await updateKeyValue('app-state', 'lastLogin', '2024-01-15');\n * ```\n *\n * @group KOS Model\n * @category Key-Value Store\n */\nexport const updateKeyValue = async (\n namespace: string,\n key: string,\n value: string | number | boolean\n) => {\n const response = await postModel<string>({\n urlOverride: `${URL}/api/keyVal/${namespace}/${key}`,\n model: value.toString(),\n });\n\n if (response?.status !== 200) {\n log.error(\"Failed to update key-value data\", response);\n throw new Error(\n `Failed to update key-value data for namespace ${namespace}`\n );\n }\n return response.data;\n};\n/**\n * Retrieves all key-value pairs from a specified namespace.\n *\n * Fetches all stored data within the given namespace as a complete object.\n * Useful for loading configuration sets, user preferences, or application\n * state data in bulk operations.\n *\n * @param namespace - Namespace to retrieve data from (defaults to \"studio\")\n * @returns Promise resolving to object containing all key-value pairs in namespace\n *\n * @throws {Error} When retrieval fails or service returns non-200 status\n *\n * @example Load Application Configuration\n * ```typescript\n * const appConfig = await getKeyValue('app-config');\n * console.log('Max retries:', appConfig.maxRetries);\n * console.log('Debug mode:', appConfig.debugMode);\n *\n * const userPrefs = await getKeyValue('user-preferences');\n * const theme = userPrefs.themeMode || 'light';\n * ```\n *\n * @group KOS Model\n * @category Key-Value Store\n */\nexport const getKeyValue = async (namespace = \"studio\") => {\n log.debug(`Retrieving all key-value data for namespace: ${namespace}`);\n const response = await getOne<KeyValueResponse>({\n urlOverride: `${URL}/api/keyVal/${namespace}`,\n });\n\n if (response?.status !== 200) {\n log.error(\"Failed to retrieve key-value data\", response);\n throw new Error(\n `Failed to retrieve key-value data for namespace ${namespace}`\n );\n }\n return response.data;\n};\n\n/**\n * Removes an entire namespace and all its key-value pairs.\n *\n * Permanently deletes all data within the specified namespace. This is a\n * destructive operation that cannot be undone. Use with extreme caution\n * for critical data or production systems.\n *\n * @param namespace - Namespace to completely remove from storage\n *\n * @throws {Error} When deletion request fails or service is unavailable\n *\n * @example Clear All User Preferences\n * ```typescript\n * // Warning: This removes ALL user preferences permanently\n * await deleteKeyValueNamespace('user-preferences');\n * console.log('All user preferences cleared');\n *\n * // Better: Clear specific preferences individually\n * await deleteKeyValue('user-preferences', 'theme-mode');\n * await deleteKeyValue('user-preferences', 'language');\n * ```\n *\n * @group KOS Model\n * @category Key-Value Store\n */\nexport const deleteKeyValueNamespace = async (namespace: string) => {\n await deleteModel({\n urlOverride: `${URL}/api/keyVal/${namespace}`,\n id: \"\",\n });\n};\n","import type {\n IKosDataModel,\n IKosIdentifiable,\n KosContextLogger,\n KosCreationContext,\n KosData,\n PublicModelInterface,\n} from \"../../../core\";\nimport { ObservableData, kosModel, kosTopicHandler } from \"../../../core\";\nimport {\n deleteKeyValue,\n getKeyValue,\n updateKeyValue,\n type KeyValueUpdate,\n} from \"./services\";\nimport type { KeyValueOptions } from \"./types\";\n\nexport const MODEL_TYPE = \"key-value-model\";\n\n/**\n * Key-Value Model - Persistent, reactive state storage with real-time synchronization across KOS applications.\n *\n * This model provides a namespaced key-value store that automatically persists data and synchronizes\n * changes across all connected clients in real-time. Perfect for storing user preferences, application\n * state, feature flags, or any data that needs to persist between sessions and sync across instances.\n *\n * ## Key Features\n * - **Persistent Storage** - Data survives application restarts and browser refreshes\n * - **Real-time Synchronization** - Changes propagate instantly to all connected clients\n * - **Namespace Isolation** - Multiple stores can coexist without key collisions\n * - **Type-Safe Values** - Supports string, number, boolean, and undefined types\n * - **Reactive Updates** - Automatic UI updates when values change (locally or remotely)\n * - **Topic-Based Sync** - Uses KOS event system for distributed state management\n *\n * ## Topic-Based Reactivity\n * The model listens to two KOS topics for real-time synchronization:\n * - **`/keyVal/set`** - Fired when any key-value pair is updated or added\n * - **`/keyVal/remove`** - Fired when a key is deleted from the store\n *\n * These topics ensure that all instances of the model with the same namespace stay\n * synchronized across browser tabs, windows, and even different client applications.\n * The model automatically filters events by namespace to ensure isolation.\n *\n * @interface\n *\n * @example Basic Usage\n * ```typescript\n * const preferences = KeyValue.instance('user-prefs')\n * .options({ namespace: 'preferences' })\n * .build();\n *\n * // Store values\n * await preferences.updateState('theme', 'dark');\n * await preferences.updateState('fontSize', 14);\n *\n * // Access reactive data\n * console.log(preferences.data.theme); // 'dark'\n * console.log(preferences.data.fontSize); // 14\n * ```\n *\n * @example React Integration\n * ```typescript\n * const UserSettings: React.FC = kosComponent(() => {\n * const settings = useModel(KeyValue, 'app-settings');\n *\n * return (\n * <div>\n * <p>Theme: {settings.data.theme || 'light'}</p>\n * <button onClick={() => settings.updateState('theme', 'dark')}>\n * Set Dark Theme\n * </button>\n * </div>\n * );\n * });\n * ```\n *\n * @group KOS Model\n * @category State Management\n * @category Key-Value Store\n * @useDeclaredType\n * @see {@link KeyValueOptions} - Configuration options for key-value stores\n * @see {@link KeyValueUpdate} - Update event structure for synchronization\n */\nexport type KeyValueModel = PublicModelInterface<KeyValueModelImpl>;\n\n/**\n * @ignore\n * @internal\n */\n@kosModel(MODEL_TYPE)\nexport class KeyValueModelImpl implements IKosDataModel, IKosIdentifiable {\n id: string;\n private logger: KosContextLogger;\n private namespace: string;\n data: KosData<Record<string, string | number | boolean | undefined>>;\n constructor(\n modelId: string,\n options: KeyValueOptions,\n context: KosCreationContext\n ) {\n this.id = modelId;\n this.logger = context.logger;\n this.data = ObservableData();\n this.namespace = options.namespace || \"studio\";\n }\n\n /**\n * @internal\n */\n async init(): Promise<void> {\n this.logger.debug(`initializing studio-state ${this.id}`);\n }\n\n /**\n * Update or delete a key-value pair in the store.\n *\n * Changes are automatically persisted and synchronized across all instances\n * with the same namespace via KOS topics.\n *\n * @param key - The key to update or delete\n * @param value - The value to set (string | number | boolean), or undefined to delete the key\n * @returns Promise that resolves when the operation completes\n *\n * @example\n * ```typescript\n * // Set a value\n * await keyValue.updateState('theme', 'dark');\n *\n * // Delete a key\n * await keyValue.updateState('theme', undefined);\n * ```\n */\n async updateState(\n key: string,\n value: string | number | boolean | undefined\n ): Promise<void> {\n this.logger.debug(`updating studio-state ${key} with value ${value}`);\n if (value !== undefined) {\n await updateKeyValue(this.namespace, key, value);\n this.data[key] = value;\n } else {\n await deleteKeyValue(this.namespace, key);\n this.data[key] = undefined;\n }\n }\n /**\n * Load initial data from persistent storage.\n *\n * @internal\n */\n async load(): Promise<void> {\n this.logger.debug(`loading studio-state ${this.id}`);\n const studioState = await getKeyValue(this.namespace);\n this.data.setValues(studioState);\n }\n\n /**\n * Topic handler for `/keyVal/set` events to sync updates across instances.\n *\n * Automatically called when any KeyValue model instance updates a value,\n * ensuring all instances with the same namespace stay synchronized.\n *\n * @param update - The key-value update event containing namespace, key, and new value\n */\n @kosTopicHandler({ topic: \"/keyVal/set\" })\n handleStateUpdate(update: KeyValueUpdate) {\n if (update.namespace !== this.namespace) {\n return;\n }\n this.data[update.key] = update.value;\n }\n\n /**\n * Topic handler for `/keyVal/remove` events to sync deletions across instances.\n *\n * Automatically called when any KeyValue model instance deletes a key,\n * ensuring all instances with the same namespace stay synchronized.\n *\n * @param update - The key-value update event containing namespace and deleted key\n */\n @kosTopicHandler({ topic: \"/keyVal/remove\" })\n handleStateDelete(update: KeyValueUpdate) {\n if (update.namespace !== this.namespace) {\n return;\n }\n this.data[update.key] = undefined;\n }\n}\n","import { KosModelRegistrationFactory } from \"../../../core\";\nimport type { KeyValueModel } from \"./key-value-model\";\nimport { KeyValueModelImpl, MODEL_TYPE } from \"./key-value-model\";\nimport type { KeyValueOptions } from \"./types\";\n\n/**\n * # KeyValue\n *\n * The registration bean includes convenience methods for creating and working with KeyValueModel instances.\n *\n * ## type\n * The type property is a string that identifies the model type.\n * The type is used to identify the model type in the model registry and to narrow down the model type in type predicates. It's most frequently\n * used when declaring dependencies on models.\n *\n * @example\n * ```typescript\n *\n * @kosDependency({modelType: KeyValue.type, id: \"studioStateId\"})\n * private studioStateModel: KeyValueModel;\n * ```\n *\n *\n * ## factory\n *\n * The factory method creates a factory function that can be used to create new KeyValueModel instances.\n *\n \n * As this is a singleton model, the factory function accepts the model options as its argument.\n *\n * If a model with the same model type already exists, the factory function will return the existing model. The options will be ignored\n * in this case and the existing model will be returned in its current state.\n *\n * @example\n * ```typescript\n * const model = KeyValue.factory({\n * // Add option data\n * });\n * ```\n \n\n *\n * ## predicate\n *\n * [Typescript type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) function that will identify and narrow down a model to a KeyValueModel.\n *\n * @example\n * ```typescript\n *\n * const model: IKosDataModel = ...; // some model\n *\n * if (KeyValue.predicate(model)) {\n * // if the function evaluates to true, the model is narrowed down to KeyValueModel\n * // and the compiler will know that the model has the KeyValueModel interface\n * model.updateAvailability(false);\n * }\n * ```\n *\n * ## registration\n *\n * The registration property is an object that can be used to simplify registration of the model with the model registry. The registration object\n * can be spread into the model registration and provides all of the required information to register the model implementation class against the model type.\n *\n *\n * @example\n *\n * In an application registration file you can declare the model registration as follows:\n *\n * **registration.ts**\n * ```typescript\n * import { KeyValue } from \"@kos-ui/project-models\";\n * import { KosModelRegistry } from \"@kosdev-code/kos-dispense-sdk\";\n *\n * import { initKosProvider } from \"@kosdev-code/kos-ui-sdk\";\n *\n * KosModelRegistry.dispense\n * .models()\n * .model(KeyValue);\n * ```\n *\n * ## registration.singleton\n \n * The studioState model is a singleton model. This means that each time the factory function is called , the same instance will be returned.\n * If the model does not yet exist, it will be created passing in the provided options to initialize it.\n *\n * Singleton models don't require an ID as they will use the model type as their ID to guarantee uniqueness throughout the system.\n \n * */\nexport const KeyValue = new KosModelRegistrationFactory<\n KeyValueModel,\n KeyValueOptions\n>({\n class: KeyValueModelImpl,\n type: MODEL_TYPE,\n});\n","var INUMBER = 'INUMBER';\nvar IOP1 = 'IOP1';\nvar IOP2 = 'IOP2';\nvar IOP3 = 'IOP3';\nvar IVAR = 'IVAR';\nvar IVARNAME = 'IVARNAME';\nvar IFUNCALL = 'IFUNCALL';\nvar IFUNDEF = 'IFUNDEF';\nvar IEXPR = 'IEXPR';\nvar IEXPREVAL = 'IEXPREVAL';\nvar IMEMBER = 'IMEMBER';\nvar IENDSTATEMENT = 'IENDSTATEMENT';\nvar IARRAY = 'IARRAY';\n\nfunction Instruction(type, value) {\n this.type = type;\n this.value = (value !== undefined && value !== null) ? value : 0;\n}\n\nInstruction.prototype.toString = function () {\n switch (this.type) {\n case INUMBER:\n case IOP1:\n case IOP2:\n case IOP3:\n case IVAR:\n case IVARNAME:\n case IENDSTATEMENT:\n return this.value;\n case IFUNCALL:\n return 'CALL ' + this.value;\n case IFUNDEF:\n return 'DEF ' + this.value;\n case IARRAY:\n return 'ARRAY ' + this.value;\n case IMEMBER:\n return '.' + this.value;\n default:\n return 'Invalid Instruction';\n }\n};\n\nfunction unaryInstruction(value) {\n return new Instruction(IOP1, value);\n}\n\nfunction binaryInstruction(value) {\n return new Instruction(IOP2, value);\n}\n\nfunction ternaryInstruction(value) {\n return new Instruction(IOP3, value);\n}\n\nfunction simplify(tokens, unaryOps, binaryOps, ternaryOps, values) {\n var nstack = [];\n var newexpression = [];\n var n1, n2, n3;\n var f;\n for (var i = 0; i < tokens.length; i++) {\n var item = tokens[i];\n var type = item.type;\n if (type === INUMBER || type === IVARNAME) {\n if (Array.isArray(item.value)) {\n nstack.push.apply(nstack, simplify(item.value.map(function (x) {\n return new Instruction(INUMBER, x);\n }).concat(new Instruction(IARRAY, item.value.length)), unaryOps, binaryOps, ternaryOps, values));\n } else {\n nstack.push(item);\n }\n } else if (type === IVAR && values.hasOwnProperty(item.value)) {\n item = new Instruction(INUMBER, values[item.value]);\n nstack.push(item);\n } else if (type === IOP2 && nstack.length > 1) {\n n2 = nstack.pop();\n n1 = nstack.pop();\n f = binaryOps[item.value];\n item = new Instruction(INUMBER, f(n1.value, n2.value));\n nstack.push(item);\n } else if (type === IOP3 && nstack.length > 2) {\n n3 = nstack.pop();\n n2 = nstack.pop();\n n1 = nstack.pop();\n if (item.value === '?') {\n nstack.push(n1.value ? n2.value : n3.value);\n } else {\n f = ternaryOps[item.value];\n item = new Instruction(INUMBER, f(n1.value, n2.value, n3.value));\n nstack.push(item);\n }\n } else if (type === IOP1 && nstack.length > 0) {\n n1 = nstack.pop();\n f = unaryOps[item.value];\n item = new Instruction(INUMBER, f(n1.value));\n nstack.push(item);\n } else if (type === IEXPR) {\n while (nstack.length > 0) {\n newexpression.push(nstack.shift());\n }\n newexpression.push(new Instruction(IEXPR, simplify(item.value, unaryOps, binaryOps, ternaryOps, values)));\n } else if (type === IMEMBER && nstack.length > 0) {\n n1 = nstack.pop();\n nstack.push(new Instruction(INUMBER, n1.value[item.value]));\n } /* else if (type === IARRAY && nstack.length >= item.value) {\n var length = item.value;\n while (length-- > 0) {\n newexpression.push(nstack.pop());\n }\n newexpression.push(new Instruction(IARRAY, item.value));\n } */ else {\n while (nstack.length > 0) {\n newexpression.push(nstack.shift());\n }\n newexpression.push(item);\n }\n }\n while (nstack.length > 0) {\n newexpression.push(nstack.shift());\n }\n return newexpression;\n}\n\nfunction substitute(tokens, variable, expr) {\n var newexpression = [];\n for (var i = 0; i < tokens.length; i++) {\n var item = tokens[i];\n var type = item.type;\n if (type === IVAR && item.value === variable) {\n for (var j = 0; j < expr.tokens.length; j++) {\n var expritem = expr.tokens[j];\n var replitem;\n if (expritem.type === IOP1) {\n replitem = unaryInstruction(expritem.value);\n } else if (expritem.type === IOP2) {\n replitem = binaryInstruction(expritem.value);\n } else if (expritem.type === IOP3) {\n replitem = ternaryInstruction(expritem.value);\n } else {\n replitem = new Instruction(expritem.type, expritem.value);\n }\n newexpression.push(replitem);\n }\n } else if (type === IEXPR) {\n newexpression.push(new Instruction(IEXPR, substitute(item.value, variable, expr)));\n } else {\n newexpression.push(item);\n }\n }\n return newexpression;\n}\n\nfunction evaluate(tokens, expr, values) {\n var nstack = [];\n var n1, n2, n3;\n var f, args, argCount;\n\n if (isExpressionEvaluator(tokens)) {\n return resolveExpression(tokens, values);\n }\n\n var numTokens = tokens.length;\n\n for (var i = 0; i < numTokens; i++) {\n var item = tokens[i];\n var type = item.type;\n if (type === INUMBER || type === IVARNAME) {\n nstack.push(item.value);\n } else if (type === IOP2) {\n n2 = nstack.pop();\n n1 = nstack.pop();\n if (item.value === 'and') {\n nstack.push(n1 ? !!evaluate(n2, expr, values) : false);\n } else if (item.value === 'or') {\n nstack.push(n1 ? true : !!evaluate(n2, expr, values));\n } else if (item.value === '=') {\n f = expr.binaryOps[item.value];\n nstack.push(f(n1, evaluate(n2, expr, values), values));\n } else {\n f = expr.binaryOps[item.value];\n nstack.push(f(resolveExpression(n1, values), resolveExpression(n2, values)));\n }\n } else if (type === IOP3) {\n n3 = nstack.pop();\n n2 = nstack.pop();\n n1 = nstack.pop();\n if (item.value === '?') {\n nstack.push(evaluate(n1 ? n2 : n3, expr, values));\n } else {\n f = expr.ternaryOps[item.value];\n nstack.push(f(resolveExpression(n1, values), resolveExpression(n2, values), resolveExpression(n3, values)));\n }\n } else if (type === IVAR) {\n if (item.value in expr.functions) {\n nstack.push(expr.functions[item.value]);\n } else if (item.value in expr.unaryOps && expr.parser.isOperatorEnabled(item.value)) {\n nstack.push(expr.unaryOps[item.value]);\n } else {\n var v = values[item.value];\n if (v !== undefined) {\n nstack.push(v);\n } else {\n throw new Error('undefined variable: ' + item.value);\n }\n }\n } else if (type === IOP1) {\n n1 = nstack.pop();\n f = expr.unaryOps[item.value];\n nstack.push(f(resolveExpression(n1, values)));\n } else if (type === IFUNCALL) {\n argCount = item.value;\n args = [];\n while (argCount-- > 0) {\n args.unshift(resolveExpression(nstack.pop(), values));\n }\n f = nstack.pop();\n if (f.apply && f.call) {\n nstack.push(f.apply(undefined, args));\n } else {\n throw new Error(f + ' is not a function');\n }\n } else if (type === IFUNDEF) {\n // Create closure to keep references to arguments and expression\n nstack.push((function () {\n var n2 = nstack.pop();\n var args = [];\n var argCount = item.value;\n while (argCount-- > 0) {\n args.unshift(nstack.pop());\n }\n var n1 = nstack.pop();\n var f = function () {\n var scope = Object.assign({}, values);\n for (var i = 0, len = args.length; i < len; i++) {\n scope[args[i]] = arguments[i];\n }\n return evaluate(n2, expr, scope);\n };\n // f.name = n1\n Object.defineProperty(f, 'name', {\n value: n1,\n writable: false\n });\n values[n1] = f;\n return f;\n })());\n } else if (type === IEXPR) {\n nstack.push(createExpressionEvaluator(item, expr));\n } else if (type === IEXPREVAL) {\n nstack.push(item);\n } else if (type === IMEMBER) {\n n1 = nstack.pop();\n nstack.push(n1[item.value]);\n } else if (type === IENDSTATEMENT) {\n nstack.pop();\n } else if (type === IARRAY) {\n argCount = item.value;\n args = [];\n while (argCount-- > 0) {\n args.unshift(nstack.pop());\n }\n nstack.push(args);\n } else {\n throw new Error('invalid Expression');\n }\n }\n if (nstack.length > 1) {\n throw new Error('invalid Expression (parity)');\n }\n // Explicitly return zero to avoid test issues caused by -0\n return nstack[0] === 0 ? 0 : resolveExpression(nstack[0], values);\n}\n\nfunction createExpressionEvaluator(token, expr, values) {\n if (isExpressionEvaluator(token)) return token;\n return {\n type: IEXPREVAL,\n value: function (scope) {\n return evaluate(token.value, expr, scope);\n }\n };\n}\n\nfunction isExpressionEvaluator(n) {\n return n && n.type === IEXPREVAL;\n}\n\nfunction resolveExpression(n, values) {\n return isExpressionEvaluator(n) ? n.value(values) : n;\n}\n\nfunction expressionToString(tokens, toJS) {\n var nstack = [];\n var n1, n2, n3;\n var f, args, argCount;\n for (var i = 0; i < tokens.length; i++) {\n var item = tokens[i];\n var type = item.type;\n if (type === INUMBER) {\n if (typeof item.value === 'number' && item.value < 0) {\n nstack.push('(' + item.value + ')');\n } else if (Array.isArray(item.value)) {\n nstack.push('[' + item.value.map(escapeValue).join(', ') + ']');\n } else {\n nstack.push(escapeValue(item.value));\n }\n } else if (type === IOP2) {\n n2 = nstack.pop();\n n1 = nstack.pop();\n f = item.value;\n if (toJS) {\n if (f === '^') {\n nstack.push('Math.pow(' + n1 + ', ' + n2 + ')');\n } else if (f === 'and') {\n nstack.push('(!!' + n1 + ' && !!' + n2 + ')');\n } else if (f === 'or') {\n nstack.push('(!!' + n1 + ' || !!' + n2 + ')');\n } else if (f === '||') {\n nstack.push('(function(a,b){ return Array.isArray(a) && Array.isArray(b) ? a.concat(b) : String(a) + String(b); }((' + n1 + '),(' + n2 + ')))');\n } else if (f === '==') {\n nstack.push('(' + n1 + ' === ' + n2 + ')');\n } else if (f === '!=') {\n nstack.push('(' + n1 + ' !== ' + n2 + ')');\n } else if (f === '[') {\n nstack.push(n1 + '[(' + n2 + ') | 0]');\n } else {\n nstack.push('(' + n1 + ' ' + f + ' ' + n2 + ')');\n }\n } else {\n if (f === '[') {\n nstack.push(n1 + '[' + n2 + ']');\n } else {\n nstack.push('(' + n1 + ' ' + f + ' ' + n2 + ')');\n }\n }\n } else if (type === IOP3) {\n n3 = nstack.pop();\n n2 = nstack.pop();\n n1 = nstack.pop();\n f = item.value;\n if (f === '?') {\n nstack.push('(' + n1 + ' ? ' + n2 + ' : ' + n3 + ')');\n } else {\n throw new Error('invalid Expression');\n }\n } else if (type === IVAR || type === IVARNAME) {\n nstack.push(item.value);\n } else if (type === IOP1) {\n n1 = nstack.pop();\n f = item.value;\n if (f === '-' || f === '+') {\n nstack.push('(' + f + n1 + ')');\n } else if (toJS) {\n if (f === 'not') {\n nstack.push('(' + '!' + n1 + ')');\n } else if (f === '!') {\n nstack.push('fac(' + n1 + ')');\n } else {\n nstack.push(f + '(' + n1 + ')');\n }\n } else if (f === '!') {\n nstack.push('(' + n1 + '!)');\n } else {\n nstack.push('(' + f + ' ' + n1 + ')');\n }\n } else if (type === IFUNCALL) {\n argCount = item.value;\n args = [];\n while (argCount-- > 0) {\n args.unshift(nstack.pop());\n }\n f = nstack.pop();\n nstack.push(f + '(' + args.join(', ') + ')');\n } else if (type === IFUNDEF) {\n n2 = nstack.pop();\n argCount = item.value;\n args = [];\n while (argCount-- > 0) {\n args.unshift(nstack.pop());\n }\n n1 = nstack.pop();\n if (toJS) {\n nstack.push('(' + n1 + ' = function(' + args.join(', ') + ') { return ' + n2 + ' })');\n } else {\n nstack.push('(' + n1 + '(' + args.join(', ') + ') = ' + n2 + ')');\n }\n } else if (type === IMEMBER) {\n n1 = nstack.pop();\n nstack.push(n1 + '.' + item.value);\n } else if (type === IARRAY) {\n argCount = item.value;\n args = [];\n while (argCount-- > 0) {\n args.unshift(nstack.pop());\n }\n nstack.push('[' + args.join(', ') + ']');\n } else if (type === IEXPR) {\n nstack.push('(' + expressionToString(item.value, toJS) + ')');\n } else if (type === IENDSTATEMENT) ; else {\n throw new Error('invalid Expression');\n }\n }\n if (nstack.length > 1) {\n if (toJS) {\n nstack = [ nstack.join(',') ];\n } else {\n nstack = [ nstack.join(';') ];\n }\n }\n return String(nstack[0]);\n}\n\nfunction escapeValue(v) {\n if (typeof v === 'string') {\n return JSON.stringify(v).replace(/\\u2028/g, '\\\\u2028').replace(/\\u2029/g, '\\\\u2029');\n }\n return v;\n}\n\nfunction contains(array, obj) {\n for (var i = 0; i < array.length; i++) {\n if (array[i] === obj) {\n return true;\n }\n }\n return false;\n}\n\nfunction getSymbols(tokens, symbols, options) {\n options = options || {};\n var withMembers = !!options.withMembers;\n var prevVar = null;\n\n for (var i = 0; i < tokens.length; i++) {\n var item = tokens[i];\n if (item.type === IVAR || item.type === IVARNAME) {\n if (!withMembers && !contains(symbols, item.value)) {\n symbols.push(item.value);\n } else if (prevVar !== null) {\n if (!contains(symbols, prevVar)) {\n symbols.push(prevVar);\n }\n prevVar = item.value;\n } else {\n prevVar = item.value;\n }\n } else if (item.type === IMEMBER && withMembers && prevVar !== null) {\n prevVar += '.' + item.value;\n } else if (item.type === IEXPR) {\n getSymbols(item.value, symbols, options);\n } else if (prevVar !== null) {\n if (!contains(symbols, prevVar)) {\n symbols.push(prevVar);\n }\n prevVar = null;\n }\n }\n\n if (prevVar !== null && !contains(symbols, prevVar)) {\n symbols.push(prevVar);\n }\n}\n\nfunction Expression(tokens, parser) {\n this.tokens = tokens;\n this.parser = parser;\n this.unaryOps = parser.unaryOps;\n this.binaryOps = parser.binaryOps;\n this.ternaryOps = parser.ternaryOps;\n this.functions = parser.functions;\n}\n\nExpression.prototype.simplify = function (values) {\n values = values || {};\n return new Expression(simplify(this.tokens, this.unaryOps, this.binaryOps, this.ternaryOps, values), this.parser);\n};\n\nExpression.prototype.substitute = function (variable, expr) {\n if (!(expr instanceof Expression)) {\n expr = this.parser.parse(String(expr));\n }\n\n return new Expression(substitute(this.tokens, variable, expr), this.parser);\n};\n\nExpression.prototype.evaluate = function (values) {\n values = values || {};\n return evaluate(this.tokens, this, values);\n};\n\nExpression.prototype.toString = function () {\n return expressionToString(this.tokens, false);\n};\n\nExpression.prototype.symbols = function (options) {\n options = options || {};\n var vars = [];\n getSymbols(this.tokens, vars, options);\n return vars;\n};\n\nExpression.prototype.variables = function (options) {\n options = options || {};\n var vars = [];\n getSymbols(this.tokens, vars, options);\n var functions = this.functions;\n return vars.filter(function (name) {\n return !(name in functions);\n });\n};\n\nExpression.prototype.toJSFunction = function (param, variables) {\n var expr = this;\n var f = new Function(param, 'with(this.functions) with (this.ternaryOps) with (this.binaryOps) with (this.unaryOps) { return ' + expressionToString(this.simplify(variables).tokens, true) + '; }'); // eslint-disable-line no-new-func\n return function () {\n return f.apply(expr, arguments);\n };\n};\n\nvar TEOF = 'TEOF';\nvar TOP = 'TOP';\nvar TNUMBER = 'TNUMBER';\nvar TSTRING = 'TSTRING';\nvar TPAREN = 'TPAREN';\nvar TBRACKET = 'TBRACKET';\nvar TCOMMA = 'TCOMMA';\nvar TNAME = 'TNAME';\nvar TSEMICOLON = 'TSEMICOLON';\n\nfunction Token(type, value, index) {\n this.type = type;\n this.value = value;\n this.index = index;\n}\n\nToken.prototype.toString = function () {\n return this.type + ': ' + this.value;\n};\n\nfunction TokenStream(parser, expression) {\n this.pos = 0;\n this.current = null;\n this.unaryOps = parser.unaryOps;\n this.binaryOps = parser.binaryOps;\n this.ternaryOps = parser.ternaryOps;\n this.consts = parser.consts;\n this.expression = expression;\n this.savedPosition = 0;\n this.savedCurrent = null;\n this.options = parser.options;\n this.parser = parser;\n}\n\nTokenStream.prototype.newToken = function (type, value, pos) {\n return new Token(type, value, pos != null ? pos : this.pos);\n};\n\nTokenStream.prototype.save = function () {\n this.savedPosition = this.pos;\n this.savedCurrent = this.current;\n};\n\nTokenStream.prototype.restore = function () {\n this.pos = this.savedPosition;\n this.current = this.savedCurrent;\n};\n\nTokenStream.prototype.next = function () {\n if (this.pos >= this.expression.length) {\n return this.newToken(TEOF, 'EOF');\n }\n\n if (this.isWhitespace() || this.isComment()) {\n return this.next();\n } else if (this.isRadixInteger() ||\n this.isNumber() ||\n this.isOperator() ||\n this.isString() ||\n this.isParen() ||\n this.isBracket() ||\n this.isComma() ||\n this.isSemicolon() ||\n this.isNamedOp() ||\n this.isConst() ||\n this.isName()) {\n return this.current;\n } else {\n this.parseError('Unknown character \"' + this.expression.charAt(this.pos) + '\"');\n }\n};\n\nTokenStream.prototype.isString = function () {\n var r = false;\n var startPos = this.pos;\n var quote = this.expression.charAt(startPos);\n\n if (quote === '\\'' || quote === '\"') {\n var index = this.expression.indexOf(quote, startPos + 1);\n while (index >= 0 && this.pos < this.expression.length) {\n this.pos = index + 1;\n if (this.expression.charAt(index - 1) !== '\\\\') {\n var rawString = this.expression.substring(startPos + 1, index);\n this.current = this.newToken(TSTRING, this.unescape(rawString), startPos);\n r = true;\n break;\n }\n index = this.expression.indexOf(quote, index + 1);\n }\n }\n return r;\n};\n\nTokenStream.prototype.isParen = function () {\n var c = this.expression.charAt(this.pos);\n if (c === '(' || c === ')') {\n this.current = this.newToken(TPAREN, c);\n this.pos++;\n return true;\n }\n return false;\n};\n\nTokenStream.prototype.isBracket = function () {\n var c = this.expression.charAt(this.pos);\n if ((c === '[' || c === ']') && this.isOperatorEnabled('[')) {\n this.current = this.newToken(TBRACKET, c);\n this.pos++;\n return true;\n }\n return false;\n};\n\nTokenStream.prototype.isComma = function () {\n var c = this.expression.charAt(this.pos);\n if (c === ',') {\n this.current = this.newToken(TCOMMA, ',');\n this.pos++;\n return true;\n }\n return false;\n};\n\nTokenStream.prototype.isSemicolon = function () {\n var c = this.expression.charAt(this.pos);\n if (c === ';') {\n this.current = this.newToken(TSEMICOLON, ';');\n this.pos++;\n return true;\n }\n return false;\n};\n\nTokenStream.prototype.isConst = function () {\n var startPos = this.pos;\n var i = startPos;\n for (; i < this.expression.length; i++) {\n var c = this.expression.charAt(i);\n if (c.toUpperCase() === c.toLowerCase()) {\n if (i === this.pos || (c !== '_' && c !== '.' && (c < '0' || c > '9'))) {\n break;\n }\n }\n }\n if (i > startPos) {\n var str = this.expression.substring(startPos, i);\n if (str in this.consts) {\n this.current = this.newToken(TNUMBER, this.consts[str]);\n this.pos += str.length;\n return true;\n }\n }\n return false;\n};\n\nTokenStream.prototype.isNamedOp = function () {\n var startPos = this.pos;\n var i = startPos;\n for (; i < this.expression.length; i++) {\n var c = this.expression.charAt(i);\n if (c.toUpperCase() === c.toLowerCase()) {\n if (i === this.pos || (c !== '_' && (c < '0' || c > '9'))) {\n break;\n }\n }\n }\n if (i > startPos) {\n var str = this.expression.substring(startPos, i);\n if (this.isOperatorEnabled(str) && (str in this.binaryOps || str in this.unaryOps || str in this.ternaryOps)) {\n this.current = this.newToken(TOP, str);\n this.pos += str.length;\n return true;\n }\n }\n return false;\n};\n\nTokenStream.prototype.isName = function () {\n var startPos = this.pos;\n var i = startPos;\n var hasLetter = false;\n for (; i < this.expression.length; i++) {\n var c = this.expression.charAt(i);\n if (c.toUpperCase() === c.toLowerCase()) {\n if (i === this.pos && (c === '$' || c === '_')) {\n if (c === '_') {\n hasLetter = true;\n }\n continue;\n } else if (i === this.pos || !hasLetter || (c !== '_' && (c < '0' || c > '9'))) {\n break;\n }\n } else {\n hasLetter = true;\n }\n }\n if (hasLetter) {\n var str = this.expression.substring(startPos, i);\n this.current = this.newToken(TNAME, str);\n this.pos += str.length;\n return true;\n }\n return false;\n};\n\nTokenStream.prototype.isWhitespace = function () {\n var r = false;\n var c = this.expression.charAt(this.pos);\n while (c === ' ' || c === '\\t' || c === '\\n' || c === '\\r') {\n r = true;\n this.pos++;\n if (this.pos >= this.expression.length) {\n break;\n }\n c = this.expression.charAt(this.pos);\n }\n return r;\n};\n\nvar codePointPattern = /^[0-9a-f]{4}$/i;\n\nTokenStream.prototype.unescape = function (v) {\n var index = v.indexOf('\\\\');\n if (index < 0) {\n return v;\n }\n\n var buffer = v.substring(0, index);\n while (index >= 0) {\n var c = v.charAt(++index);\n switch (c) {\n case '\\'':\n buffer += '\\'';\n break;\n case '\"':\n buffer += '\"';\n break;\n case '\\\\':\n buffer += '\\\\';\n break;\n case '/':\n buffer += '/';\n break;\n case 'b':\n buffer += '\\b';\n break;\n case 'f':\n buffer += '\\f';\n break;\n case 'n':\n buffer += '\\n';\n break;\n case 'r':\n buffer += '\\r';\n break;\n case 't':\n buffer += '\\t';\n break;\n case 'u':\n // interpret the following 4 characters as the hex of the unicode code point\n var codePoint = v.substring(index + 1, index + 5);\n if (!codePointPattern.test(codePoint)) {\n this.parseError('Illegal escape sequence: \\\\u' + codePoint);\n }\n buffer += String.fromCharCode(parseInt(codePoint, 16));\n index += 4;\n break;\n default:\n throw this.parseError('Illegal escape sequence: \"\\\\' + c + '\"');\n }\n ++index;\n var backslash = v.indexOf('\\\\', index);\n buffer += v.substring(index, backslash < 0 ? v.length : backslash);\n index = backslash;\n }\n\n return buffer;\n};\n\nTokenStream.prototype.isComment = function () {\n var c = this.expression.charAt(this.pos);\n if (c === '/' && this.expression.charAt(this.pos + 1) === '*') {\n this.pos = this.expression.indexOf('*/', this.pos) + 2;\n if (this.pos === 1) {\n this.pos = this.expression.length;\n }\n return true;\n }\n return false;\n};\n\nTokenStream.prototype.isRadixInteger = function () {\n var pos = this.pos;\n\n if (pos >= this.expression.length - 2 || this.expression.charAt(pos) !== '0') {\n return false;\n }\n ++pos;\n\n var radix;\n var validDigit;\n if (this.expression.charAt(pos) === 'x') {\n radix = 16;\n validDigit = /^[0-9a-f]$/i;\n ++pos;\n } else if (this.expression.charAt(pos) === 'b') {\n radix = 2;\n validDigit = /^[01]$/i;\n ++pos;\n } else {\n return false;\n }\n\n var valid = false;\n var startPos = pos;\n\n while (pos < this.expression.length) {\n var c = this.expression.charAt(pos);\n if (validDigit.test(c)) {\n pos++;\n valid = true;\n } else {\n break;\n }\n }\n\n if (valid) {\n this.current = this.newToken(TNUMBER, parseInt(this.expression.substring(startPos, pos), radix));\n this.pos = pos;\n }\n return valid;\n};\n\nTokenStream.prototype.isNumber = function () {\n var valid = false;\n var pos = this.pos;\n var startPos = pos;\n var resetPos = pos;\n var foundDot = false;\n var foundDigits = false;\n var c;\n\n while (pos < this.expression.length) {\n c = this.expression.charAt(pos);\n if ((c >= '0' && c <= '9') || (!foundDot && c === '.')) {\n if (c === '.') {\n foundDot = true;\n } else {\n foundDigits = true;\n }\n pos++;\n valid = foundDigits;\n } else {\n break;\n }\n }\n\n if (valid) {\n resetPos = pos;\n }\n\n if (c === 'e' || c === 'E') {\n pos++;\n var acceptSign = true;\n var validExponent = false;\n while (pos < this.expression.length) {\n c = this.expression.charAt(pos);\n if (acceptSign && (c === '+' || c === '-')) {\n acceptSign = false;\n } else if (c >= '0' && c <= '9') {\n validExponent = true;\n acceptSign = false;\n } else {\n break;\n }\n pos++;\n }\n\n if (!validExponent) {\n pos = resetPos;\n }\n }\n\n if (valid) {\n this.current = this.newToken(TNUMBER, parseFloat(this.expression.substring(startPos, pos)));\n this.pos = pos;\n } else {\n this.pos = resetPos;\n }\n return valid;\n};\n\nTokenStream.prototype.isOperator = function () {\n var startPos = this.pos;\n var c = this.expression.charAt(this.pos);\n\n if (c === '+' || c === '-' || c === '*' || c === '/' || c === '%' || c === '^' || c === '?' || c === ':' || c === '.') {\n this.current = this.newToken(TOP, c);\n } else if (c === '∙' || c === '•') {\n this.current = this.newToken(TOP, '*');\n } else if (c === '>') {\n if (this.expression.charAt(this.pos + 1) === '=') {\n this.current = this.newToken(TOP, '>=');\n this.pos++;\n } else {\n this.current = this.newToken(TOP, '>');\n }\n } else if (c === '<') {\n if (this.expression.charAt(this.pos + 1) === '=') {\n this.current = this.newToken(TOP, '<=');\n this.pos++;\n } else {\n this.current = this.newToken(TOP, '<');\n }\n } else if (c === '|') {\n if (this.expression.charAt(this.pos + 1) === '|') {\n this.current = this.newToken(TOP, '||');\n this.pos++;\n } else {\n return false;\n }\n } else if (c === '=') {\n if (this.expression.charAt(this.pos + 1) === '=') {\n this.current = this.newToken(TOP, '==');\n this.pos++;\n } else {\n this.current = this.newToken(TOP, c);\n }\n } else if (c === '!') {\n if (this.expression.charAt(this.pos + 1) === '=') {\n this.current = this.newToken(TOP, '!=');\n this.pos++;\n } else {\n this.current = this.newToken(TOP, c);\n }\n } else {\n return false;\n }\n this.pos++;\n\n if (this.isOperatorEnabled(this.current.value)) {\n return true;\n } else {\n this.pos = startPos;\n return false;\n }\n};\n\nTokenStream.prototype.isOperatorEnabled = function (op) {\n return this.parser.isOperatorEnabled(op);\n};\n\nTokenStream.prototype.getCoordinates = function () {\n var line = 0;\n var column;\n var newline = -1;\n do {\n line++;\n column = this.pos - newline;\n newline = this.expression.indexOf('\\n', newline + 1);\n } while (newline >= 0 && newline < this.pos);\n\n return {\n line: line,\n column: column\n };\n};\n\nTokenStream.prototype.parseError = function (msg) {\n var coords = this.getCoordinates();\n throw new Error('parse error [' + coords.line + ':' + coords.column + ']: ' + msg);\n};\n\nfunction ParserState(parser, tokenStream, options) {\n this.parser = parser;\n this.tokens = tokenStream;\n this.current = null;\n this.nextToken = null;\n this.next();\n this.savedCurrent = null;\n this.savedNextToken = null;\n this.allowMemberAccess = options.allowMemberAccess !== false;\n}\n\nParserState.prototype.next = function () {\n this.current = this.nextToken;\n return (this.nextToken = this.tokens.next());\n};\n\nParserState.prototype.tokenMatches = function (token, value) {\n if (typeof value === 'undefined') {\n return true;\n } else if (Array.isArray(value)) {\n return contains(value, token.value);\n } else if (typeof value === 'function') {\n return value(token);\n } else {\n return token.value === value;\n }\n};\n\nParserState.prototype.save = function () {\n this.savedCurrent = this.current;\n this.savedNextToken = this.nextToken;\n this.tokens.save();\n};\n\nParserState.prototype.restore = function () {\n this.tokens.restore();\n this.current = this.savedCurrent;\n this.nextToken = this.savedNextToken;\n};\n\nParserState.prototype.accept = function (type, value) {\n if (this.nextToken.type === type && this.tokenMatches(this.nextToken, value)) {\n this.next();\n return true;\n }\n return false;\n};\n\nParserState.prototype.expect = function (type, value) {\n if (!this.accept(type, value)) {\n var coords = this.tokens.getCoordinates();\n throw new Error('parse error [' + coords.line + ':' + coords.column + ']: Expected ' + (value || type));\n }\n};\n\nParserState.prototype.parseAtom = function (instr) {\n var unaryOps = this.tokens.unaryOps;\n function isPrefixOperator(token) {\n return token.value in unaryOps;\n }\n\n if (this.accept(TNAME) || this.accept(TOP, isPrefixOperator)) {\n instr.push(new Instruction(IVAR, this.current.value));\n } else if (this.accept(TNUMBER)) {\n instr.push(new Instruction(INUMBER, this.current.value));\n } else if (this.accept(TSTRING)) {\n instr.push(new Instruction(INUMBER, this.current.value));\n } else if (this.accept(TPAREN, '(')) {\n this.parseExpression(instr);\n this.expect(TPAREN, ')');\n } else if (this.accept(TBRACKET, '[')) {\n if (this.accept(TBRACKET, ']')) {\n instr.push(new Instruction(IARRAY, 0));\n } else {\n var argCount = this.parseArrayList(instr);\n instr.push(new Instruction(IARRAY, argCount));\n }\n } else {\n throw new Error('unexpected ' + this.nextToken);\n }\n};\n\nParserState.prototype.parseExpression = function (instr) {\n var exprInstr = [];\n if (this.parseUntilEndStatement(instr, exprInstr)) {\n return;\n }\n this.parseVariableAssignmentExpression(exprInstr);\n if (this.parseUntilEndStatement(instr, exprInstr)) {\n return;\n }\n this.pushExpression(instr, exprInstr);\n};\n\nParserState.prototype.pushExpression = function (instr, exprInstr) {\n for (var i = 0, len = exprInstr.length; i < len; i++) {\n instr.push(exprInstr[i]);\n }\n};\n\nParserState.prototype.parseUntilEndStatement = function (instr, exprInstr) {\n if (!this.accept(TSEMICOLON)) return false;\n if (this.nextToken && this.nextToken.type !== TEOF && !(this.nextToken.type === TPAREN && this.nextToken.value === ')')) {\n exprInstr.push(new Instruction(IENDSTATEMENT));\n }\n if (this.nextToken.type !== TEOF) {\n this.parseExpression(exprInstr);\n }\n instr.push(new Instruction(IEXPR, exprInstr));\n return true;\n};\n\nParserState.prototype.parseArrayList = function (instr) {\n var argCount = 0;\n\n while (!this.accept(TBRACKET, ']')) {\n this.parseExpression(instr);\n ++argCount;\n while (this.accept(TCOMMA)) {\n this.parseExpression(instr);\n ++argCount;\n }\n }\n\n return argCount;\n};\n\nParserState.prototype.parseVariableAssignmentExpression = function (instr) {\n this.parseConditionalExpression(instr);\n while (this.accept(TOP, '=')) {\n var varName = instr.pop();\n var varValue = [];\n var lastInstrIndex = instr.length - 1;\n if (varName.type === IFUNCALL) {\n if (!this.tokens.isOperatorEnabled('()=')) {\n throw new Error('function definition is not permitted');\n }\n for (var i = 0, len = varName.value + 1; i < len; i++) {\n var index = lastInstrIndex - i;\n if (instr[index].type === IVAR) {\n instr[index] = new Instruction(IVARNAME, instr[index].value);\n }\n }\n this.parseVariableAssignmentExpression(varValue);\n instr.push(new Instruction(IEXPR, varValue));\n instr.push(new Instruction(IFUNDEF, varName.value));\n continue;\n }\n if (varName.type !== IVAR && varName.type !== IMEMBER) {\n throw new Error('expected variable for assignment');\n }\n this.parseVariableAssignmentExpression(varValue);\n instr.push(new Instruction(IVARNAME, varName.value));\n instr.push(new Instruction(IEXPR, varValue));\n instr.push(binaryInstruction('='));\n }\n};\n\nParserState.prototype.parseConditionalExpression = function (instr) {\n this.parseOrExpression(instr);\n while (this.accept(TOP, '?')) {\n var trueBranch = [];\n var falseBranch = [];\n this.parseConditionalExpression(trueBranch);\n this.expect(TOP, ':');\n this.parseConditionalExpression(falseBranch);\n instr.push(new Instruction(IEXPR, trueBranch));\n instr.push(new Instruction(IEXPR, falseBranch));\n instr.push(ternaryInstruction('?'));\n }\n};\n\nParserState.prototype.parseOrExpression = function (instr) {\n this.parseAndExpression(instr);\n while (this.accept(TOP, 'or')) {\n var falseBranch = [];\n this.parseAndExpression(falseBranch);\n instr.push(new Instruction(IEXPR, falseBranch));\n instr.push(binaryInstruction('or'));\n }\n};\n\nParserState.prototype.parseAndExpression = function (instr) {\n this.parseComparison(instr);\n while (this.accept(TOP, 'and')) {\n var trueBranch = [];\n this.parseComparison(trueBranch);\n instr.push(new Instruction(IEXPR, trueBranch));\n instr.push(binaryInstruction('and'));\n }\n};\n\nvar COMPARISON_OPERATORS = ['==', '!=', '<', '<=', '>=', '>', 'in'];\n\nParserState.prototype.parseComparison = function (instr) {\n this.parseAddSub(instr);\n while (this.accept(TOP, COMPARISON_OPERATORS)) {\n var op = this.current;\n this.parseAddSub(instr);\n instr.push(binaryInstruction(op.value));\n }\n};\n\nvar ADD_SUB_OPERATORS = ['+', '-', '||'];\n\nParserState.prototype.parseAddSub = function (instr) {\n this.parseTerm(instr);\n while (this.accept(TOP, ADD_SUB_OPERATORS)) {\n var op = this.current;\n this.parseTerm(instr);\n instr.push(binaryInstruction(op.value));\n }\n};\n\nvar TERM_OPERATORS = ['*', '/', '%'];\n\nParserState.prototype.parseTerm = function (instr) {\n this.parseFactor(instr);\n while (this.accept(TOP, TERM_OPERATORS)) {\n var op = this.current;\n this.parseFactor(instr);\n instr.push(binaryInstruction(op.value));\n }\n};\n\nParserState.prototype.parseFactor = function (instr) {\n var unaryOps = this.tokens.unaryOps;\n function isPrefixOperator(token) {\n return token.value in unaryOps;\n }\n\n this.save();\n if (this.accept(TOP, isPrefixOperator)) {\n if (this.current.value !== '-' && this.current.value !== '+') {\n if (this.nextToken.type === TPAREN && this.nextToken.value === '(') {\n this.restore();\n this.parseExponential(instr);\n return;\n } else if (this.nextToken.type === TSEMICOLON || this.nextToken.type === TCOMMA || this.nextToken.type === TEOF || (this.nextToken.type === TPAREN && this.nextToken.value === ')')) {\n this.restore();\n this.parseAtom(instr);\n return;\n }\n }\n\n var op = this.current;\n this.parseFactor(instr);\n instr.push(unaryInstruction(op.value));\n } else {\n this.parseExponential(instr);\n }\n};\n\nParserState.prototype.parseExponential = function (instr) {\n this.parsePostfixExpression(instr);\n while (this.accept(TOP, '^')) {\n this.parseFactor(instr);\n instr.push(binaryInstruction('^'));\n }\n};\n\nParserState.prototype.parsePostfixExpression = function (instr) {\n this.parseFunctionCall(instr);\n while (this.accept(TOP, '!')) {\n instr.push(unaryInstruction('!'));\n }\n};\n\nParserState.prototype.parseFunctionCall = function (instr) {\n var unaryOps = this.tokens.unaryOps;\n function isPrefixOperator(token) {\n return token.value in unaryOps;\n }\n\n if (this.accept(TOP, isPrefixOperator)) {\n var op = this.current;\n this.parseAtom(instr);\n instr.push(unaryInstruction(op.value));\n } else {\n this.parseMemberExpression(instr);\n while (this.accept(TPAREN, '(')) {\n if (this.accept(TPAREN, ')')) {\n instr.push(new Instruction(IFUNCALL, 0));\n } else {\n var argCount = this.parseArgumentList(instr);\n instr.push(new Instruction(IFUNCALL, argCount));\n }\n }\n }\n};\n\nParserState.prototype.parseArgumentList = function (instr) {\n var argCount = 0;\n\n while (!this.accept(TPAREN, ')')) {\n this.parseExpression(instr);\n ++argCount;\n while (this.accept(TCOMMA)) {\n this.parseExpression(instr);\n ++argCount;\n }\n }\n\n return argCount;\n};\n\nParserState.prototype.parseMemberExpression = function (instr) {\n this.parseAtom(instr);\n while (this.accept(TOP, '.') || this.accept(TBRACKET, '[')) {\n var op = this.current;\n\n if (op.value === '.') {\n if (!this.allowMemberAccess) {\n throw new Error('unexpected \".\", member access is not permitted');\n }\n\n this.expect(TNAME);\n instr.push(new Instruction(IMEMBER, this.current.value));\n } else if (op.value === '[') {\n if (!this.tokens.isOperatorEnabled('[')) {\n throw new Error('unexpected \"[]\", arrays are disabled');\n }\n\n this.parseExpression(instr);\n this.expect(TBRACKET, ']');\n instr.push(binaryInstruction('['));\n } else {\n throw new Error('unexpected symbol: ' + op.value);\n }\n }\n};\n\nfunction add(a, b) {\n return Number(a) + Number(b);\n}\n\nfunction sub(a, b) {\n return a - b;\n}\n\nfunction mul(a, b) {\n return a * b;\n}\n\nfunction div(a, b) {\n return a / b;\n}\n\nfunction mod(a, b) {\n return a % b;\n}\n\nfunction concat(a, b) {\n if (Array.isArray(a) && Array.isArray(b)) {\n return a.concat(b);\n }\n return '' + a + b;\n}\n\nfunction equal(a, b) {\n return a === b;\n}\n\nfunction notEqual(a, b) {\n return a !== b;\n}\n\nfunction greaterThan(a, b) {\n return a > b;\n}\n\nfunction lessThan(a, b) {\n return a < b;\n}\n\nfunction greaterThanEqual(a, b) {\n return a >= b;\n}\n\nfunction lessThanEqual(a, b) {\n return a <= b;\n}\n\nfunction andOperator(a, b) {\n return Boolean(a && b);\n}\n\nfunction orOperator(a, b) {\n return Boolean(a || b);\n}\n\nfunction inOperator(a, b) {\n return contains(b, a);\n}\n\nfunction sinh(a) {\n return ((Math.exp(a) - Math.exp(-a)) / 2);\n}\n\nfunction cosh(a) {\n return ((Math.exp(a) + Math.exp(-a)) / 2);\n}\n\nfunction tanh(a) {\n if (a === Infinity) return 1;\n if (a === -Infinity) return -1;\n return (Math.exp(a) - Math.exp(-a)) / (Math.exp(a) + Math.exp(-a));\n}\n\nfunction asinh(a) {\n if (a === -Infinity) return a;\n return Math.log(a + Math.sqrt((a * a) + 1));\n}\n\nfunction acosh(a) {\n return Math.log(a + Math.sqrt((a * a) - 1));\n}\n\nfunction atanh(a) {\n return (Math.log((1 + a) / (1 - a)) / 2);\n}\n\nfunction log10(a) {\n return Math.log(a) * Math.LOG10E;\n}\n\nfunction neg(a) {\n return -a;\n}\n\nfunction not(a) {\n return !a;\n}\n\nfunction trunc(a) {\n return a < 0 ? Math.ceil(a) : Math.floor(a);\n}\n\nfunction random(a) {\n return Math.random() * (a || 1);\n}\n\nfunction factorial(a) { // a!\n return gamma(a + 1);\n}\n\nfunction isInteger(value) {\n return isFinite(value) && (value === Math.round(value));\n}\n\nvar GAMMA_G = 4.7421875;\nvar GAMMA_P = [\n 0.99999999999999709182,\n 57.156235665862923517, -59.597960355475491248,\n 14.136097974741747174, -0.49191381609762019978,\n 0.33994649984811888699e-4,\n 0.46523628927048575665e-4, -0.98374475304879564677e-4,\n 0.15808870322491248884e-3, -0.21026444172410488319e-3,\n 0.21743961811521264320e-3, -0.16431810653676389022e-3,\n 0.84418223983852743293e-4, -0.26190838401581408670e-4,\n 0.36899182659531622704e-5\n];\n\n// Gamma function from math.js\nfunction gamma(n) {\n var t, x;\n\n if (isInteger(n)) {\n if (n <= 0) {\n return isFinite(n) ? Infinity : NaN;\n }\n\n if (n > 171) {\n return Infinity; // Will overflow\n }\n\n var value = n - 2;\n var res = n - 1;\n while (value > 1) {\n res *= value;\n value--;\n }\n\n if (res === 0) {\n res = 1; // 0! is per definition 1\n }\n\n return res;\n }\n\n if (n < 0.5) {\n return Math.PI / (Math.sin(Math.PI * n) * gamma(1 - n));\n }\n\n if (n >= 171.35) {\n return Infinity; // will overflow\n }\n\n if (n > 85.0) { // Extended Stirling Approx\n var twoN = n * n;\n var threeN = twoN * n;\n var fourN = threeN * n;\n var fiveN = fourN * n;\n return Math.sqrt(2 * Math.PI / n) * Math.pow((n / Math.E), n) *\n (1 + (1 / (12 * n)) + (1 / (288 * twoN)) - (139 / (51840 * threeN)) -\n (571 / (2488320 * fourN)) + (163879 / (209018880 * fiveN)) +\n (5246819 / (75246796800 * fiveN * n)));\n }\n\n --n;\n x = GAMMA_P[0];\n for (var i = 1; i < GAMMA_P.length; ++i) {\n x += GAMMA_P[i] / (n + i);\n }\n\n t = n + GAMMA_G + 0.5;\n return Math.sqrt(2 * Math.PI) * Math.pow(t, n + 0.5) * Math.exp(-t) * x;\n}\n\nfunction stringOrArrayLength(s) {\n if (Array.isArray(s)) {\n return s.length;\n }\n return String(s).length;\n}\n\nfunction hypot() {\n var sum = 0;\n var larg = 0;\n for (var i = 0; i < arguments.length; i++) {\n var arg = Math.abs(arguments[i]);\n var div;\n if (larg < arg) {\n div = larg / arg;\n sum = (sum * div * div) + 1;\n larg = arg;\n } else if (arg > 0) {\n div = arg / larg;\n sum += div * div;\n } else {\n sum += arg;\n }\n }\n return larg === Infinity ? Infinity : larg * Math.sqrt(sum);\n}\n\nfunction condition(cond, yep, nope) {\n return cond ? yep : nope;\n}\n\n/**\n* Decimal adjustment of a number.\n* From @escopecz.\n*\n* @param {Number} value The number.\n* @param {Integer} exp The exponent (the 10 logarithm of the adjustment base).\n* @return {Number} The adjusted value.\n*/\nfunction roundTo(value, exp) {\n // If the exp is undefined or zero...\n if (typeof exp === 'undefined' || +exp === 0) {\n return Math.round(value);\n }\n value = +value;\n exp = -(+exp);\n // If the value is not a number or the exp is not an integer...\n if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {\n return NaN;\n }\n // Shift\n value = value.toString().split('e');\n value = Math.round(+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));\n // Shift back\n value = value.toString().split('e');\n return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));\n}\n\nfunction setVar(name, value, variables) {\n if (variables) variables[name] = value;\n return value;\n}\n\nfunction arrayIndex(array, index) {\n return array[index | 0];\n}\n\nfunction max(array) {\n if (arguments.length === 1 && Array.isArray(array)) {\n return Math.max.apply(Math, array);\n } else {\n return Math.max.apply(Math, arguments);\n }\n}\n\nfunction min(array) {\n if (arguments.length === 1 && Array.isArray(array)) {\n return Math.min.apply(Math, array);\n } else {\n return Math.min.apply(Math, arguments);\n }\n}\n\nfunction arrayMap(f, a) {\n if (typeof f !== 'function') {\n throw new Error('First argument to map is not a function');\n }\n if (!Array.isArray(a)) {\n throw new Error('Second argument to map is not an array');\n }\n return a.map(function (x, i) {\n return f(x, i);\n });\n}\n\nfunction arrayFold(f, init, a) {\n if (typeof f !== 'function') {\n throw new Error('First argument to fold is not a function');\n }\n if (!Array.isArray(a)) {\n throw new Error('Second argument to fold is not an array');\n }\n return a.reduce(function (acc, x, i) {\n return f(acc, x, i);\n }, init);\n}\n\nfunction arrayFilter(f, a) {\n if (typeof f !== 'function') {\n throw new Error('First argument to filter is not a function');\n }\n if (!Array.isArray(a)) {\n throw new Error('Second argument to filter is not an array');\n }\n return a.filter(function (x, i) {\n return f(x, i);\n });\n}\n\nfunction stringOrArrayIndexOf(target, s) {\n if (!(Array.isArray(s) || typeof s === 'string')) {\n throw new Error('Second argument to indexOf is not a string or array');\n }\n\n return s.indexOf(target);\n}\n\nfunction arrayJoin(sep, a) {\n if (!Array.isArray(a)) {\n throw new Error('Second argument to join is not an array');\n }\n\n return a.join(sep);\n}\n\nfunction sign(x) {\n return ((x > 0) - (x < 0)) || +x;\n}\n\nvar ONE_THIRD = 1/3;\nfunction cbrt(x) {\n return x < 0 ? -Math.pow(-x, ONE_THIRD) : Math.pow(x, ONE_THIRD);\n}\n\nfunction expm1(x) {\n return Math.exp(x) - 1;\n}\n\nfunction log1p(x) {\n return Math.log(1 + x);\n}\n\nfunction log2(x) {\n return Math.log(x) / Math.LN2;\n}\n\nfunction Parser(options) {\n this.options = options || {};\n this.unaryOps = {\n sin: Math.sin,\n cos: Math.cos,\n tan: Math.tan,\n asin: Math.asin,\n acos: Math.acos,\n atan: Math.atan,\n sinh: Math.sinh || sinh,\n cosh: Math.cosh || cosh,\n tanh: Math.tanh || tanh,\n asinh: Math.asinh || asinh,\n acosh: Math.acosh || acosh,\n atanh: Math.atanh || atanh,\n sqrt: Math.sqrt,\n cbrt: Math.cbrt || cbrt,\n log: Math.log,\n log2: Math.log2 || log2,\n ln: Math.log,\n lg: Math.log10 || log10,\n log10: Math.log10 || log10,\n expm1: Math.expm1 || expm1,\n log1p: Math.log1p || log1p,\n abs: Math.abs,\n ceil: Math.ceil,\n floor: Math.floor,\n round: Math.round,\n trunc: Math.trunc || trunc,\n '-': neg,\n '+': Number,\n exp: Math.exp,\n not: not,\n length: stringOrArrayLength,\n '!': factorial,\n sign: Math.sign || sign\n };\n\n this.binaryOps = {\n '+': add,\n '-': sub,\n '*': mul,\n '/': div,\n '%': mod,\n '^': Math.pow,\n '||': concat,\n '==': equal,\n '!=': notEqual,\n '>': greaterThan,\n '<': lessThan,\n '>=': greaterThanEqual,\n '<=': lessThanEqual,\n and: andOperator,\n or: orOperator,\n 'in': inOperator,\n '=': setVar,\n '[': arrayIndex\n };\n\n this.ternaryOps = {\n '?': condition\n };\n\n this.functions = {\n random: random,\n fac: factorial,\n min: min,\n max: max,\n hypot: Math.hypot || hypot,\n pyt: Math.hypot || hypot, // backward compat\n pow: Math.pow,\n atan2: Math.atan2,\n 'if': condition,\n gamma: gamma,\n roundTo: roundTo,\n map: arrayMap,\n fold: arrayFold,\n filter: arrayFilter,\n indexOf: stringOrArrayIndexOf,\n join: arrayJoin\n };\n\n this.consts = {\n E: Math.E,\n PI: Math.PI,\n 'true': true,\n 'false': false\n };\n}\n\nParser.prototype.parse = function (expr) {\n var instr = [];\n var parserState = new ParserState(\n this,\n new TokenStream(this, expr),\n { allowMemberAccess: this.options.allowMemberAccess }\n );\n\n parserState.parseExpression(instr);\n parserState.expect(TEOF, 'EOF');\n\n return new Expression(instr, this);\n};\n\nParser.prototype.evaluate = function (expr, variables) {\n return this.parse(expr).evaluate(variables);\n};\n\nvar sharedParser = new Parser();\n\nParser.parse = function (expr) {\n return sharedParser.parse(expr);\n};\n\nParser.evaluate = function (expr, variables) {\n return sharedParser.parse(expr).evaluate(variables);\n};\n\nvar optionNameMap = {\n '+': 'add',\n '-': 'subtract',\n '*': 'multiply',\n '/': 'divide',\n '%': 'remainder',\n '^': 'power',\n '!': 'factorial',\n '<': 'comparison',\n '>': 'comparison',\n '<=': 'comparison',\n '>=': 'comparison',\n '==': 'comparison',\n '!=': 'comparison',\n '||': 'concatenate',\n 'and': 'logical',\n 'or': 'logical',\n 'not': 'logical',\n '?': 'conditional',\n ':': 'conditional',\n '=': 'assignment',\n '[': 'array',\n '()=': 'fndef'\n};\n\nfunction getOptionName(op) {\n return optionNameMap.hasOwnProperty(op) ? optionNameMap[op] : op;\n}\n\nParser.prototype.isOperatorEnabled = function (op) {\n var optionName = getOptionName(op);\n var operators = this.options.operators || {};\n\n return !(optionName in operators) || !!operators[optionName];\n};\n\n/*!\n Based on ndef.parser, by Raphael Graf(r@undefined.ch)\n http://www.undefined.ch/mparser/index.html\n\n Ported to JavaScript and modified by Matthew Crumley (email@matthewcrumley.com, http://silentmatt.com/)\n\n You are free to use and modify this code in anyway you find useful. Please leave this comment in the code\n to acknowledge its original source. If you feel like it, I enjoy hearing about projects that use my code,\n but don't feel like you have to let me know or ask permission.\n*/\n\n// Backwards compatibility\nvar index = {\n Parser: Parser,\n Expression: Expression\n};\n\nexport default index;\nexport { Expression, Parser };\n","import {\n kosAction,\n ObservableData,\n uuid,\n type KosData,\n type KosModelRegistrationType,\n} from \"../../../core\";\nimport { kosModel } from \"../../../core/core/decorators\";\nimport type {\n IKosDataModel,\n KosContextLogger,\n KosCreationContext,\n} from \"../../../core/core/kosModel\";\nimport type { IKosIdentifiable } from \"../../../core/core/types\";\nimport type { PublicModelInterface } from \"../../../core/types\";\n\nimport { Parser } from \"expr-eval\";\nimport type { KosExpressionEvaluatorOptions } from \"./types\";\n\nexport const MODEL_TYPE = \"kos-expression-evaluator-model\";\n\n/**\n * Result of evaluating an expression, containing either a successful value or error details.\n *\n * @example\n * ```typescript\n * const result = evaluator.getExpressionValue('myExpression');\n * if (result?.error) {\n * console.error(`Expression error: ${result.error}`);\n * } else {\n * console.log(`Result: ${result?.value}`);\n * }\n * ```\n */\nexport interface ExpressionResult {\n /** The computed value of the expression, or undefined if evaluation failed */\n value: unknown;\n /** Error message if expression evaluation failed, undefined if successful */\n error?: string;\n}\n\n/**\n * A named expression that can be dynamically evaluated against context data.\n * Expressions automatically re-evaluate when their dependencies change.\n */\n/**\n * A reactive expression that automatically re-evaluates when its dependencies change.\n * This class is made reactive by the parent model's makeAutoObservable.\n */\nclass ReactiveExpression implements NamedExpression {\n name: string;\n expression: string;\n private expr: unknown;\n private getContextData: (() => Record<string, unknown>) | null = null;\n // Cache the last result to allow comparison without re-evaluation\n private _lastResult: ExpressionResult = { value: undefined };\n\n constructor(\n name: string,\n expression: string,\n expr: unknown,\n getContextData: () => Record<string, unknown>\n ) {\n this.name = name;\n this.expression = expression;\n this.expr = expr;\n this.getContextData = getContextData;\n // Initialize with undefined result - will be set by initial evaluation\n this._lastResult = { value: undefined, error: undefined };\n }\n\n /**\n * Pure getter that returns the cached result without side effects.\n */\n get result(): ExpressionResult {\n return this._lastResult;\n }\n\n /**\n * Update the cached result. Called by the parent model after evaluation.\n */\n updateResult(result: ExpressionResult): void {\n this._lastResult = result;\n }\n\n /**\n * Evaluate the expression with the given context data.\n * This method allows the parent model to trigger evaluation without side effects in getters.\n */\n evaluate(contextData: Record<string, unknown>): ExpressionResult {\n try {\n const value = (this.expr as any).evaluate(contextData as never);\n return { value, error: undefined };\n } catch (error) {\n return {\n value: undefined,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n }\n}\n\nexport interface NamedExpression {\n /** Unique name identifier for this expression */\n name: string;\n /** The expression string (JavaScript-like syntax) */\n expression: string;\n /** Getter that returns the cached result */\n get result(): ExpressionResult;\n /** Method to evaluate the expression with given context data */\n evaluate(contextData: Record<string, unknown>): ExpressionResult;\n /** Method to update the cached result */\n updateResult(result: ExpressionResult): void;\n}\n\n/**\n * KOS Expression Evaluator Model - Reactive expression evaluation with dynamic context and type-safe named expressions.\n *\n * This model provides a reactive expression evaluation system that automatically re-evaluates\n * expressions when their context data changes. Perfect for business rules, computed values,\n * and conditional logic that needs to stay synchronized with changing data.\n *\n * ## Key Features\n * - **Automatic reactivity** - Expressions re-evaluate when dependencies change thanks to KOS reactive patterns\n * - **Type safety** - Generic type parameter provides compile-time checking for expression names\n * - **Efficient updates** - Only affected expressions recalculate when their data dependencies change\n * - **Synchronous access** - Results available immediately via getters\n * - **Error handling** - Expressions with runtime errors are handled gracefully\n * - **KOS model integration** - Add any KOS model to context for fully reactive expressions\n *\n * @interface\n * @example Basic Usage\n * ```typescript\n * const evaluator = KosExpressionEvaluatorModel.instance('my-evaluator').build();\n *\n * evaluator.setContextData({ temperature: 72, humidity: 45 });\n * evaluator.addExpression('isComfortable', 'temperature >= 68 && temperature <= 78');\n *\n * console.log(evaluator.results.isComfortable?.value); // true\n * ```\n *\n * @group KOS Model\n * @category Expression Processing\n * @useDeclaredType\n */\nexport type KosExpressionEvaluatorModel<T extends string = string> =\n PublicModelInterface<KosExpressionEvaluatorModelImpl<T>>;\n\n/**\n * @ignore\n * @internal\n */\n@kosModel({ modelTypeId: MODEL_TYPE, singleton: false })\nexport class KosExpressionEvaluatorModelImpl<T extends string = string>\n implements IKosDataModel, IKosIdentifiable\n{\n // Registration property for type safety - actual value injected by @kosModel decorator\n static Registration: KosModelRegistrationType<\n KosExpressionEvaluatorModel,\n KosExpressionEvaluatorOptions\n >;\n id: string;\n private logger: KosContextLogger;\n\n private parser: Parser;\n private _data: KosData<Record<string, unknown>>;\n private _expressions = new Map<string, NamedExpression>();\n // Use ObservableData for results to handle dynamic properties properly\n private _results: KosData<Record<string, ExpressionResult>>;\n private _contextRevision = 0;\n\n constructor(\n modelId: string,\n options: KosExpressionEvaluatorOptions,\n context: KosCreationContext\n ) {\n this.id = modelId;\n this.logger = context.logger;\n this._data = ObservableData();\n this._results = ObservableData(); // Initialize with ObservableData for dynamic properties\n this.parser = new Parser();\n\n // Add custom functions to the parser for common visibility patterns\n\n // exists(value) - Check if value is not undefined or null\n this.parser.functions.exists = (value: unknown) =>\n value !== undefined && value !== null;\n\n // isEmpty(value) - Check if value is empty (null, undefined, \"\", [], or {})\n this.parser.functions.isEmpty = (value: unknown) => {\n if (value === undefined || value === null) return true;\n if (typeof value === \"string\") return value.length === 0;\n if (Array.isArray(value)) return value.length === 0;\n if (typeof value === \"object\") return Object.keys(value).length === 0;\n return false;\n };\n\n // Caller-supplied functions (may not shadow the built-ins above)\n for (const [name, fn] of Object.entries(options?.customFunctions ?? {})) {\n if (name in this.parser.functions) {\n this.logger.warn(\n `customFunctions.${name} ignored: a built-in with that name exists`\n );\n continue;\n }\n this.parser.functions[name] = fn;\n }\n }\n\n /**\n * Get the current context data that expressions are evaluated against.\n *\n * @returns The current context data as a record of key-value pairs\n */\n get data(): Record<string, unknown> {\n return this._data;\n }\n\n get contextRevision(): number {\n return this._contextRevision;\n }\n\n /**\n * Replace the entire context data with new values. All expressions will\n * automatically re-evaluate against the new context.\n *\n * @param newData - Complete new context data to replace existing data\n *\n * @example\n * ```typescript\n * evaluator.setContextData({ temperature: 75, humidity: 40 });\n * ```\n */\n setContextData(newData: Record<string, unknown>): void {\n this._data.setValues(newData);\n // Increment revision to trigger effect\n kosAction(() => {\n this._contextRevision++;\n this.logger.debug(\n \"Context revision incremented to:\",\n this._contextRevision\n );\n });\n }\n\n /**\n * Update a single value in the context data. All expressions using this\n * value will automatically re-evaluate.\n *\n * @param key - The context data key to update\n * @param value - The new value to set\n *\n * @example\n * ```typescript\n * evaluator.updateContextValue('temperature', 85);\n * ```\n */\n updateContextValue(key: string, value: unknown): void {\n this._data[key] = value;\n }\n\n /**\n * Update a nested property in the context data using dot notation.\n * This method safely updates nested properties without replacing the entire object structure.\n *\n * @param path - Dot-separated path to the nested property (e.g., 'sensors.humidity', 'config.thresholds.temp')\n * @param value - The new value to set at the nested path\n *\n * @example\n * ```typescript\n * evaluator.updateNestedValue('sensors.humidity', 60);\n * ```\n */\n updateNestedValue(path: string, value: unknown): void {\n const pathSegments = path.split(\".\");\n const lastSegment = pathSegments.pop();\n\n if (!lastSegment) {\n this.logger.error(`Invalid path \"${path}\" - cannot be empty`);\n return;\n }\n\n // Navigate to the parent object\n let current: Record<string, unknown> = this._data;\n for (const segment of pathSegments) {\n if (current[segment] === undefined || current[segment] === null) {\n // Create nested object if it doesn't exist\n current[segment] = {};\n }\n current = current[segment] as Record<string, unknown>;\n }\n\n // Set the final value\n current[lastSegment] = value;\n\n this.logger.debug(`Updated nested context value \"${path}\" to:`, value);\n }\n\n /**\n * Add a KOS model to the evaluation context. The model's observable properties\n * will be accessible via dotted notation and expressions will automatically\n * re-evaluate when the model's data changes.\n *\n * @param key - The context key to store the model under\n * @param model - Any KOS model instance (must be observable)\n *\n * @example\n * ```typescript\n * const sensorModel = SensorModel.instance('main-sensor').build();\n * evaluator.addModelToContext('sensor', sensorModel);\n * evaluator.addExpression('isCritical', 'sensor.temperature > 80');\n * ```\n */\n addModelToContext(key: string, model: unknown): void {\n this._data[key] = model;\n }\n\n /**\n * Add a named expression that will be automatically evaluated against context data.\n * The expression will re-evaluate whenever its dependencies in the context change.\n *\n * @param name - Unique identifier for this expression (type-safe when using generic)\n * @param expressionString - JavaScript-like expression string\n * @throws {Error} If the expression has invalid syntax\n *\n * @example\n * ```typescript\n * evaluator.addExpression('isHot', 'temperature > 80');\n * ```\n */\n addExpression(name: T, expressionString: string): void {\n try {\n const expr = this.parser.parse(expressionString);\n\n // Create reactive expression instance - evaluation is now handled by the main model\n const reactiveExpression = new ReactiveExpression(\n name,\n expressionString,\n expr,\n () => this.data\n );\n\n this._expressions.set(name, reactiveExpression);\n\n // Perform initial evaluation and cache the result\n this.evaluateExpression(name);\n\n this.logger.debug(`Added expression \"${name}\": ${expressionString}`);\n } catch (error) {\n this.logger.error(`Failed to parse expression \"${name}\"`, error);\n throw error;\n }\n }\n\n removeExpression(name: T): boolean {\n const removed = this._expressions.delete(name);\n if (removed) {\n delete this._results[name as string];\n this.logger.debug(`Removed expression \"${name}\"`);\n } else {\n this.logger.warn(\n `Attempted to remove non-existent expression \"${name}\". Available expressions: [${this.expressionNames.join(\n \", \"\n )}]`\n );\n }\n return removed;\n }\n\n getExpression(name: T): NamedExpression | undefined {\n const expression = this._expressions.get(name);\n if (!expression) {\n this.logger.warn(\n `Expression \"${name}\" not found. Available expressions: [${this.expressionNames.join(\n \", \"\n )}]`\n );\n }\n return expression;\n }\n\n getExpressionValue(name: T): ExpressionResult | undefined {\n const expression = this._expressions.get(name);\n if (!expression) {\n this.logger.warn(\n `Expression \"${name}\" not found. Available expressions: [${this.expressionNames.join(\n \", \"\n )}]`\n );\n return undefined;\n }\n return expression.result;\n }\n\n /**\n * Get the cached result of an expression without triggering re-evaluation.\n * This is useful for dependency tracking in effects where you want to avoid\n * creating reactive chains through the expression evaluation.\n *\n * @param name - The expression name to get the cached result for\n * @returns The last cached result, or undefined if expression doesn't exist\n *\n * @example\n * ```typescript\n * const cached = evaluator.getCachedExpressionValue('myExpression');\n * ```\n */\n getCachedExpressionValue(name: T): ExpressionResult | undefined {\n const expression = this._expressions.get(name) as\n | ReactiveExpression\n | undefined;\n if (!expression) {\n return undefined;\n }\n return expression.result;\n }\n\n get expressions(): NamedExpression[] {\n return Array.from(this._expressions.values());\n }\n\n get expressionNames(): T[] {\n return Array.from(this._expressions.keys()) as T[];\n }\n\n // Reactive getter that evaluates expressions when accessed\n get results(): Record<T, ExpressionResult> {\n // Force evaluation of all expressions to ensure they're current\n // This creates MobX dependencies on the actual context data being used\n this.evaluateAllExpressions();\n\n return this._results as Record<T, ExpressionResult>;\n }\n\n /**\n * Force re-evaluation of all expressions and update cached results.\n * This is called by the effect when context data changes.\n */\n private evaluateAllExpressions(): void {\n const keys = Array.from(this._expressions.keys());\n keys.forEach((key) => {\n const expression = this._expressions.get(key);\n if (expression) {\n // Call evaluate method instead of getter to avoid side effects in getter\n this.evaluateExpression(key as T);\n }\n });\n }\n\n /**\n * Evaluate a specific expression and update the cached result if it changed.\n */\n private evaluateExpression(name: T): void {\n this.logger.debug(`Evaluating expression: ${String(name)}`);\n const expression = this._expressions.get(name);\n if (!expression) {\n this.logger.warn(`Expression \"${String(name)}\" not found`);\n return;\n }\n\n // Use the expression's evaluate method to get the new result\n const newResult = expression.evaluate(this.data);\n this.logger.debug(`Expression \"${String(name)}\" evaluated to:`, newResult);\n\n // Only update if the result actually changed - direct comparison is much more efficient\n const currentResult = expression.result;\n if (\n newResult.value !== currentResult.value ||\n newResult.error !== currentResult.error\n ) {\n this.logger.debug(\n `Expression \"${String(name)}\" result changed from`,\n currentResult,\n \"to\",\n newResult\n );\n expression.updateResult(newResult);\n this.updateResult(name as string, newResult);\n }\n }\n\n /**\n * Internal method to update the results object when expression values change.\n * This is called by ReactiveExpression when its value changes.\n * ObservableData handles dynamic properties automatically with MobX atoms.\n */\n private updateResult(name: string, result: ExpressionResult): void {\n this.logger.debug(\n `ExpressionEvaluator.updateResult called for \"${name}\":`,\n result\n );\n // ObservableData handles dynamic properties perfectly!\n // Wrap in kosAction to prevent MobX strict mode violations\n kosAction(() => {\n this._results[name] = result;\n });\n }\n\n /**\n * Create an anonymous reactive expression and return its generated ID.\n * The expression becomes fully reactive and can be accessed via the returned ID.\n *\n * @param expressionString - JavaScript-like expression string\n * @returns Generated UUID that can be used to access the expression via `getExpressionValue(id)` or `results[id]`\n *\n * @example\n * ```typescript\n * const tempCheckId = evaluator.createExpression('temperature > 75');\n * const result = evaluator.getExpressionValue(tempCheckId);\n * ```\n */\n createExpression(expressionString: string): string {\n // Generate a UUID for the anonymous expression\n const anonymousId = uuid();\n\n // Add it as a named expression (making it fully reactive)\n // Cast to T since uuid() generates a string that will be used as expression name\n this.addExpression(anonymousId as T, expressionString);\n\n return anonymousId;\n }\n}\n","import { KosExpressionEvaluatorModelImpl } from \"./kos-expression-evaluator-model\";\n\nexport type {\n KosExpressionEvaluatorModel,\n KosExpressionEvaluatorModelImpl,\n ExpressionResult,\n NamedExpression,\n} from \"./kos-expression-evaluator-model\";\nexport type * from \"./types\";\n\nexport const KosExpressionEvaluator =\n KosExpressionEvaluatorModelImpl.Registration;\n","import { type ServiceResponse } from \"../../../../core\";\nimport { KosLog } from \"../../../../core/core/log\";\nimport API, { type ApiPath, type ApiResponse } from \"../../../utils/service\";\n\nconst log = KosLog.createLogger({\n name: \"kos-log-manager-service\",\n group: \"Services\",\n});\n\nconst SERVICE_PATH: ApiPath = \"/api/kos/logs/overrides\";\n\nexport type KosLogManagerResponse = ApiResponse<typeof SERVICE_PATH, \"get\">;\n\n/**\n * @category Service\n * Retrieves the initial kos-log-manager data.\n */\nexport const getLogOverrides = async (): Promise<\n ServiceResponse<KosLogManagerResponse>\n> => {\n log.debug(\"sending GET for kos-log-manager\");\n return await API.get(SERVICE_PATH);\n};\n","import type { LogLevelDesc } from \"loglevel\";\nimport {\n KosDataContainer,\n KosLog,\n type IKosDataContainer,\n type KosRequest,\n type KosResponse,\n} from \"../../../core\";\nimport {\n get,\n kosModel,\n kosTopicHandler,\n type ApiCallbackWithWildcard,\n} from \"../../../core/core/decorators\";\nimport type {\n IKosDataModel,\n KosContextLogger,\n KosCreationContext,\n} from \"../../../core/core/kosModel\";\nimport type { IKosIdentifiable } from \"../../../core/core/types\";\nimport type { PublicModelInterface } from \"../../../core/types\";\nimport { getLogOverrides } from \"./services\";\n\nimport type {\n KosLogManagerOptions,\n LogLevelDescriptor,\n LogLevelNames,\n LogOverride,\n} from \"./types\";\n\n/**\n * Model type identifier for the KOS Log Manager\n */\nexport const MODEL_TYPE = \"kos-log-manager-model\";\n\n/**\n * KOS Log Manager Model - Centralized runtime log level management for the entire KOS system.\n *\n * This singleton model provides comprehensive control over logging behavior across the KOS UI SDK\n * and connected applications. It manages dynamic log level overrides, responds to real-time\n * configuration changes, and provides both REST API and WebSocket interfaces for log management.\n * Essential for debugging, performance monitoring, and production troubleshooting.\n *\n * ## Key Features\n * - **Runtime Log Level Control** - Dynamically adjust log levels without application restart\n * - **Hierarchical Logger Management** - Apply overrides to parent loggers and all children\n * - **Real-time Configuration** - WebSocket-based updates propagate instantly across clients\n * - **REST API Integration** - Query and manage logger configurations via HTTP endpoints\n * - **Override Persistence** - Log overrides are maintained across sessions and page refreshes\n * - **Multi-Node Support** - Coordinate logging across different KOS device nodes\n *\n * ## Topic-Based Reactivity\n * The model listens to these KOS topics for real-time log management:\n * - **`/kos/logs/override/add/*`** - Fired when new log level overrides are created\n * - **`/kos/logs/override/remove/*`** - Fired when log level overrides are removed\n *\n * Both topics support wildcard capture for node type targeting, enabling precise\n * control over which device nodes receive logging configuration changes.\n *\n * ## Architecture Integration\n * The log manager integrates with the broader KOS logging ecosystem:\n * - **KosLog System** - Manages underlying logger instances and level settings\n * - **LogStreamModel** - Streams managed by this model's log level policies\n * - **LogBlockModel** - Individual log entries governed by level settings\n * - **REST Endpoints** - Provides `/api/kos/ui/loggers` for external access\n *\n * ## Common Use Cases\n * - **Development Debugging** - Increase log verbosity for specific components during development\n * - **Production Troubleshooting** - Temporarily enable debug logging to diagnose issues\n * - **Performance Monitoring** - Adjust log levels to reduce overhead in production\n * - **System Administration** - Centrally manage logging across distributed KOS deployments\n * - **Dynamic Configuration** - Change logging behavior without service interruption\n * - **Selective Logging** - Enable detailed logging for specific modules while keeping others quiet\n *\n * @interface\n * @example Basic Usage\n * ```typescript\n * const logManager = KosLogManager.instance('log-control').build();\n *\n * // Get all current logger configurations via REST API\n * const loggers = await logManager.getAllLoggers();\n * console.log(`Managing ${loggers.length} loggers`);\n * ```\n *\n * @group KOS Model\n * @category Device Logging\n * @useDeclaredType\n *\n * @see {@link LogStreamModel} - Streams whose content is governed by log levels managed here\n * @see {@link LogBlockModel} - Individual log entries affected by level settings\n * @see {@link KosLogManagerOptions} - Configuration options for the log manager\n * @see {@link LogOverride} - Log level override structure for runtime control\n * @see {@link LogLevelDescriptor} - Logger information structure returned by REST API\n */\nexport type KosLogManagerModel = PublicModelInterface<KosLogManagerModelImpl>;\n\nconst TOPIC_OVERRIDE_ADD = \"/kos/logs/override/add/*\";\nconst TOPIC_OVERRIDE_REMOVE = \"/kos/logs/override/remove/*\";\n\nconst getLogLevelName = (level: LogLevelDesc): LogLevelNames => {\n if (typeof level === \"string\") {\n return level as LogLevelNames;\n }\n if (typeof level === \"number\") {\n switch (level) {\n case 0:\n return \"trace\";\n case 1:\n return \"debug\";\n case 2:\n return \"info\";\n case 3:\n return \"warn\";\n case 4:\n return \"error\";\n default:\n return \"info\"; // Default to info if level is not recognized\n }\n }\n return \"info\"; // Default to info if level is not recognized\n};\n/**\n * @ignore\n * @internal\n */\n@kosModel(MODEL_TYPE)\nexport class KosLogManagerModelImpl implements IKosDataModel, IKosIdentifiable {\n id: string;\n private logger: KosContextLogger;\n\n private _overrides: IKosDataContainer<LogOverride>;\n constructor(\n modelId: string,\n options: KosLogManagerOptions,\n context: KosCreationContext\n ) {\n this.id = modelId;\n this.logger = context.logger;\n this._overrides = new KosDataContainer();\n if (options) {\n // Assign options properties here.\n }\n }\n\n updateModel(_options: KosLogManagerOptions): void {\n // Update model properties here.\n }\n\n // -------------------LIFECYCLE----------------------------\n\n /**\n * Resolves all registered loggers and their current log levels.\n * @returns A map of logger names to their log level descriptors\n * @private\n */\n private resolveLoggers(): Record<string, LogLevelDescriptor> {\n const loggers = KosLog.getLoggers();\n const result = Object.entries(loggers).map<LogLevelDescriptor>(\n ([name, logger]) => {\n return {\n name,\n level: getLogLevelName(logger.getLevel()) as LogLevelNames,\n };\n }\n );\n const resultMap = result.reduce<Record<string, LogLevelDescriptor>>(\n (acc, { name, level }) => {\n acc[name] = { name, level };\n return acc;\n },\n {} as Record<string, LogLevelDescriptor>\n );\n this.logger.debug(\"Resolved loggers\", resultMap);\n\n return resultMap;\n }\n /**\n * REST API endpoint to retrieve all logger configurations.\n * @get /api/kos/ui/loggers\n * @param _req - The incoming request (unused)\n * @param res - The response object to send logger data\n * @returns Array of log level descriptors for all loggers\n */\n @get(\"/api/kos/ui/loggers\")\n async getAllLoggers(\n _req?: KosRequest,\n res?: KosResponse\n ): Promise<LogLevelDescriptor[]> {\n const loggers = Object.values(this.resolveLoggers());\n\n res?.send(loggers);\n return loggers;\n }\n\n /**\n * Applies a log level override to matching loggers.\n * Sets the specified log level for the logger and all child loggers\n * whose names start with the override name.\n * @param override - The log override configuration to apply\n * @private\n */\n private setLogLevels(override: LogOverride): void {\n const loggers = Object.values(this.resolveLoggers()).filter((logger) =>\n logger.name.startsWith(override.name)\n );\n\n // Set the level of the child logger to the override level\n loggers.forEach((logger) => {\n const _logger = KosLog.getLoggers()[logger.name];\n if (!_logger) {\n this.logger.debug(`Logger ${logger.name} not found`);\n return;\n }\n _logger.setLevel(override.level);\n });\n // Set the level of the logger\n const _logger = KosLog.getLoggers()[override.name];\n if (!_logger) {\n this.logger.debug(`Logger ${override.name} not found`);\n return;\n }\n _logger.setLevel(override.level);\n globalThis.kos.logOverrides = this._overrides.data;\n }\n\n /**\n * Resets log levels to their defaults for matching loggers.\n * Removes the override for the logger and all child loggers\n * whose names start with the override name.\n * @param override - The log override configuration to reset\n * @private\n */\n private resetLogLevels(override: LogOverride): void {\n const loggers = Object.values(this.resolveLoggers()).filter((logger) =>\n logger.name.startsWith(override.name)\n );\n\n // Set the level of the child logger to the override level\n loggers.forEach((logger) => {\n const _logger = KosLog.getLoggers()[logger.name];\n if (!_logger) {\n this.logger.debug(`Logger ${logger.name} not found`);\n }\n _logger?.resetLevel();\n });\n // Set the level of the logger\n const _logger = KosLog.getLoggers()[override.name];\n if (!_logger) {\n this.logger.debug(`Logger ${override.name} not found`);\n }\n _logger?.resetLevel();\n globalThis.kos.logOverrides = this._overrides.data;\n }\n\n /**\n * WebSocket handler for log override addition events.\n * Listens to: /kos/logs/override/add/*\n * @param override - The log override to add\n * @param payload - Contains wildcard capture data including nodeType\n */\n @kosTopicHandler({\n topic: TOPIC_OVERRIDE_ADD,\n websocket: true,\n wildcardName: \"nodeType\",\n })\n handleOverrideAdded(\n override: LogOverride,\n payload: ApiCallbackWithWildcard<any>\n ) {\n this.logger.debug(\n `Override received for node type ${\n payload.wildcardCapture?.nodeType ?? \"unknown\"\n }`\n );\n this._overrides.addModel({ ...override, id: override.name });\n this.setLogLevels(override);\n }\n\n /**\n * WebSocket handler for log override removal events.\n * Listens to: /kos/logs/override/remove/*\n * @param override - The log override to remove\n */\n @kosTopicHandler({\n topic: TOPIC_OVERRIDE_REMOVE,\n websocket: true,\n wildcardName: \"nodeType\",\n })\n handleOverrideRemoved(override: LogOverride) {\n this._overrides.removeModel(override.name);\n this.resetLogLevels(override);\n }\n\n /**\n * Initializes the log manager model.\n * Called during model creation lifecycle.\n * @internal\n */\n async init(): Promise<void> {\n this.logger.debug(`initializing kos-log-manager ${this.id}`);\n }\n\n /**\n * Loads existing log overrides from the server.\n * Fetches UI-specific overrides and applies them to the current loggers.\n * Called after model initialization.\n * @internal\n */\n async load(): Promise<void> {\n this.logger.debug(`loading kos-log-manager ${this.id}`);\n\n const [error, overrides] = await getLogOverrides();\n if (error) {\n this.logger.error(\"Failed to load log overrides\", error);\n return;\n }\n const uiOverrides =\n overrides\n ?.filter((override) => override.type?.toUpperCase() === \"UI\")\n .map<LogOverride>((override) => {\n return {\n name: override.name ?? \"\",\n type: override.type ?? \"\",\n level: (override.level ?? \"info\") as LogLevelNames,\n id: override.name || \"\",\n };\n }) ?? [];\n this._overrides.addAll(uiOverrides);\n uiOverrides.forEach((override) => {\n this.setLogLevels(override);\n });\n }\n}\n","import { SingletonKosModelRegistrationFactory } from \"../../../core/core/registration\";\nimport type { KosLogManagerOptions } from \"./types\";\nimport {\n KosLogManagerModelImpl,\n MODEL_TYPE,\n KosLogManagerModel,\n} from \"./kos-log-manager-model\";\n\n/**\n * # KosLogManager\n *\n * The registration bean includes convenience methods for creating and working with KosLogManagerModel instances.\n\n *\n * ## type\n * The type property is a string that identifies the model type.\n * The type is used to identify the model type in the model registry and to narrow down the model type in type predicates. It's most frequently\n * used when declaring dependencies on models.\n *\n * @example\n * ```typescript\n *\n * @kosDependency({modelType: KosLogManager.type, id: \"kosLogManagerId\"})\n * private kosLogManagerModel: KosLogManagerModel;\n * ```\n *\n *\n * ## factory\n *\n * The factory method creates a factory function that can be used to create new KosLogManagerModel instances.\n *\n \n * As this is a singleton model, the factory function accepts the model options as its argument.\n *\n * If a model with the same model type already exists, the factory function will return the existing model. The options will be ignored\n * in this case and the existing model will be returned in its current state.\n *\n * @example\n * ```typescript\n * const model = KosLogManager.factory({\n * // Add option data\n * });\n\n * ```\n \n\n *\n * ## predicate\n *\n * [Typescript type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) function that will identify and narrow down a model to a KosLogManagerModel.\n *\n * @example\n * ```typescript\n *\n * const model: IKosDataModel = ...; // some model\n *\n * if (KosLogManager.predicate(model)) {\n * // if the function evaluates to true, the model is narrowed down to KosLogManagerModel\n * // and the compiler will know that the model has the KosLogManagerModel interface\n * model.updateAvailability(false);\n\n * }\n * ```\n *\n * ## registration\n *\n * The registration property is an object that can be used to simplify registration of the model with the model registry. The registration object\n * can be spread into the model registration and provides all of the required information to register the model implementation class against the model type.\n *\n *\n * @example\n *\n * In an application registration file you can declare the model registration as follows:\n *\n * **registration.ts**\n * ```typescript\n * import { KosLogManager } from \"@kos-ui/project-models\";\n * import { KosModelRegistry } from \"@kosdev-code/kos-dispense-sdk\";\n *\n * import { initKosProvider } from \"@kosdev-code/kos-ui-sdk\";\n *\n * KosModelRegistry.dispense\n * .models()\n * .model(KosLogManager);\n * ```\n *\n * ## registration.singleton\n \n * The kosLogManager model is a singleton model. This means that each time the factory function is called , the same instance will be returned.\n * If the model does not yet exist, it will be created passing in the provided options to initialize it.\n *\n * Singleton models don't require an ID as they will use the model type as their ID to guarantee uniqueness throughout the system.\n \n * */\nexport const KosLogManager = new SingletonKosModelRegistrationFactory<\n KosLogManagerModel,\n KosLogManagerOptions\n>({\n class: KosLogManagerModelImpl,\n type: MODEL_TYPE,\n});\n","import {\n ServiceFactory,\n resolveServiceUrl,\n type KosServiceResponse,\n} from \"../../../../core\";\nconst { URL } = resolveServiceUrl(\"KOS-TIME_SERVICE\");\nconst { postModel, getOne } = ServiceFactory.build({\n basePath: `${URL}/api/kos-time`,\n});\n\ninterface TimeBean {\n hour: number;\n min: number;\n sec: number;\n}\n\ninterface DateBean {\n month: number;\n day: number;\n year: number;\n}\n\ninterface TimezoneResponse {\n timeZone: string;\n}\n\nexport const setTime = async (time: TimeBean) => {\n const response: KosServiceResponse<any> | undefined =\n await postModel<TimeBean>({\n model: time,\n urlOverride: `${URL}/api/kos/time/time`,\n });\n if (response?.status !== 200) {\n throw Error(\"Failed to set time\");\n }\n\n return response.data;\n};\n\nexport const setDate = async (date: DateBean) => {\n const response: KosServiceResponse<any> | undefined =\n await postModel<DateBean>({\n model: date,\n urlOverride: `${URL}/api/kos/time/date`,\n });\n if (response?.status !== 200) {\n throw Error(\"Failed to set time\");\n }\n\n return response.data;\n};\n\nexport const setTimezone = async (timezone: string) => {\n const response: KosServiceResponse<any> | undefined = await postModel({\n model: {},\n urlOverride: `${URL}/api/kos/time/timezone?tz=${timezone}`,\n });\n if (response?.status !== 200) {\n throw Error(\"Failed to set timezone\");\n }\n\n return response.data;\n};\n\nexport const getTimezone = async () => {\n const response: KosServiceResponse<TimezoneResponse> | undefined =\n await getOne<TimezoneResponse>({\n urlOverride: `${URL}/api/kos/time/timezone`,\n });\n if (response?.status !== 200) {\n throw Error(\"Failed to set timezone\");\n }\n\n return response.data.timeZone;\n};\n","import { EventBus } from \"../../../common\";\nimport type {\n IKosDataModel,\n IKosModelLogger,\n KosContextLogger,\n KosCreationContext,\n PublicModelInterface,\n} from \"../../../core\";\nimport { kosModel, kosTopicHandler } from \"../../../core\";\nimport { Topics } from \"../../constants\";\nimport { getTimezone, setDate, setTime, setTimezone } from \"./services\";\nimport { type DateBean, type KosTimeOptions, type TimeBean } from \"./types\";\nexport const MODEL_TYPE = \"kos-time-model\";\n\nconst TOPIC_TIME_CHANGE = \"/kos/time/time\";\nconst TOPIC_DAY_CHANGE = \"/kos/time/day\";\nconst TOPIC_TIMEZONE_CHANGE = \"/kos/time/timezone\";\n\n/**\n * KOS Time Model - System time management with real-time synchronization and timezone control.\n *\n * This singleton model provides centralized control over system time, date, and timezone settings\n * with automatic event propagation when changes occur. Essential for applications that need to\n * synchronize time-based operations, schedule events, or maintain consistent timestamps across\n * the system.\n *\n * ## Key Features\n * - **System Time Control** - Update system hours, minutes, and seconds programmatically\n * - **Date Management** - Set system date including month, day, and year\n * - **Timezone Handling** - Change and track timezone with automatic updates\n * - **Real-time Events** - Automatic notifications when time, date, or timezone changes\n * - **EventBus Integration** - Publishes changes to internal EventBus for UI updates\n * - **WebSocket Sync** - Changes propagate across all connected clients\n *\n * ## Topic-Based Reactivity\n * The model listens to three KOS topics for time synchronization:\n * - **`/kos/time/time`** - Fired when system time changes (hour/minute/second)\n * - **`/kos/time/day`** - Fired when the date changes (day rollover or manual change)\n * - **`/kos/time/timezone`** - Fired when timezone is updated\n *\n * Additionally, the model publishes to internal EventBus topics:\n * - `TIME_CHANGE` - For UI components to react to time updates\n * - `DAY_CHANGE` - For date-dependent UI updates\n * - `TIMEZONE_CHANGE` - For timezone-aware components\n *\n * ## Common Use Cases\n * - **System Clock Management** - Synchronize device time with server time\n * - **Scheduled Operations** - Trigger events based on time changes\n * - **Multi-timezone Support** - Handle devices in different time zones\n * - **Time-based UI Updates** - Keep clocks and calendars synchronized\n * - **Audit Logging** - Ensure consistent timestamps across the system\n * - **Day Rollover Handling** - Reset daily counters or refresh data\n *\n * @interface\n * @example Basic Usage\n * ```typescript\n * const timeModel = KosTime.instance().build();\n *\n * // Update system time and date\n * await timeModel.updateSystemTime({ hour: 15, min: 45, sec: 30 });\n * await timeModel.updateSystemDate({ month: 3, day: 15, year: 2024 });\n * await timeModel.updateSystemTimezone('America/New_York');\n * ```\n *\n * @group KOS Model\n * @category System Integration\n * @useDeclaredType\n *\n * @see {@link TimeBean} - Time value structure (hour, minute, second)\n * @see {@link DateBean} - Date value structure (month, day, year)\n * @see {@link KosTimeOptions} - Configuration options for time model\n */\nexport type KosTimeModel = PublicModelInterface<KosTimeModelImpl>;\n\n/**\n * @ignore\n * @internal\n */\n@kosModel(MODEL_TYPE)\nexport class KosTimeModelImpl implements IKosModelLogger, IKosDataModel {\n id: string;\n logger: KosContextLogger;\n timezone: string;\n constructor(\n modelId: string,\n _options: KosTimeOptions,\n context: KosCreationContext\n ) {\n this.id = modelId;\n this.logger = context.logger;\n this.timezone = \"\";\n }\n\n /**\n * Updates the system clock to the provided time.\n *\n * @param time - The time to set the system time to\n */\n async updateSystemTime(time: TimeBean) {\n await setTime(time);\n }\n\n /**\n * Updates the system clock to the provided date.\n *\n * @param date - The date to set the system date to\n */\n async updateSystemDate(date: DateBean) {\n await setDate(date);\n }\n\n /**\n * Updates the system clock to the provided timezone.\n * @param timezone - The timezone to set the system timezone to\n */\n async updateSystemTimezone(timezone: string) {\n await setTimezone(timezone);\n }\n\n @kosTopicHandler({ topic: TOPIC_TIME_CHANGE, websocket: true })\n handleTimeChange(): void {\n // Handle time change here.\n EventBus.publish(Topics.TIME_CHANGE, {});\n }\n\n @kosTopicHandler({ topic: TOPIC_DAY_CHANGE, websocket: true })\n handleDayChange(): void {\n // Handle day change here.\n EventBus.publish(Topics.DAY_CHANGE, {});\n }\n\n @kosTopicHandler({ topic: TOPIC_TIMEZONE_CHANGE, websocket: true })\n async handleTimeZoneChange() {\n await this.retrieveTimezone();\n // Handle timezone change here.\n EventBus.publish(Topics.TIMEZONE_CHANGE, {});\n }\n\n // -------------------LIFECYCLE----------------------------\n\n /**\n * @internal\n */\n async init(): Promise<void> {\n this.logger.debug(`initializing kos-time ${this.id}`);\n }\n\n private async retrieveTimezone() {\n const tz = await getTimezone();\n\n if (!tz) {\n this.logger.warn(\n `Failed to retrieve timezone from system. Timezone is undefined.`\n );\n return;\n }\n\n this.setTimezone(tz);\n }\n setTimezone(tz: string) {\n this.timezone = tz ?? \"\";\n }\n\n /**\n * @internal\n */\n async load(): Promise<void> {\n this.logger.debug(`loading kos-time ${this.id}`);\n this.retrieveTimezone();\n }\n}\n","import type { SingletonKosModelRegistrationBean } from \"../../../core\";\nimport { Kos, isKosModel } from \"../../../core\";\nimport type { KosTimeModel } from \"./kos-time-model\";\nimport { KosTimeModelImpl, MODEL_TYPE } from \"./kos-time-model\";\nimport type { KosTimeOptions } from \"./types\";\n\n/**\n * # KosTime\n *\n * The registration bean includes convenience methods for creating and working with KosTimeModel instances.\n *\n * ## type\n * The type property is a string that identifies the model type.\n * The type is used to identify the model type in the model registry and to narrow down the model type in type predicates. It's most frequently\n * used when declaring dependencies on models.\n *\n * @example\n * ```typescript\n *\n * @kosDependency({modelType: KosTime.type, id: \"kosTimeId\"})\n * private kosTimeModel: KosTimeModel;\n * ```\n *\n *\n * ## factory\n *\n * The factory method creates a factory function that can be used to create new KosTimeModel instances.\n *\n \n * As this is a singleton model, the factory function accepts the model options as its argument.\n *\n * If a model with the same model type already exists, the factory function will return the existing model. The options will be ignored\n * in this case and the existing model will be returned in its current state.\n *\n * @example\n * ```typescript\n * const model = KosTime.factory({\n * // Add option data\n * });\n * ```\n \n\n *\n * ## predicate\n *\n * [Typescript type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) function that will identify and narrow down a model to a KosTimeModel.\n *\n * @example\n * ```typescript\n *\n * const model: IKosDataModel = ...; // some model\n *\n * if (KosTime.predicate(model)) {\n * // if the function evaluates to true, the model is narrowed down to KosTimeModel\n * // and the compiler will know that the model has the KosTimeModel interface\n * model.updateAvailability(false);\n * }\n * ```\n *\n * ## registration\n *\n * The registration property is an object that can be used to simplify registration of the model with the model registry. The registration object\n * can be spread into the model registration and provides all of the required information to register the model implementation class against the model type.\n *\n *\n * @example\n *\n * In an application registration file you can declare the model registration as follows:\n *\n * **registration.ts**\n * ```typescript\n * import { KosTime } from \"@kosdev-code/kos-dispense-sdk\";\n * ...\n * import { ExtensionManager, IKosRegistry } from \"@kosdev-code/kos-ui-sdk\";\n * export const kosModels: IKosRegistry[\"models\"] = {\n * ...KosTime.registration,\n * };\n * ```\n *\n * ## registration.singleton\n \n * The kosTime model is a singleton model. This means that each time the factory function is called , the same instance will be returned.\n * If the model does not yet exist, it will be created passing in the provided options to initialize it.\n *\n * Singleton models don't require an ID as they will use the model type as their ID to guarantee uniqueness throughout the system.\n * @private\n * */\nexport const KosTime: Readonly<\n SingletonKosModelRegistrationBean<KosTimeModel, KosTimeOptions>\n> = {\n registration: {\n [MODEL_TYPE]: {\n class: KosTimeModelImpl,\n singleton: true,\n },\n },\n type: MODEL_TYPE,\n predicate: isKosModel(MODEL_TYPE),\n factory: Kos.Singleton.create<KosTimeModel, KosTimeOptions>(MODEL_TYPE),\n};\n","import { kosChild, kosModel } from \"../../../core/core/decorators\";\nimport {\n KosModelContainer,\n type IKosModelContainer,\n} from \"../../../core/core/kos-container-model\";\nimport type {\n IKosDataModel,\n KosContextLogger,\n KosCreationContext,\n} from \"../../../core/core/kosModel\";\nimport type { IKosIdentifiable } from \"../../../core/core/types\";\nimport type {\n IKosModelHolder,\n PublicModelInterface,\n} from \"../../../core/types\";\n\nimport type { LogBlockModel } from \"./log-block-model\";\nimport type { LogBlockContainerOptions } from \"./types\";\n\nexport const MODEL_TYPE = \"log-block-container-model\";\n\n/**\n * Log Block Container Model - Manages multiple log blocks with automatic sorting and organization.\n *\n * This container model manages collections of LogBlockModel instances, providing organized access\n * to log blocks with automatic sorting by block number. It serves as the storage layer within\n * LogStreamModel instances, handling the efficient organization and retrieval of log blocks\n * that make up a complete log stream.\n *\n * ## Key Features\n * - **Automatic Sorting** - Maintains blocks sorted by block number for sequential access\n * - **Block Management** - Add, remove, and retrieve log blocks efficiently\n * - **Memory Organization** - Organized storage of log blocks within streams\n * - **Stream Integration** - Essential component of LogStreamModel architecture\n * - **Sequential Access** - Optimized for accessing blocks in chronological order\n *\n * ## Architecture Role\n * The container fits into the log streaming architecture as:\n * - **LogStreamModel** uses LogBlockContainerModel to organize its blocks\n * - **LogBlockContainerModel** manages multiple LogBlockModel instances\n * - **LogBlockModel** contains the actual log lines and metadata\n * - Automatic sorting by blockNum ensures proper sequential log ordering\n *\n * ## Common Use Cases\n * - **Stream Block Storage** - Central storage for all blocks within a log stream\n * - **Sequential Block Access** - Navigate through log blocks in chronological order\n * - **Block Organization** - Maintain sorted collections of log segments\n * - **Memory Management** - Efficiently organize log data for stream processing\n * - **Block Lifecycle** - Handle adding and removing blocks as streams evolve\n *\n * @example Container Usage Within Stream\n * ```typescript\n * // Typically used internally by LogStreamModel\n * const logStream = LogStream.instance('system-logs').build();\n * await logStream.load();\n *\n * // Access the container through the stream\n * const blockContainer = logStream._blocks; // Internal container\n * const blocks = logStream.blocks; // Public access to blocks\n *\n * // Container automatically sorts blocks by blockNum\n * console.log(`Stream has ${blocks.length} blocks`);\n * blocks.forEach(block => {\n * console.log(`Block ${block.blockNum}: ${block.lineCount} lines`);\n * });\n * ```\n *\n * @example Direct Container Operations\n * ```typescript\n * // Create container (typically done internally)\n * const container = LogBlockContainer.instance('log-blocks')\n * .options({})\n * .build();\n *\n * // Add blocks to container\n * const block1 = LogBlock.instance('block-1')\n * .options({\n * nodeId: 'primary',\n * stream: 'app-logs',\n * blockNum: 1,\n * startLineNum: 1,\n * endLineNum: 100,\n * startTime: new Date('2024-01-01T10:00:00Z'),\n * endTime: new Date('2024-01-01T10:05:00Z'),\n * lineCount: 100\n * })\n * .build();\n *\n * const block2 = LogBlock.instance('block-2')\n * .options({\n * nodeId: 'primary',\n * stream: 'app-logs',\n * blockNum: 2,\n * startLineNum: 101,\n * endLineNum: 200,\n * startTime: new Date('2024-01-01T10:05:00Z'),\n * endTime: new Date('2024-01-01T10:10:00Z'),\n * lineCount: 100\n * })\n * .build();\n *\n * container.addModel(block1);\n * container.addModel(block2);\n *\n * // Blocks are automatically sorted by blockNum\n * const sortedBlocks = container.data;\n * console.log(`First block: ${sortedBlocks[0].blockNum}`); // 1\n * console.log(`Second block: ${sortedBlocks[1].blockNum}`); // 2\n * ```\n *\n * @example React Block List Component\n * ```typescript\n * const BlockList: React.FC<{ container: LogBlockContainerModel }> = kosComponent(({ container }) => {\n * return (\n * <div className=\"block-list\">\n * <h3>Log Blocks ({container.data.length})</h3>\n * <div className=\"blocks\">\n * {container.data.map(block => (\n * <div key={block.id} className=\"block-item\">\n * <div className=\"block-header\">\n * <span className=\"block-num\">Block {block.blockNum}</span>\n * <span className=\"line-range\">\n * Lines {block.startLineNum}-{block.endLineNum}\n * </span>\n * </div>\n * <div className=\"block-details\">\n * <span>Stream: {block.stream}</span>\n * <span>Lines: {block.lineCount}</span>\n * <span>Loaded: {block.lines.length}</span>\n * </div>\n * <div className=\"block-time\">\n * {block.startTime.toLocaleString()} - {block.endTime.toLocaleString()}\n * </div>\n * </div>\n * ))}\n * </div>\n * </div>\n * );\n * });\n * ```\n *\n * @group KOS Model\n * @category Device Logging\n * @interface\n *\n * @see {@link LogStreamModel} - Parent stream model that uses this container\n * @see {@link LogBlockModel} - Individual log blocks managed by this container\n * @see {@link LogBlockContainerOptions} - Configuration options for the container\n */\nexport type LogBlockContainerModel =\n PublicModelInterface<LogBlockContainerModelImpl>;\n\n/**\n * @ignore\n * @internal\n */\n@kosModel(MODEL_TYPE)\nexport class LogBlockContainerModelImpl\n implements IKosIdentifiable, IKosModelHolder<LogBlockModel>, IKosDataModel\n{\n id: string;\n private logger: KosContextLogger;\n @kosChild private _models: IKosModelContainer<LogBlockModel>;\n constructor(\n modelId: string,\n options: LogBlockContainerOptions,\n context: KosCreationContext\n ) {\n this.id = modelId;\n this.logger = context.logger;\n this._models = new KosModelContainer<LogBlockModel>({\n parentId: modelId,\n sortKey: \"blockNum\",\n });\n if (options) {\n // Assign options properties here.\n }\n }\n\n getModel(id: string) {\n return this._models.getModel(id);\n }\n get models() {\n return this._models;\n }\n get data() {\n return this._models.data;\n }\n\n addModel(model: LogBlockModel) {\n this._models.addModel(model);\n }\n\n removeModel(id: string) {\n this._models.removeModel(id);\n }\n // -------------------LIFECYCLE----------------------------\n\n async init(): Promise<void> {\n this.logger.debug(`initializing log-block-container container ${this.id}`);\n }\n\n async load(): Promise<void> {\n this.logger.debug(`loading log-block-container container ${this.id}`);\n }\n}\n","import { getQueryParams, KosLog } from \"../../core\";\n\nexport const getKosConnectionId = (): string | undefined => {\n const params = getQueryParams();\n const connId = (params as any)?.connId;\n const result = connId || (window as any)?.kosBridge?.(\"connId\");\n\n KosLog.debug(`getKosConnectionId: ${result}`);\n\n return result;\n};\n","import {\n KosLog,\n type ClientResponse,\n type DeepRequired,\n type ElementType,\n type ServiceResponse,\n} from \"../../../../core\";\nimport { getKosConnectionId } from \"../../../utils/get-kos-connection-id\";\n\nimport API, { type ApiPath, type KosApi } from \"../../../utils/service\";\nimport type { LogLinesType } from \"../../log-block\";\n\nconst log = KosLog.createLogger({\n name: \"log-stream-container-service\",\n group: \"Services\",\n});\n\nconst SERVICE_PATH: ApiPath = \"/api/kos/logs/node/{nodeId}/streams\";\nexport type LogStreamContainerClientResponse = ClientResponse<\n KosApi,\n typeof SERVICE_PATH,\n \"get\"\n>;\nexport type LogStreamContainerResponse = DeepRequired<\n ElementType<LogStreamContainerClientResponse>\n>;\n\n/**\n * @group KOS Model\n * @category Device Logging\n * Retrieves the initial list of log-stream-container data.\n */\nexport const getLogStreams = async (): Promise<\n ServiceResponse<LogStreamContainerClientResponse>\n> => {\n const destinationAddress = getKosConnectionId();\n log.debug(\"sending GET for log-stream-container\");\n return await API.get(\n SERVICE_PATH,\n {\n path: {\n nodeId: \"primary\",\n },\n },\n {\n destinationAddress,\n }\n );\n};\n\nexport const subscribeToLogStream = async (\n stream: string,\n nodeId = \"primary\"\n): Promise<void> => {\n const destinationAddress = getKosConnectionId();\n const _repsonse = await API.post(\n \"/api/kos/logs/node/{nodeId}/{stream}/subscribe\",\n {\n path: {\n nodeId: nodeId,\n stream,\n },\n },\n undefined,\n {\n destinationAddress,\n }\n );\n};\n\nexport const unsubscribeFromLogStream = async (\n stream: string\n): Promise<void> => {\n const destinationAddress = getKosConnectionId();\n const _repsonse = await API.post(\n \"/api/kos/logs/node/{nodeId}/{stream}/unsubscribe\",\n { path: { nodeId: \"primary\", stream } },\n undefined,\n {\n destinationAddress,\n }\n );\n};\n\nexport const createOverride = async (): Promise<void> => {\n const destinationAddress = getKosConnectionId();\n const _repsonse = await API.post(\n \"/api/kos/logs/overrides\",\n {},\n {\n level: \"WARN\",\n name: \"com.example\",\n nodeType: \"java\",\n type: \"package\",\n },\n {\n destinationAddress,\n }\n );\n};\n\nconst SERVICE_BLOCKS_PATH: ApiPath =\n \"/api/kos/logs/node/{nodeId}/{stream}/blocks\";\nexport type LogStreamBlocksClientResponse = ClientResponse<\n KosApi,\n typeof SERVICE_BLOCKS_PATH,\n \"get\"\n>;\n\nexport const getLogStreamBlocks = async (\n stream: string\n): Promise<ServiceResponse<LogStreamBlocksClientResponse>> => {\n const destinationAddress = getKosConnectionId();\n const response = await API.get(\n \"/api/kos/logs/node/{nodeId}/{stream}/blocks\",\n {\n path: {\n nodeId: \"primary\",\n stream,\n },\n },\n {\n destinationAddress,\n }\n );\n return response;\n};\n\nexport const getLogStreamBlock = async (\n stream: string,\n blockId: number\n): Promise<ServiceResponse<LogLinesType>> => {\n const destinationAddress = getKosConnectionId();\n const response = await API.get(\n \"/api/kos/logs/node/{nodeId}/{stream}/blocks/{blockId}\",\n {\n path: {\n nodeId: \"primary\",\n stream,\n blockId,\n },\n },\n {\n destinationAddress,\n }\n );\n return response as ServiceResponse<LogLinesType>;\n};\n","import { kosModel } from \"../../../core/core/decorators\";\nimport type {\n IKosDataModel,\n KosContextLogger,\n KosCreationContext,\n} from \"../../../core/core/kosModel\";\nimport type { IKosIdentifiable } from \"../../../core/core/types\";\nimport type { PublicModelInterface } from \"../../../core/types\";\nimport { getLogStreamBlock } from \"../log-stream/services\";\n\nimport type { LogBlockOptions } from \"./types\";\n\nexport const MODEL_TYPE = \"log-block-model\";\n\n/**\n * Log Block Model - Individual log data block management within streaming log systems.\n *\n * This model represents a single block of log data within a LogStreamModel, providing efficient\n * memory management and organized access to log lines. Log blocks are the fundamental storage\n * units that enable high-performance log streaming by breaking large log streams into\n * manageable, sequential segments with precise line numbering and timing information.\n *\n * ## Key Features\n * - **Block-based Storage** - Efficient memory usage through segmented log storage\n * - **Line Management** - Precise line numbering with start/end tracking\n * - **Time-based Organization** - Temporal ordering with start and end timestamps\n * - **Dynamic Loading** - On-demand synchronization of log lines from source\n * - **Incremental Updates** - Add new lines without full reload\n * - **Stream Integration** - Seamless integration with LogStreamModel containers\n *\n * ## Architecture Relationship\n * LogBlock works as a component within the broader log streaming architecture:\n * - **LogStreamModel** contains multiple LogBlockModels via LogBlockContainerModel\n * - **LogBlockContainerModel** manages and sorts blocks by block number\n * - **LogBlockModel** stores the actual log lines and metadata for a specific segment\n * - This design enables efficient memory usage and fast access to recent log data\n *\n * ## Common Use Cases\n * - **Memory-efficient Log Storage** - Break large log streams into manageable blocks\n * - **Sequential Log Access** - Navigate through log history by block\n * - **Selective Loading** - Load only needed blocks for performance\n * - **Log Line Management** - Add, retrieve, and manage individual log entries\n * - **Time-based Log Analysis** - Filter and analyze logs by time ranges\n * - **Stream Synchronization** - Keep log blocks synchronized with source streams\n *\n * @interface\n * @example Basic Usage\n * ```typescript\n * // Typically accessed through LogStreamModel, not created directly\n * const logStream = LogStream.instance('app-logs')\n * .options({ name: 'application-logs', nodeId: 'primary' })\n * .build();\n *\n * await logStream.load();\n *\n * // Access blocks within the stream\n * const blocks = logStream.blocks;\n * const currentBlock = logStream.currentBlock;\n *\n * if (currentBlock) {\n * console.log(`Block ${currentBlock.blockNum}`);\n * console.log(`Lines: ${currentBlock.startLineNum}-${currentBlock.endLineNum}`);\n * console.log(`Time range: ${currentBlock.startTime} to ${currentBlock.endTime}`);\n * console.log(`Line count: ${currentBlock.lineCount}`);\n * }\n * ```\n *\n * @example Block Line Management\n * ```typescript\n * // Access through log stream\n * const logStream = LogStream.instance('system-logs').build();\n * const block = logStream.currentBlock;\n *\n * if (block) {\n * // Get current lines\n * console.log(`Block has ${block.lines.length} loaded lines`);\n *\n * // Add new lines (typically done automatically by stream)\n * block.addLines(['New log entry 1', 'New log entry 2']);\n *\n * // Sync with remote source\n * await block.syncLines();\n *\n * // Process lines\n * block.lines.forEach((line, index) => {\n * const globalLineNum = block.startLineNum + index;\n * console.log(`Line ${globalLineNum}: ${line}`);\n * });\n * }\n * ```\n *\n * @example Block Analysis and Filtering\n * ```typescript\n * // Analyze blocks within a stream\n * const logStream = LogStream.instance('error-logs').build();\n * await logStream.load();\n *\n * // Find blocks within a time range\n * const startTime = new Date('2024-01-01T00:00:00Z');\n * const endTime = new Date('2024-01-01T23:59:59Z');\n *\n * const blocksInRange = logStream.blocks.filter(block =>\n * block.startTime >= startTime && block.endTime <= endTime\n * );\n *\n * console.log(`Found ${blocksInRange.length} blocks in date range`);\n *\n * // Process error logs from specific blocks\n * for (const block of blocksInRange) {\n * await block.syncLines(); // Ensure lines are loaded\n *\n * const errorLines = block.lines\n * .map((line, index) => ({ line, lineNum: block.startLineNum + index }))\n * .filter(({ line }) => line.includes('ERROR'));\n *\n * if (errorLines.length > 0) {\n * console.log(`Block ${block.blockNum} has ${errorLines.length} errors`);\n * errorLines.forEach(({ line, lineNum }) => {\n * console.log(`Line ${lineNum}: ${line}`);\n * });\n * }\n * }\n * ```\n *\n * @example Block Container Integration\n * ```typescript\n * // Access blocks through their container\n * const logStream = LogStream.instance('debug-logs').build();\n * const blockContainer = logStream.blocks; // This is a LogBlockContainerModel\n *\n * // Blocks are automatically sorted by block number\n * const sortedBlocks = blockContainer.data;\n * console.log(`Stream has ${sortedBlocks.length} blocks`);\n *\n * // Get specific block by ID\n * const blockId = 'debug-logs-block-5';\n * const specificBlock = blockContainer.getModel(blockId);\n *\n * if (specificBlock) {\n * console.log(`Block ${specificBlock.blockNum} loaded`);\n * await specificBlock.syncLines();\n * }\n *\n * // Add new block to container (typically done automatically)\n * const newBlockOptions: LogBlockOptions = {\n * nodeId: 'primary',\n * stream: 'debug-logs',\n * blockNum: 10,\n * startLineNum: 1000,\n * endLineNum: 1099,\n * startTime: new Date(),\n * endTime: new Date(Date.now() + 60000),\n * lineCount: 100\n * };\n *\n * const newBlock = LogBlock.instance('debug-logs-block-10')\n * .options(newBlockOptions)\n * .build();\n *\n * blockContainer.addModel(newBlock);\n * ```\n *\n * @example Block Update and Synchronization\n * ```typescript\n * const block = logStream.currentBlock;\n *\n * if (block) {\n * // Update block metadata (typically done by stream management)\n * const updatedOptions: LogBlockOptions = {\n * ...block,\n * endLineNum: block.endLineNum + 50,\n * endTime: new Date(),\n * lineCount: block.lineCount + 50\n * };\n *\n * block.updateModel(updatedOptions);\n *\n * // Sync to get new lines\n * await block.syncLines();\n *\n * console.log(`Block now has ${block.lines.length} lines loaded`);\n * console.log(`Updated end time: ${block.endTime}`);\n * }\n * ```\n *\n * @group KOS Model\n * @category Device Logging\n * @useDeclaredType\n *\n * @see {@link LogStreamModel} - Parent stream model that contains log blocks\n * @see {@link LogBlockContainerModel} - Container that manages multiple log blocks\n * @see {@link LogBlockOptions} - Configuration options for log block instances\n * @see {@link LogBlockType} - Type definition for block data exchange\n * @see {@link LogLinesType} - Type definition for line data with block metadata\n */\nexport type LogBlockModel = PublicModelInterface<LogBlockModelImpl>;\n\n/**\n * @ignore\n * @internal\n */\n@kosModel(MODEL_TYPE)\nexport class LogBlockModelImpl implements IKosDataModel, IKosIdentifiable {\n id: string;\n private logger: KosContextLogger;\n nodeId: string;\n stream: string;\n blockNum: number;\n startLineNum: number;\n endLineNum: number;\n startTime: Date;\n endTime: Date;\n lineCount: number;\n lines: string[];\n\n inc: number;\n constructor(\n modelId: string,\n options: LogBlockOptions,\n context: KosCreationContext\n ) {\n this.id = modelId;\n this.logger = context.logger;\n\n this.nodeId = options.nodeId;\n this.stream = options.stream;\n this.blockNum = options.blockNum;\n this.startLineNum = options.startLineNum;\n this.endLineNum = options.endLineNum;\n this.startTime = options.startTime;\n this.endTime = options.endTime;\n this.lineCount = options.lineCount;\n this.lines = [];\n this.inc = 0;\n }\n\n async syncLines(): Promise<void> {\n const [error, blockData] = await getLogStreamBlock(\n this.stream,\n this.blockNum\n );\n\n if (error) {\n this.logger.error(`Failed to get log block ${this.blockNum}`);\n return;\n }\n if (blockData) {\n this.addLines(blockData.lines, true);\n }\n }\n\n updateModel(options: LogBlockOptions): void {\n this.startLineNum = options.startLineNum;\n this.endLineNum = options.endLineNum;\n this.startTime = options.startTime;\n this.endTime = options.endTime;\n this.lineCount = options.lineCount;\n }\n\n addLines(lines: string[], replace?: boolean): void {\n const baseLines = replace ? [] : this.lines;\n\n this.lines = [...baseLines, ...lines];\n this.inc += 1;\n }\n\n // -------------------LIFECYCLE----------------------------\n\n async init(): Promise<void> {\n this.logger.debug(`initializing log-block ${this.id}`);\n }\n\n async load(): Promise<void> {\n this.logger.debug(`loading log-block ${this.id}`);\n }\n}\n","import { KosModelRegistrationFactory } from \"../../../core/core/registration\";\nimport type { LogBlockModel } from \"./log-block-model\";\nimport { LogBlockModelImpl, MODEL_TYPE } from \"./log-block-model\";\nimport type { LogBlockOptions } from \"./types\";\n\n/**\n * # LogBlock\n *\n * The registration bean includes convenience methods for creating and working with LogBlockModel instances.\n *\n * ## type\n * The type property is a string that identifies the model type.\n * The type is used to identify the model type in the model registry and to narrow down the model type in type predicates. It's most frequently\n * used when declaring dependencies on models.\n *\n * @example\n * ```typescript\n *\n * @kosDependency({modelType: LogBlock.type, id: \"logBlockId\"})\n * private logBlockModel: LogBlockModel;\n * ```\n *\n *\n * ## factory\n *\n * The factory method creates a factory function that can be used to create new LogBlockModel instances.\n *\n \n * The factory function is a curried function that takes the model id as the first argument and the options as the second argument.\n *\n * If a model with the specified id already exists, the factory function will return the existing model. The options will be ignored\n * in this case and the existing model will be returned in its current state.\n *\n * @example\n * ```typescript\n * const model = LogBlock.factory(\"logBlockId\")({\n * // Add option data\n * });\n * ```\n \n\n *\n * ## predicate\n *\n * [Typescript type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) function that will identify and narrow down a model to a LogBlockModel.\n *\n * @example\n * ```typescript\n *\n * const model: IKosDataModel = ...; // some model\n *\n * if (LogBlock.predicate(model)) {\n * // if the function evaluates to true, the model is narrowed down to LogBlockModel\n * // and the compiler will know that the model has the LogBlockModel interface\n * model.updateAvailability(false);\n * }\n * ```\n *\n * ## registration\n *\n * The registration property is an object that can be used to simplify registration of the model with the model registry. The registration object\n * can be spread into the model registration and provides all of the required information to register the model implementation class against the model type.\n *\n *\n * @example\n *\n * In an application registration file you can declare the model registration as follows:\n *\n * **registration.ts**\n * ```typescript\n * import { LogBlock } from \"@kos-ui/project-models\";\n * import { KosModelRegistry } from \"@kosdev-code/kos-dispense-sdk\";\n *\n * import { initKosProvider } from \"@kosdev-code/kos-ui-sdk\";\n *\n * KosModelRegistry.dispense\n * .models()\n * .model(LogBlock);\n * ```\n *\n * ## registration.singleton\n \n * The logBlock model is NOT a singleton model. This means that each time the factory function is called with a unique ID, a new model instance will be created.\n * If the factory function is called with an ID that already exists, the existing model will be returned.\n \n * */\nexport const LogBlock = new KosModelRegistrationFactory<\n LogBlockModel,\n LogBlockOptions\n>({\n class: LogBlockModelImpl,\n type: MODEL_TYPE,\n});\n","import { KosModelRegistrationFactory } from \"../../../core\";\nimport type { LogBlockContainerModel } from \"./log-block-container-model\";\nimport {\n LogBlockContainerModelImpl,\n MODEL_TYPE,\n} from \"./log-block-container-model\";\nimport { LogBlock } from \"./log-block-registration\";\nimport type { LogBlockContainerOptions } from \"./types\";\n\n/**\n * # LogBlockContainer\n *\n * The registration bean includes convenience methods for creating and working with LogBlockContainerModel instances.\n *\n * ## type\n * The type property is a string that identifies the model type.\n * The type is used to identify the model type in the model registry and to narrow down the model type in type predicates. It's most frequently\n * used when declaring dependencies on models.\n *\n * @example\n * ```typescript\n *\n * @kosDependency({modelType: LogBlockContainer.type, id: \"logBlockContainerId\"})\n * private logBlockContainerModel: LogBlockContainerModel;\n * ```\n *\n *\n * ## factory\n *\n * The factory method creates a factory function that can be used to create new LogBlockContainerModel instances.\n *\n \n * As this is a singleton model, the factory function accepts the model options as its argument.\n *\n * If a model with the same model type already exists, the factory function will return the existing model. The options will be ignored\n * in this case and the existing model will be returned in its current state.\n *\n * @example\n * ```typescript\n * const model = LogBlockContainer.factory({\n * // Add option data\n * });\n * ```\n \n\n *\n * ## predicate\n *\n * [Typescript type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) function that will identify and narrow down a model to a LogBlockContainerModel.\n *\n * @example\n * ```typescript\n *\n * const model: IKosDataModel = ...; // some model\n *\n * if (LogBlockContainer.predicate(model)) {\n * // if the function evaluates to true, the model is narrowed down to LogBlockContainerModel\n * // and the compiler will know that the model has the LogBlockContainerModel interface\n * model.updateAvailability(false);\n * }\n * ```\n *\n * ## registration\n *\n * The registration property is an object that can be used to simplify registration of the model with the model registry. The registration object\n * can be spread into the model registration and provides all of the required information to register the model implementation class against the model type.\n *\n *\n * @example\n *\n * In an application registration file you can declare the model registration as follows:\n *\n * **registration.ts**\n * ```typescript\n * import { LogBlockContainer } from \"@kosdev-code/kos-ui-sdk\";\n * ...\n * import { ExtensionManager, IKosRegistry } from \"@kosdev-code/kos-ui-sdk\";\n * export const kosModels: IKosRegistry[\"models\"] = {\n * ...LogBlockContainer.registration,\n * };\n * ```\n *\n * ## registration.singleton\n \n * The logBlockContainer model is a singleton model. This means that each time the factory function is called , the same instance will be returned.\n * If the model does not yet exist, it will be created passing in the provided options to initialize it.\n *\n * Singleton models don't require an ID as they will use the model type as their ID to guarantee uniqueness throughout the system.\n \n * */\nexport const LogBlockContainer = new KosModelRegistrationFactory<\n LogBlockContainerModel,\n LogBlockContainerOptions\n>({\n class: LogBlockContainerModelImpl,\n type: MODEL_TYPE,\n});\n\nLogBlockContainer.addRelatedModel(LogBlock);\n","import { kosEffect } from \"../../../core\";\nimport { kosChild, kosModel } from \"../../../core/core/decorators\";\nimport type {\n IKosDataModel,\n IKosVisitor,\n KosContextLogger,\n KosCreationContext,\n} from \"../../../core/core/kosModel\";\nimport type { IKosIdentifiable } from \"../../../core/core/types\";\nimport type { PublicModelInterface } from \"../../../core/types\";\nimport {\n LogBlock,\n LogBlockContainer,\n type LogBlockContainerModel,\n type LogBlockOptions,\n type LogBlockType,\n} from \"../log-block\";\nimport {\n getLogStreamBlocks,\n subscribeToLogStream,\n unsubscribeFromLogStream,\n} from \"./services\";\n\nimport type { LogStreamOptions } from \"./types\";\n\nexport const MODEL_TYPE = \"log-stream-model\";\n\n/**\n * Log Stream Model - Real-time streaming log viewer with efficient block-based management and async iteration.\n *\n * This model provides high-performance log streaming capabilities for monitoring KOS device logs in real-time.\n * It organizes log data into efficient blocks for memory management and provides async iterator support\n * for continuous log consumption. Essential for debugging, monitoring, and troubleshooting KOS applications.\n *\n * ## Key Features\n * - **Real-time Log Streaming** - Live log updates as they are generated on the device\n * - **Block-based Management** - Efficient memory usage through log block organization\n * - **Async Iterator Support** - Stream logs using modern async/await patterns\n * - **Subscription Control** - Subscribe/unsubscribe to specific log streams\n * - **Line Number Tracking** - Maintains accurate line numbering across blocks\n * - **Multi-stream Support** - Handle multiple log streams simultaneously through container model\n *\n * ## Common Use Cases\n * - **Development Debugging** - Monitor application logs during development\n * - **Production Monitoring** - Track system health and errors in deployed applications\n * - **Troubleshooting** - Analyze log patterns to diagnose issues\n * - **Log Analysis** - Process log streams for metrics and insights\n * - **Real-time Dashboards** - Display live log feeds in monitoring interfaces\n * - **Automated Log Processing** - Stream logs to external analysis tools\n *\n * @interface\n * @example Basic Usage\n * ```typescript\n * const logStream = LogStream.instance('application-logs')\n * .options({ name: 'application-logs', nodeId: 'primary' })\n * .build();\n *\n * await logStream.subscribe();\n * const iterator = logStream.start();\n * for await (const logLine of iterator) {\n * console.log(`[LOG] ${logLine}`);\n * }\n * ```\n *\n * @group KOS Model\n * @category Device Logging\n * @useDeclaredType\n *\n * @see {@link LogStreamOptions} - Configuration options for log stream instances\n * @see {@link LogStreamContainerModel} - Container model for managing multiple streams\n * @see {@link LogBlockModel} - Individual log block management within streams\n */\nexport type LogStreamModel = PublicModelInterface<LogStreamModelImpl>;\n/**\n * @ignore\n * @internal\n */\n@kosModel(MODEL_TYPE)\nexport class LogStreamModelImpl implements IKosDataModel, IKosIdentifiable {\n id: string;\n private logger: KosContextLogger;\n nodeId: string;\n @kosChild\n private _blocks: LogBlockContainerModel;\n name: string;\n currentBlockId: string;\n isResetting: boolean;\n constructor(\n modelId: string,\n options: LogStreamOptions,\n context: KosCreationContext\n ) {\n this.id = modelId;\n this.logger = context.logger;\n this.currentBlockId = \"\";\n this.name = options.name;\n this.nodeId = options.nodeId;\n this.isResetting = true;\n this._blocks = LogBlockContainer.instance(`${modelId}-blocks`)\n .options({})\n .build();\n }\n\n get firstLineNum() {\n const firstBlock = this.populated[0];\n return firstBlock ? firstBlock.startLineNum : 0;\n }\n get currentBlock() {\n const currentBlockId = this.currentBlockId;\n const block = this._blocks.getModel(currentBlockId);\n return block;\n }\n\n get populated() {\n return this._blocks.data.filter((block) => block.lines.length > 0);\n }\n get blocks() {\n return this._blocks.data;\n }\n\n get totalLineCount() {\n return this.populated.reduce((acc, block) => acc + block.lineCount, 0);\n }\n\n accept(visitor: IKosVisitor<IKosDataModel>) {\n visitor.visit(this);\n }\n\n updateBlock(blockData: LogBlockType) {\n let block = this._blocks.models.getModel(\n `${blockData.stream}-block-${blockData.blockNum}`\n );\n const options: LogBlockOptions = {\n nodeId: blockData.nodeId,\n blockNum: blockData.blockNum,\n endLineNum: blockData.endLineNum,\n lineCount: blockData.lineCount,\n startLineNum: blockData.startLineNum,\n stream: this.name,\n endTime: new Date(blockData.endTime),\n startTime: new Date(blockData.startTime),\n };\n if (!block) {\n block = LogBlock.instance(\n `${blockData.stream}-block-${blockData.blockNum}`\n )\n .options(options)\n .build();\n this._blocks.addModel(block);\n }\n if (block) {\n block.updateModel(options);\n }\n if (\n !this.currentBlock ||\n blockData.blockNum >= this.currentBlock?.blockNum\n ) {\n this.currentBlockId = `${blockData.stream}-block-${blockData.blockNum}`;\n }\n }\n addBlock(blockData: LogBlockType) {\n const block = LogBlock.instance(\n `${blockData.stream}-block-${blockData.blockNum}`\n )\n .options({\n nodeId: blockData.nodeId,\n blockNum: blockData.blockNum,\n endLineNum: blockData.endLineNum,\n lineCount: blockData.lineCount,\n startLineNum: blockData.startLineNum,\n stream: this.name,\n endTime: new Date(blockData.endTime),\n startTime: new Date(blockData.startTime),\n })\n .build();\n this._blocks.addModel(block);\n if (\n !this.currentBlock ||\n blockData.blockNum >= this.currentBlock?.blockNum\n ) {\n this.currentBlockId = `${blockData.stream}-block-${blockData.blockNum}`;\n }\n }\n\n removeBlock(blockNum: number) {\n this._blocks.models.removeModel(`${this.name}-block-${blockNum}`);\n }\n async subscribe(): Promise<void> {\n await subscribeToLogStream(this.name);\n }\n\n async unsubscribe(): Promise<void> {\n await unsubscribeFromLogStream(this.name);\n }\n // -------------------LIFECYCLE----------------------------\n\n async reset(): Promise<void> {\n this.isResetting = true;\n if (this.populated.length > 0) {\n return;\n }\n this.logger.debug(`resetting log-stream ${this.id}`);\n for (const block of this._blocks.models.data) {\n block.lines = [];\n }\n\n const lastBlock = this._blocks.data[this._blocks.data.length - 1];\n if (lastBlock) {\n await lastBlock.syncLines();\n }\n\n this.isResetting = false;\n }\n /**\n * @internal\n */\n async init(): Promise<void> {\n this.logger.debug(`initializing log-stream ${this.id}`);\n }\n\n /**\n * @internal\n */\n async load(): Promise<void> {\n this.logger.debug(`loading log-stream ${this.id}`);\n\n const [error, previousBlocks] = await getLogStreamBlocks(this.name);\n if (error) {\n this.logger.error(`Error loading log stream: ${error}`);\n return;\n }\n if (previousBlocks) {\n for (const block of previousBlocks) {\n this.addBlock(block as LogBlockType);\n }\n }\n\n const lastBlock = this._blocks.data[this._blocks.data.length - 1];\n if (lastBlock) {\n await lastBlock.syncLines();\n }\n if (this._blocks.data.length > 1) {\n const secondLastBlock = this._blocks.data[this._blocks.data.length - 2];\n if (secondLastBlock) {\n await secondLastBlock.syncLines();\n }\n }\n }\n private generatorInstance?: AsyncGenerator<string, void, void>;\n private shouldStop = false;\n\n start() {\n this.shouldStop = false;\n this.generatorInstance = this.streamLogs();\n return this.generatorInstance;\n }\n\n stop() {\n this.shouldStop = true;\n this.generatorInstance?.next();\n console.log(\"Requested generator stop.\");\n }\n async *streamLogs(): AsyncGenerator<string, void, void> {\n const queue: string[] = [];\n let resolveQueue: (() => void) | null = null;\n let currentIndex = 0;\n let currentBlockId: string | undefined = this.currentBlockId;\n // reaction to listen for new log lines\n const disposer = kosEffect(\n () => {\n const block = this.currentBlock;\n return block\n ? {\n blockId: this.currentBlockId,\n lineCount: block.lines.length,\n }\n : null;\n }, // Track changes in lines\n (prev) => {\n const latestBlock = this.currentBlock;\n\n if (latestBlock) {\n if (currentBlockId !== prev?.blockId) {\n currentBlockId = prev?.blockId;\n currentIndex = 0;\n queue.push(...latestBlock.lines);\n } else {\n const newLines = latestBlock.lines.slice(currentIndex);\n\n queue.push(...newLines);\n currentIndex += newLines.length;\n }\n }\n\n // Wake up the generator if it was waiting\n if (resolveQueue) {\n resolveQueue();\n resolveQueue = null;\n }\n },\n { fireImmediately: true }\n );\n\n try {\n // Yield all existing lines first\n for (const block of this.populated.filter(\n (block) => block !== this.currentBlock\n )) {\n for (const line of block.lines) {\n yield line;\n }\n }\n\n // Wait for new lines and yield them as they arrive\n while (true) {\n if (queue.length === 0) {\n await new Promise<void>((resolve) => (resolveQueue = resolve));\n }\n while (queue.length > 0) {\n yield queue.shift()!;\n }\n }\n } finally {\n disposer(); // Cleanup reaction when generator is stopped\n }\n }\n}\n","import { KosModelRegistrationFactory } from \"../../../core/core/registration\";\nimport type { LogStreamOptions } from \"./types\";\nimport { LogStreamModelImpl, MODEL_TYPE } from \"./log-stream-model\";\nimport type { LogStreamModel } from \"./log-stream-model\";\n\n/**\n * # LogStream\n *\n * The registration bean includes convenience methods for creating and working with LogStreamModel instances.\n *\n * ## type\n * The type property is a string that identifies the model type.\n * The type is used to identify the model type in the model registry and to narrow down the model type in type predicates. It's most frequently\n * used when declaring dependencies on models.\n *\n * @example\n * ```typescript\n *\n * @kosDependency({modelType: LogStream.type, id: \"logStreamId\"})\n * private logStreamModel: LogStreamModel;\n * ```\n *\n *\n * ## factory\n *\n * The factory method creates a factory function that can be used to create new LogStreamModel instances.\n *\n \n * The factory function is a curried function that takes the model id as the first argument and the options as the second argument.\n *\n * If a model with the specified id already exists, the factory function will return the existing model. The options will be ignored\n * in this case and the existing model will be returned in its current state.\n *\n * @example\n * ```typescript\n * const model = LogStream.factory(\"logStreamId\")({\n * // Add option data\n * });\n * ```\n \n\n *\n * ## predicate\n *\n * [Typescript type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) function that will identify and narrow down a model to a LogStreamModel.\n *\n * @example\n * ```typescript\n *\n * const model: IKosDataModel = ...; // some model\n *\n * if (LogStream.predicate(model)) {\n * // if the function evaluates to true, the model is narrowed down to LogStreamModel\n * // and the compiler will know that the model has the LogStreamModel interface\n * model.updateAvailability(false);\n * }\n * ```\n *\n * ## registration\n *\n * The registration property is an object that can be used to simplify registration of the model with the model registry. The registration object\n * can be spread into the model registration and provides all of the required information to register the model implementation class against the model type.\n *\n *\n * @example\n *\n * In an application registration file you can declare the model registration as follows:\n *\n * **registration.ts**\n * ```typescript\n * import { LogStream } from \"@kos-ui/project-models\";\n * import { KosModelRegistry } from \"@kosdev-code/kos-dispense-sdk\";\n *\n * import { initKosProvider } from \"@kosdev-code/kos-ui-sdk\";\n *\n * KosModelRegistry.dispense\n * .models()\n * .model(LogStream);\n * ```\n *\n * ## registration.singleton\n \n * The logStream model is NOT a singleton model. This means that each time the factory function is called with a unique ID, a new model instance will be created.\n * If the factory function is called with an ID that already exists, the existing model will be returned.\n \n * */\nexport const LogStream = new KosModelRegistrationFactory<\n LogStreamModel,\n LogStreamOptions\n>({\n class: LogStreamModelImpl,\n type: MODEL_TYPE,\n});\n","import {\n kosChild,\n kosModel,\n kosTopicHandler,\n} from \"../../../core/core/decorators\";\nimport {\n KosModelContainer,\n type IKosModelContainer,\n} from \"../../../core/core/kos-container-model\";\nimport type {\n IKosDataModel,\n KosContextLogger,\n KosCreationContext,\n} from \"../../../core/core/kosModel\";\nimport type { IKosIdentifiable } from \"../../../core/core/types\";\nimport type {\n IKosModelHolder,\n PublicModelInterface,\n} from \"../../../core/types\";\nimport type { LogBlockType, LogLinesType } from \"../log-block\";\n\nimport type { LogStreamModel } from \"./log-stream-model\";\nimport { LogStream } from \"./log-stream-registration\";\nimport { getLogStreams } from \"./services\";\nimport type { LogStreamContainerOptions } from \"./types\";\n\nexport const MODEL_TYPE = \"log-stream-container-model\";\n\n/**\n * Log Stream Container Model - Manages multiple log streams with real-time topic-based synchronization.\n *\n * This container model manages multiple LogStreamModel instances and handles real-time log events\n * from the KOS system. It provides centralized management of log streams, automatic stream discovery,\n * and coordinated event handling for efficient log processing across multiple sources.\n *\n * ## Topic-Based Reactivity\n * The container listens to these KOS topics for real-time log management:\n * - **`/kos/logs/subscription/addBlock/*`** - Fired when new log blocks are created\n * - **`/kos/logs/subscription/updateBlock/*`** - Fired when existing log blocks are updated\n * - **`/kos/logs/subscription/removeBlock/*`** - Fired when log blocks are removed\n * - **`/kos/logs/subscription/lines/*`** - Fired when new log lines are added to blocks\n * - **`/kos/logs/streams/add/*`** - Fired when new log streams are discovered\n *\n * ## Key Features\n * - **Multi-stream Management** - Handle multiple log streams simultaneously\n * - **Automatic Stream Discovery** - Automatically add new streams as they become available\n * - **Topic-based Synchronization** - Real-time updates via KOS event system\n * - **Stream Selection** - Track currently selected stream for UI purposes\n * - **Block Management** - Coordinate block updates across all managed streams\n *\n * ## Common Use Cases\n * - **Log Dashboard** - Central management of multiple log sources\n * - **System Monitoring** - Monitor logs from all system components\n * - **Debugging Interface** - Switch between different log streams during troubleshooting\n * - **Log Aggregation** - Collect and manage logs from distributed sources\n *\n * @example Basic Usage\n * ```typescript\n * const logContainer = LogStreamContainer.instance('main-logger')\n * .options({})\n * .build();\n *\n * // Subscribe to and manage multiple streams\n * await logContainer.subscribeToLogStream('application-logs');\n * const appStream = logContainer.getModel('application-logs');\n * logContainer.updateSelectedStream(appStream);\n * ```\n *\n * @group KOS Model\n * @category Device Logging\n * @interface\n * @useDeclaredType\n *\n * @see {@link LogStreamModel} - Individual log stream management\n * @see {@link LogStreamContainerOptions} - Configuration options for the container\n */\nexport type LogStreamContainerModel =\n PublicModelInterface<LogStreamContainerModelImpl>;\n\nconst TOPIC_ADD_BLOCK = \"/kos/logs/subscription/addBlock/*\";\nconst TOPIC_UPDATE_BLOCK = \"/kos/logs/subscription/updateBlock/*\";\nconst TOPIC_REMOVE_BLOCK = \"/kos/logs/subscription/removeBlock/*\";\nconst TOPIC_LOG_LINES = \"/kos/logs/subscription/lines/*\";\nconst TOPIC_ADD_STREAM = \"/kos/logs/streams/add/*\";\n\n/**\n * @ignore\n * @internal\n */\n@kosModel(MODEL_TYPE)\nexport class LogStreamContainerModelImpl\n implements IKosIdentifiable, IKosModelHolder<LogStreamModel>, IKosDataModel\n{\n /** Unique identifier for the container model instance */\n id: string;\n /** Context logger for debugging log stream operations */\n private logger: KosContextLogger;\n /** Currently selected log stream for UI display purposes */\n selectedStream?: LogStreamModel;\n /** Container for managing LogStream model instances */\n @kosChild private _models: IKosModelContainer<LogStreamModel>;\n constructor(\n modelId: string,\n options: LogStreamContainerOptions,\n context: KosCreationContext\n ) {\n this.id = modelId;\n this.logger = context.logger;\n this._models = new KosModelContainer<LogStreamModel>({ parentId: modelId });\n this.selectedStream = undefined;\n if (options) {\n // Assign options properties here.\n }\n }\n\n getModel(id: string) {\n return this._models.getModel(id);\n }\n get models() {\n return this._models;\n }\n get data() {\n return this._models.data;\n }\n\n updateModel(_options: LogStreamContainerOptions): void {\n // Update model properties here.\n }\n\n addModel(model: LogStreamModel) {\n this._models.addModel(model);\n }\n\n removeModel(id: string) {\n this._models.removeModel(id);\n }\n // -------------------LIFECYCLE----------------------------\n\n updateSelectedStream(stream?: LogStreamModel) {\n this.selectedStream = stream;\n }\n\n @kosTopicHandler({\n topic: [TOPIC_ADD_STREAM],\n websocket: true,\n })\n handleStreamAdded(data: { stream: string }) {\n this.logger.debug(`Received topic: ${TOPIC_ADD_STREAM}`);\n const streamName = data.stream;\n const logStream = LogStream.instance(streamName)\n .options({\n name: streamName,\n nodeId: \"primary\",\n })\n .build();\n this.addModel(logStream);\n }\n\n @kosTopicHandler({\n topic: [TOPIC_ADD_BLOCK],\n websocket: true,\n })\n handleAddBlock(data: LogBlockType, payload) {\n this.logger.debug(`Received topic: ${payload.headers.topic}`);\n const stream = data.stream;\n const logStream = this.models.getModel(stream);\n if (logStream) {\n logStream.addBlock(data);\n }\n }\n\n @kosTopicHandler({\n topic: [TOPIC_REMOVE_BLOCK],\n websocket: true,\n })\n handleRemoveBlock(data: LogBlockType, payload) {\n this.logger.debug(`Received topic: ${payload.headers.topic}`);\n const stream = data.stream;\n const logStream = this.models.getModel(stream);\n if (logStream) {\n logStream.removeBlock(data.blockNum);\n }\n }\n\n @kosTopicHandler({\n topic: [TOPIC_UPDATE_BLOCK],\n websocket: true,\n })\n handleUpdateBlock(data: LogBlockType, payload) {\n this.logger.debug(`Received topic: ${payload.headers.topic}`);\n const stream = data.stream;\n const logStream = this.models.getModel(stream);\n if (logStream) {\n logStream.updateBlock(data);\n }\n }\n\n @kosTopicHandler({\n topic: [TOPIC_LOG_LINES],\n websocket: true,\n })\n handleLogLine(data: LogLinesType, payload) {\n this.logger.debug(`Received topic: ${payload.headers.topic}`);\n const stream = data.stream;\n const logStream = this.models.getModel(stream);\n if (logStream) {\n logStream.currentBlock?.addLines(data.lines);\n }\n }\n /**\n * @internal\n */\n async init(): Promise<void> {\n this.logger.debug(`initializing log-stream-container container ${this.id}`);\n }\n\n async subscribeToLogStream(stream: string): Promise<void> {\n const logStream = LogStream.instance(stream)\n .options({\n name: stream,\n nodeId: \"primary\",\n })\n .build();\n this.addModel(logStream);\n await logStream.subscribe();\n }\n\n /**\n * @internal\n */\n async load(): Promise<void> {\n this.logger.debug(`loading log-stream-container container ${this.id}`);\n\n const [error, streams] = await getLogStreams();\n if (error) {\n this.logger.error(`Error loading log-streams: ${error}`);\n return;\n }\n\n if (streams) {\n streams.forEach((stream) => {\n const logStream = LogStream.instance(stream)\n .options({\n name: stream,\n nodeId: \"primary\",\n })\n .build();\n this.addModel(logStream);\n });\n }\n }\n}\n","import { SingletonKosModelRegistrationFactory } from \"../../../core\";\nimport { LogBlock, LogBlockContainer } from \"../log-block\";\nimport type { LogStreamContainerModel } from \"./log-stream-container-model\";\nimport {\n LogStreamContainerModelImpl,\n MODEL_TYPE,\n} from \"./log-stream-container-model\";\nimport { LogStream } from \"./log-stream-registration\";\nimport type { LogStreamContainerOptions } from \"./types\";\n\n/**\n * # LogStreamContainer\n *\n * The registration bean includes convenience methods for creating and working with LogStreamContainerModel instances.\n *\n * ## type\n * The type property is a string that identifies the model type.\n * The type is used to identify the model type in the model registry and to narrow down the model type in type predicates. It's most frequently\n * used when declaring dependencies on models.\n *\n * @example\n * ```typescript\n *\n * @kosDependency({modelType: LogStreamContainer.type, id: \"logStreamContainerId\"})\n * private logStreamContainerModel: LogStreamContainerModel;\n * ```\n *\n *\n * ## factory\n *\n * The factory method creates a factory function that can be used to create new LogStreamContainerModel instances.\n *\n \n * As this is a singleton model, the factory function accepts the model options as its argument.\n *\n * If a model with the same model type already exists, the factory function will return the existing model. The options will be ignored\n * in this case and the existing model will be returned in its current state.\n *\n * @example\n * ```typescript\n * const model = LogStreamContainer.factory({\n * // Add option data\n * });\n * ```\n \n\n *\n * ## predicate\n *\n * [Typescript type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) function that will identify and narrow down a model to a LogStreamContainerModel.\n *\n * @example\n * ```typescript\n *\n * const model: IKosDataModel = ...; // some model\n *\n * if (LogStreamContainer.predicate(model)) {\n * // if the function evaluates to true, the model is narrowed down to LogStreamContainerModel\n * // and the compiler will know that the model has the LogStreamContainerModel interface\n * model.updateAvailability(false);\n * }\n * ```\n *\n * ## registration\n *\n * The registration property is an object that can be used to simplify registration of the model with the model registry. The registration object\n * can be spread into the model registration and provides all of the required information to register the model implementation class against the model type.\n *\n *\n * @example\n *\n * In an application registration file you can declare the model registration as follows:\n *\n * **registration.ts**\n * ```typescript\n * import { LogStreamContainer } from \"@kosdev-code/kos-ui-sdk\";\n * ...\n * import { ExtensionManager, IKosRegistry } from \"@kosdev-code/kos-ui-sdk\";\n * export const kosModels: IKosRegistry[\"models\"] = {\n * ...LogStreamContainer.registration,\n * };\n * ```\n *\n * ## registration.singleton\n \n * The logStreamContainer model is a singleton model. This means that each time the factory function is called , the same instance will be returned.\n * If the model does not yet exist, it will be created passing in the provided options to initialize it.\n *\n * Singleton models don't require an ID as they will use the model type as their ID to guarantee uniqueness throughout the system.\n \n * */\nexport const LogStreamContainer = new SingletonKosModelRegistrationFactory<\n LogStreamContainerModel,\n LogStreamContainerOptions\n>({\n class: LogStreamContainerModelImpl,\n type: MODEL_TYPE,\n});\n\nLogStreamContainer.addRelatedModel(LogStream);\nLogStreamContainer.addRelatedModel(LogBlockContainer);\nLogStreamContainer.addRelatedModel(LogBlock);\n","import type { TroubleResponse } from \"../models/trouble/services\";\n\ninterface RankAwareTrouble {\n rank: number;\n}\n\ninterface RoleAwareTrouble {\n visibleRole: string;\n}\n\ninterface ColorAwareTrouble {\n color: string;\n}\n\nconst isRankedInfo = (i: any): i is RankAwareTrouble => i?.rank !== undefined;\n\nconst isRoleAwareInfo = (i: any): i is RoleAwareTrouble =>\n i?.visibleRole !== undefined;\n\nconst isColorAwareInfo = (i: any): i is ColorAwareTrouble =>\n i?.color !== undefined;\n\nexport const defaultTroubleRankMapper = (trouble: TroubleResponse) => {\n const info = trouble.info ?? {};\n if (isRankedInfo(info)) {\n return info.rank; // return the rank\n }\n return 0; // return 0 if not ranked\n};\n\nexport const defaultTroubleColorMapper = (trouble: TroubleResponse) => {\n const info = trouble.info ?? {};\n if (isColorAwareInfo(info)) {\n return info.color; // return the color\n }\n return \"orange\"; // return ORANGE if no color defined\n};\n\nexport const defaultTroubleRoleMapper = (trouble: TroubleResponse) => {\n const info = trouble.info ?? {};\n if (isRoleAwareInfo(info)) {\n return info.visibleRole; // return the role\n }\n return \"TECHNICIAN\"; // return empty if no role\n};\n","/**\n * @internal\n */\nimport {\n KosLog,\n KosServiceResponse,\n ServiceFactory,\n resolveServiceUrl,\n} from \"../../../../core\";\nimport { FutureEndState, FutureResponse } from \"../../../services/future\";\nimport { FutureManager } from \"../../../utils/future-manager\";\nimport { getKosConnectionId } from \"../../../utils/get-kos-connection-id\";\nconst { URL } = resolveServiceUrl(\"TROUBLE_SERVICE\");\nconst { getAll, postModel } = ServiceFactory.build({\n basePath: `${URL}/api/kos/troubles`,\n});\n\nexport interface TroubleResponse<ClientAttributes = any> {\n reason: string;\n createTime: string;\n resolvable: boolean;\n ifaces: string[];\n id: string;\n clientData: any;\n type: string;\n tags: string[];\n info: any;\n attrs: ClientAttributes;\n}\n\nconst log = KosLog.createLogger({ name: \"trouble-services\" });\n\n/**\n * @category Service\n * @internal\n * Retrieves the initial Trouble data.\n */\nexport const getTroubles = async (servicePath: string) => {\n const isKosTroubles = servicePath.includes(\"/kos/troubles\");\n const destinationAddress = getKosConnectionId();\n log.info(\n `Fetching troubles from ${servicePath} with destination address: ${\n isKosTroubles ? destinationAddress : \"N/A (not a kos troubles path)\"\n }`\n );\n\n const response = await getAll<TroubleResponse>({\n urlOverride: `${URL}${servicePath}`,\n destinationAddress: isKosTroubles ? destinationAddress : undefined,\n });\n return response;\n};\n\nexport const resolveTrouble = async (\n troubleId: string,\n servicePath = \"/api/kos/troubles\",\n tracker?: string\n) => {\n try {\n const isKosTroubles = servicePath.includes(\"/kos/troubles\");\n const destinationAddress = getKosConnectionId();\n const response: KosServiceResponse<FutureResponse> = (await postModel({\n model: {},\n urlOverride: `${URL}${servicePath}/resolve/${troubleId}`,\n destinationAddress: isKosTroubles ? destinationAddress : undefined,\n tracker,\n })) as KosServiceResponse<FutureResponse>;\n if (response?.data) {\n FutureManager.initiateFuture(response.data);\n }\n return response.data;\n } catch (error) {\n const futureResponse: FutureResponse = {\n id: tracker || \"\",\n endState: FutureEndState.Fail,\n tracker: tracker,\n reason: \"Failed to resolve trouble\",\n };\n FutureManager.initiateFuture(futureResponse);\n return futureResponse;\n }\n};\n\nexport const bulkResolveTroubles = async (\n troubleIds: string[],\n servicePath = \"/api/kos/troubles\",\n tracker?: string\n) => {\n try {\n const destinationAddress = getKosConnectionId();\n const response: KosServiceResponse<FutureResponse> = (await postModel({\n model: troubleIds,\n urlOverride: `${URL}${servicePath}/resolve/`,\n destinationAddress,\n tracker,\n })) as KosServiceResponse<FutureResponse>;\n\n if (response?.data) {\n FutureManager.initiateFuture(response.data);\n }\n return response.data;\n } catch (error) {\n const futureResponse: FutureResponse = {\n id: tracker || \"\",\n endState: FutureEndState.Fail,\n tracker: tracker,\n reason: \"Failed to resolve troubles\",\n };\n FutureManager.initiateFuture(futureResponse);\n return futureResponse;\n }\n};\n","import { KosLog, registerExtensionPoint } from \"../../../../core\";\nimport type { TroubleModel } from \"../types\";\nexport const EXTENSION_TROUBLE_DATA_MAPPER = \"troubleDataMapper\";\nexport type TroubleDataMapper = (\n trouble: TroubleModel\n) => Promise<Record<string, any>>;\nconst troubleMappers = new Map<string, TroubleDataMapper[]>();\nregisterExtensionPoint(EXTENSION_TROUBLE_DATA_MAPPER, {\n register: (id: string, mapper: TroubleDataMapper) => {\n if (!troubleMappers.has(id)) {\n troubleMappers.set(id, []);\n }\n troubleMappers.get(id)?.push(mapper);\n },\n execute: async (id: string, trouble: TroubleModel) => {\n const mapper = troubleMappers.get(id);\n if (!mapper) {\n return {\n ...trouble.data,\n };\n }\n const promises = mapper.map((m) => m(trouble));\n const results = await Promise.allSettled(promises);\n const data = results.reduce(\n (acc, r) => {\n if (r.status === \"fulfilled\") {\n acc = { ...acc, ...r.value };\n } else {\n KosLog.info(`Trouble mapper ${id} failed: ${r.reason}`);\n }\n\n return acc;\n },\n { ...trouble.data }\n );\n\n return data;\n },\n});\n","import { KosLog, registerExtensionPoint } from \"../../../../core\";\nimport type { TroubleModel } from \"../types\";\nexport const EXTENSION_TROUBLE_MAPPER = \"troubleMapper\";\nexport type TroubleMapper = (trouble: TroubleModel) => Promise<string[]>;\nconst troubleMappers = new Map<string, TroubleMapper[]>();\nregisterExtensionPoint(EXTENSION_TROUBLE_MAPPER, {\n register: (id: string, mapper: TroubleMapper) => {\n if (!troubleMappers.has(id)) {\n troubleMappers.set(id, []);\n }\n troubleMappers.get(id)?.push(mapper);\n },\n execute: async (id: string, trouble: TroubleModel) => {\n const mapper = troubleMappers.get(id);\n if (!mapper) {\n return [];\n }\n const promises = mapper.map((m) => m(trouble));\n const results = await Promise.allSettled(promises);\n const paths = results\n\n .map((r) => {\n if (r.status === \"fulfilled\") {\n return r.value;\n } else {\n KosLog.info(`Trouble mapper ${id} failed: ${r.reason}`);\n return [];\n }\n })\n .flat();\n\n return Array.from(new Set(paths));\n },\n});\n","import { ExtensionManager } from \"../../../core\";\nimport type {\n HandleTroubleData,\n NozzleTroubleData,\n TroubleModel,\n} from \"../trouble/types\";\nimport \"../trouble/utils/trouble-data-extension\";\nimport { EXTENSION_TROUBLE_DATA_MAPPER } from \"../trouble/utils/trouble-data-extension\";\nimport \"../trouble/utils/trouble-extension\";\nimport { EXTENSION_TROUBLE_MAPPER } from \"../trouble/utils/trouble-extension\";\n\nExtensionManager[EXTENSION_TROUBLE_MAPPER].register(\n \"nozzle\",\n async (trouble: TroubleModel<NozzleTroubleData>) => [trouble.data.nozzlePath]\n);\n\nExtensionManager[EXTENSION_TROUBLE_MAPPER].register(\n \"path\",\n async (trouble: TroubleModel<HandleTroubleData>) => [trouble.data.path]\n);\n\nexport const troublePathFactory = async (trouble: TroubleModel) => {\n const result = new Set<string>();\n const ifaces = trouble.ifaces;\n\n const promises = ifaces?.map(\n (iface) =>\n ExtensionManager[EXTENSION_TROUBLE_MAPPER].execute(\n iface,\n trouble\n ) as Promise<string[]>\n );\n\n const results = await Promise.allSettled(promises);\n\n results.forEach((r) => {\n if (r.status === \"fulfilled\") {\n (r.value as string[]).forEach((path) => result.add(path));\n }\n });\n\n return Array.from(result);\n};\n\nexport const troubleDataFactory = async (trouble: TroubleModel) => {\n const ifaces = trouble.ifaces;\n\n const promises = ifaces?.map(\n (iface) =>\n ExtensionManager[EXTENSION_TROUBLE_DATA_MAPPER].execute(\n iface,\n trouble\n ) as Promise<Record<string, any>>\n );\n\n const troubleExtension = ExtensionManager[\n EXTENSION_TROUBLE_DATA_MAPPER\n ].execute(trouble.type, trouble) as Promise<Record<string, any>>;\n\n promises.push(troubleExtension);\n\n const results = await Promise.allSettled(promises);\n\n const result = results.reduce((acc, r) => {\n if (r.status === \"fulfilled\") {\n acc = { ...acc, ...r.value };\n }\n return acc;\n }, {});\n\n return { ...trouble.data, ...result };\n};\n","import { TroubleHandler } from \"../../../../core\";\n\nexport class ResolvableTroubleHandler implements TroubleHandler {\n type = \"ResolvableTrouble\";\n title = \"Resolvable Trouble\";\n subtitle = \"Trouble\";\n}\n\nexport class BlockPumpTroubleHandler implements TroubleHandler {\n type = \"BlockPumpTrouble\";\n title = \"Block Pump Trouble\";\n subtitle = \"Trouble\";\n}\n\nexport class TroubleHandlerFactory {\n static getHandler(type: string): TroubleHandler | undefined {\n switch (type) {\n case \"ResolvableTrouble\":\n return new ResolvableTroubleHandler();\n case \"BlockPumpTrouble\":\n return new BlockPumpTroubleHandler();\n default:\n return undefined;\n }\n }\n}\n","import {\n kosModel,\n resolveKosCompanion,\n type IKosModelLogger,\n type KosContextLogger,\n type KosCreationContext,\n} from \"../../../core\";\nimport { kosFuture } from \"../../decorators/future-service\";\nimport { FutureHandler } from \"../future/future-aware\";\nimport type { FutureAwareContainer } from \"../future/future-types\";\nimport { troubleDataFactory } from \"../trouble-container/trouble-utils\";\nimport { TroubleHandlerFactory } from \"./handlers/resolvable-trouble-handler\";\nimport { resolveTrouble, type TroubleResponse } from \"./services\";\nimport type { DeferAware, TroubleModel, TroubleOptions } from \"./types\";\n\nexport const MODEL_TYPE = \"trouble-model\";\n\nfunction isDeferAware(obj: any): obj is DeferAware {\n return typeof obj.shouldDefer === \"boolean\";\n}\n\n@kosModel(MODEL_TYPE)\nexport class TroubleModelImpl<AdditionalData extends object = any>\n implements TroubleModel<AdditionalData>, IKosModelLogger\n{\n id: string;\n logger: KosContextLogger;\n private _troubleId: string;\n private _resolvable: boolean;\n\n type: string;\n futureHandler: FutureAwareContainer;\n ifaces: string[];\n clientData: unknown;\n info: unknown;\n role: string;\n color: string;\n tags: string[];\n data: AdditionalData;\n rank: number;\n servicePath: string;\n group?: string;\n createTime?: string;\n rawJson?: TroubleResponse<any>;\n private _mapped: Record<any, any> = {};\n constructor(\n modelId: string,\n {\n resolvable,\n tags,\n info,\n id,\n clientData,\n rank,\n ifaces,\n type,\n group,\n createTime,\n role,\n color,\n servicePath,\n rawJson,\n ...rest\n }: TroubleOptions,\n context: KosCreationContext\n ) {\n this.id = modelId;\n this.logger = context.logger;\n this.type = type;\n this._troubleId = id;\n this._resolvable = !!resolvable;\n this.ifaces = ifaces;\n this.rank = rank;\n this.role = role;\n this.color = color;\n this.tags = tags;\n this.info = info;\n this.group = group;\n this.rawJson = rawJson;\n this.servicePath = servicePath ?? \"/api/kos/troubles\";\n this.createTime = createTime;\n this.clientData = clientData;\n this.data = {} as AdditionalData;\n\n Object.assign(this.data, rest);\n this.futureHandler = new FutureHandler(this);\n }\n\n // -------------------LIFECYCLE----------------------------\n\n getTitleWithContext(context: string) {\n // get the context from the handler\n // return the default context if the context is not found\n const ctx = context\n ? TroubleHandlerFactory.getHandler(this.type)?.context?.[context]\n : TroubleHandlerFactory.getHandler(this.type);\n\n // return the title from the context\n return ctx?.title || \"Trouble\";\n }\n\n getSubtitleWithContext(context: string) {\n // get the context from the handler\n // return the default context if the context is not found\n const ctx = context\n ? TroubleHandlerFactory.getHandler(this.type)?.context?.[context]\n : TroubleHandlerFactory.getHandler(this.type);\n\n // return the subtitle from the context\n return ctx?.subtitle || \"Trouble\";\n }\n\n get rawId() {\n return this._troubleId;\n }\n get title() {\n return TroubleHandlerFactory.getHandler(this.type)?.title || \"Trouble\";\n }\n\n get subtitle() {\n return TroubleHandlerFactory.getHandler(this.type)?.subtitle || \"Trouble\";\n }\n\n get troubleId() {\n return this._troubleId;\n }\n\n get resolvable() {\n return this._resolvable;\n }\n\n get future() {\n return this.futureHandler.future;\n }\n\n async resolveMappedData() {\n return await troubleDataFactory(this);\n }\n\n get deferredCompanion() {\n const companion = resolveKosCompanion(this.id, (m) => isDeferAware(m));\n if (companion && isDeferAware(companion.modelData)) {\n return companion.modelData;\n }\n return undefined;\n }\n get deferred() {\n if (this.deferredCompanion) {\n return this.deferredCompanion.deferred;\n }\n return false;\n }\n get shouldDefer(): boolean {\n const companion = resolveKosCompanion(this.id, (m) => isDeferAware(m));\n if (companion && isDeferAware(companion.modelData)) {\n return companion.modelData.shouldDefer;\n }\n return false;\n }\n\n clearDefer() {\n this.deferredCompanion?.clearDefer();\n }\n defer() {\n this.deferredCompanion?.defer();\n }\n\n getChildren() {\n const allFutures = this.futureHandler.allFutures;\n return [...allFutures];\n }\n\n @kosFuture()\n async resolve(tracker?: string) {\n if (!this._resolvable) {\n this.logger.error(\n `attempting to resolve an unresolvable trouble with id ${this._troubleId}`\n );\n throw new Error(\"Trouble is not resolvable\");\n }\n\n if (this.shouldDefer) {\n this.deferredCompanion?.defer();\n return undefined;\n }\n return await resolveTrouble(this._troubleId, this.servicePath, tracker);\n }\n}\n","import type { KosModelRegistrationBean } from \"../../../core\";\nimport { Kos, isKosModel } from \"../../../core\";\nimport { MODEL_TYPE, TroubleModelImpl } from \"./trouble-model\";\nimport type { TroubleModel, TroubleOptions } from \"./types\";\n\n/**\n * # Translation\n *\n * The registration bean includes convenience methods for creating and working with TranslationModel instances.\n *\n * ## type\n * The type property is a string that identifies the model type.\n * The type is used to identify the model type in the model registry and to narrow down the model type in type predicates. It's most frequently\n * used when declaring dependencies on models.\n *\n * @example\n * ```typescript\n *\n * @kosDependency({modelType: Translation.type, id: \"translationId\"})\n * private translationModel: TranslationModel;\n * ```\n *\n *\n * ## factory\n *\n * The factory method creates a factory function that can be used to create new TranslationModel instances.\n *\n \n * The factory function is a curried function that takes the model id as the first argument and the options as the second argument.\n *\n * If a model with the specified id already exists, the factory function will return the existing model. The options will be ignored\n * in this case and the existing model will be returned in its current state.\n *\n * @example\n * ```typescript\n * const model = Translation.factory(\"translationId\")({\n * // Add option data\n * });\n * ```\n \n\n *\n * ## predicate\n *\n * [Typescript type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) function that will identify and narrow down a model to a TranslationModel.\n *\n * @example\n * ```typescript\n *\n * const model: IKosDataModel = ...; // some model\n *\n * if (Translation.predicate(model)) {\n * // if the function evaluates to true, the model is narrowed down to TranslationModel\n * // and the compiler will know that the model has the TranslationModel interface\n * model.updateAvailability(false);\n * }\n * ```\n *\n * ## registration\n *\n * The registration property is an object that can be used to simplify registration of the model with the model registry. The registration object\n * can be spread into the model registration and provides all of the required information to register the model implementation class against the model type.\n *\n *\n * @example\n *\n * In an application registration file you can declare the model registration as follows:\n *\n * **registration.ts**\n * ```typescript\n * import { Translation } from \"@kosdev-code/kos-dispense-sdk\";\n * ...\n * import { ExtensionManager, IKosRegistry } from \"@kosdev-code/kos-ui-sdk\";\n * export const kosModels: IKosRegistry[\"models\"] = {\n * ...Translation.registration,\n * };\n * ```\n *\n * ## registration.singleton\n \n * The translation model is NOT a singleton model. This means that each time the factory function is called with a unique ID, a new model instance will be created.\n * If the factory function is called with an ID that already exists, the existing model will be returned.\n \n * */\nexport const Trouble: Readonly<\n KosModelRegistrationBean<TroubleModel, TroubleOptions>\n> = {\n registration: {\n [MODEL_TYPE]: {\n class: TroubleModelImpl,\n singleton: false,\n },\n },\n type: MODEL_TYPE,\n predicate: isKosModel(MODEL_TYPE),\n factory: Kos.Factory.create<TroubleModel, TroubleOptions>(MODEL_TYPE),\n};\n","/* eslint-disable @typescript-eslint/no-unsafe-declaration-merging */\nimport {\n DependencyLifecycle,\n ExtensionManager,\n destroyKosModel,\n kosContainerAware,\n kosFutureAware,\n kosLoggerAware,\n kosModel,\n kosTopicHandler,\n type IKosDataModel,\n type IKosIdentifiable,\n type KosContainerAwareWithProp,\n type KosFutureAwareFull,\n type KosLoggerAware,\n type KosModelRegistrationType,\n type PublicModelInterface,\n} from \"../../../core\";\n\nimport { KosCoreModelPropertyMapper } from \"../../constants\";\nimport { kosFuture } from \"../../decorators\";\nimport {\n defaultTroubleColorMapper,\n defaultTroubleRankMapper,\n defaultTroubleRoleMapper,\n} from \"../../utils/trouble-utils\";\nimport {\n bulkResolveTroubles,\n getTroubles,\n type TroubleResponse,\n} from \"../trouble/services\";\nimport { Trouble } from \"../trouble/trouble-registration\";\nimport type { TroubleModel } from \"../trouble/types\";\nimport { troublePathFactory } from \"./trouble-utils\";\nimport type { TroubleContainerOptions } from \"./types\";\n\nconst addTrouble = (trouble: TroubleResponse) => {\n const options = {\n ...trouble,\n rank: troubleRankMapper(trouble),\n color: troubleColorMapper(trouble),\n role: troubleRoleMapper(trouble),\n id: String(trouble.id),\n };\n\n const newTrouble = Trouble.factory(`trouble-${trouble.id}`)(options);\n return newTrouble;\n};\nfunction troubleRankMapper(trouble: TroubleResponse): number {\n const _rank = ExtensionManager.propertyMapper.hasMapper(\n KosCoreModelPropertyMapper.TroubleRank\n )\n ? ExtensionManager.propertyMapper.executeMapper<TroubleResponse, number>(\n KosCoreModelPropertyMapper.TroubleRank,\n trouble\n )\n : defaultTroubleRankMapper(trouble);\n return _rank;\n}\n\nfunction troubleColorMapper(trouble: TroubleResponse): string {\n const color = ExtensionManager.propertyMapper.hasMapper(\n KosCoreModelPropertyMapper.TroubleColor\n )\n ? ExtensionManager.propertyMapper.executeMapper<TroubleResponse, string>(\n KosCoreModelPropertyMapper.TroubleColor,\n trouble\n )\n : defaultTroubleColorMapper(trouble);\n return color.toLowerCase();\n}\n\nfunction troubleRoleMapper(trouble: TroubleResponse): string {\n const role = ExtensionManager.propertyMapper.hasMapper(\n KosCoreModelPropertyMapper.TroubleRole\n )\n ? ExtensionManager.propertyMapper.executeMapper<TroubleResponse, string>(\n KosCoreModelPropertyMapper.TroubleRole,\n trouble\n )\n : defaultTroubleRoleMapper(trouble);\n return role.toLowerCase();\n}\nexport const MODEL_TYPE = \"trouble-container-model\";\n\nexport type TroubleContainerModel =\n PublicModelInterface<TroubleContainerModelImpl>;\nexport interface TroubleContainerModelImpl\n extends KosContainerAwareWithProp<TroubleModel, \"troubles\">,\n KosFutureAwareFull,\n KosLoggerAware {}\nexport class Troubles {\n static readonly INDEX_TROUBLES_BY_IFACE = \"byIface\";\n static readonly INDEX_TROUBLES_BY_TYPE = \"byType\";\n static readonly INDEX_TROUBLES_BY_GROUP = \"byGroup\";\n static readonly INDEX_TROUBLES_BY_DEFERRED = \"byDeferred\";\n static readonly SORT_KEY_RANK = \"rank\";\n static readonly TROUBLES_DEFERRED = \"true\";\n}\n@kosModel({ modelTypeId: MODEL_TYPE, singleton: true })\n@kosLoggerAware()\n@kosFutureAware()\n@kosContainerAware<TroubleModel>({\n containerProperty: \"troubles\",\n containerOptions: {\n indexMap: {\n [Troubles.INDEX_TROUBLES_BY_IFACE]: troublePathFactory,\n [Troubles.INDEX_TROUBLES_BY_TYPE]: \"type\",\n [Troubles.INDEX_TROUBLES_BY_GROUP]: \"group\",\n [Troubles.INDEX_TROUBLES_BY_DEFERRED]: \"deferred\",\n },\n sortKey: Troubles.SORT_KEY_RANK,\n },\n})\nexport class TroubleContainerModelImpl\n implements IKosIdentifiable, IKosDataModel\n{\n static Registration: KosModelRegistrationType<\n TroubleContainerModelImpl,\n TroubleContainerOptions\n >;\n id: string;\n servicePath = \"/api/kos/troubles\";\n constructor(modelId: string, options: TroubleContainerOptions) {\n this.id = modelId;\n this.servicePath = options.servicePath ?? this.servicePath;\n }\n\n // -------------------LIFECYCLE----------------------------\n async reload(): Promise<void> {\n this.logger.info(\"reloading trouble container\");\n const _troubles = await getTroubles(this.servicePath);\n const incoming = _troubles?.data ?? [];\n\n const incomingKeys = new Set(incoming.map((t) => `trouble-${t.id}`));\n\n const toRemove = this.troubles.data\n .map((m) => m.id)\n .filter((id) => !incomingKeys.has(id));\n\n const toAdd = incoming\n .filter((t) => !this.troubles.getModel(`trouble-${t.id}`))\n .map(addTrouble);\n\n this.troubles.removeAll(toRemove);\n this.troubles.addAll(toAdd);\n }\n async load(): Promise<void> {\n this.logger.debug(\"loading trouble container\");\n try {\n const _troubles = await getTroubles(this.servicePath);\n _troubles?.data.forEach((trouble) => {\n const options = {\n ...trouble,\n servicePath: this.servicePath,\n rank: troubleRankMapper(trouble),\n color: troubleColorMapper(trouble),\n role: troubleRoleMapper(trouble),\n id: String(trouble.id),\n rawJson: trouble,\n };\n\n const newTrouble = Trouble.factory(`trouble-${trouble.id}`)(options);\n this.troubles.addModel(newTrouble);\n });\n } catch (e) {\n this.logger.error(e);\n throw e;\n }\n }\n\n @kosFuture()\n async resolveAll(tracker?: string) {\n const troubleIds = this.troubles.data\n .filter((trouble) => trouble.resolvable)\n .map((trouble) => trouble.rawId);\n return await bulkResolveTroubles(troubleIds, this.servicePath, tracker);\n }\n\n @kosTopicHandler({\n topic: \"/kos/trouble/remove\",\n websocket: true,\n lifecycle: DependencyLifecycle.INIT,\n })\n handleTroubleRemoved(id: string) {\n const troubleId = `trouble-${id}`;\n const removed = this.troubles.getModel(troubleId);\n\n this.troubles.removeModel(troubleId);\n if (removed) {\n destroyKosModel(removed);\n }\n }\n\n @kosTopicHandler({ topic: \"/kos/trouble/add\", websocket: true })\n handleTroubleAdded(trouble: TroubleResponse) {\n const options = {\n ...trouble,\n servicePath: this.servicePath,\n rank: troubleRankMapper(trouble),\n color: troubleColorMapper(trouble),\n role: troubleRoleMapper(trouble),\n id: String(trouble.id),\n rawJson: trouble,\n };\n if (options.role === \"NONE\") {\n // ignore troubles with role NONE\n return;\n }\n const newTrouble = Trouble.factory(`trouble-${trouble.id}`)(options);\n this.troubles.addModel(newTrouble);\n }\n}\n","export {\n Troubles,\n type TroubleContainerModel,\n} from \"./trouble-container-model\";\n\nexport type { TroubleContainerOptions } from \"./types\";\n\nimport { TroubleContainerModelImpl } from \"./trouble-container-model\";\n\nexport const TroubleContainer = TroubleContainerModelImpl.Registration;\n","import { KosLog, ServiceFactory, resolveServiceUrl } from \"../../../../core\";\nimport type { OTAArtifactResponse } from \"../types\";\n\nconst { URL } = resolveServiceUrl(\"OTA-SERVICE\");\n\nconst { getAll } = ServiceFactory.build({\n basePath: `${URL}/api/kos/ota`,\n});\n\nconst log = KosLog.createLogger({\n name: \"ota-service\",\n group: \"Services\",\n});\n\n/**\n * @category Service\n * GET request to /api/kos/ota/artifacts\n */\nexport const getArtifacts = async () => {\n log.debug(\"sending GET request to /api/kos/ota/artifacts\");\n\n const response = await getAll<OTAArtifactResponse>({\n urlOverride: `${URL}/api/kos/ota/artifacts`,\n });\n\n log.debug(\"getArtifacts - response:\", response);\n\n return response?.data;\n};\n","import {\n kosDependency,\n kosModel,\n kosTopicHandler,\n} from \"../../../core/core/decorators\";\nimport {\n KosDataContainer,\n type IKosDataContainer,\n} from \"../../../core/core/kos-data-container\";\nimport type {\n IKosDataModel,\n KosContextLogger,\n KosCreationContext,\n} from \"../../../core/core/kosModel\";\nimport type { IKosIdentifiable } from \"../../../core/core/types\";\nimport type { PublicModelInterface } from \"../../../core/types\";\nimport type { TroubleContainerModel } from \"../trouble-container\";\nimport { TroubleContainer } from \"../trouble-container\";\nimport { getArtifacts } from \"./services\";\nimport type {\n OTAArtifactResponse,\n OTARequest,\n UpdaterItem,\n UpdaterOptions,\n UpdaterStatus,\n} from \"./types\";\n\nexport const MODEL_TYPE = \"ota-model\";\n\n/**\n * OTA - Over-the-Air update management system for KOS devices.\n *\n * The OTA model provides comprehensive management of software updates and artifacts on KOS devices,\n * including real-time download progress tracking, installation management, and error handling.\n * This model is essential for applications that need to manage software updates, display update\n * status, and handle system maintenance operations.\n *\n * ## Key Features\n * - **Real-Time Update Tracking** - Live monitoring of download progress and installation status\n * - **Artifact Management** - Complete visibility into available and installed software artifacts\n * - **Trouble Integration** - Integration with KOS trouble system for error tracking and resolution\n * - **Status Monitoring** - Comprehensive status tracking (downloading, pending, ready, error, idle)\n * - **Installation Control** - Safe installation and reboot management for pending updates\n * - **Progress Reporting** - Detailed download progress with size and percentage completion\n *\n * ## Topic-Based Reactivity\n * The model listens to these KOS topics for real-time synchronization:\n * - **`/kos/ota/artifacts/all`** - Complete artifact list updates from OTA service\n * - **`/kos/ota/artifacts/changed`** - Incremental artifact status changes during downloads\n *\n * ## Update States\n * - **idle** - No updates in progress, system ready\n * - **downloading** - Updates actively downloading from remote sources\n * - **pending** - Updates downloaded and staged, ready for installation\n * - **ready** - Updates installed and ready for use\n * - **error** - Update process encountered errors, intervention needed\n *\n * ## Common Use Cases\n * - **Update Status Dashboard** - Display current update status and progress to users\n * - **System Maintenance** - Manage scheduled updates and installations\n * - **Error Handling** - Monitor and resolve update-related issues\n * - **Progress Monitoring** - Track download progress for large artifacts\n * - **Installation Management** - Control when updates are applied to minimize downtime\n *\n * @interface\n * @example Basic Usage\n * ```typescript\n * const otaModel = Ota.instance('system-updater').build();\n *\n * // Access current update status and manage installations\n * console.log(otaModel.status); // 'idle' | 'downloading' | 'pending' | 'ready' | 'error'\n * if (otaModel.status === 'pending') {\n * otaModel.installAndReboot();\n * }\n * ```\n *\n * @group KOS Model\n * @category System Integration\n * @useDeclaredType\n *\n * @see {@link UpdaterOptions} - Configuration options for OTA model\n * @see {@link UpdaterItem} - Individual update artifact interface\n * @see {@link UpdaterStatus} - Available update status types\n * @see {@link OTAArtifactResponse} - Raw artifact data from OTA service\n * @see {@link TroubleContainer} - Integrated trouble management system\n */\nexport type OtaModel = PublicModelInterface<OtaModelImpl>;\n\nconst getLastRequest = (\n requests: Record<string, OTARequest>\n): OTARequest | null => {\n let lastRequest: OTARequest | null = null;\n\n for (const provider in requests) {\n const currentConfig = requests[provider];\n const currentLastUpdateTime = currentConfig.lastUpdateTime;\n\n if (!lastRequest || lastRequest.lastUpdateTime < currentLastUpdateTime) {\n lastRequest = currentConfig;\n }\n }\n\n return lastRequest;\n};\n\nconst mapOTAArtifactResponseToUpdaterItem = (\n otaArtifactResponse: OTAArtifactResponse\n): UpdaterItem | undefined => {\n const artifactInfo = otaArtifactResponse.artifactInfo;\n\n const lastRequest = getLastRequest(otaArtifactResponse.requests);\n\n const id = artifactInfo?.identifier || lastRequest?.kabId;\n if (!id) return undefined;\n\n let status: UpdaterStatus;\n switch (otaArtifactResponse.status) {\n case \"INSTALLED\":\n status = \"ready\";\n break;\n case \"INVALID\":\n status = \"error\";\n break;\n case \"MISSING\":\n status = (lastRequest?.currentSize || 0) > 0 ? \"downloading\" : \"idle\";\n break;\n case \"STAGED\":\n status = \"pending\";\n }\n\n const manifest = artifactInfo === undefined;\n\n return {\n id,\n manifest,\n label: artifactInfo?.version,\n name: artifactInfo?.name,\n status,\n error: status === \"error\" ? lastRequest?.lastErrorReason : undefined,\n errorCount: status === \"error\" ? lastRequest?.errorCount : 0,\n progress:\n status === \"downloading\" && lastRequest && !manifest\n ? (lastRequest.currentSize / artifactInfo?.size) * 100\n : undefined,\n size: artifactInfo?.size,\n };\n};\n\n/**\n * @ignore\n * @internal\n */\n@kosModel(MODEL_TYPE)\nexport class OtaModelImpl implements IKosDataModel, IKosIdentifiable {\n /** Unique identifier for the model instance */\n id: string;\n private logger: KosContextLogger;\n\n /** Internal data container holding all available update artifacts */\n private data: IKosDataContainer<UpdaterItem> = new KosDataContainer();\n\n /** Trouble container dependency for tracking OTA-related troubles */\n @kosDependency({ modelType: TroubleContainer.type })\n private troubleContainer!: TroubleContainerModel;\n\n /** Trouble condition indicating downloads are currently in progress */\n get downloadInProgressTrouble() {\n const downloadInProgressTrouble =\n this.troubleContainer.troubles.getIndexByKey(\n \"byType\",\n \"OTADownloadInProgressTrouble\"\n )?.[0];\n\n return downloadInProgressTrouble;\n }\n\n /** Trouble condition indicating updates are downloaded and pending installation */\n get updatePendingTrouble() {\n const updatePendingTrouble = this.troubleContainer.troubles.getIndexByKey(\n \"byType\",\n \"OTAUpdatePendingTrouble\"\n )?.[0];\n\n return updatePendingTrouble;\n }\n\n /** Trouble condition indicating OTA process is paused due to errors */\n get pausedDueToErrorsTrouble() {\n const pendingTrouble = this.troubleContainer.troubles.getIndexByKey(\n \"byType\",\n \"OTAPausedDueToErrorsTrouble\"\n )?.[0];\n\n return pendingTrouble;\n }\n\n /** Collection of all available update artifacts with their current status */\n get updates() {\n return this.data;\n }\n\n /** Current overall update status based on active trouble conditions */\n get status(): UpdaterStatus {\n const status = this.pausedDueToErrorsTrouble\n ? \"error\"\n : this.downloadInProgressTrouble\n ? \"downloading\"\n : this.updatePendingTrouble\n ? \"pending\"\n : \"idle\";\n\n return status;\n }\n\n constructor(\n modelId: string,\n options: UpdaterOptions,\n context: KosCreationContext\n ) {\n this.id = modelId;\n this.logger = context.logger;\n\n if (options) {\n // Assign options properties here.\n }\n }\n\n /**\n * Installs pending updates and initiates system reboot.\n * This method resolves the OTAUpdatePendingTrouble to trigger installation.\n */\n installAndReboot() {\n if (!this.updatePendingTrouble) {\n this.logger.error(\n \"installAndReboot - OTAUpdatePendingTrouble not present\"\n );\n }\n\n this.logger.debug(\"installAndReboot - resolve OTAUpdatePendingTrouble\");\n\n this.updatePendingTrouble?.resolve();\n }\n\n // -------------------LIFECYCLE----------------------------\n\n /**\n * @internal\n */\n async init(): Promise<void> {\n this.logger.debug(`initializing ota ${this.id}`);\n }\n\n /**\n * @internal\n */\n async load(): Promise<void> {\n this.logger.debug(`loading ota ${this.id}`);\n\n try {\n const artifacts = await getArtifacts();\n if (artifacts) {\n artifacts.forEach((otaArtifactResponse) => {\n const model =\n mapOTAArtifactResponseToUpdaterItem(otaArtifactResponse);\n\n if (model) this.data.addModel(model);\n });\n }\n } catch (error) {\n this.logger.error(`loading ota ${this.id} - error:`, error);\n }\n }\n\n // -------------------TOPIC-HANDLERS-----------------------\n\n @kosTopicHandler({\n topic: \"/kos/ota/artifacts/all\",\n websocket: true,\n })\n async handleAllArtifacts(artifacts: OTAArtifactResponse[]) {\n this.logger.debug(\"handleAllArtifacts:\", artifacts);\n\n await this.data.clear();\n\n try {\n artifacts.forEach((otaArtifactResponse) => {\n const model = mapOTAArtifactResponseToUpdaterItem(otaArtifactResponse);\n\n if (model) this.data.addModel(model);\n });\n } catch (error) {\n this.logger.error(`handleAllArtifacts ${this.id} - error:`, error);\n }\n }\n\n @kosTopicHandler({\n topic: \"/kos/ota/artifacts/changed\",\n websocket: true,\n })\n handleChangedArtifacts(artifacts: OTAArtifactResponse[]) {\n this.logger.debug(\"handleChangedArtifacts:\", artifacts);\n\n try {\n artifacts.forEach((otaArtifactResponse) => {\n const model = mapOTAArtifactResponseToUpdaterItem(otaArtifactResponse);\n\n if (model) this.data.updateModel(model);\n });\n } catch (error) {\n this.logger.error(`handleChangedArtifacts ${this.id} - error:`, error);\n }\n }\n}\n","import { SingletonKosModelRegistrationFactory } from \"../../../core/core/registration\";\nimport type { OtaModel } from \"./ota-model\";\nimport { MODEL_TYPE, OtaModelImpl } from \"./ota-model\";\nimport type { UpdaterOptions } from \"./types\";\n\n/**\n * # Ota\n *\n * The registration bean includes convenience methods for creating and working with OtaModel instances.\n *\n * ## type\n * The type property is a string that identifies the model type.\n * The type is used to identify the model type in the model registry and to narrow down the model type in type predicates. It's most frequently\n * used when declaring dependencies on models.\n *\n * @example\n * ```typescript\n *\n * @kosDependency({modelType: Ota.type, id: \"oTAId\"})\n * private oTAModel: OtaModel;\n * ```\n *\n *\n * ## factory\n *\n * The factory method creates a factory function that can be used to create new OtaModel instances.\n *\n \n * As this is a singleton model, the factory function accepts the model options as its argument.\n *\n * If a model with the same model type already exists, the factory function will return the existing model. The options will be ignored\n * in this case and the existing model will be returned in its current state.\n *\n * @example\n * ```typescript\n * const model = Ota.factory({\n * // Add option data\n * });\n * ```\n \n\n *\n * ## predicate\n *\n * [Typescript type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) function that will identify and narrow down a model to a OtaModel.\n *\n * @example\n * ```typescript\n *\n * const model: IKosDataModel = ...; // some model\n *\n * if (Ota.predicate(model)) {\n * // if the function evaluates to true, the model is narrowed down to OtaModel\n * // and the compiler will know that the model has the OtaModel interface\n * model.updateAvailability(false);\n * }\n * ```\n *\n * ## registration\n *\n * The registration property is an object that can be used to simplify registration of the model with the model registry. The registration object\n * can be spread into the model registration and provides all of the required information to register the model implementation class against the model type.\n *\n *\n * @example\n *\n * In an application registration file you can declare the model registration as follows:\n *\n * **registration.ts**\n * ```typescript\n * import { Ota } from \"@kos-ui/project-models\";\n * import { KosModelRegistry } from \"@kosdev-code/kos-dispense-sdk\";\n *\n * import { initKosProvider } from \"@kosdev-code/kos-ui-sdk\";\n *\n * KosModelRegistry.dispense\n * .models()\n * .model(Ota);\n * ```\n *\n * ## registration.singleton\n \n * The oTA model is a singleton model. This means that each time the factory function is called , the same instance will be returned.\n * If the model does not yet exist, it will be created passing in the provided options to initialize it.\n *\n * Singleton models don't require an ID as they will use the model type as their ID to guarantee uniqueness throughout the system.\n \n * */\nexport const Ota = new SingletonKosModelRegistrationFactory<\n OtaModel,\n UpdaterOptions\n>({\n class: OtaModelImpl,\n type: MODEL_TYPE,\n});\n","/**\n * Bridge a @kosFuture method call to a Promise that settles on the FUTURE's\n * terminal state — not on the HTTP acknowledgment.\n *\n * A @kosFuture method resolves as soon as the backend accepts the operation;\n * the real outcome (SUCCESS / FAIL / ABORT / CANCEL) arrives later on the\n * future model via topic updates. Inside React that state is observable\n * through the model's future-aware getters, but imperative callers (commands,\n * services, tests) have no way to await the outcome. This util observes the\n * future created by the call and resolves/rejects the returned promise from\n * its end state, with cancellation and progress subscription support.\n */\n\nimport { reaction } from \"mobx\";\nimport { KosLog } from \"../../core\";\nimport type {\n FutureContainer,\n IFutureModel,\n} from \"../models/future/future-types\";\nimport { FutureEndState } from \"../services/future\";\nimport type { CancellablePromise } from \"../types/cancellable-promise\";\n\nconst log = KosLog.createLogger({ name: \"await-future-call\", group: \"Models\" });\n\n/**\n * Rejection raised when the awaited future ends in FAIL / ABORT / CANCEL.\n * `reason` carries the backend's reason code (e.g. a ReasonException id),\n * so callers can map it to user-facing messages.\n */\nexport class FutureCallError extends Error {\n readonly endState: FutureEndState;\n readonly reason?: string;\n readonly futureId?: string;\n\n constructor(endState: FutureEndState, reason?: string, futureId?: string) {\n super(reason ?? `Future ended with ${endState}`);\n this.name = \"FutureCallError\";\n this.endState = endState;\n this.reason = reason;\n this.futureId = futureId;\n }\n\n get isCancelled() {\n return (\n this.endState === FutureEndState.Canceled ||\n this.endState === FutureEndState.Aborted\n );\n }\n}\n\nexport interface AwaitFutureCallOptions {\n /** Alias the wrapped method registers its future under (@kosFuture alias). */\n alias?: string;\n /**\n * Reject with a timeout error if the future has not reached an end state\n * within this window. Unset = wait indefinitely.\n */\n timeoutMs?: number;\n}\n\n/**\n * Invoke a @kosFuture method on a future-aware model and return a\n * CancellablePromise that settles from the future's end state:\n *\n * - resolves with the method's response once the future ends in SUCCESS\n * - rejects with {@link FutureCallError} on FAIL / ABORT / CANCEL\n * - rejects with the service error if the call itself throws\n * - resolves with the response when the call turns out not to be\n * future-tracked (no future was produced)\n *\n * The future created by the call is captured reactively (the @kosFuture\n * wrapper registers it on the model's futureHandler before the request is\n * sent), so no timing hacks are needed and concurrent operations on other\n * aliases are unaffected.\n *\n * @example Awaiting real completion from a command\n * ```typescript\n * try {\n * await awaitFutureCall(artifact, (a) =>\n * a.publishImportedKab(path, version, qualifier)\n * );\n * studio.notifications.success(\"Published\");\n * } catch (e) {\n * if (e instanceof FutureCallError && !e.isCancelled) {\n * studio.notifications.error(mapReason(e.reason));\n * }\n * }\n * ```\n *\n * @example Cancellation and progress\n * ```typescript\n * const call = awaitFutureCall(model, (m) => m.performOperation());\n * const stop = call.onProgressUpdate((p, status) => render(p, status));\n * // later: await call.cancel();\n * ```\n */\nexport function awaitFutureCall<T extends FutureContainer, R>(\n model: T,\n methodCall: (model: T) => Promise<R>,\n options: AwaitFutureCallOptions = {}\n): CancellablePromise<R> {\n const { alias, timeoutMs } = options;\n\n const initial = model.futureHandler.getFuture(alias);\n\n let tracked: IFutureModel | undefined;\n let settled = false;\n let acked = false;\n let ackResponse: R | undefined;\n let cancelRequested = false;\n const disposers: Array<() => void> = [];\n const progressCallbacks = new Set<\n (progress: number, status: string) => void\n >();\n\n const dispose = () => {\n disposers.forEach((d) => d());\n disposers.length = 0;\n progressCallbacks.clear();\n };\n\n const promise = new Promise<R>((resolve, reject) => {\n const settle = (fn: () => void) => {\n if (settled) return;\n settled = true;\n dispose();\n fn();\n };\n\n const finishFromEndState = (endState: FutureEndState | undefined) => {\n if (!endState) return;\n if (endState === FutureEndState.Success) {\n settle(() => resolve(ackResponse as R));\n } else {\n settle(() =>\n reject(new FutureCallError(endState, tracked?.reason, tracked?.id))\n );\n }\n };\n\n const watchTracked = (future: IFutureModel) => {\n tracked = future;\n\n if (cancelRequested) {\n future.cancelFuture().catch((e) => log.error(e));\n }\n\n // Settle from the terminal state. fireImmediately covers futures that\n // completed before we attached (fast operations, ack-time end states).\n disposers.push(\n reaction(\n () => future.endState,\n (endState) => finishFromEndState(endState),\n { fireImmediately: true }\n )\n );\n\n // Progress fan-out for subscribers.\n disposers.push(\n reaction(\n () => [future.progress, future.status] as const,\n ([progress, status]) => {\n progressCallbacks.forEach((cb) => {\n try {\n cb(progress, status);\n } catch (e) {\n log.warn(\"progress callback error\", e);\n }\n });\n },\n { fireImmediately: true }\n )\n );\n };\n\n // Capture the future this call registers on the handler. The @kosFuture\n // wrapper adds it before the request is issued, so it always appears\n // before the acknowledgment resolves.\n disposers.push(\n reaction(\n () => model.futureHandler.getFuture(alias),\n (future) => {\n if (!tracked && future && future !== initial) {\n watchTracked(future);\n return;\n }\n // The handler dropped the future without a terminal state — the\n // call produced nothing to track (e.g. empty future response).\n if (tracked && !future && !tracked.endState && acked) {\n settle(() => resolve(ackResponse as R));\n }\n },\n { fireImmediately: true }\n )\n );\n\n if (timeoutMs !== undefined) {\n const timer = setTimeout(() => {\n settle(() =>\n reject(\n new Error(`Future for call did not complete within ${timeoutMs}ms`)\n )\n );\n }, timeoutMs);\n disposers.push(() => clearTimeout(timer));\n }\n\n methodCall(model)\n .then((response) => {\n acked = true;\n ackResponse = response;\n\n if (!tracked) {\n // Not a future-tracked call — the acknowledgment is the outcome.\n settle(() => resolve(response));\n return;\n }\n finishFromEndState(tracked.endState);\n })\n .catch((error) => {\n settle(() => reject(error));\n });\n }) as CancellablePromise<R>;\n\n promise.cancel = async () => {\n cancelRequested = true;\n if (tracked && !tracked.endState) {\n await tracked.cancelFuture();\n }\n };\n\n promise.getController = () => undefined;\n\n promise.isCancelled = () =>\n cancelRequested ||\n tracked?.endState === FutureEndState.Canceled ||\n tracked?.endState === FutureEndState.Aborted;\n\n Object.defineProperty(promise, \"progress\", {\n get: () => tracked?.progress ?? 0,\n enumerable: true,\n });\n\n Object.defineProperty(promise, \"status\", {\n get: () => tracked?.status ?? \"PENDING\",\n enumerable: true,\n });\n\n Object.defineProperty(promise, \"isRunning\", {\n get: () => !settled && (!tracked || !tracked.endState),\n enumerable: true,\n });\n\n Object.defineProperty(promise, \"timeRemaining\", {\n get: () => tracked?.timeRemaining ?? \"\",\n enumerable: true,\n });\n\n promise.onProgressUpdate = (\n callback: (progress: number, status: string) => void\n ) => {\n progressCallbacks.add(callback);\n callback(promise.progress, promise.status);\n return () => progressCallbacks.delete(callback);\n };\n\n return promise;\n}\n","/**\n * Utility for creating cancellable service functions\n */\n\nexport type CancellableFunction<T extends (...args: any[]) => any> = T & {\n /**\n * Cancel any in-flight request\n */\n cancel: () => void;\n /**\n * Get the current AbortController\n */\n getController: () => AbortController | undefined;\n /**\n * Check if there's an active request\n */\n isActive: () => boolean;\n};\n\n/**\n * Creates a cancellable version of a service function.\n * The service function must accept an AbortSignal as its last parameter.\n *\n * @example\n * ```typescript\n * // Original service\n * const getUsers = async (params?: UserParams, signal?: AbortSignal) => {\n * return api.get('/users', params, { signal });\n * };\n *\n * // Make it cancellable\n * const cancellableGetUsers = createCancellableService(getUsers);\n *\n * // Use it\n * const users = await cancellableGetUsers({ page: 1 });\n *\n * // Cancel if needed\n * cancellableGetUsers.cancel();\n * ```\n */\nexport function createCancellableService<TArgs extends any[], TReturn>(\n serviceFunction: (...args: [...TArgs, AbortSignal?]) => Promise<TReturn>\n): CancellableFunction<(...args: TArgs) => Promise<TReturn>> {\n let controller: AbortController | undefined;\n\n const wrappedFunction = async (...args: TArgs): Promise<TReturn> => {\n // Cancel previous request\n if (controller) {\n controller.abort();\n }\n\n // Create new controller\n controller = new AbortController();\n const currentController = controller;\n\n try {\n // Call the service with the abort signal\n return await serviceFunction(...args, currentController.signal);\n } finally {\n // Clear controller if this is still the active request\n if (controller === currentController) {\n controller = undefined;\n }\n }\n };\n\n // Add utility methods\n wrappedFunction.cancel = () => {\n if (controller) {\n controller.abort();\n controller = undefined;\n }\n };\n\n wrappedFunction.getController = () => controller;\n\n wrappedFunction.isActive = () => !!controller;\n\n return wrappedFunction as CancellableFunction<\n (...args: TArgs) => Promise<TReturn>\n >;\n}\n\n/**\n * Creates a cancellable service class that manages multiple service functions\n *\n * @example\n * ```typescript\n * class UserService extends CancellableServiceManager {\n * getUsers = this.createMethod(async (params?: UserParams, signal?: AbortSignal) => {\n * return api.get('/users', params, { signal });\n * });\n *\n * getUser = this.createMethod(async (id: string, signal?: AbortSignal) => {\n * return api.get(`/users/${id}`, undefined, { signal });\n * });\n * }\n * ```\n */\nexport class CancellableServiceManager {\n private controllers = new Map<string, AbortController>();\n\n /**\n * Create a cancellable method\n */\n protected createMethod<TArgs extends any[], TReturn>(\n name: string,\n serviceFunction: (...args: [...TArgs, AbortSignal?]) => Promise<TReturn>\n ): CancellableFunction<(...args: TArgs) => Promise<TReturn>> {\n const wrappedFunction = async (...args: TArgs): Promise<TReturn> => {\n // Cancel previous request for this method\n this.cancelMethod(name);\n\n // Create new controller\n const controller = new AbortController();\n this.controllers.set(name, controller);\n\n try {\n return await serviceFunction(...args, controller.signal);\n } finally {\n // Clear controller if it's still the active one\n if (this.controllers.get(name) === controller) {\n this.controllers.delete(name);\n }\n }\n };\n\n wrappedFunction.cancel = () => this.cancelMethod(name);\n wrappedFunction.getController = () => this.controllers.get(name);\n wrappedFunction.isActive = () => this.controllers.has(name);\n\n return wrappedFunction as CancellableFunction<\n (...args: TArgs) => Promise<TReturn>\n >;\n }\n\n /**\n * Cancel a specific method's request\n */\n cancelMethod(name: string): void {\n const controller = this.controllers.get(name);\n if (controller) {\n controller.abort();\n this.controllers.delete(name);\n }\n }\n\n /**\n * Cancel all active requests\n */\n cancelAll(): void {\n for (const controller of this.controllers.values()) {\n controller.abort();\n }\n this.controllers.clear();\n }\n\n /**\n * Get all active method names\n */\n getActiveMethods(): string[] {\n return Array.from(this.controllers.keys());\n }\n\n /**\n * Check if any requests are active\n */\n hasActiveRequests(): boolean {\n return this.controllers.size > 0;\n }\n}\n","import {\n createClient,\n type AvailableMethods,\n type ClientResponse,\n} from \"../../core\";\nimport type { paths } from \"./types\";\n\nexport const api = createClient<paths>();\n\nexport type BaseResponseType<\n K extends keyof paths,\n M extends AvailableMethods<paths[K]>\n> = ClientResponse<paths, K, M>;\n","import { BASE_URL, getQueryParams, kosFetch } from \"../../../../core\";\n\nconst params = getQueryParams();\nconst DEBUG =\n (params as any).debug === \"true\" || (params as any).debug === true;\n// const MSG_TYPE_CANVAS_DATA = 'canvas-data';\nconst PATH_CANVAS_DATA = \"/api/system/canvas\";\n\n/**\n * Sends canvas data to a specified endpoint using a POST request.\n *\n * @param data - The data to be sent to the canvas endpoint.\n * @returns A promise that resolves when the data has been successfully sent.\n */\nexport const sendCanvasData = async (data: any, apiPathOverride?: string) => {\n const path = apiPathOverride || PATH_CANVAS_DATA;\n const FULL_PATH = `${BASE_URL}${path}`;\n await kosFetch(FULL_PATH, {\n method: \"POST\",\n headers: {\n hide: DEBUG ? \"false\" : \"true\",\n },\n body: data,\n });\n // sendKosMessage(data, {\n // requestType: MSG_TYPE_CANVAS_DATA,\n // headers: {\n // hide: 'true',\n // },\n // });\n};\n","/**\n * Converts an RGB color value to the RGB332 color format.\n *\n * RGB332 is a compact 8-bit color format where:\n * - The red component is represented by the 3 most significant bits.\n * - The green component is represented by the next 3 bits.\n * - The blue component is represented by the 2 least significant bits.\n *\n * @param r - The red component of the color (0-255).\n * @param g - The green component of the color (0-255).\n * @param b - The blue component of the color (0-255).\n * @returns The RGB332 representation of the color as an 8-bit number.\n */\nconst rgbToRgb332 = (r: number, g: number, b: number): number =>\n ((r >> 5) << 5) | ((g >> 5) << 2) | (b >> 6);\n\n/**\n * Encodes an RGBA frame into a specified format.\n *\n * @param rgba - A `Uint8ClampedArray` containing the RGBA pixel data of the frame.\n * @param format - The desired output format. Can be either `'base64'` or `'rgb332'`.\n * - `'base64'`: Encodes the frame as a Base64 string.\n * - `'rgb332'`: Encodes the frame using the RGB332 color format.\n * @param stripAlpha - A boolean indicating whether to exclude the alpha channel\n * from the encoding. If `true`, the alpha channel is removed.\n\n * @returns A string representing the encoded frame in the specified format.\n */\nexport function encodeFrame(\n rgba: Uint8ClampedArray,\n format: \"base64\" | \"rgb332\",\n stripAlpha: boolean\n): string {\n if (format === \"base64\") {\n const rgb = stripAlpha\n ? rgba.filter((_, i) => i % 4 !== 3)\n : Array.from(rgba);\n return btoa(String.fromCharCode(...rgb));\n } else {\n const rgb332: number[] = [];\n for (let i = 0; i < rgba.length; i += 4) {\n rgb332.push(rgbToRgb332(rgba[i], rgba[i + 1], rgba[i + 2]));\n }\n return String.fromCharCode(...rgb332);\n }\n}\n","import { EventBus } from \"../../../common\";\nimport { kosDependency, kosModel } from \"../../../core/core/decorators\";\nimport type {\n IKosDataModel,\n KosContextLogger,\n KosCreationContext,\n} from \"../../../core/core/kosModel\";\nimport type { IKosIdentifiable } from \"../../../core/core/types\";\nimport type { PublicModelInterface } from \"../../../core/types\";\nimport { BrowserRouter, type KosBrowserRouter } from \"../browser-router\";\nimport type { DoneAware, Renderer } from \"../canvas-dispatcher\";\nimport { sendCanvasData } from \"../canvas-dispatcher/services\";\nimport { encodeFrame } from \"../canvas-dispatcher/utils/encode-frame\";\n\nimport type { CanvasRendererOptions } from \"./types\";\n\nexport const MODEL_TYPE = \"canvas-renderer-model\";\n\nexport type CanvasRendererModel = PublicModelInterface<CanvasRendererModelImpl>;\n\nfunction isDoneAware(obj: any): obj is DoneAware {\n return typeof obj.onDone === \"function\";\n}\n@kosModel(MODEL_TYPE)\nexport class CanvasRendererModelImpl\n implements IKosDataModel, IKosIdentifiable\n{\n id: string;\n\n @kosDependency({\n modelType: BrowserRouter.type,\n })\n private router!: KosBrowserRouter;\n private logger: KosContextLogger;\n private _renderer: Renderer | null = null;\n private _clearOnComplete: boolean | undefined = undefined;\n private isStreaming = false;\n private renderLoopId: number | null = null;\n private sendIntervalId: ReturnType<typeof setInterval> | null = null;\n private timeoutId: ReturnType<typeof setTimeout> | null = null;\n private apiPath: string;\n private endpointName: string;\n width = 50;\n height = 30;\n fps = 10;\n durationMs: number | null = null;\n private _onFrame: ((dataString: string) => void) | null = null;\n\n constructor(\n modelId: string,\n options: CanvasRendererOptions,\n context: KosCreationContext\n ) {\n this.id = modelId;\n this.logger = context.logger;\n\n this.width = options.width ?? 50;\n this.height = options.height ?? 30;\n this.fps = options.fps ?? 10;\n this.durationMs = options.durationMs ?? null;\n this.apiPath = options.apiPath ?? \"/api/system/canvas\";\n this.endpointName = options.endpoint;\n }\n\n set onFrame(callback: (dataString: string) => void) {\n this._onFrame = callback;\n }\n\n set renderer(renderer: Renderer | null) {\n if (this._renderer) {\n // If we already have a renderer, stop it first\n this.stopStreaming();\n this._renderer.dispose?.();\n }\n this._renderer = renderer;\n\n if (this.isStreaming) {\n // If we are currently streaming, restart the stream with the new renderer\n this.startStreaming();\n }\n }\n\n setClearOnComplete(clear: boolean | undefined) {\n this._clearOnComplete = clear;\n }\n\n /**\n * Sends a data frame to the canvas dispatcher.\n *\n * @param data - The data frame to be sent as a string.\n *\n * @remarks\n * This method is responsible for dispatching the provided data frame\n * to the canvas system using the `sendCanvasData` function.\n */\n sendDataFrame(data: string, apiPath?: string): void {\n sendCanvasData(data, apiPath);\n }\n\n checkStreaming() {\n // If one-shot renderer, stop after 1 frame\n if (this.isOneShotDone() || !this.isStreaming) {\n requestAnimationFrame(() => {\n // Don't clear canvas for one-shot renderers\n const isOneShot = this.isOneShotDone();\n this.stopStreaming(!isOneShot);\n });\n return;\n }\n }\n private handleFrame(rgba: Uint8ClampedArray) {\n const dataString = encodeFrame(rgba, \"base64\", true);\n this.sendDataFrame(dataString, this.apiPath);\n this._onFrame?.(dataString);\n }\n\n stopStreaming(clearCanvas = true) {\n this.logger.debug(`stopStreaming called with clearCanvas=${clearCanvas}`);\n this.isStreaming = false;\n if (this.renderLoopId) cancelAnimationFrame(this.renderLoopId);\n if (this.sendIntervalId) clearInterval(this.sendIntervalId);\n if (this.timeoutId) clearTimeout(this.timeoutId);\n this._renderer?.pause?.();\n\n // Clear the canvas by sending a blank frame (unless explicitly disabled)\n if (clearCanvas) {\n this.logger.debug(`Clearing canvas...`);\n this.clearCanvas();\n }\n }\n\n private clearCanvas(): void {\n // Use current dimensions if available, otherwise fall back to constructor defaults\n const canvasWidth = this.width > 0 ? this.width : 50; // Default from constructor\n const canvasHeight = this.height > 0 ? this.height : 30; // Default from constructor\n\n if (canvasWidth > 0 && canvasHeight > 0) {\n // Create a blank (black) frame\n const pixelCount = canvasWidth * canvasHeight * 4; // RGBA\n const blankPixels = new Uint8ClampedArray(pixelCount);\n // Array is initialized to 0s (black with 0 alpha), set alpha to 255 for solid black\n for (let i = 3; i < pixelCount; i += 4) {\n blankPixels[i] = 255; // Set alpha channel to fully opaque\n }\n\n // Send the blank frame\n const dataString = encodeFrame(blankPixels, \"base64\", true);\n this.logger.debug(\n `Sending clear frame: ${canvasWidth}x${canvasHeight}, apiPath: ${this.apiPath}`\n );\n this.sendDataFrame(dataString, this.apiPath);\n this._onFrame?.(dataString);\n }\n }\n\n isOneShotDone() {\n return (\n isDoneAware(this._renderer) &&\n this._renderer.isOneShot?.() === true &&\n (this._renderer as any).isOneShotDone\n );\n }\n\n startStreaming() {\n {\n if (!this._renderer) return;\n\n if (!this.apiPath) {\n this.logger.error(\n `No endpoint configured for canvas renderer ${this.id}`\n );\n return;\n }\n this.isStreaming = true;\n this._renderer.reset();\n this._renderer.play?.();\n\n const doneAware = isDoneAware(this._renderer);\n\n // Register completion callback for DoneAware renderers\n if (isDoneAware(this._renderer)) {\n this._renderer.onDone(() => {\n this.logger.debug(`Renderer completed for ${this.id}`);\n\n // Publish completion event to EventBus\n EventBus.publish(\"/canvas/renderer/completed\", {\n endpoint: this.endpointName,\n rendererId: this.id,\n rendererType: this._renderer?.constructor.name,\n timestamp: Date.now(),\n });\n\n // Determine whether to clear canvas on completion\n // Priority: explicit clearOnComplete > renderer type default\n let shouldClear = true;\n\n if (this._clearOnComplete !== undefined) {\n // Explicit setting takes precedence\n shouldClear = this._clearOnComplete;\n } else {\n // Default: clear for continuous renderers, keep for one-shot\n const isOneShot = (this._renderer as any)?.isOneShot?.() ?? false;\n shouldClear = !isOneShot;\n }\n\n this.stopStreaming(shouldClear);\n });\n }\n\n // Always render once immediately\n this._renderer.renderFrame(this.width, this.height);\n const initialPixels = this._renderer.readPixels?.(\n this.width,\n this.height\n );\n if (initialPixels && this._onFrame) {\n this.handleFrame(initialPixels);\n }\n\n // If one-shot renderer, stop after 1 frame\n if (this.isOneShotDone()) {\n requestAnimationFrame(() => {\n // Don't clear canvas for one-shot renderers\n this.stopStreaming(false);\n });\n return;\n }\n\n // Start rendering loop\n const renderLoop = () => {\n this._renderer?.renderFrame(this.width, this.height);\n this.renderLoopId = requestAnimationFrame(renderLoop);\n };\n this.renderLoopId = requestAnimationFrame(renderLoop);\n\n // Stream pixel data\n this.sendIntervalId = setInterval(() => {\n const pixels = this._renderer?.readPixels?.(this.width, this.height);\n if (pixels && this._onFrame) {\n this.handleFrame(pixels);\n this.checkStreaming();\n }\n }, 1000 / this.fps);\n\n // Stop non-DoneAware renderers after a fixed duration\n if (!doneAware && this.durationMs != null) {\n this.timeoutId = setTimeout(() => {\n this.stopStreaming();\n }, this.durationMs);\n }\n }\n }\n // -------------------LIFECYCLE----------------------------\n\n async init(): Promise<void> {\n this.logger.debug(`initializing canvas-renderer ${this.id}`);\n }\n\n async load(): Promise<void> {\n this.logger.debug(`loading canvas-renderer ${this.id}`);\n\n this.router.use(\n \"POST\",\n `/api/ui/canvas/${this.endpointName}/stop`,\n async (_req, res) => {\n this.logger.debug(`HTTP stop endpoint called for ${this.endpointName}`);\n this.stopStreaming();\n res.send({ status: \"OK\" });\n }\n );\n\n this.router.use(\n \"POST\",\n `/api/ui/canvas/${this.endpointName}/start`,\n async (_req, res) => {\n this.startStreaming();\n\n res.send({ status: \"OK\" });\n }\n );\n }\n}\n","import { KosModelRegistrationFactory } from \"../../../core/core/registration\";\nimport type { CanvasRendererModel } from \"./canvas-renderer-model\";\nimport { CanvasRendererModelImpl, MODEL_TYPE } from \"./canvas-renderer-model\";\nimport type { CanvasRendererOptions } from \"./types\";\n\n/**\n * # CanvasRenderer\n *\n * The registration bean includes convenience methods for creating and working with CanvasRendererModel instances.\n *\n * ## type\n * The type property is a string that identifies the model type.\n * The type is used to identify the model type in the model registry and to narrow down the model type in type predicates. It's most frequently\n * used when declaring dependencies on models.\n *\n * @example\n * ```typescript\n *\n * @kosDependency({modelType: CanvasRenderer.type, id: \"canvasRendererId\"})\n * private canvasRendererModel: CanvasRendererModel;\n * ```\n *\n *\n * ## factory\n *\n * The factory method creates a factory function that can be used to create new CanvasRendererModel instances.\n *\n \n * The factory function is a curried function that takes the model id as the first argument and the options as the second argument.\n *\n * If a model with the specified id already exists, the factory function will return the existing model. The options will be ignored\n * in this case and the existing model will be returned in its current state.\n *\n * @example\n * ```typescript\n * const model = CanvasRenderer.factory(\"canvasRendererId\")({\n * // Add option data\n * });\n * ```\n \n\n *\n * ## predicate\n *\n * [Typescript type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) function that will identify and narrow down a model to a CanvasRendererModel.\n *\n * @example\n * ```typescript\n *\n * const model: IKosDataModel = ...; // some model\n *\n * if (CanvasRenderer.predicate(model)) {\n * // if the function evaluates to true, the model is narrowed down to CanvasRendererModel\n * // and the compiler will know that the model has the CanvasRendererModel interface\n * model.updateAvailability(false);\n * }\n * ```\n *\n * ## registration\n *\n * The registration property is an object that can be used to simplify registration of the model with the model registry. The registration object\n * can be spread into the model registration and provides all of the required information to register the model implementation class against the model type.\n *\n *\n * @example\n *\n * In an application registration file you can declare the model registration as follows:\n *\n * **registration.ts**\n * ```typescript\n * import { CanvasRenderer } from \"@kos-ui/project-models\";\n * import { KosModelRegistry } from \"@kosdev-code/kos-dispense-sdk\";\n *\n * import { initKosProvider } from \"@kosdev-code/kos-ui-sdk\";\n *\n * KosModelRegistry.dispense\n * .models()\n * .model(CanvasRenderer);\n * ```\n *\n * ## registration.singleton\n \n * The canvasRenderer model is NOT a singleton model. This means that each time the factory function is called with a unique ID, a new model instance will be created.\n * If the factory function is called with an ID that already exists, the existing model will be returned.\n \n * */\nexport const CanvasRenderer = new KosModelRegistrationFactory<\n CanvasRendererModel,\n CanvasRendererOptions\n>({\n class: CanvasRendererModelImpl,\n type: MODEL_TYPE,\n});\n","import type { DoneAware, Renderer } from \"../../../types\";\n\n/**\n * A base class for rendering video frames using a 2D canvas.\n *\n * Provides utilities for frame capture, playback control, and detecting when a video has finished playing.\n * Implements the `Renderer` and `DoneAware` interfaces to integrate with a unified animation/rendering system.\n */\nexport class VideoRendererBase implements Renderer, DoneAware {\n /** The underlying HTML video element used as the media source */\n protected video: HTMLVideoElement;\n\n /** Internal offscreen canvas used to draw current video frame */\n protected canvas: HTMLCanvasElement;\n\n /** 2D rendering context for the offscreen canvas */\n protected ctx: CanvasRenderingContext2D;\n\n /** Timestamp of the last update (used for throttling if needed) */\n protected lastUpdate = 0;\n\n /** Callback to invoke when video playback completes */\n private doneCallback: (() => void) | null = null;\n\n /**\n * Constructs a video renderer that will play and extract pixels from the provided source.\n *\n * @param src - The URL or path of the video to play\n */\n constructor({ src }: { src: string }) {\n this.video = document.createElement(\"video\");\n this.video.src = src;\n this.video.crossOrigin = \"anonymous\"; // Allow CORS-safe use in canvas\n this.video.muted = true; // Prevent autoplay restrictions\n this.video.loop = false; // We trigger done manually when finished\n\n this.canvas = document.createElement(\"canvas\");\n const ctx = this.canvas.getContext(\"2d\");\n if (!ctx) throw new Error(\"2D canvas not supported\");\n this.ctx = ctx;\n\n this.handleEnded = this.handleEnded.bind(this);\n this.video.addEventListener(\"ended\", this.handleEnded);\n }\n\n private handleEnded(): void {\n if (this.doneCallback) this.doneCallback();\n }\n /**\n * Resets the video to the beginning and pauses playback.\n */\n reset(): void {\n this.video.pause();\n this.video.currentTime = 0;\n this.lastUpdate = performance.now();\n }\n\n /**\n * Starts or resumes playback of the video.\n */\n play(): void {\n this.video.play().catch(console.warn); // Prevent unhandled promise if autoplay fails\n }\n\n /**\n * Pauses video playback.\n */\n pause(): void {\n this.video.pause();\n }\n\n /**\n * Draws the current video frame onto the offscreen canvas at the given resolution.\n *\n * @param width - Desired canvas width\n * @param height - Desired canvas height\n */\n renderFrame(width: number, height: number): void {\n this.canvas.width = width;\n this.canvas.height = height;\n\n if (this.video.readyState >= 2) {\n this.ctx.drawImage(this.video, 0, 0, width, height);\n }\n }\n\n /**\n * Extracts the most recently rendered frame's pixel data as a flat RGBA array.\n *\n * @param width - Width of the canvas area to extract\n * @param height - Height of the canvas area to extract\n * @returns A Uint8ClampedArray containing RGBA values\n */\n readPixels(width: number, height: number): Uint8ClampedArray {\n return this.ctx.getImageData(0, 0, width, height).data;\n }\n\n /**\n * Registers a callback to be invoked once the video finishes playing.\n *\n * @param callback - Function to call on video end\n */\n onDone(callback: () => void): void {\n this.doneCallback = callback;\n }\n\n dispose(): void {\n this.video.pause();\n this.video.removeAttribute(\"src\");\n this.video.load(); // Unload the video data\n this.video.remove(); // Remove from DOM if ever added\n\n this.video.removeEventListener(\"ended\", this.handleEnded);\n this.doneCallback = null;\n }\n\n /**\n * Utility method for timing-based frame updates (optional use).\n *\n * @param intervalMs - Minimum time between steps in milliseconds\n * @returns `true` if enough time has passed to trigger a new update\n */\n protected shouldStep(intervalMs: number): boolean {\n const now = performance.now();\n if (now - this.lastUpdate >= intervalMs) {\n this.lastUpdate = now;\n return true;\n }\n return false;\n }\n}\n","import type { Renderer } from \"../../../types\";\n\n/**\n * Abstract base class for WebGL-based renderers.\n *\n * Provides a shared WebGL canvas, rendering context, and utility methods for\n * consistent pixel reading and throttled animation timing.\n */\nexport abstract class WebGLRendererBase implements Renderer {\n /** The internal offscreen canvas used for rendering */\n protected canvas: HTMLCanvasElement;\n\n /** The WebGL rendering context used to draw and sample frames */\n protected gl: WebGLRenderingContext;\n\n /** The last known canvas width used for reading pixels */\n protected lastWidth = 0;\n\n /** The last known canvas height used for reading pixels */\n protected lastHeight = 0;\n\n /** Timestamp of the last frame update used for throttling */\n protected lastUpdate = 0;\n\n constructor() {\n this.canvas = document.createElement(\"canvas\");\n const gl = this.canvas.getContext(\"webgl\");\n if (!gl) throw new Error(\"WebGL not supported\");\n this.gl = gl;\n }\n\n /**\n * Reset the internal renderer state.\n * Must be implemented by subclasses to reset animation state.\n */\n abstract reset(): void;\n\n /**\n * Render a frame at the given resolution into the internal WebGL canvas.\n * This method should perform the draw but not return the pixels.\n *\n * @param width - The width of the canvas to render to\n * @param height - The height of the canvas to render to\n */\n abstract renderFrame(width: number, height: number): void;\n\n /**\n * Throttle rendering logic based on a minimum time interval.\n *\n * @param intervalMs - The minimum time in milliseconds between steps\n * @returns `true` if enough time has passed to perform a new step\n */\n protected shouldStep(intervalMs: number): boolean {\n const now = performance.now();\n if (now - this.lastUpdate >= intervalMs) {\n this.lastUpdate = now;\n return true;\n }\n return false;\n }\n\n /**\n * Read and return the current pixel buffer from the WebGL canvas.\n * The result is vertically flipped to match 2D canvas expectations.\n *\n * @param width - Optional override for width (defaults to `lastWidth`)\n * @param height - Optional override for height (defaults to `lastHeight`)\n * @returns A `Uint8ClampedArray` of RGBA pixel data\n */\n readPixels(\n width = this.lastWidth,\n height = this.lastHeight\n ): Uint8ClampedArray {\n const pixels = new Uint8Array(width * height * 4);\n this.gl.readPixels(\n 0,\n 0,\n width,\n height,\n this.gl.RGBA,\n this.gl.UNSIGNED_BYTE,\n pixels\n );\n\n // WebGL stores pixels from bottom-to-top; flip to match top-to-bottom\n const flipped = new Uint8ClampedArray(pixels.length);\n for (let y = 0; y < height; y++) {\n const src = y * width * 4;\n const dst = (height - 1 - y) * width * 4;\n flipped.set(pixels.subarray(src, src + width * 4), dst);\n }\n\n return flipped;\n }\n}\n","import type { Renderer } from \"../../types\";\nimport { WebGLRendererBase } from \"./base/webgl-base-renderer\";\n\n/**\n * A WebGL-based renderer that creates a vertical color-drop animation.\n *\n * This renderer simulates falling color bands (like a waterfall or rain)\n * by animating a vertical gradient of hues within a specified hue range.\n *\n * The animation is driven by a shader program and controlled through\n * uniform parameters including `hueOffset`, `minHue`, and `maxHue`.\n */\nexport class DropRenderer extends WebGLRendererBase implements Renderer {\n // Shader program and related attribute/uniform handles\n private program: WebGLProgram;\n private posBuffer: WebGLBuffer;\n private aPosition: number;\n private uMinHue: WebGLUniformLocation;\n private uMaxHue: WebGLUniformLocation;\n private uHueOffset: WebGLUniformLocation;\n private uGridHeight: WebGLUniformLocation;\n\n // Animation state\n private minHue = 0;\n private maxHue = 80;\n private hueOffset = 0;\n private speedPx = 1; // vertical scroll speed in pixels per update\n\n /**\n * Creates a new DropRenderer with the specified scroll speed.\n * @param speedPx - The vertical speed in pixels per update cycle.\n */\n constructor({ speedPx = 1 }: { speedPx?: number } = {}) {\n super();\n this.speedPx = speedPx;\n\n const gl = this.gl;\n\n const vertexShaderSource = `\n attribute vec2 a_position;\n void main() {\n gl_Position = vec4(a_position, 0, 1);\n }\n `;\n\n const fragmentShaderSource = `\n precision mediump float;\n uniform float minHue;\n uniform float maxHue;\n uniform float hueOffset;\n uniform float gridHeight;\n\n vec3 hslToRgb(float h, float s, float l) {\n float c = (1.0 - abs(2.0 * l - 1.0)) * s;\n float x = c * (1.0 - abs(mod(h * 6.0, 2.0) - 1.0));\n float m = l - c / 2.0;\n vec3 rgb;\n\n if (h < 1.0/6.0) rgb = vec3(c, x, 0.0);\n else if (h < 2.0/6.0) rgb = vec3(x, c, 0.0);\n else if (h < 3.0/6.0) rgb = vec3(0.0, c, x);\n else if (h < 4.0/6.0) rgb = vec3(0.0, x, c);\n else if (h < 5.0/6.0) rgb = vec3(x, 0.0, c);\n else rgb = vec3(c, 0.0, x);\n\n return rgb + vec3(m);\n }\n\n void main() {\n float relY = mod((1.0 - gl_FragCoord.y / gridHeight) - hueOffset, 1.0);\n float hue = minHue + relY * (maxHue - minHue);\n vec3 rgb = hslToRgb(hue, 1.0, 0.5);\n gl_FragColor = vec4(rgb, 1.0);\n }\n `;\n\n // Compile and link shaders\n const vertexShader = this.compileShader(\n gl.VERTEX_SHADER,\n vertexShaderSource\n );\n const fragmentShader = this.compileShader(\n gl.FRAGMENT_SHADER,\n fragmentShaderSource\n );\n this.program = this.createProgram(vertexShader, fragmentShader);\n\n // Set up vertex buffer for a full-screen quad\n this.posBuffer = gl.createBuffer()!;\n gl.bindBuffer(gl.ARRAY_BUFFER, this.posBuffer);\n gl.bufferData(\n gl.ARRAY_BUFFER,\n new Float32Array([-1, -1, 1, -1, -1, 1, -1, 1, 1, -1, 1, 1]),\n gl.STATIC_DRAW\n );\n\n // Locate attribute and uniform bindings\n this.aPosition = gl.getAttribLocation(this.program, \"a_position\");\n this.uMinHue = gl.getUniformLocation(this.program, \"minHue\")!;\n this.uMaxHue = gl.getUniformLocation(this.program, \"maxHue\")!;\n this.uHueOffset = gl.getUniformLocation(this.program, \"hueOffset\")!;\n this.uGridHeight = gl.getUniformLocation(this.program, \"gridHeight\")!;\n }\n\n /**\n * Resets the renderer's animation state to its initial values.\n */\n reset(): void {\n this.hueOffset = 0;\n this.lastUpdate = performance.now();\n }\n\n /**\n * Renders a new frame by updating hueOffset and redrawing the gradient.\n *\n * @param width - Width of the output frame\n * @param height - Height of the output frame\n */\n renderFrame(width: number, height: number): void {\n const gl = this.gl;\n this.canvas.width = width;\n this.canvas.height = height;\n\n if (this.shouldStep(50)) {\n // Convert pixel-based speed to relative offset (0 to 1)\n const normalizedSpeed = this.speedPx / height;\n this.hueOffset = (this.hueOffset + normalizedSpeed) % 1.0;\n }\n\n gl.viewport(0, 0, width, height);\n gl.clear(gl.COLOR_BUFFER_BIT);\n\n gl.useProgram(this.program);\n\n gl.enableVertexAttribArray(this.aPosition);\n gl.bindBuffer(gl.ARRAY_BUFFER, this.posBuffer);\n gl.vertexAttribPointer(this.aPosition, 2, gl.FLOAT, false, 0, 0);\n\n // Pass uniforms to shader\n gl.uniform1f(this.uMinHue, this.minHue / 360.0);\n gl.uniform1f(this.uMaxHue, this.maxHue / 360.0);\n gl.uniform1f(this.uHueOffset, this.hueOffset);\n gl.uniform1f(this.uGridHeight, height);\n\n gl.drawArrays(gl.TRIANGLES, 0, 6);\n }\n\n /**\n * Compiles a GLSL shader of the given type.\n *\n * @param type - gl.VERTEX_SHADER or gl.FRAGMENT_SHADER\n * @param source - GLSL source code\n * @returns The compiled shader object\n */\n private compileShader(type: number, source: string): WebGLShader {\n const shader = this.gl.createShader(type)!;\n this.gl.shaderSource(shader, source);\n this.gl.compileShader(shader);\n if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) {\n throw new Error(\n this.gl.getShaderInfoLog(shader) || \"Shader compile failed\"\n );\n }\n return shader;\n }\n\n /**\n * Links a vertex and fragment shader into a complete WebGL program.\n *\n * @param vertexShader - Compiled vertex shader\n * @param fragmentShader - Compiled fragment shader\n * @returns The linked WebGL program\n */\n private createProgram(\n vertexShader: WebGLShader,\n fragmentShader: WebGLShader\n ): WebGLProgram {\n const program = this.gl.createProgram()!;\n this.gl.attachShader(program, vertexShader);\n this.gl.attachShader(program, fragmentShader);\n this.gl.linkProgram(program);\n if (!this.gl.getProgramParameter(program, this.gl.LINK_STATUS)) {\n throw new Error(\"Program linking failed\");\n }\n return program;\n }\n}\n","import type { Renderer } from \"../../../types\";\n\n/**\n * An abstract base class for 2D canvas rendering. This class provides a foundational\n * implementation for managing a canvas element and its 2D rendering context, as well\n * as utility methods for rendering and pixel data extraction.\n *\n * Subclasses must implement the `reset` and `renderFrame` methods to define specific\n * rendering behavior.\n *\n * @implements Renderer\n */\nexport abstract class Canvas2DRendererBase implements Renderer {\n protected canvas: HTMLCanvasElement;\n protected ctx: CanvasRenderingContext2D;\n protected lastUpdate = 0;\n\n constructor() {\n this.canvas = document.createElement(\"canvas\");\n const ctx = this.canvas.getContext(\"2d\");\n if (!ctx) throw new Error(\"2D canvas not supported\");\n this.ctx = ctx;\n }\n\n dispose(): void {\n this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);\n this.canvas.remove();\n }\n /**\n * Determines whether a specified time interval has elapsed since the last update.\n *\n * @param intervalMs - The time interval in milliseconds to check against.\n * @returns `true` if the elapsed time since the last update is greater than or equal to the specified interval; otherwise, `false`.\n */\n protected shouldStep(intervalMs: number): boolean {\n const now = performance.now();\n if (now - this.lastUpdate >= intervalMs) {\n this.lastUpdate = now;\n return true;\n }\n return false;\n }\n abstract reset(): void;\n abstract renderFrame(width: number, height: number): void;\n\n /**\n * Reads pixel data from the canvas context within the specified width and height.\n *\n * @param width - The width of the area to read pixels from, starting at the top-left corner (0, 0).\n * @param height - The height of the area to read pixels from, starting at the top-left corner (0, 0).\n * @returns A `Uint8ClampedArray` containing the RGBA pixel data for the specified area.\n */\n readPixels(width: number, height: number): Uint8ClampedArray {\n return this.ctx.getImageData(0, 0, width, height).data;\n }\n}\n","import type { OneShotCapable } from \"../../../types\";\n\nexport type AbstractConstructor<T = any> = abstract new (...args: any[]) => T;\n\nexport function OneShotRendererMixin<TBase extends AbstractConstructor>(\n Base: TBase\n): AbstractConstructor<InstanceType<TBase> & OneShotCapable> {\n abstract class Mixin extends Base implements OneShotCapable {\n private doneCallback: (() => void) | null = null;\n private oneShotDone = false;\n\n isOneShot(): boolean {\n return true;\n }\n\n onDone(cb: () => void): void {\n this.doneCallback = cb;\n }\n\n public signalDoneIfNeeded(): void {\n if (!this.oneShotDone) {\n this.doneCallback?.();\n this.oneShotDone = true;\n }\n }\n\n public resetOneShot(): void {\n this.doneCallback = null;\n this.oneShotDone = false;\n }\n\n public get isOneShotDone(): boolean {\n return this.oneShotDone;\n }\n }\n\n return Mixin as unknown as AbstractConstructor<\n InstanceType<TBase> & OneShotCapable\n >;\n}\n","import type { OneShotCapable, Renderer } from \"../../types\";\nimport { Canvas2DRendererBase } from \"./base/canvas-2d-renderer\";\nimport { OneShotRendererMixin } from \"./mixins/one-shot-renderer-mixin\";\n\nconst GradientBase = OneShotRendererMixin(Canvas2DRendererBase);\n\nexport type GradientDirection = \"horizontal\" | \"vertical\" | \"radial\";\n\nexport class GradientRenderer\n extends GradientBase\n implements Renderer, OneShotCapable\n{\n private offset = 0;\n private speed: number;\n private colors: string[];\n private direction: GradientDirection;\n private loop: boolean;\n\n constructor({\n colors = [\"red\", \"yellow\", \"green\"],\n direction = \"horizontal\",\n speed = 2,\n loop = true,\n }: {\n colors?: string[];\n direction?: GradientDirection;\n speed?: number;\n loop?: boolean;\n } = {}) {\n super();\n this.colors = colors;\n this.direction = direction;\n this.speed = speed;\n this.loop = loop;\n }\n\n override reset(): void {\n this.offset = 0;\n this.lastUpdate = performance.now();\n if (!this.loop) this.resetOneShot();\n }\n\n override renderFrame(width: number, height: number): void {\n if (!this.loop && this.isOneShotDone) return;\n\n // Only update offset if looping\n if (this.loop && this.shouldStep(50)) {\n this.offset += this.speed;\n }\n\n const startX = this.loop ? -this.offset : 0;\n const endX = this.loop ? width * 2 - this.offset : width;\n\n const gradient = this.ctx.createLinearGradient(startX, 0, endX, 0);\n const step = 1 / (this.colors.length - 1);\n this.colors.forEach((color, i) => {\n gradient.addColorStop(i * step, color);\n });\n\n this.ctx.fillStyle = gradient;\n this.ctx.fillRect(0, 0, width, height);\n\n // If one-shot, signal done right after rendering once\n if (!this.loop && !this.isOneShotDone) {\n this.signalDoneIfNeeded();\n }\n }\n}\n","import type { OneShotCapable, Renderer } from \"../../types\";\nimport { Canvas2DRendererBase } from \"./base/canvas-2d-renderer\";\nimport { OneShotRendererMixin } from \"./mixins/one-shot-renderer-mixin\";\n\nconst Base = OneShotRendererMixin(Canvas2DRendererBase);\n\nexport class ImageRenderer extends Base implements Renderer, OneShotCapable {\n private img: HTMLImageElement;\n private loaded = false;\n\n constructor({ src }: { src: string }) {\n super();\n this.img = new Image();\n this.img.src = src;\n this.img.crossOrigin = \"anonymous\";\n\n this.img.onload = () => {\n this.loaded = true;\n // this.signalDoneIfNeeded();\n };\n }\n\n override reset(): void {\n this.resetOneShot();\n // Optionally reset loaded state if reusing src dynamically\n }\n\n override renderFrame(width: number, height: number): void {\n if (!this.loaded || this.isOneShotDone) return;\n\n this.canvas.width = width;\n this.canvas.height = height;\n this.ctx.drawImage(this.img, 0, 0, width, height);\n\n this.signalDoneIfNeeded();\n }\n}\n","import type { VideoRenderDataSpecification } from \"../../types\";\nimport { VideoRendererBase } from \"./base/video-base-renderer\";\n\n/**\n * Enhanced video renderer with configurable looping support.\n *\n * Supports:\n * - Infinite looping (loop: true)\n * - Fixed number of loops (loop: number)\n * - Single play (loop: false or undefined)\n * - Start/end time trimming\n */\nexport class LoopingVideoRenderer extends VideoRendererBase {\n private loopConfig: boolean | number;\n private currentLoopCount = 0;\n private startTime: number;\n private endTime: number | null;\n private completionCallback: (() => void) | null = null;\n\n constructor(data: VideoRenderDataSpecification) {\n super(data);\n\n this.loopConfig = data.loop ?? false;\n this.startTime = data.startTime ?? 0;\n this.endTime = data.endTime ?? null;\n\n // Remove the base class ended handler and use our own\n this.video.removeEventListener(\"ended\", (this as any).handleEnded);\n this.video.addEventListener(\"ended\", this.handleVideoEnd.bind(this));\n\n // Set initial start time if specified\n if (this.startTime > 0) {\n this.video.currentTime = this.startTime;\n }\n\n // Handle end time if specified\n if (this.endTime !== null) {\n this.video.addEventListener(\n \"timeupdate\",\n this.handleTimeUpdate.bind(this)\n );\n }\n }\n\n private handleTimeUpdate(): void {\n if (this.endTime !== null && this.video.currentTime >= this.endTime) {\n this.handleVideoEnd();\n }\n }\n\n private handleVideoEnd(): void {\n if (this.loopConfig === true) {\n // Infinite loop\n this.video.currentTime = this.startTime;\n this.video.play().catch(console.warn);\n } else if (\n typeof this.loopConfig === \"number\" &&\n this.currentLoopCount < this.loopConfig - 1\n ) {\n // Still have loops remaining\n this.currentLoopCount++;\n this.video.currentTime = this.startTime;\n this.video.play().catch(console.warn);\n } else {\n // All loops complete or single play done\n this.video.pause();\n if (this.completionCallback) {\n this.completionCallback();\n }\n }\n }\n\n override reset(): void {\n super.reset();\n this.currentLoopCount = 0;\n this.video.currentTime = this.startTime;\n }\n\n override onDone(callback: () => void): void {\n this.completionCallback = callback;\n }\n\n /**\n * Returns true if this renderer should only play once (no looping)\n */\n isOneShot(): boolean {\n return this.loopConfig === false || this.loopConfig === 1;\n }\n\n override dispose(): void {\n this.video.removeEventListener(\"ended\", this.handleVideoEnd);\n this.video.removeEventListener(\"timeupdate\", this.handleTimeUpdate);\n this.completionCallback = null;\n super.dispose();\n }\n}\n","/**\n * Color utility functions for canvas renderers\n */\n\nexport interface RgbColor {\n r: number;\n g: number;\n b: number;\n}\n\n/**\n * Converts a hex color string to RGB values\n * @param hex - Hex color string (with or without #, e.g., \"#ff0000\", \"ff0000\", \"#f00\", \"f00\")\n * @returns RGB color object with r, g, b values (0-255)\n * @throws Error if hex string is invalid\n */\nexport function hexToRgb(hex: string): RgbColor {\n // Remove # if present\n const cleanHex = hex.replace(\"#\", \"\");\n\n // Validate hex string\n if (!/^[0-9A-Fa-f]{3}$|^[0-9A-Fa-f]{6}$/.test(cleanHex)) {\n throw new Error(`Invalid hex color: ${hex}`);\n }\n\n let r: number, g: number, b: number;\n\n if (cleanHex.length === 3) {\n // Short form: \"f0a\" -> \"ff00aa\"\n r = parseInt(cleanHex[0] + cleanHex[0], 16);\n g = parseInt(cleanHex[1] + cleanHex[1], 16);\n b = parseInt(cleanHex[2] + cleanHex[2], 16);\n } else {\n // Long form: \"ff00aa\"\n r = parseInt(cleanHex.substring(0, 2), 16);\n g = parseInt(cleanHex.substring(2, 4), 16);\n b = parseInt(cleanHex.substring(4, 6), 16);\n }\n\n return { r, g, b };\n}\n\n/**\n * Normalizes a color value to RGB format\n * @param color - Either an RGB object or hex string\n * @returns RGB color object with r, g, b values (0-255)\n */\nexport function normalizeColor(color: RgbColor | string): RgbColor {\n if (typeof color === \"string\") {\n return hexToRgb(color);\n }\n return color;\n}\n\n/**\n * Converts RGB values to a CSS-compatible rgb() string\n * @param color - RGB color object or hex string\n * @returns CSS rgb() string, e.g., \"rgb(255,0,0)\"\n */\nexport function toRgbString(color: RgbColor | string): string {\n const rgb = normalizeColor(color);\n return `rgb(${rgb.r},${rgb.g},${rgb.b})`;\n}\n\n/**\n * Converts RGB values to hex string\n * @param color - RGB color object\n * @returns Hex color string with # prefix, e.g., \"#ff0000\"\n */\nexport function rgbToHex(color: RgbColor): string {\n const toHex = (n: number) =>\n Math.max(0, Math.min(255, Math.round(n)))\n .toString(16)\n .padStart(2, \"0\");\n return `#${toHex(color.r)}${toHex(color.g)}${toHex(color.b)}`;\n}\n","import type { Renderer, MatrixRenderDataSpecification } from \"../../types\";\nimport { Canvas2DRendererBase } from \"./base/canvas-2d-renderer\";\nimport { normalizeColor } from \"../color-utils\";\n\n/**\n * A falling-character visual effect inspired by the Matrix.\n *\n * This renderer creates animated vertical columns of glowing characters that fall\n * at different speeds and randomness, using a 2D canvas buffer.\n */\nexport class MatrixRenderer extends Canvas2DRendererBase implements Renderer {\n /** Tracks the Y position of the falling highlight in each column */\n private columns: number[] = [];\n\n /** Probability that a column will advance during an update */\n private fallChance: number;\n\n /** Vertical step size (in pixels) for falling columns */\n private speed: number;\n\n /** Base color for the matrix rain effect */\n private baseColor: { r: number; g: number; b: number };\n\n /** Calculated colors for different trail positions */\n private trailColors: Array<{ r: number; g: number; b: number }>;\n\n /**\n * Constructs a Matrix-style renderer.\n *\n * @param data - Matrix renderer configuration\n */\n constructor(data: MatrixRenderDataSpecification = {}) {\n super();\n this.speed = data.speed ?? 1;\n this.fallChance = data.fallChance ?? 0.7;\n\n // Default to cyan if no color provided, normalize color if provided\n if (data.baseColor) {\n this.baseColor = normalizeColor(data.baseColor);\n } else {\n this.baseColor = { r: 0, g: 255, b: 255 }; // Default cyan\n }\n\n // Pre-calculate trail colors based on the base color\n this.trailColors = this.calculateTrailColors();\n }\n\n /**\n * Calculates the trail colors based on the base color.\n * Creates a gradient from bright to dim for the trailing effect.\n */\n private calculateTrailColors(): Array<{ r: number; g: number; b: number }> {\n const trailLength = 5;\n const colors: Array<{ r: number; g: number; b: number }> = [];\n\n for (let i = 0; i <= trailLength; i++) {\n // Calculate fade factor (1.0 at head, decreasing towards tail)\n const fadeFactor = 1.0 - (i / trailLength) * 0.6; // Fade to 40% brightness\n\n colors.push({\n r: Math.floor(this.baseColor.r * fadeFactor),\n g: Math.floor(this.baseColor.g * fadeFactor),\n b: Math.floor(this.baseColor.b * fadeFactor),\n });\n }\n\n return colors;\n }\n\n /**\n * Resets all column positions and timing state.\n */\n reset(): void {\n this.columns = [];\n this.lastUpdate = performance.now();\n }\n\n /**\n * Renders the next frame of the animation into the internal canvas buffer.\n *\n * @param width - Width of the canvas in pixels\n * @param height - Height of the canvas in pixels\n */\n renderFrame(width: number, height: number): void {\n // Initialize columns randomly if width changed or first render\n if (this.columns.length !== width) {\n this.columns = Array(width)\n .fill(0)\n .map(() => Math.floor(Math.random() * height));\n }\n\n // Advance column positions based on fallChance and speed\n if (this.shouldStep(50)) {\n this.columns = this.columns.map((y) =>\n y > height + 5\n ? 0\n : y + (Math.random() < this.fallChance ? this.speed : 0)\n );\n }\n\n // Create a new pixel buffer\n const imageData = this.ctx.createImageData(width, height);\n const data = imageData.data;\n data.fill(0); // Fully transparent black base\n\n // Draw glow trails and leading dots for each column\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n const colY = this.columns[x];\n let r = 0,\n g = 0,\n b = 0;\n\n if (y === colY) {\n // Brightest point - use the base color at full intensity\n r = this.baseColor.r;\n g = this.baseColor.g;\n b = this.baseColor.b;\n } else if (y < colY && y > colY - this.trailColors.length) {\n // Trailing glow - use pre-calculated trail colors\n const trailIndex = colY - y;\n if (trailIndex < this.trailColors.length) {\n const color = this.trailColors[trailIndex];\n r = color.r;\n g = color.g;\n b = color.b;\n }\n }\n\n const i = (y * width + x) * 4;\n data[i] = r;\n data[i + 1] = g;\n data[i + 2] = b;\n data[i + 3] = 255; // fully opaque\n }\n }\n\n // Write pixel buffer to canvas\n this.ctx.putImageData(imageData, 0, 0);\n }\n}\n","import type { DoneAware, Renderer } from \"../../types\";\n\n/**\n * Predefined overlay positions for easy positioning\n */\nexport type OverlayPosition =\n | \"top-left\"\n | \"top-center\"\n | \"top-right\"\n | \"center-left\"\n | \"center\"\n | \"center-right\"\n | \"bottom-left\"\n | \"bottom-center\"\n | \"bottom-right\";\n\n/**\n * Custom positioning with explicit coordinates\n */\nexport interface OverlayCustomPosition {\n x: number;\n y: number;\n}\n\n/**\n * Configuration for a single overlay icon\n */\nexport interface OverlayIconConfig {\n /** Image source for the overlay icon */\n src: string;\n /** Size of the overlay icon (width and height) */\n size: number;\n /** Position of the overlay - either predefined name or custom coordinates */\n position: OverlayPosition | OverlayCustomPosition;\n /** Optional offset from the position in pixels */\n offset?: { x?: number; y?: number };\n /** Optional opacity (0-1) */\n opacity?: number;\n /** Whether the overlay should always be visible (default: true) */\n persistent?: boolean;\n}\n\n/**\n * Configuration for overlay renderer\n */\nexport interface OverlayRenderDataSpecification {\n /** The base renderer configuration */\n baseRenderer: {\n type: string;\n data: any;\n };\n /** Array of overlay icons to display */\n overlays: OverlayIconConfig[];\n /** Whether overlays should remain visible after base renderer completes (default: true) */\n persistOverlaysOnComplete?: boolean;\n}\n\n/**\n * A renderer that wraps another renderer and adds static overlay icons\n * that are not affected by scrolling, scaling, or other transformations.\n */\nexport class OverlayRenderer implements Renderer, DoneAware {\n private baseRenderer: Renderer;\n private overlayIcons: Map<string, HTMLImageElement> = new Map();\n private overlayConfigs: OverlayIconConfig[];\n private loadedIcons = new Set<string>();\n private canvas: HTMLCanvasElement;\n private ctx: CanvasRenderingContext2D;\n private persistOverlaysOnComplete: boolean;\n private baseRendererCompleted = false;\n private completionCallback: (() => void) | null = null;\n private hasSignaledCompletion = false;\n\n constructor(\n data: OverlayRenderDataSpecification,\n rendererFactory: (type: string, data: any) => Renderer\n ) {\n // Create the base renderer\n this.baseRenderer = rendererFactory(\n data.baseRenderer.type,\n data.baseRenderer.data\n );\n this.overlayConfigs = data.overlays;\n this.persistOverlaysOnComplete = data.persistOverlaysOnComplete !== false; // Default to true\n\n // Create our own canvas for compositing\n this.canvas = document.createElement(\"canvas\");\n const ctx = this.canvas.getContext(\"2d\");\n if (!ctx) throw new Error(\"2D canvas not supported\");\n this.ctx = ctx;\n\n // Load overlay images\n this.loadOverlayImages();\n\n // Listen for base renderer completion if it supports DoneAware\n if (\n \"onDone\" in this.baseRenderer &&\n typeof this.baseRenderer.onDone === \"function\"\n ) {\n (this.baseRenderer as any).onDone(() => {\n this.baseRendererCompleted = true;\n // When base completes and we should NOT persist, signal our completion\n if (!this.persistOverlaysOnComplete && this.completionCallback) {\n this.completionCallback();\n }\n });\n }\n }\n\n private async loadOverlayImages(): Promise<void> {\n for (const overlay of this.overlayConfigs) {\n const img = new Image();\n img.crossOrigin = \"anonymous\";\n\n img.onload = () => {\n this.loadedIcons.add(overlay.src);\n };\n\n img.onerror = (error) => {\n console.error(`Failed to load overlay image: ${overlay.src}`, error);\n };\n\n img.src = overlay.src;\n this.overlayIcons.set(overlay.src, img);\n }\n }\n\n private calculateOverlayPosition(\n overlay: OverlayIconConfig,\n canvasWidth: number,\n canvasHeight: number\n ): { x: number; y: number } {\n let x: number;\n let y: number;\n\n if (typeof overlay.position === \"string\") {\n // Predefined position\n switch (overlay.position) {\n case \"top-left\":\n x = 0;\n y = 0;\n break;\n case \"top-center\":\n x = (canvasWidth - overlay.size) / 2;\n y = 0;\n break;\n case \"top-right\":\n x = canvasWidth - overlay.size;\n y = 0;\n break;\n case \"center-left\":\n x = 0;\n y = (canvasHeight - overlay.size) / 2;\n break;\n case \"center\":\n x = (canvasWidth - overlay.size) / 2;\n y = (canvasHeight - overlay.size) / 2;\n break;\n case \"center-right\":\n x = canvasWidth - overlay.size;\n y = (canvasHeight - overlay.size) / 2;\n break;\n case \"bottom-left\":\n x = 0;\n y = canvasHeight - overlay.size;\n break;\n case \"bottom-center\":\n x = (canvasWidth - overlay.size) / 2;\n y = canvasHeight - overlay.size;\n break;\n case \"bottom-right\":\n x = canvasWidth - overlay.size;\n y = canvasHeight - overlay.size;\n break;\n default:\n x = 0;\n y = 0;\n }\n } else {\n // Custom position\n x = overlay.position.x;\n y = overlay.position.y;\n }\n\n // Apply offset if provided\n if (overlay.offset) {\n x += overlay.offset.x || 0;\n y += overlay.offset.y || 0;\n }\n\n return { x, y };\n }\n\n reset(): void {\n this.baseRenderer.reset();\n this.baseRendererCompleted = false;\n this.hasSignaledCompletion = false;\n }\n\n renderFrame(width: number, height: number): void {\n // Set canvas size - this clears the canvas\n this.canvas.width = width;\n this.canvas.height = height;\n\n // Clear the canvas explicitly\n this.ctx.clearRect(0, 0, width, height);\n\n // If base renderer has completed and we persist overlays\n if (this.baseRendererCompleted && this.persistOverlaysOnComplete) {\n // Just render overlays on clear canvas\n this.renderOverlays(width, height);\n } else {\n // Normal operation: render base content + overlays\n\n // Call base renderer's renderFrame\n this.baseRenderer.renderFrame(width, height);\n\n // Get the base renderer's pixel data\n const basePixels = this.baseRenderer.readPixels(width, height);\n\n // Put base content on our canvas if it exists\n if (basePixels && basePixels.length > 0) {\n const imageData = new ImageData(\n basePixels as unknown as Uint8ClampedArray<ArrayBuffer>,\n width,\n height\n );\n this.ctx.putImageData(imageData, 0, 0);\n }\n\n // Render overlays on top\n this.renderOverlays(width, height);\n }\n }\n\n private renderOverlays(canvasWidth: number, canvasHeight: number): void {\n for (const overlay of this.overlayConfigs) {\n if (!overlay.persistent && overlay.persistent !== undefined) {\n continue; // Skip non-persistent overlays when not needed\n }\n\n const img = this.overlayIcons.get(overlay.src);\n if (!img || !this.loadedIcons.has(overlay.src)) {\n continue; // Skip if image not loaded\n }\n\n const position = this.calculateOverlayPosition(\n overlay,\n canvasWidth,\n canvasHeight\n );\n\n // Save context state\n this.ctx.save();\n\n // Apply opacity if specified\n if (overlay.opacity !== undefined) {\n this.ctx.globalAlpha = Math.max(0, Math.min(1, overlay.opacity));\n }\n\n // Draw the overlay icon\n this.ctx.drawImage(\n img,\n position.x,\n position.y,\n overlay.size,\n overlay.size\n );\n\n // Restore context state\n this.ctx.restore();\n }\n }\n\n readPixels(width: number, height: number): Uint8ClampedArray {\n // Return current canvas pixels\n return this.ctx.getImageData(0, 0, width, height).data;\n }\n\n play?(): void {\n if (this.baseRenderer.play) {\n this.baseRenderer.play();\n }\n }\n\n pause?(): void {\n if (this.baseRenderer.pause) {\n this.baseRenderer.pause();\n }\n }\n\n dispose?(): void {\n // Clean up overlay images\n this.overlayIcons.clear();\n this.loadedIcons.clear();\n\n // Clean up canvas\n this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);\n this.canvas.remove();\n\n // Dispose base renderer\n if (this.baseRenderer.dispose) {\n this.baseRenderer.dispose();\n }\n }\n\n // DoneAware implementation\n onDone(callback: () => void): void {\n this.completionCallback = callback;\n\n // If base renderer is already completed, we might need to call the callback\n if (this.hasSignaledCompletion) {\n callback();\n }\n }\n\n isOneShot?(): boolean {\n // Never act as one-shot if we persist overlays (we need to keep rendering them)\n if (this.persistOverlaysOnComplete) {\n return false;\n }\n\n // Otherwise, delegate to base renderer\n if (\n \"isOneShot\" in this.baseRenderer &&\n typeof this.baseRenderer.isOneShot === \"function\"\n ) {\n return (this.baseRenderer as any).isOneShot();\n }\n return false;\n }\n}\n","import type {\n DoneAware,\n ImageRenderDataSpecification,\n Renderer,\n} from \"../../types\";\nimport { Canvas2DRendererBase } from \"./base/canvas-2d-renderer\";\nimport { toRgbString } from \"../color-utils\";\n\n/**\n * Enhanced image renderer with scrolling capabilities.\n *\n * Features:\n * - Smooth scrolling in any direction\n * - Configurable speed and gap\n * - Looping support\n * - Completion events when scroll finishes (if not looping)\n */\nexport class ScrollingImageRenderer\n extends Canvas2DRendererBase\n implements Renderer, DoneAware\n{\n private img: HTMLImageElement;\n private loaded = false;\n private scrollConfig: ImageRenderDataSpecification[\"scroll\"];\n private loopConfig: boolean | number;\n private duration: number | undefined;\n private pauseDuration: number;\n private colorOverride: ImageRenderDataSpecification[\"colorOverride\"];\n private originalSvgData: string | null = null;\n private position = 0;\n private startTime = 0;\n private lastFrameTime = 0;\n private currentLoopCount = 0;\n private completionCallback: (() => void) | null = null;\n private isPlaying = false;\n private completed = false;\n private isPaused = false;\n private pauseStartTime = 0;\n\n constructor(data: ImageRenderDataSpecification) {\n super();\n\n this.img = new Image();\n this.img.crossOrigin = \"anonymous\";\n\n this.scrollConfig = data.scroll;\n this.loopConfig = data.loop ?? false;\n this.duration = data.duration;\n this.pauseDuration = data.pauseBetweenLoops ?? 0;\n this.colorOverride = data.colorOverride;\n\n // Check if this is an SVG and we have color override\n if (this.colorOverride && data.src.toLowerCase().includes(\".svg\")) {\n this.loadAndProcessSvg(data.src);\n } else {\n this.img.src = data.src;\n }\n\n this.img.onload = () => {\n this.loaded = true;\n };\n\n this.img.onerror = (error) => {\n console.error(\"Failed to load image:\", error);\n };\n }\n\n override reset(): void {\n this.position = 0;\n this.startTime = performance.now();\n this.lastFrameTime = this.startTime;\n this.currentLoopCount = 0;\n this.completed = false;\n this.isPlaying = false;\n this.isPaused = false;\n this.pauseStartTime = 0;\n }\n\n play(): void {\n if (!this.isPlaying) {\n this.isPlaying = true;\n this.startTime = performance.now();\n this.lastFrameTime = this.startTime;\n }\n }\n\n pause(): void {\n this.isPlaying = false;\n }\n\n override renderFrame(width: number, height: number): void {\n if (!this.loaded) {\n // Image not loaded yet\n return;\n }\n\n if (this.completed) {\n // Animation completed - keep showing last frame\n return;\n }\n\n if (this.isPaused) {\n // During pause, show blank screen\n this.canvas.width = width;\n this.canvas.height = height;\n this.ctx.clearRect(0, 0, width, height);\n\n // Check if pause duration has elapsed\n if (this.pauseDuration > 0) {\n const pauseElapsed = performance.now() - this.pauseStartTime;\n if (pauseElapsed >= this.pauseDuration) {\n // End pause and start next loop\n this.isPaused = false;\n this.position = 0;\n this.startTime = performance.now();\n this.lastFrameTime = this.startTime;\n }\n }\n return;\n }\n\n this.canvas.width = width;\n this.canvas.height = height;\n\n // Clear canvas\n this.ctx.clearRect(0, 0, width, height);\n\n if (!this.scrollConfig?.enabled) {\n // Static image display\n this.ctx.drawImage(this.img, 0, 0, width, height);\n\n // Check duration for static display\n if (this.duration && this.isPlaying) {\n const elapsed = performance.now() - this.startTime;\n if (elapsed >= this.duration) {\n this.handleCompletion();\n }\n }\n return;\n }\n\n // Scrolling logic\n const direction = this.scrollConfig.direction || \"left\";\n const speed = this.scrollConfig.speed || 50;\n const gap = this.scrollConfig.gap || 0;\n\n if (this.isPlaying) {\n const now = performance.now();\n const deltaTime = (now - this.lastFrameTime) / 1000; // Convert to seconds\n this.lastFrameTime = now;\n\n // Update position based on direction and speed\n const moveDistance = speed * deltaTime;\n\n switch (direction) {\n case \"left\":\n this.position += moveDistance; // Position increases as image moves left\n break;\n case \"right\":\n this.position += moveDistance;\n break;\n case \"up\":\n this.position += moveDistance; // Position increases as image moves up\n break;\n case \"down\":\n this.position += moveDistance;\n break;\n }\n }\n\n // Draw the scrolling image\n this.drawScrollingImage(width, height, direction, gap);\n\n // Check if scroll has completed one full cycle AFTER drawing\n // This ensures the last frame is drawn before stopping\n this.checkScrollCompletion(width, height, direction, gap);\n }\n\n private drawScrollingImage(\n width: number,\n height: number,\n direction: string,\n gap: number\n ): void {\n // Calculate image dimensions with aspect ratio\n const aspectRatio = this.img.width / this.img.height;\n let drawWidth: number;\n let drawHeight: number;\n\n if (this.scrollConfig?.maintainAspectRatio !== false) {\n // Maintain aspect ratio (default behavior)\n if (this.scrollConfig?.height) {\n // Height specified, calculate width\n drawHeight = this.scrollConfig.height;\n drawWidth = drawHeight * aspectRatio;\n } else if (this.scrollConfig?.width) {\n // Width specified, calculate height\n drawWidth = this.scrollConfig.width;\n drawHeight = drawWidth / aspectRatio;\n } else {\n // Default: fit to canvas height for horizontal scroll, width for vertical\n if (direction === \"left\" || direction === \"right\") {\n drawHeight = height;\n drawWidth = drawHeight * aspectRatio;\n } else {\n drawWidth = width;\n drawHeight = drawWidth / aspectRatio;\n }\n }\n } else {\n // Don't maintain aspect ratio - use specified dimensions or canvas size\n drawWidth = this.scrollConfig?.width || width;\n drawHeight = this.scrollConfig?.height || height;\n }\n\n // Calculate offsets for centering or explicit positioning\n let offsetX: number;\n let offsetY: number;\n\n // For horizontal scrolling, default Y to center, X to 0\n // For vertical scrolling, default X to center, Y to 0\n if (direction === \"left\" || direction === \"right\") {\n // Horizontal scrolling\n offsetX = 0; // X position is controlled by scrolling\n if (\n this.scrollConfig?.offsetY === \"center\" ||\n this.scrollConfig?.offsetY === undefined\n ) {\n offsetY = (height - drawHeight) / 2;\n } else {\n offsetY = this.scrollConfig.offsetY as number;\n }\n } else {\n // Vertical scrolling\n if (\n this.scrollConfig?.offsetX === \"center\" ||\n this.scrollConfig?.offsetX === undefined\n ) {\n offsetX = (width - drawWidth) / 2;\n } else {\n offsetX = this.scrollConfig.offsetX as number;\n }\n offsetY = 0; // Y position is controlled by scrolling\n }\n\n switch (direction) {\n case \"left\": {\n // Image moves from right to left\n // For images wider than canvas: we want the image to start fully off-screen right\n // and scroll left until it's fully off-screen left\n // Start position: left edge at right edge of canvas (x = width)\n // End position: right edge at left edge of canvas (x = -drawWidth)\n const xPos = width - this.position;\n\n // Draw main image if any part is visible\n if (xPos < width && xPos > -drawWidth) {\n this.ctx.drawImage(this.img, xPos, offsetY, drawWidth, drawHeight);\n }\n\n // If looping with gap (but not pause), draw the next image after the gap\n if (\n this.loopConfig &&\n this.pauseDuration === 0 &&\n this.position > gap\n ) {\n const nextXPos = xPos + drawWidth + gap;\n if (nextXPos < width) {\n this.ctx.drawImage(\n this.img,\n nextXPos,\n offsetY,\n drawWidth,\n drawHeight\n );\n }\n }\n break;\n }\n\n case \"right\": {\n // Image moves from left to right\n // Start position: off-screen left (-drawWidth)\n // End position: off-screen right (width)\n const xPos = -drawWidth + this.position;\n\n // Draw main image\n if (xPos > -drawWidth && xPos < width) {\n this.ctx.drawImage(this.img, xPos, offsetY, drawWidth, drawHeight);\n }\n\n // If looping with gap (but not pause), draw the next image after the gap\n if (\n this.loopConfig &&\n this.pauseDuration === 0 &&\n xPos - gap - drawWidth > -drawWidth\n ) {\n const nextXPos = xPos - drawWidth - gap;\n if (nextXPos < width) {\n this.ctx.drawImage(\n this.img,\n nextXPos,\n offsetY,\n drawWidth,\n drawHeight\n );\n }\n }\n break;\n }\n\n case \"up\": {\n // Image moves from bottom to top\n const yPos = height - this.position;\n\n // Draw main image\n if (yPos > -drawHeight && yPos < height) {\n this.ctx.drawImage(this.img, offsetX, yPos, drawWidth, drawHeight);\n }\n\n // If looping with gap (but not pause), draw the next image after the gap\n if (\n this.loopConfig &&\n this.pauseDuration === 0 &&\n yPos + drawHeight + gap < height\n ) {\n const nextYPos = yPos + drawHeight + gap;\n if (nextYPos > -drawHeight) {\n this.ctx.drawImage(\n this.img,\n offsetX,\n nextYPos,\n drawWidth,\n drawHeight\n );\n }\n }\n break;\n }\n\n case \"down\": {\n // Image moves from top to bottom\n const yPos = -drawHeight + this.position;\n\n // Draw main image\n if (yPos > -drawHeight && yPos < height) {\n this.ctx.drawImage(this.img, offsetX, yPos, drawWidth, drawHeight);\n }\n\n // If looping with gap (but not pause), draw the next image after the gap\n if (\n this.loopConfig &&\n this.pauseDuration === 0 &&\n yPos - gap - drawHeight > -drawHeight\n ) {\n const nextYPos = yPos - drawHeight - gap;\n if (nextYPos < height) {\n this.ctx.drawImage(\n this.img,\n offsetX,\n nextYPos,\n drawWidth,\n drawHeight\n );\n }\n }\n break;\n }\n }\n }\n\n private checkScrollCompletion(\n width: number,\n height: number,\n direction: string,\n gap: number\n ): void {\n if (!this.isPlaying) return;\n\n // Calculate the actual image dimensions - MUST match drawScrollingImage logic exactly\n const aspectRatio = this.img.width / this.img.height;\n let drawWidth: number;\n let drawHeight: number;\n\n if (this.scrollConfig?.maintainAspectRatio !== false) {\n if (this.scrollConfig?.height) {\n drawHeight = this.scrollConfig.height;\n drawWidth = drawHeight * aspectRatio;\n } else if (this.scrollConfig?.width) {\n drawWidth = this.scrollConfig.width;\n drawHeight = drawWidth / aspectRatio;\n } else {\n // Use passed canvas dimensions as default (not this.canvas)\n if (direction === \"left\" || direction === \"right\") {\n drawHeight = height;\n drawWidth = drawHeight * aspectRatio;\n } else {\n drawWidth = width;\n drawHeight = drawWidth / aspectRatio;\n }\n }\n } else {\n drawWidth = this.scrollConfig?.width || width;\n drawHeight = this.scrollConfig?.height || height;\n }\n\n let _cycleLength: number;\n\n switch (direction) {\n case \"left\":\n case \"right\":\n // Full cycle is when image travels completely across and off the screen\n // The image needs to travel: canvas width + image width\n _cycleLength = width + drawWidth;\n // Add gap only if we're looping for the next cycle\n if (this.loopConfig) {\n _cycleLength += gap;\n }\n break;\n case \"up\":\n case \"down\":\n // Full cycle is when image travels completely across and off the screen\n _cycleLength = height + drawHeight;\n // Add gap only if we're looping for the next cycle\n if (this.loopConfig) {\n _cycleLength += gap;\n }\n break;\n default:\n _cycleLength = 0;\n }\n\n // Check if we've completed a full cycle\n // For left/right scroll: image is off-screen when xPos <= -drawWidth (left) or xPos >= canvas.width (right)\n // For up/down scroll: image is off-screen when yPos <= -drawHeight (up) or yPos >= canvas.height (down)\n\n let isOffScreen = false;\n const buffer = 1; // Small buffer to ensure image is fully off-screen\n\n switch (direction) {\n case \"left\": {\n // Image has scrolled completely off the left edge\n const xPosLeft = width - this.position;\n isOffScreen = xPosLeft < -drawWidth - buffer;\n break;\n }\n case \"right\": {\n const xPosRight = -drawWidth + this.position;\n isOffScreen = xPosRight > width + buffer;\n break;\n }\n case \"up\": {\n const yPosUp = height - this.position;\n isOffScreen = yPosUp < -drawHeight - buffer;\n break;\n }\n case \"down\": {\n const yPosDown = -drawHeight + this.position;\n isOffScreen = yPosDown > height + buffer;\n break;\n }\n }\n\n if (isOffScreen) {\n if (\n this.loopConfig === false ||\n (typeof this.loopConfig === \"number\" && this.loopConfig === 1)\n ) {\n // Single play - stop\n this.handleCompletion();\n } else if (typeof this.loopConfig === \"number\" && this.loopConfig > 1) {\n // Limited loops\n this.currentLoopCount++;\n if (this.currentLoopCount >= this.loopConfig) {\n this.handleCompletion();\n } else {\n // Start pause before next loop\n this.startPauseOrNextLoop();\n }\n } else if (this.loopConfig === true) {\n // Infinite loop - start pause before next loop\n this.startPauseOrNextLoop();\n }\n }\n }\n\n private startPauseOrNextLoop(): void {\n if (this.pauseDuration > 0) {\n // Start pause with blank screen\n this.isPaused = true;\n this.pauseStartTime = performance.now();\n } else {\n // No pause configured, immediately start next loop\n this.position = 0;\n }\n }\n\n private handleCompletion(): void {\n this.completed = true;\n this.isPlaying = false;\n if (this.completionCallback) {\n this.completionCallback();\n }\n }\n\n onDone(callback: () => void): void {\n this.completionCallback = callback;\n }\n\n isOneShot(): boolean {\n return !this.scrollConfig?.enabled && !this.loopConfig;\n }\n\n private async loadAndProcessSvg(url: string): Promise<void> {\n try {\n const response = await fetch(url);\n const svgText = await response.text();\n this.originalSvgData = svgText;\n\n // Process the SVG with color override\n const processedSvg = this.applySvgColorOverride(svgText);\n\n // Convert to data URL\n const dataUrl = `data:image/svg+xml;base64,${btoa(processedSvg)}`;\n this.img.src = dataUrl;\n } catch (error) {\n console.error(\"Failed to load and process SVG:\", error);\n // Fallback to original URL\n this.img.src = url;\n }\n }\n\n private applySvgColorOverride(svgContent: string): string {\n if (!this.colorOverride) {\n return svgContent;\n }\n\n // Convert color to RGB string using utility function\n const newColor = toRgbString(this.colorOverride);\n\n // Replace common fill patterns in SVG\n const processedSvg = svgContent\n // Replace fill attributes\n .replace(/fill\\s*=\\s*[\"'][^\"']*[\"']/gi, `fill=\"${newColor}\"`)\n // Replace fill styles in style attributes\n .replace(/fill\\s*:\\s*[^;\"]*/gi, `fill:${newColor}`)\n // Replace stroke for outlined elements (optional - you might not want this)\n .replace(/stroke\\s*=\\s*[\"'][^\"']*[\"']/gi, `stroke=\"${newColor}\"`)\n .replace(/stroke\\s*:\\s*[^;\"]*/gi, `stroke:${newColor}`);\n\n return processedSvg;\n }\n\n override dispose(): void {\n this.img.removeAttribute(\"src\");\n this.completionCallback = null;\n this.originalSvgData = null;\n }\n}\n","import type {\n DoneAware,\n Renderer,\n TextRenderDataSpecification,\n} from \"../../types\";\nimport { toRgbString } from \"../color-utils\";\nimport { Canvas2DRendererBase } from \"./base/canvas-2d-renderer\";\n\n/**\n * Enhanced text renderer with scrolling capabilities.\n *\n * Features:\n * - Smooth scrolling in any direction\n * - Configurable speed and gap\n * - Font size and family customization\n * - Color support with hex/RGB values\n * - Looping support\n * - Completion events when scroll finishes (if not looping)\n */\nexport class ScrollingTextRenderer\n extends Canvas2DRendererBase\n implements Renderer, DoneAware\n{\n private text: string;\n private lines: string[];\n private fontSize: number;\n private fontFamily: string;\n private lineHeight: number;\n private textColor: string;\n private scrollConfig: TextRenderDataSpecification[\"scroll\"];\n private loopConfig: boolean | number;\n private duration: number | undefined;\n private pauseDuration: number;\n private position = 0;\n private startTime = 0;\n private lastFrameTime = 0;\n private currentLoopCount = 0;\n private completionCallback: (() => void) | null = null;\n private isPlaying = false;\n private completed = false;\n private isPaused = false;\n private pauseStartTime = 0;\n\n // Text measurement cache\n private textWidth = 0;\n private textHeight = 0;\n private lineWidths: number[] = [];\n private textMeasured = false;\n\n constructor(data: TextRenderDataSpecification) {\n super();\n\n this.text = data.text;\n this.lines = data.text.split(\"\\n\");\n // Default to very small font size suitable for 30x50 LED panels (roughly 8-10 pixels high)\n this.fontSize = data.fontSize ?? 8;\n // Default line height with small spacing for LED panels\n this.lineHeight = data.lineHeight ?? this.fontSize + 2;\n // Use pixel-perfect monospace font stack - monospace ensures consistent character width\n this.fontFamily =\n data.fontFamily ?? \"monospace, 'Lucida Console', 'Courier New', Courier\";\n this.scrollConfig = data.scroll;\n this.loopConfig = data.loop ?? false;\n this.duration = data.duration;\n this.pauseDuration = data.pauseBetweenLoops ?? 0;\n\n // Set text color\n if (data.color) {\n this.textColor = toRgbString(data.color);\n } else {\n this.textColor = \"rgb(255,255,255)\"; // Default to white\n }\n }\n\n private measureText(): void {\n if (this.textMeasured) return;\n\n // Set up font for measurement\n this.ctx.font = `${this.fontSize}px ${this.fontFamily}`;\n\n // Measure each line individually\n this.lineWidths = [];\n let maxWidth = 0;\n\n for (const line of this.lines) {\n const metrics = this.ctx.measureText(line);\n const lineWidth = metrics.width;\n this.lineWidths.push(lineWidth);\n maxWidth = Math.max(maxWidth, lineWidth);\n }\n\n this.textWidth = maxWidth;\n // Total height is number of lines * line height\n this.textHeight = this.lines.length * this.lineHeight;\n this.textMeasured = true;\n }\n\n override reset(): void {\n this.position = 0;\n this.startTime = performance.now();\n this.lastFrameTime = this.startTime;\n this.currentLoopCount = 0;\n this.completed = false;\n this.isPlaying = false;\n this.isPaused = false;\n this.pauseStartTime = 0;\n this.textMeasured = false; // Reset measurement cache\n this.lineWidths = []; // Reset line width cache\n }\n\n play(): void {\n if (!this.isPlaying) {\n this.isPlaying = true;\n this.startTime = performance.now();\n this.lastFrameTime = this.startTime;\n }\n }\n\n pause(): void {\n this.isPlaying = false;\n }\n\n override renderFrame(width: number, height: number): void {\n this.canvas.width = width;\n this.canvas.height = height;\n\n // Measure text if not done yet\n this.measureText();\n\n if (this.completed) {\n // Animation completed - keep showing last frame\n return;\n }\n\n if (this.isPaused) {\n // During pause, show blank screen\n this.ctx.clearRect(0, 0, width, height);\n\n // Check if pause duration has elapsed\n if (this.pauseDuration > 0) {\n const pauseElapsed = performance.now() - this.pauseStartTime;\n if (pauseElapsed >= this.pauseDuration) {\n // End pause and start next loop\n this.isPaused = false;\n this.position = 0;\n this.startTime = performance.now();\n this.lastFrameTime = this.startTime;\n }\n }\n return;\n }\n\n // Clear canvas\n this.ctx.clearRect(0, 0, width, height);\n\n if (!this.scrollConfig?.enabled) {\n // Static text display\n this.drawStaticText(width, height);\n\n // Check duration for static display\n if (this.duration && this.isPlaying) {\n const elapsed = performance.now() - this.startTime;\n if (elapsed >= this.duration) {\n this.handleCompletion();\n }\n }\n return;\n }\n\n // Scrolling logic\n const direction = this.scrollConfig.direction || \"left\";\n const speed = this.scrollConfig.speed || 50;\n const gap = this.scrollConfig.gap || 0;\n\n if (this.isPlaying) {\n const now = performance.now();\n const deltaTime = (now - this.lastFrameTime) / 1000; // Convert to seconds\n this.lastFrameTime = now;\n\n // Update position based on direction and speed\n const moveDistance = speed * deltaTime;\n\n switch (direction) {\n case \"left\":\n case \"right\":\n case \"up\":\n case \"down\":\n this.position += moveDistance;\n break;\n }\n }\n\n // Draw the scrolling text\n this.drawScrollingText(width, height, direction, gap);\n\n // Check if scroll has completed one full cycle AFTER drawing\n this.checkScrollCompletion(width, height, direction);\n }\n\n private drawStaticText(width: number, height: number): void {\n // Set font and color\n this.ctx.font = `${this.fontSize}px ${this.fontFamily}`;\n this.ctx.fillStyle = this.textColor;\n this.ctx.textBaseline = \"top\";\n\n // Center the text block vertically\n const totalTextHeight = this.textHeight;\n const startY = (height - totalTextHeight) / 2;\n\n // Draw each line\n for (let i = 0; i < this.lines.length; i++) {\n const line = this.lines[i];\n const lineWidth = this.lineWidths[i];\n\n // Center each line horizontally\n const x = (width - lineWidth) / 2;\n const y = startY + i * this.lineHeight;\n\n this.ctx.fillText(line, x, y);\n }\n }\n\n private drawScrollingText(\n width: number,\n height: number,\n direction: string,\n gap: number\n ): void {\n // Set font and color\n this.ctx.font = `${this.fontSize}px ${this.fontFamily}`;\n this.ctx.fillStyle = this.textColor;\n this.ctx.textBaseline = \"top\";\n\n // Calculate base offsets for centering or explicit positioning\n let baseOffsetX: number;\n let baseOffsetY: number;\n\n // For horizontal scrolling, default Y to center, X to 0\n // For vertical scrolling, default X to center, Y to 0\n if (direction === \"left\" || direction === \"right\") {\n // Horizontal scrolling\n baseOffsetX = 0; // X position is controlled by scrolling\n if (\n this.scrollConfig?.offsetY === \"center\" ||\n this.scrollConfig?.offsetY === undefined\n ) {\n // Center the text block vertically\n baseOffsetY = (height - this.textHeight) / 2;\n } else {\n baseOffsetY = this.scrollConfig.offsetY as number;\n }\n } else {\n // Vertical scrolling\n if (\n this.scrollConfig?.offsetX === \"center\" ||\n this.scrollConfig?.offsetX === undefined\n ) {\n baseOffsetX = width / 2;\n this.ctx.textAlign = \"center\";\n } else {\n baseOffsetX = this.scrollConfig.offsetX as number;\n this.ctx.textAlign = \"left\";\n }\n baseOffsetY = 0; // Y position is controlled by scrolling\n }\n\n // Draw multi-line text for each direction\n this.drawMultiLineScrollText(\n direction,\n width,\n height,\n gap,\n baseOffsetX,\n baseOffsetY\n );\n }\n\n private drawMultiLineScrollText(\n direction: string,\n width: number,\n height: number,\n gap: number,\n baseOffsetX: number,\n baseOffsetY: number\n ): void {\n switch (direction) {\n case \"left\": {\n // Text moves from right to left\n const xPos = width - this.position;\n\n // Draw main text block if any part is visible\n if (xPos < width && xPos > -this.textWidth) {\n this.drawTextBlock(xPos, baseOffsetY, \"left\");\n }\n\n // If looping with gap (but not pause), draw the next text after the gap\n if (\n this.loopConfig &&\n this.pauseDuration === 0 &&\n this.position > gap\n ) {\n const nextXPos = xPos + this.textWidth + gap;\n if (nextXPos < width) {\n this.drawTextBlock(nextXPos, baseOffsetY, \"left\");\n }\n }\n break;\n }\n\n case \"right\": {\n // Text moves from left to right\n const xPos = -this.textWidth + this.position;\n\n // Draw main text block\n if (xPos > -this.textWidth && xPos < width) {\n this.drawTextBlock(xPos, baseOffsetY, \"left\");\n }\n\n // If looping with gap (but not pause), draw the next text after the gap\n if (\n this.loopConfig &&\n this.pauseDuration === 0 &&\n xPos - gap - this.textWidth > -this.textWidth\n ) {\n const nextXPos = xPos - this.textWidth - gap;\n if (nextXPos < width) {\n this.drawTextBlock(nextXPos, baseOffsetY, \"left\");\n }\n }\n break;\n }\n\n case \"up\": {\n // Text moves from bottom to top\n const yPos = height - this.position;\n\n // Draw main text block\n if (yPos > -this.textHeight && yPos < height) {\n this.drawTextBlock(baseOffsetX, yPos, \"center\");\n }\n\n // If looping with gap (but not pause), draw the next text after the gap\n if (\n this.loopConfig &&\n this.pauseDuration === 0 &&\n yPos + this.textHeight + gap < height\n ) {\n const nextYPos = yPos + this.textHeight + gap;\n if (nextYPos > -this.textHeight) {\n this.drawTextBlock(baseOffsetX, nextYPos, \"center\");\n }\n }\n break;\n }\n\n case \"down\": {\n // Text moves from top to bottom\n const yPos = -this.textHeight + this.position;\n\n // Draw main text block\n if (yPos > -this.textHeight && yPos < height) {\n this.drawTextBlock(baseOffsetX, yPos, \"center\");\n }\n\n // If looping with gap (but not pause), draw the next text after the gap\n if (\n this.loopConfig &&\n this.pauseDuration === 0 &&\n yPos - gap - this.textHeight > -this.textHeight\n ) {\n const nextYPos = yPos - this.textHeight - gap;\n if (nextYPos < height) {\n this.drawTextBlock(baseOffsetX, nextYPos, \"center\");\n }\n }\n break;\n }\n }\n }\n\n private drawTextBlock(\n x: number,\n y: number,\n alignment: \"left\" | \"center\"\n ): void {\n // Draw each line\n for (let i = 0; i < this.lines.length; i++) {\n const line = this.lines[i];\n const lineWidth = this.lineWidths[i];\n\n let lineX: number;\n if (alignment === \"center\") {\n // Center the line\n lineX = x - lineWidth / 2;\n } else {\n // Left align the line\n lineX = x;\n }\n\n const lineY = y + i * this.lineHeight;\n\n this.ctx.fillText(line, lineX, lineY);\n }\n }\n\n private checkScrollCompletion(\n width: number,\n height: number,\n direction: string\n ): void {\n if (!this.isPlaying) return;\n\n let isOffScreen = false;\n const buffer = 1; // Small buffer to ensure text is fully off-screen\n\n switch (direction) {\n case \"left\": {\n // Text has scrolled completely off the left edge\n const xPosLeft = width - this.position;\n isOffScreen = xPosLeft < -this.textWidth - buffer;\n break;\n }\n case \"right\": {\n const xPosRight = -this.textWidth + this.position;\n isOffScreen = xPosRight > width + buffer;\n break;\n }\n case \"up\": {\n const yPosUp = height - this.position;\n isOffScreen = yPosUp < -this.textHeight - buffer;\n break;\n }\n case \"down\": {\n const yPosDown = -this.textHeight + this.position;\n isOffScreen = yPosDown > height + buffer;\n break;\n }\n }\n\n if (isOffScreen) {\n if (\n this.loopConfig === false ||\n (typeof this.loopConfig === \"number\" && this.loopConfig === 1)\n ) {\n // Single play - stop\n this.handleCompletion();\n } else if (typeof this.loopConfig === \"number\" && this.loopConfig > 1) {\n // Limited loops\n this.currentLoopCount++;\n if (this.currentLoopCount >= this.loopConfig) {\n this.handleCompletion();\n } else {\n // Start pause before next loop\n this.startPauseOrNextLoop();\n }\n } else if (this.loopConfig === true) {\n // Infinite loop - start pause before next loop\n this.startPauseOrNextLoop();\n }\n }\n }\n\n private startPauseOrNextLoop(): void {\n if (this.pauseDuration > 0) {\n // Start pause with blank screen\n this.isPaused = true;\n this.pauseStartTime = performance.now();\n } else {\n // No pause configured, immediately start next loop\n this.position = 0;\n }\n }\n\n private handleCompletion(): void {\n this.completed = true;\n this.isPlaying = false;\n if (this.completionCallback) {\n this.completionCallback();\n }\n }\n\n onDone(callback: () => void): void {\n this.completionCallback = callback;\n }\n\n isOneShot(): boolean {\n return !this.scrollConfig?.enabled && !this.loopConfig;\n }\n\n override dispose(): void {\n this.completionCallback = null;\n }\n}\n","import type {\n DoneAware,\n Renderer,\n SequenceRenderDataSpecification,\n RenderSpecification,\n} from \"../../types\";\nimport { getRenderer } from \"./renderer-factory\";\n\n/**\n * A renderer that plays multiple patterns in sequence.\n *\n * Features:\n * - Plays patterns in order from a list of pattern IDs\n * - Supports looping the entire sequence\n * - Handles transitions between patterns\n * - Emits completion when all patterns have played\n */\nexport class SequenceRenderer implements Renderer, DoneAware {\n private patterns: string[];\n private currentPatternIndex = 0;\n private currentRenderer: Renderer | null = null;\n private loopConfig: boolean | number;\n private currentLoopCount = 0;\n private transitionDuration: number;\n private patternOverrides: Record<string, any>;\n private completionCallback: (() => void) | null = null;\n private patternStore: Map<string, RenderSpecification<any>>;\n private canvas: HTMLCanvasElement;\n private ctx: CanvasRenderingContext2D;\n private width = 0;\n private height = 0;\n\n constructor(\n data: SequenceRenderDataSpecification & {\n patternStore?: Map<string, RenderSpecification<any>>;\n }\n ) {\n this.patterns = data.patterns;\n this.loopConfig = data.loop ?? false;\n this.transitionDuration = data.transitionDuration ?? 0;\n this.patternOverrides = data.patternOverrides ?? {};\n this.patternStore = data.patternStore ?? new Map();\n\n this.canvas = document.createElement(\"canvas\");\n const ctx = this.canvas.getContext(\"2d\");\n if (!ctx) throw new Error(\"2D canvas not supported\");\n this.ctx = ctx;\n\n if (this.patterns.length === 0) {\n throw new Error(\"SequenceRenderer requires at least one pattern\");\n }\n\n this.loadCurrentPattern();\n }\n\n private loadCurrentPattern(): void {\n const patternId = this.patterns[this.currentPatternIndex];\n const patternSpec = this.patternStore.get(patternId);\n\n if (!patternSpec) {\n console.warn(`Pattern \"${patternId}\" not found in store, skipping`);\n this.moveToNextPattern();\n return;\n }\n\n // Clean up previous renderer\n if (this.currentRenderer) {\n this.currentRenderer.dispose?.();\n }\n\n // Apply any overrides for this specific pattern\n const overrides = this.patternOverrides[patternId] ?? {};\n const modifiedData = { ...patternSpec.data, ...overrides };\n\n // Create the renderer for this pattern\n try {\n this.currentRenderer = getRenderer({\n mode: patternSpec.type,\n data: modifiedData,\n });\n\n // If the pattern renderer is DoneAware, listen for its completion\n if (this.currentRenderer && this.isDoneAware(this.currentRenderer)) {\n this.currentRenderer.onDone(() => {\n this.handlePatternComplete();\n });\n }\n\n // Initialize the renderer\n if (this.currentRenderer) {\n this.currentRenderer.reset();\n this.currentRenderer.play?.();\n\n // Render initial frame if we have dimensions\n if (this.width > 0 && this.height > 0) {\n this.currentRenderer.renderFrame(this.width, this.height);\n }\n }\n } catch (error) {\n console.error(\n `Failed to create renderer for pattern \"${patternId}\":`,\n error\n );\n this.moveToNextPattern();\n }\n }\n\n private isDoneAware(obj: any): obj is DoneAware {\n return typeof obj?.onDone === \"function\";\n }\n\n private handlePatternComplete(): void {\n // Add transition delay if specified\n if (this.transitionDuration > 0) {\n setTimeout(() => {\n this.moveToNextPattern();\n }, this.transitionDuration);\n } else {\n this.moveToNextPattern();\n }\n }\n\n private moveToNextPattern(): void {\n this.currentPatternIndex++;\n\n if (this.currentPatternIndex >= this.patterns.length) {\n // We've completed all patterns in the sequence\n if (this.loopConfig === true) {\n // Infinite loop - restart from beginning\n this.currentPatternIndex = 0;\n this.loadCurrentPattern();\n } else if (\n typeof this.loopConfig === \"number\" &&\n this.currentLoopCount < this.loopConfig - 1\n ) {\n // Still have loops remaining\n this.currentLoopCount++;\n this.currentPatternIndex = 0;\n this.loadCurrentPattern();\n } else {\n // Sequence complete\n if (this.completionCallback) {\n this.completionCallback();\n }\n }\n } else {\n // Load next pattern in sequence\n this.loadCurrentPattern();\n }\n }\n\n reset(): void {\n this.currentPatternIndex = 0;\n this.currentLoopCount = 0;\n this.loadCurrentPattern();\n }\n\n play(): void {\n this.currentRenderer?.play?.();\n }\n\n pause(): void {\n this.currentRenderer?.pause?.();\n }\n\n renderFrame(width: number, height: number): void {\n this.width = width;\n this.height = height;\n this.canvas.width = width;\n this.canvas.height = height;\n\n if (this.currentRenderer) {\n this.currentRenderer.renderFrame(width, height);\n }\n }\n\n readPixels(width: number, height: number): Uint8ClampedArray {\n if (this.currentRenderer) {\n return this.currentRenderer.readPixels(width, height);\n }\n // Return empty canvas if no current renderer\n return this.ctx.getImageData(0, 0, width, height).data;\n }\n\n onDone(callback: () => void): void {\n this.completionCallback = callback;\n }\n\n isOneShot(): boolean {\n // Sequence is one-shot if no looping and only one pattern that is one-shot\n if (this.loopConfig === false || this.loopConfig === 1) {\n if (this.patterns.length === 1 && this.currentRenderer) {\n return (this.currentRenderer as any).isOneShot?.() ?? false;\n }\n return true;\n }\n return false;\n }\n\n dispose(): void {\n if (this.currentRenderer) {\n this.currentRenderer.dispose?.();\n }\n this.completionCallback = null;\n }\n\n /**\n * Set the pattern store for looking up patterns by ID\n */\n setPatternStore(store: Map<string, RenderSpecification<any>>): void {\n this.patternStore = store;\n // Reload current pattern with new store\n if (this.patterns.length > 0) {\n this.loadCurrentPattern();\n }\n }\n}\n","import type {\n OneShotCapable,\n Renderer,\n ColorRenderDataSpecification,\n} from \"../../types\";\nimport { Canvas2DRendererBase } from \"./base/canvas-2d-renderer\";\nimport { OneShotRendererMixin } from \"./mixins/one-shot-renderer-mixin\";\nimport { toRgbString } from \"../color-utils\";\n\nconst Base = OneShotRendererMixin(Canvas2DRendererBase);\n\n/**\n * Renders a single solid color frame onto the canvas.\n * Implements OneShotCapable, signaling `onDone()` after the first render.\n */\nexport class SolidColorRenderer\n extends Base\n implements Renderer, OneShotCapable\n{\n private color: string;\n\n constructor(data: ColorRenderDataSpecification = { r: 0, g: 0, b: 0 }) {\n super();\n\n // Support both legacy r,g,b format and new color format\n let colorValue: { r: number; g: number; b: number } | string;\n\n if (data.color !== undefined) {\n colorValue = data.color;\n } else if (\n data.r !== undefined &&\n data.g !== undefined &&\n data.b !== undefined\n ) {\n colorValue = { r: data.r, g: data.g, b: data.b };\n } else {\n colorValue = { r: 0, g: 0, b: 0 }; // Default to black\n }\n\n this.color = toRgbString(colorValue);\n }\n\n setColor(color: { r: number; g: number; b: number } | string): void {\n this.color = toRgbString(color);\n this.resetOneShot();\n }\n\n override reset(): void {\n this.resetOneShot();\n }\n\n override renderFrame(width: number, height: number): void {\n if (this.isOneShotDone) return;\n\n this.canvas.width = width;\n this.canvas.height = height;\n\n this.ctx.fillStyle = this.color;\n this.ctx.fillRect(0, 0, width, height);\n\n this.signalDoneIfNeeded(); // tell the hook we're done\n }\n}\n","import type { Renderer } from \"../../types\";\nimport { Canvas2DRendererBase } from \"./base/canvas-2d-renderer\";\n\n/**\n * A horizontal hue sweep renderer using 2D canvas.\n *\n * This renderer generates a horizontally scrolling gradient across a configurable hue range.\n * The hue scrolls left-to-right in HSL color space, creating a smooth and colorful sweep animation.\n */\nexport class SweepRenderer extends Canvas2DRendererBase implements Renderer {\n /** The horizontal pixel offset into the hue sweep */\n private offset = 0;\n\n /** Minimum hue (in degrees) to include in the sweep (e.g. 0 for red) */\n private minHue: number;\n\n /** Maximum hue (in degrees) to include in the sweep (e.g. 60 for yellow) */\n private maxHue: number;\n\n /** Horizontal sweep speed in pixels per update step */\n private speed: number;\n\n /**\n * Constructs a sweep renderer.\n *\n * @param minHue - Start of the hue range (in degrees, default 0)\n * @param maxHue - End of the hue range (in degrees, default 360)\n * @param speed - Horizontal speed of the sweep (pixels per update, default 1)\n */\n constructor({\n minHue = 0,\n maxHue = 360,\n speed = 1,\n }: {\n minHue?: number;\n maxHue?: number;\n speed?: number;\n } = {}) {\n super();\n this.minHue = minHue;\n this.maxHue = maxHue;\n this.speed = speed;\n }\n\n /**\n * Resets the animation state to the beginning of the sweep.\n */\n reset(): void {\n this.offset = 0;\n this.lastUpdate = performance.now();\n }\n\n /**\n * Converts an HSL color to RGB.\n *\n * @param h - Hue [0, 1]\n * @param s - Saturation [0, 1]\n * @param l - Lightness [0, 1]\n * @returns Tuple of [r, g, b] in range [0, 255]\n */\n private hslToRgb(h: number, s: number, l: number): [number, number, number] {\n let r: number, g: number, b: number;\n\n if (s === 0) {\n r = g = b = l; // Achromatic\n } else {\n const hue2rgb = (p: number, q: number, t: number): number => {\n if (t < 0) t += 1;\n if (t > 1) t -= 1;\n if (t < 1 / 6) return p + (q - p) * 6 * t;\n if (t < 1 / 2) return q;\n if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;\n return p;\n };\n const q = l < 0.5 ? l * (1 + s) : l + s - l * s;\n const p = 2 * l - q;\n\n r = hue2rgb(p, q, h + 1 / 3);\n g = hue2rgb(p, q, h);\n b = hue2rgb(p, q, h - 1 / 3);\n }\n\n return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)];\n }\n\n /**\n * Renders the current frame by drawing a hue-mapped horizontal gradient across the canvas.\n *\n * @param width - Width of the canvas in pixels\n * @param height - Height of the canvas in pixels\n */\n renderFrame(width: number, height: number): void {\n // Only step the animation every ~50ms\n if (this.shouldStep(50)) {\n this.offset = (this.offset + this.speed) % width;\n }\n\n const imageData = this.ctx.createImageData(width, height);\n const data = imageData.data;\n\n let i = 0;\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n // Compute normalized hue position with offset\n const hue = ((x + this.offset) % width) / width;\n const mappedHue =\n this.minHue / 360 + hue * ((this.maxHue - this.minHue) / 360);\n\n const [r, g, b] = this.hslToRgb(mappedHue, 1, 0.5);\n\n data[i++] = r;\n data[i++] = g;\n data[i++] = b;\n data[i++] = 255; // alpha\n }\n }\n\n this.ctx.putImageData(imageData, 0, 0);\n }\n}\n","import {\n EXTENSION_CANVAS_RENDERER,\n ExtensionManager,\n registerExtensionPoint,\n} from \"../../../../../core\";\nimport type {\n RenderDataSpecification,\n Renderer,\n RendererConstructor,\n RendererMode,\n} from \"../../types\";\nimport { VideoRendererBase } from \"./base/video-base-renderer\";\nimport { DropRenderer } from \"./drop-renderer\";\nimport { GradientRenderer } from \"./gradient-renderer\";\nimport { ImageRenderer } from \"./image-renderer\";\nimport { LoopingVideoRenderer } from \"./looping-video-renderer\";\nimport { MatrixRenderer } from \"./matrix-renderer\";\nimport { OverlayRenderer } from \"./overlay-renderer\";\nimport { ScrollingImageRenderer } from \"./scrolling-image-renderer\";\nimport { ScrollingTextRenderer } from \"./scrolling-text-renderer\";\nimport { SequenceRenderer } from \"./sequence-renderer\";\nimport { SolidColorRenderer } from \"./solid-color-renderer\";\nimport { SweepRenderer } from \"./sweep-renderer\";\n\nconst canvasRenderers = new Map<string, RendererConstructor>();\nregisterExtensionPoint(EXTENSION_CANVAS_RENDERER, {\n register(id: string, renderer: RendererConstructor) {\n canvasRenderers.set(id, renderer);\n },\n execute(id: string, data: any): Renderer | null {\n const RendererClass = canvasRenderers.get(id);\n if (!RendererClass) {\n return null;\n }\n return new RendererClass(data);\n },\n});\n\n// Use the enhanced LoopingVideoRenderer for video mode\nExtensionManager.canvas.registerRenderer(\"video\", LoopingVideoRenderer);\n\n// Keep the base renderer available as \"video-basic\" if needed\nExtensionManager.canvas.registerRenderer(\"video-basic\", VideoRendererBase);\n\n// Register both image renderers - factory will choose based on data\nExtensionManager[EXTENSION_CANVAS_RENDERER].register(\n \"image-static\",\n ImageRenderer\n);\nExtensionManager[EXTENSION_CANVAS_RENDERER].register(\n \"image-scrolling\",\n ScrollingImageRenderer\n);\n\n// Custom image renderer that chooses based on scroll config\nconst ImageRendererFactory = class {\n constructor(data: any) {\n if (data.scroll?.enabled) {\n return new ScrollingImageRenderer(data);\n }\n return new ImageRenderer(data);\n }\n} as any;\n\nExtensionManager[EXTENSION_CANVAS_RENDERER].register(\n \"image\",\n ImageRendererFactory\n);\nExtensionManager[EXTENSION_CANVAS_RENDERER].register(\n \"color\",\n SolidColorRenderer\n);\n\nExtensionManager[EXTENSION_CANVAS_RENDERER].register(\"matrix\", MatrixRenderer);\nExtensionManager[EXTENSION_CANVAS_RENDERER].register(\"sweep\", SweepRenderer);\nExtensionManager[EXTENSION_CANVAS_RENDERER].register(\n \"gradient\",\n GradientRenderer\n);\nExtensionManager[EXTENSION_CANVAS_RENDERER].register(\"drop\", DropRenderer);\nExtensionManager[EXTENSION_CANVAS_RENDERER].register(\n \"sequence\",\n SequenceRenderer\n);\nExtensionManager[EXTENSION_CANVAS_RENDERER].register(\n \"text\",\n ScrollingTextRenderer\n);\n\n// Create a factory for overlay renderer that provides access to the renderer factory\nconst OverlayRendererFactory = class {\n constructor(data: any) {\n // Create a factory function that the overlay renderer can use\n const rendererFactory = (type: string, rendererData: any) => {\n const renderer = getRenderer({ mode: type as any, data: rendererData });\n if (!renderer) {\n throw new Error(`Failed to create renderer of type: ${type}`);\n }\n return renderer;\n };\n return new OverlayRenderer(data, rendererFactory);\n }\n} as any;\n\nExtensionManager[EXTENSION_CANVAS_RENDERER].register(\n \"overlay\",\n OverlayRendererFactory\n);\n\n/**\n * Returns a renderer instance based on the specified mode and parameters.\n *\n * @param params - An object containing the parameters for the renderer.\n * @param params.mode - The mode of the renderer. Supported values are:\n * - `'matrix'`: Creates a matrix renderer with a specified fall chance.\n * - `'video'`: Creates a video renderer with a specified video source.\n * - `'image'`: Creates a image renderer with a specified inmage source.\n *\n * @param params.fallChance - The chance of falling, used only in `'matrix'` mode.\n * @param params.video - The video source identifier, used only in `'video'` mode.\n * - `'video1'`: Uses the `/assets/video.mp4` file.\n * - Any other value: Uses the `/assets/circle-spin.mp4` file.\n *\n * @returns A `Renderer` instance corresponding to the specified mode.\n *\n * @throws {Error} If an unknown mode is provided.\n */\nexport const getRenderer = <T extends RendererMode>({\n mode,\n data,\n}: {\n mode: T;\n data?: RenderDataSpecification<T> | null;\n}): Renderer | null => {\n const renderer: Renderer = ExtensionManager[\n EXTENSION_CANVAS_RENDERER\n ].execute(mode, data);\n if (renderer) {\n return renderer;\n }\n throw new Error(`Unknown mode: ${mode}`);\n};\n","import {\n KosModelContainer,\n type IKosModelContainer,\n type KosContext,\n} from \"../../../core\";\nimport { kosChild, kosModel, post } from \"../../../core/core/decorators\";\nimport type {\n IKosDataModel,\n KosContextLogger,\n KosCreationContext,\n} from \"../../../core/core/kosModel\";\nimport type {\n KosRequest,\n KosResponse,\n} from \"../../../core/core/services/browser-router\";\nimport type { IKosIdentifiable } from \"../../../core/core/types\";\nimport type { PublicModelInterface } from \"../../../core/types\";\nimport { CanvasRenderer, type CanvasRendererModel } from \"../canvas-renderer\";\nimport { CanvasDispatcher } from \"./canvas-dispatcher-registration\";\nimport type {\n CanvasDispatcherOptions,\n EndpointData,\n RenderDataSpecification,\n RendererMode,\n RenderSpecification,\n} from \"./types\";\nimport { getRenderer } from \"./utils/renderers/renderer-factory\";\n\nexport const MODEL_TYPE = \"canvas-dispatcher-model\";\n\nexport type CanvasDispatcherModel =\n PublicModelInterface<CanvasDispatcherModelImpl>;\n\n/**\n * Converts a hex color string (e.g. \"#ff00aa\" or \"ff00aa\") to an RGB object.\n * @param hex - The hex color string.\n * @returns An object with r, g, b values (0-255), or null if invalid.\n */\nfunction hexToRgb(hex: string): { r: number; g: number; b: number } | null {\n // Remove leading '#' if present\n hex = hex.replace(/^#/, \"\");\n // Support short form (#f0a)\n if (hex.length === 3) {\n hex = hex\n .split(\"\")\n .map((c) => c + c)\n .join(\"\");\n }\n if (hex.length !== 6) return null;\n const num = parseInt(hex, 16);\n return {\n r: (num >> 16) & 255,\n g: (num >> 8) & 255,\n b: num & 255,\n };\n}\n\n@kosModel(MODEL_TYPE)\nexport class CanvasDispatcherModelImpl\n implements IKosDataModel, IKosIdentifiable\n{\n id: string;\n private logger: KosContextLogger;\n\n private _content: Map<string, string> = new Map();\n private _patterns: Map<string, RenderSpecification<any>> = new Map();\n\n @kosChild\n private _endpointRenderers: IKosModelContainer<CanvasRendererModel>;\n\n // Note: BrowserRouter is automatically injected when using HTTP decorators!\n\n pattern?: RendererMode;\n data?: RenderDataSpecification<any> | null;\n\n constructor(\n modelId: string,\n _options: CanvasDispatcherOptions,\n context: KosCreationContext\n ) {\n this.id = modelId;\n this.logger = context.logger;\n this._endpointRenderers = new KosModelContainer();\n }\n\n addNamedEndpoint(name: string, data: EndpointData) {\n if (this._endpointRenderers.getModel(name)) {\n this.logger.warn(`Endpoint \"${name}\" already exists. Overwriting.`);\n }\n const renderer = CanvasRenderer.instance(name)\n .options({\n apiPath: data.apiPath,\n width: data.width,\n height: data.height,\n fps: data.fps,\n durationMs: data.durationMs ?? null,\n endpoint: name,\n })\n .build();\n\n this._endpointRenderers.addModel(renderer);\n\n return renderer;\n }\n\n addContent(name: string, contentUrl: string) {\n if (this._content.has(name)) {\n this.logger.warn(`Content \"${name}\" already exists. Overwriting.`);\n }\n this._content.set(name, contentUrl);\n }\n\n addPattern(name: string, data: RenderSpecification<any>) {\n if (this._patterns.has(name)) {\n this.logger.warn(`Pattern \"${name}\" already exists. Overwriting.`);\n }\n this._patterns.set(name, data);\n }\n\n // -------------------HTTP ENDPOINTS----------------------------\n\n @post(\"/api/ui/canvas/patterns\")\n async handlePatternsPost(\n req: KosRequest<\"/api/ui/canvas/patterns\">,\n res: KosResponse\n ) {\n const pattern: RenderSpecification<any> | RenderSpecification<any>[] =\n req.body;\n const _data = Array.isArray(pattern) ? pattern : [pattern];\n if (_data.some((p) => !p.id || !p.type || !p.data)) {\n res.status?.(400).send({ error: `Invalid pattern data` });\n return;\n }\n\n for (const pattern of _data) {\n if (this._patterns.has(pattern.id)) {\n this.logger.warn(\n `Pattern \"${pattern.id}\" already exists. Overwriting.`\n );\n }\n this.addPattern(pattern.id, pattern);\n }\n\n res.status?.(200).send({ status: \"OK\" });\n }\n\n @post(\"/api/ui/canvas/pattern/:endpoint/:pattern\")\n async handlePatternApplication(\n req: KosRequest<\"/api/ui/canvas/pattern/:endpoint/:pattern\">,\n res: KosResponse\n ) {\n const pattern = req.params.pattern;\n const endpoint = req.params.endpoint;\n\n const rendererModel = this._endpointRenderers.getModel(endpoint);\n if (!rendererModel) {\n res.status?.(404).send({ error: `Endpoint \"${endpoint}\" not found` });\n return;\n }\n if (!this._patterns.has(pattern)) {\n res.status?.(404).send({ error: `Pattern \"${pattern}\" not found` });\n return;\n }\n\n const patternData = this._patterns.get(pattern)!;\n\n const mode = patternData.type as RendererMode;\n // Merge request body data with pattern data to allow runtime overrides\n const requestData = req.body || {};\n this.data = {\n ...patternData.data,\n ...requestData,\n } as RenderDataSpecification<any>;\n\n // If it's a sequence renderer, pass the pattern store\n const rendererData =\n mode === \"sequence\"\n ? { ...this.data, patternStore: this._patterns }\n : this.data;\n\n rendererModel.renderer = getRenderer({\n mode: mode,\n data: rendererData,\n });\n\n // Set the clearOnComplete option if specified\n rendererModel.setClearOnComplete(patternData.clearOnComplete);\n\n rendererModel.startStreaming();\n res.status?.(200).send({ status: \"OK\" });\n }\n\n @post(\"/api/ui/canvas/color/:endpoint/:color\")\n async handleColorApplication(\n req: KosRequest<\"/api/ui/canvas/color/:endpoint/:color\">,\n res: KosResponse\n ) {\n const color = req.params.color;\n const rgb = hexToRgb(color);\n\n if (!rgb) {\n res.status?.(400).send({ error: \"Invalid color format\" });\n return;\n }\n\n const endpoint = req.params.endpoint;\n const rendererModel = this._endpointRenderers.getModel(endpoint);\n if (!rendererModel) {\n res.status?.(404).send({ error: `Endpoint \"${endpoint}\" not found` });\n return;\n }\n const { r, b, g } = rgb;\n rendererModel.renderer = getRenderer({\n mode: \"color\",\n data: {\n r,\n g,\n b,\n },\n });\n\n rendererModel.startStreaming();\n res.status?.(200).send({ status: \"OK\" });\n }\n\n @post(\"/api/ui/canvas/endpoint\")\n async handleEndpointCreation(\n req: KosRequest<\"/api/ui/canvas/endpoint\">,\n res: KosResponse\n ) {\n const data: EndpointData = req.body;\n\n if (!data.apiPath || !data.id) {\n res.status?.(400).send({ error: \"Name and path are required\" });\n return;\n }\n\n this.addNamedEndpoint(data.id, data);\n\n res.status?.(200).send({ status: \"OK\" });\n }\n\n // -------------------LIFECYCLE----------------------------\n\n async load(context?: KosContext): Promise<void> {\n const patternData = context?.get(CanvasDispatcher.loader);\n if (patternData) {\n patternData.patterns?.forEach((pattern: RenderSpecification<any>) => {\n if (!pattern.id || !pattern.type || !pattern.data) {\n this.logger.warn(`Invalid pattern data: ${JSON.stringify(pattern)}`);\n return;\n }\n this.addPattern(pattern.id, pattern);\n });\n }\n }\n}\n","import { SingletonKosModelRegistrationFactory } from \"../../../core\";\nimport type { CanvasDispatcherModel } from \"./canvas-dispatcher-model\";\nimport {\n CanvasDispatcherModelImpl,\n MODEL_TYPE,\n} from \"./canvas-dispatcher-model\";\nimport type { CanvasDispatcherOptions } from \"./types\";\n\n/**\n * # CanvasDispatcher\n *\n * The registration bean includes convenience methods for creating and working with CanvasDispatcherModel instances.\n *\n * ## type\n * The type property is a string that identifies the model type.\n * The type is used to identify the model type in the model registry and to narrow down the model type in type predicates. It's most frequently\n * used when declaring dependencies on models.\n *\n * @example\n * ```typescript\n *\n * @kosDependency({modelType: CanvasDispatcher.type, id: \"canvasDispatcherId\"})\n * private canvasDispatcherModel: CanvasDispatcherModel;\n * ```\n *\n *\n * ## factory\n *\n * The factory method creates a factory function that can be used to create new CanvasDispatcherModel instances.\n *\n \n * As this is a singleton model, the factory function accepts the model options as its argument.\n *\n * If a model with the same model type already exists, the factory function will return the existing model. The options will be ignored\n * in this case and the existing model will be returned in its current state.\n *\n * @example\n * ```typescript\n * const model = CanvasDispatcher.factory({\n * // Add option data\n * });\n * ```\n \n\n *\n * ## predicate\n *\n * [Typescript type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) function that will identify and narrow down a model to a CanvasDispatcherModel.\n *\n * @example\n * ```typescript\n *\n * const model: IKosDataModel = ...; // some model\n *\n * if (CanvasDispatcher.predicate(model)) {\n * // if the function evaluates to true, the model is narrowed down to CanvasDispatcherModel\n * // and the compiler will know that the model has the CanvasDispatcherModel interface\n * model.updateAvailability(false);\n * }\n * ```\n *\n * ## registration\n *\n * The registration property is an object that can be used to simplify registration of the model with the model registry. The registration object\n * can be spread into the model registration and provides all of the required information to register the model implementation class against the model type.\n *\n *\n * @example\n *\n * In an application registration file you can declare the model registration as follows:\n *\n * **registration.ts**\n * ```typescript\n * import { CanvasDispatcher } from \"@kos-ui/project-models\";\n * import { KosModelRegistry } from \"@kosdev-code/kos-dispense-sdk\";\n *\n * import { initKosProvider } from \"@kosdev-code/kos-ui-sdk\";\n *\n * KosModelRegistry.dispense\n * .models()\n * .model(CanvasDispatcher);\n * ```\n *\n * ## registration.singleton\n \n * The canvasDispatcher model is a singleton model. This means that each time the factory function is called , the same instance will be returned.\n * If the model does not yet exist, it will be created passing in the provided options to initialize it.\n *\n * Singleton models don't require an ID as they will use the model type as their ID to guarantee uniqueness throughout the system.\n \n * */\nexport const CanvasDispatcher = new SingletonKosModelRegistrationFactory<\n CanvasDispatcherModel,\n CanvasDispatcherOptions\n>({\n class: CanvasDispatcherModelImpl,\n type: MODEL_TYPE,\n});\n","/**\n * @internal\n */\nimport {\n FetchError,\n KosLog,\n ServiceFactory,\n resolveServiceUrl,\n} from \"../../../../core\";\nconst { URL } = resolveServiceUrl(\"DEVICE_SERVICE\");\nconst { getOne } = ServiceFactory.build({\n basePath: `${URL}/api/device`,\n});\n\nconst log = KosLog.createLogger({ name: \"device-service\", group: \"Services\" });\n\ntype SerialNumberResponse = [string | undefined, string | undefined];\n\ntype DeviceResponse = [string, undefined] | [undefined, DevicePayload];\ntype DevicePayload = {\n serialNumber: string;\n name: string;\n nodeId: string;\n};\n/**\n * @category Service\n * @internal\n * Retrieves the device serial number.\n */\nexport const getSerialNumber = async (): Promise<SerialNumberResponse> => {\n log.debug(\"sending GET for device serial number\");\n try {\n const response = await getOne<DevicePayload>({\n urlOverride: `${URL}/api/kos/device/serialNumber`,\n });\n\n return [undefined, response?.data.serialNumber];\n } catch (error) {\n if (error instanceof FetchError) {\n log.error(`Error fetching device serial number: ${error.payload.error}`);\n return [error.payload.error, undefined];\n }\n }\n\n return [\"unknownError\", undefined];\n};\n\n/**\n * @category Service\n * @internal\n * Retrieves the initial device data.\n */\nexport const getDeviceDetails = async (): Promise<DeviceResponse> => {\n log.debug(\"sending GET for device details\");\n try {\n const response = await getOne<DevicePayload>({\n urlOverride: `${URL}/api/kos/device`,\n });\n\n if (!response) {\n return [\"unknownError\", undefined];\n }\n return [undefined, response.data];\n } catch (error) {\n if (error instanceof FetchError) {\n log.error(`Error fetching device serial number: ${error.payload.error}`);\n return [error.payload.error, undefined];\n }\n }\n\n return [\"unknownError\", undefined];\n};\n","import type {\n IKosDataModel,\n IKosIdentifiable,\n KosContextLogger,\n KosCreationContext,\n PublicModelInterface,\n} from \"../../../core\";\nimport { kosModel, kosTopicHandler } from \"../../../core\";\nimport { getDeviceDetails, getSerialNumber } from \"./services\";\nimport type { DeviceOptions } from \"./types\";\n\nexport const MODEL_TYPE = \"device-model\";\nexport const TOPIC_CRITICAL_DATA_CHANGED = \"/kos/criticalData/changed\";\nexport const TOPIC_CRITICAL_DATA_AVAILABLE = \"/kos/criticalData/available\";\nexport const TOPIC_CRITICAL_DATA_UNAVAILABLE = \"/kos/criticalData/unavailable\";\n\n/**\n * KOS Device Model - Device Identity and Node Configuration Management\n *\n * The Device model provides centralized management of device identity, node configuration,\n * and hardware identification within KOS systems. It handles device serial numbers,\n * names, and node topology information essential for system coordination and administration.\n *\n * ## Key Features\n *\n * ### Device Identity Management\n * - **Serial Number Tracking**: Hardware-based device identification\n * - **Name Management**: Human-readable device naming for administration\n * - **Node Configuration**: Multi-node deployment topology handling\n *\n * ### Real-time Synchronization\n * - **Critical Data Events**: Automatic updates on system data changes\n * - **WebSocket Integration**: Live device state synchronization\n * - **Lazy Loading**: Efficient data retrieval when needed\n *\n * ### Node Topology Support\n * - **Node Type/Name Parsing**: Automatic node identifier decomposition\n * - **Multi-node Deployments**: Support for complex system architectures\n * - **Role-based Configuration**: Node-specific parameter management\n *\n * ## Common Integration Patterns\n *\n * ### System Administration Dashboards\n * ```typescript\n * const device = Device.factory({\n * serialNumber: 'KOS-DEV-001',\n * name: 'Production Dispenser Alpha',\n * nodeId: 'primary-main'\n * });\n *\n * // Access device identity\n * console.log(`Device: ${device.name}`);\n * console.log(`Serial: ${device.serialNumber}`);\n * console.log(`Node: ${device.nodeType}-${device.nodeName}`);\n * ```\n *\n * ### Multi-node System Coordination\n * ```typescript\n * const primaryDevice = Device.factory({\n * nodeId: 'primary-controller'\n * });\n *\n * const secondaryDevice = Device.factory({\n * nodeId: 'secondary-backup'\n * });\n *\n * // Coordinate based on node roles\n * if (primaryDevice.nodeType === 'primary') {\n * // Handle primary node logic\n * }\n * ```\n *\n * ### Device Registration and Setup\n * ```typescript\n * const newDevice = Device.factory({\n * serialNumber: await getHardwareSerial(),\n * name: userProvidedName,\n * nodeId: deploymentConfiguration.nodeId\n * });\n *\n * // Device automatically loads additional data\n * // from critical data events\n * ```\n *\n * ## Real-time Updates\n *\n * The Device model automatically responds to critical data changes:\n * - Monitors `/kos/criticalData/changed` and `/kos/criticalData/available` topics\n * - Updates serial number and configuration when system data becomes available\n * - Maintains consistency across device restarts and configuration changes\n *\n * ## Singleton Behavior\n *\n * Device models use singleton pattern - each device type has one instance:\n * - Subsequent factory calls return the existing instance\n * - Options are ignored after first creation\n * - Ensures system-wide device identity consistency\n *\n * This is an alias for the implementation {@link DeviceModelImpl}.\n *\n * @interface\n * @group KOS Model\n * @category Device Data\n * @useDeclaredType\n */\nexport type DeviceModel = PublicModelInterface<DeviceModelImpl>;\n\n@kosModel(MODEL_TYPE)\nexport class DeviceModelImpl implements IKosDataModel, IKosIdentifiable {\n id: string;\n private logger: KosContextLogger;\n private _serialNumber: string | \"unassigned\";\n\n /**\n * Hardware-based device serial number for unique identification.\n *\n * Returns the device's hardware serial number or \"unassigned\" if not yet loaded.\n * Serial numbers are typically retrieved from the device's hardware identification\n * system during critical data events.\n *\n * @example\n * ```typescript\n * const device = Device.factory({});\n *\n * // Check if serial number is available\n * if (device.serialNumber !== \"unassigned\") {\n * console.log(`Device Serial: ${device.serialNumber}`);\n * }\n * ```\n */\n get serialNumber(): string | \"unassigned\" {\n return this._serialNumber;\n }\n\n private _name: string | \"unassigned\";\n\n /**\n * Human-readable device name for administrative identification.\n *\n * Returns the configured device name or \"unassigned\" if not yet set.\n * Device names are typically configured during device setup and used\n * in administrative interfaces for device identification and management.\n *\n * @example\n * ```typescript\n * const device = Device.factory({\n * name: 'Main Production Dispenser'\n * });\n *\n * console.log(`Device Name: ${device.name}`);\n * // Output: \"Device Name: Main Production Dispenser\"\n * ```\n */\n get name(): string | \"unassigned\" {\n return this._name;\n }\n\n private _nodeId: string | \"unassigned\";\n\n /**\n * Full node identifier within the KOS deployment.\n *\n * Returns the complete node ID or \"unassigned\" if not yet configured.\n * Node IDs follow the pattern \"type-instance\" (e.g., \"primary-main\", \"secondary-backup\")\n * and identify the specific node role and instance within multi-node deployments.\n *\n * @example\n * ```typescript\n * const device = Device.factory({\n * nodeId: 'primary-controller'\n * });\n *\n * console.log(`Node ID: ${device.nodeId}`);\n * // Output: \"Node ID: primary-controller\"\n * ```\n *\n * @see {@link nodeType} for extracting the node type portion\n * @see {@link nodeName} for extracting the node name portion\n */\n get nodeId(): string | \"unassigned\" {\n return this._nodeId;\n }\n\n /**\n * Node type extracted from the node identifier.\n *\n * Returns the first part of the node ID (before the hyphen).\n * For node ID \"primary-controller\", this returns \"primary\".\n * Used for role-based logic and node coordination.\n *\n * @example\n * ```typescript\n * const device = Device.factory({\n * nodeId: 'primary-controller'\n * });\n *\n * console.log(`Node Type: ${device.nodeType}`);\n * // Output: \"Node Type: primary\"\n *\n * // Role-based coordination\n * if (device.nodeType === 'primary') {\n * // Handle primary node responsibilities\n * }\n * ```\n */\n get nodeType(): string {\n const [nodeType] = this.nodeId.split(\"-\");\n return nodeType;\n }\n\n /**\n * Node name extracted from the node identifier.\n *\n * Returns the second part of the node ID (after the hyphen).\n * For node ID \"primary-controller\", this returns \"controller\".\n * Used for instance-specific identification within node types.\n *\n * @example\n * ```typescript\n * const device = Device.factory({\n * nodeId: 'secondary-backup'\n * });\n *\n * console.log(`Node Name: ${device.nodeName}`);\n * // Output: \"Node Name: backup\"\n *\n * // Instance-specific logic\n * if (device.nodeName === 'backup') {\n * // Handle backup node configuration\n * }\n * ```\n */\n get nodeName(): string {\n const [, nodeName] = this.nodeId.split(\"-\");\n return nodeName;\n }\n\n constructor(\n modelId: string,\n _options: DeviceOptions,\n context: KosCreationContext\n ) {\n this.id = modelId;\n this.logger = context.logger;\n this._serialNumber = \"unassigned\";\n this._name = \"unassigned\";\n this._nodeId = \"unassigned\";\n }\n\n /**\n * Update the device model with new configuration options.\n *\n * Allows dynamic updating of device identity and node configuration.\n * Any undefined values will be set to \"unassigned\". This method is typically\n * called internally during device data loading or external configuration changes.\n *\n * @param options - Device configuration options to apply\n *\n * @example\n * ```typescript\n * const device = Device.factory({});\n *\n * // Update with new device information\n * device.updateModel({\n * serialNumber: 'KOS-DEVICE-12345',\n * name: 'Updated Dispenser Name',\n * nodeId: 'primary-main'\n * });\n *\n * console.log(device.serialNumber); // \"KOS-DEVICE-12345\"\n * console.log(device.name); // \"Updated Dispenser Name\"\n * console.log(device.nodeId); // \"primary-main\"\n * ```\n *\n * @example Partial Updates\n * ```typescript\n * // Only update specific fields\n * device.updateModel({\n * name: 'New Device Name'\n * // serialNumber and nodeId remain unchanged\n * });\n * ```\n */\n updateModel(options: DeviceOptions): void {\n this._serialNumber = options.serialNumber ?? \"unassigned\";\n this._name = options.name ?? \"unassigned\";\n this._nodeId = options.nodeId ?? \"unassigned\";\n }\n\n private async loadDeviceData() {\n const [error, device] = await getDeviceDetails();\n if (error) {\n this.logger.error(`Error fetching device serial number: ${error}`);\n return;\n }\n if (device) {\n const { name, nodeId } = device;\n this.updateModel({ name, nodeId, serialNumber: this.serialNumber });\n }\n }\n\n private async loadSerialNumber() {\n const [error, serialNumber] = await getSerialNumber();\n if (error) {\n this.logger.error(`Error fetching device serial number: ${error}`);\n return;\n }\n\n this.updateModel({ serialNumber, name: this.name, nodeId: this.nodeId });\n }\n\n /**\n * Handle critical data changes to load the serial number at the appropriate time.\n */\n @kosTopicHandler({\n topic: [TOPIC_CRITICAL_DATA_CHANGED, TOPIC_CRITICAL_DATA_AVAILABLE],\n websocket: true,\n })\n async handleCriticalDataChanged() {\n this.logger.debug(`Critical data changed for device ${this.id}`);\n await this.loadSerialNumber();\n }\n\n // -------------------LIFECYCLE----------------------------\n\n /**\n * @internal\n */\n async init(): Promise<void> {\n this.logger.debug(`initializing device ${this.id}`);\n }\n\n /**\n * @internal\n */\n async load(): Promise<void> {\n this.logger.debug(`loading device ${this.id}`);\n await this.loadDeviceData();\n await this.loadSerialNumber();\n }\n}\n","import { SingletonKosModelRegistrationFactory } from \"../../../core\";\nimport type { DeviceModel } from \"./device-model\";\nimport { DeviceModelImpl, MODEL_TYPE } from \"./device-model\";\nimport type { DeviceOptions } from \"./types\";\n\n/**\n * # Device Model Registration Factory\n *\n * **KOS Device Identity and Node Configuration Management**\n *\n * The Device registration factory provides convenient methods for creating and working with DeviceModel instances.\n * Device models handle device identity, hardware serial numbers, and node configuration within KOS deployments.\n *\n * ## Core Registration Properties\n *\n * ### type\n *\n * Model type identifier used for dependency injection and type narrowing.\n * Essential for declaring model dependencies in other components.\n *\n * @example Model Dependency Declaration\n * ```typescript\n * @kosDependency({modelType: Device.type, id: \"deviceId\"})\n * private deviceModel: DeviceModel;\n * ```\n *\n * ### factory\n *\n * Creates DeviceModel instances with singleton behavior. Multiple calls return the same instance,\n * ensuring system-wide device identity consistency.\n *\n * **Singleton Behavior**: Subsequent factory calls return existing instance; options ignored after first creation.\n *\n * @example Device Creation and Identity Access\n * ```typescript\n * const device = Device.factory({\n * serialNumber: 'KOS-DEVICE-001',\n * name: 'Production Dispenser Alpha',\n * nodeId: 'primary-controller'\n * });\n *\n * // Access device identity\n * console.log(`Device: ${device.name} (${device.serialNumber})`);\n * console.log(`Node: ${device.nodeType}-${device.nodeName}`);\n * ```\n *\n * @example Multi-node System Coordination\n * ```typescript\n * const primaryDevice = Device.factory({ nodeId: 'primary-main' });\n * const backupDevice = Device.factory({ nodeId: 'secondary-backup' });\n *\n * // Coordinate based on node roles\n * if (primaryDevice.nodeType === 'primary') {\n * // Handle primary node responsibilities\n * }\n * ```\n *\n * ### predicate\n *\n * [TypeScript type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates)\n * for identifying and narrowing models to DeviceModel instances.\n *\n * @example Type Narrowing for Device Operations\n * ```typescript\n * const model: IKosDataModel = getModel(); // some model\n *\n * if (Device.predicate(model)) {\n * // Compiler now knows model is DeviceModel\n * console.log(`Device Serial: ${model.serialNumber}`);\n * model.updateModel({ name: 'Updated Name' });\n * }\n * ```\n *\n * ### registration\n *\n * Registration object for model registry integration. Provides all required information\n * for registering the DeviceModelImpl implementation with the model registry.\n *\n * @example Model Registry Configuration\n * ```typescript\n * // registration.ts\n * import { Device } from \"@kos-ui/project-models\";\n * import { KosModelRegistry } from \"@kosdev-code/kos-dispense-sdk\";\n *\n * KosModelRegistry.dispense\n * .models()\n * .model(Device);\n * ```\n *\n * ## Singleton Architecture\n *\n * **Device models use singleton pattern** ensuring system-wide consistency:\n * - Each device type has exactly one instance\n * - Subsequent factory calls return existing instance\n * - Options are ignored after initial creation\n * - Uses model type as unique identifier\n * - Guarantees device identity consistency across system\n *\n * @group KOS Model\n * @category Device Data\n */\nexport const Device = new SingletonKosModelRegistrationFactory<\n DeviceModel,\n DeviceOptions\n>({\n class: DeviceModelImpl,\n type: MODEL_TYPE,\n});\n","import type {\n IKosDataModel,\n IKosIdentifiable,\n KosContextLogger,\n KosCreationContext,\n PublicModelInterface,\n} from \"../../../core\";\nimport { kosModel } from \"../../../core\";\nimport type {\n EthernetData,\n Ip44Settings,\n NetworkInterfaceCategory,\n NetworkInterfaceData,\n WifiData,\n} from \"./services\";\nimport type { NetworkInterfaceOptions } from \"./types\";\n\nexport const MODEL_TYPE = \"network-interface-model\";\n\n/**\n * NetworkInterface - Network interface management and monitoring for KOS devices.\n *\n * The NetworkInterface model provides comprehensive network interface management capabilities, including\n * WiFi and Ethernet configuration, IP settings, and real-time network state monitoring. This model is\n * essential for applications that need to display network status, configure network connections, or\n * manage network interfaces on KOS devices.\n *\n * ## Key Features\n * - **Network Interface Discovery** - Automatically discovers and tracks available network interfaces\n * - **WiFi Management** - Access WiFi connection details, signal strength, and access point information\n * - **Ethernet Monitoring** - Track Ethernet connection status, speed, and duplex settings\n * - **IP Configuration** - Monitor and manage IPv4 settings including addresses, gateways, and DNS\n * - **Connection State Tracking** - Real-time monitoring of network device states and connectivity\n * - **Hardware Information** - Access to MAC addresses, MTU settings, and device capabilities\n *\n * ## Network Interface Categories\n * The model categorizes interfaces for easier management:\n * - **INTERNAL** - Internal system interfaces (loopback, etc.)\n * - **INTEGRATION** - Integration-specific interfaces\n * - **EXTERNAL** - User-facing network interfaces (WiFi, Ethernet)\n * - **NONE** - Uncategorized interfaces\n *\n * ## Common Use Cases\n * - **Network Status Display** - Show current connection status and network details in UI\n * - **Connection Management** - Allow users to view and configure network settings\n * - **Network Diagnostics** - Provide detailed network interface information for troubleshooting\n * - **System Integration** - Monitor network connectivity for automated systems\n * - **Configuration Interfaces** - Build network configuration screens with current state\n *\n * @interface\n * @example Basic Usage\n * ```typescript\n * const networkInterface = NetworkInterface.instance('eth0')\n * .options({\n * name: 'eth0',\n * type: 'ethernet',\n * configured: true,\n * category: 'EXTERNAL'\n * })\n * .build();\n *\n * console.log(networkInterface.name); // 'eth0'\n * console.log(networkInterface.configured); // true\n * ```\n *\n * @group KOS Model\n * @category Network Interfaces\n * @useDeclaredType\n *\n * @see {@link NetworkInterfaceContainer} - Container model for managing multiple network interfaces\n * @see {@link NetworkInterfaceOptions} - Configuration options interface\n * @see {@link EthernetData} - Ethernet-specific interface data\n * @see {@link WifiData} - WiFi-specific interface data\n * @see {@link Ip44Settings} - IPv4 configuration settings\n */\nexport type NetworkInterfaceModel =\n PublicModelInterface<NetworkInterfaceModelImpl>;\n\n/**\n * @ignore\n * @internal\n */\n@kosModel(MODEL_TYPE)\nexport class NetworkInterfaceModelImpl\n implements IKosDataModel, IKosIdentifiable, NetworkInterfaceData\n{\n /** Unique identifier for the model instance */\n id: string;\n\n /** Network interface name (e.g., 'eth0', 'wlan0', 'lo') */\n name: string;\n\n /** Interface type identifier (e.g., 'ethernet', 'wifi', 'loopback') */\n type: string;\n\n /** NetworkManager device state code indicating connection status */\n nmdevicestate: number;\n\n /** Hardware MAC address of the network interface */\n hwaddress: string;\n\n /** Maximum Transmission Unit size for the interface */\n mtu: number;\n\n /** Whether the interface is currently configured and active */\n configured: boolean;\n\n /** WiFi-specific connection data including SSID, signal strength, and security */\n wifi?: WifiData;\n\n /** Ethernet-specific connection data including carrier status, speed, and duplex */\n ethernet?: EthernetData;\n\n /** IPv4 network settings including address, gateway, and DNS configuration */\n ip4settings?: Ip44Settings;\n\n /** Interface categorization for organizational purposes */\n category: NetworkInterfaceCategory;\n\n private logger: KosContextLogger;\n\n constructor(\n modelId: string,\n options: NetworkInterfaceOptions,\n context: KosCreationContext\n ) {\n this.id = modelId;\n this.logger = context.logger;\n\n this.name = options.name;\n this.type = options.type;\n this.nmdevicestate = options.nmdevicestate;\n this.hwaddress = options.hwaddress;\n this.mtu = options.mtu;\n this.configured = options.configured;\n this.wifi = options.wifi;\n this.ethernet = options.ethernet;\n this.ip4settings = options.ip4settings;\n this.category = options.category;\n }\n\n updateModel(options: NetworkInterfaceOptions): void {\n this.name = options.name;\n this.type = options.type;\n this.nmdevicestate = options.nmdevicestate;\n this.hwaddress = options.hwaddress;\n this.mtu = options.mtu;\n this.configured = options.configured;\n this.wifi = options.wifi;\n this.ethernet = options.ethernet;\n this.ip4settings = options.ip4settings;\n this.category = options.category;\n }\n\n // -------------------LIFECYCLE----------------------------\n\n /**\n * @internal\n */\n async init(): Promise<void> {\n this.logger.debug(`initializing network-interface ${this.id}`);\n }\n\n /**\n * @internal\n */\n async load(): Promise<void> {\n this.logger.debug(`loading network-interface ${this.id}`);\n }\n}\n","import { KosModelRegistrationFactory } from \"../../../core\";\nimport type { NetworkInterfaceModel } from \"./network-interface-model\";\nimport {\n MODEL_TYPE,\n NetworkInterfaceModelImpl,\n} from \"./network-interface-model\";\nimport type { NetworkInterfaceOptions } from \"./types\";\n\n/**\n * # NetworkInterface\n *\n * The registration bean includes convenience methods for creating and working with NetworkInterfaceModel instances.\n *\n * ## type\n * The type property is a string that identifies the model type.\n * The type is used to identify the model type in the model registry and to narrow down the model type in type predicates. It's most frequently\n * used when declaring dependencies on models.\n *\n * @example\n * ```typescript\n *\n * @kosDependency({modelType: NetworkInterface.type, id: \"networkInterfaceId\"})\n * private networkInterfaceModel: NetworkInterfaceModel;\n * ```\n *\n *\n * ## factory\n *\n * The factory method creates a factory function that can be used to create new NetworkInterfaceModel instances.\n *\n \n * The factory function is a curried function that takes the model id as the first argument and the options as the second argument.\n *\n * If a model with the specified id already exists, the factory function will return the existing model. The options will be ignored\n * in this case and the existing model will be returned in its current state.\n *\n * @example\n * ```typescript\n * const model = NetworkInterface.factory(\"networkInterfaceId\")({\n * // Add option data\n * });\n * ```\n \n\n *\n * ## predicate\n *\n * [Typescript type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) function that will identify and narrow down a model to a NetworkInterfaceModel.\n *\n * @example\n * ```typescript\n *\n * const model: IKosDataModel = ...; // some model\n *\n * if (NetworkInterface.predicate(model)) {\n * // if the function evaluates to true, the model is narrowed down to NetworkInterfaceModel\n * // and the compiler will know that the model has the NetworkInterfaceModel interface\n * model.updateAvailability(false);\n * }\n * ```\n *\n * ## registration\n *\n * The registration property is an object that can be used to simplify registration of the model with the model registry. The registration object\n * can be spread into the model registration and provides all of the required information to register the model implementation class against the model type.\n *\n *\n * @example\n *\n * In an application registration file you can declare the model registration as follows:\n *\n * **registration.ts**\n * ```typescript\n * import { NetworkInterface } from \"@kos-ui/project-models\";\n * import { KosModelRegistry } from \"@kosdev-code/kos-dispense-sdk\";\n *\n * import { initKosProvider } from \"@kosdev-code/kos-ui-sdk\";\n *\n * KosModelRegistry.dispense\n * .models()\n * .model(NetworkInterface);\n * ```\n *\n * ## registration.singleton\n \n * The networkInterface model is NOT a singleton model. This means that each time the factory function is called with a unique ID, a new model instance will be created.\n * If the factory function is called with an ID that already exists, the existing model will be returned.\n * @group KOS Model\n * @category Network Interfaces\n * */\nexport const NetworkInterface = new KosModelRegistrationFactory<\n NetworkInterfaceModel,\n NetworkInterfaceOptions\n>({\n class: NetworkInterfaceModelImpl,\n type: MODEL_TYPE,\n});\n","/**\n * @internal\n */\nimport {\n FetchError,\n KosLog,\n ServiceFactory,\n resolveServiceUrl,\n} from \"../../../../core\";\nimport { getKosConnectionId } from \"../../../utils/get-kos-connection-id\";\nconst { URL } = resolveServiceUrl(\"NETWORK-INTERFACE_SERVICE\");\nconst { getAll } = ServiceFactory.build({\n basePath: `${URL}/api/kos/network/interfaces`,\n});\n\nconst log = KosLog.createLogger({\n name: \"network-interface-service\",\n group: \"Services\",\n});\n\n/**\n * Network interface categories for organizational purposes.\n * @group KOS Model\n * @category Network Interfaces\n */\nexport type NetworkInterfaceCategory =\n | \"INTERNAL\"\n | \"INTEGRATION\"\n | \"EXTERNAL\"\n | \"NONE\";\n\n/**\n * Ethernet-specific interface data including connection status and performance metrics.\n * @group KOS Model\n * @category Network Interfaces\n */\nexport interface EthernetData {\n /** Whether the Ethernet cable is connected (link up/down status) */\n carrier: boolean;\n /** Connection speed in Mbps (e.g., 10, 100, 1000) */\n speed: number;\n /** Duplex mode - 'full' for full-duplex, 'half' for half-duplex */\n duplex: string;\n}\n\n/**\n * WiFi-specific interface data including access point details and signal metrics.\n * @group KOS Model\n * @category Network Interfaces\n */\nexport interface WifiData {\n /** Access Point flags indicating capabilities and features */\n apFlags: number;\n /** BSSID (MAC address) of the connected access point */\n bssid: string;\n /** WPA security flags for the connection */\n wpaFlags: number;\n /** Connection bitrate in bits per second */\n bitrate: number;\n /** Network name (Service Set Identifier) */\n ssid: string;\n /** Signal strength percentage (0-100) */\n signal: number;\n /** RSN (Robust Security Network) flags for WPA2/WPA3 */\n rsnFlags: number;\n /** Time in seconds since the access point was last seen */\n lastSeenAgo: number;\n /** WiFi frequency in MHz (e.g., 2437 for 2.4GHz, 5220 for 5GHz) */\n frequency: number;\n}\n\n/**\n * IPv4 network configuration settings including addressing and DNS.\n * @group KOS Model\n * @category Network Interfaces\n */\nexport interface Ip44Settings {\n /** Subnet prefix length (e.g., 24 for /24 subnet mask) */\n prefix: number;\n /** List of address/prefix combinations in CIDR notation */\n addressprefixlist: string[];\n /** Primary IP address assigned to the interface */\n address: string;\n /** IP configuration method ('auto' for DHCP, 'manual' for static) */\n method: string;\n /** Default gateway IP address for routing */\n gateway: string;\n /** List of DNS server IP addresses */\n dnslist: string[];\n}\n\n/**\n * Complete network interface data structure containing all interface properties.\n * This is the main interface that NetworkInterfaceModel implements.\n * @group KOS Model\n * @category Network Interfaces\n */\nexport interface NetworkInterfaceData {\n /** Network interface name (e.g., 'eth0', 'wlan0', 'lo') */\n name: string;\n /** Interface type identifier (e.g., 'ethernet', 'wifi', 'loopback') */\n type: string;\n /** NetworkManager device state code indicating connection status */\n nmdevicestate: number;\n /** Hardware MAC address of the network interface */\n hwaddress: string;\n /** Maximum Transmission Unit size for the interface */\n mtu: number;\n /** Whether the interface is currently configured and active */\n configured: boolean;\n /** WiFi-specific connection data (only present for WiFi interfaces) */\n wifi?: WifiData;\n /** Ethernet-specific connection data (only present for Ethernet interfaces) */\n ethernet?: EthernetData;\n /** IPv4 network settings (present when interface has IP configuration) */\n ip4settings?: Ip44Settings;\n /** Interface categorization for organizational purposes */\n category: NetworkInterfaceCategory;\n}\n\ntype NetworkInterfaceResponse =\n | [error: string, data: undefined]\n | [error: undefined, data: NetworkInterfaceData[] | undefined];\n/**\n * @category Service\n * @internal\n * Retrieves the initial network-interface data.\n */\n\nexport const getNetworkInterfaces =\n async (): Promise<NetworkInterfaceResponse> => {\n const destinationAddress = getKosConnectionId();\n log.debug(\"sending GET for copy-logs\");\n\n try {\n const response = await getAll<NetworkInterfaceData>({\n destinationAddress,\n });\n\n return [undefined, response?.data];\n } catch (error) {\n if (error instanceof FetchError) {\n log.error(`Error fetching log file size: ${error.payload.error}`);\n return [error.payload.error, undefined];\n }\n }\n\n return [\"unknownError\", undefined];\n };\n","import type {\n IKosDataModel,\n IKosIdentifiable,\n IKosModelContainer,\n IKosModelHolder,\n KosContextLogger,\n KosCreationContext,\n PublicModelInterface,\n} from \"../../../core\";\nimport { kosChild, kosModel, KosModelContainer } from \"../../../core\";\nimport type { NetworkInterfaceModel } from \"./network-interface-model\";\nimport { NetworkInterface } from \"./network-interface-registration\";\nimport { getNetworkInterfaces } from \"./services\";\nimport type { NetworkInterfaceContainerOptions } from \"./types\";\n\nexport const MODEL_TYPE = \"network-interface-container-model\";\n\n/**\n * NetworkInterfaceContainer - Centralized management of multiple network interfaces on KOS devices.\n *\n * The NetworkInterfaceContainer model provides comprehensive management of all network interfaces\n * available on a KOS device, including automatic discovery, categorization, and real-time updates.\n * This container model is essential for applications that need to manage multiple network interfaces,\n * build network configuration screens, or monitor overall network connectivity status.\n *\n * ## Key Features\n * - **Automatic Interface Discovery** - Loads and manages all available network interfaces from the device\n * - **Category-Based Indexing** - Organizes interfaces by category (INTERNAL, INTEGRATION, EXTERNAL, NONE)\n * - **Real-Time Refresh** - Updates interface data with current network state\n * - **Unified Interface Management** - Single point of access for all network interface operations\n * - **Dynamic Interface Tracking** - Handles interface addition/removal as network state changes\n * - **Service Integration** - Automatically fetches interface data from KOS network services\n *\n * ## Interface Categories\n * The container automatically organizes interfaces into categories:\n * - **EXTERNAL** - User-facing interfaces (WiFi adapters, Ethernet ports)\n * - **INTERNAL** - System interfaces (loopback, virtual interfaces)\n * - **INTEGRATION** - Integration-specific network interfaces\n * - **NONE** - Uncategorized interfaces\n *\n * ## Common Use Cases\n * - **Network Configuration UI** - Build comprehensive network settings interfaces\n * - **System Monitoring** - Track overall network connectivity and interface health\n * - **Interface Selection** - Allow users to choose from available network interfaces\n * - **Network Diagnostics** - Provide detailed system-wide network interface information\n * - **Automated Network Management** - Programmatically manage multiple interfaces\n *\n * @example Basic Usage\n * ```typescript\n * const networkContainer = NetworkInterfaceContainer.instance('system-interfaces')\n * .build();\n *\n * // Access all network interfaces and get specific interface\n * const allInterfaces = networkContainer.models;\n * const ethInterface = networkContainer.getModel('eth0');\n * ```\n *\n * @group KOS Model\n * @category Network Interfaces\n * @interface\n * @useDeclaredType\n *\n * @see {@link NetworkInterface} - Individual network interface model\n * @see {@link NetworkInterfaceOptions} - Network interface configuration options\n * @see {@link getNetworkInterfaces} - Service function for loading interface data\n */\nexport type NetworkInterfaceContainerModel =\n PublicModelInterface<NetworkInterfaceContainerModelImpl>;\n\n/**\n * @ignore\n * @internal\n */\n@kosModel(MODEL_TYPE)\nexport class NetworkInterfaceContainerModelImpl\n implements\n IKosIdentifiable,\n IKosModelHolder<NetworkInterfaceModel>,\n IKosDataModel\n{\n /** Unique identifier for the container model instance */\n id: string;\n /** Context logger for debugging and network interface operations */\n private logger: KosContextLogger;\n /** Container for managing NetworkInterface model instances with category indexing */\n @kosChild private _models: IKosModelContainer<NetworkInterfaceModel>;\n constructor(\n modelId: string,\n options: NetworkInterfaceContainerOptions,\n context: KosCreationContext\n ) {\n this.id = modelId;\n this.logger = context.logger;\n this._models = new KosModelContainer<NetworkInterfaceModel>({\n parentId: modelId,\n indexMap: {\n byCategory: \"category\",\n },\n });\n if (options) {\n // Assign options properties here.\n }\n }\n\n getModel(id: string) {\n return this._models.getModel(id);\n }\n get models() {\n return this._models;\n }\n get data() {\n return this._models.data;\n }\n\n addModel(model: NetworkInterfaceModel) {\n this._models.addModel(model);\n }\n\n removeModel(id: string) {\n this._models.removeModel(id);\n }\n // -------------------LIFECYCLE----------------------------\n\n /**\n * @internal\n */\n async init(): Promise<void> {\n this.logger.debug(\n `initializing network-interface-container container ${this.id}`\n );\n }\n\n async refreshInterfaces() {\n this.logger.debug(`refreshing interfaces`);\n const [error, networkInterfaces] = await getNetworkInterfaces();\n if (error) {\n this.logger.error(`Error loading network interfaces: ${error}`);\n return;\n }\n\n if (networkInterfaces) {\n networkInterfaces.forEach((networkInterfaceData) => {\n const networkInterfaceModel = NetworkInterface.instance(\n networkInterfaceData.name\n )\n .forceUpdate.options(networkInterfaceData)\n .build();\n this.addModel(networkInterfaceModel);\n });\n }\n }\n\n /**\n * @internal\n */\n async load(): Promise<void> {\n this.logger.debug(\n `loading network-interface-container container ${this.id}`\n );\n\n this.refreshInterfaces();\n }\n}\n","import { SingletonKosModelRegistrationFactory } from \"../../../core\";\nimport type { NetworkInterfaceContainerModel } from \"./network-interface-container-model\";\nimport {\n MODEL_TYPE,\n NetworkInterfaceContainerModelImpl,\n} from \"./network-interface-container-model\";\nimport { NetworkInterface } from \"./network-interface-registration\";\nimport type { NetworkInterfaceContainerOptions } from \"./types\";\n\n/**\n * # NetworkInterfaceContainer\n *\n * The registration bean includes convenience methods for creating and working with NetworkInterfaceContainerModel instances.\n *\n * ## type\n * The type property is a string that identifies the model type.\n * The type is used to identify the model type in the model registry and to narrow down the model type in type predicates. It's most frequently\n * used when declaring dependencies on models.\n *\n * @example\n * ```typescript\n *\n * @kosDependency({modelType: NetworkInterfaceContainer.type, id: \"networkInterfaceContainerId\"})\n * private networkInterfaceContainerModel: NetworkInterfaceContainerModel;\n * ```\n *\n *\n * ## factory\n *\n * The factory method creates a factory function that can be used to create new NetworkInterfaceContainerModel instances.\n *\n \n * As this is a singleton model, the factory function accepts the model options as its argument.\n *\n * If a model with the same model type already exists, the factory function will return the existing model. The options will be ignored\n * in this case and the existing model will be returned in its current state.\n *\n * @example\n * ```typescript\n * const model = NetworkInterfaceContainer.factory({\n * // Add option data\n * });\n * ```\n \n\n *\n * ## predicate\n *\n * [Typescript type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) function that will identify and narrow down a model to a NetworkInterfaceContainerModel.\n *\n * @example\n * ```typescript\n *\n * const model: IKosDataModel = ...; // some model\n *\n * if (NetworkInterfaceContainer.predicate(model)) {\n * // if the function evaluates to true, the model is narrowed down to NetworkInterfaceContainerModel\n * // and the compiler will know that the model has the NetworkInterfaceContainerModel interface\n * model.updateAvailability(false);\n * }\n * ```\n *\n * ## registration\n *\n * The registration property is an object that can be used to simplify registration of the model with the model registry. The registration object\n * can be spread into the model registration and provides all of the required information to register the model implementation class against the model type.\n *\n *\n * @example\n *\n * In an application registration file you can declare the model registration as follows:\n *\n * **registration.ts**\n * ```typescript\n * import { NetworkInterfaceContainer } from \"@kosdev-code/kos-dispense-sdk\";\n * ...\n * import { ExtensionManager, IKosRegistry } from \"@kosdev-code/kos-ui-sdk\";\n * export const kosModels: IKosRegistry[\"models\"] = {\n * ...NetworkInterfaceContainer.registration,\n * };\n * ```\n *\n * ## registration.singleton\n \n * The networkInterfaceContainer model is a singleton model. This means that each time the factory function is called , the same instance will be returned.\n * If the model does not yet exist, it will be created passing in the provided options to initialize it.\n *\n * Singleton models don't require an ID as they will use the model type as their ID to guarantee uniqueness throughout the system.\n * @group KOS Model\n * @category Network Interfaces\n * */\nexport const NetworkInterfaceContainer =\n new SingletonKosModelRegistrationFactory<\n NetworkInterfaceContainerModel,\n NetworkInterfaceContainerOptions\n >({\n class: NetworkInterfaceContainerModelImpl,\n type: MODEL_TYPE,\n });\n\nNetworkInterfaceContainer.addRelatedModel(NetworkInterface);\n","/**\n * @internal\n */\n\nimport { KosLog, resolveServiceUrl, ServiceFactory } from \"../../../../core\";\n\nconst { URL } = resolveServiceUrl(\"STORAGE-DEVICE_SERVICE\");\nconst { getAll } = ServiceFactory.build({\n basePath: `${URL}/api/kos/storage/devices`,\n});\n\nconst log = KosLog.createLogger({\n name: \"storage-device-service\",\n group: \"Services\",\n});\n\nexport interface StorageDeviceResponse {\n mountDir: string;\n removed: boolean;\n id: string;\n vendor: string;\n runTimeMs: number;\n model: string;\n nodeId: string;\n local: boolean;\n label: string;\n syspath: string;\n deviceType?: \"disk\" | \"partition\";\n}\n/**\n * @category Service\n * @internal\n * Retrieves the initial storage-device data.\n */\nexport const getStorageDevices = async () => {\n log.debug(\"sending GET for storage-device\");\n const response = await getAll<StorageDeviceResponse>({});\n if (!response?.data || response.status !== 200) {\n log.error(\"Failed to retrieve storage-device data\", response);\n return [];\n }\n return response.data;\n};\n","import type {\n IKosDataModel,\n IKosIdentifiable,\n KosContextLogger,\n KosCreationContext,\n PublicModelInterface,\n} from \"../../../core\";\nimport { kosModel, kosParentAware } from \"../../../core\";\nimport type { StorageDeviceOptions } from \"./types\";\n\nexport const MODEL_TYPE = \"storage-device-model\";\n\n/**\n * StorageDevice - Manages individual USB/external storage device information and state.\n *\n * The StorageDevice model represents individual storage devices (USB drives, SD cards,\n * external drives) connected to the KOS system. It tracks device hardware information,\n * mount status, and provides access to device metadata including vendor, model, runtime\n * statistics, and file system details.\n *\n * ## Key Features\n * - **Hardware Information** - Vendor, model, and system path details\n * - **Mount Management** - Track mount directory and removal status\n * - **Runtime Statistics** - Device runtime and usage metrics\n * - **Node Awareness** - Multi-node device distribution tracking\n * - **File System Integration** - Label and mount point management\n * - **Parent-Aware Architecture** - Designed for container model management\n *\n * ## Device Properties\n * Storage devices expose comprehensive hardware and state information:\n * - **Physical Details**: vendor, model, syspath for hardware identification\n * - **Mount Information**: mountDir, label for file system access\n * - **Status Tracking**: removed flag, local/remote node distribution\n * - **Runtime Metrics**: runTimeMs for usage analytics\n *\n * ## Common Use Cases\n * - **Storage Management UI** - Display available storage devices and capacity\n * - **File Transfer Operations** - Access mount points for file operations\n * - **System Monitoring** - Track device insertion/removal events\n * - **Backup Management** - Identify backup destination devices\n * - **Multi-node Systems** - Manage storage across distributed KOS nodes\n * - **Device Diagnostics** - Runtime statistics and health monitoring\n *\n * @interface\n * @example Basic Usage\n * ```typescript\n * const usbDrive = StorageDevice.instance('usb-drive-1')\n * .options({\n * mountDir: '/media/usb1',\n * vendor: 'SanDisk',\n * model: 'Ultra USB 3.0',\n * label: 'BACKUP_DRIVE',\n * nodeId: 'primary',\n * local: true,\n * removed: false,\n * runTimeMs: 1800000,\n * syspath: '/sys/devices/usb1'\n * })\n * .build();\n *\n * // Access device properties\n * console.log(`${usbDrive.vendor} ${usbDrive.model} at ${usbDrive.mountDir}`);\n * ```\n *\n * @group KOS Model\n * @category Device Management\n * @useDeclaredType\n *\n * @see {@link StorageDeviceOptions} - Configuration options for StorageDevice instances\n * @see {@link StorageDeviceContainerModel} - Container for managing multiple storage devices\n * @see {@link StorageDeviceResponse} - API response structure for device data\n */\nexport type StorageDevice = PublicModelInterface<StorageDeviceModelImpl>;\n\nexport type StorageDeviceModel = PublicModelInterface<StorageDeviceModelImpl>;\n\n/**\n * @ignore\n * @internal\n */\n@kosParentAware()\n@kosModel(MODEL_TYPE)\nexport class StorageDeviceModelImpl implements IKosDataModel, IKosIdentifiable {\n /** Unique identifier for the storage device model instance */\n id: string;\n /** File system mount directory path where device is accessible */\n mountDir: string;\n /** Whether the device has been physically removed from the system */\n removed: boolean;\n /** Device manufacturer name (e.g., 'SanDisk', 'Western Digital') */\n vendor: string;\n /** Total device runtime in milliseconds for usage tracking */\n runTimeMs: number;\n /** Device model name or identifier (e.g., 'Ultra USB 3.0', 'My Passport') */\n model: string;\n /** KOS node identifier where this device is connected */\n nodeId: string;\n /** Whether the device is connected to the local node */\n local: boolean;\n /** File system label or volume name for the device */\n label: string;\n /** System path for hardware identification and low-level access */\n syspath: string;\n /** Context logger for debugging and diagnostics */\n private logger: KosContextLogger;\n constructor(\n modelId: string,\n options: StorageDeviceOptions,\n context: KosCreationContext\n ) {\n this.id = modelId;\n this.logger = context.logger;\n this.mountDir = options.mountDir;\n this.removed = options.removed;\n this.vendor = options.vendor;\n this.runTimeMs = options.runTimeMs;\n this.model = options.model;\n this.nodeId = options.nodeId;\n this.local = options.local;\n this.label = options.label;\n this.syspath = options.syspath;\n }\n\n /**\n * Updates the storage device model with new configuration options.\n * @param options New configuration options to apply to the device\n */\n updateModel(options: StorageDeviceOptions): void {\n this.mountDir = options.mountDir;\n this.removed = options.removed;\n this.vendor = options.vendor;\n this.runTimeMs = options.runTimeMs;\n this.model = options.model;\n this.nodeId = options.nodeId;\n this.local = options.local;\n this.label = options.label;\n this.syspath = options.syspath;\n }\n\n // -------------------LIFECYCLE----------------------------\n\n /**\n * @internal\n */\n async init(): Promise<void> {\n this.logger.debug(`initializing storage-device ${this.id}`);\n }\n\n /**\n * @internal\n */\n async load(): Promise<void> {\n this.logger.debug(`loading storage-device ${this.id}`);\n }\n}\n","import { KosModelRegistrationFactory } from \"../../../core\";\nimport type { StorageDeviceModel } from \"./storage-device-model\";\nimport { MODEL_TYPE, StorageDeviceModelImpl } from \"./storage-device-model\";\nimport type { StorageDeviceOptions } from \"./types\";\n\n/**\n * # StorageDevice\n *\n * The registration bean includes convenience methods for creating and working with StorageDeviceModel instances.\n *\n * ## type\n * The type property is a string that identifies the model type.\n * The type is used to identify the model type in the model registry and to narrow down the model type in type predicates. It's most frequently\n * used when declaring dependencies on models.\n *\n * @example\n * ```typescript\n *\n * @kosDependency({modelType: StorageDevice.type, id: \"storageDeviceId\"})\n * private storageDeviceModel: StorageDeviceModel;\n * ```\n *\n *\n * ## factory\n *\n * The factory method creates a factory function that can be used to create new StorageDeviceModel instances.\n *\n \n * The factory function is a curried function that takes the model id as the first argument and the options as the second argument.\n *\n * If a model with the specified id already exists, the factory function will return the existing model. The options will be ignored\n * in this case and the existing model will be returned in its current state.\n *\n * @example\n * ```typescript\n * const model = StorageDevice.factory(\"storageDeviceId\")({\n * // Add option data\n * });\n * ```\n \n\n *\n * ## predicate\n *\n * [Typescript type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) function that will identify and narrow down a model to a StorageDeviceModel.\n *\n * @example\n * ```typescript\n *\n * const model: IKosDataModel = ...; // some model\n *\n * if (StorageDevice.predicate(model)) {\n * // if the function evaluates to true, the model is narrowed down to StorageDeviceModel\n * // and the compiler will know that the model has the StorageDeviceModel interface\n * model.updateAvailability(false);\n * }\n * ```\n *\n * ## registration\n *\n * The registration property is an object that can be used to simplify registration of the model with the model registry. The registration object\n * can be spread into the model registration and provides all of the required information to register the model implementation class against the model type.\n *\n *\n * @example\n *\n * In an application registration file you can declare the model registration as follows:\n *\n * **registration.ts**\n * ```typescript\n * import { StorageDevice } from \"@kos-ui/project-models\";\n * import { KosModelRegistry } from \"@kosdev-code/kos-dispense-sdk\";\n *\n * import { initKosProvider } from \"@kosdev-code/kos-ui-sdk\";\n *\n * KosModelRegistry.dispense\n * .models()\n * .model(StorageDevice);\n * ```\n *\n * ## registration.singleton\n \n * The storageDevice model is NOT a singleton model. This means that each time the factory function is called with a unique ID, a new model instance will be created.\n * If the factory function is called with an ID that already exists, the existing model will be returned.\n \n * */\nexport const StorageDevice = new KosModelRegistrationFactory<\n StorageDeviceModel,\n StorageDeviceOptions\n>({\n class: StorageDeviceModelImpl,\n type: MODEL_TYPE,\n});\n","import {\n type IKosIdentifiable,\n type IKosModelHolder,\n kosChild,\n kosModel,\n kosTopicHandler,\n type PublicModelInterface,\n} from \"../../../core\";\nimport {\n type IKosModelContainer,\n KosModelContainer,\n} from \"../../../core/core/kos-container-model\";\nimport {\n type IKosDataModel,\n KosContextLogger,\n type KosCreationContext,\n} from \"../../../core/core/kosModel\";\n\nimport { getStorageDevices, type StorageDeviceResponse } from \"./services\";\nimport type { StorageDeviceModel } from \"./storage-device-model\";\nimport { StorageDevice } from \"./storage-device-registration\";\nimport type {\n StorageDeviceContainerOptions,\n StorageDeviceOptions,\n} from \"./types\";\n\nexport const MODEL_TYPE = \"storage-device-container-model\";\n\nexport const TOPIC_STORAGE_AVAILABILITY = \"/kos/storage\";\n\n/**\n * StorageDeviceContainer - Manages collections of storage devices with real-time discovery.\n *\n * The StorageDeviceContainer model provides centralized management of multiple storage devices\n * connected to KOS systems. It automatically discovers devices through REST API calls and\n * maintains real-time synchronization via WebSocket topics, handling device insertion,\n * removal, and state updates across the entire storage ecosystem.\n *\n * ## Key Features\n * - **Automatic Device Discovery** - Scans and loads all available storage devices\n * - **Real-time Synchronization** - WebSocket updates for insertion/removal events\n * - **Collection Management** - Add, remove, and query storage device collections\n * - **Availability Monitoring** - Track overall storage availability status\n * - **Volume Access** - Direct access to managed storage device instances\n * - **Parent-Child Architecture** - Proper lifecycle management for contained devices\n *\n * ## Topic-Based Reactivity\n * The model listens to these KOS topics for real-time synchronization:\n * - **`/kos/storage`** - Storage device availability changes (insertion/removal events)\n * - Payload: `StorageDeviceResponse[]` - Array of current storage device states\n * - Triggers automatic model updates, additions, and removals\n * - Handles both physical device changes and mount/unmount operations\n *\n * ## Storage Management Operations\n * The container provides comprehensive storage device management:\n * - **Device Lifecycle**: Automatic creation and cleanup of StorageDevice models\n * - **State Synchronization**: Real-time updates from system storage changes\n * - **Collection Queries**: Access devices by ID, status, or availability\n * - **Volume Tracking**: Monitor mounted and available storage volumes\n *\n * ## Common Use Cases\n * - **Storage Management Dashboard** - Display all connected storage devices\n * - **File Transfer Interface** - Select available storage for operations\n * - **System Monitoring** - Track storage availability and health\n * - **Backup Management** - Identify backup destination devices\n * - **Multi-node Storage** - Manage distributed storage across KOS nodes\n * - **Device Diagnostics** - Monitor storage device runtime and status\n *\n * @example Basic Storage Container Usage\n * ```typescript\n * // Create storage device container for system management\n * const storageContainer = StorageDeviceContainer.instance('main-storage')\n * .options({}) // Empty configuration - behavior driven by discovery\n * .build();\n *\n * // Check overall storage availability\n * console.log(`Storage available: ${storageContainer.isStorageInserted}`);\n * console.log(`Total volumes: ${storageContainer.volumes.length}`);\n *\n * // Access individual storage devices\n * const usbDevice = storageContainer.getModel('usb-drive-1');\n * if (usbDevice && !usbDevice.removed) {\n * console.log(`USB device mounted at: ${usbDevice.mountDir}`);\n * }\n * ```\n *\n * @example Storage Device Discovery and Management\n * ```typescript\n * // Container automatically handles device discovery\n * const storageManager = StorageDeviceContainer.instance('storage-mgr')\n * .options({})\n * .build();\n *\n * // Monitor storage changes with reactive patterns\n * const monitorStorageChanges = () => {\n * // Container automatically updates via /kos/storage topic\n * const availableDevices = storageManager.data.filter(device =>\n * !device.removed && device.mountDir\n * );\n *\n * const localDevices = availableDevices.filter(device => device.local);\n * const remoteDevices = availableDevices.filter(device => !device.local);\n *\n * console.log(`Available storage: ${availableDevices.length} devices`);\n * console.log(`Local: ${localDevices.length}, Remote: ${remoteDevices.length}`);\n *\n * return {\n * total: availableDevices.length,\n * local: localDevices.length,\n * remote: remoteDevices.length,\n * devices: availableDevices\n * };\n * };\n * ```\n *\n * @example React Storage Management Interface\n * ```typescript\n * const StorageManagerComponent: React.FC = kosComponent(() => {\n * const storageContainer = useModel(StorageDeviceContainer, 'storage-manager');\n *\n * // Reactive data automatically updates via WebSocket\n * const availableDevices = storageContainer.volumes.filter(device =>\n * !device.removed && device.mountDir\n * );\n *\n * const removedDevices = storageContainer.volumes.filter(device =>\n * device.removed\n * );\n *\n * return (\n * <div className=\"storage-manager\">\n * <div className=\"storage-status\">\n * <h2>Storage Overview</h2>\n * <div className=\"status-indicator\">\n * <span className={storageContainer.isStorageInserted ? 'online' : 'offline'}>\n * {storageContainer.isStorageInserted ? 'Storage Available' : 'No Storage'}\n * </span>\n * </div>\n * <div className=\"device-count\">\n * Total Devices: {storageContainer.volumes.length}\n * </div>\n * </div>\n *\n * <div className=\"device-sections\">\n * <section className=\"available-devices\">\n * <h3>Available Storage ({availableDevices.length})</h3>\n * {availableDevices.map(device => (\n * <StorageDeviceCard key={device.id} device={device} />\n * ))}\n * </section>\n *\n * {removedDevices.length > 0 && (\n * <section className=\"removed-devices\">\n * <h3>Recently Removed ({removedDevices.length})</h3>\n * {removedDevices.map(device => (\n * <StorageDeviceCard key={device.id} device={device} />\n * ))}\n * </section>\n * )}\n * </div>\n * </div>\n * );\n * });\n * ```\n *\n * @example Storage Device Filtering and Queries\n * ```typescript\n * // Create storage container for advanced device management\n * const storageController = StorageDeviceContainer.instance('storage-ctrl')\n * .options({})\n * .build();\n *\n * // Helper functions for device filtering\n * const getStorageQueries = (container: StorageDeviceContainer) => ({\n * // Get all available (mounted and not removed) devices\n * getAvailableDevices: () =>\n * container.data.filter(device => !device.removed && device.mountDir),\n *\n * // Get devices by specific node\n * getDevicesByNode: (nodeId: string) =>\n * container.data.filter(device => device.nodeId === nodeId),\n *\n * // Get local vs remote devices\n * getLocalDevices: () =>\n * container.data.filter(device => device.local),\n *\n * // Get devices by vendor\n * getDevicesByVendor: (vendor: string) =>\n * container.data.filter(device =>\n * device.vendor.toLowerCase().includes(vendor.toLowerCase())\n * ),\n *\n * // Get backup-suitable devices (available with sufficient runtime)\n * getBackupDevices: () =>\n * container.data.filter(device =>\n * !device.removed &&\n * device.mountDir &&\n * device.runTimeMs > 300000 // More than 5 minutes runtime\n * ),\n *\n * // Get device statistics\n * getStorageStats: () => {\n * const devices = container.data;\n * return {\n * total: devices.length,\n * available: devices.filter(d => !d.removed && d.mountDir).length,\n * removed: devices.filter(d => d.removed).length,\n * local: devices.filter(d => d.local).length,\n * remote: devices.filter(d => !d.local).length,\n * averageRuntime: devices.reduce((sum, d) => sum + d.runTimeMs, 0) / devices.length\n * };\n * }\n * });\n *\n * // Usage examples\n * const queries = getStorageQueries(storageController);\n *\n * console.log('Storage Statistics:', queries.getStorageStats());\n * console.log('Available Devices:', queries.getAvailableDevices().length);\n * console.log('Backup-Ready Devices:', queries.getBackupDevices().length);\n * ```\n *\n * @example WebSocket Topic Synchronization\n * ```typescript\n * // The container automatically handles /kos/storage topic updates\n * const storageSync = StorageDeviceContainer.instance('sync-demo')\n * .options({})\n * .build();\n *\n * // Topic payload structure: StorageDeviceResponse[]\n * // Example payload when device is inserted:\n * // [\n * // {\n * // id: \"usb-drive-new\",\n * // mountDir: \"/media/usb-new\",\n * // vendor: \"Kingston\",\n * // model: \"DataTraveler\",\n * // label: \"KINGSTON_32GB\",\n * // nodeId: \"primary\",\n * // local: true,\n * // removed: false,\n * // runTimeMs: 0,\n * // syspath: \"/sys/devices/usb/new\"\n * // }\n * // ]\n *\n * // Container automatically:\n * // 1. Compares payload with existing models\n * // 2. Removes models not in payload (device unplugged)\n * // 3. Updates existing models with new state\n * // 4. Creates new models for discovered devices\n * // 5. Maintains parent-child relationships\n *\n * // Monitor changes reactively\n * const logStorageChanges = () => {\n * const currentDevices = storageSync.data.map(device => ({\n * id: device.id,\n * vendor: device.vendor,\n * mounted: !!device.mountDir,\n * removed: device.removed\n * }));\n *\n * console.log('Current Storage State:', currentDevices);\n * };\n * ```\n *\n * @example Multi-Node Storage Architecture\n * ```typescript\n * // Container manages storage across distributed KOS nodes\n * const distributedStorage = StorageDeviceContainer.instance('distributed')\n * .options({})\n * .build();\n *\n * // Analyze storage distribution across nodes\n * const analyzeStorageDistribution = () => {\n * const nodeGroups = distributedStorage.data.reduce((groups, device) => {\n * const nodeId = device.nodeId;\n * if (!groups[nodeId]) {\n * groups[nodeId] = {\n * nodeId,\n * devices: [],\n * available: 0,\n * totalRuntime: 0\n * };\n * }\n *\n * groups[nodeId].devices.push(device);\n * if (!device.removed && device.mountDir) {\n * groups[nodeId].available++;\n * }\n * groups[nodeId].totalRuntime += device.runTimeMs;\n *\n * return groups;\n * }, {} as Record<string, any>);\n *\n * // Display node distribution\n * Object.values(nodeGroups).forEach((node: any) => {\n * const avgRuntime = node.totalRuntime / node.devices.length;\n * console.log(`Node ${node.nodeId}:`);\n * console.log(` Devices: ${node.devices.length}`);\n * console.log(` Available: ${node.available}`);\n * console.log(` Avg Runtime: ${Math.round(avgRuntime / 60000)}min`);\n * });\n *\n * return nodeGroups;\n * };\n * ```\n *\n * @group KOS Model\n * @category Device Management\n *\n * @see {@link StorageDevice} - Individual storage device model\n * @see {@link StorageDeviceOptions} - Configuration options for storage devices\n * @see {@link StorageDeviceContainerOptions} - Container configuration options\n * @see {@link StorageDeviceResponse} - API response structure for device discovery\n */\nexport type StorageDeviceContainer =\n PublicModelInterface<StorageDeviceContainerModelImpl>;\n\nexport type StorageDeviceContainerModel =\n PublicModelInterface<StorageDeviceContainerModelImpl>;\n\n/**\n * @ignore\n * @internal\n */\n@kosModel(MODEL_TYPE)\nexport class StorageDeviceContainerModelImpl\n implements\n IKosIdentifiable,\n IKosModelHolder<StorageDeviceModel>,\n IKosDataModel\n{\n id: string;\n private logger: KosContextLogger;\n @kosChild private _models: IKosModelContainer<StorageDeviceModel>;\n constructor(\n modelId: string,\n options: StorageDeviceContainerOptions,\n context: KosCreationContext\n ) {\n this.id = modelId;\n this.logger = context.logger;\n this._models = new KosModelContainer<StorageDeviceModel>({\n parentId: modelId,\n });\n if (options) {\n // Assign options properties here.\n }\n }\n\n getModel(id: string) {\n return this._models.getModel(id);\n }\n get models() {\n return this._models;\n }\n get data() {\n return this._models.data;\n }\n\n addModel(model: StorageDeviceModel) {\n this._models.addModel(model);\n }\n\n removeModel(id: string) {\n this._models.removeModel(id);\n }\n // -------------------LIFECYCLE----------------------------\n\n async init(): Promise<void> {\n this.logger.debug(\n `initializing storage-device-container container ${this.id}`\n );\n }\n get isStorageInserted() {\n return this.data.length > 0;\n }\n\n get volumes() {\n return this.data;\n }\n\n @kosTopicHandler({\n topic: TOPIC_STORAGE_AVAILABILITY,\n websocket: true,\n })\n handleStorageAvailability(devices: StorageDeviceResponse[]) {\n const toRemove = this._models.data.filter(\n (model) => !devices.find((device) => device.id === model.id)\n );\n toRemove.forEach((model) => {\n this.removeModel(model.id);\n });\n\n devices.forEach((device) => {\n const model = this.getModel(device.id);\n if (model) {\n const options: StorageDeviceOptions = {\n ...device,\n kosParentId: this.id,\n };\n model.updateModel(options);\n } else {\n const options: StorageDeviceOptions = {\n ...device,\n kosParentId: this.id,\n };\n const model = StorageDevice.instance(device.id)\n .options(options)\n .build();\n this.addModel(model);\n }\n });\n }\n\n async load(): Promise<void> {\n this.logger.debug(`loading storage-device-container container ${this.id}`);\n const storageDevices = await getStorageDevices();\n storageDevices.forEach((storageDevice) => {\n // Only add partitions or storage devices with no deviceType (for backward compatibility)\n if (storageDevice.deviceType !== \"disk\") {\n const options: StorageDeviceOptions = {\n ...storageDevice,\n kosParentId: this.id,\n };\n const model = StorageDevice.instance(storageDevice.id)\n .options(options)\n .build();\n this.addModel(model);\n }\n });\n }\n}\n","import { SingletonKosModelRegistrationFactory } from \"../../../core\";\nimport type { StorageDeviceContainerModel } from \"./storage-device-container-model\";\nimport {\n MODEL_TYPE,\n StorageDeviceContainerModelImpl,\n} from \"./storage-device-container-model\";\nimport { StorageDevice } from \"./storage-device-registration\";\nimport type { StorageDeviceContainerOptions } from \"./types\";\n\n/**\n * # StorageDeviceContainer\n *\n * The registration bean includes convenience methods for creating and working with StorageDeviceContainerModel instances.\n *\n * ## type\n * The type property is a string that identifies the model type.\n * The type is used to identify the model type in the model registry and to narrow down the model type in type predicates. It's most frequently\n * used when declaring dependencies on models.\n *\n * @example\n * ```typescript\n *\n * @kosDependency({modelType: StorageDeviceContainer.type, id: \"storageDeviceContainerId\"})\n * private storageDeviceContainerModel: StorageDeviceContainerModel;\n * ```\n *\n *\n * ## factory\n *\n * The factory method creates a factory function that can be used to create new StorageDeviceContainerModel instances.\n *\n \n * As this is a singleton model, the factory function accepts the model options as its argument.\n *\n * If a model with the same model type already exists, the factory function will return the existing model. The options will be ignored\n * in this case and the existing model will be returned in its current state.\n *\n * @example\n * ```typescript\n * const model = StorageDeviceContainer.factory({\n * // Add option data\n * });\n * ```\n \n\n *\n * ## predicate\n *\n * [Typescript type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) function that will identify and narrow down a model to a StorageDeviceContainerModel.\n *\n * @example\n * ```typescript\n *\n * const model: IKosDataModel = ...; // some model\n *\n * if (StorageDeviceContainer.predicate(model)) {\n * // if the function evaluates to true, the model is narrowed down to StorageDeviceContainerModel\n * // and the compiler will know that the model has the StorageDeviceContainerModel interface\n * model.updateAvailability(false);\n * }\n * ```\n *\n * ## registration\n *\n * The registration property is an object that can be used to simplify registration of the model with the model registry. The registration object\n * can be spread into the model registration and provides all of the required information to register the model implementation class against the model type.\n *\n *\n * @example\n *\n * In an application registration file you can declare the model registration as follows:\n *\n * **registration.ts**\n * ```typescript\n * import { StorageDeviceContainer } from \"@kosdev-code/kos-dispense-sdk\";\n * ...\n * import { ExtensionManager, IKosRegistry } from \"@kosdev-code/kos-ui-sdk\";\n * export const kosModels: IKosRegistry[\"models\"] = {\n * ...StorageDeviceContainer.registration,\n * };\n * ```\n *\n * ## registration.singleton\n \n * The storageDeviceContainer model is a singleton model. This means that each time the factory function is called , the same instance will be returned.\n * If the model does not yet exist, it will be created passing in the provided options to initialize it.\n *\n * Singleton models don't require an ID as they will use the model type as their ID to guarantee uniqueness throughout the system.\n \n * */\nexport const StorageDeviceContainer = new SingletonKosModelRegistrationFactory<\n StorageDeviceContainerModel,\n StorageDeviceContainerOptions\n>({\n class: StorageDeviceContainerModelImpl,\n type: MODEL_TYPE,\n});\n\nStorageDeviceContainer.addRelatedModel(StorageDevice);\n","/**\n * @internal\n */\nimport {\n KosLog,\n ServiceFactory,\n resolveServiceUrl,\n type KosServiceResponse,\n} from \"../../../../core\";\nimport type { FutureResponse } from \"../../../services/future\";\n\nconst { URL } = resolveServiceUrl(\"USB-UPDATE_SERVICE\");\nconst { getAll, postModel } = ServiceFactory.build({\n basePath: `${URL}/api/kos/update/available`,\n});\n\nconst log = KosLog.createLogger({\n name: \"usb-update-service\",\n group: \"Services\",\n});\n\nexport interface UpdateNote {\n summary: string;\n details: string[];\n}\n\nexport interface UsbUpdateResponse {\n active: boolean;\n blocked: boolean;\n createTime: Date;\n deviceId: string;\n manifestId: string;\n notes: UpdateNote[];\n}\n\n/**\n * @category Service\n * @internal\n * Retrieves the initial usb-update data.\n */\nexport const getAvailableUpdates = async () => {\n log.debug(\"sending GET for usb-update\");\n const response = await getAll<UsbUpdateResponse>({\n urlOverride: `${URL}/api/kos/update/available`,\n });\n\n if (!response?.data || response?.status !== 200) {\n log.error(\"Failed to retrieve usb-update data\", response);\n return [];\n }\n\n return response.data;\n};\n\nexport const installUpdate = async (\n manifestId: string,\n deviceId: string,\n tracker: string\n): Promise<FutureResponse> => {\n const response: KosServiceResponse<FutureResponse> | undefined =\n await postModel({\n model: {\n manifestId,\n deviceId,\n },\n tracker,\n urlOverride: `${URL}/api/kos/update/install`,\n });\n\n if (!response?.data) {\n throw new Error(\"No response from server\");\n }\n\n return response.data;\n};\n","import type {\n IKosDataModel,\n IKosIdentifiable,\n KosContextLogger,\n KosCreationContext,\n PublicModelInterface,\n} from \"../../../core\";\nimport { kosModel } from \"../../../core\";\n\nimport { kosFuture } from \"../../decorators/future-service\";\nimport { FutureHandler } from \"../future/future-aware\";\nimport type {\n FutureAwareContainer,\n FutureContainer,\n} from \"../future/future-types\";\nimport { installUpdate, type UpdateNote } from \"./services\";\nimport type { UsbUpdateOptions } from \"./types\";\n\nexport const MODEL_TYPE = \"usb-update-model\";\n\nexport type UsbUpdateModel = PublicModelInterface<UsbUpdateModelImpl>;\n\n/**\n * USB Update Model\n * @category Model\n */\n@kosModel(MODEL_TYPE)\nexport class UsbUpdateModelImpl\n implements IKosDataModel, IKosIdentifiable, FutureContainer\n{\n id: string;\n active: boolean;\n blocked: boolean;\n createTime: Date;\n deviceId: string;\n manifestId: string;\n notes: UpdateNote[];\n futureHandler: FutureAwareContainer<Record<string, unknown>>;\n\n private logger: KosContextLogger;\n\n constructor(\n modelId: string,\n options: UsbUpdateOptions,\n context: KosCreationContext\n ) {\n this.id = modelId;\n this.logger = context.logger;\n this.active = options.active;\n this.blocked = options.blocked;\n this.createTime = options.createTime;\n this.deviceId = options.deviceId;\n this.manifestId = options.manifestId;\n this.notes = options.notes;\n this.futureHandler = new FutureHandler(this);\n }\n\n updateModel(options: UsbUpdateOptions): void {\n this.active = options.active;\n this.blocked = options.blocked;\n this.createTime = options.createTime;\n this.deviceId = options.deviceId;\n this.manifestId = options.manifestId;\n this.notes = options.notes;\n }\n\n reset() {\n this.futureHandler.removeFuture();\n }\n\n get future() {\n return this.futureHandler.future;\n }\n\n @kosFuture()\n async install(tracker?: string) {\n // should be handed in by the `kosFuture` decorator\n if (!tracker) {\n throw new Error(\"No tracker provided\");\n }\n\n this.logger.info(\n `Installing update for manifest ${this.manifestId} from device ${this.deviceId}`\n );\n\n return installUpdate(this.manifestId, this.deviceId, tracker);\n }\n\n // -------------------LIFECYCLE----------------------------\n\n async init(): Promise<void> {\n this.logger.debug(`initializing usb-update ${this.id}`);\n }\n\n async load(): Promise<void> {\n this.logger.debug(`loading usb-update ${this.id}`);\n }\n}\n","import { KosModelRegistrationFactory } from \"../../../core\";\nimport type { UsbUpdateOptions } from \"./types\";\nimport type { UsbUpdateModel } from \"./usb-update-model\";\nimport { MODEL_TYPE, UsbUpdateModelImpl } from \"./usb-update-model\";\n\n/**\n * # UsbUpdate\n *\n * The registration bean includes convenience methods for creating and working with UsbUpdateModel instances.\n *\n * ## type\n * The type property is a string that identifies the model type.\n * The type is used to identify the model type in the model registry and to narrow down the model type in type predicates. It's most frequently\n * used when declaring dependencies on models.\n *\n * @example\n * ```typescript\n *\n * @kosDependency({modelType: UsbUpdate.type, id: \"usbUpdateId\"})\n * private usbUpdateModel: UsbUpdateModel;\n * ```\n *\n *\n * ## factory\n *\n * The factory method creates a factory function that can be used to create new UsbUpdateModel instances.\n *\n \n * The factory function is a curried function that takes the model id as the first argument and the options as the second argument.\n *\n * If a model with the specified id already exists, the factory function will return the existing model. The options will be ignored\n * in this case and the existing model will be returned in its current state.\n *\n * @example\n * ```typescript\n * const model = UsbUpdate.factory(\"usbUpdateId\")({\n * // Add option data\n * });\n * ```\n \n\n *\n * ## predicate\n *\n * [Typescript type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) function that will identify and narrow down a model to a UsbUpdateModel.\n *\n * @example\n * ```typescript\n *\n * const model: IKosDataModel = ...; // some model\n *\n * if (UsbUpdate.predicate(model)) {\n * // if the function evaluates to true, the model is narrowed down to UsbUpdateModel\n * // and the compiler will know that the model has the UsbUpdateModel interface\n * model.updateAvailability(false);\n * }\n * ```\n *\n * ## registration\n *\n * The registration property is an object that can be used to simplify registration of the model with the model registry. The registration object\n * can be spread into the model registration and provides all of the required information to register the model implementation class against the model type.\n *\n *\n * @example\n *\n * In an application registration file you can declare the model registration as follows:\n *\n * **registration.ts**\n * ```typescript\n * import { UsbUpdate } from \"@kos-ui/project-models\";\n * import { KosModelRegistry } from \"@kosdev-code/kos-dispense-sdk\";\n *\n * import { initKosProvider } from \"@kosdev-code/kos-ui-sdk\";\n *\n * KosModelRegistry.dispense\n * .models()\n * .model(UsbUpdate);\n * ```\n *\n * ## registration.singleton\n \n * The usbUpdate model is NOT a singleton model. This means that each time the factory function is called with a unique ID, a new model instance will be created.\n * If the factory function is called with an ID that already exists, the existing model will be returned.\n \n * */\nexport const UsbUpdate = new KosModelRegistrationFactory<\n UsbUpdateModel,\n UsbUpdateOptions\n>({\n class: UsbUpdateModelImpl,\n type: MODEL_TYPE,\n});\n","import type {\n IKosDataModel,\n IKosIdentifiable,\n IKosModelContainer,\n IKosModelHolder,\n KosContextLogger,\n KosCreationContext,\n PublicModelInterface,\n} from \"../../../core\";\nimport {\n KosModelContainer,\n kosAction,\n kosChild,\n kosDependency,\n kosModel,\n kosModelEffect,\n} from \"../../../core\";\nimport {\n StorageDeviceContainer,\n type StorageDeviceContainerModel,\n} from \"../storage-device\";\nimport { getAvailableUpdates } from \"./services\";\nimport type { UsbUpdateContainerOptions } from \"./types\";\nimport type { UsbUpdateModel } from \"./usb-update-model\";\nimport { UsbUpdate } from \"./usb-update-registration\";\n\nexport const MODEL_TYPE = \"usb-update-container-model\";\n\nexport type UsbUpdateContainerModel =\n PublicModelInterface<UsbUpdateContainerModelImpl>;\n\n@kosModel(MODEL_TYPE)\nexport class UsbUpdateContainerModelImpl\n implements IKosIdentifiable, IKosModelHolder<UsbUpdateModel>, IKosDataModel\n{\n id: string;\n private disposer?: () => void;\n @kosDependency({ modelType: StorageDeviceContainer.type })\n storageService!: StorageDeviceContainerModel;\n\n private _activeUpdate?: UsbUpdateModel;\n private logger: KosContextLogger;\n @kosChild private _models: IKosModelContainer<UsbUpdateModel>;\n\n constructor(\n modelId: string,\n options: UsbUpdateContainerOptions,\n context: KosCreationContext\n ) {\n this.id = modelId;\n this.logger = context.logger;\n this._models = new KosModelContainer<UsbUpdateModel>({ parentId: modelId });\n\n if (options) {\n // Assign options properties here.\n }\n }\n\n getModel(id: string) {\n return this._models.getModel(id);\n }\n\n get models() {\n return this._models;\n }\n\n get data() {\n return this._models.data;\n }\n\n addModel(model: UsbUpdateModel) {\n this._models.addModel(model);\n }\n\n removeModel(id: string) {\n this._models.removeModel(id);\n }\n\n get activeUpdate() {\n return this._activeUpdate;\n }\n\n reset() {\n this.clearActiveUpdate();\n }\n\n clearActiveUpdate() {\n this._activeUpdate = undefined;\n }\n\n updateActiveUpdate(update: UsbUpdateModel) {\n this._activeUpdate = update;\n }\n\n private _isSearching = false;\n private _hasSearched = false;\n\n // -------------------LIFECYCLE----------------------------\n\n get isUsbInserted(): boolean {\n return this.storageService.isStorageInserted;\n }\n\n get hasAvailableUpdates(): boolean {\n return this._models.data.length > 0;\n }\n\n get isSearchingUpdates(): boolean {\n return this._isSearching;\n }\n\n get noAvailableUpdates(): boolean {\n return (\n this.isUsbInserted &&\n this._hasSearched &&\n !this._isSearching &&\n this._models.data.length === 0\n );\n }\n\n async syncAvailableUpdates() {\n kosAction(() => {\n this._isSearching = true;\n });\n\n try {\n const updates = await getAvailableUpdates();\n\n kosAction(() => {\n const allKeys = updates.map(\n (update) => `${update.deviceId}-${update.manifestId}`\n );\n\n this._models.data\n .filter((model) => !allKeys.includes(model.id))\n .forEach((model) => this.removeModel(model.id));\n\n updates.forEach((update) => {\n const modelId = `${update.deviceId}-${update.manifestId}`;\n const model = UsbUpdate.instance(modelId)\n .forceUpdate.options({\n ...update,\n createTime: new Date(update.createTime),\n })\n .build();\n\n this.addModel(model);\n });\n\n if (this.data.length === 1) {\n this.updateActiveUpdate(this.data[0]);\n } else {\n this.clearActiveUpdate();\n }\n });\n } finally {\n kosAction(() => {\n this._isSearching = false;\n this._hasSearched = true;\n });\n }\n }\n\n @kosModelEffect({\n dependencies: (model) => [\n model.isUsbInserted,\n model.storageService.data.length,\n ],\n })\n usbInsertedEffect() {\n if (this.isUsbInserted) {\n this.syncAvailableUpdates();\n } else {\n this._models.clear();\n this.clearActiveUpdate();\n kosAction(() => {\n this._hasSearched = false;\n this._isSearching = false;\n });\n }\n }\n\n async init(): Promise<void> {\n this.logger.debug(`initializing usb-update-container container ${this.id}`);\n }\n\n unload(): void {\n this.disposer?.();\n }\n\n async activate(): Promise<void> {\n this.logger.debug(`activating usb-update-container container ${this.id}`);\n\n await this.syncAvailableUpdates();\n }\n\n async load(): Promise<void> {\n this.logger.debug(`loading usb-update-container container ${this.id}`);\n }\n}\n","import { SingletonKosModelRegistrationFactory } from \"../../../core\";\nimport type { UsbUpdateContainerOptions } from \"./types\";\nimport type { UsbUpdateContainerModel } from \"./usb-update-container-model\";\nimport {\n MODEL_TYPE,\n UsbUpdateContainerModelImpl,\n} from \"./usb-update-container-model\";\nimport { UsbUpdate } from \"./usb-update-registration\";\n\n/**\n * # UsbUpdateContainer\n *\n * The registration bean includes convenience methods for creating and working with UsbUpdateContainerModel instances.\n *\n * ## type\n * The type property is a string that identifies the model type.\n * The type is used to identify the model type in the model registry and to narrow down the model type in type predicates. It's most frequently\n * used when declaring dependencies on models.\n *\n * @example\n * ```typescript\n *\n * @kosDependency({modelType: UsbUpdateContainer.type, id: \"usbUpdateContainerId\"})\n * private usbUpdateContainerModel: UsbUpdateContainerModel;\n * ```\n *\n *\n * ## factory\n *\n * The factory method creates a factory function that can be used to create new UsbUpdateContainerModel instances.\n *\n \n * As this is a singleton model, the factory function accepts the model options as its argument.\n *\n * If a model with the same model type already exists, the factory function will return the existing model. The options will be ignored\n * in this case and the existing model will be returned in its current state.\n *\n * @example\n * ```typescript\n * const model = UsbUpdateContainer.factory({\n * // Add option data\n * });\n * ```\n \n\n *\n * ## predicate\n *\n * [Typescript type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) function that will identify and narrow down a model to a UsbUpdateContainerModel.\n *\n * @example\n * ```typescript\n *\n * const model: IKosDataModel = ...; // some model\n *\n * if (UsbUpdateContainer.predicate(model)) {\n * // if the function evaluates to true, the model is narrowed down to UsbUpdateContainerModel\n * // and the compiler will know that the model has the UsbUpdateContainerModel interface\n * model.updateAvailability(false);\n * }\n * ```\n *\n * ## registration\n *\n * The registration property is an object that can be used to simplify registration of the model with the model registry. The registration object\n * can be spread into the model registration and provides all of the required information to register the model implementation class against the model type.\n *\n *\n * @example\n *\n * In an application registration file you can declare the model registration as follows:\n *\n * **registration.ts**\n * ```typescript\n * import { UsbUpdateContainer } from \"@kosdev-code/kos-dispense-sdk\";\n * ...\n * import { ExtensionManager, IKosRegistry } from \"@kosdev-code/kos-ui-sdk\";\n * export const kosModels: IKosRegistry[\"models\"] = {\n * ...UsbUpdateContainer.registration,\n * };\n * ```\n *\n * ## registration.singleton\n \n * The usbUpdateContainer model is a singleton model. This means that each time the factory function is called , the same instance will be returned.\n * If the model does not yet exist, it will be created passing in the provided options to initialize it.\n *\n * Singleton models don't require an ID as they will use the model type as their ID to guarantee uniqueness throughout the system.\n \n * */\nexport const UsbUpdateContainer = new SingletonKosModelRegistrationFactory<\n UsbUpdateContainerModel,\n UsbUpdateContainerOptions\n>({\n class: UsbUpdateContainerModelImpl,\n type: MODEL_TYPE,\n});\n\nUsbUpdateContainer.addRelatedModel(UsbUpdate);\n","/**\n * @fileoverview Translation service functions for internationalization and localization.\n *\n * This module provides service functions for loading translation data, managing locale\n * descriptors, and handling multi-language content in KOS applications. Supports both\n * static file-based translations and dynamic translation service integration.\n *\n * @module TranslationServices\n */\n\nimport {\n KosLog,\n ServiceFactory,\n getQueryParams,\n resolveServiceUrl,\n} from \"../../../../core\";\n\n/** Base URL for translation service endpoints */\nconst { URL } = resolveServiceUrl(\"TRANSLATION_SERVICE\");\n\n/** Pre-configured service methods for translation operations */\nconst { getOne } = ServiceFactory.build({\n basePath: `${URL}/api/translation`,\n});\n\n/** Logger instance for translation service operations */\nconst log = KosLog.createLogger({\n name: \"translation-service\",\n group: \"Services\",\n});\n\n/**\n * Generic translation data response format.\n *\n * Represents the structure of translation data returned from various translation\n * endpoints, supporting flexible key-value structures for different locales\n * and translation namespaces.\n *\n * @group KOS Model\n * @category i18n\n */\nexport type TranslationResponse = Record<string, any>;\n\n/**\n * Locale descriptor defining translation file location and fallback behavior.\n *\n * Describes how to locate and load translation files for a specific locale,\n * including fallback chains for graceful degradation when translations are\n * missing or incomplete.\n *\n * @group KOS Model\n * @category i18n\n */\nexport interface LocaleDescriptor {\n /** Default locale to use when this locale's translations are unavailable */\n defaultLocale: string;\n /** Path to the translation file for this locale */\n file: string;\n /** Optional array of fallback locales to try in order */\n fallbacks?: string[];\n}\n\n/**\n * Complete localization configuration for organizing translation namespaces.\n *\n * Defines the structure for managing multiple translation namespaces with\n * locale-specific configurations. Enables organized translation management\n * across different features or components of an application.\n *\n * @group KOS Model\n * @category i18n\n */\nexport interface Localization {\n /**\n * Translation namespaces organized by feature or component.\n * Each namespace contains locale configurations and file paths.\n */\n namespaces: {\n [key: string]: {\n /** Locale-specific configuration for this namespace */\n locales: {\n [key: string]: LocaleDescriptor;\n };\n /** Base path for translation files in this namespace */\n basePath: string;\n };\n };\n /** Root path for the localization configuration */\n path: string;\n}\n\n/**\n * Determines the default host URL for translation file requests.\n *\n * Resolves the base URL for loading translation files, checking query parameters\n * for host overrides before falling back to the current window location. Used\n * internally for constructing complete URLs to translation resources.\n *\n * @returns Default host URL for translation requests\n * @internal\n */\nconst getDefaultHost = () => {\n const defaultHost = window.location.origin;\n const params = getQueryParams();\n const hostUrl = (params as any)?.host;\n const result = hostUrl || defaultHost;\n return result;\n};\n\n/**\n * Loads translation data from a specified URL.\n *\n * Fetches translation JSON files from static resources or translation services.\n * Handles network errors gracefully by returning empty objects rather than\n * throwing exceptions, enabling fallback behavior in translation systems.\n *\n * @param url - Relative or absolute URL to the translation file\n * @param root - Optional root URL override (defaults to current window origin)\n * @returns Promise resolving to translation data object\n *\n * @throws {Error} When network request fails unexpectedly (non-200 responses return empty object)\n *\n * @example Load Translation File\n * ```typescript\n * const frenchTranslations = await getTranslations('/assets/locales/fr/common.json');\n * console.log('Welcome message:', frenchTranslations.welcome);\n *\n * const customTranslations = await getTranslations('/api/translations/dashboard', 'https://translations.example.com');\n * ```\n *\n * @group KOS Model\n * @category i18n\n */\nexport const getTranslations = async (url: string, root?: string) => {\n log.debug(`Loading translations from: ${url}`);\n const rootUrl = root ?? getDefaultHost();\n try {\n const response = await fetch(`${rootUrl}${url}`);\n\n if (response.status !== 200) {\n log.warn(`Failed to fetch translations at ${url}: ${response.status}`);\n return {};\n }\n const json = await response.json();\n return json;\n } catch (error) {\n log.error(\"Error fetching translations\", error);\n throw error;\n }\n};\n\n/**\n * Retrieves the system-wide localization configuration descriptor.\n *\n * Fetches the complete localization configuration from the KOS system,\n * including namespace definitions, locale mappings, and file path information.\n * Used for initializing translation containers with proper configuration.\n *\n * @returns Promise resolving to complete localization descriptor\n *\n * @throws {Error} When service request fails or returns non-200 status\n *\n * @example Initialize Translation System\n * ```typescript\n * const localizationConfig = await getLocalizationDescriptor();\n * const translationContainer = TranslationContainer.instance('app-i18n')\n * .options({\n * lang: 'en',\n * descriptor: localizationConfig\n * })\n * .build();\n * ```\n *\n * @group KOS Model\n * @category i18n\n */\nexport const getLocalizationDescriptor = async () => {\n log.debug(\"Getting system localization descriptor\");\n const response = await getOne<Localization>({\n urlOverride: `${URL}/api/system/kos/localization`,\n });\n\n if (response?.status !== 200) {\n throw new Error(\n `Failed to get localization descriptor ${response?.status}`\n );\n }\n return response.data;\n};\n\n/**\n * Creates a context-specific localization descriptor retrieval function.\n *\n * Returns a curried function that fetches localization configuration for a\n * specific context from the KOS system. Useful for creating context-aware\n * translation loaders that can be configured once and used multiple times.\n *\n * @param context - Context identifier for localization configuration\n * @returns Async function that retrieves context-specific localization descriptor\n *\n * @throws {Error} When service request fails or context is not found\n *\n * @example Create Context-Specific Loader\n * ```typescript\n * const getStudioTranslations = getKosLocalizationDescriptor('studio');\n * const studioConfig = await getStudioTranslations();\n *\n * const getDeviceTranslations = getKosLocalizationDescriptor('device');\n * const deviceConfig = await getDeviceTranslations();\n *\n * // Use in translation container initialization\n * const container = TranslationContainer.instance('context-aware')\n * .options({\n * lang: 'es',\n * descriptor: studioConfig\n * })\n * .build();\n * ```\n *\n * @group KOS Model\n * @category i18n\n */\nexport const getKosLocalizationDescriptor = (context: string) => async () => {\n log.debug(`Getting KOS localization descriptor for context: ${context}`);\n const response = await getOne<Record<string, Localization>>({\n urlOverride: `${URL}/api/kos/localization/contexts`,\n });\n\n if (response?.status !== 200) {\n throw new Error(\n `Failed to get KOS localization descriptor ${response?.status}`\n );\n }\n return response.data[context];\n};\n","export const CONTEXT_LANG_RESOLVER = \"langResolver\";\n","/**\n * @ignore\n * @internal\n */\nimport { IReactionDisposer } from \"mobx\";\nimport type {\n IKosDataModel,\n IKosIdentifiable,\n KosContext,\n KosContextLogger,\n KosCreationContext,\n} from \"../../../core\";\nimport {\n KosContextManager,\n kosAction,\n kosModel,\n kosModelEffect,\n kosParentAware,\n} from \"../../../core\";\nimport type { PublicModelInterface } from \"../../../core/types\";\nimport { CONTEXT_LANG_RESOLVER } from \"./constants\";\nimport {\n LocaleDescriptor,\n TranslationResponse,\n getTranslations,\n} from \"./services\";\nimport { TranslationContainerModel } from \"./translation-container-model\";\nimport type { TranslationOptions } from \"./types\";\n\nexport const MODEL_TYPE = \"translation-model\";\ninterface ResolveTranslationOptionsBase<T = string> {\n context?: string;\n defaultValue?: T;\n}\n\ninterface ResolveTranslationsDataOptions<T = string>\n extends ResolveTranslationOptionsBase<T> {\n data: Record<string, any> | string;\n}\n\ntype ResolveTranslationsOptionsMap<T = string> =\n ResolveTranslationOptionsBase<T> &\n Record<string, string | number | boolean | undefined | null>;\nexport type ResolveTranslationOptions<T = string> =\n | ResolveTranslationsDataOptions<T>\n | ResolveTranslationsOptionsMap<T>;\n/**\n * Translation - Individual namespace translations with automatic locale switching and interpolation.\n *\n * The Translation model provides access to localized text for a specific namespace within a KOS\n * application. It handles locale switching, fallback chains, variable interpolation, and context-aware\n * translations for building truly international device interfaces that adapt to user language preferences\n * automatically.\n *\n * ## Key Features\n * - **Namespace Isolation** - Translations organized by functional area or feature\n * - **Automatic Locale Switching** - React to parent container locale changes\n * - **Fallback Chains** - Graceful degradation through locale hierarchy (pt-BR → pt → es → en)\n * - **Variable Interpolation** - Support for both template (`{{variable}}`) and macro (`__variable__`) substitution\n * - **Context-Aware Keys** - Conditional translations based on context (e.g., `title_edit` vs `title`)\n * - **Real-time Updates** - Automatic UI updates when locale or translations change\n * - **Bundle Resolution** - Custom loading strategies for different deployment scenarios\n *\n * ## Variable Interpolation Patterns\n * The model supports two interpolation patterns for dynamic content:\n * - **Template Variables** (`{{variable}}`) - Context-based substitution passed via options\n * - **Macro Variables** (`__variable__`) - Data-based substitution from nested objects\n *\n * ## Fallback Resolution\n * When translations are missing, the system follows a sophisticated fallback chain:\n * 1. **Current locale** (e.g., `pt-BR`)\n * 2. **Parent locale** (e.g., `pt`)\n * 3. **Fallback locales** (configured per locale, e.g., `es`)\n * 4. **Default locale** (typically `en`)\n * 5. **Provided default value** or raw key\n *\n * ## Common Use Cases\n * - **Feature-Specific UI** - Isolated translations for dashboards, settings, alerts\n * - **Form Validation** - Localized error messages with variable interpolation\n * - **Status Displays** - Dynamic content with device state and user context\n * - **Multi-Language Interfaces** - Complete internationalization for global deployments\n * - **Context-Aware Content** - Mode-specific text (create vs edit, online vs offline)\n * - **Rich Text Support** - Integration with Trans component for formatted content\n *\n * @interface\n * @example Basic Usage\n * ```typescript\n * const statusTranslations = Translation.instance('device-status')\n * .options({\n * namespace: 'device-status',\n * currentLocale: 'es',\n * defaultLocale: 'en',\n * descriptor: {\n * 'es': { fallbacks: ['en'] },\n * 'en': { fallbacks: [] }\n * }\n * })\n * .build();\n *\n * // Resolve localized keys with fallback support\n * const title = statusTranslations.resolveKey('title');\n * ```\n *\n * @group KOS Model\n * @category i18n\n * @useDeclaredType\n *\n * @see {@link TranslationOptions} - Configuration options for Translation instances\n * @see {@link TranslationContainerModel} - Container for managing multiple translation namespaces\n * @see {@link useKosTranslation} - React hook for accessing translations in components\n * @see {@link Trans} - React component for rich text translations with markup\n */\nexport type TranslationModel = PublicModelInterface<TranslationModelImpl>;\n\nfunction extractOptions(options: any) {\n const isBasicOptions = typeof options === \"string\";\n const isDataObject = isBasicOptions\n ? false\n : !!options?.data && typeof options?.data !== \"string\";\n const defaultValue = isBasicOptions ? options : options?.defaultValue;\n const context = isBasicOptions ? undefined : options?.context;\n const data = isBasicOptions\n ? undefined\n : isDataObject\n ? options?.data\n : options;\n\n return { isBasicOptions, defaultValue, context, data };\n}\nfunction flattenObject(\n obj: Record<string, any>,\n parentKey = \"\"\n): Record<string, any> {\n return Object.keys(obj).reduce((acc, key) => {\n const newKey = parentKey ? `${parentKey}.${key}` : key;\n if (\n typeof obj[key] === \"object\" &&\n obj[key] !== null &&\n !Array.isArray(obj[key])\n ) {\n const flattenedChild = flattenObject(obj[key], newKey);\n return { ...acc, ...flattenedChild };\n } else {\n return { ...acc, [newKey]: obj[key] };\n }\n }, {});\n}\n/**\n * Overlay one locale's bundle onto the accumulated one.\n *\n * Objects merge key by key, so a locale translating part of a nested group\n * inherits the rest. Arrays REPLACE: a translated list is one unit, and merging\n * two by index would splice a base-locale tail onto a shorter translation.\n * Arrays must be tested before the object branch, since `typeof [] === \"object\"`.\n */\nfunction mergeObjects<T extends Record<string, any>>(\n base: T,\n overlay: Partial<T>\n): T {\n const result: any = { ...base };\n\n for (const key in overlay) {\n if (Object.prototype.hasOwnProperty.call(overlay, key)) {\n if (\n typeof overlay[key] === \"object\" &&\n overlay[key] !== null &&\n !Array.isArray(overlay[key]) &&\n typeof base[key] === \"object\" &&\n base[key] !== null &&\n !Array.isArray(base[key])\n ) {\n result[key] = mergeObjects(base[key], (overlay as any)[key]);\n } else {\n result[key] = overlay[key];\n }\n }\n }\n\n return result;\n}\n\nexport const expandMacros = (text: string, data: Record<string, any>) => {\n const regex = /__(.*?)__/g;\n\n const replacedText = text.replace(\n regex,\n (match, key) =>\n // Use the key to access the corresponding value in the data object\n Object.prototype.hasOwnProperty.call(data || {}, key.trim())\n ? data?.[key.trim()]\n : match // Replace with the value from the data object or keep the original match if no value found\n );\n\n // If the text hasn't changed, return it\n if (replacedText === text) {\n return replacedText;\n }\n if (regex.test(replacedText)) {\n return expandMacros(replacedText, data);\n }\n return replacedText;\n};\n\nexport const replaceText = (\n text: string,\n data: Record<string, any>,\n context?: Record<string, any>\n) => {\n const regex = /{{(.*?)}}/g;\n\n const expandedText = expandMacros(text, data);\n const replacedText = expandedText.replace(regex, (match, key) => {\n const trimmedKey = key.trim();\n\n // First, try to look up the raw key as-is\n if (Object.prototype.hasOwnProperty.call(context || {}, trimmedKey)) {\n return context?.[trimmedKey];\n }\n\n // If not found and key contains a dot, traverse the dotted path\n if (trimmedKey.includes(\".\")) {\n const parts = trimmedKey.split(\".\");\n let value: any = context;\n\n // Fail-fast traversal along the dotted path\n for (const part of parts) {\n if (\n value &&\n typeof value === \"object\" &&\n Object.prototype.hasOwnProperty.call(value, part)\n ) {\n value = value[part];\n } else {\n // Path traversal failed, return original match\n return match;\n }\n }\n\n // Successfully traversed the path\n return value;\n }\n\n // Key not found, return original match\n return match;\n });\n\n const result = expandMacros(replacedText, data);\n return result;\n};\n\nconst splitKey = (currentNamespace: string, _key: string) => {\n if (_key.includes(\":\")) {\n const [namespace, key] = _key.split(\":\");\n return { namespace, key };\n } else {\n return { namespace: currentNamespace, key: _key };\n }\n};\n@kosParentAware()\n@kosModel(MODEL_TYPE)\nexport class TranslationModelImpl implements IKosDataModel, IKosIdentifiable {\n /** Unique identifier for the model instance */\n id: string;\n /** Namespace identifier for translation key isolation */\n namespace: string;\n /** Locale descriptor configuration mapping locales to fallback chains */\n descriptor: Record<string, LocaleDescriptor>;\n /** Default locale to use when no translation is found in fallback chain */\n defaultLocale: string;\n /** Currently active locale for translation resolution */\n currentLocale: string;\n /** Custom bundle resolver for loading translation data */\n bundleResolver?: (\n namespace: string,\n locale: string,\n context?: KosContext\n ) => Promise<TranslationResponse>;\n /** Flattened translation data for efficient key lookup */\n private data: Record<string, any>;\n /** Context logger for debugging and diagnostics */\n private logger: KosContextLogger;\n /** Path resolver function for translation bundle location */\n private resolver: (namespace: string, locale: string) => string;\n /** Reaction disposer for locale change monitoring */\n private disposer?: IReactionDisposer;\n /** Parent translation container reference for namespace resolution */\n private context: TranslationContainerModel;\n /** Base URL for loading translation resources */\n private rootUrl?: string;\n constructor(\n modelId: string,\n options: TranslationOptions,\n context: KosCreationContext\n ) {\n this.id = modelId;\n this.defaultLocale = options.defaultLocale || \"en\";\n this.currentLocale = options.currentLocale || \"en\";\n this.namespace = options.namespace;\n this.descriptor = options.descriptor;\n this.rootUrl = options.rootUrl;\n this.data = {};\n this.resolver =\n options.resolver || context.kosContext.get(CONTEXT_LANG_RESOLVER);\n this.bundleResolver = options.bundleResolver;\n this.logger = context.logger;\n this.context = context.kosContext.parentModel as TranslationContainerModel;\n if (options) {\n // Assign options properties here.\n }\n }\n\n // -------------------LIFECYCLE----------------------------\n\n /**\n * Builds the fallback chain for a given locale.\n * @param locale The locale to get translation fallback chain for\n * @returns Array of locales in priority order\n * @private\n */\n getTranslationLocales(locale: string) {\n const _locale = this.descriptor[locale];\n if (!locale || !_locale) {\n return [this.defaultLocale];\n }\n\n if (!this.defaultLocale && !_locale.fallbacks) {\n return [locale];\n }\n let langs = _locale.fallbacks || [this.defaultLocale];\n if (!langs.includes(locale)) {\n langs = [locale, ...langs];\n }\n return langs;\n }\n /**\n * Loads and merges translations for all locales in the fallback chain.\n * @private\n */\n private async loadTranslations() {\n const reversed = this.getTranslationLocales(this.currentLocale).reverse();\n const allTranslations = reversed.map((lang) => {\n if (this.bundleResolver) {\n const context = KosContextManager.getContext(this.id);\n return this.bundleResolver(this.namespace, lang, context);\n }\n try {\n const translationsPath = this.resolver(this.namespace, lang);\n return getTranslations(translationsPath, this.rootUrl);\n } catch {\n return Promise.resolve({});\n }\n });\n const results = await Promise.allSettled(allTranslations);\n\n kosAction(() => {\n const newData = results.reduce<Record<string, any>>(\n (acc, result, index) => {\n if (result.status === \"fulfilled\") {\n this.logger.debug(`resolved ${reversed[index]}`, result.value);\n if (result.value) {\n acc = mergeObjects(acc, result.value);\n }\n } else {\n this.logger.error(\n `failed to load translation ${this.id} for ${reversed[index]}`\n );\n }\n return acc;\n },\n {}\n );\n this.data = flattenObject(newData);\n });\n }\n /**\n * @internal\n */\n async init(): Promise<void> {\n this.logger.debug(`initializing translation ${this.id}`);\n }\n\n /**\n * Checks if a translation key exists in the current namespace.\n * @param _key Translation key, optionally with namespace prefix\n * @returns True if the key exists\n */\n exists(_key: string) {\n const { namespace, key } = splitKey(this.namespace, _key);\n if (namespace !== this.namespace) {\n const ns = this.context.getModel(namespace);\n if (ns) {\n return ns.exists(key);\n } else {\n return false;\n }\n }\n return !!this.data[key];\n }\n /**\n * Resolves a translation key with optional variable interpolation.\n * @param _key Translation key, optionally with namespace prefix\n * @param options Options for interpolation and fallback\n * @returns Resolved translation string or array\n */\n resolveKey<T = string>(\n _key: string,\n options?: ResolveTranslationOptions<T> | string\n ) {\n if (!_key) {\n this.logger.debug(`key is empty`);\n return \"\";\n }\n const { defaultValue, context, data } = extractOptions(options);\n const { namespace, key } = splitKey(this.namespace, _key);\n const contextKey = `${key}_${context}`;\n if (namespace !== this.namespace) {\n const ns = this.context.getModel(namespace);\n if (ns) {\n return ns.resolveKey(key, options);\n } else {\n return defaultValue ?? key;\n }\n }\n if (context && this.data[contextKey]) {\n const value = this.data[contextKey];\n if (Array.isArray(value)) {\n return value.map((v) => replaceText(v, this.data, data as any));\n }\n return replaceText(this.data[contextKey], this.data, data as any);\n }\n if (this.data[key]) {\n const value = this.data[key];\n if (Array.isArray(value)) {\n return value.map((v) => replaceText(v, this.data, data as any));\n }\n return replaceText(this.data[key], this.data, data as any);\n }\n\n return defaultValue ?? key;\n }\n\n /**\n * @internal\n */\n unload(): void {\n this.logger.debug(`unloading translation ${this.id}`);\n if (this.disposer) {\n this.disposer();\n }\n }\n\n /**\n * @internal\n */\n async load(): Promise<void> {\n this.logger.debug(`loading translation ${this.id}`);\n await this.loadTranslations();\n }\n\n /**\n * @internal\n */\n async ready(): Promise<void> {\n this.logger.debug(`ready translation ${this.id}`);\n }\n\n @kosModelEffect({\n dependencies: (model) => [model.currentLocale],\n })\n async handleCurrentLocaleChange() {\n await this.loadTranslations();\n }\n}\n","import type { KosModelRegistrationBean } from \"../../../core\";\nimport { Kos, isKosModel } from \"../../../core\";\nimport type { TranslationModel } from \"./translation-model\";\nimport { MODEL_TYPE, TranslationModelImpl } from \"./translation-model\";\nimport type { TranslationOptions } from \"./types\";\n\n/**\n * # Translation\n *\n * The registration bean includes convenience methods for creating and working with TranslationModel instances.\n *\n * ## type\n * The type property is a string that identifies the model type.\n * The type is used to identify the model type in the model registry and to narrow down the model type in type predicates. It's most frequently\n * used when declaring dependencies on models.\n *\n * @example\n * ```typescript\n *\n * @kosDependency({modelType: Translation.type, id: \"translationId\"})\n * private translationModel: TranslationModel;\n * ```\n *\n *\n * ## factory\n *\n * The factory method creates a factory function that can be used to create new TranslationModel instances.\n *\n \n * The factory function is a curried function that takes the model id as the first argument and the options as the second argument.\n *\n * If a model with the specified id already exists, the factory function will return the existing model. The options will be ignored\n * in this case and the existing model will be returned in its current state.\n *\n * @example\n * ```typescript\n * const model = Translation.factory(\"translationId\")({\n * // Add option data\n * });\n * ```\n \n\n *\n * ## predicate\n *\n * [Typescript type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) function that will identify and narrow down a model to a TranslationModel.\n *\n * @example\n * ```typescript\n *\n * const model: IKosDataModel = ...; // some model\n *\n * if (Translation.predicate(model)) {\n * // if the function evaluates to true, the model is narrowed down to TranslationModel\n * // and the compiler will know that the model has the TranslationModel interface\n * model.updateAvailability(false);\n * }\n * ```\n *\n * ## registration\n *\n * The registration property is an object that can be used to simplify registration of the model with the model registry. The registration object\n * can be spread into the model registration and provides all of the required information to register the model implementation class against the model type.\n *\n *\n * @example\n *\n * In an application registration file you can declare the model registration as follows:\n *\n * **registration.ts**\n * ```typescript\n * import { Translation } from \"@kosdev-code/kos-dispense-sdk\";\n * ...\n * import { ExtensionManager, IKosRegistry } from \"@kosdev-code/kos-ui-sdk\";\n * export const kosModels: IKosRegistry[\"models\"] = {\n * ...Translation.registration,\n * };\n * ```\n *\n * ## registration.singleton\n \n * The translation model is NOT a singleton model. This means that each time the factory function is called with a unique ID, a new model instance will be created.\n * If the factory function is called with an ID that already exists, the existing model will be returned.\n \n * */\nexport const Translation: Readonly<\n KosModelRegistrationBean<TranslationModel, TranslationOptions>\n> = {\n registration: {\n [MODEL_TYPE]: {\n class: TranslationModelImpl,\n singleton: false,\n },\n },\n type: MODEL_TYPE,\n predicate: isKosModel(MODEL_TYPE),\n factory: Kos.Factory.create<TranslationModel, TranslationOptions>(MODEL_TYPE),\n};\n","/**\n * @internal\n * @ignore\n */\nimport type {\n IKosDataModel,\n IKosIdentifiable,\n IKosModelContainer,\n IKosModelHolder,\n KosContextLogger,\n KosCreationContext,\n ReloadAware,\n} from \"../../../core\";\nimport {\n KosModelContainer,\n kosAction,\n kosChild,\n kosModel,\n whenReady,\n} from \"../../../core\";\n\nimport type { PublicModelInterface } from \"../../../core/types\";\nimport { CONTEXT_LANG_RESOLVER } from \"./constants\";\nimport { Localization } from \"./services\";\nimport type { TranslationModel } from \"./translation-model\";\nimport { Translation } from \"./translation-registration\";\nimport type { TranslationContainerOptions, TranslationOptions } from \"./types\";\n\nexport const MODEL_TYPE = \"translation-container-model\";\n\n/**\n * TranslationContainer - Multi-namespace translation management with automatic locale switching.\n *\n * The TranslationContainer model serves as the central orchestrator for internationalization in KOS\n * applications. It manages multiple translation namespaces, handles global locale switching, and provides\n * namespace resolution with fallback chains. This container enables building sophisticated multi-language\n * interfaces that adapt automatically to user language preferences across all application features.\n *\n * ## Key Features\n * - **Multi-Namespace Management** - Organize translations by feature areas (dashboard, alerts, settings)\n * - **Global Locale Control** - Centralized locale switching affects all contained translation models\n * - **Automatic Discovery** - Dynamic namespace loading and registration as features request translations\n * - **Fallback Resolution** - Sophisticated locale fallback chains for graceful degradation\n * - **Custom Resolvers** - Flexible translation loading strategies for different deployment scenarios\n * - **Reload Capability** - Dynamic translation updates without application restart\n * - **Default Namespace** - Optional primary namespace for application-wide common translations\n *\n * ## Namespace Organization\n * Translation namespaces organize translations by functional areas:\n * - **Feature-Based**: dashboard, device-config, maintenance, alerts\n * - **Component-Based**: forms, modals, navigation, status-displays\n * - **Common**: common, shared, ui-elements for cross-cutting concerns\n *\n * ## Locale Management Architecture\n * The container manages locale switching across all child translation models:\n * 1. **Centralized Control**: Single point for locale changes\n * 2. **Automatic Propagation**: All child models receive locale updates\n * 3. **Reactive Loading**: Translation files loaded automatically on locale switch\n * 4. **Fallback Coordination**: Container coordinates fallback chains across namespaces\n *\n * ## Common Use Cases\n * - **Application Initialization** - Bootstrap internationalization system with locale descriptors\n * - **User Language Switching** - Provide language selector that updates entire application\n * - **Feature Translation Loading** - Dynamic namespace registration as features are accessed\n * - **Multi-Tenant Systems** - Different translation sets for different deployments\n * - **Development Workflows** - Hot-reload translations during development\n * - **Global Device Interfaces** - Centralized management for device control applications\n *\n * @example Basic Usage\n * ```typescript\n * const translationContainer = TranslationContainer.instance('app-translations')\n * .options({\n * lang: 'es',\n * defaultNamespace: 'common',\n * descriptor: {\n * namespaces: {\n * 'common': {\n * basePath: '/assets/locales',\n * locales: {\n * 'en': { file: 'en/common.json', defaultLocale: 'en' },\n * 'es': { file: 'es/common.json', defaultLocale: 'en' }\n * }\n * }\n * }\n * }\n * })\n * .build();\n *\n * // Access translations and switch language\n * const commonTranslations = translationContainer.getModel('common');\n * translationContainer.currentLocale = 'fr';\n * ```\n *\n * @group KOS Model\n * @category i18n\n * @interface\n * @useDeclaredType\n *\n * @see {@link TranslationContainerOptions} - Configuration options for TranslationContainer instances\n * @see {@link TranslationModel} - Individual translation namespace model\n * @see {@link useKosTranslation} - React hook for accessing container translations\n * @see {@link useKosTranslationContext} - React hook for container-level operations\n */\nexport type TranslationContainerModel =\n PublicModelInterface<TranslationContainerModelImpl>;\n\nconst pathJoin = (parts: string[], sep = \"/\") =>\n parts.join(sep).replace(new RegExp(sep + \"{1,}\", \"g\"), sep);\n\nfunction defaultResolver(\n this: TranslationContainerModel,\n namespace: string,\n locale: string\n) {\n const namespaceDescriptor = this.descriptor.namespaces[namespace];\n if (!namespaceDescriptor) {\n throw new Error(\"namespace \" + namespace + \" not found in descriptor\");\n }\n const basePath = namespaceDescriptor.basePath;\n const localePath = namespaceDescriptor.locales[locale].file;\n return pathJoin([basePath, localePath]);\n}\n\n/**\n * @ignore\n * @internal\n */\n@kosModel(MODEL_TYPE)\nexport class TranslationContainerModelImpl\n implements\n IKosIdentifiable,\n IKosModelHolder<TranslationModel>,\n IKosDataModel,\n ReloadAware\n{\n /** Unique identifier for the container model instance */\n id: string;\n /** Currently active locale for all managed translation namespaces */\n lang: string;\n /** Base URL for loading translation resources */\n private rootUrl?: string;\n /** Localization descriptor defining namespace configuration and locale mappings */\n descriptor: Localization;\n /** Optional default namespace identifier for primary application translations */\n private _defaultNamespace?: string;\n /** Path resolver function for constructing translation file URLs */\n private resolver: (\n this: TranslationContainerModel,\n namespace: string,\n locale: string\n ) => string;\n /** Context logger for debugging translation operations */\n private logger: KosContextLogger;\n /** URL for dynamically loading localization descriptors */\n private descriptorUrl?: string;\n /** Array tracking registered namespace identifiers */\n private namespaces: string[] = [];\n /** Container-wide bundle loader, handed to every namespace it resolves */\n private bundleResolver?: TranslationOptions[\"bundleResolver\"];\n /** Container for managing Translation model instances */\n @kosChild private _models: IKosModelContainer<TranslationModel>;\n constructor(\n modelId: string,\n options: TranslationContainerOptions,\n context: KosCreationContext\n ) {\n this.id = modelId;\n this.lang = options.lang || \"en\";\n\n this.descriptor = options.descriptor;\n this._defaultNamespace = options.defaultNamespace;\n this.descriptorUrl = options.descriptorUrl;\n this.rootUrl = options.rootUrl;\n this.resolver = options.resolver || defaultResolver.bind(this);\n this.bundleResolver = options.bundleResolver;\n context.kosContext.set(CONTEXT_LANG_RESOLVER, this.resolver);\n this.logger = context.logger;\n this._models = new KosModelContainer<TranslationModel>({\n parentId: modelId,\n });\n }\n\n set currentLocale(locale: string) {\n this.lang = locale;\n this.models.data.forEach((model) => {\n model.currentLocale = locale;\n });\n }\n get defaultNamespace() {\n return this._defaultNamespace\n ? this.getModel(\"translation-\" + this._defaultNamespace)\n : undefined;\n }\n getModel(id: string) {\n this.logger.debug(\"getting model \" + id);\n return this._models.getModel(\"translation-\" + id);\n }\n get models() {\n return this._models;\n }\n get data() {\n return this._models.data;\n }\n\n async reload() {\n for (const namespace of this.namespaces) {\n const ns = this.resolveNamespace(namespace);\n await whenReady(ns);\n }\n }\n resolveNamespace(namespace: string) {\n const namespaceDescriptor = this.descriptor.namespaces?.[namespace];\n\n if (!namespaceDescriptor) {\n this.logger.warn(\"namespace \" + namespace + \" not found in descriptor\");\n const translation = Translation.factory(\"translation-\" + namespace)({\n kosParentId: this.id,\n namespace,\n rootUrl: this.rootUrl,\n currentLocale: this.lang,\n defaultLocale: this.lang,\n descriptor: {},\n resolver: this.resolver,\n bundleResolver: this.bundleResolver,\n });\n\n this.addModel(translation);\n return translation;\n } else {\n const firstLocale = Object.keys(\n this.descriptor.namespaces[namespace].locales\n )[0];\n const namespaceDefault =\n this.descriptor.namespaces[namespace].locales[firstLocale]\n .defaultLocale;\n const translation = Translation.factory(\"translation-\" + namespace)({\n kosParentId: this.id,\n namespace,\n rootUrl: this.rootUrl,\n currentLocale: this.lang,\n defaultLocale: namespaceDefault,\n descriptor: this.descriptor.namespaces[namespace].locales,\n resolver: this.resolver,\n bundleResolver: this.bundleResolver,\n });\n\n this.addModel(translation);\n if (!this.namespaces.includes(namespace)) {\n kosAction(() => {\n this.namespaces.push(namespace);\n });\n }\n return translation;\n }\n }\n\n addModel(model: TranslationModel) {\n this._models.addModel(model);\n }\n\n removeModel(id: string) {\n this._models.removeModel(id);\n }\n // -------------------LIFECYCLE----------------------------\n\n /**\n * @internal\n */\n async init(): Promise<void> {\n this.logger.debug(\n \"initializing translation-container container \" + this.id\n );\n }\n\n /**\n * @internal\n */\n async load(): Promise<void> {\n this.logger.debug(\"loading translation-container container \" + this.id);\n }\n}\n","import type { SingletonKosModelRegistrationBean } from \"../../../core\";\nimport { Kos, isKosModel } from \"../../../core\";\nimport type { TranslationContainerModel } from \"./translation-container-model\";\nimport {\n MODEL_TYPE,\n TranslationContainerModelImpl,\n} from \"./translation-container-model\";\nimport type { TranslationContainerOptions } from \"./types\";\n\n/**\n * # TranslationContainer\n *\n * The registration bean includes convenience methods for creating and working with TranslationContainerModel instances.\n *\n * ## type\n * The type property is a string that identifies the model type.\n * The type is used to identify the model type in the model registry and to narrow down the model type in type predicates. It's most frequently\n * used when declaring dependencies on models.\n *\n * @example\n * ```typescript\n *\n * @kosDependency({modelType: TranslationContainer.type, id: \"translationContainerId\"})\n * private translationContainerModel: TranslationContainerModel;\n * ```\n *\n *\n * ## factory\n *\n * The factory method creates a factory function that can be used to create new TranslationContainerModel instances.\n *\n \n * As this is a singleton model, the factory function accepts the model options as its argument.\n *\n * If a model with the same model type already exists, the factory function will return the existing model. The options will be ignored\n * in this case and the existing model will be returned in its current state.\n *\n * @example\n * ```typescript\n * const model = TranslationContainer.factory({\n * // Add option data\n * });\n * ```\n \n\n *\n * ## predicate\n *\n * [Typescript type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) function that will identify and narrow down a model to a TranslationContainerModel.\n *\n * @example\n * ```typescript\n *\n * const model: IKosDataModel = ...; // some model\n *\n * if (TranslationContainer.predicate(model)) {\n * // if the function evaluates to true, the model is narrowed down to TranslationContainerModel\n * // and the compiler will know that the model has the TranslationContainerModel interface\n * model.updateAvailability(false);\n * }\n * ```\n *\n * ## registration\n *\n * The registration property is an object that can be used to simplify registration of the model with the model registry. The registration object\n * can be spread into the model registration and provides all of the required information to register the model implementation class against the model type.\n *\n *\n * @example\n *\n * In an application registration file you can declare the model registration as follows:\n *\n * **registration.ts**\n * ```typescript\n * import { TranslationContainer } from \"@kosdev-code/kos-dispense-sdk\";\n * ...\n * import { ExtensionManager, IKosRegistry } from \"@kosdev-code/kos-ui-sdk\";\n * export const kosModels: IKosRegistry[\"models\"] = {\n * ...TranslationContainer.registration,\n * };\n * ```\n *\n * ## registration.singleton\n \n * The translationContainer model is a singleton model. This means that each time the factory function is called , the same instance will be returned.\n * If the model does not yet exist, it will be created passing in the provided options to initialize it.\n *\n * Singleton models don't require an ID as they will use the model type as their ID to guarantee uniqueness throughout the system.\n * @group KOS Model\n * @category i18n\n * */\nexport const TranslationContainer: Readonly<\n SingletonKosModelRegistrationBean<\n TranslationContainerModel,\n TranslationContainerOptions\n >\n> = {\n registration: {\n [MODEL_TYPE]: {\n class: TranslationContainerModelImpl,\n singleton: true,\n },\n },\n type: MODEL_TYPE,\n predicate: isKosModel(MODEL_TYPE),\n factory: Kos.Singleton.create<\n TranslationContainerModel,\n TranslationContainerOptions\n >(MODEL_TYPE),\n};\n","import { modelFactory } from \"../../../core\";\nimport type { IWsEvent, WsEventOptions } from \"./types\";\nexport const WS_EVENT_TYPE = \"kos-ws-event\";\nexport const WsEventFactory = modelFactory<IWsEvent, WsEventOptions>(\n WS_EVENT_TYPE\n);\n","import { observable } from \"mobx\";\nimport { KosWsEvents, type ApiCallback } from \"../../../common\";\nimport {\n KosLog,\n kosModel,\n kosTopicHandler,\n type KosInternalEvent,\n} from \"../../../core\";\nimport type { EventData, IWsEvent } from \"./types\";\nimport { WsEventFactory } from \"./ws-event-factory\";\n\nconst stringify = ({ headers, body }: KosInternalEvent) => {\n const headText = Object.entries(headers)\n .map(([key, value]) => `${key}:${value}`)\n .join(\"\\\\n\");\n return headText + \"\\\\n\\\\n\" + body;\n};\n@kosModel(WsEventFactory.type)\nexport class WsEventModel implements IWsEvent {\n id: string;\n events: Map<string, EventData>;\n private _topicMap: Map<string, number>;\n constructor(modelId: string) {\n this.id = modelId;\n this.events = observable.map(new Map<string, EventData>());\n\n this._topicMap = new Map<string, number>();\n }\n\n get websocketEvents() {\n return Array.from(this.events.values());\n }\n\n @kosTopicHandler({\n topic: [KosWsEvents.SEND],\n })\n handleSendEvent(\n _data: KosInternalEvent,\n payload: ApiCallback<KosInternalEvent>\n ) {\n this.processEvent(payload, true);\n }\n\n @kosTopicHandler({\n topic: [KosWsEvents.RECEIVED],\n })\n handleReceiveEvent(\n _data: KosInternalEvent,\n payload: ApiCallback<KosInternalEvent>\n ) {\n this.processEvent(payload);\n }\n\n processEvent(data: ApiCallback<KosInternalEvent>, isSend = false) {\n KosLog.debug(\"kos event received\");\n const { body, headers } = data.body;\n\n const isUnique = headers[\"request-id\"] || headers[\"response-id\"];\n const msgId =\n headers[\"request-id\"] ||\n headers[\"response-id\"] ||\n headers[\"topic\"] ||\n headers[\"type\"];\n\n if (msgId) {\n let rawKey = msgId;\n if (!isUnique) {\n const count = this._topicMap.get(msgId) || 0;\n\n rawKey = `${rawKey}-${count + 1}`;\n this._topicMap.set(msgId, count + 1);\n } else {\n const dir = isSend ? \"send\" : \"receive\";\n rawKey = `${rawKey}-${dir}`;\n }\n const rawData: EventData = {\n msgId: rawKey,\n content: body,\n headers,\n timestamp: Date.now(),\n raw: stringify({ headers, body }),\n direction: isSend ? \"send\" : \"receive\",\n mocked: !!headers[\"mocked\"],\n };\n this.events.set(rawKey, rawData);\n KosLog.debug(`logged ${this.events.size} events`);\n }\n }\n}\n","import { FutureFactory, FutureModel } from \"./models/future\";\nimport {\n FutureContainerFactory,\n FutureContainerModel,\n} from \"./models/future-container\";\nimport { KosTime } from \"./models/kos-time/kos-time-registration\";\nimport { StateBean } from \"./models/state-bean/state-bean-registration\";\nimport { StateProp } from \"./models/state-prop/state-prop-registration\";\n// ------- PREPEND IMPORTS --------\n\nimport { KosConfigPropertySpec } from \"./models/config-bean-prop\";\nimport { RegionInfo } from \"./models/region-info\";\nimport { Translation, TranslationContainer } from \"./models/translation\";\nimport { TroubleContainer } from \"./models/trouble-container\";\n\nimport type { IKosRegistry } from \"../core/core/types\";\nimport { WsEventModel } from \"./models/ws-event\";\nimport { WsEventFactory } from \"./models/ws-event/ws-event-factory\";\n\nconst getKosModel = () => {\n const kosModels: IKosRegistry[\"models\"] = {\n [FutureFactory.type]: {\n class: FutureModel,\n },\n [FutureContainerFactory.type]: {\n class: FutureContainerModel,\n singleton: true,\n },\n ...RegionInfo.registration,\n\n ...KosConfigPropertySpec.registration,\n\n ...TroubleContainer.registration,\n ...Translation.registration,\n ...TranslationContainer.registration,\n\n [WsEventFactory.type]: {\n class: WsEventModel,\n singleton: true,\n },\n ...StateBean.registration,\n ...StateProp.registration,\n ...KosTime.registration,\n };\n return { ...kosModels };\n};\n\nexport const CoreModels = getKosModel();\nexport const Registry: IKosRegistry = {\n models: CoreModels,\n preloadModels: [],\n};\n","import {\n RegistrationManager,\n registerKosModel,\n registerLegacyModel,\n type RegistrationResult,\n} from \"../../core\";\nimport { KosLogManager, LogStreamContainer } from \"../models\";\nimport { BrowserRouter } from \"../models/browser-router\";\nimport { CanvasDispatcher } from \"../models/canvas-dispatcher\";\nimport { CanvasRenderer } from \"../models/canvas-renderer\";\nimport { ConfigBean } from \"../models/config-bean/config-bean-model\";\nimport { Device } from \"../models/device\";\nimport { KeyValue } from \"../models/key-value\";\nimport { KosExpressionEvaluator } from \"../models/kos-expression-evaluator\";\nimport { NetworkInterfaceContainer } from \"../models/network-interface\";\nimport { Ota } from \"../models/ota/ota-registration\";\nimport { SoftwareInfo } from \"../models/software-info/software-info-registration\";\nimport { StorageDeviceContainer } from \"../models/storage-device\";\nimport { TroubleContainer } from \"../models/trouble-container\";\nimport { Trouble } from \"../models/trouble/trouble-registration\";\nimport { UsbUpdateContainer } from \"../models/usb-update\";\nimport { CoreModels } from \"../registration\";\n\nconst PRELOAD = true;\nexport const registerCoreModels =\n <R>(root: R) =>\n () => {\n const coreModels = CoreModels;\n registerKosModel(KosModelRegistry)(Trouble)\n .model(TroubleContainer)\n .model(StorageDeviceContainer)\n .model(UsbUpdateContainer)\n .model(Device)\n .model(Ota)\n .model(ConfigBean)\n .model(SoftwareInfo)\n .model(KeyValue)\n .model(NetworkInterfaceContainer)\n .model(CanvasDispatcher)\n .model(CanvasRenderer)\n .model(KosExpressionEvaluator)\n .model(BrowserRouter, PRELOAD)\n .model(LogStreamContainer)\n .model(KosLogManager);\n\n Object.keys(coreModels).forEach((key) => {\n const model = coreModels[key];\n registerLegacyModel(KosModelRegistry)(key, model);\n });\n\n return {\n preload: RegistrationManager.model.preloadModel(root),\n model: RegistrationManager.model.register(root),\n companion: RegistrationManager.companion.register(root),\n legacy: RegistrationManager.model.registerLegacyModel(root),\n };\n };\n\ntype ModelRegistry<R> = {\n core: { models: () => RegistrationResult<R> };\n preload: ReturnType<typeof RegistrationManager.model.preloadModel>;\n model: ReturnType<typeof RegistrationManager.model.register>;\n companion: ReturnType<typeof RegistrationManager.companion.register>;\n};\n\nconst _KosModelRegistry = {};\n\n(_KosModelRegistry as any).core = {\n models: registerCoreModels(_KosModelRegistry),\n};\n(_KosModelRegistry as any).preload =\n RegistrationManager.model.preloadModel(_KosModelRegistry);\n(_KosModelRegistry as any).model =\n RegistrationManager.model.register(_KosModelRegistry);\n(_KosModelRegistry as any).companion =\n RegistrationManager.companion.register(_KosModelRegistry);\n(_KosModelRegistry as any).legacy =\n RegistrationManager.model.registerLegacyModel(_KosModelRegistry);\n\ntype KosModelRegistryType = ModelRegistry<typeof _KosModelRegistry>;\n\nconst KosModelRegistry: KosModelRegistryType = _KosModelRegistry as any;\n\nexport { KosModelRegistry };\n","/// <reference types=\"@types/node/timers\"/>\n/**\n * @module TimerManager\n * @description\n * The TimerManager module provides functionality for managing timers and executing actions at specific intervals.\n * It includes a `KosTimer` class for individual timers and a set of utility functions to interact with timers.\n *\n * @example\n * // Create a timer with a 60-second timeout and default actions\n * const timer = TimerManager.createTimer(\"myTimer\", 60, [{ name: \"customAction\" }]);\n *\n * // Start the timer\n * TimerManager.startTimer(\"myTimer\");\n *\n * // Add a timeout action to the timer\n * TimerManager.addTimeoutAction(\"myTimer\", { name: \"newAction\", remainingTime: 30 });\n *\n * // Reset the timer\n * TimerManager.resetTimer(\"myTimer\");\n */\n\nimport { EventBus } from \"../../common\";\nimport { KosLog, kosAutoEffect } from \"../../core\";\nimport type { KosConfigProperty } from \"../models\";\n\n/**\n * Event name for timer-related events.\n */\nexport const TIMER_EVENT = `/kos-timer-event`;\n\n/**\n * Event name for timer-tick events.\n */\nexport const TOPIC_TIMER_TICK_EVENT = `/kos-timer-event/tick`;\n\n/**\n * Default action name for timer end event.\n */\nexport const TIMER_END = \"defaultTimerEnd\";\n\n/**\n * Represents a timer event.\n */\nexport interface TimerEvent {\n name: string;\n action: string;\n remainingTime: number;\n}\n\n/**\n * Represents a function that can be executed as a timer action.\n */\ntype TimerActionFn = (name: string, timeRemaining: number) => void;\n\n/**\n * Represents a timer action configuration.\n */\nexport interface TimerAction {\n name: string;\n action?: TimerActionFn;\n remainingTime?: number;\n singleUse?: boolean;\n}\n\nconst log = KosLog.createLogger({ name: \"timer-manager\" });\n\nconst isConfigProperty = (\n value: number | KosConfigProperty<number>\n): value is KosConfigProperty<number> =>\n (value as KosConfigProperty<number>).updateProperty !== undefined;\n/**\n * Manages the behavior of a timer.\n */\nexport class KosTimer {\n private name: string;\n private timeout: number;\n private timer?: NodeJS.Timeout;\n private state: \"inactive\" | \"active\" | \"paused\" | \"complete\" = \"inactive\";\n private decrementValue = 1;\n private remainingTime: number;\n private timeoutActions: Map<number, TimerAction[]> = new Map();\n\n get id() {\n return this.name;\n }\n /**\n * Creates a new timer.\n * @param name - The name of the timer.\n * @param timeout - The duration (in seconds) of the timer.\n * @param defaultActions - Optional default timer actions.\n */\n constructor(\n name: string,\n timeout: number | KosConfigProperty<number>,\n defaultActions?: TimerAction[]\n ) {\n this.name = name;\n\n const timeoutValue =\n typeof timeout === \"number\" ? timeout : timeout.value || 60;\n this.timeout = timeoutValue;\n this.state = \"inactive\";\n\n this.remainingTime = timeoutValue;\n\n if (isConfigProperty(timeout)) {\n kosAutoEffect(() => {\n KosLog.info(\n `Updating config value timer ${name} with new timeout value ${timeout.value}`\n );\n const newValue = timeout.value || 60;\n this.updateTimeout(newValue);\n });\n }\n // Add a default timeout action for timer end event.\n this.addTimeoutAction({\n name: TIMER_END,\n });\n\n if (defaultActions) {\n // Add any provided default actions.\n defaultActions.forEach((action) => {\n this.addTimeoutAction(action);\n });\n }\n }\n\n /**\n * Starts the timer.\n */\n public start() {\n if (this.state === \"active\") {\n log.debug(`Timer ${this.name} already started`);\n return;\n }\n\n if (this.state === \"inactive\" || this.state === \"paused\") {\n this.state = \"active\";\n this.timer = setInterval(() => this.updateTimer(), 1000);\n }\n }\n\n /**\n * Pauses the timer.\n */\n public pause() {\n if (this.timer) {\n log.debug(`Pausing timer ${this.name}`);\n this.state = \"paused\";\n clearInterval(this.timer);\n }\n }\n\n /**\n * Restarts the timer. The timer will continue to run from its initial state.\n */\n public restart() {\n this.pause();\n this.remainingTime = this.timeout;\n this.start();\n }\n /**\n * Resets the timer to its initial state. The timer will be stopped and reset to its initial state.\n * The timer will need to be started again to continue running.\n */\n public reset() {\n this.pause();\n this.remainingTime = this.timeout;\n this.state = \"inactive\";\n }\n\n public updateTimeout(timeout: number) {\n this.timeout = timeout;\n this.restart();\n }\n\n /**\n * Adds a timeout action to the timer.\n * @param timerAction - The timer action configuration to add.\n */\n public addTimeoutAction(timerAction: TimerAction) {\n const time = timerAction.remainingTime ?? 0;\n\n if (!this.timeoutActions.has(time)) {\n this.timeoutActions.set(time, []);\n }\n const name = timerAction.name;\n const existingAction = this.timeoutActions\n .get(time)!\n .find((action) => action.name === name);\n if (existingAction) {\n existingAction.action = timerAction.action;\n } else {\n this.timeoutActions.get(time)!.push(timerAction);\n }\n }\n\n /**\n * Removes a timeout action from the timer by action name.\n * @param actionName - The name of the action to remove.\n */\n public removeTimeoutAction(actionName: string) {\n for (const [time, actions] of this.timeoutActions.entries()) {\n const updatedActions = actions.filter(\n (action) => action.name !== actionName\n );\n\n if (updatedActions.length === 0) {\n this.timeoutActions.delete(time);\n } else {\n this.timeoutActions.set(time, updatedActions);\n }\n }\n }\n\n /**\n * Updates the timer's remaining time and executes timeout actions.\n */\n private updateTimer() {\n this.remainingTime =\n Math.round((this.remainingTime - this.decrementValue) * 100) / 100;\n\n if (this.remainingTime <= 0) {\n if (this.state === \"active\") {\n this.executeActions(0);\n }\n\n this.pause();\n return;\n }\n\n if (this.state === \"active\") {\n this.executeActions(this.remainingTime);\n }\n }\n\n /**\n * Executes timeout actions at the specified time.\n * @param time - The remaining time at which to execute actions.\n */\n private executeActions(time: number) {\n if (this.timeoutActions.has(time)) {\n this.timeoutActions.get(time)!.forEach((timerAction) => {\n log.debug(`Executing timer action ${timerAction.name} at ${time}`);\n timerAction.action?.(timerAction.name, time);\n this.notifyTimeoutAction(timerAction);\n if (timerAction.singleUse) {\n log.info(\n `${this.name} Removing single-use action ${timerAction.name}`\n );\n this.removeTimeoutAction(timerAction.name);\n }\n });\n }\n this.notifyTick();\n }\n\n private notifyTick() {\n EventBus.publish(`${TOPIC_TIMER_TICK_EVENT}/${this.name}`, {\n name: this.name,\n remainingTime: this.remainingTime,\n });\n }\n /**\n * Notifies a timeout action through the EventBus.\n * @param action - The timeout action to notify.\n */\n private notifyTimeoutAction(action: TimerAction) {\n EventBus.publish(TIMER_EVENT, {\n name: this.name,\n action: action.name,\n remainingTime: this.remainingTime,\n });\n }\n}\n\n// A map to store timer instances.\nconst timers = new Map<string, KosTimer>();\n\n/**\n * Executes a function on a timer with the specified name.\n * @param name - The name of the timer to operate on.\n * @param action - The function to execute on the timer.\n */\nconst executeOnTimer = (name: string, action: (timer: KosTimer) => void) => {\n const timer = timers.get(name);\n if (!timer) {\n log.error(`Timer ${name} not found`);\n return;\n }\n action(timer);\n};\n\n/**\n * The TimerManager provides utility functions to manage timers.\n */\nexport const TimerManager = {\n /**\n * Creates a new timer with a timeout relative to the current date.\n * @param name - The name of the timer\n * @param date - The date to set the timer to\n * @param defaultActions - Optional default timer actions.\n * @returns the time instance\n */\n createRelativeTimer(\n name: string,\n date: Date,\n defaultActions?: TimerAction[]\n ) {\n const now = new Date();\n const timeout = Math.round((date.getTime() - now.getTime()) / 1000);\n return this.createTimer(name, timeout, defaultActions);\n },\n /**\n * Creates a new timer or retrieves an existing one by name.\n * @param name - The name of the timer.\n * @param timeout - The duration (in seconds) of the timer (default: 60 seconds).\n * @param defaultActions - Optional default timer actions.\n * @returns The timer instance.\n */\n createTimer(name: string, timeout = 60, defaultActions?: TimerAction[]) {\n if (timers.has(name)) {\n return timers.get(name);\n }\n const timer = new KosTimer(name, timeout, defaultActions);\n timers.set(name, timer);\n return timer;\n },\n\n /**\n * Gets an existing timer by name.\n * @param name - The name of the timer.\n * @returns The timer instance or `undefined` if not found.\n */\n getTimer(name: string) {\n return timers.get(name);\n },\n\n /**\n * Clears (pauses) an existing timer by name.\n * @param name - The name of the timer.\n */\n clearTimer(name: string) {\n executeOnTimer(name, (timer) => timer.pause());\n },\n\n /**\n * Restarts an existing timer to its initial state by name. The timer will continue to run from its initial state.\n * @param name - The name of the timer.\n */\n restartTimer(name: string) {\n executeOnTimer(name, (timer) => timer.restart());\n },\n\n /**\n * Resets an existing timer to its initial state by name.\n * @param name - The name of the timer.\n */\n resetTimer(name: string) {\n executeOnTimer(name, (timer) => timer.reset());\n },\n\n /**\n * Adds a timeout action to an existing timer by name.\n * @param name - The name of the timer.\n * @param action - The timer action configuration to add.\n */\n addTimeoutAction(name: string, action: TimerAction) {\n executeOnTimer(name, (timer) => timer.addTimeoutAction(action));\n },\n\n /**\n * Removes a timeout action from an existing timer by name and action name.\n * @param name - The name of the timer.\n * @param actionName - The name of the action to remove.\n */\n removeTimeoutAction(name: string, actionName: string) {\n executeOnTimer(name, (timer) => timer.removeTimeoutAction(actionName));\n },\n\n /**\n * Starts an existing timer by name.\n * @param name - The name of the timer.\n */\n startTimer(name: string) {\n executeOnTimer(name, (timer) => timer.start());\n },\n};\n","/**\n * @internal\n */\n// eslint-disable-next-line @nx/enforce-module-boundaries\nimport { FetchError, KosLog } from \"../../../../core\";\nimport { api, type BaseResponseType } from \"../../../utils\";\nimport { createCancellableService } from \"../../../utils/cancellable-service\";\nimport { getKosConnectionId } from \"../../../utils/get-kos-connection-id\";\n\nconst log = KosLog.createLogger({\n name: \"software-info-service\",\n group: \"Services\",\n});\nexport interface Nodes {\n [key: string]: NodeSoftwareInfo[]; // Use an index signature for dynamic keys\n}\n\nexport interface NodeSoftwareInfo {\n node: string;\n artifacts: SoftwareInfoDescriptorFragment[];\n}\n\nexport interface SoftwareInfoDescriptorFragment {\n name: string;\n group: string;\n version: string;\n}\n\nexport type DeviceSoftwareInfoResponse = BaseResponseType<\n \"/api/kos/manifest/info\",\n \"get\"\n>;\n\n/**\n * @category Service\n * @internal\n * Retrieves the initial software-info data.\n * @param signal - Optional AbortSignal to cancel the request\n */\nexport const getSoftwareInfos = async (\n signal?: AbortSignal\n): Promise<DeviceSoftwareInfoResponse> => {\n const destinationAddress = getKosConnectionId();\n log.debug(\"sending GET for software-info\");\n const [error, response] = await api.get(\"/api/kos/manifest/info\", undefined, {\n signal,\n destinationAddress,\n });\n\n if (!response) {\n // Check if it was aborted\n if (signal?.aborted) {\n log.debug(\"Request was aborted\");\n throw new FetchError(\"Request was aborted\");\n }\n log.error(\"Failed to fetch software-info\", error);\n throw new FetchError(\"Failed to fetch software-info\");\n }\n\n return response as DeviceSoftwareInfoResponse;\n};\n\n/**\n * Cancellable version of getSoftwareInfos\n * @example\n * ```typescript\n * // In your model\n * const data = await getSoftwareInfosWithCancel();\n *\n * // Cancel if needed\n * getSoftwareInfosWithCancel.cancel();\n *\n * // Check if active\n * if (getSoftwareInfosWithCancel.isActive()) {\n * console.log('Request in progress');\n * }\n * ```\n */\nexport const getSoftwareInfosWithCancel =\n createCancellableService(getSoftwareInfos);\n","import { kosAction } from \"../../../core\";\nimport { kosModel } from \"../../../core/core/decorators\";\nimport type {\n IKosDataModel,\n KosContextLogger,\n KosCreationContext,\n} from \"../../../core/core/kosModel\";\nimport type { PublicModelInterface } from \"../../../core/types\";\nimport { FetchError } from \"../../../core/util/service-factory\";\nimport { getSoftwareInfos } from \"./services\";\nimport type { ArtifactsType, NodeInfoType, SoftwareInfoOptions } from \"./types\";\n\nexport const MODEL_TYPE = \"software-info-model\";\n\n/**\n * SoftwareInfo - System software version and artifact management for KOS devices.\n *\n * The SoftwareInfo model provides comprehensive visibility into installed software versions,\n * artifacts, and system components across all nodes in a KOS device. This model is essential\n * for applications that need to display system information, perform version checks, or\n * manage software compatibility and updates.\n *\n * ## Key Features\n * - **Node-Based Architecture** - Track software information across multiple device nodes\n * - **Artifact Management** - Complete visibility into installed software components and versions\n * - **Version Tracking** - Monitor KOS framework versions and application artifacts\n * - **Group Organization** - Automatic categorization of artifacts by functional groups\n * - **System Overview** - Comprehensive system software inventory and version reporting\n * - **Compatibility Checking** - Version information for dependency and compatibility validation\n *\n * ## Data Structure\n * The model organizes software information hierarchically:\n * - **Nodes** - Individual system nodes (primary, secondary, etc.)\n * - **Artifacts** - Software components installed on each node\n * - **Groups** - Logical grouping of related artifacts (core, ui, services, etc.)\n * - **Versions** - Specific version information for each artifact\n *\n * ## Common Use Cases\n * - **System Information Display** - Show installed software versions to users and administrators\n * - **Version Compatibility** - Check software versions before updates or feature activation\n * - **Support Diagnostics** - Provide detailed software information for troubleshooting\n * - **Update Planning** - Assess current software state before planning updates\n * - **Inventory Management** - Track and report on installed software components\n *\n * @interface\n * @example Basic Usage\n * ```typescript\n * const softwareInfo = SoftwareInfo.instance('system-info').build();\n *\n * // Access system software information across nodes\n * const nodes = softwareInfo.nodes;\n * nodes?.forEach(node => {\n * console.log(`Node ${node.nodeName}: KOS ${node.kosVersion}`);\n * });\n * ```\n *\n * @group KOS Model\n * @category System Integration\n * @useDeclaredType\n *\n * @see {@link SoftwareInfoOptions} - Configuration options for SoftwareInfo model\n * @see {@link NodeInfoType} - Individual node software information\n * @see {@link ArtifactsType} - Software artifact information\n * @see {@link getSoftwareInfos} - Service function for loading software data\n */\nexport type SoftwareInfoModel = PublicModelInterface<SoftwareInfoModelImpl>;\n\n/**\n * @ignore\n * @internal\n */\n@kosModel(MODEL_TYPE)\nexport class SoftwareInfoModelImpl implements IKosDataModel {\n /** Unique identifier for the model instance */\n id: string;\n private logger: KosContextLogger;\n\n /** Software information for all device nodes, including KOS versions and artifacts */\n nodes: NodeInfoType[] | undefined;\n constructor(\n modelId: string,\n _options: SoftwareInfoOptions,\n context: KosCreationContext\n ) {\n this.id = modelId;\n this.logger = context.logger;\n this.nodes = [];\n }\n\n // -------------------LIFECYCLE----------------------------\n\n /**\n * @internal\n */\n async init(): Promise<void> {\n this.logger.debug(`initializing software-info ${this.id}`);\n }\n\n /**\n * Groups artifacts by a specified property for organization.\n * @param arr Array of artifacts to group\n * @param property Property to group by\n * @returns Grouped artifacts organized by the specified property\n * @private\n */\n groupBy(arr: ArtifactsType[], property: keyof ArtifactsType) {\n return arr.reduce(\n (acc: Record<string, ArtifactsType[]>, cur: ArtifactsType) => {\n acc[cur[property]] = [...(acc[cur[property]] || []), cur];\n return acc;\n },\n {}\n );\n }\n\n /**\n * @internal\n */\n async load(): Promise<void> {\n this.logger.debug(`loading software-info ${this.id}`);\n try {\n const response = await getSoftwareInfos();\n const nodes = response?.nodes || {};\n kosAction(() => {\n const nodeList = Object.keys(nodes).map((el: string) => nodes[el][0]);\n\n const updatedList = nodeList.map((el) => {\n return {\n nodeName: el.nodeType,\n kosVersion: el.kosVersion,\n group: this.groupBy(el.artifacts, \"group\"),\n };\n });\n this.nodes = updatedList;\n });\n } catch (error) {\n if (error instanceof FetchError) {\n this.logger.error(`Failed to fetch software-info`, error);\n }\n }\n }\n}\n","import { Kos } from \"../../../core/core/kos-model-factory\";\nimport type { KosModelRegistrationBean } from \"../../../core/types\";\nimport { isKosModel } from \"../../../core/util/kos-model-utils\";\nimport { MODEL_TYPE, SoftwareInfoModelImpl } from \"./software-info-model\";\nimport type { SoftwareInfoModel, SoftwareInfoOptions } from \"./types\";\n\n/**\n * # SoftwareInfo\n *\n * The registration bean includes convenience methods for creating and working with SoftwareInfoModel instances.\n *\n * ## type\n * The type property is a string that identifies the model type.\n * The type is used to identify the model type in the model registry and to narrow down the model type in type predicates. It's most frequently\n * used when declaring dependencies on models.\n *\n * @example\n * ```typescript\n *\n * @kosDependency({modelType: SoftwareInfo.type, id: \"softwareInfoId\"})\n * private softwareInfoModel: SoftwareInfoModel;\n * ```\n *\n *\n * ## factory\n *\n * The factory method creates a factory function that can be used to create new SoftwareInfoModel instances.\n *\n \n * The factory function is a curried function that takes the model id as the first argument and the options as the second argument.\n *\n * If a model with the specified id already exists, the factory function will return the existing model. The options will be ignored\n * in this case and the existing model will be returned in its current state.\n *\n * @example\n * ```typescript\n * const model = SoftwareInfo.factory(\"softwareInfoId\")({\n * // Add option data\n * });\n * ```\n \n\n *\n * ## predicate\n *\n * [Typescript type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) function that will identify and narrow down a model to a SoftwareInfoModel.\n *\n * @example\n * ```typescript\n *\n * const model: IKosDataModel = ...; // some model\n *\n * if (SoftwareInfo.predicate(model)) {\n * // if the function evaluates to true, the model is narrowed down to SoftwareInfoModel\n * // and the compiler will know that the model has the SoftwareInfoModel interface\n * model.updateAvailability(false);\n * }\n * ```\n *\n * ## registration\n *\n * The registration property is an object that can be used to simplify registration of the model with the model registry. The registration object\n * can be spread into the model registration and provides all of the required information to register the model implementation class against the model type.\n *\n *\n * @example\n *\n * In an application registration file you can declare the model registration as follows:\n *\n * **registration.ts**\n * ```typescript\n * import { SoftwareInfo } from \"@kos-ui/kos-dispenser-model\";\n * ...\n * import { ExtensionManager, IKosRegistry } from \"@kosdev-code/kos-ui-sdk\";\n * export const kosModels: IKosRegistry[\"models\"] = {\n * ...SoftwareInfo.registration,\n * };\n * ```\n *\n * ## registration.singleton\n \n * The softwareInfo model is NOT a singleton model. This means that each time the factory function is called with a unique ID, a new model instance will be created.\n * If the factory function is called with an ID that already exists, the existing model will be returned.\n \n * */\nexport const SoftwareInfo: Readonly<\n KosModelRegistrationBean<SoftwareInfoModel, SoftwareInfoOptions>\n> = {\n registration: {\n [MODEL_TYPE]: {\n class: SoftwareInfoModelImpl,\n singleton: false,\n },\n },\n type: MODEL_TYPE,\n predicate: isKosModel(MODEL_TYPE),\n factory: Kos.Factory.create<SoftwareInfoModel, SoftwareInfoOptions>(\n MODEL_TYPE\n ),\n};\n"],"names":["KosWsEvents","log","id","config","params","level","DependencyLifecycle","DependencyResolutionPolicy","hasHttpRouteHandlers","logLevel","api","kosServiceRequest","ResponseRetention","ReplayStrategy","makeAutoObservable","observable","makeObservable","action","createAtom","KosContainerIndexEvents","autorun","runInAction","models","isComputedProp","reaction","kosAction","observe","EventBus.publish","KosModelState","KosModelEvents","getKosModel","kosModel","companionModels","condition","once","delay","ObservableMap","cache","when","Transitions","rejectAfterDelay","dependentModel","machine","createMachine","state","transition","invoke","service","interpret","immediate","EventBus.subscribe","BASE_URL","kosFetch","PORT","URL","baseKosServiceRequest","API","sub","originalSubscribe","window","encodeFrame","timers","module","WebSocketEvents","MESSAGE_SEPARATOR","Transport","Logger","KosWSTransportStatus","computed","count","subscriptions","AsyncEventBus.iterate","fsm","logger","reset","KosModelRegistry","KosCoreState","KosCoreEvents","onlineMachine","getDefaultHost","AuthState","deleteModel","getAll","getOne","add","modifyModel","isObservable","EventBus.hasEventSubscriptions","EventBusState.waitForAllWithState","KosCoreModelPropertyMapper","Topics","postModel","flattenObject","PATH_PROP","DESTINATION_PROP","servicePathMapper","modifyConfigBean","modifyConfigBeanService","getConfigBean","getConfigBeanService","__decorateClass","UnitTupleKeys","acc","MODEL_TYPE","Registration","RegionInfo","format","result","buildFutureModel","FutureEndState","data","FutureModel","FutureContainerModel","deleteFuture","deleteFutureService","addFuture","addFutureService","model","n2","args","argCount","n1","f","i","div","__publicField","SERVICE_PATH","_logger","block","troubleMappers","Base","hexToRgb","p","q","pattern","WsEventModel","KosConfigPropertySpec","coreModels"],"mappings":";;;;;AAAO,MAAM,gBAAgB;AACtB,MAAM,eAAe;AACrB,MAAM,aAAa;AACnB,MAAM,oBAAoB;AAC1B,MAAM,qBAAqB;AAC3B,MAAM,SAAS;AACf,MAAM,0BAA0B;AAChC,MAAM,qBAAqB;AAC3B,MAAM,sBAAsB;AAC5B,MAAM,iBAAiB;AACvB,MAAM,sBAAsB;AAC5B,MAAM,sBAAsB;AAC5B,MAAM,uBAAuB;AAE7B,MAAM,wBAAwB;AAC9B,MAAM,aAAa,QAAQ,IAAI,iBAAiB;AAChD,MAAM,OAAO,QAAQ,IAAI,gBAAgB;AAEzC,MAAM,YAAY,GAAG,UAAU,IAAI,IAAI;AAEvC,MAAM,eAAe;A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