@kosdev-code/kos-ui-sdk 3.0.27 → 3.0.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../../../packages/kos-api-levels/src/deprecation.ts","../../../packages/kos-api-levels/src/registry.ts","../../../packages/kos-ui-sdk/src/common/events/eventBus.functional.ts","../../../packages/kos-ui-sdk/src/common/file-utils.ts","../../../packages/kos-ui-sdk/src/core/core/api/wrapPromise.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kos-companion.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kos-context.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kos-execute-service-request.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kos-multiple-future-aware.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kos-log.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kos-mixin.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kos-reference.ts","../../../packages/kos-ui-sdk/src/core/types/utils/kos-fetch.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kos-trouble-aware.ts","../../../packages/kos-ui-sdk/src/core/core/extension/initialize-extension.ts","../../../packages/kos-ui-sdk/src/core/core/extension/plugin-extension-manager.ts","../../../packages/kos-ui-sdk/src/core/util/debounce.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kosSubscribe.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kos-view-model.ts","../../../packages/kos-ui-sdk/src/core/util/ancestor-path-visitor.ts","../../../packages/kos-ui-sdk/src/core/util/apply-mixins.ts","../../../packages/kos-ui-sdk/src/core/util/array-utils.ts","../../../packages/kos-ui-sdk/src/core/util/date-utils.ts","../../../packages/kos-ui-sdk/src/core/util/hsl-to-hex.ts","../../../packages/kos-ui-sdk/src/core/util/middleware.ts","../../../packages/kos-ui-sdk/src/core/util/model-registration-utils.ts","../../../packages/kos-ui-sdk/src/core/util/paired-client-heartbeat.ts","../../../packages/kos-ui-sdk/src/core/util/retry-with-exponential-backoff.ts","../../../packages/kos-ui-sdk/src/core/util/service-response.ts","../../../packages/kos-ui-sdk/src/core/util/wait-for-request.ts","../../../packages/kos-ui-sdk/src/core/core/indexing/kos-index-aware.ts","../../../packages/kos-ui-sdk/src/core/core/indexing/kos-container-index-aware.ts","../../../packages/kos-ui-sdk/src/core/core/kos-registration.ts","../../../packages/kos-ui-sdk/src/core/core/kos-singleton-registration.ts","../../../packages/kos-ui-sdk/src/core/core/models/kos-token/index.ts","../../../packages/kos-ui-sdk/src/models/decorators/kos-config-bean.ts","../../../packages/kos-ui-sdk/src/models/decorators/kos-config-bean-prop.ts","../../../packages/kos-ui-sdk/src/models/decorators/kos-state-bean.ts","../../../packages/kos-ui-sdk/src/models/decorators/kos-state-prop.ts","../../../packages/kos-ui-sdk/src/models/types/cancellable-promise.ts","../../../packages/kos-ui-sdk/src/models/utils/cancellable-future-call.ts","../../../packages/kos-ui-sdk/src/models/models/translation/descriptor-merge.ts","../../../packages/kos-ui-sdk/src/models/models/translation/translation-context.ts","../../../packages/kos-ui-sdk/src/models/utils/extension-manager.ts","../../../packages/kos-ui-sdk/src/models/utils/persistence-store.ts","../../../packages/kos-ui-sdk/src/models/utils/region-utils.ts","../../../packages/kos-ui-sdk/src/models/utils/service-accessor.ts","../../../packages/kos-ui-sdk/src/models/utils/services/kos/daily/service.ts","../../../packages/kos-ui-sdk/src/models/utils/services/kos/1.6.5/service.ts","../../../packages/kos-ui-sdk/src/models/utils/services/kos/1.8.1/service.ts","../../../packages/kos-ui-sdk/src/models/utils/services/kos/1.9.x/service.ts","../../../packages/kos-ui-sdk/src/models/utils/services/vfs/daily/service.ts","../../../packages/kos-ui-sdk/src/models/utils/services/vfs/1.6.5/service.ts","../../../packages/kos-ui-sdk/src/models/utils/services/vfs/1.8.1/service.ts","../../../packages/kos-ui-sdk/src/models/utils/services/vfs/1.9.x/service.ts","../../../packages/kos-ui-sdk/src/models/utils/timezone-utils.ts","../../../packages/kos-ui-sdk/src/models/models/trouble/utils/is-trouble-aware.ts","../../../packages/kos-ui-sdk/src/models/services/login/index.ts","../../../packages/kos-ui-sdk/src/models/models/gpio-pin/gpio-pin-model.ts","../../../packages/kos-ui-sdk/src/models/models/gpio-pin/gpio-pin-container-model.ts","../../../packages/kos-ui-sdk/src/models/models/gpio-chip/gpio-chip-model.ts","../../../packages/kos-ui-sdk/src/models/models/gpio-chip/services/gpio-chip-services.ts","../../../packages/kos-ui-sdk/src/models/models/gpio-chip/gpio-chip-builders.ts","../../../packages/kos-ui-sdk/src/models/models/gpio-chip/gpio-chip-container-model.ts","../../../packages/kos-ui-sdk/src/models/models/studio-properties/services/studio-properties-services.ts","../../../packages/kos-ui-sdk/src/models/models/studio-properties/studio-properties-model.ts","../../../packages/kos-ui-sdk/src/models/models/studio-properties/studio-properties-registration.ts","../../../packages/kos-ui-sdk/src/ui/components/loading-message/loading-message-styles.ts","../../../packages/kos-ui-sdk/src/ui/components/loading-message/index.tsx","../../../packages/kos-ui-sdk/src/ui/components/error-boundary/error-boundary.tsx","../../../packages/kos-ui-sdk/src/ui/components/progress-bar/progress-bar.tsx","../../../packages/kos-ui-sdk/src/ui/components/kos-model-loader/contexts/kos-model-context.tsx","../../../packages/kos-ui-sdk/src/ui/components/kos-model-loader/contexts/kos-model-hierarchy-context.tsx","../../../packages/kos-ui-sdk/src/ui/components/kos-model-loader/kos-model-loader.tsx","../../../packages/kos-ui-sdk/src/ui/contexts/fetch-kos-core.ts","../../../packages/kos-ui-sdk/src/ui/contexts/kos-core-context.tsx","../../../packages/kos-ui-sdk/src/ui/policies/constants.ts","../../../packages/kos-ui-sdk/src/ui/policies/reload-on-disconnect-policy.tsx","../../../packages/kos-ui-sdk/src/ui/components/reconnecting-overlay/use-reconnecting-overlay-state.ts","../../../packages/kos-ui-sdk/src/ui/components/reconnecting-overlay/reconnecting-overlay-styles.ts","../../../packages/kos-ui-sdk/src/ui/components/reconnecting-overlay/index.tsx","../../../packages/kos-ui-sdk/src/ui/components/connection-dev-button/use-connection-dev-state.ts","../../../packages/kos-ui-sdk/src/ui/components/connection-dev-button/connection-dev-button-styles.ts","../../../packages/kos-ui-sdk/src/ui/components/connection-dev-button/index.tsx","../../../packages/kos-ui-sdk/src/ui/contexts/create-model-context.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/use-kos-model.ts","../../../packages/kos-ui-sdk/src/ui/hooks/kos-time/use-kos-time.ts","../../../packages/kos-ui-sdk/src/ui/contexts/kos-time/kos-time-provider.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/software-info/use-software-info.ts","../../../packages/kos-ui-sdk/src/ui/hooks/software-info/with-software-info.tsx","../../../packages/kos-ui-sdk/src/ui/contexts/software-info/software-info-provider.tsx","../../../packages/kos-ui-sdk/src/ui/contexts/token-context.tsx","../../../packages/kos-ui-sdk/src/ui/contexts/translation-container/kos-translations-provider.tsx","../../../packages/kos-ui-sdk/src/ui/features/canvas/hooks/canvas-dispatcher/use-canvas-dispatcher.ts","../../../packages/kos-ui-sdk/src/ui/features/canvas/hooks/canvas-dispatcher/with-canvas-dispatcher.tsx","../../../packages/kos-ui-sdk/src/ui/features/canvas/utils/preview-decoder.ts","../../../packages/kos-ui-sdk/src/ui/features/canvas/components/canvas-streamer/canvas-streamer.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/device/use-device.ts","../../../packages/kos-ui-sdk/src/ui/hooks/device/with-device.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/fetch-model.ts","../../../packages/kos-ui-sdk/src/ui/hooks/kos-time/with-kos-time.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/network-interface-container/use-network-interface-container.ts","../../../packages/kos-ui-sdk/src/ui/hooks/network-interface-container/with-network-interface-container.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/ota/use-ota.ts","../../../packages/kos-ui-sdk/src/ui/hooks/ota/with-ota.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/outside-alerter.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/state-prop/use-state-prop.ts","../../../packages/kos-ui-sdk/src/ui/hooks/storage-device-container/use-storage-device-container.ts","../../../packages/kos-ui-sdk/src/ui/hooks/storage-device-container/with-storage-device-container.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/timer/use-timer.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/translation-container/trans.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/translation-container/use-translation.ts","../../../packages/kos-ui-sdk/src/ui/hooks/translation-container/use-translation-container.ts","../../../packages/kos-ui-sdk/src/ui/hooks/translation-container/with-translation-container.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/trouble/use-trouble.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/trouble/use-trouble-container.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/trouble/use-trouble-visibility.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/trouble/with-trouble-container.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/usb-update-container/use-usb-update-container.ts","../../../packages/kos-ui-sdk/src/ui/hooks/usb-update-container/with-usb-update-container.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/use-config-bean.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/use-config-property.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/use-connection-state.ts","../../../packages/kos-ui-sdk/src/ui/utils/date.ts","../../../packages/kos-ui-sdk/src/ui/utils/date-utils.ts","../../../packages/kos-ui-sdk/src/ui/hooks/use-date-props.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/use-date-relative-prop.ts","../../../packages/kos-ui-sdk/src/ui/hooks/use-function-warmup.ts","../../../packages/kos-ui-sdk/src/ui/hooks/use-kos-date-formats.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/use-kos-region-timezones.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/use-kos-regions.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/use-kos-time-formats.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/use-local-computed.ts","../../../packages/kos-ui-sdk/src/ui/hooks/use-mutation-observer.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/use-press-gesture/strategy/dom-intersection-strategy.ts","../../../packages/kos-ui-sdk/src/ui/hooks/use-press-gesture/use-press-gesture.ts","../../../packages/kos-ui-sdk/src/ui/hooks/use-project-reloading.ts","../../../packages/kos-ui-sdk/src/ui/hooks/use-time-props.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/use-region-time-props.ts","../../../packages/kos-ui-sdk/src/ui/hooks/view-model/use-view-model.ts","../../../packages/kos-ui-sdk/src/ui/hooks/with-project-reload.tsx","../../../packages/kos-ui-sdk/src/index.ts"],"sourcesContent":["const _warned = new Set<string>();\n\n/**\n * Emits a one-time console warning in non-production environments when a\n * deprecated API is used.\n *\n * @param apiName - The name of the deprecated API (e.g. `@kosSubscribe`)\n * @param serviceId - The service the API belongs to (e.g. `core.subscribe`)\n * @param deprecatedAtLevel - The API level at which this API was deprecated\n * @param replacement - The recommended replacement (e.g. `@kosTopicHandler`)\n * @param removeAtLevel - The API level at which this API will be removed\n */\nexport function warnDeprecated(\n apiName: string,\n serviceId: string,\n deprecatedAtLevel: number,\n replacement: string,\n removeAtLevel: number\n): void {\n if (\n typeof process !== \"undefined\" &&\n process.env[\"NODE_ENV\"] === \"production\"\n ) {\n return;\n }\n if (_warned.has(apiName)) return;\n _warned.add(apiName);\n console.warn(\n `[KOS] \"${apiName}\" is deprecated since ${serviceId} level ${deprecatedAtLevel}. ` +\n `Use \"${replacement}\" instead. Will be removed at level ${removeAtLevel}.`\n );\n}\n","import type { ApiLevelMap } from \"./types\";\n\nconst _registry: ApiLevelMap = {};\n\n/**\n * Registers API levels for an SDK package. Each SDK package calls this on\n * import to populate the in-memory registry. Works in browser and Node.js.\n * The call lives in each package's index.ts; the release scanner\n * (`scanner/generate-release.ts`) updates its level number.\n */\nexport function registerApiLevels(levels: ApiLevelMap): void {\n Object.assign(_registry, levels);\n}\n\nexport function getRegistry(): Readonly<ApiLevelMap> {\n return _registry;\n}\n","/**\n * Functional programming utilities for the EventBus\n * Provides reactive and promise-based patterns for event handling\n */\n\nimport { ApiCallback, EventCallback, publish, subscribe } from \"./eventBus\";\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/**\n * Wait for multiple events to occur (Promise.all pattern)\n *\n * @param eventTypes - Array of event types to wait for\n * @param timeout - Optional timeout in milliseconds\n * @returns Promise that resolves when all events have occurred\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function waitForAll<T = ApiCallback>(\n eventTypes: string[],\n timeout?: number\n): Promise<T[]> {\n const promises = eventTypes.map((eventType) =>\n waitFor<T>(eventType, timeout)\n );\n return Promise.all(promises);\n}\n\n/**\n * Wait for the first event to occur from a list (Promise.race pattern)\n *\n * @param eventTypes - Array of event types to race\n * @param timeout - Optional timeout in milliseconds\n * @returns Promise that resolves with the first event\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function race<T = ApiCallback>(\n eventTypes: string[],\n timeout?: number\n): Promise<{ eventType: string; data: T }> {\n return new Promise((resolve, reject) => {\n const unsubscribers: (() => void)[] = [];\n let timeoutId: NodeJS.Timeout | null = null;\n let resolved = false;\n\n const cleanup = () => {\n unsubscribers.forEach((unsub) => unsub());\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n };\n\n eventTypes.forEach((eventType) => {\n const unsubscribe = once(eventType, (msg?: T) => {\n if (!resolved) {\n resolved = true;\n cleanup();\n resolve({ eventType, data: msg! });\n }\n });\n unsubscribers.push(unsubscribe);\n });\n\n if (timeout) {\n timeoutId = setTimeout(() => {\n if (!resolved) {\n resolved = true;\n cleanup();\n reject(\n new Error(`Timeout waiting for any event: ${eventTypes.join(\", \")}`)\n );\n }\n }, timeout);\n }\n });\n}\n\n/**\n * Filter events based on a predicate function\n *\n * @param eventType - The event type to filter\n * @param predicate - Function to test each event\n * @param callback - Callback for events that pass the filter\n * @returns Unsubscribe function\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function filter<T = ApiCallback>(\n eventType: string,\n predicate: (msg: T) => boolean,\n callback: EventCallback<T>\n): () => void {\n const subscription = subscribe(eventType, (msg?: T) => {\n if (msg && predicate(msg)) {\n callback(msg);\n }\n });\n\n return subscription.unsubscribe;\n}\n\n/**\n * Transform events using a map function\n *\n * @param eventType - The event type to transform\n * @param transform - Function to transform the event data\n * @param callback - Callback for transformed events\n * @returns Unsubscribe function\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function map<T = ApiCallback, R = any>(\n eventType: string,\n transform: (msg: T) => R,\n callback: (msg: R) => void\n): () => void {\n const subscription = subscribe(eventType, (msg?: T) => {\n if (msg) {\n const transformed = transform(msg);\n callback(transformed);\n }\n });\n\n return subscription.unsubscribe;\n}\n\n/**\n * Debounce events - only emit after a period of inactivity\n *\n * @param eventType - The event type to debounce\n * @param delay - Delay in milliseconds\n * @param callback - Callback for debounced events\n * @returns Unsubscribe function\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function debounce<T = ApiCallback>(\n eventType: string,\n delay: number,\n callback: EventCallback<T>\n): () => void {\n let timeoutId: NodeJS.Timeout | null = null;\n\n const subscription = subscribe(eventType, (msg?: T) => {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n timeoutId = setTimeout(() => {\n callback(msg);\n }, delay);\n });\n\n return () => {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n subscription.unsubscribe();\n };\n}\n\n/**\n * Throttle events - limit emissions to once per interval\n *\n * @param eventType - The event type to throttle\n * @param interval - Minimum interval between emissions in milliseconds\n * @param callback - Callback for throttled events\n * @returns Unsubscribe function\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function throttle<T = ApiCallback>(\n eventType: string,\n interval: number,\n callback: EventCallback<T>\n): () => void {\n let lastEmit = 0;\n let pendingTimeout: NodeJS.Timeout | null = null;\n\n const subscription = subscribe(eventType, (msg?: T) => {\n const now = Date.now();\n const timeSinceLastEmit = now - lastEmit;\n\n if (timeSinceLastEmit >= interval) {\n lastEmit = now;\n callback(msg);\n } else if (!pendingTimeout) {\n // Schedule emission for the remaining time\n pendingTimeout = setTimeout(() => {\n lastEmit = Date.now();\n callback(msg);\n pendingTimeout = null;\n }, interval - timeSinceLastEmit);\n }\n });\n\n return () => {\n if (pendingTimeout) {\n clearTimeout(pendingTimeout);\n }\n subscription.unsubscribe();\n };\n}\n\n/**\n * Buffer events and emit them as an array\n *\n * @param eventType - The event type to buffer\n * @param bufferTime - Time window to collect events in milliseconds\n * @param callback - Callback for buffered events\n * @returns Unsubscribe function\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function buffer<T = ApiCallback>(\n eventType: string,\n bufferTime: number,\n callback: (events: T[]) => void\n): () => void {\n let buffer: T[] = [];\n let timeoutId: NodeJS.Timeout | null = null;\n\n const flush = () => {\n if (buffer.length > 0) {\n callback([...buffer]);\n buffer = [];\n }\n };\n\n const subscription = subscribe(eventType, (msg?: T) => {\n if (msg) {\n buffer.push(msg);\n\n if (!timeoutId) {\n timeoutId = setTimeout(() => {\n flush();\n timeoutId = null;\n }, bufferTime);\n }\n }\n });\n\n return () => {\n if (timeoutId) {\n clearTimeout(timeoutId);\n flush(); // Emit any remaining buffered events\n }\n subscription.unsubscribe();\n };\n}\n\n/**\n * Create a replay subject that remembers the last N events\n *\n * @param eventType - The event type to replay\n * @param bufferSize - Number of events to remember\n * @returns Object with subscribe method that replays buffered events\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function replay<T = ApiCallback>(eventType: string, bufferSize = 1) {\n const buffer: T[] = [];\n\n // Subscribe to capture events\n subscribe(eventType, (msg?: T) => {\n if (msg) {\n buffer.push(msg);\n if (buffer.length > bufferSize) {\n buffer.shift();\n }\n }\n });\n\n return {\n subscribe: (callback: EventCallback<T>) => {\n // Replay buffered events immediately\n buffer.forEach((event) => callback(event));\n\n // Then subscribe for future events\n return subscribe(eventType, callback);\n },\n };\n}\n\n/**\n * Merge multiple event streams into one\n *\n * @param eventTypes - Array of event types to merge\n * @param callback - Callback for all merged events\n * @returns Unsubscribe function for all subscriptions\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function merge<T = ApiCallback>(\n eventTypes: string[],\n callback: (eventType: string, msg: T) => void\n): () => void {\n const subscriptions = eventTypes.map((eventType) =>\n subscribe(eventType, (msg?: T) => {\n if (msg) {\n callback(eventType, msg);\n }\n })\n );\n\n return () => {\n subscriptions.forEach((sub) => sub.unsubscribe());\n };\n}\n\n/**\n * Create a state machine that transitions based on events\n *\n * @param initialState - The initial state\n * @param transitions - Object mapping states to event handlers\n * @returns Object with current state and unsubscribe function\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function stateMachine<TState extends string, T = ApiCallback>(\n initialState: TState,\n transitions: Record<TState, Record<string, (msg: T) => TState>>\n) {\n let currentState = initialState;\n const subscriptions: (() => void)[] = [];\n\n // Subscribe to all events mentioned in transitions\n const allEvents = new Set<string>();\n Object.values(transitions).forEach((stateTransitions) => {\n Object.keys(stateTransitions as Record<string, any>).forEach((event) => {\n allEvents.add(event);\n });\n });\n\n allEvents.forEach((eventType) => {\n const { unsubscribe } = subscribe(eventType, (msg?: T) => {\n const stateTransitions = transitions[currentState];\n if (stateTransitions && stateTransitions[eventType]) {\n const nextState = stateTransitions[eventType](msg!);\n currentState = nextState;\n }\n });\n subscriptions.push(unsubscribe);\n });\n\n return {\n get state() {\n return currentState;\n },\n unsubscribe: () => {\n subscriptions.forEach((unsub) => unsub());\n },\n };\n}\n\n/**\n * Utility to create a promise that can be resolved by publishing an event\n *\n * @param requestEvent - Event type to publish the request\n * @param responseEvent - Event type to wait for the response\n * @param request - The request data to publish\n * @param timeout - Optional timeout in milliseconds\n * @returns Promise that resolves with the response\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function request<TRequest = any, TResponse = ApiCallback>(\n requestEvent: string,\n responseEvent: string,\n request: TRequest,\n timeout?: number\n): Promise<TResponse> {\n const responsePromise = waitFor<TResponse>(responseEvent, timeout);\n publish(requestEvent, request);\n return responsePromise;\n}\n\n/**\n * Create an async iterator for events\n *\n * @param eventType - The event type to iterate\n * @returns Async iterator for use with for-await-of\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport async function* eventIterator<T = ApiCallback>(\n eventType: string\n): AsyncIterableIterator<T> {\n const queue: T[] = [];\n const waiters: ((value: T) => void)[] = [];\n\n const subscription = subscribe(eventType, (msg?: T) => {\n if (msg) {\n if (waiters.length > 0) {\n const waiter = waiters.shift()!;\n waiter(msg);\n } else {\n queue.push(msg);\n }\n }\n });\n\n try {\n while (true) {\n if (queue.length > 0) {\n yield queue.shift()!;\n } else {\n yield await new Promise<T>((resolve) => {\n waiters.push(resolve);\n });\n }\n }\n } finally {\n subscription.unsubscribe();\n }\n}\n\n/**\n * Namespace collecting all functional event bus utilities.\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport const EventBusFunctional = {\n once,\n waitFor,\n waitForAll,\n race,\n filter,\n map,\n debounce,\n throttle,\n buffer,\n replay,\n merge,\n stateMachine,\n request,\n eventIterator,\n};\n","type Sizes = \"bytes\" | \"KB\" | \"MB\" | \"GB\" | \"TB\";\ninterface Convert {\n value: number;\n scale: Sizes;\n toString: () => string;\n}\nexport const convertFileSizeRaw = (bytes: number, decimals = 0): Convert => {\n if (!+bytes)\n return {\n value: 0,\n scale: \"bytes\",\n toString: () => `0 bytes`,\n };\n\n const k = 1024;\n const dm = decimals < 0 ? 0 : decimals;\n const sizes: Sizes[] = [\"bytes\", \"KB\", \"MB\", \"GB\", \"TB\"];\n\n const i = Math.floor(Math.log(bytes) / Math.log(k));\n const value = parseFloat((bytes / Math.pow(k, i)).toFixed(dm));\n const scale = sizes[i];\n return {\n value,\n scale,\n toString: () => `${value} ${scale}`,\n };\n};\n","/**\n * Utility function that will wrap an arbitrary promise in order for it to\n * conform to the React Suspense API. By utilizing this higher order function\n * React components can participate in the Suspense workflow and enable the application\n * to display fallback behaviour while KOS data models or APIs are being fetched.\n *\n * @param promise The promise to be resolved\n * @returns an Object with a single `read` function that will be used to broadcast\n * status back to the React framework.\n */\nexport function wrapPromise<T>(promise: Promise<T>) {\n let status = `pending`;\n let response;\n\n const suspender = promise.then(\n (res) => {\n status = `success`;\n response = res;\n },\n (err) => {\n status = `error`;\n response = err;\n }\n );\n\n const read = (): T => {\n switch (status) {\n case `pending`:\n throw suspender;\n case `error`:\n throw response;\n default:\n return response;\n }\n };\n\n return { read };\n}\n","/* eslint-disable no-param-reassign */\nimport type { DependencyLifecycle } from \"../../types\";\nimport type { IKosDataModel } from \"../kosModel\";\nimport { kosParentAware } from \"./kos-parent\";\nimport { CompanionParentModel } from \"./propKeys\";\n\n/**\n * @kosService core.companion\n * @kosApiLevel 13\n */\nexport interface KosCompanionOptions {\n /**\n * Pattern mode:\n * - 'decorator': Proxy all parent properties transparently (default)\n * - 'composition': Only provide getCompanionParent() method\n */\n mode?: \"decorator\" | \"composition\";\n /** Properties to exclude from proxying (only applies in decorator mode). Default: [] */\n excludeProperties?: string[];\n /** Custom parent property name. Default: 'companionParent' */\n parentProperty?: string;\n /**\n * Lifecycle phase of the parent at which this companion is created. Defaults to INIT\n * (created during parent instantiation); LOAD creates it after the parent's load()\n * completes, READY after ready(), and so on.\n *\n * @kosApiLevel 15\n */\n lifecycle?: DependencyLifecycle;\n}\n\n/**\n * Base interface for all companion models.\n * Provides the getCompanionParent() method available in both decorator and composition modes.\n *\n * @kosService core.companion\n * @kosApiLevel 13\n */\nexport interface KosCompanionAware<\n TParent extends IKosDataModel = IKosDataModel\n> {\n /**\n * Gets the companion's parent model instance.\n * Available in both decorator and composition modes.\n * Provides access to the model this companion extends.\n *\n * @returns The parent model instance that this companion enhances\n */\n getCompanionParent(): TParent;\n}\n\n/**\n * Members injected into a companion in composition mode. Declare an interface with the\n * same name as the class that extends this type (TypeScript interface merging).\n *\n * @kosService core.companion\n */\nexport type KosCompanionComposition<\n TParent extends IKosDataModel = IKosDataModel\n> = KosCompanionAware<TParent>;\n\n/**\n * Members injected into a companion in decorator mode (the default). Declare an\n * interface with the same name as the class that extends this type (TypeScript\n * interface merging); to type the proxied parent members as well, also extend the\n * parent model's interface.\n *\n * @kosService core.companion\n */\nexport type KosCompanionDecorator<\n TParent extends IKosDataModel = IKosDataModel\n> = KosCompanionAware<TParent>;\n\n/**\n * Class decorator that makes a KOS model a companion of a parent model, extending it\n * with behavior that lives in a separate model.\n *\n * Both modes provide `getCompanionParent()` and a read-only `companionParent` (or\n * `parentProperty`) getter.\n * - **decorator** (default): the parent's properties and methods are also proxied onto\n * the companion, so it can stand in for the parent. Lifecycle methods, topic\n * handlers, `_`-prefixed members, `excludeProperties` and members the companion\n * defines itself are not proxied.\n * - **composition**: the parent is reachable only through those two accessors.\n *\n * The decorator also applies @kosParentAware.\n *\n * @param options Configuration options for the companion decorator\n * @returns A class decorator\n *\n * @example\n * ```typescript\n * interface ServiceCompanionModelImpl extends KosCompanionComposition<ServiceModel> {}\n *\n * @kosModel(\"service-companion\")\n * @kosCompanion({ mode: 'composition' })\n * class ServiceCompanionModelImpl implements IKosDataModel {\n * get serviceInfo() {\n * return `Service: ${this.getCompanionParent().serviceName}`;\n * }\n * }\n * ```\n *\n * @category KOS Model Decorator\n * @since 2.1.0\n * @kosService core.companion\n * @kosApiLevel 2\n */\nexport function kosCompanion(options?: KosCompanionOptions): ClassDecorator {\n return (target: any) => {\n const mode = options?.mode || \"decorator\";\n const parentProperty = options?.parentProperty || \"companionParent\";\n const excludeProperties = options?.excludeProperties || [];\n const lifecycle = options?.lifecycle;\n\n // Companions by definition have parent relationships - automatically apply kosParentAware\n kosParentAware()(target);\n\n // Add the companion configuration to the prototype\n // This will be processed by kosModel.ts during model instantiation\n target.prototype[CompanionParentModel] = {\n mode,\n parentProperty,\n excludeProperties,\n lifecycle,\n };\n\n return target;\n };\n}\n","/**\n * @internal\n */\nimport { KosContextManager } from \"../context/kos-context-manager\";\n\n/**\n * Method decorator that injects the current KOS execution context into a method call.\n *\n * @kosService core.context\n * @kosApiLevel 2\n */\nexport function kosContext(\n _target: any,\n _propertyKey: string,\n descriptor: PropertyDescriptor\n) {\n // store the original method\n const originalMethod = descriptor.value;\n\n // modify the descriptor value\n descriptor.value = function (...args: any[]) {\n // get the kos context\n const ctx = KosContextManager.getContext((this as any).id);\n // add the context as the last argument\n args.push(ctx);\n\n // apply the original method\n return originalMethod.apply(this, args);\n };\n}\n","import type { ClientResponse } from \"../../util/kos-service-request\";\nimport type { KosExecutionContext } from \"./kos-execution-context\";\nimport type { KosLoggerAware } from \"./kos-logger-aware\";\nimport type { HttpMethod, ServiceRequestExecutor } from \"./kos-service-request\";\n\n/**\n * Runs a method-driven service request: checks the injected context, awaits the\n * error-first tuple, logs a failure and treats an empty body as a failure, so the\n * caller handles only the success path.\n *\n * ```typescript\n * const data = await executeServiceRequest(this, $ctx, {\n * body: { id: cartridgeId },\n * });\n * if (!data) return;\n * ```\n *\n * Failures are logged against the method name the decorator puts on `$ctx.$name`.\n *\n * Use it only with a @kosServiceRequest that has no `lifecycle`. A lifecycle-driven\n * handler receives `(error, data)` with the request already performed and never gets\n * a context.\n *\n * @param host Model the request belongs to; supplies the logger.\n * @param $ctx Context the decorator injected as the method's last parameter.\n * @param params `pathParams` / `queryParams` / `body` / `requestOptions`.\n * @returns The response body, or `undefined` when the request could not run,\n * failed, or came back empty.\n *\n * @kosService core.service-request\n * @kosApiLevel 24\n */\nexport async function executeServiceRequest<\n Paths extends Record<string, any>,\n Path extends keyof Paths,\n Method extends HttpMethod = \"get\",\n Transformed = ClientResponse<Paths, Path, Method>\n>(\n host: KosLoggerAware,\n $ctx: KosExecutionContext<Paths, Path, Method, Transformed> | undefined,\n params?: Parameters<ServiceRequestExecutor<Paths, Path, Method>>[0]\n): Promise<NonNullable<Transformed> | undefined> {\n const name = $ctx?.$name ?? \"service request\";\n if (!$ctx?.$request) {\n // Almost always a decorator with a `lifecycle`, which gets no context; say so,\n // because the symptom is a method that silently does nothing.\n host.logger.error(\n `${name}: missing execution context — executeServiceRequest is for method-driven requests; ` +\n `a @kosServiceRequest with a lifecycle receives (error, data) instead and needs no helper`\n );\n return undefined;\n }\n\n const [error, data] = await $ctx.$request(params);\n if (error) {\n host.logger.error(`${name}: request failed`, error);\n return undefined;\n }\n if (data == null) {\n host.logger.error(`${name}: no data returned`);\n return undefined;\n }\n // The context's Transformed type is the raw response, or the transform's output.\n return data as NonNullable<Transformed>;\n}\n","/* eslint-disable no-param-reassign */\nimport type { MultipleFutureHandler } from \"../../../models/models/future/future-aware\";\nimport type { IFutureModel } from \"../../../models/models/future/future-types\";\nimport { MultipleFutureContainerSetup } from \"./propKeys\";\n\n/**\n * @kosService core.future-aware\n * @kosApiLevel 14\n */\nexport interface KosMultipleFutureAwareOptions {\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 * Members injected by @kosMultipleFutureAware in minimal mode. Minimal mode also\n * injects an `<alias>Future` getter per @kosFuture alias; declare the ones you read on\n * the merged interface.\n *\n * @example\n * ```typescript\n * interface MaintenanceModelImpl extends KosMultipleFutureAwareMinimal {\n * calibrationFuture?: IFutureModel;\n * }\n * ```\n *\n * @kosService core.future-aware\n * @kosApiLevel 14\n */\nexport interface KosMultipleFutureAwareMinimal {\n /**\n * Container that tracks the model's concurrent Future operations by alias.\n */\n futureHandler: MultipleFutureHandler;\n}\n\n/**\n * Utility types to generate future property names for multiple futures (for internal use)\n */\ntype FutureGetters<T extends string> = {\n readonly [K in T as `${K}Future`]?: IFutureModel;\n};\n\ntype ProgressGetters<T extends string> = {\n readonly [K in T as `${K}Progress`]: number;\n};\n\ntype StatusGetters<T extends string> = {\n readonly [K in T as `${K}Status`]: string;\n};\n\ntype IsRunningGetters<T extends string> = {\n readonly [K in T as `${K}IsRunning`]: boolean;\n};\n\ntype IsCancelledGetters<T extends string> = {\n readonly [K in T as `${K}IsCancelled`]: boolean;\n};\n\ntype CancelMethods<T extends string> = {\n readonly [K in T as `cancel${Capitalize<K>}`]: () => Promise<void>;\n};\n\n/**\n * @kosService core.future-aware\n */\nexport type MultipleFutureProperties<T extends string> = FutureGetters<T> &\n ProgressGetters<T> &\n StatusGetters<T> &\n IsRunningGetters<T> &\n IsCancelledGetters<T> &\n CancelMethods<T>;\n\n/**\n * Members injected by @kosMultipleFutureAware in full mode (the default), where `T` is\n * the union of @kosFuture aliases. Declare an interface with the same name as the\n * class that extends this type (TypeScript interface merging).\n *\n * @kosService core.future-aware\n */\nexport type KosMultipleFutureAwareFull<T extends string = string> =\n KosMultipleFutureAwareMinimal & MultipleFutureProperties<T>;\n\n/**\n * Class decorator that lets a KOS model track several concurrent Futures, one per\n * @kosFuture `alias`. For a single Future, use @kosFutureAware.\n *\n * The model gets a `futureHandler` container and an `<alias>Future` getter per alias.\n * Full mode also adds `<alias>Progress`, `<alias>Status`, `<alias>IsRunning`,\n * `<alias>IsCancelled` and `cancel<Alias>()`. An optional\n * `onFutureUpdate(future, alias)` method on the model is called as each Future\n * progresses.\n *\n * @param options Configuration options for the decorator\n * @returns A class decorator\n *\n * @example\n * ```typescript\n * interface IceAgitatorModelImpl extends KosMultipleFutureAwareFull<\"pour\" | \"agitate\"> {}\n *\n * @kosModel(\"ice-agitator-model\")\n * @kosMultipleFutureAware()\n * class IceAgitatorModelImpl implements IKosDataModel {\n * @kosFuture({ alias: \"pour\" })\n * async pourIce(): Promise<FutureResponse | undefined> {\n * return startPourService();\n * }\n *\n * @kosFuture({ alias: \"agitate\" })\n * async agitate(): Promise<FutureResponse | undefined> {\n * return startAgitateService();\n * }\n * }\n * // this.pourProgress, this.agitateIsRunning, this.cancelPour(), ...\n * ```\n *\n * @category KOS Model Decorator\n * @since 2.0.0\n * @kosService core.future-aware\n * @kosApiLevel 14\n */\nexport function kosMultipleFutureAware(\n options?: KosMultipleFutureAwareOptions\n): ClassDecorator {\n return (target: any) => {\n const mode = options?.mode || \"full\";\n const handlerProperty = options?.handlerProperty || \"futureHandler\";\n\n // Add the MultipleFutureContainerSetup configuration to the prototype\n // This will be processed by kosModel.ts during model instantiation\n target.prototype[MultipleFutureContainerSetup] = {\n mode,\n handlerProperty,\n };\n\n return target;\n };\n}\n","/**\n * @internal\n */\nimport { IKosDataModel } from \"../kosModel\";\nimport { LogConfig } from \"./propKeys\";\n\ninterface DecoratedKosModel<T extends IKosDataModel = IKosDataModel> {\n new (...args: any[]): T;\n}\n\ninterface LogConfigProps {\n group?: string;\n}\n/**\n * @kosService core.logging\n * @kosApiLevel 2\n */\nexport const kosLogger =\n <T extends IKosDataModel>({ group }: LogConfigProps = { group: \"\" }) =>\n (constructor: DecoratedKosModel<T>): any => {\n constructor[LogConfig] = constructor[LogConfig] || {};\n constructor[LogConfig] = { group };\n };\n","/* eslint-disable no-param-reassign */\nimport type { IKosDataModel } from \"../kosModel\";\nimport type { KosModelRegistrationFactory } from \"../registration/base-kos-model-registration\";\nimport type { KosCompanionAware } from \"./kos-companion\";\nimport { CompanionParentModel, MixinModels } from \"./propKeys\";\n\n/**\n * A mixin declared on a host, keyed by the property that holds it.\n *\n * @internal\n */\nexport interface KosMixinDefinition {\n registration: KosModelRegistrationFactory<any, any>;\n options?: unknown;\n}\n\n/**\n * The host interface a mixin requires.\n *\n * @kosService core.mixin\n * @kosApiLevel 25\n */\nexport type KosMixinHost<TMixin> = TMixin extends KosCompanionAware<infer THost>\n ? THost\n : IKosDataModel;\n\n/**\n * The options a host passes to its mixin. Any option can be a prop key, resolved from the\n * host's data when the mixin is created.\n *\n * @kosService core.mixin\n * @kosApiLevel 25\n */\nexport type KosMixinOptions<O> = O extends { data?: infer D }\n ? { [K in keyof D]: D[K] | string }\n : never;\n\n/**\n * Mixes a reusable behaviour into a model. The host gets its own instance of the mixin\n * in the decorated property, there from the moment the host is created and observable,\n * so the host's effects can react to it.\n *\n * The mixin calls back into the host through `getCompanionParent()`, typed by the host\n * interface it declares; a host that does not implement that interface does not\n * compile.\n *\n * @param mixin The mixin model's registration.\n * @param options The mixin's model options, received as `options.data`. Any option can\n * be a prop key (`createPropKey`), resolved from the host's data when the mixin is\n * created.\n *\n * @example\n * ```typescript\n * interface DirtyHost extends IKosDataModel { onDirtyChanged?(dirty: boolean): void }\n * interface DirtyTrackingImpl extends KosCompanionComposition<DirtyHost> {}\n *\n * @kosModel(\"dirty-tracking\")\n * @kosCompanion({ mode: \"composition\" })\n * class DirtyTrackingImpl implements IKosDataModel { ... }\n *\n * @kosModel(\"recipe\")\n * class RecipeImpl implements IKosDataModel, DirtyHost {\n * @kosMixin(DirtyTracking, { fields: [\"name\"] })\n * dirty!: DirtyTrackingModel;\n * }\n * ```\n *\n * @category KOS Model Decorator\n * @kosService core.mixin\n * @kosApiLevel 25\n */\nexport function kosMixin<TMixin extends IKosDataModel, O extends object>(\n mixin: KosModelRegistrationFactory<TMixin, O>,\n options?: KosMixinOptions<O>\n) {\n return (target: KosMixinHost<TMixin>, propertyKey: string): void => {\n const companion = mixin.class.prototype[CompanionParentModel];\n if (companion?.mode !== \"composition\") {\n throw new Error(\n `Mixin ${mixin.type} must be a @kosCompanion({ mode: \"composition\" }) model`\n );\n }\n if (companion.lifecycle !== undefined) {\n throw new Error(\n `Mixin ${mixin.type} cannot set a companion lifecycle; mixins are created with their host`\n );\n }\n\n const host = target as any;\n host[MixinModels] = host[MixinModels] || {};\n const mixins: Record<string, KosMixinDefinition> = host[MixinModels];\n if (Object.values(mixins).some((m) => m.registration.type === mixin.type)) {\n throw new Error(\n `Mixin ${mixin.type} is already mixed into this model; a host holds one instance of each mixin`\n );\n }\n mixins[propertyKey] = { registration: mixin, options };\n };\n}\n","/**\n * @ignore\n * @deprecated\n */\nimport { warnDeprecated } from \"@kosdev-code/kos-api-levels\";\nimport { ReferenceConfig } from \"./propKeys\";\n\n/**\n * @kosService core.reference\n * @kosApiLevel 2\n */\ninterface ReferenceProps {\n modelType: string;\n}\n\n/**\n * @kosService core.reference\n * @kosApiLevel 2\n * @kosDeprecated {replacement: @kosDependency, removeAt: 3}\n */\nexport const kosReference =\n (props: ReferenceProps) =>\n (target: {} | any, name: PropertyKey): any => {\n warnDeprecated(\"@kosReference\", \"core.reference\", 1, \"@kosDependency\", 3);\n target[ReferenceConfig] = target[ReferenceConfig] || {};\n target[ReferenceConfig][name] = props;\n };\n","/**\n * @kosService core.fetch\n * @kosApiLevel 1\n */\nexport enum KosFetchMethods {\n GET = `GET`,\n PUT = `PUT`,\n POST = `POST`,\n DELETE = `DELETE`,\n}\n\ntype FetchMethodStrings = keyof typeof KosFetchMethods;\n\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport interface Headers {\n append(name: string, value: string): void;\n delete(name: string): void;\n get(name: string): string | null;\n has(name: string): boolean;\n set(name: string, value: string): void;\n forEach(\n callbackfn: (value: string, key: string, parent: Headers) => void,\n thisArg?: any\n ): void;\n}\n\ninterface Body {\n readonly body: ReadableStream<Uint8Array> | null;\n readonly bodyUsed: boolean;\n arrayBuffer(): Promise<ArrayBuffer>;\n blob(): Promise<Blob>;\n formData(): Promise<FormData>;\n json<T = any>(): Promise<T | null>;\n text(): Promise<string>;\n}\n\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport interface Response extends Body {\n readonly headers: Headers;\n readonly ok: boolean;\n readonly redirected: boolean;\n readonly status: number;\n readonly statusText: string;\n readonly type: ResponseType;\n readonly url: string;\n clone(): Response;\n}\n\n/**\n * Configuration for retrying failed service requests with exponential backoff.\n *\n * @kosService core.fetch\n *\n * Applies to requests made through the service-request client. Setting `retry`\n * to `true` on {@link KosFetchOptions} uses the defaults below; a partial\n * `RetryConfig` overrides only the fields it sets:\n * - `maxAttempts`: 3\n * - `baseDelayMs`: 350\n * - `backoffFactor`: 2\n * - `retryMutations`: false (POST, PUT, DELETE and PATCH are not retried)\n * - `retryOn`: unset, so every error response is retried\n *\n * Only error responses are retried; timeouts and aborts are returned at once.\n *\n * @example\n * ```typescript\n * retry: { maxAttempts: 5, retryOn: (response) => response.status === 503 }\n * ```\n *\n * @category Service Request\n * @kosApiLevel 22\n */\nexport interface RetryConfig {\n /** Maximum number of attempts (including the initial request). @default 3 */\n maxAttempts?: number;\n\n /** Base delay in milliseconds before the first retry. @default 350 */\n baseDelayMs?: number;\n\n /** Multiplier applied to the delay after each attempt. @default 2 */\n backoffFactor?: number;\n\n /**\n * Whether to retry mutating methods (POST, PUT, DELETE, PATCH).\n * Set to `true` only if the endpoint is idempotent.\n * @default false\n */\n retryMutations?: boolean;\n\n /**\n * Predicate called with the error {@link Response} to decide whether to\n * retry. Return `true` to retry, `false` to stop immediately. When omitted,\n * every error response is retried up to `maxAttempts`.\n */\n retryOn?: (response: Response) => boolean;\n}\n\n/**\n * Represents the configuration options for performing a Kos WebSocket fetch operation.\n *\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport interface KosFetchOptions {\n /**\n * The HTTP method for the request (e.g., 'GET', 'POST', 'PUT', 'DELETE', etc.).\n */\n method: FetchMethodStrings;\n\n /**\n * The request body - can be string, ArrayBuffer, Blob, or FormData.\n */\n body?: string | ArrayBuffer | Blob | FormData | Uint8Array;\n\n /**\n * Indicates whether the request should be ordered.\n */\n ordered?: boolean;\n\n /**\n * The destination address for the WebSocket request.\n */\n destinationAddress?: string;\n\n /**\n * @internal\n */\n signal?: AbortSignal;\n\n /**\n * The tracker associated with the request.\n */\n tracker?: string;\n\n /**\n * @internal\n */\n studio?: boolean;\n\n /**\n * @internal\n */\n fos?: boolean;\n\n /**\n * @internal\n */\n bridge?: boolean;\n\n /**\n * Timeout budget for the entire call, in milliseconds: waiting for the\n * transport to become ready plus the request itself.\n *\n * A request issued while the socket is down rejects with a\n * `TransportNotReadyError` if the transport does not become ready within the\n * budget. Otherwise the remaining budget applies to the request, which\n * rejects with a `TimeoutError` `DOMException` when it runs out. The two\n * errors are distinct so callers can tell a slow service from a down\n * transport.\n *\n * Defaults to the `KOS_WS_TIMEOUT` environment value, or 30000. Pass `0` or\n * `Infinity` to queue until the transport recovers; such a request does not\n * settle while the socket is down.\n */\n timeout?: number;\n\n /**\n * @kosApiLevel 5\n */\n headers?: Record<string, string>;\n\n /**\n * Enable streaming mode for large responses\n * @kosApiLevel 11\n */\n stream?: boolean;\n\n /**\n * Response type hint for binary data handling\n * @kosApiLevel 11\n */\n responseType?: \"text\" | \"json\" | \"arraybuffer\" | \"blob\";\n\n /**\n * Retry configuration for transient failures.\n *\n * - `true`: enable retry with all defaults\n * - `RetryConfig`: partial overrides (unspecified fields use defaults)\n * - omitted: no retry\n *\n * Mutating methods (POST, PUT, DELETE, PATCH) are retried only when\n * `retryMutations` is `true`.\n * @kosApiLevel 22\n */\n retry?: boolean | RetryConfig;\n}\n\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport interface KosFetchResponse {\n headers: Headers;\n status: string | number | boolean;\n ok: boolean;\n json: <\n T = Record<string | number | symbol, string | number | symbol>\n >() => Promise<T>;\n body: ReadableStream<Uint8Array> | null;\n}\n\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport interface KosFetchReqeust {\n path: string;\n requestId: string;\n method: FetchMethodStrings;\n destinationAddress?: string;\n ordered?: boolean;\n tracker?: string;\n bridge?: boolean;\n /**\n * @kosApiLevel 5\n */\n headers?: Record<string, string | number | boolean>;\n}\n\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport interface KosMessageRequest\n extends Omit<KosFetchReqeust, \"method\" | \"path\" | \"requestId\"> {\n requestType: string;\n requestId?: string;\n headers?: Record<string, string>;\n}\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport interface KosBroadcastRequest {\n topic: string;\n}\n\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport interface KosMessageOptions extends KosBroadcastRequest {\n destinationAddress?: string;\n responseId?: string;\n type?: string;\n}\n\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport interface KosHttpMessageOptions {\n destinationAddress: string;\n sourceAddress: string;\n responseId: string;\n status: number;\n type: string;\n contentType?: string;\n}\n\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport interface KosFetchResponseParams {\n path: string;\n responseId?: string;\n destinationAddress: string;\n status: string | number | boolean;\n}\n\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport interface KosFetchPostReqeust extends KosFetchReqeust {\n body?: string;\n}\n","/* eslint-disable no-param-reassign */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { DependencyModels, TroubleAwareSetup } from \"./propKeys\";\n\n/**\n * @kosService core.trouble-aware\n * @kosApiLevel 13\n */\nexport interface KosTroubleAwareOptions {\n /** Path property name to use for trouble resolution. Default: 'path' */\n pathProperty?: string;\n}\n\n/**\n * Class decorator that makes a KOS model TroubleAware: it gets reactive `troubles`\n * (the troubles whose path matches the model's path), `troublesByType` and\n * `troubleStatus` (an empty string by default). The trouble container is added as a\n * dependency automatically.\n *\n * The model must expose its device path on `path`, or on the property named by\n * `pathProperty`. Declare an interface with the same name as the class that extends\n * `TroubleAware` (TypeScript interface merging) so the members are typed.\n *\n * @param options Configuration options for the decorator\n * @returns A class decorator\n *\n * @example\n * ```typescript\n * interface HolderModelImpl extends TroubleAware {}\n *\n * @kosModel(\"holder-model\")\n * @kosTroubleAware()\n * class HolderModelImpl implements IKosDataModel {\n * path: string;\n *\n * constructor(modelId: string, options: HolderOptions) {\n * this.path = options.path;\n * }\n * }\n * ```\n *\n * @category KOS Model Decorator\n * @since 2.0.0\n * @kosService core.trouble-aware\n * @kosApiLevel 13\n */\nexport function kosTroubleAware(\n options?: KosTroubleAwareOptions\n): ClassDecorator {\n return (target: any) => {\n const pathProperty = options?.pathProperty || \"path\";\n\n // Add the TroubleAwareSetup configuration to the prototype\n // This will be processed by kosModel.ts during model instantiation\n target.prototype[TroubleAwareSetup] = {\n pathProperty,\n };\n\n // Add troubleContainer as a managed dependency\n target.prototype[DependencyModels] =\n target.prototype[DependencyModels] || {};\n target.prototype[DependencyModels][\"troubleContainer\"] = {\n modelType: \"trouble-container-model\",\n id: \"trouble-container-model\", // TroubleContainer is a singleton\n options: {},\n lazy: false, // Ensure it's created immediately\n };\n\n return target;\n };\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { KosContext } from \"../context\";\nimport { ExtensionManager } from \"../extension\";\n\n/**\n * @kosService core.extension\n * @kosApiLevel 2\n */\nexport interface ExtensionPointOptions {\n extension: string;\n}\n/**\n * @kosService core.extension\n * @kosApiLevel 2\n */\nexport interface InitializeContextExtensionPointOptions\n extends ExtensionPointOptions {\n context?: KosContext;\n}\n\n/**\n * @kosService core.extension\n * @kosApiLevel 2\n */\nexport interface ContextDataExtensionPoint<D extends object, T extends object>\n extends ExtensionPointOptions {\n data: D;\n contextData: T;\n}\n/**\n * Executes an extension point and adds the value to the specified context\n * @param options The options for the extension point\n * @param options.context The KOS model context to add the value to. If not specified, the value will not be added to any context.\n * @param options.extension The extension point to execute\n *\n * @returns The value returned from the extension point\n * */\n/**\n * @kosService core.extension\n * @kosApiLevel 2\n */\nexport const executeLoaderExtension = async ({\n context,\n extension,\n}: InitializeContextExtensionPointOptions) => {\n const contextData = await ExtensionManager.loader.executeLoader(\n extension,\n {}\n );\n\n context?.set(extension, contextData);\n\n return contextData;\n};\n\n/**\n * Executes a registered data transformation extension point. This extension point is used to transform data from the backend into a format that is\n * usable by the application.\n *\n * @param options The options for the extension point\n * @param options.contextData The context data to pass to the extension point\n * @param options.data The data to transform\n * @param options.extension The extension point to execute\n * @returns The transformed data\n * */\n/**\n * @kosService core.extension\n * @kosApiLevel 2\n */\nexport const executeDataMapperExtension = async <\n D extends object = any,\n R extends object = any,\n T extends object = any\n>({\n extension,\n contextData,\n data,\n}: ContextDataExtensionPoint<D, T>) => {\n const transformed = await ExtensionManager.dataMapper.executeMapper<D, R>(\n extension,\n data,\n contextData\n );\n\n return transformed;\n};\n\n/**\n * Executes a registered data transformation extension point. This extension point is used to map a single property value and\n * is typically used to map a property value from the backend into a format that is usable by the application.\n *\n *\n * @param options The options for the extension point\n * @param options.contextData The context data to pass to the extension point\n * @param options.data The data to transform\n * @param options.extension The extension point to execute\n * @returns The transformed data\n * */\n/**\n * @kosService core.extension\n * @kosApiLevel 2\n */\nexport const executePropertyMapperExtension = async <\n D extends object = any,\n T extends object = any\n>({\n extension,\n contextData,\n data,\n}: ContextDataExtensionPoint<D, T>) => {\n const value = await ExtensionManager.propertyMapper.executeMapper(\n extension,\n data,\n contextData\n );\n\n return value;\n};\n","/**\n * @kosService core.extension\n * @kosApiLevel 2\n */\nexport const PLUGIN_EXTENSION_NAME = \"Extensions\";\n\n/**\n * Represents the type for the extensions.\n */\n/**\n * @kosService core.extension\n */\nexport interface PluginExtensionsType {\n [k: string]: {\n [k: string]: {\n component?: string;\n remote?: string;\n };\n };\n}\n/**\n * @kosService core.extension\n * @kosApiLevel 2\n */\nexport class PluginExtensionManager {\n private extensions: PluginExtensionsType;\n\n constructor() {\n this.extensions = {};\n }\n register(extensionPoint: string, name: string, component: string) {\n this.extensions[extensionPoint] = this.extensions[extensionPoint] || {};\n this.extensions[extensionPoint][name] = { component };\n }\n\n get(extension: string, id: string) {\n if (!this.extensions[extension]) {\n throw new Error(`Extension point ${extension} not found`);\n }\n return this.extensions[extension][id];\n }\n\n get allExtensions() {\n return this.extensions;\n }\n}\n","/**\n * Debounces a function so it runs once the timeout has passed since the last call.\n *\n * @param context - The context (this value) to be used when calling the debounced function.\n * @param func - The function to debounce.\n * @param timeout - The duration (in milliseconds) to wait after the last invocation before calling the function.\n * Defaults to 300 milliseconds.\n * @returns A debounced version of the provided function.\n *\n * @kosService core.utils\n * @kosApiLevel 2\n */\nfunction debounce(context: any, func: Function, timeout = 300) {\n let timer: ReturnType<typeof setTimeout>;\n\n /**\n * Returns a debounced version of the provided function.\n *\n * @param args - The arguments to pass to the debounced function.\n */\n return (...args: any) => {\n /**\n * Clears the previous timer.\n */\n clearTimeout(timer);\n\n /**\n * Sets a new timer to call the provided function after the specified timeout.\n */\n timer = setTimeout(() => {\n func.apply(context, args);\n }, timeout);\n };\n}\n\nexport default debounce;\n","/**\n * @deprecated\n * @internal\n */\nimport { warnDeprecated } from \"@kosdev-code/kos-api-levels\";\nimport { action } from \"mobx\";\nimport debounce from \"../../util/debounce\";\nimport { SubscriptionHandlers } from \"./propKeys\";\n\n/**\n * @kosService core.subscribe\n * @kosApiLevel 2\n */\nexport interface IKosSubscriptionHandlerParams<T, M> {\n topic: string;\n condition?: (payload: T, model: M) => boolean;\n handler: Function;\n websocket?: boolean;\n skipParse?: boolean;\n}\n\n/**\n * @kosService core.subscribe\n * @kosApiLevel 2\n * @kosDeprecated {replacement: @kosTopicHandler, removeAt: 3}\n */\nexport const kosSubscribe =\n <T = unknown, M = unknown>({\n topic,\n handler,\n websocket = false,\n condition = () => true,\n }: IKosSubscriptionHandlerParams<T, M>) =>\n (target: T) => {\n warnDeprecated(\"@kosSubscribe\", \"core.subscribe\", 1, \"@kosTopicHandler\", 3);\n target[SubscriptionHandlers] = target[SubscriptionHandlers] || {};\n if (Array.isArray(topic)) {\n topic.forEach((t) => {\n target[SubscriptionHandlers][t] = {\n websocket,\n handler,\n condition,\n };\n });\n } else {\n target[SubscriptionHandlers][topic] = {\n websocket,\n handler: debounce(target, action(handler), 200),\n condition,\n };\n }\n };\n","/* eslint-disable no-param-reassign */\nimport { autorun, makeAutoObservable, reaction, runInAction } from \"mobx\";\nimport { DependencyLifecycle } from \"../../types\";\nimport type { KosContextLogger } from \"../kosModel\";\nimport {\n initializeStateMachine,\n injectStateMachineSupport,\n} from \"./fsm-injection-utils\";\nimport {\n KosViewModelSymbol,\n ModelEffects,\n StateMachineSetup,\n ViewModelConfig,\n} from \"./propKeys\";\n\n/**\n * Configuration options for the @kosViewModel decorator.\n *\n * @kosService core.view-model\n * @kosApiLevel 20\n */\nexport interface KosViewModelOptions {\n /**\n * Optional type identifier for this ViewModel.\n * Used for logging, debugging, and optional DevTools registration.\n * If not provided, defaults to the class name.\n */\n typeId?: string;\n\n /**\n * When true, registers this ViewModel with KOS DevTools for inspection.\n * Default: false (ViewModels are not tracked by default)\n */\n devToolsEnabled?: boolean;\n}\n\n/**\n * Interface for ViewModels that support cleanup. `useViewModel` calls `dispose()` when\n * the ViewModel is replaced or the component unmounts.\n *\n * @kosService core.view-model\n * @kosApiLevel 20\n */\nexport interface IKosViewModelDisposable {\n dispose(): void | Promise<void>;\n}\n\n/**\n * Interface for ViewModels that require async initialization, such as waiting for the\n * models they wrap to be ready. `useViewModel` calls `ready()` after construction and\n * reports its progress through the `ready` and `error` fields of its result.\n *\n * @kosService core.view-model\n * @kosApiLevel 20\n */\nexport interface IKosViewModelReady {\n ready(): Promise<void>;\n}\n\n/**\n * Type guard to check if an object implements IKosViewModelReady.\n */\nexport function hasReadyHook(obj: unknown): obj is IKosViewModelReady {\n return (\n obj !== null &&\n typeof obj === \"object\" &&\n \"ready\" in obj &&\n typeof (obj as IKosViewModelReady).ready === \"function\"\n );\n}\n\n/**\n * Members injected by @kosLoggerAware into a ViewModel. Declare an interface with the\n * same name as the class that extends this type (TypeScript interface merging).\n *\n * @kosService core.view-model\n * @kosApiLevel 20\n */\nexport interface KosViewModelLoggerAware {\n logger: KosContextLogger;\n}\n\n/**\n * Type guard to check if an object implements IKosViewModelDisposable.\n */\nexport function isDisposable(obj: unknown): obj is IKosViewModelDisposable {\n return (\n obj !== null &&\n typeof obj === \"object\" &&\n \"dispose\" in obj &&\n typeof (obj as IKosViewModelDisposable).dispose === \"function\"\n );\n}\n\n// Counter for generating unique instance IDs\nlet viewModelCounter = 0;\n\n// Symbol for storing effect disposers on ViewModel instances\nconst ViewModelEffectDisposers = Symbol(\"ViewModelEffectDisposers\");\n\n/**\n * Checks if a ViewModel has model effects defined.\n */\nfunction hasViewModelEffects(instance: Record<string, unknown>): boolean {\n const effects = instance[ModelEffects as unknown as string];\n return !!effects && Object.keys(effects as object).length > 0;\n}\n\n/**\n * Injects model effect support into a ViewModel instance.\n * Effects are set up immediately and disposers are stored for cleanup.\n */\nfunction injectViewModelEffects(\n instance: Record<string, unknown>,\n typeId: string\n): void {\n if (!hasViewModelEffects(instance)) return;\n\n const modelEffects = instance[ModelEffects as unknown as string] as Record<\n string,\n {\n value: (...args: unknown[]) => void;\n dependencies?: (model: unknown) => unknown[];\n options?: { fireImmediately?: boolean };\n }\n >;\n\n const disposers: VoidFunction[] = [];\n\n for (const effectName of Object.keys(modelEffects)) {\n const { value, dependencies, options } = modelEffects[effectName];\n const handler = value.bind(instance);\n\n const effectHandler = () => {\n runInAction(() => handler());\n };\n\n const disposer = dependencies\n ? reaction(() => dependencies(instance), effectHandler, {\n fireImmediately: !!options?.fireImmediately,\n })\n : autorun(effectHandler);\n\n disposers.push(disposer);\n }\n\n // Store disposers for cleanup\n // configurable: true so makeAutoObservable can redefine it\n Object.defineProperty(instance, ViewModelEffectDisposers, {\n value: disposers,\n writable: false,\n enumerable: false,\n configurable: true,\n });\n\n // Cast to any for dynamic property access\n const inst = instance as unknown as Record<string, unknown>;\n const originalDispose = inst[\"dispose\"] as\n | ((...args: unknown[]) => void | Promise<void>)\n | undefined;\n\n // Create effect disposal function\n const disposeEffects = () => {\n for (const dispose of disposers) {\n try {\n dispose();\n } catch (e) {\n console.warn(\n `[kosViewModel] Failed to dispose effect for ${typeId}:`,\n e\n );\n }\n }\n };\n\n // If the instance already has a dispose method, wrap it to also dispose effects\n if (typeof originalDispose === \"function\") {\n inst[\"dispose\"] = function (this: unknown) {\n disposeEffects();\n return originalDispose.call(this);\n };\n } else {\n // Add a dispose method that cleans up effects\n inst[\"dispose\"] = disposeEffects;\n }\n}\n\n/**\n * Injects state machine support into a ViewModel instance and initializes it.\n * ViewModels have no lifecycle phases, so the FSM initializes at construction:\n * the state property holds `initial`, `isFsmInitialized` is true, and the\n * entry handler for `initial` runs once.\n * Logs a warning if initializeAt was given explicitly with a value other than\n * INIT, since it has no effect on a ViewModel.\n */\nfunction injectViewModelStateMachine(\n instance: Record<string, unknown>,\n typeId: string\n): void {\n const fsmSetup = instance[StateMachineSetup as unknown as string] as\n | {\n config: { initializeAt?: DependencyLifecycle };\n initializeAtExplicit?: boolean;\n }\n | undefined;\n if (!fsmSetup) return;\n\n const { config, initializeAtExplicit } = fsmSetup;\n\n if (\n initializeAtExplicit &&\n config.initializeAt !== DependencyLifecycle.INIT\n ) {\n console.warn(\n `[kosViewModel] ViewModel \"${typeId}\" has @kosStateMachine with ` +\n `initializeAt: ${config.initializeAt}. ViewModels do not have lifecycle phases, ` +\n `so the FSM will initialize immediately. Consider removing initializeAt or using ` +\n `@kosModel if lifecycle-aware FSM initialization is required.`\n );\n }\n\n injectStateMachineSupport(instance);\n initializeStateMachine(instance, config.initializeAt as string);\n}\n\n/**\n * Safely wraps makeAutoObservable with error handling.\n */\nfunction makeSafeObservable<T extends object>(instance: T): T {\n try {\n return makeAutoObservable(instance);\n } catch (e) {\n console.error(\"[kosViewModel] Failed to make observable:\", e);\n return instance;\n }\n}\n\n/**\n * Proxy handler for ViewModel construction.\n * Intercepts new() calls to inject observability.\n */\nconst viewModelConstructorProxy: ProxyHandler<any> = {\n construct(TargetClass, args) {\n const config = (TargetClass.prototype[ViewModelConfig] ||\n {}) as KosViewModelOptions;\n const typeId = config.typeId || TargetClass.name;\n const instanceId = `${typeId}-${++viewModelCounter}`;\n\n // Create the instance\n const instance = new TargetClass(...args);\n\n // Inject state machine support if @kosStateMachine is stacked\n injectViewModelStateMachine(instance, typeId);\n\n // Inject model effect support if @kosModelEffect is used\n injectViewModelEffects(instance, typeId);\n\n // Store metadata as non-enumerable properties for debugging\n // configurable: true so makeAutoObservable can redefine it\n Object.defineProperty(instance, \"__viewModelTypeId\", {\n value: typeId,\n writable: false,\n enumerable: false,\n configurable: true,\n });\n\n Object.defineProperty(instance, \"__viewModelInstanceId\", {\n value: instanceId,\n writable: false,\n enumerable: false,\n configurable: true,\n });\n\n // Make the instance observable\n const observableInstance = makeSafeObservable(instance);\n\n // Optional DevTools registration\n if (\n config.devToolsEnabled &&\n (globalThis as any).__KOS_DEVTOOLS__?.registerViewModel\n ) {\n (globalThis as any).__KOS_DEVTOOLS__.registerViewModel(\n instanceId,\n observableInstance\n );\n }\n\n return observableInstance;\n },\n};\n\n/**\n * Class decorator for a ViewModel: a plain class made into a reactive model without the\n * KOS model lifecycle.\n *\n * Use it for state derived from one or more KOS models for a component. Dependencies\n * are passed to the constructor, instances are created with `new` (usually inside\n * `useViewModel`), and there are no lifecycle phases or dependency resolution. A\n * ViewModel may also use @kosLoggerAware, @kosModelEffect and @kosStateMachine; its\n * state machine initializes at construction.\n *\n * @param options Configuration options for the ViewModel\n * @returns A class decorator\n *\n * @example\n * ```typescript\n * @kosViewModel({ typeId: 'order-summary' })\n * export class OrderSummaryViewModel {\n * constructor(private readonly order: IOrderModel) {}\n *\n * get total(): number {\n * return this.order.items.reduce((sum, i) => sum + i.price, 0);\n * }\n * }\n *\n * const OrderSummary = kosComponent(({ order }: Props) => {\n * const { viewModel } = useViewModel(() => new OrderSummaryViewModel(order), [order]);\n * return <p>Total: {viewModel.total}</p>;\n * });\n * ```\n *\n * @category KOS ViewModel Decorator\n * @kosService core.view-model\n * @kosApiLevel 20\n */\nexport function kosViewModel(options?: KosViewModelOptions): ClassDecorator {\n return (target: any) => {\n const config = options || {};\n const typeId = config.typeId || target.name;\n\n // Store configuration on prototype for the proxy to access\n // Use same structure as KosModelSymbol for @kosLoggerAware compatibility\n target.prototype[KosViewModelSymbol] = { type: typeId };\n target.prototype[ViewModelConfig] = config;\n\n // Preserve class name for debugging\n const ProxiedClass = new Proxy(target, viewModelConstructorProxy);\n Object.defineProperty(ProxiedClass, \"name\", { value: target.name });\n\n return ProxiedClass;\n };\n}\n","/**\n * (C) Copyright 2025, TCCC, All rights reserved.\n */\n\nimport type { IKosDataModel, IKosModel } from \"../core/kosModel\";\nimport { KosModelVisitor } from \"./kos-model-visitor\";\n\n/**\n * Visitor that finds the ids of a target model's ancestors in any KOS model\n * hierarchy that implements the visitor pattern.\n *\n * It walks the tree depth-first and tracks the current path, so when the\n * target is found the accumulated path is the ancestor list. The traversal\n * visits every model until the target is found, which suits hierarchies of\n * up to a few hundred models.\n *\n * @example\n * ```typescript\n * const visitor = new AncestorPathVisitor(\"target-item-id\");\n * visitor.start(rootContainerModel);\n * const ancestors = visitor.getAncestorPath(); // [\"root\", \"parent\"]\n * ```\n *\n * @category Core\n * @kosService core.utils\n * @kosApiLevel 20\n */\nexport class AncestorPathVisitor extends KosModelVisitor {\n private targetId: string;\n private currentPath: string[] = [];\n private foundPath: string[] | null = null;\n\n constructor(targetId: string) {\n super();\n this.targetId = targetId;\n }\n\n /**\n * Wraps the visit with path tracking: push the model, check whether it is\n * the target, visit its children, then pop it again if the target was not\n * found in this subtree.\n *\n * The base class logic is inlined rather than calling super.visit() so the\n * push and pop happen at the right points relative to cycle detection and\n * child traversal.\n */\n override visit(model: IKosModel): void {\n // Cycle detection from base class\n if (this.visitedModels.has(model.modelId)) {\n return;\n }\n\n // Push to path BEFORE processing\n this.currentPath.push(model.modelId);\n\n // Mark as visited\n this.visitedModels.add(model.modelId);\n\n // Check if this is the target\n const stopVisiting = !!this.visitModel(model.modelData);\n\n if (!stopVisiting) {\n // Visit children (depth-first)\n model.getChildren?.().forEach((child) => {\n // Early exit if target was found in a sibling subtree\n if (this.foundPath) {\n return;\n }\n child.accept?.(this);\n });\n }\n\n // Backtrack: pop from path if target not found in this subtree\n if (!this.foundPath) {\n this.currentPath.pop();\n }\n }\n\n /**\n * Called for each model during traversal.\n * Returns true to stop traversal when target is found.\n */\n visitModel<T extends IKosDataModel>(model: T): boolean | void {\n // Check if this is the target\n if (model.id === this.targetId) {\n // Save ancestor path (everything except the target itself)\n this.foundPath = this.currentPath.slice(0, -1);\n return true; // Stop traversal\n }\n\n // Continue depth-first traversal\n return false;\n }\n\n /**\n * Get the ancestor path (IDs from root to parent, not including target).\n * Returns empty array if target not found or target is at root level.\n */\n getAncestorPath(): string[] {\n return this.foundPath ?? [];\n }\n\n /**\n * Check if target was found during traversal.\n */\n wasFound(): boolean {\n return this.foundPath !== null;\n }\n}\n","/**\n * @kosService core.kos-model\n * @kosApiLevel 2\n */\nexport function applyMixins(derivedCtor: any, baseCtors: any[]) {\n baseCtors.forEach((baseCtor) => {\n Object.getOwnPropertyNames(baseCtor.prototype).forEach((name) => {\n const descriptor = Object.getOwnPropertyDescriptor(\n baseCtor.prototype,\n name\n );\n Object.defineProperty(\n derivedCtor.prototype,\n name,\n <PropertyDescriptor & ThisType<any>>descriptor\n );\n });\n });\n}\n","/**\n * @kosService core.utils\n * @kosApiLevel 5\n */\nexport function arraysEqual(_a?: any[], _b?: any[]): boolean {\n const a = _a ?? [];\n const b = _b ?? [];\n if (a.length !== b.length) return false;\n return a.every((val, index) => val === b[index]);\n}\n","const formatter = new Intl.RelativeTimeFormat(undefined, {\n numeric: \"auto\",\n});\n\nconst DIVISIONS: { amount: number; name: Intl.RelativeTimeFormatUnit }[] = [\n { amount: 60, name: \"seconds\" },\n { amount: 60, name: \"minutes\" },\n { amount: 24, name: \"hours\" },\n { amount: 7, name: \"days\" },\n { amount: 4.34524, name: \"weeks\" },\n { amount: 12, name: \"months\" },\n { amount: Number.POSITIVE_INFINITY, name: \"years\" },\n];\n\n/**\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport function formatDateSince(date: Date) {\n let duration = (date.getTime() - Date.now()) / 1000;\n\n for (let i = 0; i <= DIVISIONS.length; i++) {\n const division = DIVISIONS[i];\n if (Math.abs(duration) < division.amount) {\n return formatter.format(Math.round(duration), division.name);\n }\n duration /= division.amount;\n }\n return formatter.format(Math.round(duration), \"years\");\n}\n\n/**\n * @kosService core.utils\n * @kosApiLevel 3\n */\nexport const isLeapYear = (year: number): boolean =>\n (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;\n\n/**\n * @kosService core.utils\n * @kosApiLevel 3\n */\nexport const getDaysInMonth = (year: number, month: number): number =>\n [31, isLeapYear(year) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][\n month\n ];\n\n/**\n * @kosService core.utils\n * @kosApiLevel 3\n */\nexport const addMonthsToDate = (date: Date, value: number) => {\n const d = new Date(date),\n n = date.getDate();\n d.setDate(1);\n d.setMonth(d.getMonth() + value);\n d.setDate(Math.min(n, getDaysInMonth(d.getFullYear(), d.getMonth())));\n return d;\n};\n\n/**\n * @kosService core.utils\n * @kosApiLevel 3\n */\nexport const addDaysToDate = (date: Date, value: number) => {\n const d = new Date(date);\n d.setDate(d.getDate() + value);\n return d;\n};\n\nconst DEFAULT_LOCALE = \"en-US\";\n\ninterface FormatDateOptions {\n dateStyle?: \"short\" | \"medium\" | \"long\" | \"full\";\n locales?: string | string[];\n}\n\ninterface FormatTimeOptions {\n timeStyle?: \"short\" | \"medium\" | \"long\" | \"full\";\n locales?: string | string[];\n}\n\ninterface FormatDateTimeOptions extends FormatDateOptions, FormatTimeOptions {}\n\ninterface FormatOptions {\n year?: \"numeric\" | \"2-digit\";\n month?: \"short\" | \"long\" | \"numeric\" | \"2-digit\" | \"narrow\";\n day?: \"numeric\" | \"2-digit\";\n weekday?: \"short\" | \"long\" | \"narrow\";\n hour?: \"numeric\" | \"2-digit\";\n minute?: \"numeric\" | \"2-digit\";\n second?: \"numeric\" | \"2-digit\";\n hour12?: boolean;\n timeZoneName?:\n | \"short\"\n | \"long\"\n | \"shortOffset\"\n | \"longOffset\"\n | \"shortGeneric\"\n | \"longGeneric\";\n}\n\nconst dateStyleMap: Record<\n NonNullable<FormatDateTimeOptions[\"dateStyle\"]>,\n Partial<FormatOptions>\n> = {\n short: { year: \"numeric\", month: \"2-digit\", day: \"2-digit\" },\n medium: { year: \"numeric\", month: \"short\", day: \"2-digit\" },\n long: { year: \"numeric\", month: \"long\", day: \"numeric\" },\n full: {\n year: \"numeric\",\n month: \"long\",\n day: \"numeric\",\n weekday: \"long\",\n },\n};\n\nconst timeStyleMap: Record<\n NonNullable<FormatDateTimeOptions[\"timeStyle\"]>,\n Partial<FormatOptions>\n> = {\n short: { hour: \"2-digit\", minute: \"2-digit\", hour12: true },\n medium: {\n hour: \"2-digit\",\n minute: \"2-digit\",\n second: \"2-digit\",\n hour12: true,\n },\n long: {\n hour: \"2-digit\",\n minute: \"2-digit\",\n second: \"2-digit\",\n hour12: true,\n timeZoneName: \"short\",\n },\n full: {\n hour: \"2-digit\",\n minute: \"2-digit\",\n hour12: true,\n timeZoneName: \"long\",\n },\n};\n\n/**\n * Formats a date with `Intl.DateTimeFormat` according to `dateStyle` and locale.\n *\n * `\"short\"` uses a numeric year with two-digit month and day in the locale's\n * order (`12/31/2025` in en-US); the other styles use the built-in `Intl` styles.\n *\n * @param date - The date object or timestamp to format.\n * @param options - Options to customize formatting.\n * @param options.dateStyle - One of `\"short\"`, `\"medium\"`, `\"long\"`, or `\"full\"`.\n * @param options.locales - Optional locale string or array of locale strings.\n * @returns A formatted date string.\n *\n * @kosService core.utils\n * @kosApiLevel 3\n */\n\nexport const formatDate = (\n date?: Date | number,\n { dateStyle = \"short\", locales = DEFAULT_LOCALE }: FormatDateOptions = {\n dateStyle: \"short\",\n locales: DEFAULT_LOCALE,\n }\n) => {\n const options = dateStyle === \"short\" ? dateStyleMap.short : { dateStyle }; // Let Intl handle medium/long/full\n return new Intl.DateTimeFormat(locales, options).format(date);\n};\n\n/**\n * Formats a time with `Intl.DateTimeFormat` according to `timeStyle` and\n * locale. All styles use a 12-hour clock; `\"medium\"` and `\"long\"` add seconds,\n * and `\"long\"` and `\"full\"` add the time zone name.\n *\n * @param date - The date object or timestamp to extract the time from.\n * @param options - Options to customize time formatting.\n * @param options.timeStyle - One of `\"short\"`, `\"medium\"`, `\"long\"`, or `\"full\"`.\n * @param options.locales - Optional locale string or locale array.\n * @returns A formatted time string.\n *\n * @kosService core.utils\n * @kosApiLevel 3\n */\n\nexport const formatTime = (\n date?: Date | number,\n { locales = DEFAULT_LOCALE, timeStyle = \"short\" }: FormatTimeOptions = {\n locales: DEFAULT_LOCALE,\n timeStyle: \"short\",\n }\n) => {\n const options = timeStyleMap[timeStyle];\n return new Intl.DateTimeFormat(locales, options).format(date);\n};\n\n/**\n * Formats a date and time in one string with `Intl.DateTimeFormat`. It takes\n * the same `dateStyle` and `timeStyle` names as {@link formatDate} and\n * {@link formatTime}; both default to `\"short\"` (`12/31/2025, 11:59 PM` in en-US).\n *\n * @param date - The `Date` object or timestamp to format.\n * @param options - Formatting options.\n * @param options.dateStyle - Custom date format: `\"short\"`, `\"medium\"`, `\"long\"`, or `\"full\"`.\n * @param options.timeStyle - Custom time format: `\"short\"`, `\"medium\"`, `\"long\"`, or `\"full\"`.\n * @param options.locales - Optional locale string or locale array.\n * @returns A string representing the formatted date and/or time.\n *\n * @kosService core.utils\n * @kosApiLevel 3\n */\n\nexport const formatDateTime = (\n date?: Date | number,\n {\n dateStyle = \"short\",\n locales = DEFAULT_LOCALE,\n timeStyle = \"short\",\n }: FormatDateTimeOptions = {\n dateStyle: \"short\",\n locales: DEFAULT_LOCALE,\n timeStyle: \"short\",\n }\n) => {\n const options: FormatOptions = {\n ...(dateStyle && dateStyleMap[dateStyle]),\n ...(timeStyle && timeStyleMap[timeStyle]),\n };\n return new Intl.DateTimeFormat(locales, options).format(date);\n};\n","/**\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport const hslToHex = (h: number, s: number, l: number) => {\n l /= 100;\n const a = (s * Math.min(l, 1 - l)) / 100;\n const f = (n) => {\n const k = (n + h / 30) % 12;\n const color = l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);\n return Math.round(255 * color)\n .toString(16)\n .padStart(2, \"0\"); // convert to Hex and prefix \"0\" if needed\n };\n return `#${f(0)}${f(8)}${f(4)}`;\n};\n\n/**\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport const hslStringToHex = (hsl: string) => {\n const reg = new RegExp(\"hsl\\\\((\\\\d+),\\\\s+(\\\\d+)\\\\%,\\\\s+(\\\\d+)\\\\%\\\\)\");\n const match = reg.exec(hsl);\n if (!match) {\n throw Error(\"Invalid HSL string\");\n }\n return hslToHex(parseInt(match[1]), parseInt(match[2]), parseInt(match[3]));\n};\n\n/**\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport const resolveVariable = (element: Element, variable: string) =>\n getComputedStyle(element).getPropertyValue(variable);\n/**\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport const variableToHex = (element: Element, variable: string) =>\n hslStringToHex(resolveVariable(element, variable));\n","/**\n * @kosService core.middleware\n */\nexport type Middleware<\n D extends object = Record<string, ScalarValue>,\n R extends object = Record<string, ScalarValue>\n> = (context: Context<D, R>, next: () => Promise<void>) => Promise<void>;\n\n/**\n * @kosService core.middleware\n * @kosApiLevel 2\n */\nexport interface Context<\n D extends object = Record<string, ScalarValue>,\n R extends object = Record<string, ScalarValue>\n> {\n data: D;\n result: Partial<R>;\n}\n\ntype ScalarValue = string | number | boolean | null | undefined;\n/**\n * @kosService core.middleware\n * @kosApiLevel 2\n */\nexport class MiddlewareChain<\n D extends object = Record<string, ScalarValue>,\n R extends object = Record<string, ScalarValue>,\n T extends Context<D, R> = Context<D, R>\n> {\n private middlewares: Middleware<D, R>[] = [];\n\n use(middleware: Middleware<D, R>): void {\n this.middlewares.push(middleware);\n }\n\n async execute(context: T): Promise<void> {\n let index = 0;\n\n const next = async (): Promise<void> => {\n index++;\n if (index < this.middlewares.length) {\n await this.middlewares[index](context, next);\n }\n };\n\n await this.middlewares[index](context, next);\n }\n}\n\n/**\n * @kosService core.middleware\n * @kosApiLevel 2\n */\nexport const processMiddleware = async <\n D extends object = Record<string, ScalarValue>,\n R extends object = Record<string, ScalarValue>\n>(\n data: D,\n middleware: Middleware<D, R>[]\n) => {\n const chain = new MiddlewareChain<D, R>();\n middleware.forEach((m) => chain.use(m));\n\n const context: Context<D, R> = { data, result: {} as R };\n await chain.execute(context);\n return context.result as R;\n};\n","import { KosCore } from \"../core/kosCore\";\nimport type { KosCompanionModelType } from \"../core/types/registration\";\nimport type { BaseKosModelRegistrationBean } from \"../types/model\";\n\n/**\n * @kosService core.kos-model\n * @kosApiLevel 2\n */\nexport const updateModelRegistration = <\n T extends BaseKosModelRegistrationBean<any, any>\n>(\n modelRegistration: T\n): void => {\n KosCore.getInstance().modelManager.registerModel(modelRegistration);\n};\n\n/**\n * @kosService core.kos-model\n * @kosApiLevel 2\n */\nexport const updateCompanionModelRegistration = (\n typeId: string,\n companionRegistration: KosCompanionModelType<any>\n): void => {\n KosCore.getInstance().modelManager.registerCompanionModel(\n typeId,\n companionRegistration\n );\n};\n","import { KosCore } from \"../core/kosCore\";\nimport { sendKosMessageResponse } from \"./kos-message-utils\";\n\nconst TOPIC = \"/kos/ui/internal/heartbeat/\";\n\ninterface HeartbeatOptions {\n // An ID to identify the pairing between the two clients.\n relationshipId: string;\n // The websocket client ID that the active one should pair with.\n destinationAddress: string;\n // A function called if the pairing is aborted.\n onAbort?: () => void;\n // By default the utlity will emit a beat every 2000 miliseconds. Use this\n // to change that.\n beatTime?: number;\n // By default the utlity will wait 3 seconds without a beat from the paired client\n // before aborting. Use this to change that.\n waitTime?: number;\n}\n\n/**\n * Sets up a connection between two clients such that\n * if one is closed, the other is notified of its closure.\n *\n * @category Utility\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport const pairedClientHeartbeat = ({\n relationshipId,\n destinationAddress,\n onAbort,\n waitTime,\n beatTime,\n}: HeartbeatOptions) => {\n const transport = KosCore.getInstance().transport;\n\n // Create an abort controller so we can cancel any requests that depend\n // on both clients being open (e.g in the case where one client is waiting for a response from another)\n const controller = new AbortController();\n\n let lastHeartBeat: number = performance.now();\n\n // Subscribe to the client heartbeat topic using the intent reponse id.\n const unsubscribe = transport.subscribeTopic({\n topic: `${TOPIC}${relationshipId}`,\n callback: () => {\n lastHeartBeat = performance.now();\n },\n });\n\n const _waitTime = waitTime ?? 3000;\n\n // If the last heartbeat was more than 5 seconds ago, abort the operation.\n const waitInterval = window.setInterval(() => {\n let timeDiff = performance.now() - lastHeartBeat;\n timeDiff = timeDiff / 1000;\n\n if (timeDiff > _waitTime / 1000) {\n controller.abort();\n }\n // Check that the last pulse was within the last 3 seconds.\n }, _waitTime);\n\n const _beatTime = beatTime ?? 2000;\n\n const beatInterval = window.setInterval(() => {\n sendKosMessageResponse({\n msg: {},\n options: {\n topic: `${TOPIC}${relationshipId}`,\n destinationAddress,\n },\n });\n }, _beatTime);\n\n const cleanUpHeartbeat = () => {\n window.clearInterval(beatInterval);\n window.clearInterval(waitInterval);\n unsubscribe();\n };\n\n const handleAbort = () => {\n cleanUpHeartbeat();\n if (onAbort) {\n onAbort();\n }\n controller.signal.removeEventListener(\"abort\", handleAbort);\n };\n\n controller.signal.addEventListener(\"abort\", handleAbort);\n\n return { cleanUpHeartbeat };\n};\n","import { KosLog } from \"../core/log\";\n\ninterface BackoffOptions {\n /** the maximum number of attempts to make */\n maxAttempts: number;\n\n /** the base delay (in ms) between attempts */\n baseDelayMs: number;\n\n /** the factor by which to increase the delay with each attempt */\n backoffFactor: number;\n}\n/**\n * Default backoff options.\n */\nconst BASE_OPTIONS: BackoffOptions = {\n maxAttempts: 5,\n baseDelayMs: 100,\n backoffFactor: 1.5,\n};\n\n/**\n * Provides exponential backoff for a given operation.\n * @param operation - the async operation to perform\n * @param options - optional backoff options\n * @returns - the result of the operation if successful\n * @throws - the last error if all attempts fail\n *\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport async function retryWithExponentialBackoff<T>(\n operation: () => Promise<T>,\n options?: Partial<BackoffOptions>\n): Promise<T> {\n let attempt = 1;\n const _options = { ...BASE_OPTIONS, ...options };\n const { maxAttempts, baseDelayMs, backoffFactor } = _options;\n let delayMs = baseDelayMs;\n\n while (attempt <= maxAttempts) {\n try {\n const result = await operation();\n return result; // If the operation succeeds, return the result\n } catch (error) {\n KosLog.error(`Attempt ${attempt} failed: ${error}`);\n\n if (attempt < maxAttempts) {\n // Exponential backoff: increase the delay exponentially with each attempt\n delayMs = baseDelayMs * Math.pow(backoffFactor, attempt);\n await new Promise((resolve) => setTimeout(resolve, delayMs));\n attempt++;\n } else {\n throw error; // If all attempts fail, re-throw the error\n }\n }\n }\n\n // If we reach this point, all attempts have failed, so reject with the last error\n throw new Error(\"All attempts failed\");\n}\n","import type {\n ApiPath,\n HttpMethod,\n} from \"../core/decorators/kos-service-request\";\nimport type { IKosDataModel } from \"../core/kosModel\";\n\n/**\n * Helpers for reading and clearing the responses that `@kosServiceRequest`\n * methods cache on a model. Responses are keyed by HTTP method and the\n * resolved request path.\n */\n\n/**\n * Returns the response data a `@kosServiceRequest` method cached for the given\n * path and method. The return type defaults to `any`; pass a type parameter to\n * type the result. For a path with parameters, pass the resolved path.\n *\n * @param model - The KOS model instance\n * @param path - The API path constant\n * @param method - The HTTP method (defaults to 'get')\n * @returns The cached response data, or undefined if not found/expired\n *\n * @kosService core.service-response\n *\n * @example\n * ```typescript\n * const status = getServiceResponse<DeviceStatus>(this, PATH_DEVICE_STATUS);\n * ```\n * @kosApiLevel 15\n */\nexport function getServiceResponse<T = any>(\n model: IKosDataModel,\n path: ApiPath,\n method: HttpMethod = \"get\"\n): T | undefined {\n const store = (model as any).serviceResponses;\n if (!store) {\n return undefined;\n }\n\n return store.getByPath(path, method);\n}\n\n/**\n * Checks whether an unexpired cached response exists for the given path and method.\n *\n * @param model - The KOS model instance\n * @param path - The API path constant\n * @param method - The HTTP method (defaults to 'get')\n * @returns true if a valid cached response exists\n *\n * @kosService core.service-response\n * @kosApiLevel 15\n */\nexport function hasCachedResponse(\n model: IKosDataModel,\n path: ApiPath,\n method: HttpMethod = \"get\"\n): boolean {\n const store = (model as any).serviceResponses;\n if (!store) {\n return false;\n }\n\n return store.has(`${method.toUpperCase()}:${path}`);\n}\n\n/**\n * Clears the cached response for one path and method.\n *\n * @param model - The KOS model instance\n * @param path - The API path constant\n * @param method - The HTTP method (defaults to 'get')\n *\n * @kosService core.service-response\n * @kosApiLevel 15\n */\nexport function clearServiceResponse(\n model: IKosDataModel,\n path: ApiPath,\n method: HttpMethod = \"get\"\n): void {\n const store = (model as any).serviceResponses;\n if (!store) {\n return;\n }\n\n store.delete(`${method.toUpperCase()}:${path}`);\n}\n\n/**\n * Clears the cached responses for a path across all HTTP methods.\n *\n * @param model - The KOS model instance\n * @param path - The API path constant\n *\n * @kosService core.service-response\n * @kosApiLevel 15\n */\nexport function clearPath(model: IKosDataModel, path: ApiPath): void {\n const store = (model as any).serviceResponses;\n if (!store) {\n return;\n }\n\n store.clearPath(path);\n}\n\n/**\n * Clears every cached service response on the model.\n *\n * @param model - The KOS model instance\n *\n * @kosService core.service-response\n * @kosApiLevel 15\n */\nexport function clearAllServiceResponses(model: IKosDataModel): void {\n const store = (model as any).serviceResponses;\n if (!store) {\n return;\n }\n\n store.clear();\n}\n","import log from \"loglevel\";\nimport { EventBus } from \"../../common\";\n\nimport { uuid } from \"./api-request-id\";\nimport { KosServiceResponse } from \"./kos-fetch\";\n\n/**\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport interface ErrorResponse {\n error?: string;\n}\n\n/**\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport const waitForRequest = async <ResponseType extends ErrorResponse>(\n requestId: string,\n timeout = 60000\n) =>\n new Promise<ResponseType>((resolve, reject) => {\n const { unsubscribe } = EventBus.subscribe(requestId, (op) => {\n log.debug(`recieved response for refId ${requestId}: ${op}`);\n unsubscribe();\n clearTimeout(cancel);\n try {\n const body: ResponseType = op?.body ? JSON.parse(op.body) : {};\n resolve(body);\n } catch {\n const body = (op?.body as unknown) || {};\n resolve(body as ResponseType);\n }\n });\n\n const cancel = setTimeout(() => {\n unsubscribe();\n reject(Error(`Request with ID ${requestId} timed out. Cancelling.`));\n }, timeout);\n });\n\n/**\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport const sendRequest = async <R, T extends KosServiceResponse<any>>(\n requestPromise: (param: R) => Promise<T | undefined>,\n params: R,\n refId: string\n) => {\n const op = waitForRequest(refId);\n const result = await Promise.allSettled([requestPromise(params), op]);\n\n if (result[0].status === \"fulfilled\") {\n if (result[1].status === \"rejected\") {\n throw Error(result[1].reason);\n } else {\n if (result[0].value) {\n if (result[1].value.error) {\n throw Error(result[1].value.error);\n }\n result[0].value.data = result[1].value;\n return result[0].value;\n }\n }\n } else {\n throw Error(result[0].reason);\n }\n return undefined;\n};\n\ninterface SyncPublishParams<T> {\n topic: string;\n msg: T;\n requestId?: string;\n}\n/**\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport const syncPublish = async <T, R extends ErrorResponse>({\n topic,\n msg,\n requestId,\n}: SyncPublishParams<T>) => {\n const _requestId = requestId ?? uuid();\n const responsePromise = waitForRequest<R>(_requestId);\n EventBus.publish(topic, msg, { sync: _requestId });\n const response = await responsePromise;\n if (response.error) {\n throw Error(response.error);\n }\n return response;\n};\n","/* eslint-disable no-param-reassign */\n/**\n * Item-level decorator that makes a model contribute to the kos-ui-sdk\n * container indexing system.\n *\n * It installs an accessor at `INDEX_RECORD_SYMBOL` that returns the\n * instance's current index record (`KosModelContainer` reads it when\n * publishing ADDED, and containers re-read it on REQUEST_SEED), and a model\n * effect that publishes CHANGED when one of the declared `fields` changes.\n *\n * @kosService core.indexing\n * @kosApiLevel 22\n */\n\nimport * as EventBus from \"../../../common/events/eventBus\";\nimport { KosContextManager } from \"../context/kos-context-manager\";\nimport { ModelEffects } from \"../decorators/propKeys\";\n\nimport { KosContainerIndexEvents } from \"./topics\";\nimport {\n INDEX_COLLECTION_KEY,\n INDEX_RECORD_SYMBOL,\n type IndexChangedEvent,\n type IndexRecordContribution,\n} from \"./types\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Options\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface KosIndexAwareOptions {\n /**\n * Per-item collection tag. May be:\n *\n * - A static string.\n * - A function called with the instance, returning the tag\n * (heterogeneous case where one container holds items belonging\n * to multiple collections, distinguished by some item property).\n * - Undefined: the item resolves its collection from its\n * `KosContext`, walking up the parent chain. Under a\n * `@kosContainerIndexAware` container that declares a collection,\n * this picks up the container's value.\n */\n collection?: string | ((self: any) => string | undefined);\n\n /**\n * Field names projected into the index record and watched for\n * change. Empty/absent means no CHANGED events are emitted; the\n * record still exposes `id`, `modelType`, and `collection`.\n */\n fields?: string[];\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Companion interface for TS interface merging\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Merge this interface into a `@kosIndexAware` model class\n * (`interface MyItemModelImpl extends KosIndexAware {}`) to type the\n * index record accessor.\n */\nexport interface KosIndexAware {\n readonly [INDEX_RECORD_SYMBOL]: IndexRecordContribution;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Decorator\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Class decorator that registers a model as a publisher of index\n * records.\n *\n * The record always carries the instance's `id` and `modelTypeId`, plus the\n * resolved collection and the declared `fields`.\n *\n * @example\n * ```ts\n * interface VirtualMachineModelImpl extends KosIndexAware {}\n *\n * @kosModel(\"virtual-machine-model\")\n * @kosIndexAware({ collection: (self) => self.type, fields: [\"name\"] })\n * class VirtualMachineModelImpl implements IKosDataModel { ... }\n * ```\n *\n * @category KOS Model Decorator\n * @kosService core.indexing\n * @kosApiLevel 22\n */\nexport function kosIndexAware(options?: KosIndexAwareOptions): ClassDecorator {\n return (target: any) => {\n const collection = options?.collection;\n const fields = options?.fields ?? [];\n\n installRecordAccessor(target, collection, fields);\n if (fields.length > 0) {\n installChangeEffect(target, fields);\n }\n\n return target;\n };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Helpers\n// ─────────────────────────────────────────────────────────────────────────────\n\nfunction installRecordAccessor(\n target: any,\n collection: KosIndexAwareOptions[\"collection\"],\n fields: string[]\n): void {\n Object.defineProperty(target.prototype, INDEX_RECORD_SYMBOL, {\n get(): IndexRecordContribution {\n const record: IndexRecordContribution = {\n id: this.id,\n modelType: this.modelTypeId,\n };\n const resolved =\n typeof collection === \"function\" ? collection(this) : collection;\n // Fall back to the inherited context value when the item\n // declared nothing of its own. `KosContextManager.getContext`\n // looks up the bean by id; `.get` auto-walks the parent chain,\n // so a container-declared collection is visible here without\n // any explicit plumbing.\n const inherited =\n resolved === undefined\n ? (KosContextManager.getContext(this.id)?.get(\n INDEX_COLLECTION_KEY\n ) as string | undefined)\n : undefined;\n const finalCollection = resolved ?? inherited;\n if (finalCollection !== undefined) {\n record.collection = finalCollection;\n }\n for (const field of fields) {\n record[field] = this[field];\n }\n return record;\n },\n enumerable: false,\n configurable: true,\n });\n}\n\nfunction installChangeEffect(target: any, fields: string[]): void {\n target.prototype[ModelEffects] = target.prototype[ModelEffects] || {};\n target.prototype[ModelEffects].handleIndexFieldChange = {\n dependencies: (model: any) => fields.map((field) => model[field]),\n value: function (this: any) {\n const record: IndexRecordContribution = this[INDEX_RECORD_SYMBOL];\n // Skip if no collection resolved — neither item-declared nor\n // inherited from a container's context. Without a collection\n // the consumer can't route the record.\n if (!record.collection) {\n return;\n }\n const payload: IndexChangedEvent = {\n record: record as IndexChangedEvent[\"record\"],\n };\n EventBus.publish(KosContainerIndexEvents.CHANGED, payload);\n },\n };\n}\n","/* eslint-disable no-param-reassign */\n/**\n * Container-level decorator for the kos-ui-sdk container indexing system.\n * Works with `@kosContainerAware` or `@kosChild`-based containers; it needs\n * only an `itemsProperty` naming the array of items the container exposes.\n *\n * - On `init`, writes the declared collection onto the container's\n * `KosContext`, where items resolve it by walking up the parent chain.\n * - On `KosContainerIndexEvents.REQUEST_SEED`, publishes one SEED event with\n * the records of the current items, so consumers can subscribe at any time.\n * - On `unload`, publishes one PURGE per distinct collection in the current\n * items so consumers can drop those records.\n *\n * ADDED and REMOVED events come from `KosModelContainer` itself at the moment\n * of mutation.\n *\n * @kosService core.indexing\n * @kosApiLevel 22\n */\n\nimport * as EventBus from \"../../../common/events/eventBus\";\nimport type { KosContext } from \"../context/kos-context-manager\";\nimport { SubscriptionHandlers } from \"../decorators/propKeys\";\n\nimport { KosContainerIndexEvents } from \"./topics\";\nimport {\n INDEX_COLLECTION_KEY,\n INDEX_RECORD_SYMBOL,\n isIndexableItem,\n type IndexPurgeEvent,\n type IndexRecord,\n type IndexRecordContribution,\n type IndexSeedEvent,\n} from \"./types\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Options\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface KosContainerIndexAwareOptions {\n /**\n * Name of the property on the container that exposes its items\n * as an array, such as the `data` getter from `@kosContainerAware` or a\n * custom getter on a `@kosChild`-managed collection. Used for SEED and\n * PURGE; ADDED and REMOVED do not depend on it.\n */\n itemsProperty: string;\n\n /**\n * Collection tag written onto the container's own `KosContext`\n * so child items inherit it. Optional when items declare their own\n * `collection` through `@kosIndexAware`.\n */\n collection?: string;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Decorator\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Class decorator that wires a container model into the kos-ui-sdk\n * indexing system.\n *\n * @example\n * ```ts\n * @kosModel(\"image-container-model\")\n * @kosContainerAware<IImageModel>()\n * @kosContainerIndexAware({ itemsProperty: \"data\", collection: \"images\" })\n * class ImageContainerModelImpl implements IKosDataModel { ... }\n * ```\n *\n * @category KOS Model Decorator\n * @kosService core.indexing\n * @kosApiLevel 22\n */\nexport function kosContainerIndexAware(\n options: KosContainerIndexAwareOptions\n): ClassDecorator {\n return (target: any) => {\n const itemsProperty = options.itemsProperty;\n const declaredCollection = options.collection;\n\n installContextWriter(target, declaredCollection);\n installRequestSeedHandler(target, itemsProperty);\n installPurgeOnUnload(target, itemsProperty);\n\n return target;\n };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Helpers\n// ─────────────────────────────────────────────────────────────────────────────\n\nfunction installContextWriter(\n target: any,\n declaredCollection: string | undefined\n): void {\n if (declaredCollection === undefined) return;\n\n const originalInit = target.prototype.init;\n target.prototype.init = async function (context?: KosContext) {\n context?.set(INDEX_COLLECTION_KEY, declaredCollection);\n if (originalInit) {\n await originalInit.call(this, context);\n }\n };\n}\n\nfunction installRequestSeedHandler(target: any, itemsProperty: string): void {\n target.prototype[SubscriptionHandlers] =\n target.prototype[SubscriptionHandlers] || {};\n target.prototype[SubscriptionHandlers][KosContainerIndexEvents.REQUEST_SEED] =\n {\n websocket: false,\n skipParse: true,\n // The subscription manager calls transform(body) before\n // condition/handler. For an internal EventBus event with a\n // plain object payload we just want to pass it through\n // untouched.\n transform: (payload: unknown) => payload,\n condition: () => true,\n handler: function (this: any) {\n const items = (this[itemsProperty] ?? []) as unknown[];\n const records = collectRecords(items);\n if (records.size === 0) return;\n const payload: IndexSeedEvent = {\n modelType: this.modelTypeId,\n items: Array.from(records.values()),\n };\n EventBus.publish(KosContainerIndexEvents.SEED, payload);\n },\n };\n}\n\nfunction installPurgeOnUnload(target: any, itemsProperty: string): void {\n const originalUnload = target.prototype.unload;\n target.prototype.unload = function (context?: KosContext) {\n const items = (this[itemsProperty] ?? []) as unknown[];\n const collections = new Set<string>();\n for (const item of items) {\n if (!isIndexableItem(item)) continue;\n const contribution: IndexRecordContribution = item[INDEX_RECORD_SYMBOL];\n if (contribution.collection) {\n collections.add(contribution.collection);\n }\n }\n for (const collection of collections) {\n const payload: IndexPurgeEvent = {\n modelType: this.modelTypeId,\n collection,\n };\n EventBus.publish(KosContainerIndexEvents.PURGE, payload);\n }\n if (originalUnload) {\n return originalUnload.call(this, context);\n }\n return undefined;\n };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Record collection (shared with the request-seed handler)\n// ─────────────────────────────────────────────────────────────────────────────\n\nfunction collectRecords(items: unknown[]): Map<string, IndexRecord> {\n const result = new Map<string, IndexRecord>();\n for (const item of items) {\n if (!isIndexableItem(item)) continue;\n const contribution: IndexRecordContribution = item[INDEX_RECORD_SYMBOL];\n if (!contribution.collection) continue;\n result.set(contribution.id, contribution as IndexRecord);\n }\n return result;\n}\n","import {\n IdentifiableModelFactory,\n KosIdentifiableModelRegistration,\n KosModelClassRegistration,\n KosSingletonModelClassRegistration,\n SingletonFactory,\n} from \"../types\";\nimport { isKosModel } from \"../util\";\nimport { Kos } from \"./kos-model-factory\";\nimport type { IKosDataModel, KosCreationContext } from \"./kosModel\";\n\ntype IdentifiableChildRegistration<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> = KosModelClassRegistration<T, O> & {\n singleton: false;\n factory: IdentifiableModelFactory<T, O>;\n};\n\ntype SingletonChildRegistration<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> = KosSingletonModelClassRegistration<T, O> & {\n singleton: true;\n factory: SingletonFactory<T, O>;\n};\n\ntype _ChildRegistration<\n T extends IKosDataModel = any,\n O extends object = Record<string, any>\n> = IdentifiableChildRegistration<T, O> | SingletonChildRegistration<T, O>;\n\ntype Reg<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> = KosIdentifiableModelRegistration<T, O> & {\n singleton: false;\n factory: IdentifiableModelFactory<T, O>;\n};\ninterface ModelRegistration<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> {\n [k: string]: Reg<T, O>;\n}\ninterface RegistrationProps<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> {\n type: string;\n model: new (modelId: string, options: O, context: KosCreationContext) => T;\n childRegistration?: any;\n}\nexport class KosRegistration<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> {\n type: string;\n childRegistration?: any;\n model: new (modelId: string, options: O, context: KosCreationContext) => T;\n constructor({ type, model, childRegistration }: RegistrationProps<T, O>) {\n this.type = type;\n this.model = model;\n this.childRegistration = childRegistration;\n }\n\n get factory() {\n return Kos.Factory.create<T, O>(this.type);\n }\n\n get registration(): ModelRegistration<T, O> {\n return {\n [this.type]: {\n class: this.model,\n singleton: false,\n factory: this.factory,\n },\n ...this.childRegistration,\n } as ModelRegistration<T, O>;\n }\n\n get predicate() {\n return isKosModel<T>(this.type);\n }\n}\n","import {\n IdentifiableModelFactory,\n KosIdentifiableModelRegistration,\n KosSingletonModelClassRegistration,\n SingletonFactory,\n} from \"../types\";\nimport { isKosModel } from \"../util\";\nimport { Kos } from \"./kos-model-factory\";\nimport type { IKosDataModel, KosCreationContext } from \"./kosModel\";\n\ntype IdentifiableChildRegistration<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> = KosIdentifiableModelRegistration<T, O> & {\n factory: IdentifiableModelFactory<T, O>;\n};\n\ntype SingletonChildRegistration<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> = KosSingletonModelClassRegistration<T, O> & {\n factory: SingletonFactory<T, O>;\n};\n\ntype _ChildRegistration<\n T extends IKosDataModel = any,\n O extends object = Record<string, any>\n> = IdentifiableChildRegistration<T, O> | SingletonChildRegistration<T, O>;\n\ntype Reg<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> = KosSingletonModelClassRegistration<T, O> & {\n factory: SingletonFactory<T, O>;\n};\ninterface Singleton<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> {\n [k: string]: Reg<T, O>;\n}\n\ninterface RegistrationProps<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> {\n type: string;\n model: new (modelId: string, options: O, context: KosCreationContext) => T;\n childRegistration?: any;\n}\nexport class KosSingletonRegistration<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> {\n type: string;\n model: new (modelId: string, options: O, context: KosCreationContext) => T;\n childRegistration?: any;\n constructor({ type, model, childRegistration }: RegistrationProps<T, O>) {\n this.type = type;\n this.model = model;\n this.childRegistration = childRegistration;\n }\n\n get factory() {\n return Kos.Singleton.create<T, O>(this.type);\n }\n\n get registration(): Singleton<T, O> {\n return {\n [this.type]: {\n class: this.model,\n singleton: true,\n factory: this.factory,\n },\n ...this.childRegistration,\n } as Singleton<T, O>;\n }\n\n get predicate() {\n return isKosModel<T>(this.type);\n }\n}\n","import { makeAutoObservable } from \"mobx\";\nimport { EventBus } from \"../../../../common\";\n\nexport interface IKosToken {\n token?: string;\n}\nclass KosToken implements IKosToken {\n private _token?: string;\n constructor() {\n makeAutoObservable(this);\n EventBus.subscribe(\"token\", (token) => {\n this.token = token?.body;\n });\n }\n\n get token() {\n return this._token;\n }\n\n set token(token) {\n this._token = token;\n }\n}\n\nexport default KosToken;\n","/* eslint-disable no-param-reassign */\nimport { DependencyLifecycle, DependencyModels } from \"../../core\";\nimport { ConfigBean } from \"../models/config-bean\";\nimport { configBeanModelId } from \"../models/config-bean/config-bean-model\";\n\ninterface KosConfigParams {\n path: string;\n lazy?: boolean;\n serviceBasePath?: string;\n /**\n * Connection the bean's requests and topic subscription are routed to.\n * Accepts a prop key so a host model can bind it per device.\n * When set, the bean's model id includes it so beans never collide across devices.\n */\n destinationAddress?: string;\n}\n\nexport const kosConfigBean =\n ({ path, lazy, serviceBasePath, destinationAddress }: KosConfigParams) =>\n (target: {} | any, name: PropertyKey): any => {\n target[DependencyModels] = target[DependencyModels] || {};\n // eslint-disable-next-line max-len\n target[DependencyModels][name] = {\n modelType: ConfigBean.type,\n id: configBeanModelId(path, destinationAddress),\n options: {\n path,\n serviceBasePath,\n destinationAddress,\n },\n lifecycle: DependencyLifecycle.INIT,\n lazy,\n };\n };\n","/* eslint-disable no-param-reassign */\n\nimport { DependencyLifecycle, DependencyModels } from \"../../core\";\nimport { KosConfigPropertySpec } from \"../models/config-bean-prop\";\nimport { OptionsExpander } from \"../models/config-bean-prop/types\";\n\nexport interface ToUnitConverterSystem {\n iface: \"system\";\n system: string;\n}\n\nexport interface ToUnitConverterSystemUnit {\n iface: \"systemunit\";\n system: string;\n unit: string;\n}\n\nexport interface ToUnitConverterMeasure {\n iface: \"measure\";\n measure: string;\n}\n\nexport interface ToUnitConverterUnit {\n iface: \"unit\";\n unit: string;\n}\n\nexport type ToUnitConverter =\n | ToUnitConverterSystem\n | ToUnitConverterSystemUnit\n | ToUnitConverterMeasure\n | ToUnitConverterUnit;\nexport interface UnitConverter {\n system?: string;\n measure?: string;\n unit?: string;\n alias?: string;\n}\ninterface KosConfigParams {\n path: string;\n attribute: string;\n formatter?:\n | Intl.NumberFormatOptions\n | ((system: string) => Intl.NumberFormatOptions);\n optionsExpander?: OptionsExpander;\n lazy?: boolean;\n serviceBasePath?: string;\n /**\n * Connection the property's bean is routed to. Accepts a prop key so a host\n * model can bind it per device; the property and bean ids include it.\n */\n destinationAddress?: string;\n converter?: {\n measure?: string;\n from?: UnitConverter | string;\n to?: UnitConverter | string;\n };\n}\n\nexport function kosConfigProperty(params: KosConfigParams) {\n const {\n path,\n attribute,\n converter,\n formatter,\n lazy,\n optionsExpander,\n serviceBasePath,\n destinationAddress,\n } = params;\n const _converter = converter;\n if (_converter) {\n if (\n typeof _converter !== \"function\" &&\n typeof _converter.from === \"string\"\n ) {\n _converter.from = { unit: _converter.from };\n }\n\n if (typeof _converter !== \"function\" && typeof _converter.to === \"string\") {\n _converter.to = { unit: _converter.to };\n }\n }\n return (target: {} | any, name: PropertyKey): any => {\n target[DependencyModels] = target[DependencyModels] || {};\n // eslint-disable-next-line max-len\n target[DependencyModels][name] = {\n modelType: KosConfigPropertySpec.type,\n id: destinationAddress\n ? `${destinationAddress}-${path}-${attribute}`\n : `${path}-${attribute}`,\n options: {\n path,\n attribute,\n serviceBasePath,\n destinationAddress,\n converter: _converter,\n formatter,\n optionsExpander,\n },\n\n lifecycle: DependencyLifecycle.INIT,\n lazy,\n };\n };\n}\n","import { DependencyLifecycle, DependencyModels } from \"../../core\";\nimport { StateBean } from \"../models/state-bean\";\n\ninterface KosStateParams {\n path: string;\n}\n\nexport const kosStateBean =\n ({ path }: KosStateParams) =>\n (target: {} | any, name: PropertyKey): any => {\n target[DependencyModels] = target[DependencyModels] || {};\n // eslint-disable-next-line max-len\n target[DependencyModels][name] = {\n modelType: StateBean.type,\n id: `${StateBean.type}-${path}`,\n options: {\n path,\n },\n lifecycle: DependencyLifecycle.INIT,\n };\n };\n","import { DependencyLifecycle, DependencyModels } from \"../../core\";\n\nimport { StateProp } from \"../models/state-prop\";\nimport { StatePropertyTypes } from \"../models/types\";\n\ntype StateKeys<T extends Record<string, StatePropertyTypes>> = keyof T;\n\ninterface KosStateParams<T extends Record<string, StatePropertyTypes> = any> {\n path: string;\n attribute: `${string & StateKeys<T>}`;\n}\n\nexport function kosStateProp<\n T extends Record<string, StatePropertyTypes> = any\n>(params: KosStateParams<T>) {\n const { path, attribute } = params;\n\n return (target: {} | any, name: PropertyKey): any => {\n target[DependencyModels] = target[DependencyModels] || {};\n // eslint-disable-next-line max-len\n target[DependencyModels][name] = {\n modelType: StateProp.type,\n id: `${path}-${attribute}`,\n options: {\n path,\n attribute,\n },\n\n lifecycle: DependencyLifecycle.INIT,\n };\n };\n}\n","import { autorun as kosAutoEffect } from \"mobx\";\n\n/**\n * A long-running operation whose progress can be observed imperatively.\n *\n * Progress surfaces (notifications, status indicators, modals) depend on this\n * interface rather than on any producer. `awaitFutureCall` adapts a KOS Future\n * to it; an upload or an aggregate of several operations can implement it too.\n */\nexport interface ProgressOperation<T = unknown> extends Promise<T> {\n /**\n * Percent complete, 0-100. A value of 0 or less means the operation has not\n * reported progress yet, so consumers should show an indeterminate state.\n */\n readonly progress: number;\n\n /**\n * Current status of the operation.\n * Common values: \"NOT_ACTIVE\", \"IN_PROGRESS\", a terminal end state\n * (\"SUCCESS\" | \"FAIL\" | \"ABORT\" | \"CANCEL\"), or consumer-defined.\n */\n readonly status: string;\n\n /**\n * Whether the operation is currently running\n */\n readonly isRunning: boolean;\n\n /**\n * Human-readable time remaining (e.g. \"2 minutes\"), when the source can\n * estimate it. Empty/undefined when unknown.\n */\n readonly timeRemaining?: string;\n\n /**\n * Cancel this specific operation\n */\n cancel(): Promise<void>;\n\n /**\n * Whether the operation was cancelled. Treat a missing implementation as unknown.\n */\n isCancelled?(): boolean;\n\n /**\n * Subscribe to progress updates\n * Returns a dispose function to clean up the subscription\n */\n onProgressUpdate(\n callback: (progress: number, status: string) => void\n ): () => void;\n}\n\n/**\n * A Promise that can be cancelled and provides progress/state tracking\n */\nexport interface CancellablePromise<T> extends ProgressOperation<T> {\n /**\n * Get the underlying AbortController for this operation\n */\n getController(): AbortController | undefined;\n\n /**\n * Check if this operation is cancelled\n */\n isCancelled(): boolean;\n}\n\n/**\n * Options for creating a cancellable promise with progress tracking\n */\nexport interface CancellablePromiseOptions<T> {\n promise: Promise<T>;\n abortController?: AbortController;\n cancelFuture?: () => Promise<void>;\n future?: any; // The KOS Future object for progress tracking\n}\n\n/**\n * Create a cancellable promise wrapper with reactive progress tracking\n */\nexport function createCancellablePromise<T>(\n promise: Promise<T>,\n abortController?: AbortController,\n cancelFuture?: () => Promise<void>,\n future?: any\n): CancellablePromise<T>;\nexport function createCancellablePromise<T>(\n options: CancellablePromiseOptions<T>\n): CancellablePromise<T>;\nexport function createCancellablePromise<T>(\n promiseOrOptions: Promise<T> | CancellablePromiseOptions<T>,\n abortController?: AbortController,\n cancelFuture?: () => Promise<void>,\n future?: any\n): CancellablePromise<T> {\n // Handle both call signatures\n const options =\n promiseOrOptions instanceof Promise\n ? { promise: promiseOrOptions, abortController, cancelFuture, future }\n : promiseOrOptions;\n\n const {\n promise,\n abortController: controller,\n cancelFuture: cancelFn,\n future: futureRef,\n } = options;\n\n // Create the base promise\n const cancellablePromise = promise as CancellablePromise<T>;\n\n // Progress tracking state\n let currentProgress = 0;\n let currentStatus = \"PENDING\";\n let isRunning = true;\n const progressCallbacks = new Set<\n (progress: number, status: string) => void\n >();\n\n // Update progress from Future if available\n let effectDisposer: (() => void) | undefined;\n if (futureRef && typeof futureRef === \"object\") {\n // Use kosAutoEffect to track Future changes\n effectDisposer = kosAutoEffect(() => {\n const newProgress = futureRef.progress || 0;\n const newStatus = futureRef.status || \"PENDING\";\n const newIsRunning = !futureRef.endState;\n\n if (\n newProgress !== currentProgress ||\n newStatus !== currentStatus ||\n newIsRunning !== isRunning\n ) {\n currentProgress = newProgress;\n currentStatus = newStatus;\n isRunning = newIsRunning;\n\n // Notify all subscribers\n progressCallbacks.forEach((callback) => {\n try {\n callback(currentProgress, currentStatus);\n } catch (error) {\n console.warn(\"Progress callback error:\", error);\n }\n });\n }\n });\n }\n\n // Clean up effect when promise completes\n promise.finally(() => {\n isRunning = false;\n if (!controller?.signal.aborted) {\n currentStatus = \"COMPLETED\";\n progressCallbacks.forEach((callback) => {\n try {\n callback(currentProgress, currentStatus);\n } catch (error) {\n console.warn(\"Progress callback error:\", error);\n }\n });\n }\n if (effectDisposer) {\n effectDisposer();\n }\n progressCallbacks.clear();\n });\n\n // Add cancellation methods\n cancellablePromise.cancel = async () => {\n if (controller && !controller.signal.aborted) {\n controller.abort();\n }\n if (cancelFn) {\n await cancelFn();\n }\n isRunning = false;\n currentStatus = \"CANCELLED\";\n progressCallbacks.forEach((callback) => {\n try {\n callback(currentProgress, currentStatus);\n } catch (error) {\n console.warn(\"Progress callback error:\", error);\n }\n });\n if (effectDisposer) {\n effectDisposer();\n }\n };\n\n cancellablePromise.getController = () => controller;\n\n cancellablePromise.isCancelled = () => controller?.signal.aborted ?? false;\n\n // Add progress tracking properties\n Object.defineProperty(cancellablePromise, \"progress\", {\n get: () => currentProgress,\n enumerable: true,\n });\n\n Object.defineProperty(cancellablePromise, \"status\", {\n get: () => currentStatus,\n enumerable: true,\n });\n\n Object.defineProperty(cancellablePromise, \"isRunning\", {\n get: () => isRunning,\n enumerable: true,\n });\n\n cancellablePromise.onProgressUpdate = (\n callback: (progress: number, status: string) => void\n ) => {\n progressCallbacks.add(callback);\n\n // Call immediately with current state\n callback(currentProgress, currentStatus);\n\n // Return dispose function\n return () => progressCallbacks.delete(callback);\n };\n\n return cancellablePromise;\n}\n","/**\n * Helpers that make a @kosFuture method call cancellable without reaching for\n * the model's future.\n */\n\nimport { KosLog } from \"../../core\";\nimport type { FutureContainer } from \"../models/future/future-types\";\nimport type { CancellablePromise } from \"../types/cancellable-promise\";\nimport { createCancellablePromise } from \"../types/cancellable-promise\";\n\n/**\n * Calls a @kosFuture method and returns a CancellablePromise whose `cancel()`\n * cancels the future the call started.\n *\n * @example\n * ```typescript\n * const call = makeCancellable(model, (m) => m.performOperation(\"data\"));\n * await call.cancel();\n * ```\n */\nexport function makeCancellable<T extends FutureContainer, R>(\n model: T,\n methodCall: (model: T) => Promise<R>\n): CancellablePromise<R> {\n // Store the current future before the call\n const initialFuture = model.futureHandler.future;\n\n // Execute the method call\n const promise = methodCall(model);\n\n // Wait a tick to get the new future created by the method\n let newFuture: any = null;\n setTimeout(() => {\n newFuture = model.futureHandler.future;\n // Only use the new future if it's different from the initial one\n if (newFuture === initialFuture) {\n newFuture = null;\n }\n }, 0);\n\n return createCancellablePromise({\n promise,\n abortController: undefined, // No direct AbortController access\n cancelFuture: async () => {\n // Cancel through the Future system\n if (newFuture) {\n await newFuture.cancelFuture();\n } else {\n // Fallback to current future\n const currentFuture = model.futureHandler.future;\n if (currentFuture) {\n await currentFuture.cancelFuture();\n }\n }\n },\n future: newFuture, // Pass the future for progress tracking\n });\n}\n\n/**\n * {@link makeCancellable} for a method given by name and arguments.\n *\n * @example\n * ```typescript\n * const call = withCancellation(model, \"performOperation\", \"data\");\n * ```\n */\nexport function withCancellation<T extends FutureContainer, K extends keyof T>(\n model: T,\n methodName: K,\n ...args: T[K] extends (...args: infer A) => any ? A : never\n): CancellablePromise<\n T[K] extends (...args: any[]) => Promise<infer R> ? R : never\n> {\n const method = model[methodName];\n if (typeof method !== \"function\") {\n throw new Error(`${String(methodName)} is not a method`);\n }\n\n // Store the current future state\n const initialFuture = model.futureHandler.future;\n\n // Call the method\n const promise = (method as any).apply(model, args);\n\n // Get the new future after method execution\n let targetFuture: any = null;\n setTimeout(() => {\n const currentFuture = model.futureHandler.future;\n if (currentFuture && currentFuture !== initialFuture) {\n targetFuture = currentFuture;\n }\n }, 0);\n\n return createCancellablePromise({\n promise,\n abortController: undefined,\n cancelFuture: async () => {\n if (targetFuture) {\n await targetFuture.cancelFuture();\n } else {\n const fallbackFuture = model.futureHandler.future;\n if (fallbackFuture) {\n await fallbackFuture.cancelFuture();\n }\n }\n },\n future: targetFuture, // Pass the future for progress tracking\n });\n}\n\n/**\n * Collects cancellable calls so they can be cancelled together.\n *\n * @example\n * ```typescript\n * const batch = createCancellationBatch();\n * batch.add(model, (m) => m.performOperation());\n * await batch.cancelAll();\n * ```\n */\nexport class CancellationBatch {\n private operations: Array<CancellablePromise<any>> = [];\n\n add<T extends FutureContainer, R>(\n model: T,\n methodCall: (model: T) => Promise<R>\n ): CancellablePromise<R> {\n const cancellable = makeCancellable(model, methodCall);\n this.operations.push(cancellable);\n return cancellable;\n }\n\n async cancelAll(): Promise<void> {\n await Promise.all(\n this.operations.map((op) =>\n op.cancel().catch(() => {\n // Ignore cancellation errors, just log them if needed\n KosLog.warn(\"Cancellation failed for operation:\", op);\n })\n )\n );\n }\n\n getAllControllers(): Array<AbortController | undefined> {\n return this.operations.map((op) => op.getController());\n }\n\n getActiveCount(): number {\n return this.operations.filter((op) => !op.isCancelled()).length;\n }\n\n clear(): void {\n this.operations = [];\n }\n}\n\nexport function createCancellationBatch(): CancellationBatch {\n return new CancellationBatch();\n}\n","/**\n * Folds several localization contexts into the one descriptor a\n * TranslationContainer is built from. Kept separate from\n * KosTranslationProvider so the merge rules can be tested without a DOM.\n */\nimport type { Localization } from \"./services\";\n\n/** A locale code paired with its name, rendered in that locale's own language. */\nexport interface LocaleOption {\n locale: string;\n label: string;\n}\n\n/**\n * Fold contexts into one descriptor, earlier entries winning.\n *\n * Precedence is per namespace, not per key or per locale: a namespace declared\n * by two contexts is taken whole from the earlier one, and the later context's\n * locales for that namespace are dropped even where the winner has none. A later\n * context can add namespaces but cannot extend one an earlier context declared.\n *\n * Each namespace's `basePath` is set to its own context's `path`, so namespaces\n * from different contexts keep resolving against the URL their context is\n * served from. The merged descriptor has no top-level `path`, since\n * `defaultResolver` reads `basePath` per namespace.\n */\nexport function mergeLocalizationDescriptors(\n descriptors: Localization[]\n): Localization {\n const merged: Localization[\"namespaces\"] = {};\n\n // Reverse, so the first context's namespaces are applied last and win.\n for (const descriptor of [...descriptors].reverse()) {\n for (const [name, namespace] of Object.entries(\n descriptor.namespaces ?? {}\n )) {\n merged[name] = { ...namespace, basePath: descriptor.path };\n }\n }\n\n return { namespaces: merged } as Localization;\n}\n\n/**\n * Every locale any namespace offers, as picker options.\n *\n * The result is a union across namespaces: one namespace translated into a\n * locale is enough to offer it for the whole app, and namespaces without it fall\n * back at resolve time. Excluded namespaces contribute nothing, which keeps a\n * content-bearing namespace (a brandset) from advertising locales the UI itself\n * cannot render.\n *\n * Labels come from `Intl.DisplayNames` and are rendered in the locale's own\n * language (\"italiano\", not \"Italian\").\n */\nexport function collectLocaleOptions(\n descriptors: Localization[],\n excludeNamespaces: string[] = []\n): LocaleOption[] {\n const codes = new Set<string>();\n\n for (const descriptor of descriptors) {\n for (const [name, namespace] of Object.entries(\n descriptor.namespaces ?? {}\n )) {\n if (excludeNamespaces.includes(name)) continue;\n for (const locale of Object.keys(namespace.locales ?? {})) {\n codes.add(locale);\n }\n }\n }\n\n return Array.from(codes).map((locale) => {\n return {\n locale,\n label: new Intl.DisplayNames([locale], { type: \"language\" }).of(\n locale\n ) as string,\n };\n });\n}\n","import { KosContextManager, whenReady } from \"../../../core\";\nimport { TranslationContainer } from \"./translation-container-registration\";\nimport type { TranslationContainerOptions } from \"./types\";\n\nexport const TranslationContext = {\n set(name: string, value: any) {\n const context = KosContextManager.getContext(TranslationContainer.type);\n if (context) {\n context.set(name, value);\n }\n },\n get(name: string) {\n const context = KosContextManager.getContext(TranslationContainer.type);\n return context?.get(name);\n },\n};\n\nexport const KosTranslations = {\n async init(options: TranslationContainerOptions) {\n const tc = TranslationContainer.factory(options);\n await whenReady(tc);\n return { translations: tc };\n },\n};\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport {\n ExtensionManager,\n ExtensionOptions,\n PropertyMapper,\n type DataLoader,\n} from \"../../core\";\nimport { KosCoreModelPropertyMapper } from \"../constants\";\nimport type { IConfigBeanModel, RegionInfoModel } from \"../models\";\nimport { CanvasDispatcher } from \"../models/canvas-dispatcher\";\nimport type { TroubleResponse } from \"../models/trouble/services\";\n\nexport type TroubleRankMapper = PropertyMapper<TroubleResponse, number, any>;\n\nexport type TroubleColorMapper = PropertyMapper<TroubleResponse, string, any>;\n\nexport type TroubleRoleMapper = PropertyMapper<TroubleResponse, string, any>;\n\nexport type RegionServicePathMapper = PropertyMapper<\n RegionInfoModel,\n string,\n any\n>;\n\nexport type ConfigServicePathMapper = PropertyMapper<\n IConfigBeanModel,\n string,\n any\n>;\nexport class CoreExtensionManager {\n /**\n * Maps the rank property of the trouble into the {@link TroubleModel}.\n *\n * @param troubleRankMapper - Mapping function that derives a numeric rank from a {@link TroubleResponse}\n * @param options - Optional {@link ExtensionOptions} to control failure behavior.\n * Defaults to `failurePolicy: \"throw\"`, which throws an {@link ExtensionException} on mapper failure.\n * Set to `\"continue\"` to log the error and return a fallback value instead.\n * @returns this instance for chaining\n * */\n registerTroubleRankMapper(\n troubleRankMapper: TroubleRankMapper,\n options?: ExtensionOptions\n ) {\n ExtensionManager.propertyMapper.registerPropertyMapper(\n KosCoreModelPropertyMapper.TroubleRank,\n troubleRankMapper,\n options\n );\n return this;\n }\n\n /**\n * Maps the role property of the trouble into the {@link TroubleModel}.\n *\n * @param troubleRoleMapper - Mapping function that derives a role string from a {@link TroubleResponse}\n * @param options - Optional {@link ExtensionOptions} to control failure behavior.\n * Defaults to `failurePolicy: \"throw\"`, which throws an {@link ExtensionException} on mapper failure.\n * Set to `\"continue\"` to log the error and return a fallback value instead.\n * @returns this instance for chaining\n * */\n registerTroubleRoleMapper(\n troubleRoleMapper: TroubleRoleMapper,\n options?: ExtensionOptions\n ) {\n ExtensionManager.propertyMapper.registerPropertyMapper(\n KosCoreModelPropertyMapper.TroubleRole,\n troubleRoleMapper,\n options\n );\n return this;\n }\n\n /**\n * Maps the color property of the trouble into the {@link TroubleModel}.\n *\n * @param troubleColorMapper - Mapping function that derives a color string from a {@link TroubleResponse}\n * @param options - Optional {@link ExtensionOptions} to control failure behavior.\n * Defaults to `failurePolicy: \"throw\"`, which throws an {@link ExtensionException} on mapper failure.\n * Set to `\"continue\"` to log the error and return a fallback value instead.\n * @returns this instance for chaining\n * */\n registerTroubleColorMapper(\n troubleColorMapper: TroubleColorMapper,\n options?: ExtensionOptions\n ) {\n ExtensionManager.propertyMapper.registerPropertyMapper(\n KosCoreModelPropertyMapper.TroubleColor,\n troubleColorMapper,\n options\n );\n return this;\n }\n\n /**\n * Registers a data loader for a given model id. The loader is invoked during model\n * initialization to fetch data that is provided as context to associated mappers.\n *\n * @param id - The model identifier to associate the loader with\n * @param loader - Async function that loads and returns data for the model\n * @param options - Optional {@link ExtensionOptions} to control failure behavior.\n * Defaults to `failurePolicy: \"throw\"`, which throws an {@link ExtensionException} on loader failure.\n * Set to `\"continue\"` to log the error and return `undefined` instead.\n */\n registerModelLoader(\n id: string,\n loader: DataLoader,\n options?: ExtensionOptions\n ) {\n ExtensionManager.loader.registerLoader(id, loader, options);\n }\n\n registerRegionServicePathMapper(\n regionServicePathMapper: RegionServicePathMapper\n ) {\n ExtensionManager.propertyMapper.registerPropertyMapper(\n KosCoreModelPropertyMapper.RegionServicePath,\n regionServicePathMapper\n );\n return this;\n }\n\n /**\n * Registers a data loader for the {@link CanvasDispatcher} pattern data.\n *\n * @param loader - Async function that loads canvas pattern data\n * @param options - Optional {@link ExtensionOptions} to control failure behavior.\n * Defaults to `failurePolicy: \"throw\"`, which throws an {@link ExtensionException} on loader failure.\n * Set to `\"continue\"` to log the error and return `undefined` instead.\n */\n registerCanvasPatternLoader(loader: DataLoader, options?: ExtensionOptions) {\n ExtensionManager.loader.registerLoader(\n CanvasDispatcher.loader,\n loader,\n options\n );\n }\n\n registerConfigServicePathMapper(\n configServicePathMapper: ConfigServicePathMapper\n ) {\n ExtensionManager.propertyMapper.registerPropertyMapper(\n KosCoreModelPropertyMapper.ConfigServicePath,\n configServicePathMapper\n );\n return this;\n }\n}\n","import { destroyKosModel, whenReady } from \"../../core\";\nimport { KeyValue } from \"../models/key-value\";\n\n/**\n * A persistence store that can be used to store data for a given session id and key\n * The store is namespaced by the stateKey and the sessionId allows for multiple instances\n * of data to be created with the same store using the session id as the discriminator.\n * The store is backed by a {@link KeyValue} model.\n * @public\n * @interface\n */\nexport interface PersistenceStoreAware {\n /** The key value data store */\n store: KosPersistenceStore;\n\n /** The sessionId to be used when multiple instances of a persistence store are required for a given namespace */\n sessionId: string;\n\n /** The stateKey used to namespace the store */\n stateKey: string;\n}\nexport interface KosPersistenceStore {\n /**\n * Update the state of the store for a given key. The session id of the store instance\n * will be used to segregate the data. For example, if the session id is \"my-session\" and the\n * key is \"my-key\", the data will be stored as \"my-session-my-key\". However the session id is not\n * externally visible and is managed by the store.\n *\n * @param key - the key to update\n * @param value - the value to update\n *\n */\n updateState(\n key: string,\n value: string | number | boolean | undefined\n ): Promise<void>;\n\n /**\n * Clean all the data from the store for the given session id\n */\n clean(): void;\n\n /**\n * Retrieve the state of the store for a given key. The session id of the store instance\n * will be used to retrieve the data.\n * @param key - the key to retrieve\n * @returns the value of the key or undefined if the key does not exist\n */\n getState(key: string): string | number | boolean | undefined;\n\n /**\n * Unsubscribe from the store. This will remove the store from the persistence layer\n */\n unsubscribe(): void;\n}\n\n/**\n * Subscribe to a KOS Persistence Store or create a new one\n * The store will be namespaced by the stateKey and the sessionId allows\n * for multiple instances of data to be created with the same store using the session id\n * as the discriminator.\n *\n * If the sessionId is not provided, the store will be global\n *\n * @param stateKey - the namespace of the given persistence store\n * @param sessionId - the data partition with the namespace that the store will operate within\n * @returns a {@link KosPersistenceStore} instance\n */\nexport const subscribeStore = async (\n stateKey: string,\n sessionId?: string\n): Promise<KosPersistenceStore> => {\n const toolState = KeyValue.instance(stateKey).options({}).build();\n const prefix = sessionId ? `${sessionId}-` : \"\";\n await whenReady(toolState);\n return {\n getState: (key: string) => toolState.data[`${prefix}${key}`],\n updateState: async (\n key: string,\n value: string | number | boolean | undefined\n ) => {\n await toolState.updateState(`${prefix}${key}`, value);\n },\n clean: async () => {\n for (const key of toolState.data.keys) {\n await toolState.updateState(`${prefix}${key}`, undefined);\n }\n },\n unsubscribe: () => {\n destroyKosModel(toolState);\n },\n };\n};\n","import { whenReady } from \"../../core\";\nimport { KosConfigPropertySpec } from \"../models/config-bean-prop\";\n\nconst REGION_PATH = \"kos:service:region\";\nconst REGION_ATTRIBUTE = \"regionId\";\nconst REGION_ID = `${REGION_PATH}-${REGION_ATTRIBUTE}`;\n\nexport const updateRegion = async (region: string) => {\n const regionInfo = KosConfigPropertySpec.factory(REGION_ID)({\n path: REGION_PATH,\n attribute: REGION_ATTRIBUTE,\n });\n await whenReady(regionInfo);\n\n regionInfo.updateProperty(region);\n};\n","/**\n * Public accessor for the KOS API service client.\n *\n * Encapsulates the dynamic import of the internal `service` module,\n * preserving the lazy-load pattern while providing a stable import\n * path for external consumers (e.g., @matrica-code/kos-declarative-model).\n */\nexport async function getKosServiceApi() {\n const { default: API } = await import(\"./service\");\n return API;\n}\n","import type { KosExecutionContext } from \"../../../../../core/core/decorators/kos-execution-context\";\nimport type {\n HttpMethod,\n IKosServiceRequestParams,\n} from \"../../../../../core/core/decorators/kos-service-request\";\nimport { kosServiceRequest as baseKosServiceRequest } from \"../../../../../core/core/decorators/kos-service-request\";\nimport type { ClientResponse } from \"../../../../../core/util/kos-service-request\";\nimport { createClient } from \"../../../../../core/util/kos-service-request\";\n\nimport type { PathsByMethod } from \"../../../../../core/util/kos-service-request\";\nimport type { paths } from \"./openapi\";\n\n/**\n * Type aliases for kos API\n */\nexport type Api = paths;\nexport type ApiPath = keyof paths;\nexport type ValidPaths = PathsByMethod<paths>;\n\n/**\n * Methods a response type can be derived for: the lowercase subset of\n * HttpMethod. The uppercase spellings HttpMethod also permits do not match the\n * keys of an OpenAPI `paths` object, so they would silently yield `unknown`.\n */\nexport type SupportedMethod = \"get\" | \"post\" | \"put\" | \"delete\";\n\n/**\n * Get client response type for kos API\n */\nexport type ApiResponse<\n Path extends ApiPath,\n Method extends SupportedMethod = \"get\"\n> = ClientResponse<paths, Path, Method>;\n\n/**\n * Get execution context type for kos API\n */\nexport type ExecutionContext<\n Path extends ApiPath = ApiPath,\n Method extends HttpMethod = \"get\",\n Transformed = ApiResponse<Path, SupportedMethod & Method>\n> = KosExecutionContext<paths, Path, Method, Transformed>;\n\n/**\n * Typed decorator factory for @kosServiceRequest with kos API types\n *\n * Provides full IntelliSense and type safety for path, query params, and body\n * based on the kos OpenAPI schema.\n *\n * @example\n * ```typescript\n * import { kosServiceRequest } from '../../utils/services/kos/daily/service';\n * import { DependencyLifecycle } from '@kosdev-code/kos-ui-sdk';\n *\n * @kosServiceRequest({\n * path: '/api/...',\n * method: 'get',\n * lifecycle: DependencyLifecycle.LOAD\n * })\n * private onDataLoaded(): void {\n * // Fully typed based on kos API\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\n/**\n * One endpoint of the kos API: a path and the method it is called with.\n */\nexport interface Endpoint {\n path: ApiPath;\n method: SupportedMethod;\n}\n\n/**\n * Declare an endpoint once. The decorator config, the execution context type\n * and the response type are all derived from the result, so the path string\n * is written once and cannot drift between them.\n *\n * @example\n * ```typescript\n * export const BoardApi = {\n * list: endpoint(\"/api/board\", \"get\"),\n * update: endpoint(\"/api/board/{id}\", \"put\"),\n * } as const;\n * ```\n */\nexport function endpoint<Path extends ApiPath, Method extends SupportedMethod>(\n path: Path,\n method: Method\n) {\n return { path, method } as const;\n}\n\n/**\n * Execution context for an endpoint: the method-driven `$ctx` parameter type.\n * Pass `Transformed` when the decorator declares a `transform`, so what the\n * method receives is typed as the mapper's output rather than the raw response.\n */\nexport type EndpointCtx<\n E extends Endpoint,\n Transformed = EndpointResponse<E>\n> = ExecutionContext<E[\"path\"], E[\"method\"], Transformed>;\n\n/** Response body type for an endpoint. */\nexport type EndpointResponse<E extends Endpoint> = ApiResponse<\n E[\"path\"],\n E[\"method\"]\n>;\n\n/**\n * @kosServiceRequest preconfigured from an endpoint descriptor, defaulting to\n * log-and-continue error handling. Pass overrides (lifecycle, errorHandler,\n * cache, …) as the second argument.\n *\n * A `transform` narrows what the model receives: its return type becomes the\n * handler's data type, so the raw response shape stops at the mapper.\n *\n * @example\n * ```typescript\n * @serviceRequest(BoardApi.update)\n * async renameBoard(name: string, $ctx?: EndpointCtx<typeof BoardApi.update>) {\n * const data = await executeServiceRequest(this, $ctx, {\n * pathParams: { id: this.id },\n * body: { name },\n * });\n * if (!data) return;\n * }\n * ```\n */\nexport function serviceRequest<\n E extends Endpoint,\n Transformed = EndpointResponse<E>\n>(\n ep: E,\n opts?: Partial<\n IKosServiceRequestParams<\n paths,\n E[\"path\"],\n E[\"method\"],\n EndpointResponse<E>,\n Transformed\n >\n >\n) {\n return kosServiceRequest<\n E[\"path\"],\n E[\"method\"],\n EndpointResponse<E>,\n Transformed\n >({\n path: ep.path,\n method: ep.method,\n errorHandler: { strategy: \"log\", defaultValue: null },\n ...opts,\n });\n}\n\n/**\n * Create an API client for kos\n */\nexport const api = createClient<paths>();\n\nexport default api;\n","import type { KosExecutionContext } from \"../../../../../core/core/decorators/kos-execution-context\";\nimport type {\n HttpMethod,\n IKosServiceRequestParams,\n} from \"../../../../../core/core/decorators/kos-service-request\";\nimport { kosServiceRequest as baseKosServiceRequest } from \"../../../../../core/core/decorators/kos-service-request\";\nimport type { ClientResponse } from \"../../../../../core/util/kos-service-request\";\nimport { createClient } from \"../../../../../core/util/kos-service-request\";\n\nimport type { PathsByMethod } from \"../../../../../core/util/kos-service-request\";\nimport type { paths } from \"./openapi\";\n\n/**\n * Type aliases for kos API\n */\nexport type Api = paths;\nexport type ApiPath = keyof paths;\nexport type ValidPaths = PathsByMethod<paths>;\n\n/**\n * Get client response type for kos API\n */\nexport type ApiResponse<\n Path extends ApiPath,\n Method extends \"get\" | \"post\" | \"put\" | \"delete\" = \"get\"\n> = ClientResponse<paths, Path, Method>;\n\n/**\n * Get execution context type for kos API\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 API types\n *\n * Provides full IntelliSense and type safety for path, query params, and body\n * based on the kos OpenAPI schema.\n *\n * @example\n * ```typescript\n * import { kosServiceRequest } from '../../utils/services/kos/1.6.5/service';\n * import { DependencyLifecycle } from '@kosdev-code/kos-ui-sdk';\n *\n * @kosServiceRequest({\n * path: '/api/...',\n * method: 'get',\n * lifecycle: DependencyLifecycle.LOAD\n * })\n * private onDataLoaded(): void {\n * // Fully typed based on kos API\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\n/**\n * Create an API client for kos\n */\nexport const api = createClient<paths>();\n\nexport default api;\n","import type { KosExecutionContext } from \"../../../../../core/core/decorators/kos-execution-context\";\nimport type {\n HttpMethod,\n IKosServiceRequestParams,\n} from \"../../../../../core/core/decorators/kos-service-request\";\nimport { kosServiceRequest as baseKosServiceRequest } from \"../../../../../core/core/decorators/kos-service-request\";\nimport type { ClientResponse } from \"../../../../../core/util/kos-service-request\";\nimport { createClient } from \"../../../../../core/util/kos-service-request\";\n\nimport type { PathsByMethod } from \"../../../../../core/util/kos-service-request\";\nimport type { paths } from \"./openapi\";\n\n/**\n * Type aliases for kos API\n */\nexport type Api = paths;\nexport type ApiPath = keyof paths;\nexport type ValidPaths = PathsByMethod<paths>;\n\n/**\n * Get client response type for kos API\n */\nexport type ApiResponse<\n Path extends ApiPath,\n Method extends \"get\" | \"post\" | \"put\" | \"delete\" = \"get\"\n> = ClientResponse<paths, Path, Method>;\n\n/**\n * Get execution context type for kos API\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 API types\n *\n * Provides full IntelliSense and type safety for path, query params, and body\n * based on the kos OpenAPI schema.\n *\n * @example\n * ```typescript\n * import { kosServiceRequest } from '../../utils/services/kos/1.8.1/service';\n * import { DependencyLifecycle } from '@kosdev-code/kos-ui-sdk';\n *\n * @kosServiceRequest({\n * path: '/api/...',\n * method: 'get',\n * lifecycle: DependencyLifecycle.LOAD\n * })\n * private onDataLoaded(): void {\n * // Fully typed based on kos API\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\n/**\n * Create an API client for kos\n */\nexport const api = createClient<paths>();\n\nexport default api;\n","import type { KosExecutionContext } from \"../../../../../core/core/decorators/kos-execution-context\";\nimport type {\n HttpMethod,\n IKosServiceRequestParams,\n} from \"../../../../../core/core/decorators/kos-service-request\";\nimport { kosServiceRequest as baseKosServiceRequest } from \"../../../../../core/core/decorators/kos-service-request\";\nimport type { ClientResponse } from \"../../../../../core/util/kos-service-request\";\nimport { createClient } from \"../../../../../core/util/kos-service-request\";\n\nimport type { PathsByMethod } from \"../../../../../core/util/kos-service-request\";\nimport type { paths } from \"./openapi\";\n\n/**\n * Type aliases for kos API\n */\nexport type Api = paths;\nexport type ApiPath = keyof paths;\nexport type ValidPaths = PathsByMethod<paths>;\n\n/**\n * Get client response type for kos API\n */\nexport type ApiResponse<\n Path extends ApiPath,\n Method extends \"get\" | \"post\" | \"put\" | \"delete\" = \"get\"\n> = ClientResponse<paths, Path, Method>;\n\n/**\n * Get execution context type for kos API\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 API types\n *\n * Provides full IntelliSense and type safety for path, query params, and body\n * based on the kos OpenAPI schema.\n *\n * @example\n * ```typescript\n * import { kosServiceRequest } from '../../utils/services/kos/1.9.x/service';\n * import { DependencyLifecycle } from '@kosdev-code/kos-ui-sdk';\n *\n * @kosServiceRequest({\n * path: '/api/...',\n * method: 'get',\n * lifecycle: DependencyLifecycle.LOAD\n * })\n * private onDataLoaded(): void {\n * // Fully typed based on kos API\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\n/**\n * Create an API client for kos\n */\nexport const api = createClient<paths>();\n\nexport default api;\n","import type { KosExecutionContext } from \"../../../../../core/core/decorators/kos-execution-context\";\nimport type {\n HttpMethod,\n IKosServiceRequestParams,\n} from \"../../../../../core/core/decorators/kos-service-request\";\nimport { kosServiceRequest as baseKosServiceRequest } from \"../../../../../core/core/decorators/kos-service-request\";\nimport type { ClientResponse } from \"../../../../../core/util/kos-service-request\";\nimport { createClient } from \"../../../../../core/util/kos-service-request\";\n\nimport type { PathsByMethod } from \"../../../../../core/util/kos-service-request\";\nimport type { paths } from \"./openapi\";\n\n/**\n * Type aliases for vfs API\n */\nexport type Api = paths;\nexport type ApiPath = keyof paths;\nexport type ValidPaths = PathsByMethod<paths>;\n\n/**\n * Methods a response type can be derived for: the lowercase subset of\n * HttpMethod. The uppercase spellings HttpMethod also permits do not match the\n * keys of an OpenAPI `paths` object, so they would silently yield `unknown`.\n */\nexport type SupportedMethod = \"get\" | \"post\" | \"put\" | \"delete\";\n\n/**\n * Get client response type for vfs API\n */\nexport type ApiResponse<\n Path extends ApiPath,\n Method extends SupportedMethod = \"get\"\n> = ClientResponse<paths, Path, Method>;\n\n/**\n * Get execution context type for vfs API\n */\nexport type ExecutionContext<\n Path extends ApiPath = ApiPath,\n Method extends HttpMethod = \"get\",\n Transformed = ApiResponse<Path, SupportedMethod & Method>\n> = KosExecutionContext<paths, Path, Method, Transformed>;\n\n/**\n * Typed decorator factory for @kosServiceRequest with vfs API types\n *\n * Provides full IntelliSense and type safety for path, query params, and body\n * based on the vfs OpenAPI schema.\n *\n * @example\n * ```typescript\n * import { kosServiceRequest } from '../../utils/services/vfs/daily/service';\n * import { DependencyLifecycle } from '@kosdev-code/kos-ui-sdk';\n *\n * @kosServiceRequest({\n * path: '/api/...',\n * method: 'get',\n * lifecycle: DependencyLifecycle.LOAD\n * })\n * private onDataLoaded(): void {\n * // Fully typed based on vfs API\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\n/**\n * One endpoint of the vfs API: a path and the method it is called with.\n */\nexport interface Endpoint {\n path: ApiPath;\n method: SupportedMethod;\n}\n\n/**\n * Declare an endpoint once. The decorator config, the execution context type\n * and the response type are all derived from the result, so the path string\n * is written once and cannot drift between them.\n *\n * @example\n * ```typescript\n * export const BoardApi = {\n * list: endpoint(\"/api/board\", \"get\"),\n * update: endpoint(\"/api/board/{id}\", \"put\"),\n * } as const;\n * ```\n */\nexport function endpoint<Path extends ApiPath, Method extends SupportedMethod>(\n path: Path,\n method: Method\n) {\n return { path, method } as const;\n}\n\n/**\n * Execution context for an endpoint: the method-driven `$ctx` parameter type.\n * Pass `Transformed` when the decorator declares a `transform`, so what the\n * method receives is typed as the mapper's output rather than the raw response.\n */\nexport type EndpointCtx<\n E extends Endpoint,\n Transformed = EndpointResponse<E>\n> = ExecutionContext<E[\"path\"], E[\"method\"], Transformed>;\n\n/** Response body type for an endpoint. */\nexport type EndpointResponse<E extends Endpoint> = ApiResponse<\n E[\"path\"],\n E[\"method\"]\n>;\n\n/**\n * @kosServiceRequest preconfigured from an endpoint descriptor, defaulting to\n * log-and-continue error handling. Pass overrides (lifecycle, errorHandler,\n * cache, …) as the second argument.\n *\n * A `transform` narrows what the model receives: its return type becomes the\n * handler's data type, so the raw response shape stops at the mapper.\n *\n * @example\n * ```typescript\n * @serviceRequest(BoardApi.update)\n * async renameBoard(name: string, $ctx?: EndpointCtx<typeof BoardApi.update>) {\n * const data = await executeServiceRequest(this, $ctx, {\n * pathParams: { id: this.id },\n * body: { name },\n * });\n * if (!data) return;\n * }\n * ```\n */\nexport function serviceRequest<\n E extends Endpoint,\n Transformed = EndpointResponse<E>\n>(\n ep: E,\n opts?: Partial<\n IKosServiceRequestParams<\n paths,\n E[\"path\"],\n E[\"method\"],\n EndpointResponse<E>,\n Transformed\n >\n >\n) {\n return kosServiceRequest<\n E[\"path\"],\n E[\"method\"],\n EndpointResponse<E>,\n Transformed\n >({\n path: ep.path,\n method: ep.method,\n errorHandler: { strategy: \"log\", defaultValue: null },\n ...opts,\n });\n}\n\n/**\n * Create an API client for vfs\n */\nexport const api = createClient<paths>();\n\nexport default api;\n","import type { KosExecutionContext } from \"../../../../../core/core/decorators/kos-execution-context\";\nimport type {\n HttpMethod,\n IKosServiceRequestParams,\n} from \"../../../../../core/core/decorators/kos-service-request\";\nimport { kosServiceRequest as baseKosServiceRequest } from \"../../../../../core/core/decorators/kos-service-request\";\nimport type { ClientResponse } from \"../../../../../core/util/kos-service-request\";\nimport { createClient } from \"../../../../../core/util/kos-service-request\";\n\nimport type { PathsByMethod } from \"../../../../../core/util/kos-service-request\";\nimport type { paths } from \"./openapi\";\n\n/**\n * Type aliases for vfs API\n */\nexport type Api = paths;\nexport type ApiPath = keyof paths;\nexport type ValidPaths = PathsByMethod<paths>;\n\n/**\n * Get client response type for vfs API\n */\nexport type ApiResponse<\n Path extends ApiPath,\n Method extends \"get\" | \"post\" | \"put\" | \"delete\" = \"get\"\n> = ClientResponse<paths, Path, Method>;\n\n/**\n * Get execution context type for vfs API\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 vfs API types\n *\n * Provides full IntelliSense and type safety for path, query params, and body\n * based on the vfs OpenAPI schema.\n *\n * @example\n * ```typescript\n * import { kosServiceRequest } from '../../utils/services/vfs/1.6.5/service';\n * import { DependencyLifecycle } from '@kosdev-code/kos-ui-sdk';\n *\n * @kosServiceRequest({\n * path: '/api/...',\n * method: 'get',\n * lifecycle: DependencyLifecycle.LOAD\n * })\n * private onDataLoaded(): void {\n * // Fully typed based on vfs API\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\n/**\n * Create an API client for vfs\n */\nexport const api = createClient<paths>();\n\nexport default api;\n","import type { KosExecutionContext } from \"../../../../../core/core/decorators/kos-execution-context\";\nimport type {\n HttpMethod,\n IKosServiceRequestParams,\n} from \"../../../../../core/core/decorators/kos-service-request\";\nimport { kosServiceRequest as baseKosServiceRequest } from \"../../../../../core/core/decorators/kos-service-request\";\nimport type { ClientResponse } from \"../../../../../core/util/kos-service-request\";\nimport { createClient } from \"../../../../../core/util/kos-service-request\";\n\nimport type { PathsByMethod } from \"../../../../../core/util/kos-service-request\";\nimport type { paths } from \"./openapi\";\n\n/**\n * Type aliases for vfs API\n */\nexport type Api = paths;\nexport type ApiPath = keyof paths;\nexport type ValidPaths = PathsByMethod<paths>;\n\n/**\n * Get client response type for vfs API\n */\nexport type ApiResponse<\n Path extends ApiPath,\n Method extends \"get\" | \"post\" | \"put\" | \"delete\" = \"get\"\n> = ClientResponse<paths, Path, Method>;\n\n/**\n * Get execution context type for vfs API\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 vfs API types\n *\n * Provides full IntelliSense and type safety for path, query params, and body\n * based on the vfs OpenAPI schema.\n *\n * @example\n * ```typescript\n * import { kosServiceRequest } from '../../utils/services/vfs/1.8.1/service';\n * import { DependencyLifecycle } from '@kosdev-code/kos-ui-sdk';\n *\n * @kosServiceRequest({\n * path: '/api/...',\n * method: 'get',\n * lifecycle: DependencyLifecycle.LOAD\n * })\n * private onDataLoaded(): void {\n * // Fully typed based on vfs API\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\n/**\n * Create an API client for vfs\n */\nexport const api = createClient<paths>();\n\nexport default api;\n","import type { KosExecutionContext } from \"../../../../../core/core/decorators/kos-execution-context\";\nimport type {\n HttpMethod,\n IKosServiceRequestParams,\n} from \"../../../../../core/core/decorators/kos-service-request\";\nimport { kosServiceRequest as baseKosServiceRequest } from \"../../../../../core/core/decorators/kos-service-request\";\nimport type { ClientResponse } from \"../../../../../core/util/kos-service-request\";\nimport { createClient } from \"../../../../../core/util/kos-service-request\";\n\nimport type { PathsByMethod } from \"../../../../../core/util/kos-service-request\";\nimport type { paths } from \"./openapi\";\n\n/**\n * Type aliases for vfs API\n */\nexport type Api = paths;\nexport type ApiPath = keyof paths;\nexport type ValidPaths = PathsByMethod<paths>;\n\n/**\n * Get client response type for vfs API\n */\nexport type ApiResponse<\n Path extends ApiPath,\n Method extends \"get\" | \"post\" | \"put\" | \"delete\" = \"get\"\n> = ClientResponse<paths, Path, Method>;\n\n/**\n * Get execution context type for vfs API\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 vfs API types\n *\n * Provides full IntelliSense and type safety for path, query params, and body\n * based on the vfs OpenAPI schema.\n *\n * @example\n * ```typescript\n * import { kosServiceRequest } from '../../utils/services/vfs/1.9.x/service';\n * import { DependencyLifecycle } from '@kosdev-code/kos-ui-sdk';\n *\n * @kosServiceRequest({\n * path: '/api/...',\n * method: 'get',\n * lifecycle: DependencyLifecycle.LOAD\n * })\n * private onDataLoaded(): void {\n * // Fully typed based on vfs API\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\n/**\n * Create an API client for vfs\n */\nexport const api = createClient<paths>();\n\nexport default api;\n","import { whenReady } from \"../../core\";\nimport { KosConfigPropertySpec } from \"../models/config-bean-prop\";\n\nconst REGION_SETTINGS_PATH = \"kos:service:region:settings\";\nconst TIMEZONE_ATTRIBUTE = \"timeZone\";\nconst REGION_TIMEZONE_ID = `${REGION_SETTINGS_PATH}-${TIMEZONE_ATTRIBUTE}`;\n\nexport const updateTimeZone = async (timezone: string) => {\n const timezoneInfo = KosConfigPropertySpec.factory(REGION_TIMEZONE_ID)({\n path: REGION_SETTINGS_PATH,\n attribute: TIMEZONE_ATTRIBUTE,\n });\n await whenReady(timezoneInfo);\n\n timezoneInfo.updateProperty(timezone);\n};\n","import type { TroubleAware } from \"../types\";\n\n/**\n * Type guard for {@link TroubleAware}: true when `obj` has a `troubles` array\n * and a `troublesByType` object. It checks structure only, not the contents.\n *\n * @category Utilities\n * @category Trouble Management\n *\n * @param obj - The object to check\n * @returns `true` if the object implements TroubleAware\n *\n * @see {@link TroubleAware} - The interface this function checks for\n * @see {@link useTroubleDecoration} - Hook that uses this guard internally\n */\nexport function isTroubleAware(obj?: any): obj is TroubleAware {\n return (\n obj?.troubles !== undefined &&\n obj?.troubles instanceof Array &&\n obj?.troublesByType !== undefined &&\n typeof obj?.troublesByType === \"object\"\n );\n}\n","import { BASE_URL, kosFetch, KosLog, KosServiceResponse } from \"../../../core\";\n\nconst log = KosLog.createLogger({ name: \"services\", group: \"Services\" });\n\ninterface LoginResponse {\n token: string;\n}\n\n/**\n * Convienience function to provide Studio specific login functions defaulting the url\n * Studio endpoint.\n * @param username - the username of the user to log in\n * @param password - the password of the user to log in\n * @returns a login response with the token of the logged in user\n *\n * @internal\n * @see login\n */\nexport const studioLogin = async (username: string, password: string) =>\n login(username, password, `${BASE_URL}/api/server/login`);\n\n/**\n * Attempts a log in against the specified URL.\n * @param username - the username of the user to log in\n * @param password - the password of the user to log in\n * @param url - the url to send the login request to.\n * @defaultValue - defaults to the Admin server URL.\n *\n * @returns a login response with the token of the logged in user\n */\nexport const login = async (\n username: string,\n password: string,\n url = `${BASE_URL}/api/login`\n) => {\n const response = await kosFetch(`${url}`, {\n method: `POST`,\n destinationAddress: \"\",\n body: JSON.stringify({\n email: username,\n password,\n }),\n });\n if (!response.ok) {\n const configResponse = await response.json();\n\n throw Error(`${configResponse?.error}`);\n }\n const configResponse: KosServiceResponse<LoginResponse> | null =\n await response.json();\n return configResponse;\n};\n\n/**\n * Convienience function to provide Studio specific password reset functions defaulting the url\n * Studio endpoint.\n * @param username - the userID of the user to start the password reset process.\n * @returns an API response with no value.\n *\n * @see startPasswordReset\n * @internal\n */\nexport const studioStartPasswordReset = async (userId: string) =>\n startPasswordReset(userId, `${BASE_URL}/api/server/startPasswordReset`, \"\");\n\n/**\n * When a user is first created or if the password is forgotten. A user can request\n * a password reset from thier Organization administrator. The administrator will end\n * up calling this function in order to initiate the request and have reset token sent\n * to the user on thier specified e-mail address (or other method.)\n * The token, received by the user, can be used as part of the reset call to provide a new password.\n *\n * @param userId - the user ID of the suer to start the password reset process.\n * @param url - the url to send the login request to.\n * @defaultValue - defaults to the Admin server URL.\n * @returns an API response with no value.\n * @internal\n * @see resetPassword\n */\nexport const startPasswordReset = async (\n userId: string,\n url = `${BASE_URL}/api/startPasswordReset`,\n destinationAddress = \"server\"\n) => {\n const response = await kosFetch(`${url}?email=${userId}`, {\n method: `POST`,\n destinationAddress,\n });\n if (!response.ok) {\n throw Error(\n `There was a problem reseting config; returned status ${response.status}`\n );\n }\n const configResponse: KosServiceResponse<unknown> | null =\n await response.json();\n return configResponse;\n};\n\n/**\n * Convienience function to provide Studio specific password reset functions defaulting the url\n * Studio endpoint.\n * @param token - the reset token recieved as part of the `startPasswordReset` process\n * @param password - the new password to be used by the user specified in the token.\n * @returns an API response with no value.\n * @internal\n * @see startPasswordReset\n */\nexport const studioResetPassword = async (token: string, password: string) =>\n resetPassword(token, password, `${BASE_URL}/api/server/resetPassword`);\n\n/**\n * Resets the password for the user.\n *\n * @param token - the reset token recieved as part of the `startPasswordReset` process\n * @param password - the new password to be used by the user specified in the token.\n * @param url - the url to send the login request to.\n * @defaultValue - defaults to the Admin server URL.\n * @returns an API response with no value.\n *\n * @internal\n * @see resetPassword\n */\nexport const resetPassword = async (\n token: string,\n password: string,\n url = `${BASE_URL}/api/resetPassword`\n) => {\n log.debug(\n `resetting password with token ${token} and password ${password.replace(\n /./g,\n \"*\"\n )}`\n );\n const response = await kosFetch(`${url}`, {\n method: `POST`,\n destinationAddress: \"\",\n body: JSON.stringify({\n token,\n password,\n }),\n });\n log.debug(`password reset returned status ${response.status}`);\n if (!response.ok) {\n log.error(`password reset failed with message ${response.statusText}`);\n\n const configResponse = await response.json();\n\n throw Error(\n `${configResponse?.error}:There was a problem resetting the password.`\n );\n }\n const configResponse: KosServiceResponse<unknown> | null =\n await response.json();\n return configResponse;\n};\n\nexport const studioAcceptOrgInvitation = async (\n token: string,\n password: string,\n name: string\n) =>\n acceptOrgInvitation(\n token,\n password,\n name,\n `${BASE_URL}/api/server/acceptInvite`\n );\nexport const acceptOrgInvitation = async (\n token: string,\n password: string,\n name: string,\n url = `${BASE_URL}/api/server/acceptInvite`\n) => {\n log.debug(\n `accepting invite with token ${token} and password ${password.replace(\n /./g,\n \"*\"\n )}`\n );\n const response = await kosFetch(`${url}`, {\n method: `POST`,\n destinationAddress: \"\",\n body: JSON.stringify({\n token,\n password,\n name,\n }),\n });\n log.debug(`invitation accept returned status ${response.status}`);\n if (!response.ok) {\n log.error(`invite failed with message ${response.statusText}`);\n\n const configResponse = await response.json();\n\n throw Error(\n `${configResponse?.error}:There was a problem accepting the invite.`\n );\n }\n const configResponse: KosServiceResponse<unknown> | null =\n await response.json();\n return configResponse;\n};\n","/* eslint-disable @typescript-eslint/no-unsafe-declaration-merging */\n\nimport {\n kosLoggerAware,\n KosLoggerAware,\n kosModel,\n} from \"../../../core/core/decorators\";\nimport type { IKosDataModel } from \"../../../core/core/kosModel\";\nimport type { KosModelRegistrationType } from \"../../../core/core/registration/model-registration\";\nimport type { IKosIdentifiable } from \"../../../core/core/types\";\nimport type { PublicModelInterface } from \"../../../core/types\";\n\nimport type { GpioPinOptions } from \"./types\";\n\nexport const MODEL_TYPE = \"gpio-pin-model\";\n\nexport type GpioPinModel = PublicModelInterface<GpioPinModelImpl>;\n\n// Interface merging for decorator type safety\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface GpioPinModelImpl extends KosLoggerAware {}\n\n@kosModel({ modelTypeId: MODEL_TYPE, singleton: false })\n@kosLoggerAware()\nexport class GpioPinModelImpl implements IKosDataModel, IKosIdentifiable {\n // Registration property for type safety - actual value injected by @kosModel decorator\n static Registration: KosModelRegistrationType<GpioPinModel, GpioPinOptions>;\n\n id: string;\n pinNum: number;\n chipNum: number;\n name: string;\n status: \"bound\" | \"pending\" | \"invalid\" | \"free\";\n connected: boolean;\n // logger property is automatically provided by @kosLoggerAware decorator\n\n constructor(modelId: string, options: GpioPinOptions) {\n this.id = modelId;\n this.chipNum = options.chipNum;\n this.pinNum = options.pinNum;\n this.name = options.name;\n this.status = \"free\";\n this.connected = options.connected ?? false;\n }\n\n updateModel(\n options: Partial<Omit<GpioPinOptions, \"chipNum\" | \"pinNum\" | \"name\">>\n ): void {\n this.status = options.status ?? this.status;\n this.connected = options.connected ?? this.connected;\n\n // Update model properties here.\n }\n\n // -------------------LIFECYCLE----------------------------\n\n async init(): Promise<void> {\n this.logger.debug(`initializing gpio-pin ${this.id}`);\n }\n\n async load(): Promise<void> {\n this.logger.debug(`loading gpio-pin ${this.id}`);\n }\n}\n\nexport const GpioPin = GpioPinModelImpl.Registration;\n","/* eslint-disable @typescript-eslint/no-unsafe-declaration-merging */\nimport {\n kosContainerAware,\n kosLoggerAware,\n kosModel,\n type KosContainerAware,\n type KosLoggerAware,\n} from \"../../../core/core/decorators\";\nimport type { IKosDataModel } from \"../../../core/core/kosModel\";\nimport type { KosModelRegistrationType } from \"../../../core/core/registration/model-registration\";\nimport type { IKosIdentifiable } from \"../../../core/core/types\";\nimport type { PublicModelInterface } from \"../../../core/types\";\n\nimport { GpioPin, type GpioPinModel } from \"./gpio-pin-model\";\nimport type { GpioPinContainerOptions } from \"./types\";\n\nexport const MODEL_TYPE = \"gpio-pin-container-model\";\n\nexport type GpioPinContainerModel =\n PublicModelInterface<GpioPinContainerModelImpl>;\n\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface GpioPinContainerModelImpl\n extends KosLoggerAware,\n KosContainerAware<GpioPinModel> {}\n\n@kosModel({ modelTypeId: MODEL_TYPE, singleton: false })\n@kosContainerAware<GpioPinModel>({\n containerOptions: {\n sortKey: \"pinNum\",\n },\n})\n@kosLoggerAware()\nexport class GpioPinContainerModelImpl\n implements IKosIdentifiable, IKosDataModel\n{\n // Registration property for type safety - actual value injected by @kosModel decorator\n static Registration: KosModelRegistrationType<\n GpioPinContainerModel,\n GpioPinContainerOptions\n >;\n\n id: string;\n\n constructor(modelId: string, _options: GpioPinContainerOptions) {\n this.id = modelId;\n // Container is automatically injected with parentId: modelId\n }\n\n updateModel(_options: GpioPinContainerOptions): void {\n // Update model properties here.\n }\n\n getPin(pinNum: number) {\n const pin = this.data[pinNum];\n if (!pin) {\n this.logger.warn(\n `Pin number ${pinNum} not found in container ${this.id}`\n );\n return undefined;\n }\n if (pin.pinNum !== pinNum) {\n this.logger.warn(\n `Pin number mismatch for pin ${pin.id} in container ${this.id}: expected ${pinNum}, got ${pin.pinNum}`\n );\n return undefined;\n }\n return this.data[pinNum];\n }\n // -------------------LIFECYCLE----------------------------\n\n async init(): Promise<void> {\n this.logger.debug(`initializing gpio-pin-container container ${this.id}`);\n }\n\n async load(): Promise<void> {\n this.logger.debug(`loading gpio-pin-container container ${this.id}`);\n }\n}\nexport const GpioPinContainer = GpioPinContainerModelImpl.Registration;\n\nGpioPinContainer.addRelatedModel(GpioPin);\n","/* eslint-disable @typescript-eslint/no-unsafe-declaration-merging */\n\nimport {\n kosChild,\n kosLoggerAware,\n KosLoggerAware,\n kosModel,\n} from \"../../../core/core/decorators\";\nimport type { IKosDataModel } from \"../../../core/core/kosModel\";\nimport type { KosModelRegistrationType } from \"../../../core/core/registration/model-registration\";\nimport type { IKosIdentifiable } from \"../../../core/core/types\";\nimport type { PublicModelInterface } from \"../../../core/types\";\nimport { GpioPinContainer, type GpioPinContainerModel } from \"../gpio-pin\";\n\nimport type { GpioChipOptions } from \"./types\";\n\nexport const MODEL_TYPE = \"gpio-chip-model\";\n\nexport type GpioChipModel = PublicModelInterface<GpioChipModelImpl>;\n\n// Interface merging for decorator type safety\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface GpioChipModelImpl extends KosLoggerAware {}\n\n@kosModel({ modelTypeId: MODEL_TYPE, singleton: false })\n@kosLoggerAware()\nexport class GpioChipModelImpl implements IKosDataModel, IKosIdentifiable {\n // Registration property for type safety - actual value injected by @kosModel decorator\n static Registration: KosModelRegistrationType<GpioChipModel, GpioChipOptions>;\n\n id: string;\n\n num: number;\n devName: string;\n name: string;\n pinCount: number;\n pinNames: string[];\n\n @kosChild private _pins: GpioPinContainerModel;\n // logger property is automatically provided by @kosLoggerAware decorator\n\n constructor(modelId: string, options: GpioChipOptions) {\n this.id = modelId;\n // logger is automatically injected by @kosLoggerAware decorator\n\n this.num = options.num;\n this.devName = options.devName;\n this.name = options.name;\n this.pinCount = options.pinCount;\n this.pinNames = options.pinNames;\n this._pins = GpioPinContainer.instance(`${this.id}-pins`)\n .options({})\n .build();\n }\n\n get pinManager() {\n return this._pins;\n }\n\n updateModel(_options: GpioChipOptions): void {\n // Update model properties here.\n }\n\n // -------------------LIFECYCLE----------------------------\n\n async handleGpioChipLoad(): Promise<void> {}\n async init(): Promise<void> {\n this.logger.debug(`initializing gpio-chip ${this.id}`);\n }\n\n async load(): Promise<void> {\n this.logger.debug(`loading gpio-chip ${this.id}`);\n }\n}\n\nexport const GpioChip = GpioChipModelImpl.Registration;\n","import { KOS_SERVICE_1_9_X as KOS_SERVICE } from \"../../../utils/services-index\";\n\nexport const GPIO_CHIP_PATH: KOS_SERVICE.ApiPath = \"/api/kos/gpio/chips\";\nexport type GpioChipContainerResponse = KOS_SERVICE.ApiResponse<\n typeof GPIO_CHIP_PATH,\n \"get\"\n>;\n\nexport const GPIO_PIN_PATH: KOS_SERVICE.ApiPath = \"/api/kos/gpio/pins\";\nexport type GpioPinContainerResponse = KOS_SERVICE.ApiResponse<\n typeof GPIO_PIN_PATH,\n \"get\"\n>;\n\nexport const gpioServiceRequest = KOS_SERVICE.kosServiceRequest;\nexport const gpioApi = KOS_SERVICE.api;\n","import { GpioPin } from \"../gpio-pin\";\nimport { GpioChip, type GpioChipModel } from \"./gpio-chip-model\";\nimport { type GpioChipContainerResponse } from \"./services\";\nimport { type GpioChipOptions } from \"./types\";\n\nexport type GpioChipResponse = GpioChipContainerResponse[number];\n\nexport interface GpioChipDto extends GpioChipOptions {\n id: string;\n}\n\nexport function mapGpioChipToOptions(dto: GpioChipDto): GpioChipOptions {\n return dto;\n}\n\nexport function createGpioChipModel(dto: GpioChipDto): GpioChipModel {\n return GpioChip.instance(dto.id).options(mapGpioChipToOptions(dto)).build();\n}\n\nexport function updateGpioChipModel(\n dto: GpioChipDto,\n model: GpioChipModel\n): void {\n model.updateModel(mapGpioChipToOptions(dto));\n}\n\nexport function filterGpioChipDto(chip: GpioChipResponse): boolean {\n return !!chip.num || chip.num === 0;\n}\n\nexport function mapGpioChipId(chip: GpioChipResponse): GpioChipDto {\n return {\n id: `${GpioChip.type}-${chip.num}`,\n num: chip.num ?? 0,\n devName: chip.devName ?? \"\",\n name: chip.name ?? \"\",\n pinCount: chip.pinCount ?? 0,\n pinNames: chip.pinNames ?? [],\n };\n}\n\nexport function afterGpioChipCreated(\n model: GpioChipModel,\n dto: GpioChipDto\n): void {\n dto.pinNames.forEach((pinName, index) => {\n const pinModel = GpioPin.instance(`${model.name}-${pinName}`)\n .options({\n name: pinName,\n pinNum: index,\n chipNum: dto.num,\n })\n .build();\n model.pinManager.addModel(pinModel);\n });\n}\n","/* eslint-disable @typescript-eslint/no-unsafe-declaration-merging */\nimport type { SingletonKosModelRegistrationFactory } from \"../../../core\";\nimport {\n kosContainerAware,\n kosLoggerAware,\n kosModel,\n type KosContainerAware,\n type KosLoggerAware,\n} from \"../../../core/core/decorators\";\nimport type { IKosDataModel } from \"../../../core/core/kosModel\";\nimport type { IKosIdentifiable } from \"../../../core/core/types\";\nimport {\n DependencyLifecycle,\n type PublicModelInterface,\n} from \"../../../core/types\";\n\nimport { GpioChip, type GpioChipModel } from \"./gpio-chip-model\";\nimport {\n GPIO_CHIP_PATH,\n gpioApi,\n gpioServiceRequest,\n type GpioChipContainerResponse,\n} from \"./services\";\nimport type { GpioChipContainerOptions } from \"./types\";\nimport {\n afterGpioChipCreated,\n createGpioChipModel,\n filterGpioChipDto,\n mapGpioChipId,\n updateGpioChipModel,\n type GpioChipResponse,\n} from \"./gpio-chip-builders\";\n\nexport const MODEL_TYPE = \"gpio-chip-container-model\";\n\nexport type GpioChipContainerModel =\n PublicModelInterface<GpioChipContainerModelImpl>;\n\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface GpioChipContainerModelImpl\n extends KosLoggerAware,\n KosContainerAware<GpioChipModel, GpioChipResponse> {}\n\n@kosModel({ modelTypeId: MODEL_TYPE, singleton: true })\n@kosContainerAware<GpioChipModel>({\n containerOptions: {\n sortKey: \"num\",\n },\n reconcile: {\n create: createGpioChipModel,\n update: updateGpioChipModel,\n filter: filterGpioChipDto,\n idMapper: mapGpioChipId,\n afterCreate: afterGpioChipCreated,\n },\n})\n@kosLoggerAware()\nexport class GpioChipContainerModelImpl\n implements IKosIdentifiable, IKosDataModel\n{\n // Registration property for type safety - actual value injected by @kosModel decorator\n static Registration: SingletonKosModelRegistrationFactory<\n GpioChipContainerModel,\n GpioChipContainerOptions\n >;\n\n id: string;\n destinationAddress: string;\n\n constructor(modelId: string, options: GpioChipContainerOptions) {\n this.id = modelId;\n this.destinationAddress = options.destinationAddress ?? \"\";\n }\n\n updateModel(_options: GpioChipContainerOptions): void {\n // Update model properties here.\n }\n // -------------------LIFECYCLE----------------------------\n\n @gpioServiceRequest({\n path: GPIO_CHIP_PATH,\n method: \"get\",\n errorHandler: {\n strategy: \"log\",\n defaultValue: [],\n },\n lifecycle: DependencyLifecycle.INIT,\n requestOptions: (model) => {\n return {\n destinationAddress: (model as GpioChipContainerModelImpl)\n .destinationAddress,\n };\n },\n })\n async handleGpioChipInit(\n _error: never,\n response: Record<string, GpioChipContainerResponse>\n ): Promise<void> {\n const [error, pinData] = await gpioApi.get(\n \"/api/kos/gpio/pins\",\n undefined,\n {\n destinationAddress: this.destinationAddress,\n }\n );\n\n if (error) {\n this.logger.error(\"Failed to fetch GPIO pins\", error);\n return;\n }\n\n this.reconcile(Object.values(response).flat());\n\n const statuses = [\"bound\", \"pending\", \"invalid\", \"free\"] as const;\n for (const status of statuses) {\n Object.entries(pinData as Record<string, any>).forEach(\n ([_key, value]) => {\n value?.[status]?.forEach((pin) => {\n const pinNum = pin.pinNum;\n const chipNum = pin.chipNum;\n if (chipNum === undefined || pinNum === undefined) {\n this.logger.warn(\n \"Skipping pin with missing chipNum or pinNum\",\n pin\n );\n return;\n }\n const chipModel = this.data[chipNum];\n if (!chipModel || chipModel.num !== chipNum) {\n this.logger.warn(\n `No chip model found for chipNum ${chipNum} when processing pin ${pinNum}`\n );\n return;\n }\n const pinModel = chipModel.pinManager.getPin(pinNum);\n if (!pinModel) {\n this.logger.warn(\n `No pin model found for pinNum ${pinNum} in chipNum ${chipNum}`\n );\n return;\n }\n\n pinModel.updateModel({\n connected: pin.connected,\n status: status,\n });\n });\n }\n );\n }\n }\n async init(): Promise<void> {\n this.logger.debug(`initializing gpio-chip-container container ${this.id}`);\n }\n\n async load(): Promise<void> {\n this.logger.debug(`loading gpio-chip-container container ${this.id}`);\n }\n}\nexport const GpioChipContainer = GpioChipContainerModelImpl.Registration;\n\nGpioChipContainer.addRelatedModel(GpioChip);\n","import { KosLog, type ServiceResponse } from \"../../../../core\";\nimport API, { type ApiPath, type ApiResponse } from \"../../../utils/service\";\n\nconst log = KosLog.createLogger({\n name: \"studio-properties-service\",\n group: \"Services\",\n});\n\nconst SERVICE_PATH: ApiPath = \"/api/kos/studio/properties\";\nexport type StudioPropertiesClientResponse = ApiResponse<\n typeof SERVICE_PATH,\n \"get\"\n>;\nexport interface StudioPropertiesResponse {\n data?: Record<string, any>;\n}\n\n/**\n * @category Service\n * Retrieves the initial studio-properties data.\n */\nexport const getStudioProperties = async (\n connectionId: string\n): Promise<ServiceResponse<StudioPropertiesResponse>> => {\n log.debug(\"sending GET for studio-properties\");\n if (!connectionId) {\n log.error(\"connectionId is undefined\");\n throw new Error(\"connectionId is undefined\");\n }\n return await API.get(\n SERVICE_PATH,\n {},\n {\n destinationAddress: connectionId,\n timeout: 500,\n }\n );\n};\n","import {\n kosComputed,\n KosLog,\n ObservableData,\n WebSocketTransport,\n type KosData,\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\";\nimport { getStudioProperties } from \"./services\";\n\nimport type { StudioPropertiesOptions } from \"./types\";\n\nexport const MODEL_TYPE = \"studio-properties-model\";\n\nconst TOPIC_PROPERTIES = \"/kos/studio/properties\";\n\n/**\n * Runtime properties of one KOS Studio connection, such as which Studio tools\n * are enabled. `initializePropertiesSession` loads the properties for the\n * connection and subscribes to its `/kos/studio/properties` topic; when the\n * properties cannot be loaded it falls back to defaults.\n * `terminatePropertiesSession` ends the subscription.\n *\n * @interface\n * @example\n * ```typescript\n * const studioProps = StudioProperties.instance(\"studio-conn-1\")\n * .options({ connectionId })\n * .build();\n * await studioProps.initializePropertiesSession();\n * const legacyTools = studioProps.get(\"kos.studio.tool.legacy\");\n * ```\n *\n * @group KOS Model\n * @category System Integration\n * @useDeclaredType\n *\n * @see {@link StudioPropertiesOptions} - Configuration options for StudioPropertiesModel instances\n */\nexport type StudioPropertiesModel =\n PublicModelInterface<StudioPropertiesModelImpl>;\n\nconst DEFAULT_STUDIO_PROPERTIES = {\n \"kos.studio.tool.legacy\": 1,\n};\n\n/**\n * @ignore\n * @internal\n */\n@kosModel(MODEL_TYPE)\nexport class StudioPropertiesModelImpl\n implements IKosDataModel, IKosIdentifiable\n{\n /** Unique identifier for the model instance */\n id: string;\n /** Studio VM connection identifier for property routing */\n connectionId: string;\n /** WebSocket subscription cleanup function */\n private unsubscribe: VoidFunction | null = null;\n /** Context logger for debugging and diagnostics */\n private logger: KosContextLogger;\n /** Observable data store for Studio properties */\n private data: KosData<Record<string, any>>;\n constructor(\n modelId: string,\n options: StudioPropertiesOptions,\n context: KosCreationContext\n ) {\n this.id = modelId;\n this.logger = context.logger;\n\n this.data = ObservableData();\n this.connectionId = options.connectionId;\n }\n\n // -------------------LIFECYCLE----------------------------\n\n /**\n * @internal\n */\n async init(): Promise<void> {\n this.logger.debug(`initializing studio-properties ${this.id}`);\n }\n\n /**\n * @internal\n */\n async load(): Promise<void> {\n this.logger.debug(`loading studio-properties ${this.id}`);\n }\n\n /** Ends the `/kos/studio/properties` subscription. */\n async terminatePropertiesSession(): Promise<void> {\n this.unsubscribe?.();\n }\n\n /**\n * Loads the connection's properties and subscribes to its `/kos/studio/properties` topic.\n */\n async initializePropertiesSession() {\n this.unsubscribe = WebSocketTransport.getInstance().subscribeTopic({\n topic: TOPIC_PROPERTIES,\n destinationAddress: this.connectionId,\n callback: (msg) => {\n this.logger.error(\n `Received studio-properties message for connection ${\n this.connectionId\n }: ${JSON.stringify(msg)}`\n );\n },\n });\n const [error, data] = await getStudioProperties(this.connectionId);\n if (error) {\n this.logger.error(`Error loading studio-properties: ${error}`);\n this.data.setValues(DEFAULT_STUDIO_PROPERTIES);\n return;\n }\n if (data) {\n const update = Object.keys(data).reduce((acc, key) => {\n acc[key] = data[key] ?? key;\n return acc;\n }, {});\n this.data.setValues(update ?? DEFAULT_STUDIO_PROPERTIES);\n KosLog.ifDebug(() =>\n this.logger.debug(`studio-properties loaded: ${JSON.stringify(update)}`)\n );\n }\n }\n\n /**\n * Retrieves a Studio property value by key.\n * @param key Property key to retrieve\n * @returns The property value or undefined if not set\n */\n get(key: string): any {\n return this.data[key];\n }\n\n /**\n * A computed value that tracks one property.\n * @param key Property key to observe\n * @returns Computed value of the property\n */\n createObservableProperty(key: string) {\n return kosComputed(() => this.get(key));\n }\n}\n","import { KosModelRegistrationFactory } from \"../../../core/core/registration\";\nimport type { StudioPropertiesOptions } from \"./types\";\nimport {\n StudioPropertiesModelImpl,\n MODEL_TYPE,\n} from \"./studio-properties-model\";\nimport type { StudioPropertiesModel } from \"./studio-properties-model\";\n\n/**\n * Registration for {@link StudioPropertiesModel}.\n *\n * `type` identifies the model in the registry and in `@kosDependency` declarations.\n * `register()` adds the model to the registry. `instance(id)` builds the model, or returns the existing one when the id is already in use.\n *\n * @example\n * ```typescript\n * const model = StudioProperties.instance(\"studioPropertiesId\").options(options).build();\n * ```\n */\nexport const StudioProperties = new KosModelRegistrationFactory<\n StudioPropertiesModel,\n StudioPropertiesOptions\n>({\n class: StudioPropertiesModelImpl,\n type: MODEL_TYPE,\n});\n","import { css, keyframes } from \"@emotion/react\";\n\nexport const run = keyframes`\n 0% {\n left: -90px;\n color: #eee;\n }\n 50% {\n color: #666;\n }\n 100% {\n left: 90px;\n color: #eee;\n }\n`;\n\nexport const loadingDot = css`\n font-size: 100px;\n margin-top: -80px;\n position: relative;\n animation: ${run} ease-in-out infinite alternate;\n animation-duration: 1.2s;\n`;\n","import styled from \"@emotion/styled\";\nimport { createPortal } from \"react-dom\";\nimport { loadingDot } from \"./loading-message-styles\";\n\ninterface PortalProps {\n children: React.ReactNode;\n}\n\nexport const Portal = ({ children }: PortalProps) =>\n createPortal(children, document.body);\ninterface Props {\n message?: string;\n theme?: \"light\" | \"dark\";\n}\nfunction LoadingMessage({\n message = \"Wait a moment while we load your app.\",\n theme = \"light\",\n}: Props) {\n return (\n <Portal>\n <MessageContainer theme={theme}>\n {message}\n <div css={loadingDot}>.</div>\n </MessageContainer>\n </Portal>\n );\n}\n\nexport default LoadingMessage;\n\nconst MessageContainer = styled.div<{ theme: \"light\" | \"dark\" }>`\n padding-inline: 20px;\n width: 100%;\n height: 100vh;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n position: fixed;\n font-size: 14px;\n top: 0;\n left: 0;\n color: ${({ theme }) => (theme === \"light\" ? \"black\" : \"white\")};\n z-index: 10000;\n`;\n","import React, { ErrorInfo } from \"react\";\nimport { KosLog } from \"../../../core\";\n\nconst log = KosLog.createLogger({ name: \"error-boundary\" });\n\nexport interface ErrorBoundaryState {\n error: Error | null;\n errorInfo: ErrorInfo | null;\n}\n\nexport interface ErrorBoundaryProps extends React.PropsWithChildren {\n fallback?: React.ReactNode;\n /** Names the guarded region so a caught error is traceable to its seam. */\n name?: string;\n}\nclass ErrorBoundary extends React.Component<\n ErrorBoundaryProps,\n ErrorBoundaryState\n> {\n constructor(props: ErrorBoundaryProps) {\n super(props);\n this.state = { error: null, errorInfo: null };\n }\n\n /**\n * Recovers during the render phase. Without this React renders the boundary\n * with `null` children and waits for `componentDidCatch` to schedule a\n * fallback, and a second error in the same batch escalates past the boundary\n * to the root, unmounting the whole tree.\n */\n static getDerivedStateFromError(\n error: Error\n ): Pick<ErrorBoundaryState, \"error\"> {\n return { error };\n }\n\n override componentDidCatch(error: Error, errorInfo: ErrorInfo) {\n // A boundary that swallows the cause leaves nothing to diagnose, so the\n // error is reported before the fallback replaces the subtree.\n const seam = this.props.name ? ` in ${this.props.name}` : \"\";\n // The message carries the cause inline: an Error passed as a bare argument\n // serialises to `{}` under some log sinks.\n log.error(\n `Error boundary caught${seam}: ${error?.message ?? error}`,\n error,\n errorInfo.componentStack\n );\n this.setState({\n error: error,\n errorInfo: errorInfo,\n });\n }\n\n override render() {\n // Keyed on `error` because that is what the render phase sets; `errorInfo`\n // only arrives later, from the commit phase.\n if (this.state.error) {\n // Error path\n return (\n this.props.fallback || (\n <div>\n <h2>Something went wrong.</h2>\n <details style={{ whiteSpace: `pre-wrap` }}>\n {this.state.error.toString()}\n <br />\n {this.state.errorInfo?.componentStack}\n </details>\n </div>\n )\n );\n }\n // Normally, just render children\n return this.props.children;\n }\n}\n\nexport default ErrorBoundary;\n","import { css } from \"@emotion/react\";\ntype Status = \"error\" | \"warn\" | \"normal\";\ninterface Props {\n value: number;\n title?: JSX.Element;\n subtitle?: string;\n status?: Status;\n}\n\nconst statusMap: Record<Status, string> = {\n normal: \"#B5F7F6\",\n warn: \"#F3D78A\",\n error: \"#FC8486\",\n};\nexport const ProgressBar = ({\n value = 0,\n title,\n status = \"normal\",\n subtitle,\n}: Props) => {\n const progressBarContainer = css`\n display: flex;\n flex-direction: column;\n `;\n const progressContainer = css`\n position: relative;\n height: 18px;\n width: 100%;\n background-color: #ddd;\n border-radius: 5px;\n overflow: hidden;\n `;\n\n const titleContainer = css`\n position: absolute;\n top: 50%; /* position the top edge of the element at the middle of the parent */\n left: 50%; /* position the left edge of the element at the middle of the parent */\n z-index: 5;\n transform: translate(-50%, -50%);\n font-size: smaller;\n `;\n\n const progress = css`\n width: ${value}%;\n height: 35px;\n background-color: ${statusMap[status]};\n text-align: center;\n line-height: 32px;\n color: black;\n `;\n\n const indeterminate = css`\n animation: indeterminateAnimation 1s infinite linear;\n transform-origin: 0% 50%;\n @keyframes indeterminateAnimation {\n 0% {\n transform: translateX(0) scaleX(0);\n }\n 40% {\n transform: translateX(0) scaleX(0.4);\n }\n 100% {\n transform: translateX(100%) scaleX(0.5);\n }\n }\n `;\n\n return (\n <div css={progressBarContainer}>\n <div css={progressContainer}>\n <div css={titleContainer}>{title}</div>\n <div css={[progress, value < 0 ? indeterminate : \"\"]}></div>\n </div>\n <div>{subtitle}</div>\n </div>\n );\n};\n","import {\n createContext,\n PropsWithChildren,\n useCallback,\n useContext,\n useState,\n} from \"react\";\nimport { IKosDataModel } from \"../../../../core\";\n\ninterface KosModelContextProps {\n model?: IKosDataModel;\n setModel: (model: IKosDataModel) => boolean;\n}\n\nconst defaultProps: KosModelContextProps = {\n setModel: () => false,\n};\n\nexport const KosModelContext =\n createContext<KosModelContextProps>(defaultProps);\n\nexport const useContextModel = <T extends IKosDataModel>(): T | undefined => {\n const context = useContext(KosModelContext);\n if (context == undefined) {\n throw new Error(`useModels must be used within a KosModelProvider`);\n }\n return context.model as T;\n};\n\nexport const KosModelProvider: React.FunctionComponent<PropsWithChildren> = ({\n children,\n}) => {\n const [model, setModel] = useState<IKosDataModel>();\n const setKosModel = useCallback(\n (kosModel: IKosDataModel) => {\n setModel(kosModel);\n return true;\n },\n [setModel]\n );\n return (\n <KosModelContext.Provider value={{ model, setModel: setKosModel }}>\n {children}\n </KosModelContext.Provider>\n );\n};\n","import {\n createContext,\n PropsWithChildren,\n useCallback,\n useContext,\n useMemo,\n useState,\n} from \"react\";\nimport { getKosModelSync, IKosDataModel, KosLog } from \"../../../../core\";\n\ninterface KosNestedModelContextProps {\n models: IKosDataModel[];\n addModel: (model: IKosDataModel) => void;\n}\n\nconst log = KosLog.createLogger({ name: \"kos-model-hierarchy-context\" });\nconst defaultNestedProps: KosNestedModelContextProps = {\n models: [],\n addModel: () => {\n log.debug(\"Default implementation being used. Do Nothing.\");\n },\n};\n\nexport const NestedModelContext =\n createContext<KosNestedModelContextProps>(defaultNestedProps);\n\nexport const KosModelCollectionProvider: React.FunctionComponent<\n PropsWithChildren\n> = ({ children }) => {\n const [models, setModels] = useState<IKosDataModel[]>([]);\n const addModel = useCallback(\n (model: IKosDataModel) => {\n if (!models.includes(model)) {\n log.debug(\"adding to hierarchy context\", model.id);\n setModels((prevModels) => [...prevModels, model]);\n }\n },\n [models]\n );\n return (\n <NestedModelContext.Provider value={{ models, addModel }}>\n {children}\n </NestedModelContext.Provider>\n );\n};\n\ninterface ModelHierarchyProps {\n filter?: (model: IKosDataModel) => boolean;\n}\n\nconst DEFAULT_FILTER = () => true;\nexport const useContextModelHierarchy = (\n props?: ModelHierarchyProps\n): IKosDataModel[] => {\n const context = useContext(NestedModelContext);\n if (!context) {\n throw new Error(\n `useContextModelHierarchy must be used within a KosModelCollectionProvider`\n );\n }\n\n const filter = props?.filter || DEFAULT_FILTER;\n const filteredModels = useMemo(\n () => context.models.filter(filter),\n [context.models, filter]\n );\n return filteredModels;\n};\n\nexport const useModelFromHierarchy = <T extends IKosDataModel = IKosDataModel>(\n type: string\n): T | undefined => {\n const context = useContextModelHierarchy({\n filter: (model) => {\n const _model = getKosModelSync(model.id);\n return _model?.type === type;\n },\n });\n return context[0] as T;\n};\n","import {\n PropsWithChildren,\n Suspense,\n useContext,\n useEffect,\n useState,\n} from \"react\";\nimport { IKosDataModel, KosLog } from \"../../../core\";\nimport { ErrorBoundaryWithFallback } from \"../error-boundary\";\nimport { ErrorBoundaryProps } from \"../error-boundary/error-boundary\";\nimport {\n KosModelContext,\n KosModelProvider,\n} from \"./contexts/kos-model-context\";\nimport { NestedModelContext } from \"./contexts/kos-model-hierarchy-context\";\n\nconst log = KosLog.createLogger({ name: \"kos-model-loader\" });\nexport interface KosModelLoaderProps {\n model?: IKosDataModel;\n ready: boolean;\n error?: string;\n loading?: React.ReactElement;\n}\n\nconst DefaultLoader = () => <div></div>;\n\nexport const KosModelLoader: React.FunctionComponent<\n PropsWithChildren<ErrorBoundaryProps & KosModelLoaderProps>\n> = ({ fallback, children, ...modelProps }) => (\n <KosModelProvider>\n <ErrorBoundaryWithFallback fallback={fallback}>\n <Suspense>\n <KosModelLoaderDisplay {...modelProps}>\n {children}\n </KosModelLoaderDisplay>\n </Suspense>\n </ErrorBoundaryWithFallback>\n </KosModelProvider>\n);\nexport const KosModelLoaderDisplay: React.FunctionComponent<\n PropsWithChildren<KosModelLoaderProps>\n> = (props) => {\n const [model, setCurrentModel] = useState<IKosDataModel>();\n const [isReady, setIsReady] = useState(false);\n const { setModel } = useContext(KosModelContext);\n const hierarchyContext = useContext(NestedModelContext);\n useEffect(() => {\n if (props.model) {\n setCurrentModel(props.model);\n setModel(props.model);\n setIsReady(true);\n if (hierarchyContext) {\n hierarchyContext.addModel(props.model);\n }\n }\n }, [hierarchyContext, props.model, setModel]);\n\n if (props.error) {\n log.error(props.error);\n throw new Error(props.error);\n }\n\n const loader = props.loading || <DefaultLoader></DefaultLoader>;\n return <>{model && isReady ? props.children : loader}</>;\n};\n","import type { IKosCoreManager, IKosRegistry } from \"../../core\";\nimport { KosCore, wrapPromise } from \"../../core\";\n\nexport function fetchKosCore(registration: IKosRegistry, alias?: string) {\n const kosCore = KosCore.create(registration, false, alias);\n const promise = kosCore.whenReady().then(() => kosCore);\n return wrapPromise<IKosCoreManager>(promise);\n}\n","import { observer } from \"mobx-react-lite\";\nimport React, { useEffect, useMemo } from \"react\";\nimport { IKosCoreManager, IKosRegistry, kosAutoEffect } from \"../../core\";\nimport { fetchKosCore } from \"./fetch-kos-core\";\n\nexport interface ProviderProps {\n children?: React.ReactNode;\n}\n\ninterface IKosContext {\n kosCore: IKosCoreManager;\n online: boolean;\n}\nconst KosContext = React.createContext<IKosContext | undefined>(undefined);\nconst initKosProvider = (\n registration: IKosRegistry = { models: {}, preloadModels: [] },\n alias?: string\n) => {\n const resource = fetchKosCore(registration, alias);\n\n const KosCoreContextProvider: React.FC<ProviderProps> = ({ children }) => {\n const kosCore = resource.read();\n const [online, setOnline] = React.useState(kosCore.isOnline);\n\n useEffect(() => {\n const disposer = kosAutoEffect(() => {\n setOnline(kosCore.isOnline);\n });\n\n return () => {\n disposer();\n };\n }, [kosCore]);\n\n const value = useMemo<IKosContext>(() => {\n return { kosCore, online };\n }, [kosCore, online]);\n\n return <KosContext.Provider value={value}>{children}</KosContext.Provider>;\n };\n\n return { KosCoreContextProvider: observer(KosCoreContextProvider) };\n};\n\nexport const useKosCore = () => {\n const context = React.useContext(KosContext);\n if (context === undefined) {\n throw new Error(`useKosCore must be used within a KosCoreContextProvider`);\n }\n\n return context;\n};\n\nexport default initKosProvider;\n","/**\n * sessionStorage key used to signal to the next page load that a\n * reload-on-disconnect recovery just occurred. Overlay components read it\n * on mount so the \"reconnecting\" UI can persist across the reload without\n * a visible gap.\n *\n * @kosService core.reload-on-disconnect-policy\n * @kosApiLevel 23\n */\nexport const KOS_RECOVERING_SESSION_KEY = \"kos:recovering\";\n","import { useEffect, useRef } from \"react\";\nimport { EventBus } from \"../../common\";\nimport { WebSocketEvents } from \"../../core/core/transport/base-message-transport\";\nimport { KosLog } from \"../../core/core/log\";\nimport { KOS_RECOVERING_SESSION_KEY } from \"./constants\";\n\n/**\n * Metadata the policy records about the triggering disconnect.\n *\n * @kosService core.reload-on-disconnect-policy\n * @kosApiLevel 23\n */\nexport interface ReloadOnDisconnectInfo {\n code: number;\n reason: string;\n wasClean: boolean;\n at: number;\n}\n\n/**\n * Props for ReloadOnDisconnectPolicy.\n *\n * @kosService core.reload-on-disconnect-policy\n * @kosApiLevel 23\n */\nexport interface ReloadOnDisconnectPolicyProps {\n /**\n * Delay before reloading, in milliseconds. Lets rapid-fire reconnect\n * attempts settle without stacking reloads. Default: 3000.\n */\n graceMs?: number;\n /**\n * Called synchronously immediately before the reload. Useful for\n * telemetry. Keep it synchronous, since the reload may preempt async work.\n */\n onBeforeReload?: (info: ReloadOnDisconnectInfo) => void;\n /**\n * Test seam. Replace the reload function. Defaults to\n * () => window.location.reload().\n */\n reloadFn?: () => void;\n}\n\nconst DEFAULT_GRACE_MS = 3000;\n\nconst defaultReloadFn = () => {\n window.location.reload();\n};\n\n/**\n * Mounts a connection-recovery policy: when the WebSocket disconnects, wait\n * a short grace window, record the disconnect in sessionStorage, then\n * `window.location.reload()` the page. Renders nothing.\n *\n * The grace window only de-bounces rapid disconnect/reconnect flapping. Even\n * a sub-second reconnect triggers the reload, because the data layer cannot\n * guarantee freshness across the gap.\n *\n * Apps that reconcile on reconnect instead (Studio, for example) do not mount\n * this policy.\n *\n * Pair with an overlay that reads `KOS_RECOVERING_SESSION_KEY` on mount to\n * keep a \"reconnecting\" message visible across the reload boundary.\n *\n * @kosService core.reload-on-disconnect-policy\n * @kosApiLevel 23\n */\nexport const ReloadOnDisconnectPolicy: React.FC<\n ReloadOnDisconnectPolicyProps\n> = ({\n graceMs = DEFAULT_GRACE_MS,\n onBeforeReload,\n reloadFn = defaultReloadFn,\n}) => {\n const pendingReloadRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n useEffect(() => {\n const { unsubscribe } = EventBus.subscribe(\n WebSocketEvents.DISCONNECTED,\n (msg) => {\n if (pendingReloadRef.current) {\n return;\n }\n\n const payload = msg?.body as\n | { code: number; reason: string; wasClean: boolean }\n | undefined;\n if (!payload || typeof payload.code !== \"number\") {\n return;\n }\n\n const info: ReloadOnDisconnectInfo = {\n code: payload.code,\n reason: payload.reason,\n wasClean: payload.wasClean,\n at: Date.now(),\n };\n\n try {\n sessionStorage.setItem(\n KOS_RECOVERING_SESSION_KEY,\n JSON.stringify(info)\n );\n } catch (err) {\n KosLog.warn(\n \"ReloadOnDisconnectPolicy: failed to write sessionStorage\",\n err\n );\n }\n\n KosLog.warn(\n `ReloadOnDisconnectPolicy: scheduling reload in ${graceMs}ms ` +\n `(code=${info.code}, wasClean=${info.wasClean})`\n );\n\n pendingReloadRef.current = setTimeout(() => {\n pendingReloadRef.current = null;\n try {\n onBeforeReload?.(info);\n } catch (err) {\n KosLog.error(\"ReloadOnDisconnectPolicy: onBeforeReload threw\", err);\n }\n reloadFn();\n }, graceMs);\n }\n );\n\n return () => {\n unsubscribe();\n if (pendingReloadRef.current) {\n clearTimeout(pendingReloadRef.current);\n pendingReloadRef.current = null;\n }\n };\n }, [graceMs, onBeforeReload, reloadFn]);\n\n return null;\n};\n","import { useEffect, useState } from \"react\";\nimport { EventBus } from \"../../../common\";\nimport { WebSocketEvents } from \"../../../core/core/transport/base-message-transport\";\nimport { useKosCore } from \"../../contexts/kos-core-context\";\nimport {\n KOS_RECOVERING_SESSION_KEY,\n type ReloadOnDisconnectInfo,\n} from \"../../policies\";\n\n/**\n * Snapshot of the overlay's state, returned by useReconnectingOverlayState.\n *\n * @kosService core.use-reconnecting-overlay-state\n * @kosApiLevel 23\n */\nexport interface ReconnectingOverlayState {\n /** Whether the overlay should currently be displayed. */\n visible: boolean;\n /** Details of the disconnect, if one is being recovered from. */\n info: ReloadOnDisconnectInfo | null;\n /** Milliseconds since the tracked disconnect, or null. */\n sinceMs: number | null;\n /** Force-hide the overlay. Does not clear `info`. */\n dismiss: () => void;\n}\n\n/**\n * Options for useReconnectingOverlayState.\n *\n * @kosService core.use-reconnecting-overlay-state\n * @kosApiLevel 23\n */\nexport interface UseReconnectingOverlayStateOptions {\n /**\n * Predicate evaluated after a CONNECTED event. When true, the overlay\n * hides. Defaults to `({ online }) => online`, i.e. hide as soon as KOS\n * Core reports online. Apps that need to wait for specific model state\n * can pass a stricter predicate.\n */\n isReady?: (state: {\n online: boolean;\n info: ReloadOnDisconnectInfo | null;\n }) => boolean;\n /**\n * Whether to read `sessionStorage[KOS_RECOVERING_SESSION_KEY]` on mount\n * to carry overlay state across a page reload. Default: true. Set false\n * for apps that don't use the reload-on-disconnect policy.\n */\n readSessionStorage?: boolean;\n}\n\nconst defaultIsReady = ({ online }: { online: boolean }) => online;\n\nconst readRecoveringInfo = (): ReloadOnDisconnectInfo | null => {\n try {\n const raw = sessionStorage.getItem(KOS_RECOVERING_SESSION_KEY);\n if (!raw) return null;\n sessionStorage.removeItem(KOS_RECOVERING_SESSION_KEY);\n const parsed = JSON.parse(raw);\n if (\n parsed &&\n typeof parsed === \"object\" &&\n typeof parsed.code === \"number\"\n ) {\n return parsed as ReloadOnDisconnectInfo;\n }\n } catch {\n // sessionStorage may be unavailable or payload malformed; ignore\n }\n return null;\n};\n\n/**\n * Headless state hook for the reconnecting overlay.\n *\n * Becomes `visible` when a WebSocket disconnect is observed, or when the\n * page load carries a `KOS_RECOVERING_SESSION_KEY` in sessionStorage from\n * a prior reload-on-disconnect cycle. Becomes hidden when the ready\n * predicate reports the app is fully connected again.\n *\n * Returns { visible, info, sinceMs, dismiss }. Apps pair this with their\n * own overlay markup, or use the default `<ReconnectingOverlay />`.\n *\n * @kosService core.use-reconnecting-overlay-state\n * @kosApiLevel 23\n */\nexport const useReconnectingOverlayState = (\n options: UseReconnectingOverlayStateOptions = {}\n): ReconnectingOverlayState => {\n const { isReady = defaultIsReady, readSessionStorage = true } = options;\n const { online } = useKosCore();\n\n const [info, setInfo] = useState<ReloadOnDisconnectInfo | null>(() =>\n readSessionStorage ? readRecoveringInfo() : null\n );\n const [dismissed, setDismissed] = useState(false);\n\n useEffect(() => {\n const { unsubscribe } = EventBus.subscribe(\n WebSocketEvents.DISCONNECTED,\n (msg) => {\n const payload = msg?.body as\n | { code: number; reason: string; wasClean: boolean }\n | undefined;\n if (!payload || typeof payload.code !== \"number\") return;\n setInfo({\n code: payload.code,\n reason: payload.reason,\n wasClean: payload.wasClean,\n at: Date.now(),\n });\n setDismissed(false);\n }\n );\n return () => {\n unsubscribe();\n };\n }, []);\n\n const ready = isReady({ online, info });\n const visible = !dismissed && !!info && !ready;\n\n return {\n visible,\n info,\n sinceMs: info ? Date.now() - info.at : null,\n dismiss: () => setDismissed(true),\n };\n};\n","import { css, keyframes } from \"@emotion/react\";\n\nconst spin = keyframes`\n to { transform: rotate(360deg); }\n`;\n\nexport const overlayRoot = css`\n position: fixed;\n inset: 0;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n gap: 16px;\n background: rgba(0, 0, 0, 0.72);\n color: #ffffff;\n font-family: system-ui, -apple-system, \"Segoe UI\", sans-serif;\n z-index: 2147483647;\n pointer-events: auto;\n user-select: none;\n`;\n\nexport const spinner = css`\n width: 48px;\n height: 48px;\n border-radius: 50%;\n border: 4px solid rgba(255, 255, 255, 0.25);\n border-top-color: #ffffff;\n animation: ${spin} 1s linear infinite;\n`;\n\nexport const message = css`\n font-size: 18px;\n font-weight: 500;\n letter-spacing: 0.02em;\n`;\n","import type React from \"react\";\nimport {\n useReconnectingOverlayState,\n type ReconnectingOverlayState,\n type UseReconnectingOverlayStateOptions,\n} from \"./use-reconnecting-overlay-state\";\nimport { message, overlayRoot, spinner } from \"./reconnecting-overlay-styles\";\n\nexport {\n useReconnectingOverlayState,\n type ReconnectingOverlayState,\n type UseReconnectingOverlayStateOptions,\n} from \"./use-reconnecting-overlay-state\";\n\n/**\n * Props for the default ReconnectingOverlay.\n *\n * @kosService core.reconnecting-overlay\n * @kosApiLevel 23\n */\nexport interface ReconnectingOverlayProps\n extends UseReconnectingOverlayStateOptions {\n /** Override the default message (\"Reconnecting…\"). */\n messageText?: string;\n /**\n * Fully replace the rendered content with a custom renderer. Receives the\n * overlay state. If provided, the default layout (spinner + message) is\n * not rendered.\n */\n renderContent?: (state: ReconnectingOverlayState) => React.ReactNode;\n className?: string;\n}\n\n/**\n * Minimal, unbranded overlay that displays while the app is recovering\n * from a WebSocket disconnect (or immediately after a reload triggered by\n * ReloadOnDisconnectPolicy). Pair with that policy — or use in isolation\n * for apps that want to show the overlay without reloading.\n *\n * Apps with design-system requirements should wrap\n * `useReconnectingOverlayState` in their own component rather than relying\n * on these default styles.\n *\n * @kosService core.reconnecting-overlay\n * @kosApiLevel 23\n */\nexport const ReconnectingOverlay: React.FC<ReconnectingOverlayProps> = ({\n messageText = \"Reconnecting…\",\n renderContent,\n className,\n isReady,\n readSessionStorage,\n}) => {\n const state = useReconnectingOverlayState({ isReady, readSessionStorage });\n\n if (!state.visible) return null;\n\n return (\n <div\n css={overlayRoot}\n className={className}\n role=\"alertdialog\"\n aria-live=\"assertive\"\n aria-label=\"Reconnecting\"\n >\n {renderContent ? (\n renderContent(state)\n ) : (\n <>\n <div css={spinner} aria-hidden=\"true\" />\n <div css={message}>{messageText}</div>\n </>\n )}\n </div>\n );\n};\n","import { useEffect, useState } from \"react\";\nimport { KosCore, kosAutoEffect, type IKosCoreManager } from \"../../../core\";\n\n/**\n * Connection status shown by ConnectionDevButton.\n *\n * @kosService core.use-connection-dev-state\n * @kosApiLevel 25\n */\nexport type ConnectionDevStatus = \"online\" | \"offline\" | \"reconnecting\";\n\n/**\n * Snapshot of the connection, returned by useConnectionDevState.\n *\n * @kosService core.use-connection-dev-state\n * @kosApiLevel 25\n */\nexport interface ConnectionDevState {\n /**\n * `reconnecting` while KOS Core reloads or runs its reconnect sequence,\n * otherwise `online` or `offline` from the core's connection.\n */\n status: ConnectionDevStatus;\n}\n\nconst readStatus = (core: IKosCoreManager): ConnectionDevStatus => {\n if (core.reloading) return \"reconnecting\";\n return core.isOnline ? \"online\" : \"offline\";\n};\n\n/**\n * Headless state hook for ConnectionDevButton. Tracks KOS Core's `isOnline`\n * and `reloading` reactively and reports them as one status.\n *\n * @kosService core.use-connection-dev-state\n * @kosApiLevel 25\n */\nexport const useConnectionDevState = (): ConnectionDevState => {\n const [status, setStatus] = useState<ConnectionDevStatus>(() =>\n readStatus(KosCore.getInstance())\n );\n\n useEffect(() => {\n const core = KosCore.getInstance();\n const disposer = kosAutoEffect(() => {\n setStatus(readStatus(core));\n });\n return () => {\n disposer();\n };\n }, []);\n\n return { status };\n};\n","import { css } from \"@emotion/react\";\n\nconst OFFSET = \"16px\";\n\nexport const buttonRoot = css`\n position: fixed;\n display: inline-flex;\n align-items: center;\n gap: 8px;\n padding: 6px 12px;\n border: 1px solid rgba(255, 255, 255, 0.25);\n border-radius: 6px;\n background: rgba(0, 0, 0, 0.72);\n color: #ffffff;\n font-family: system-ui, -apple-system, \"Segoe UI\", sans-serif;\n font-size: 12px;\n line-height: 1.4;\n cursor: pointer;\n z-index: 2147483646;\n\n &:disabled {\n cursor: default;\n opacity: 0.6;\n }\n`;\n\nexport const positions = {\n \"bottom-left\": css`\n bottom: ${OFFSET};\n left: ${OFFSET};\n `,\n \"bottom-right\": css`\n bottom: ${OFFSET};\n right: ${OFFSET};\n `,\n \"top-left\": css`\n top: ${OFFSET};\n left: ${OFFSET};\n `,\n \"top-right\": css`\n top: ${OFFSET};\n right: ${OFFSET};\n `,\n} as const;\n\nexport const statusText = css`\n font-weight: 600;\n text-transform: uppercase;\n letter-spacing: 0.04em;\n`;\n","import type React from \"react\";\nimport { KosCore } from \"../../../core\";\nimport {\n useConnectionDevState,\n type ConnectionDevState,\n} from \"./use-connection-dev-state\";\nimport {\n buttonRoot,\n positions,\n statusText,\n} from \"./connection-dev-button-styles\";\n\nexport {\n useConnectionDevState,\n type ConnectionDevState,\n type ConnectionDevStatus,\n} from \"./use-connection-dev-state\";\n\n/**\n * Props for ConnectionDevButton.\n *\n * @kosService core.connection-dev-button\n * @kosApiLevel 25\n */\nexport interface ConnectionDevButtonProps {\n /** Screen corner the button is fixed to. Default: \"bottom-right\". */\n position?: \"bottom-left\" | \"bottom-right\" | \"top-left\" | \"top-right\";\n /** Button label. Default: \"Drop connection\". */\n label?: string;\n className?: string;\n /**\n * Fully replace the button's content with a custom renderer. Receives the\n * connection state. If provided, the default label and status are not\n * rendered.\n */\n renderContent?: (state: ConnectionDevState) => React.ReactNode;\n}\n\n/**\n * Minimal, unbranded development button that drops the KOS websocket so the\n * reconnect path can be exercised from any KOS application. Shows the live\n * connection status and, on click, calls the transport's `dropConnection()`;\n * the transport reconnects on its own and KOS Core runs its reconnect\n * sequence. Disabled while the core is not online.\n *\n * Pair with ReconnectingOverlay to see the reconnect as users do.\n *\n * @kosService core.connection-dev-button\n * @kosApiLevel 25\n */\nexport const ConnectionDevButton: React.FC<ConnectionDevButtonProps> = ({\n position = \"bottom-right\",\n label = \"Drop connection\",\n className,\n renderContent,\n}) => {\n const state = useConnectionDevState();\n\n return (\n <button\n type=\"button\"\n css={[buttonRoot, positions[position]]}\n className={className}\n disabled={state.status !== \"online\"}\n onClick={() => KosCore.getInstance().transport.dropConnection()}\n >\n {renderContent ? (\n renderContent(state)\n ) : (\n <>\n <span>{label}</span>\n <span css={statusText}>{state.status}</span>\n </>\n )}\n </button>\n );\n};\n","import React from \"react\";\n\ninterface HeaderTranslations {\n title: string;\n createLabel: string;\n deleteLabel: string;\n}\ninterface ModalTranslations {\n okText: string;\n cancelText: string;\n title: string;\n}\nexport interface Translations {\n header?: Partial<HeaderTranslations>;\n createModal?: Partial<ModalTranslations>;\n}\nconst DEFAULT_TRANSLATIONS: ContextTranslations = {\n header: {\n title: \"Model\",\n createLabel: \"Create new Model\",\n deleteLabel: \"Delete\",\n },\n createModal: {\n okText: \"OK\",\n cancelText: \"Cancel\",\n title: \"Create New Model\",\n },\n};\n\ninterface ContextTranslations {\n header: HeaderTranslations;\n createModal: ModalTranslations;\n}\ninterface Props {\n translations?: Translations;\n children: React.ReactNode;\n}\nconst CreateModelTranslationsContext =\n React.createContext<ContextTranslations>(DEFAULT_TRANSLATIONS);\n\nconst CreateModelTranslationsProvider: React.FC<Props> = ({\n translations = DEFAULT_TRANSLATIONS,\n children,\n}) => {\n const merged: ContextTranslations = {\n header: { ...DEFAULT_TRANSLATIONS.header, ...translations.header },\n createModal: {\n ...DEFAULT_TRANSLATIONS.createModal,\n ...translations.createModal,\n },\n };\n return (\n <CreateModelTranslationsContext.Provider value={merged}>\n {children}\n </CreateModelTranslationsContext.Provider>\n );\n};\n\nexport { CreateModelTranslationsContext, CreateModelTranslationsProvider };\n","import {\n clearModelHookCacheEntry,\n destroyKosModel,\n modelHookCache,\n IKosCoreManager,\n IKosDataModel,\n kosAutoEffect,\n KosCore,\n ModelFactory,\n} from \"../../core\";\n\nimport { useEffect, useState } from \"react\";\nimport { useKosCore } from \"../contexts/kos-core-context\";\n\nimport type { IReactionDisposer } from \"mobx\";\nimport { KosModelEvents, KosModelState } from \"../../core\";\nimport { isUpdateable } from \"../../core/core/registration/model-registration\";\nimport { KosModelLoader } from \"../components/kos-model-loader\";\ninterface Options<T extends IKosDataModel, O extends Object = {}> {\n modelId?: string;\n factory?: ModelFactory<T, O>;\n modelType?: string;\n options?: O;\n activate?: boolean;\n destroyOnUnmount?: boolean;\n forceUpdate?: boolean;\n}\n\nconst MAX_RETRIES = 8;\nconst waitForRetry = (depth = 0) =>\n new Promise((resolve) => {\n setTimeout(() => {\n resolve(true);\n }, 2 ** depth * 10);\n });\n\n/**\n * Reads a model out of the suspense cache, suspending or rethrowing as the\n * entry requires. Exported for tests.\n */\nexport function readModelHookEntry(\n key: string,\n fetcher: () => Promise<unknown>\n) {\n const entry = modelHookCache.get(key);\n\n if (entry) {\n if (entry.status === \"finished\") {\n const kosModel = KosCore.getInstance().modelManager.getModelById(key);\n return { kosModel, model: kosModel?.modelData };\n }\n\n // An error entry has no promise to suspend on, so rethrow the cause.\n if (entry.status === \"error\") {\n throw entry.error;\n }\n\n throw entry.promise;\n }\n\n const promise = fetcher().then(\n () => {\n modelHookCache.set(key, { status: \"finished\", key });\n },\n (error) => {\n modelHookCache.set(key, { status: \"error\", error });\n throw error;\n }\n );\n\n modelHookCache.set(key, { status: \"pending\", promise });\n\n throw promise;\n}\n\nfunction useSuspenseData<T>(\n key: string,\n fetcher: (...args: any[]) => Promise<T>\n) {\n // Attempt to fetch the data (or retrieve from cache), throwing a promise if it's not ready.\n const data = readModelHookEntry(key, fetcher) as T;\n\n // If the data is available, return it.\n return data;\n}\n\nasync function fetchModel<T extends IKosDataModel, O extends Object = {}>(\n kosCore: IKosCoreManager,\n modelOptions: Options<T, O>\n) {\n const { modelId, factory, modelType, options } = modelOptions;\n let retryCount = 0;\n await kosCore.whenReady();\n let _model: T;\n if (options) {\n const _factory =\n typeof modelType === \"string\"\n ? kosCore.modelManager.getModelFactory<T>(modelType)\n : factory;\n\n if (!_factory) {\n throw Error(\"No Factory Specified. Cannot create a new instance\");\n }\n // build the model first\n _model = _factory.build(modelId!, options);\n }\n const kosModel = kosCore.modelManager.getModelById<T>(modelId!);\n\n if (!kosModel) {\n if (retryCount > MAX_RETRIES) {\n throw Error(`KOS Model ${modelId} has not been found`);\n }\n\n await waitForRetry(retryCount);\n const count = retryCount + 1;\n retryCount = count;\n }\n await kosModel?.whenReady();\n\n if (kosModel) {\n _model = kosModel.modelData;\n return { kosModel, model: _model };\n }\n\n return { kosModel: undefined, model: undefined };\n}\n/**\n * Primary hook for consuming KOS models in React components.\n *\n * @kosService core.use-kos-model\n * @kosApiLevel 2\n */\nexport const useKosModel = <T extends IKosDataModel, O extends Object = {}>(\n modelOptions: Options<T, O>\n) => {\n const { modelId, modelType, activate, destroyOnUnmount } = modelOptions;\n const kosCoreContext = useKosCore();\n const [ready, setReady] = useState(false);\n\n const [error, setError] = useState<string | undefined>();\n\n const { kosModel, model } = useSuspenseData(\n modelId || modelType || \"\",\n () => {\n const response = fetchModel(kosCoreContext.kosCore, modelOptions);\n return response;\n }\n );\n\n useEffect(() => {\n if (modelOptions.forceUpdate && model) {\n if (isUpdateable(model)) {\n model.updateModel(modelOptions.options || {});\n }\n }\n }, [model]);\n useEffect(() => {\n async function waitForModel() {\n try {\n await kosCoreContext.kosCore.whenReady();\n if (activate) {\n await kosModel?.fsm.transitionTo(\n KosModelEvents.GO_ACTIVE,\n KosModelState.ACTIVE\n );\n }\n setReady(true);\n return kosModel;\n } catch (e) {\n setError((e as Error).message);\n throw e;\n }\n }\n\n let disposer: IReactionDisposer | undefined = undefined;\n if (kosCoreContext.kosCore && modelId) {\n waitForModel()\n .then((kosModel) => {\n disposer = kosAutoEffect(() => {\n const _ready = kosModel?.status === KosModelState.READY;\n setReady(_ready);\n });\n })\n .catch((e) => {\n console.error(e);\n });\n }\n return () => {\n if (activate) {\n if (model?.id) {\n const kosModel = kosCoreContext.kosCore.modelManager.getModelById<T>(\n model.id\n );\n\n kosModel?.fsm\n .transitionTo(KosModelEvents.GO_INACTIVE, KosModelState.INACTIVE)\n .then(() => {\n if (destroyOnUnmount) {\n const modelId = model.id;\n destroyKosModel(model).then(() => {\n clearModelHookCacheEntry(modelId);\n disposer?.();\n });\n }\n });\n }\n } else {\n if (destroyOnUnmount && model) {\n destroyKosModel(model).then(() => {\n clearModelHookCacheEntry(modelId);\n disposer?.();\n });\n }\n }\n };\n }, [\n activate,\n destroyOnUnmount,\n kosCoreContext.kosCore,\n kosModel,\n model,\n modelId,\n ]);\n\n return {\n model,\n ready,\n error,\n status: {\n model,\n ready,\n error,\n },\n KosModelLoader,\n };\n};\n","import { KosTime, KosTimeModel } from \"../../../models\";\nimport { useKosModel } from \"../use-kos-model\";\n\n/**\n * Hook for accessing the KOS time model.\n *\n * @kosService core.use-kos-time\n * @kosApiLevel 2\n */\nexport const useKosTime = () => {\n const modelId = KosTime.type;\n const result = useKosModel<KosTimeModel>({\n modelId,\n modelType: KosTime.type,\n options: {},\n });\n\n return result;\n};\n","import { PropsWithChildren, createContext, useContext, useMemo } from \"react\";\nimport { KosTimeModel } from \"../../../models\";\nimport { useKosTime } from \"../../hooks/kos-time/use-kos-time\";\n\ninterface KosTimeType {\n model?: KosTimeModel;\n}\nexport const KosTimeContext = createContext<KosTimeType | undefined>(undefined);\n\ninterface KosTimeProviderProps {}\n\nexport const KosTimeProvider: React.FunctionComponent<\n PropsWithChildren<KosTimeProviderProps>\n> = ({ children }) => {\n const { model, ready } = useKosTime();\n const value: KosTimeType = useMemo(() => {\n if (ready && model) {\n return { model };\n }\n return {};\n }, [ready, model]);\n return (\n <KosTimeContext.Provider value={value}>{children}</KosTimeContext.Provider>\n );\n};\nexport const useKosTimeContext = () => {\n const context = useContext(KosTimeContext);\n if (!context) {\n throw new Error(\"useKosTimeContext must be used within a KosTimeProvider\");\n }\n return context;\n};\n","import { SoftwareInfo, type SoftwareInfoModel } from \"../../../models\";\nimport { useKosModel } from \"../use-kos-model\";\n\n/**\n * Hook for accessing the KOS software info model.\n *\n * @kosService core.use-software-info\n * @kosApiLevel 2\n */\nexport const useSoftwareInfo = () => {\n const modelId = SoftwareInfo.type;\n const result = useKosModel<SoftwareInfoModel>({\n modelId,\n modelType: SoftwareInfo.type,\n options: {},\n });\n\n return result;\n};\n","import type { SoftwareInfoModel } from \"../../../models\";\nimport { useSoftwareInfo } from \"./use-software-info\";\n\ninterface SoftwareInfoProps {\n softwareInfo: SoftwareInfoModel;\n}\n// react HOC to provide a SoftwareInfo to a component\nexport function withSoftwareInfo<\n T extends SoftwareInfoProps = SoftwareInfoProps\n>(WrappedComponent: React.ComponentType<T>) {\n return () => (props: Omit<T, keyof SoftwareInfoProps>) => {\n const { model, status, KosModelLoader } = useSoftwareInfo();\n\n return (\n <KosModelLoader {...status}>\n <WrappedComponent {...(props as T)} softwareInfo={model} />\n </KosModelLoader>\n );\n };\n}\n","import { PropsWithChildren, createContext, useContext, useMemo } from \"react\";\nimport type { SoftwareInfoModel } from \"../../../models\";\nimport { useSoftwareInfo } from \"../../hooks/software-info\";\n\ninterface SoftwareInfoType {\n model?: SoftwareInfoModel;\n}\nexport const SoftwareInfoContext = createContext<SoftwareInfoType | undefined>(\n undefined\n);\n\ninterface SoftwareInfoProviderProps {\n id: string;\n}\n\nexport const SoftwareInfoProvider: React.FunctionComponent<\n PropsWithChildren<SoftwareInfoProviderProps>\n> = ({ children }) => {\n const { model, ready } = useSoftwareInfo();\n const value: SoftwareInfoType = useMemo(() => {\n if (ready && model) {\n return { model };\n }\n return {};\n }, [ready, model]);\n return (\n <SoftwareInfoContext.Provider value={value}>\n {children}\n </SoftwareInfoContext.Provider>\n );\n};\nexport const useSoftwareInfoContext = () => {\n const context = useContext(SoftwareInfoContext);\n if (!context) {\n throw new Error(\n \"useSoftwareInfoContext must be used within a SoftwareInfoProvider\"\n );\n }\n return context;\n};\n","import React from \"react\";\nimport { KosToken } from \"../../core\";\n\nconst token = new KosToken();\nconst TokenContext = React.createContext<KosToken>(token);\n\nfunction TokenProvider({ children }: { children: React.ReactNode }) {\n return (\n <TokenContext.Provider value={token}>{children}</TokenContext.Provider>\n );\n}\nexport { TokenContext, TokenProvider };\n","import { KosLog, getQueryParams } from \"../../../core\";\nimport {\n KosTranslations,\n Localization,\n TranslationContainerModel,\n collectLocaleOptions,\n getKosLocalizationDescriptor,\n mergeLocalizationDescriptors,\n} from \"../../../models\";\n\nimport {\n PropsWithChildren,\n createContext,\n useContext,\n useEffect,\n useMemo,\n useState,\n} from \"react\";\n\ninterface TranslationContainerType {\n setLocale: (locale: string) => void;\n allLocales: { locale: string; label: string }[];\n}\nexport const TranslationContainerContext = createContext<\n TranslationContainerType | undefined\n>(undefined);\n\ninterface TranslationContainerProviderProps {\n appContext?: string | string[];\n rootUrl?: string;\n locale?: string;\n descriptorResolver?: () => Promise<Localization>;\n excludeNamespaces?: string[];\n resolver?: (\n this: TranslationContainerModel,\n namespace: string,\n locale: string\n ) => string;\n}\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\nexport const KosTranslationProvider: React.FunctionComponent<\n PropsWithChildren<TranslationContainerProviderProps>\n> = ({\n children,\n appContext,\n locale = \"en\",\n resolver,\n rootUrl,\n descriptorResolver,\n excludeNamespaces = [],\n}) => {\n const [ready, setReady] = useState(false);\n const [localization, setLocalization] = useState<Localization>();\n const [translations, setTranslations] = useState<TranslationContainerModel>();\n const [allLocales, setAllLocales] = useState<\n { locale: string; label: string }[]\n >([]);\n const resolvedRootUrl = rootUrl || getDefaultHost();\n const _appContext = useMemo(() => appContext ?? \"app/system\", [appContext]);\n useEffect(() => {\n async function initTools() {\n const contexts = Array.isArray(_appContext) ? _appContext : [_appContext];\n\n const descriptorPromises = contexts.map((context) => {\n const localizationResolver =\n descriptorResolver || getKosLocalizationDescriptor(context);\n return localizationResolver();\n });\n\n const descriptorsResults = await Promise.allSettled(descriptorPromises);\n const descriptors: Localization[] = descriptorsResults\n .map((d) => {\n if (d.status === \"rejected\") {\n KosLog.warn(\"Failed to load localization descriptor\", d.reason);\n return undefined;\n }\n return d.value;\n })\n .filter((d) => !!d) as Localization[];\n\n setLocalization(mergeLocalizationDescriptors(descriptors));\n setAllLocales(collectLocaleOptions(descriptors, excludeNamespaces));\n }\n initTools();\n }, [_appContext, descriptorResolver]);\n\n useEffect(() => {\n async function initLocalization() {\n if (localization) {\n const _rootUrl = resolvedRootUrl;\n const { translations } = await KosTranslations.init({\n lang: locale,\n descriptor: localization,\n defaultNamespace: \"common\",\n resolver: resolver,\n rootUrl: _rootUrl,\n });\n setTranslations(translations);\n setReady(true);\n }\n }\n\n initLocalization();\n }, [locale, localization, resolver, resolvedRootUrl]);\n\n const value: TranslationContainerType = useMemo(() => {\n if (ready) {\n return {\n setLocale: (locale: string) => {\n if (translations) {\n translations.currentLocale = locale;\n }\n },\n allLocales,\n };\n }\n return {\n setLocale: () => {\n throw new Error(\"Translations not ready\");\n },\n allLocales: [],\n };\n }, [ready, translations]);\n\n const content = ready ? children : null;\n return (\n <TranslationContainerContext.Provider value={value}>\n {content}\n </TranslationContainerContext.Provider>\n );\n};\nexport const useKosTranslationContext = () => {\n const context = useContext(TranslationContainerContext);\n if (!context) {\n throw new Error(\n \"useTranslationContainerContext must be used within a TranslationContainerProvider\"\n );\n }\n return context;\n};\n","import {\n CanvasDispatcher,\n type CanvasDispatcherModel,\n type CanvasDispatcherOptions,\n} from \"../../../../../models/models/canvas-dispatcher\";\nimport { useKosModel } from \"../../../../hooks/use-kos-model\";\n\nexport const useCanvasDispatcher = () => {\n const modelId = CanvasDispatcher.type;\n const result = useKosModel<CanvasDispatcherModel, CanvasDispatcherOptions>({\n modelId,\n modelType: CanvasDispatcher.type,\n options: {},\n });\n\n return result;\n};\n","import type { CanvasDispatcherModel } from \"../../../../../models/models/canvas-dispatcher\";\nimport { useCanvasDispatcher } from \"./use-canvas-dispatcher\";\n\ninterface CanvasDispatcherProps {\n canvasDispatcher: CanvasDispatcherModel;\n}\n\ntype HoCCanvasDispatcherProps = CanvasDispatcherProps;\n// react HOC to provide a CanvasDispatcher to a component\nexport function withCanvasDispatcher<\n T extends HoCCanvasDispatcherProps = HoCCanvasDispatcherProps\n>(WrappedComponent: React.ComponentType<T>) {\n return (props: Omit<T, keyof CanvasDispatcherProps>) => {\n const { model, status, KosModelLoader } = useCanvasDispatcher();\n\n return (\n <KosModelLoader {...status}>\n <WrappedComponent {...(props as T)} canvasDispatcher={model} />\n </KosModelLoader>\n );\n };\n}\n","export const decodeBase64RGB = (\n base64: string,\n width: number,\n height: number\n): Uint8ClampedArray => {\n const binary = atob(base64);\n const rgba = new Uint8ClampedArray(width * height * 4);\n for (let i = 0, j = 0; i < binary.length && j < rgba.length; i += 3, j += 4) {\n rgba[j] = binary.charCodeAt(i);\n rgba[j + 1] = binary.charCodeAt(i + 1);\n rgba[j + 2] = binary.charCodeAt(i + 2);\n rgba[j + 3] = 255;\n }\n return rgba;\n};\n\nexport const decodeRGB332 = (\n data: string,\n width: number,\n height: number\n): Uint8ClampedArray => {\n const rgba = new Uint8ClampedArray(width * height * 4);\n for (let i = 0; i < data.length; i++) {\n const byte = data.charCodeAt(i);\n const r = (((byte >> 5) & 0x07) * 255) / 7;\n const g = (((byte >> 2) & 0x07) * 255) / 7;\n const b = ((byte & 0x03) * 255) / 3;\n const j = i * 4;\n rgba[j] = r;\n rgba[j + 1] = g;\n rgba[j + 2] = b;\n rgba[j + 3] = 255;\n }\n return rgba;\n};\n\n/**\n * Renders a decoded preview onto a canvas context by decoding image data\n * from a specified format and scaling it to the desired size.\n *\n * @param ctx - The 2D rendering context of the target canvas.\n * @param format - The format of the input data string. Can be either 'base64' or 'rgb332'.\n * @param dataString - The encoded image data as a string.\n * @param width - The width of the image in pixels.\n * @param height - The height of the image in pixels.\n * @param pixelSize - The scaling factor for each pixel in the rendered image.\n *\n * @remarks\n * - If `format` is 'base64', the `dataString` is decoded using `decodeBase64RGB`.\n * - If `format` is 'rgb332', the `dataString` is decoded using `decodeRGB332`.\n * - The function creates a temporary canvas to decode and render the image data\n * before scaling it onto the target canvas.\n * - Image smoothing is disabled to preserve the pixelated appearance of the image.\n */\nexport function renderDecodedPreview({\n ctx,\n format,\n dataString,\n width,\n height,\n pixelSize,\n}: {\n ctx: CanvasRenderingContext2D;\n format: \"base64\" | \"rgb332\";\n dataString: string;\n width: number;\n height: number;\n pixelSize: number;\n}) {\n const decode =\n format === \"base64\"\n ? decodeBase64RGB(dataString, width, height)\n : decodeRGB332(dataString, width, height);\n\n const img = new ImageData(\n decode as unknown as Uint8ClampedArray<ArrayBuffer>,\n width,\n height\n );\n const tempCanvas = document.createElement(\"canvas\");\n tempCanvas.width = width;\n tempCanvas.height = height;\n const tempCtx = tempCanvas.getContext(\"2d\");\n tempCtx?.putImageData(img, 0, 0);\n ctx.imageSmoothingEnabled = false;\n ctx.clearRect(0, 0, width * pixelSize, height * pixelSize);\n ctx.drawImage(tempCanvas, 0, 0, width * pixelSize, height * pixelSize);\n}\n","import styled from \"@emotion/styled\";\n\nimport { useCallback, useEffect, useRef, useState } from \"react\";\n\nimport { observer as kosComponent } from \"mobx-react-lite\";\nimport { createPortal } from \"react-dom\";\nimport { KosLog } from \"../../../../../core\";\nimport type { CanvasDispatcherModel } from \"../../../../../models/models/canvas-dispatcher\";\nimport type { CanvasRendererModel } from \"../../../../../models/models/canvas-renderer\";\nimport { withCanvasDispatcher } from \"../../hooks/canvas-dispatcher\";\nimport { renderDecodedPreview } from \"../../utils/preview-decoder\";\n\nconst log = KosLog.createLogger({ name: \"canvas-streamer\" });\nlog.debug(\"main-view component loaded\");\nconst PIXEL_SIZE = 10;\n\ninterface CanvasStreamerProps {\n height?: number;\n width?: number;\n defaultFps?: number;\n showPreview?: boolean;\n name: string;\n apiPath?: string;\n canvasDispatcher: CanvasDispatcherModel;\n}\n\nexport const CanvasStreamerBase: React.FunctionComponent<CanvasStreamerProps> =\n kosComponent(\n ({\n canvasDispatcher,\n height = 30,\n width = 50,\n defaultFps = 10,\n showPreview = false,\n name,\n apiPath = \"/api/system/canvas\",\n }) => {\n const canvasRef = useRef<HTMLCanvasElement>(null);\n\n const [renderer, setRenderer] = useState<CanvasRendererModel>();\n\n useEffect(() => {\n const _endpoint = canvasDispatcher.addNamedEndpoint(name, {\n apiPath,\n fps: defaultFps,\n width,\n height,\n id: name,\n });\n\n setRenderer(_endpoint);\n }, [canvasDispatcher]);\n /**\n * Callback function to handle frame processing.\n *\n * @param rgba - A `Uint8ClampedArray` representing the RGBA pixel data of the frame.\n *\n * This function performs the following operations:\n * If a preview canvas is available and `showPreview` is enabled, renders a decoded\n * preview of the frame onto the canvas using `renderDecodedPreview`.\n *\n * Dependencies:\n * - `width` and `height`: Dimensions of the grid for encoding and rendering.\n * - `showPreview`: A flag to determine whether to render a preview.\n * - `canvasRef`: A reference to the preview canvas element.\n * - `PIXEL_SIZE`: The size of each pixel in the preview rendering.\n */\n const onFrame = useCallback(\n (dataString: string) => {\n if (canvasRef.current && showPreview) {\n const previewCtx = canvasRef.current.getContext(\"2d\");\n if (previewCtx) {\n renderDecodedPreview({\n ctx: previewCtx,\n format: \"base64\",\n dataString,\n height,\n width,\n pixelSize: PIXEL_SIZE,\n });\n }\n }\n },\n [width, height, showPreview]\n );\n\n useEffect(() => {\n if (!renderer) return;\n renderer.onFrame = onFrame;\n renderer.width = width;\n renderer.height = height;\n renderer.fps = defaultFps;\n }, [renderer, onFrame, width, height, defaultFps]);\n\n return (\n showPreview &&\n createPortal(\n <Main>\n <PreviewContainer>\n <canvas\n ref={canvasRef}\n width={width * PIXEL_SIZE}\n height={height * PIXEL_SIZE}\n style={{ border: \"1px solid black\" }}\n />\n </PreviewContainer>\n </Main>,\n document.body\n )\n );\n }\n );\n\nexport const CanvasStreamer = withCanvasDispatcher(CanvasStreamerBase);\n\nconst Main = styled.div`\n display: flex;\n flex-direction: column;\n gap: 8px;\n\n width: 100%;\n justify-content: space-between;\n align-items: center;\n`;\n\nconst PreviewContainer = styled.div`\n display: flex;\n flex-direction: column;\n align-items: center;\n`;\n","import { Device, DeviceModel } from \"../../../models\";\nimport { useKosModel } from \"../use-kos-model\";\n\n/**\n * Hook for accessing the KOS device model.\n *\n * @kosService core.use-device\n * @kosApiLevel 2\n */\nexport const useDevice = () => {\n const modelId = Device.type;\n const result = useKosModel<DeviceModel>({\n modelId,\n modelType: Device.type,\n options: {},\n });\n\n return result;\n};\n","import { DeviceModel } from \"../../../models\";\nimport { useDevice } from \"./use-device\";\n\nexport interface DeviceProps {\n device: DeviceModel;\n}\n\ntype HoCDeviceProps = DeviceProps;\n// react HOC to provide a Device to a component\nexport function withDevice<T extends HoCDeviceProps = HoCDeviceProps>(\n WrappedComponent: React.ComponentType<T>\n) {\n return (props: Omit<T, keyof DeviceProps>) => {\n const { model, status, KosModelLoader } = useDevice();\n\n return (\n <KosModelLoader {...status}>\n <WrappedComponent {...(props as T)} device={model} />\n </KosModelLoader>\n );\n };\n}\n","import { IKosDataModel, KosCore, wrapPromise } from \"../../core\";\n\nexport default function fetchModel<\n T extends IKosDataModel,\n O extends object = Record<string, unknown>\n>(modelType: string, id?: string, options?: O) {\n const corePromise = new Promise<T>((resolve) => {\n KosCore.getInstance()\n .whenReady()\n .then(() => {\n const { model } =\n KosCore.getInstance().modelManager.createModelInstance<T>(\n modelType,\n id ?? modelType,\n options\n );\n return model.whenReady().then(() => {\n resolve(model.modelData);\n });\n });\n });\n\n return wrapPromise<T>(corePromise);\n}\n","import { KosTimeModel } from \"../../../models\";\nimport { useKosTime } from \"./use-kos-time\";\n\ninterface KosTimeProps {\n kosTime: KosTimeModel;\n}\n// react HOC to provide a KosTime to a component\nexport function withKosTime<T extends KosTimeProps = KosTimeProps>(\n WrappedComponent: React.ComponentType<T>\n) {\n return (props: Omit<T, keyof KosTimeProps>) => {\n const { model, status, KosModelLoader } = useKosTime();\n\n return (\n <KosModelLoader {...status}>\n <WrappedComponent {...(props as T)} kosTime={model} />\n </KosModelLoader>\n );\n };\n}\n","import {\n NetworkInterfaceContainer,\n NetworkInterfaceContainerModel,\n} from \"../../../models\";\nimport { useKosModel } from \"../use-kos-model\";\n\n/**\n * Hook for accessing the KOS network interface container model.\n *\n * @kosService core.use-network\n * @kosApiLevel 2\n */\nexport const useNetworkInterfaceContainer = () => {\n const modelId = NetworkInterfaceContainer.type;\n const result = useKosModel<NetworkInterfaceContainerModel>({\n modelId,\n modelType: NetworkInterfaceContainer.type,\n options: {},\n });\n\n return result;\n};\n","import { NetworkInterfaceContainerModel } from \"../../../models\";\nimport { useNetworkInterfaceContainer } from \"./use-network-interface-container\";\n\ninterface NetworkInterfaceContainerProps {\n networkInterfaceContainer: NetworkInterfaceContainerModel;\n}\n\ntype HoCNetworkInterfaceContainerProps = NetworkInterfaceContainerProps;\n// react HOC to provide a NetworkInterfaceContainer to a component\nexport function withNetworkInterfaceContainer<\n T extends HoCNetworkInterfaceContainerProps = HoCNetworkInterfaceContainerProps\n>(WrappedComponent: React.ComponentType<T>) {\n return (props: Omit<T, keyof NetworkInterfaceContainerProps>) => {\n const { model, status, KosModelLoader } = useNetworkInterfaceContainer();\n\n return (\n <KosModelLoader {...status}>\n <WrappedComponent {...(props as T)} networkInterfaceContainer={model} />\n </KosModelLoader>\n );\n };\n}\n","import { Ota, type OtaModel } from \"../../../models\";\nimport { useKosModel } from \"../use-kos-model\";\n\n/**\n * Hook for accessing the KOS OTA (over-the-air update) model.\n *\n * @kosService core.use-ota\n * @kosApiLevel 2\n */\nexport const useOta = () => {\n const modelId = Ota.type;\n const result = useKosModel<OtaModel>({\n modelId,\n modelType: Ota.type,\n options: {},\n });\n\n return result;\n};\n","import type { OtaModel } from \"../../../models\";\nimport { useOta } from \"./use-ota\";\n\ninterface OtaProps {\n oTA: OtaModel;\n}\n\ntype HoCOtaProps = OtaProps;\n// react HOC to provide a Ota to a component\nexport function withOta<T extends HoCOtaProps = HoCOtaProps>(\n WrappedComponent: React.ComponentType<T>\n) {\n return (props: Omit<T, keyof OtaProps>) => {\n const { model, status, KosModelLoader } = useOta();\n\n return (\n <KosModelLoader {...status}>\n <WrappedComponent {...(props as T)} oTA={model} />\n </KosModelLoader>\n );\n };\n}\n","import { useRef, useEffect, PropsWithChildren } from \"react\";\n\n/**\n * Hook that alerts clicks outside of the passed ref\n */\nfunction useOutsideAlerter(ref, onAction) {\n useEffect(() => {\n /**\n * Alert if clicked on outside of element\n */\n function handleClickOutside(event) {\n if (ref.current && !ref.current.contains(event.target)) {\n onAction();\n }\n }\n\n function handleEscFunction(event) {\n if (event.key === \"Escape\") {\n onAction();\n }\n }\n // Bind the event listener\n document.addEventListener(\"mousedown\", handleClickOutside);\n document.addEventListener(\"keydown\", handleEscFunction, false);\n return () => {\n // Unbind the event listener on clean up\n document.removeEventListener(\"mousedown\", handleClickOutside);\n document.removeEventListener(\"keydown\", handleEscFunction, false);\n };\n }, [ref, onAction]);\n}\n\ninterface Props {\n onAlert: () => void;\n}\n/**\n * Component that alerts if you click outside of it\n */\nexport default function OutsideAlerter(props: PropsWithChildren<Props>) {\n const wrapperRef = useRef(null);\n const onAction = props.onAlert;\n useOutsideAlerter(wrapperRef, onAction);\n\n return (\n <div ref={wrapperRef} style={{ width: \"100%\" }}>\n {props.children}\n </div>\n );\n}\n","import { KosStateProp, StatePropertyTypes } from \"../../../models\";\n\nimport { useEffect, useState } from \"react\";\nimport { kosAutoEffect, whenReady } from \"../../../core\";\n\ninterface UseStatePropertyProps<T extends StatePropertyTypes = any> {\n stateProp?: KosStateProp<T>;\n}\n\ntype StatePropertyStatus<T extends StatePropertyTypes = any> = [\n value: T | undefined,\n status: { ready: boolean; error?: string }\n];\nexport const useStateProperty = <T extends StatePropertyTypes = any>(\n props: UseStatePropertyProps<T>\n): StatePropertyStatus<T> => {\n const { stateProp } = props;\n const [value, setValue] = useState<T | undefined>(props.stateProp?.value);\n const [ready, setReady] = useState(false);\n const [error, setError] = useState<string | undefined>(undefined);\n\n useEffect(() => {\n async function waitForProp(prop?: KosStateProp) {\n try {\n if (prop) {\n await whenReady(prop);\n setReady(true);\n }\n } catch (e) {\n setError((e as Error).message);\n }\n }\n\n waitForProp(stateProp);\n }, [stateProp]);\n\n useEffect(() => {\n const disposer = kosAutoEffect(() => {\n if (stateProp && ready) {\n setValue(stateProp.value);\n }\n });\n return () => {\n disposer();\n };\n }, [ready, stateProp]);\n\n const status = { ready, error };\n return [value, status];\n};\n","import { useEffect, useState } from \"react\";\nimport { kosAutoEffect } from \"../../../core\";\nimport {\n StorageDeviceContainer,\n StorageDeviceContainerModel,\n type StorageDeviceModel,\n} from \"../../../models\";\nimport { useKosModel } from \"../use-kos-model\";\n\n/**\n * Hook for accessing the KOS storage device container model.\n *\n * @kosService core.use-storage\n * @kosApiLevel 2\n */\nexport const useStorageDeviceContainer = () => {\n const [inserted, setInserted] = useState<boolean>(false);\n const [devices, setDevices] = useState<StorageDeviceModel[]>([]);\n const modelId = StorageDeviceContainer.type;\n const result = useKosModel<StorageDeviceContainerModel>({\n modelId,\n modelType: StorageDeviceContainer.type,\n options: {},\n });\n\n useEffect(() => {\n const disposer = kosAutoEffect(() => {\n setInserted(result.model?.isStorageInserted ?? false);\n setDevices(result.model?.data ?? []);\n });\n\n return () => {\n disposer();\n };\n }, [result.model]);\n\n return { ...result, inserted, devices };\n};\n","import { StorageDeviceContainerModel } from \"../../../models\";\nimport { useStorageDeviceContainer } from \"./use-storage-device-container\";\n\ninterface StorageDeviceContainerProps {\n storageDeviceContainer: StorageDeviceContainerModel;\n}\n\ntype HoCStorageDeviceContainerProps = StorageDeviceContainerProps;\n// react HOC to provide a StorageDeviceContainer to a component\nexport function withStorageDeviceContainer<\n T extends HoCStorageDeviceContainerProps = HoCStorageDeviceContainerProps\n>(WrappedComponent: React.ComponentType<T>) {\n return (props: Omit<T, keyof StorageDeviceContainerProps>) => {\n const { model, status, KosModelLoader } = useStorageDeviceContainer();\n\n return (\n <KosModelLoader {...status}>\n <WrappedComponent {...(props as T)} storageDeviceContainer={model} />\n </KosModelLoader>\n );\n };\n}\n","import { useCallback, useEffect } from \"react\";\nimport { EventBus } from \"../../../common\";\nimport { KosLog } from \"../../../core\";\nimport {\n KosTimer,\n TIMER_END,\n TIMER_EVENT,\n TimerEvent,\n TimerManager,\n TOPIC_TIMER_TICK_EVENT,\n} from \"../../../models\";\n\nconst LOG = KosLog.createLogger({ name: \"use-timer\" });\ninterface TimerHookProps {\n timerName: string;\n onTimerExpired: (event: TimerHookEvent) => void;\n onTimerTick?: (event: TimerTickEvent) => void;\n timerEventActions?: Record<string, (event: TimerHookEvent) => void>;\n autoStart?: boolean;\n}\ntype TimerHookEvent = TimerEvent & { timer: KosTimer };\n\ntype TimerTickEvent = Omit<TimerHookEvent, \"action\"> & {\n timer: KosTimer;\n};\nexport const useTimer = ({\n timerName,\n onTimerExpired,\n onTimerTick,\n timerEventActions,\n autoStart,\n}: TimerHookProps) => {\n const t = TimerManager.getTimer(timerName);\n\n useEffect(() => {\n if (!t) {\n console.warn(`Timer with name ${timerName} does not exist.`);\n return undefined;\n }\n const result = EventBus.subscribe(TIMER_EVENT, (data) => {\n const { name, action, remainingTime } =\n data?.body as unknown as TimerEvent;\n if (name === timerName) {\n if (action === TIMER_END) {\n onTimerExpired({ name, action, remainingTime, timer: t });\n } else if (timerEventActions?.[action]) {\n timerEventActions[action]({ name, action, remainingTime, timer: t });\n }\n }\n });\n if (autoStart) t.start();\n return () => {\n result.unsubscribe();\n };\n }, [autoStart, onTimerExpired, timerEventActions, timerName, t]);\n\n useEffect(() => {\n if (!t || !onTimerTick) {\n return undefined;\n }\n const TOPIC_TIMER_TICK = `${TOPIC_TIMER_TICK_EVENT}/${timerName}`;\n const result = EventBus.subscribe(TOPIC_TIMER_TICK, (data) => {\n const { name, remainingTime } = data?.body as unknown as TimerEvent;\n if (name === timerName) {\n onTimerTick({ name, remainingTime, timer: t });\n }\n });\n return () => {\n result.unsubscribe();\n };\n }, [onTimerTick, timerName, t]);\n\n const start = useCallback(() => {\n if (t) {\n t.start();\n } else {\n LOG.warn(`Timer with name ${timerName} does not exist.`);\n }\n }, [t, timerName]);\n\n const reset = useCallback(() => {\n if (t) {\n t.reset();\n } else {\n LOG.warn(`Timer with name ${timerName} does not exist.`);\n }\n }, [t, timerName]);\n\n const pause = useCallback(() => {\n if (t) {\n t.pause();\n } else {\n LOG.warn(`Timer with name ${timerName} does not exist.`);\n }\n }, [t, timerName]);\n\n return {\n timer: t,\n start,\n reset,\n pause,\n };\n};\n","import React, { type ReactNode, type ReactElement } from \"react\";\nimport { TFunction } from \"./use-translation\";\n\nconst escapeRegExp = (toEscape: string) => {\n const escapableChars = /[\\\\^$.*+?()[\\]{}|]/g;\n const hasEscapableChar = RegExp(escapableChars.source);\n\n return hasEscapableChar.test(toEscape)\n ? toEscape.replace(escapableChars, \"\\\\$&\")\n : toEscape;\n};\n\nconst isRegExp = (toTest: string | RegExp): toTest is RegExp =>\n toTest instanceof RegExp;\n\nconst isString = (toTest: string | RegExp | ReactNode): toTest is string =>\n typeof toTest === \"string\";\n\nconst replaceString = (\n source: string,\n _toMatch: string | RegExp,\n callback: (match: string, index: number) => ReactNode\n) => {\n if (source === \"\" || _toMatch === \"\") return source;\n\n let toMatch = _toMatch;\n\n if (!isRegExp(toMatch)) {\n toMatch = new RegExp(\"(\" + escapeRegExp(toMatch) + \")\", \"gi\");\n }\n\n const result: ReactNode[] = source.split(toMatch);\n\n // Matches will be every odd string in the array, iterate over them and\n // call the callback to insert our component for each match.\n for (let i = 1, length = result.length; i < length; i += 2) {\n result[i] = callback(result[i] as string, i);\n }\n\n return result;\n};\n\nexport const stringComponentInsert = (\n _source: string | (string | ReactNode)[],\n toMatch: string | RegExp,\n callback: (match: string, index: number) => string | ReactElement\n) => {\n let source = _source;\n if (!Array.isArray(source)) source = [source];\n\n return source.flatMap((x) =>\n isString(x) ? replaceString(x, toMatch, callback) : x\n );\n};\n\ninterface Components {\n [key: string]: JSX.Element;\n}\n\ntype ComponentArray = JSX.Element[];\n\ntype ComponentMap = Components | ComponentArray;\ninterface TransProps {\n t: TFunction;\n i18nKey: string;\n defaults?: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n values?: Record<string, any | undefined>;\n components?: ComponentMap;\n context?: string;\n className?: string;\n}\n\nfunction substituteBlocks(stringValue: string, componentsMap: ComponentMap) {\n let blocks: string | ReactNode[] = stringValue;\n\n Object.entries(componentsMap).forEach(([key, value]) => {\n const regex = new RegExp(`<${key}>(.*?)</${key}>|<${key}/>`, \"g\");\n\n blocks = stringComponentInsert(blocks, regex, (match, index) => {\n if (value.type === \"br\") {\n return <br />;\n }\n return React.cloneElement(value, { key: `${key}-${index}` }, match);\n });\n });\n\n return blocks;\n}\n\n/**\n * React component for rendering translated strings with embedded components or markup.\n *\n * @kosService core.use-translation\n * @kosApiLevel 2\n */\nexport const Trans: React.FunctionComponent<TransProps> = (props) => {\n const { i18nKey, t, defaults, components, values = {}, context } = props;\n const translated = t(i18nKey, {\n defaultValue: defaults,\n data: values,\n context,\n returnObjects: true,\n });\n\n const element = substituteBlocks(translated, components || {});\n return <span className={props.className}>{element}</span>;\n};\n","import { useCallback, useMemo } from \"react\";\nimport { KosLog, getKosModel, whenReady } from \"../../../core\";\nimport {\n ResolveTranslationOptions,\n TranslationContainer,\n TranslationContainerModel,\n} from \"../../../models\";\n\nconst cache = new Map();\n\nfunction fetchData(key, fetcher) {\n // Check if there's already a cached promise or result.\n if (cache.has(key)) {\n const entry = cache.get(key);\n if (entry.status === \"finished\") {\n return entry.result;\n }\n\n // An error entry has no promise to suspend on, so rethrow the cause.\n if (entry.status === \"error\") {\n throw entry.error;\n }\n\n throw entry.promise;\n } else {\n // If no cache exists, create a new promise.\n const promise = fetcher().then(\n (result) => {\n cache.set(key, { status: \"finished\", result });\n },\n (error) => {\n cache.set(key, { status: \"error\", error });\n throw error;\n }\n );\n\n // Store the promise in the cache with a pending status.\n const entry = { status: \"pending\", promise };\n cache.set(key, entry);\n\n // Suspend by throwing the promise.\n throw promise;\n }\n}\n\nexport function useSuspenseData<T>(\n key: string,\n fetcher: (...args: any[]) => Promise<T>\n) {\n // Attempt to fetch the data (or retrieve from cache), throwing a promise if it's not ready.\n const data = fetchData(key, fetcher) as T;\n\n // If the data is available, return it.\n return data;\n}\n\nconst fetchTranslationContainer = async () => {\n const container = await getKosModel(TranslationContainer.type);\n await whenReady(container.model);\n return container.model as TranslationContainerModel;\n};\nconst fetchTranslations = async (\n parent: TranslationContainerModel,\n namespace: string,\n additionalNamespaces: string[]\n) => {\n const trans = parent.resolveNamespace(namespace);\n await whenReady(trans);\n for (const ns of additionalNamespaces) {\n const additional = parent.resolveNamespace(ns);\n await whenReady(additional);\n\n //TODO: This is a hack to force the model to resolve the translations\n cache.set(ns, { status: \"finished\", result: additional });\n }\n return trans;\n};\n\nexport type TFunction = <T = string>(\n key: string,\n options?: ResolveTranslationOptions<T> | string\n) => T | string;\n\nexport interface UseKosTranslationOptions {\n keyPrefix?: string;\n}\n/**\n * Primary hook for consuming KOS translations in React components.\n * Resolves a translation namespace and returns a `t` function for key lookup.\n *\n * @kosService core.use-translation\n * @kosApiLevel 2\n */\nexport const useKosTranslation = (\n namespace: string | string[],\n baseOptions?: UseKosTranslationOptions\n) => {\n const allNamespaces = [namespace].flat();\n const [defaultNamespace, ...additionalNamespaces] = allNamespaces;\n\n const model = useSuspenseData(\n TranslationContainer.type,\n fetchTranslationContainer\n );\n\n const allKeys = allNamespaces.join(\"__\");\n const translationModel = useSuspenseData(allKeys, () =>\n fetchTranslations(model, defaultNamespace, additionalNamespaces)\n );\n\n const i18n = useMemo(() => {\n return {\n exists: (key: string) => {\n const expandedKey = baseOptions?.keyPrefix\n ? `${baseOptions.keyPrefix}.${key}`\n : key;\n if (translationModel) {\n return translationModel.exists(expandedKey);\n }\n\n return false;\n },\n };\n }, [baseOptions?.keyPrefix, translationModel]);\n const t = useCallback<TFunction>(\n <T = string>(\n key: string,\n options?: ResolveTranslationOptions<T> | string\n ) => {\n const expandedKey = baseOptions?.keyPrefix\n ? `${baseOptions.keyPrefix}.${key}`\n : key;\n if (translationModel) {\n return translationModel.resolveKey(expandedKey, options) as T;\n }\n\n KosLog.debug(\n `Translation model ${namespace} not ready for key: ${expandedKey}`\n );\n return expandedKey;\n },\n [baseOptions?.keyPrefix, namespace, translationModel]\n );\n return { t, i18n };\n};\n","import {\n TranslationContainer,\n type TranslationContainerModel,\n} from \"../../../models\";\nimport { useKosModel } from \"../use-kos-model\";\n\n/**\n * Hook for accessing the KOS translation container model.\n *\n * @kosService core.use-translation\n * @kosApiLevel 2\n */\nexport const useTranslationContainer = () => {\n const modelId = TranslationContainer.type;\n const result = useKosModel<TranslationContainerModel>({\n modelId,\n modelType: TranslationContainer.type,\n options: {},\n });\n\n return result;\n};\n","import type { TranslationContainerModel } from \"../../../models\";\nimport { useTranslationContainer } from \"./use-translation-container\";\n\ninterface TranslationContainerProps {\n translationContainer: TranslationContainerModel;\n}\n\ntype HoCTranslationContainerProps = TranslationContainerProps;\n/**\n * Higher-order component that injects a `TranslationContainerModel` into a wrapped component.\n *\n * @kosService core.use-translation\n * @kosApiLevel 2\n */\nexport function withTranslationContainer<\n T extends HoCTranslationContainerProps = HoCTranslationContainerProps\n>(WrappedComponent: React.ComponentType<T>) {\n return (props: Omit<T, keyof TranslationContainerProps>) => {\n const { model, status, KosModelLoader } = useTranslationContainer();\n\n return (\n <KosModelLoader {...status}>\n <WrappedComponent {...(props as T)} translationContainer={model} />\n </KosModelLoader>\n );\n };\n}\n","import { Trouble, type TroubleModel } from \"../../../models\";\nimport { useKosModel } from \"../use-kos-model\";\n\nexport const useTroubleModel = (id: string) => {\n const modelId = id;\n\n const result = useKosModel<TroubleModel>({\n modelId,\n modelType: Trouble.type,\n });\n\n return result;\n};\n","import { TroubleContainer, type TroubleContainerModel } from \"../../../models\";\nimport { useKosModel } from \"../use-kos-model\";\n\nexport const useTroubleContainerModel = () => {\n const result = useKosModel<TroubleContainerModel>({\n modelId: TroubleContainer.type,\n modelType: TroubleContainer.type,\n options: {},\n });\n return result;\n};\n","import { useCallback, useEffect, useState } from \"react\";\nimport { kosAutoEffect } from \"../../../core\";\nimport type { TroubleModel } from \"../../../models/models/trouble\";\nimport type { FutureResponse } from \"../../../models/services/future\";\nimport { useTroubleContainerModel } from \"../trouble/use-trouble-container\";\n\ninterface Props {\n troubleType?: string;\n condition?: (trouble: TroubleModel) => boolean;\n}\n\ntype TroubleVisibility = [\n boolean,\n () => Promise<FutureResponse | undefined>,\n TroubleModel | undefined,\n TroubleModel[]\n];\nexport const useTroublePresence = ({\n troubleType,\n condition,\n}: Props): TroubleVisibility => {\n const { model } = useTroubleContainerModel();\n const [active, setActive] = useState<boolean>(false);\n const [troubles, setTroubles] = useState<TroubleModel[]>([]);\n\n const onComplete = useCallback(() => {\n if (troubles.length > 0 && troubles[0]?.resolvable) {\n return troubles[0]?.resolve();\n }\n return Promise.resolve(undefined);\n }, [troubles]);\n useEffect(() => {\n const disposer = kosAutoEffect(() => {\n const troublesByType =\n (troubleType\n ? model?.troubles.getIndexByKey(\"byType\", troubleType)\n : model?.troubles.data) || [];\n const activeTroubles = condition\n ? troublesByType.filter(condition)\n : troublesByType;\n setActive(activeTroubles.length > 0);\n setTroubles(activeTroubles);\n });\n return disposer;\n }, [condition, model, troubleType]);\n\n return [\n active,\n onComplete,\n troubles.length > 0 ? troubles[0] : undefined,\n troubles,\n ];\n};\n","import type { TroubleContainerModel } from \"../../../models\";\nimport { useTroubleContainerModel } from \"./use-trouble-container\";\n\ninterface TroubleContainerProps {\n troubleContainer: TroubleContainerModel;\n}\n// react HOC to provide a BoardContainer to a component\nexport function withTroubleContainer<\n T extends TroubleContainerProps = TroubleContainerProps\n>(WrappedComponent: React.ComponentType<T>) {\n return (props: Omit<T, keyof TroubleContainerProps>) => {\n const { model, status, KosModelLoader } = useTroubleContainerModel();\n\n return (\n <KosModelLoader {...status}>\n <WrappedComponent {...(props as T)} troubleContainer={model} />\n </KosModelLoader>\n );\n };\n}\n","import { useEffect, useState } from \"react\";\nimport { kosAutoEffect } from \"../../../core\";\nimport {\n UsbUpdateContainer,\n type UsbUpdateContainerModel,\n type UsbUpdateModel,\n} from \"../../../models\";\nimport { useKosModel } from \"../use-kos-model\";\n\n/**\n * Hook for accessing the KOS USB update container model.\n *\n * @kosService core.use-usb-update\n * @kosApiLevel 2\n */\nexport const useUsbUpdateContainer = () => {\n const modelId = UsbUpdateContainer.type;\n const result = useKosModel<UsbUpdateContainerModel>({\n modelId,\n modelType: UsbUpdateContainer.type,\n options: {},\n activate: true,\n destroyOnUnmount: true,\n });\n\n const [inserted, setInserted] = useState<boolean>(false);\n const [updateAvailable, setUpdateAvailable] = useState<boolean>(false);\n const [updates, setUpdates] = useState<UsbUpdateModel[]>([]);\n const [isSearching, setIsSearching] = useState<boolean>(false);\n const [noUpdates, setNoUpdates] = useState<boolean>(false);\n\n useEffect(() => {\n const disposer = kosAutoEffect(() => {\n setInserted(result.model?.isUsbInserted ?? false);\n setUpdateAvailable(result.model?.hasAvailableUpdates ?? false);\n setUpdates(result.model?.data ?? []);\n setIsSearching(result.model?.isSearchingUpdates ?? false);\n setNoUpdates(result.model?.noAvailableUpdates ?? false);\n });\n\n return () => {\n disposer();\n };\n }, [result.model]);\n\n return {\n ...result,\n inserted,\n updateAvailable,\n updates,\n isSearching,\n noUpdates,\n };\n};\n","import type { UsbUpdateContainerModel } from \"../../../models\";\nimport { useUsbUpdateContainer } from \"./use-usb-update-container\";\n\ninterface UsbUpdateContainerProps {\n usbUpdateContainer: UsbUpdateContainerModel;\n}\n\ntype HoCUsbUpdateContainerProps = UsbUpdateContainerProps;\n// react HOC to provide a UsbUpdateContainer to a component\nexport function withUsbUpdateContainer<\n T extends HoCUsbUpdateContainerProps = HoCUsbUpdateContainerProps\n>(WrappedComponent: React.ComponentType<T>) {\n return (props: Omit<T, keyof UsbUpdateContainerProps>) => {\n const { model, status, KosModelLoader } = useUsbUpdateContainer();\n\n return (\n <KosModelLoader {...status}>\n <WrappedComponent {...(props as T)} usbUpdateContainer={model} />\n </KosModelLoader>\n );\n };\n}\n","import { autorun } from \"mobx\";\nimport { useEffect, useState } from \"react\";\nimport type { IConfigBeanModel, IConfigBeanModelOptions } from \"../../models\";\nimport { ConfigBean, ConfigPropertyTypes } from \"../../models\";\nimport { useKosModel } from \"./use-kos-model\";\n\ninterface UseConfigBeanParams {\n path: string;\n propKey?: string;\n}\n/**\n * Hook for binding to a KOS configuration bean.\n *\n * @kosService core.use-config-property\n * @kosApiLevel 2\n */\nexport const useConfigBean = ({ path, propKey }: UseConfigBeanParams) => {\n const { status } = useKosModel<IConfigBeanModel, IConfigBeanModelOptions>({\n modelType: ConfigBean.type,\n modelId: path,\n options: {\n path,\n },\n });\n const [ready, setReady] = useState(false);\n const [config, setConfig] = useState<IConfigBeanModel>();\n const [value, setValue] = useState<ConfigPropertyTypes>(\"\");\n const [error, setError] = useState<string>();\n const updateValue = (val: string) => {\n if (config && propKey) {\n config.updateProperty(propKey, val);\n }\n };\n useEffect(() => {\n if (status.model) {\n setConfig(status.model);\n }\n\n if (status.model && propKey) {\n if (status.model?.props.has(propKey)) {\n setValue(status.model.props[propKey]!);\n } else {\n setError(`property ${propKey} not found`);\n }\n }\n\n if (status.ready) {\n setReady(status.ready);\n }\n }, [status.ready, status.model, propKey]);\n\n useEffect(() => {\n if (propKey) {\n autorun(() => {\n const prop = config?.props[propKey];\n setValue(prop || \"\");\n });\n }\n }, [config, propKey]);\n\n return {\n config,\n ready,\n value,\n error,\n updateValue,\n };\n};\n","import {\n ChangeEvent,\n Reducer,\n useCallback,\n useEffect,\n useReducer,\n useState,\n} from \"react\";\nimport { kosAutoEffect, whenReady } from \"../../core\";\nimport type {\n ConfigPropertyTypes,\n OptionsType,\n SchemaOptionsType,\n} from \"../../models\";\nimport { KosConfigProperty } from \"../../models\";\n\ntype SelectCallback = string | ChangeEvent<HTMLSelectElement>;\nexport type OptionsTransformer = (options?: OptionsType[]) => any[];\n\ntype KosConfigProp =\n | KosConfigProperty<ConfigPropertyTypes>\n | KosConfigProperty<string>\n | KosConfigProperty<number>\n | KosConfigProperty<boolean>;\ninterface Props {\n configProperty?: KosConfigProp;\n optionsTransformer?: OptionsTransformer;\n}\n\ninterface UpdateAction<T extends object = any> {\n type: \"UPDATE\";\n payload: Partial<ConfigPropertyState<T>>;\n}\ninterface ConfigPropertyState<O extends object = any> {\n value: string;\n displayValue: string;\n significantValue: any;\n unit: string;\n options: OptionsType[];\n mappedOptions: O[];\n updateProperty?: (value: string) => void;\n displayOptions?: SchemaOptionsType;\n}\nconst reducer = <T extends object = any>(\n state: Partial<ConfigPropertyState<T>>,\n action: UpdateAction\n) => {\n switch (action.type) {\n case \"UPDATE\":\n return action.payload;\n default:\n return state;\n }\n};\n/**\n * Hook for binding to a KOS configuration property.\n *\n * @kosService core.use-config-property\n * @kosApiLevel 2\n */\nexport const useConfigProperty = <T extends object = any>({\n configProperty,\n optionsTransformer,\n}: Props) => {\n const [ready, setReady] = useState(false);\n const [error, setError] = useState(\"\");\n\n const [state, dispatch] = useReducer<\n Reducer<Partial<ConfigPropertyState<T>>, UpdateAction<T>>\n >(reducer, {\n value: String(configProperty?.value),\n displayValue: configProperty?.displayValue,\n significantValue: configProperty?.significantValue,\n unit: configProperty?.unit,\n options: configProperty?.options,\n mappedOptions: [],\n updateProperty: configProperty?.updateProperty,\n displayOptions: configProperty?.displayOptions,\n });\n\n const handleUpdate = useCallback(\n (e: SelectCallback) => {\n let value = \"factory\";\n if (typeof e === \"string\") {\n value = e;\n } else if (e?.target?.value) {\n value = e.target.value;\n }\n\n if (value) {\n configProperty?.updateProperty(value);\n }\n },\n [configProperty]\n );\n useEffect(() => {\n async function waitForProp(prop?: KosConfigProp) {\n try {\n if (prop) {\n await whenReady(prop);\n setReady(true);\n }\n } catch (e) {\n setError((e as Error).message);\n }\n }\n\n waitForProp(configProperty);\n }, [configProperty]);\n\n useEffect(() => {\n const disposer = kosAutoEffect(() => {\n if (configProperty && ready) {\n let mapped: any[] = [];\n if (optionsTransformer) {\n mapped = optionsTransformer(configProperty.options);\n }\n dispatch({\n type: \"UPDATE\",\n payload: {\n value: String(configProperty.value),\n displayValue: configProperty.displayValue,\n significantValue: configProperty.significantValue,\n unit: configProperty.unit,\n options: configProperty.options,\n mappedOptions: mapped,\n updateProperty: configProperty.updateProperty,\n displayOptions: configProperty?.displayOptions,\n },\n });\n }\n });\n return () => {\n disposer();\n };\n }, [configProperty, optionsTransformer, ready]);\n\n return {\n ...state,\n configSelectProps: {\n onChange: handleUpdate,\n value: state.value,\n options: optionsTransformer\n ? state.mappedOptions || []\n : state.options || [],\n },\n ready,\n error,\n };\n};\n","import { useEffect, useState } from \"react\";\nimport { EventBus } from \"../../common\";\nimport { WebSocketEvents } from \"../../core/core/transport/base-message-transport\";\nimport { useKosCore } from \"../contexts/kos-core-context\";\n\n/**\n * Details of the most recent WebSocket close event.\n *\n * @kosService core.use-connection-state\n * @kosApiLevel 23\n */\nexport interface DisconnectInfo {\n code: number;\n reason: string;\n wasClean: boolean;\n /** Wall-clock time (Date.now()) when the disconnect was observed. */\n at: number;\n}\n\n/**\n * Current KOS Core connection state plus info about the last disconnect.\n *\n * @kosService core.use-connection-state\n * @kosApiLevel 23\n */\nexport interface ConnectionState {\n online: boolean;\n lastDisconnect: DisconnectInfo | null;\n /** Milliseconds since the last disconnect, or null if none observed. */\n sinceLastDisconnectMs: number | null;\n}\n\n/**\n * Observes KOS Core connection state.\n *\n * Returns the current `online` status plus information about the most recent\n * disconnect (code, reason, wasClean, timestamp). `sinceLastDisconnectMs` is\n * recomputed on each render; components that need it to tick continuously\n * should re-render themselves via an interval.\n *\n * @kosService core.use-connection-state\n * @kosApiLevel 23\n */\nexport const useConnectionState = (): ConnectionState => {\n const { online } = useKosCore();\n const [lastDisconnect, setLastDisconnect] = useState<DisconnectInfo | null>(\n null\n );\n\n useEffect(() => {\n const { unsubscribe } = EventBus.subscribe(\n WebSocketEvents.DISCONNECTED,\n (msg) => {\n const payload = msg?.body as\n | { code: number; reason: string; wasClean: boolean }\n | undefined;\n if (\n payload &&\n typeof payload === \"object\" &&\n typeof payload.code === \"number\"\n ) {\n setLastDisconnect({\n code: payload.code,\n reason: payload.reason,\n wasClean: payload.wasClean,\n at: Date.now(),\n });\n }\n }\n );\n return () => {\n unsubscribe();\n };\n }, []);\n\n return {\n online,\n lastDisconnect,\n sinceLastDisconnectMs: lastDisconnect\n ? Date.now() - lastDisconnect.at\n : null,\n };\n};\n","/**\n * Type for month represented as zero-based (0 for January, 11 for December).\n */\ntype Month = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11;\n\n/**\n * Utility method to get an array of zero-based month options (0 through 11).\n */\nexport function getMonthOptions(): Month[] {\n return Array.from({ length: 12 }, (_, index) => index as Month);\n}\n\n/**\n * Utility method to determine the number of days in a given month of a particular year.\n * @param month - Zero-based month (0 for January, 11 for December).\n * @param year - The year to account for leap years (optional, default is current year).\n * @returns The number of days in the specified month.\n */\nexport function getDaysInMonth(month: Month, year?: number): number {\n const yearToUse = year ?? new Date().getFullYear();\n const daysInEachMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];\n\n // Adjust for leap year\n if (\n month === 1 &&\n ((yearToUse % 4 === 0 && yearToUse % 100 !== 0) || yearToUse % 400 === 0)\n ) {\n return 29;\n }\n\n return daysInEachMonth[month] ?? 0;\n}\n\n/**\n * Utility method to get an array of zero-based day options for a specific month and year.\n * @param month - Zero-based month (0 for January, 11 for December).\n * @param year - The year to account for leap years (optional, default is current year).\n * @returns The array of zero-based day options.\n */\nexport function getDayOptions(month: Month, year?: number): number[] {\n const daysInMonth = getDaysInMonth(month, year);\n return Array.from({ length: daysInMonth }, (_, index) => index);\n}\n\n/**\n * Utility method to get an array of year options.\n * @param startYear - The starting year for the array.\n * @param endYear - The ending year for the array.\n * @returns The array of year options.\n */\nexport function getYearOptions(startYear: number, endYear: number): number[] {\n if (startYear > endYear) {\n throw new Error(\"Start year must be less than or equal to end year\");\n }\n return Array.from(\n { length: endYear - startYear + 1 },\n (_, index) => startYear + index\n );\n}\n","import { getDaysInMonth } from \"./date\";\n\n// Returns the number of days in a given month & year\nexport function getDays(year: number, month: number): number {\n return new Date(year, month, 0).getDate();\n}\n\n// Returns an array of all days in a given month & year\n// TODO: Make numbers locale specific\nexport function getDaysArray(year: number, month: number): number[] {\n const numberOfDays = getDaysInMonth(month as any, year);\n const daysAry: number[] = [];\n for (let i = 1; i <= numberOfDays; i++) {\n daysAry.push(i);\n }\n return daysAry;\n}\n\n// Returns an array of months from 0 - 11\n// Note: The array needs to be 0-11 for date functions\nexport function getMonthsArray(): number[] {\n const months = [...Array(12).keys()].map((key) =>\n new Date(0, key).getMonth()\n );\n return months;\n}\n\n// Returns an array of full years\n// When passed a tupple of numbers, it will generate an array with the\n// provided year range.\nexport function getYearsArray(\n number: [number, number] = [2018, 2028]\n): number[] {\n // Create an array +- number of years from current year\n const yearsArray: number[] = [];\n for (let i = number[0]; i <= number[1]; i++) {\n yearsArray.push(i);\n }\n // Return the array\n return yearsArray;\n}\n\nexport type YearFormat = \"short\" | \"long\";\n\nexport function getFormattedYearsArray(\n format: YearFormat,\n range: [number, number] = [2018, 2028]\n): number[] {\n const fullYearsArray = getYearsArray(range);\n if (format === \"long\") {\n return fullYearsArray;\n }\n // Modify the values of the full years array to only return YY instead\n return fullYearsArray.map((year) => Number(year.toString().substring(2)));\n}\n\nexport type MonthFormat = \"numeric\" | \"short\" | \"long\";\n\nexport function getFormattedMonthsArray(\n monthFormat: MonthFormat = \"numeric\",\n locale = \"en-US\"\n) {\n const format = new Intl.DateTimeFormat(locale, {\n month: monthFormat,\n timeZone: \"UTC\",\n }).format;\n\n return [...Array(12).keys()].map((m) => format(new Date(Date.UTC(0, m, 1))));\n}\n\ninterface GetFormattedDateProps {\n locale?: string;\n year: number;\n month: number;\n day: number;\n formatOptions?: Intl.DateTimeFormatOptions;\n displayOrder?: string;\n}\n\n// Formats a given year, month, date based on an optional local and format options\nexport function getFormattedDate({\n locale = \"en-US\",\n year,\n month,\n day,\n formatOptions = {\n weekday: \"long\",\n year: \"numeric\",\n month: \"long\",\n day: \"numeric\",\n },\n displayOrder,\n}: GetFormattedDateProps): string {\n // Correct the month, due to it being an index in the Date method\n const correctedMonth = month - 1;\n const dateFormat = new Date(year, correctedMonth, day);\n const monthName = new Intl.DateTimeFormat(locale, {\n month: formatOptions.month,\n }).format(dateFormat);\n const yearName = new Intl.DateTimeFormat(locale, {\n year: formatOptions.year,\n }).format(dateFormat);\n const dayName = new Intl.DateTimeFormat(locale, {\n day: formatOptions.day,\n }).format(dateFormat);\n\n if (displayOrder) {\n if (displayOrder == \"MMDDYY\") {\n return `${monthName} ${dayName} ${yearName}`;\n } else if (displayOrder === \"DDMMYY\") {\n return `${dayName} ${monthName} ${yearName}`;\n } else if (displayOrder === \"YYMMDD\") {\n return `${yearName} ${monthName} ${dayName}`;\n } else {\n return `${yearName} ${dayName} ${monthName}`;\n }\n }\n // If a displayOrder override isn't provided, format according to the locale:\n return new Intl.DateTimeFormat(locale, formatOptions).format(dateFormat);\n}\n\n// Formats a year to the full 4 digit year to be used in Date methods\nexport function getFormattedYear(year: number): number {\n const formattedYear =\n year.toString().length === 2\n ? new Date(Date.parse(`01 Jan 20${year}`)).getFullYear()\n : year;\n return formattedYear;\n}\n\n// Formats a month to the 2 digit month code to be used in Date methods\nexport function getFormattedMonth(month: number | string): number {\n const formattedMonth =\n typeof month === \"string\"\n ? new Date(Date.parse(`01 ${month.substring(0, 3)} 2023`)).getMonth() + 1\n : month;\n return formattedMonth;\n}\n\n// Return an array assuming the calendar week starts on Sunday\nexport function getCalendarMonthArray(\n month,\n year,\n dayOptions: { label: string; value: number; disabled: boolean }[]\n): { label: string; value: number; disabled: boolean }[] {\n const formattedYear = getFormattedYear(year);\n const firstDay = new Date(formattedYear, month, 1).getDay();\n const numberOfDays = new Date(formattedYear, month + 1, 0).getDate();\n\n const monthArray = [...Array(42).keys()].map((index) => {\n if (index < firstDay || index > numberOfDays + firstDay - 1) {\n return { label: \"\", value: 0, disabled: true };\n } else {\n return dayOptions[index - firstDay];\n }\n });\n\n return monthArray;\n}\n\n// Returns a boolean value of if a provided month, day and year form a valid date\nexport function isValidDate(year, month, day): boolean {\n const zeroIndexedMonth = month - 1;\n const d = new Date(year, zeroIndexedMonth, day);\n return (\n new Date(d).getMonth() === zeroIndexedMonth && new Date(d).getDate() === day\n );\n}\n\n// Returns the last of the month in a provided month and year\nexport function getLastDayOfMonth(year, month): number {\n const lastDay = new Date(year, month, 0).getDate();\n return lastDay;\n}\n\nexport type DayFormatOptions = \"short\" | \"long\" | \"narrow\" | undefined;\n\nexport function getDayStrings(\n locale = \"en-US\",\n dayFormat: DayFormatOptions = \"short\"\n) {\n const format = new Intl.DateTimeFormat(locale, { weekday: dayFormat }).format;\n return [...Array(7).keys()].map((day) =>\n format(new Date(Date.UTC(2021, 5, day)))\n );\n}\n","import { format, parseISO } from \"date-fns\";\nimport { Dispatch, SetStateAction, useEffect, useMemo, useState } from \"react\";\nimport { RegionInfo, RegionInfoModel, RegionInfoOptions } from \"../../models\";\nimport {\n DayFormatOptions,\n MonthFormat,\n YearFormat,\n getCalendarMonthArray,\n getDayStrings,\n getDaysArray,\n getFormattedMonthsArray,\n getFormattedYear,\n getFormattedYearsArray,\n getLastDayOfMonth,\n getMonthsArray,\n isValidDate,\n} from \"../utils/date-utils\";\nimport { useKosModel } from \"./use-kos-model\";\n\nexport type DaysOfWeekFilter = [\n number?,\n number?,\n number?,\n number?,\n number?,\n number?,\n number?\n];\n\nexport interface UseDateArrayFormatOptions {\n yearFormat?: YearFormat;\n monthFormat?: MonthFormat;\n dayFormat?: DayFormatOptions;\n}\nexport interface UseDateArraysProps {\n locale?: string;\n // TODO: Can we tighten the typing on the number?\n year?: number;\n // TODO: Can we tighten the typing on the number?\n month?: number;\n // TODO: Can we tighten the typing on the number?\n day?: number;\n formatOptions?: UseDateArrayFormatOptions;\n yearRange?: [number, number];\n daysOfWeekFilter?: DaysOfWeekFilter;\n}\n\nexport function useDateArrays({\n locale = \"en-US\",\n year = new Date().getFullYear(),\n month = new Date().getMonth(),\n yearRange = [2018, 2028],\n daysOfWeekFilter = [],\n formatOptions: {\n yearFormat = \"long\",\n monthFormat = \"long\",\n dayFormat = \"short\",\n } = {},\n}: UseDateArraysProps) {\n const yearsArray = useYears(yearFormat, yearRange);\n const yearsOptionsArray = useYearsOptions(yearFormat, yearRange, locale);\n const monthsArray = useMonths(monthFormat, locale);\n const monthsOptionsArray = useMonthsOptions(monthFormat, locale);\n const daysArray = useDays(year, month);\n const daysOptionsArray = useDayOptions(year, month, locale, daysOfWeekFilter);\n const calendarDayArray = useCalendarDayArray(month, year, daysOptionsArray);\n const dayNamesArray = useDayNames(locale, dayFormat);\n\n return {\n daysArray,\n monthsArray,\n yearsArray,\n yearsOptionsArray,\n monthsOptionsArray,\n daysOptionsArray,\n calendarDayArray,\n dayNamesArray,\n };\n}\n\n// TODO: Tighten the range type to only be positive numbers within a range\nexport function useYears(\n format: YearFormat = \"long\",\n range: [number, number] = [2018, 2028]\n): number[] {\n const yearsArray = useMemo(\n () => getFormattedYearsArray(format, range),\n [format, range]\n );\n return yearsArray;\n}\n\nexport function useYearsOptions(\n format: YearFormat = \"long\",\n range: [number, number] = [2018, 2028],\n locale = \"en-US\"\n): { label: string; value: number }[] {\n const rawYearsArray = useYears(format, range);\n const yearsOptionsArray = useMemo(\n () =>\n rawYearsArray.map((year) => {\n return {\n label: year.toLocaleString(locale).replace(\",\", \"\"),\n value: year,\n };\n }),\n [locale, rawYearsArray]\n );\n return yearsOptionsArray;\n}\n\nexport function useMonths(\n format: MonthFormat,\n locale = \"en-US\"\n): number[] | string[] {\n const monthsArray = useMemo(\n () => getFormattedMonthsArray(format, locale),\n [format, locale]\n );\n return monthsArray;\n}\n\nexport function useMonthsOptions(\n format: MonthFormat,\n locale = \"en-US\"\n): { label: string; value: number }[] {\n const monthsArray = useMemo(() => getMonthsArray(), []);\n const monthLabelsArray = useMemo(\n () => getFormattedMonthsArray(format, locale),\n [format, locale]\n );\n const monthsOptionsArray = useMemo(\n () =>\n [...Array(12).keys()].map((index) => {\n return {\n label: monthLabelsArray[index],\n value: Number(monthsArray[index]),\n };\n }),\n [monthLabelsArray, monthsArray]\n );\n\n return monthsOptionsArray;\n}\n\nexport function useDays(year: number, month: number): number[] {\n // Convert year\n const formattedYear = getFormattedYear(year);\n\n const daysArray = useMemo(\n () => getDaysArray(formattedYear, month),\n [month, formattedYear]\n );\n\n return daysArray;\n}\n\nconst isFilteredDayOfWeek = (\n year: number,\n month: number,\n day: number,\n filters: DaysOfWeekFilter = []\n): boolean => {\n const dateToCheck: number = new Date(year, month, day).getDay();\n return filters.length > 0 && filters.includes(dateToCheck);\n};\n\nexport function useDayOptions(\n year: number,\n month: number,\n locale = \"en-US\",\n daysOfWeekFilter: DaysOfWeekFilter = []\n): { label: string; value: number; disabled: boolean }[] {\n // TODO: Refactor to be able to pass in additional metadata\n const rawDaysArray = useDays(year, month);\n\n const daysOptionsArray = useMemo(\n () =>\n rawDaysArray.map((day) => {\n return {\n label: day.toLocaleString(locale),\n value: day,\n disabled: isFilteredDayOfWeek(year, month, day, daysOfWeekFilter),\n };\n }),\n [daysOfWeekFilter, locale, month, rawDaysArray, year]\n );\n\n return daysOptionsArray;\n}\nexport function useDayNames(\n locale = \"en-US\",\n dayFormat: DayFormatOptions = \"short\"\n): string[] {\n const dayNamesArray = useMemo(\n () => getDayStrings(locale, dayFormat),\n [locale, dayFormat]\n );\n return dayNamesArray;\n}\n\ninterface UseFormattedDateProps {\n // TODO: Can we tighten the typing on the number?\n year: number;\n // TODO: Can we tighten the typing on the number?\n month: number;\n // TODO: Can we tighten the typing on the number?\n day: number;\n yearRange?: number;\n formatString: string;\n}\n\nexport function useFormattedDate({\n year = new Date().getFullYear(),\n month = new Date().getMonth(),\n day = new Date().getDate(),\n formatString,\n}: UseFormattedDateProps): { formattedDate: string } {\n const indexedMonth = month;\n const date = new Date(year, indexedMonth, day);\n const formattedDate = format(date, formatString);\n\n return { formattedDate };\n}\n\nexport function useCalendarDayArray(\n month: number,\n year: number,\n dayOptionsArray: { label: string; value: number; disabled: boolean }[]\n): { label: string; value: number; disabled: boolean }[] {\n const calendarDayArray = useMemo(\n () => getCalendarMonthArray(month, year, dayOptionsArray),\n [month, year, dayOptionsArray]\n );\n return calendarDayArray;\n}\n\nexport interface UseDatePropsReturnActions {\n setYear: Dispatch<SetStateAction<number>>;\n setYearRange: Dispatch<SetStateAction<[number, number]>>;\n setMonth: Dispatch<SetStateAction<number>>;\n setDay: Dispatch<SetStateAction<number>>;\n nextMonth: () => void;\n previousMonth: () => void;\n nextYear: () => void;\n previousYear: () => void;\n}\n\nexport interface UseDatePropsReturnState {\n year: number;\n yearRange: [number, number];\n month: number;\n day: number;\n yearsArray: number[];\n yearsOptionsArray: { label: string; value: number; disabled?: boolean }[];\n monthsArray: string[] | number[];\n monthsOptionsArray: {\n label: string | number;\n value: number;\n disabled?: boolean;\n }[];\n daysArray: number[];\n daysOptionsArray: { label: string; value: number; disabled?: boolean }[];\n calendarDayNames: string[];\n calendarDayArray: {\n label: string;\n value: number;\n disabled?: boolean;\n }[];\n formattedDate: string;\n}\n\nexport interface UseDatePropsReturn {\n dateActions: UseDatePropsReturnActions;\n dateState: UseDatePropsReturnState;\n}\n\nexport enum DateDisplayFormat {\n \"MMDDYY\" = \"MMDDYY\",\n \"DDMMYY\" = \"DDMMYY\",\n \"YYMMDD\" = \"YYMMDD\",\n \"YYDDMM\" = \"YYDDMM\",\n}\n\ninterface UseDatePropsFormatOptions extends UseDateArrayFormatOptions {\n formatString?: string;\n}\ninterface UseDatePropsFilterOptions {\n yearsRange?: [number, number];\n daysOfWeekFilter?: DaysOfWeekFilter;\n}\n\ninterface UseDateProps {\n locale?: string;\n date?: { day?: number; month?: number; year?: number };\n formatOptions?: UseDatePropsFormatOptions;\n filterOptions?: UseDatePropsFilterOptions;\n}\n\nexport function useDateProps({\n locale = \"en-US\",\n date: {\n year: yearProp = new Date().getFullYear(),\n month: monthProp = new Date().getMonth(),\n day: dayProp = new Date().getDate(),\n } = {\n year: new Date().getFullYear(),\n month: new Date().getMonth(),\n day: new Date().getDate(),\n },\n formatOptions: {\n yearFormat = \"long\",\n monthFormat = \"long\",\n dayFormat = \"short\",\n formatString = \"yyyy/MM/dd\",\n } = {},\n filterOptions: {\n yearsRange = [2018, 2028] as [number, number],\n daysOfWeekFilter = [] as DaysOfWeekFilter,\n } = {},\n}: UseDateProps): UseDatePropsReturn {\n const [year, setYear] = useState<number>(yearProp);\n const [yearRange, setYearRange] = useState<[number, number]>(yearsRange);\n const [month, setMonth] = useState<number>(monthProp);\n const [day, setDay] = useState<number>(dayProp);\n\n useEffect(() => {\n setYear(yearProp);\n }, [yearProp]);\n\n useEffect(() => {\n setMonth(monthProp);\n }, [monthProp]);\n\n useEffect(() => {\n setDay(dayProp);\n }, [dayProp]);\n\n const {\n yearsArray,\n yearsOptionsArray,\n monthsArray,\n monthsOptionsArray,\n daysArray,\n daysOptionsArray,\n calendarDayArray,\n dayNamesArray,\n } = useDateArrays({\n locale,\n year,\n yearRange,\n month,\n formatOptions: {\n yearFormat,\n monthFormat,\n dayFormat,\n },\n daysOfWeekFilter,\n });\n\n const { formattedDate } = useFormattedDate({\n year,\n month,\n day,\n formatString,\n });\n\n const nextMonth = (): void => {\n // Account for going past December\n const formattedYear =\n month < 11 ? getFormattedYear(year) : getFormattedYear(year + 1);\n const nextMonth = month < 11 ? month + 1 : 0;\n\n // Account for the day and if it's valid in the month\n if (!isValidDate(formattedYear, nextMonth, day)) {\n const lastValidDay = getLastDayOfMonth(formattedYear, nextMonth);\n setDay(lastValidDay);\n }\n if (nextMonth === 0) {\n setYear(formattedYear);\n }\n setMonth(nextMonth);\n };\n\n const previousMonth = (): void => {\n // Account for going before January\n const formattedYear =\n month === 0 ? getFormattedYear(year - 1) : getFormattedYear(year);\n\n const prevMonth = month === 0 ? 11 : month - 1;\n // Account for the day and if it's valid in the month\n if (!isValidDate(formattedYear, prevMonth, day)) {\n const lastValidDay = getLastDayOfMonth(formattedYear, prevMonth);\n setDay(lastValidDay);\n }\n if (prevMonth === 11) {\n setYear(formattedYear);\n }\n setMonth(prevMonth);\n };\n\n const nextYear = (): void => {\n const nextYear = year < yearRange[1] ? year + 1 : yearRange[0];\n // Account for the day and if it's valid in the month\n const formattedYear = getFormattedYear(nextYear);\n\n if (isValidDate(formattedYear, month, day)) {\n setYear(nextYear);\n } else {\n // If it's not a valid day, change the day to the last day of the month\n const lastValidDay = getLastDayOfMonth(getFormattedYear(year + 1), month);\n setDay(lastValidDay);\n setYear(nextYear);\n }\n };\n\n const previousYear = (): void => {\n const prevYear = year > yearRange[0] ? year - 1 : yearRange[0];\n const formattedYear = getFormattedYear(prevYear);\n\n if (isValidDate(formattedYear, month, day)) {\n setYear(prevYear);\n } else {\n // If it's not a valid day, change the day to the last day of the month\n const lastValidDay = getLastDayOfMonth(getFormattedYear(year - 1), month);\n setDay(lastValidDay);\n setYear(prevYear);\n }\n };\n\n return {\n dateActions: {\n setYear,\n setYearRange,\n setMonth,\n setDay,\n nextMonth,\n previousMonth,\n nextYear,\n previousYear,\n },\n dateState: {\n year,\n yearRange,\n month,\n day,\n yearsArray,\n yearsOptionsArray,\n monthsArray,\n monthsOptionsArray,\n daysArray,\n daysOptionsArray,\n calendarDayNames: dayNamesArray,\n calendarDayArray,\n formattedDate,\n },\n };\n}\n\nexport interface UseRegionalFormatProps {\n date?: Date | string;\n dateFormat?: string;\n timeFormat?: string;\n options?: {\n ignoreDateFormat?: boolean;\n };\n}\n\nexport function useRegionalTimeDate({\n date = new Date(),\n dateFormat,\n timeFormat,\n options = {},\n}: UseRegionalFormatProps): { formattedDate: string; formattedTime: string } {\n const [formattedTime, setFormattedTime] = useState(\"Formatting Time...\");\n const [formattedDate, setFormattedDate] = useState(\"Formatting Date...\");\n\n const ignoreDate = !!options.ignoreDateFormat;\n const { model, ready } = useKosModel<RegionInfoModel, RegionInfoOptions>({\n modelId: RegionInfo.type,\n modelType: RegionInfo.type,\n options: {},\n });\n const dateToFormat = typeof date === \"string\" ? parseISO(date) : date;\n\n useEffect(() => {\n if (ignoreDate) {\n setFormattedDate(\"\");\n } else if (dateFormat) {\n // Set date according to format string\n setFormattedDate(format(dateToFormat, dateFormat));\n } else {\n // Set date according to model if no date format string provided\n if (ready) {\n setFormattedDate(\n format(\n dateToFormat,\n model?.selectedDateFormat ? model?.selectedDateFormat : \"\"\n )\n );\n }\n }\n }, [ignoreDate, date, dateFormat, dateToFormat, model, ready]);\n\n useEffect(() => {\n if (timeFormat) {\n // Set date according to format string\n setFormattedTime(format(dateToFormat, timeFormat));\n } else {\n // Set date according to model if no time format string provided\n if (ready) {\n setFormattedTime(\n format(\n dateToFormat,\n model?.selectedTimeFormat ? model?.selectedTimeFormat : \"\"\n )\n );\n }\n }\n }, [date, timeFormat, dateToFormat, model, ready]);\n\n return { formattedDate, formattedTime };\n}\n","import { useEffect, useRef, useState } from \"react\";\nimport type { KosConfigProperty } from \"../../models\";\nimport { useConfigProperty } from \"./use-config-property\";\nimport { useRegionalTimeDate } from \"./use-date-props\";\n\ninterface Props {\n configProperty?: KosConfigProperty<number>;\n is24Hr?: boolean;\n}\n\ninterface DateRelative {\n hours: number;\n minutes: number;\n seconds: number;\n formattedTime;\n timeActions: {\n setHours: (hours: number) => void;\n setMinutes: (minutes: number) => void;\n setSeconds: (seconds: number) => void;\n };\n}\ninterface DateRelativeDataProps {\n secondsFromMidnight?: number;\n}\n\n/**\n * Hook to convert seconds from midnight to a human readable time format\n *\n * The hook will use the time format based on the regional settings\n *\n * @param secondsFromMidnight - The number of seconds from midnight\n * @returns The hours, minutes, seconds, formatted time and actions to update the time\n */\nexport const useDateRelativeData = ({\n secondsFromMidnight = 0,\n}: DateRelativeDataProps) => {\n const [hours, setHours] = useState(0);\n const [minutes, setMinutes] = useState(0);\n const [seconds, setSeconds] = useState(0);\n const [date, setDate] = useState(new Date());\n const { formattedTime } = useRegionalTimeDate({\n date,\n options: {\n ignoreDateFormat: true,\n },\n });\n useEffect(() => {\n const numericValue = Number(secondsFromMidnight);\n const _hours = Math.floor(numericValue / 3600);\n const _minutes = Math.floor((numericValue % 3600) / 60);\n const _seconds = numericValue % 60;\n setHours(_hours);\n setMinutes(_minutes);\n setSeconds(_seconds);\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() + numericValue * 1000);\n setDate(new Date(time));\n }, [secondsFromMidnight]);\n\n return {\n hours,\n minutes,\n seconds,\n formattedTime,\n timeActions: {\n setHours,\n setMinutes,\n setSeconds,\n },\n };\n};\n\n/**\n * Hook to translate date relative configuration properties to human readable time\n *\n * @param configProperty - The configuration property to use\n * @returns\n * @see useDateRelativeData\n */\nexport const useDateRelativeConfig = ({\n configProperty,\n}: Props): DateRelative => {\n const { value } = useConfigProperty({ configProperty });\n\n const secondsFromMidnight = parseInt(value || \"0\", 10);\n const { hours, minutes, seconds, formattedTime, timeActions } =\n useDateRelativeData({\n secondsFromMidnight,\n });\n\n const timeoutRef = useRef<NodeJS.Timeout>();\n\n useEffect(() => {\n // Calculate the new value only once per effect run\n const newValue = hours * 3600 + minutes * 60 + seconds;\n\n // Clear any previously set timeout to ensure only the latest update is applied\n if (timeoutRef.current) {\n clearTimeout(timeoutRef.current);\n }\n\n // Set a new timeout to update the property after 100ms\n timeoutRef.current = setTimeout(() => {\n if (configProperty) {\n configProperty.updateProperty(newValue.toString());\n }\n }, 100); // 100 milliseconds delay\n\n // Cleanup function to clear the timeout if the component is unmounted or dependencies change\n return () => {\n if (timeoutRef.current) {\n clearTimeout(timeoutRef.current);\n }\n };\n }, [configProperty, hours, minutes, seconds]); // Dependencies list\n return {\n hours,\n minutes,\n seconds,\n formattedTime,\n timeActions,\n };\n};\n","import { useEffect } from \"react\";\n\n// A warmup marker to simulate a special execution path\n/**\n * Represents a marker type used to indicate that a function or process\n * has been warmed up and is ready for use.\n *\n * This type is typically used as a flag or annotation in scenarios\n * where initialization or preparation steps are required before\n * execution.\n */\nexport type WarmupMarker = { __warmup: true };\n\n// Accepts a function that takes 0 or 1 argument\ntype Warmupable<T extends (arg?: any) => any> = (\n arg?: any | WarmupMarker\n) => ReturnType<T>;\n\ninterface UseFunctionWarmupOptions {\n intervalMs?: number; // How often to re-warm (ms)\n immediate?: boolean; // Should warmup run on mount\n}\n\n/**\n * A React hook that periodically invokes a given function to keep it \"warmed up.\"\n * This can be useful for functions that require initialization or caching to\n * improve performance during actual usage.\n *\n * @template T - The type of the function to be warmed up.\n * @param fn - The function to be warmed up. It should accept an optional argument\n * and handle a special warmup call with `{ __warmup: true }`.\n * @param options - Configuration options for the warmup behavior.\n * @param options.intervalMs - The interval in milliseconds at which the function\n * should be warmed up. Defaults to 5 minutes (300,000 ms).\n * If set to `null` or `0`, periodic warmup is disabled.\n * @param options.immediate - Whether to perform an immediate warmup when the hook\n * is first invoked. Defaults to `true`.\n *\n * @returns void\n *\n * @remarks\n * - If the `immediate` option is enabled, the function will be warmed up immediately\n * using `requestIdleCallback` if available, or a `setTimeout` fallback.\n * - Errors thrown during the warmup process are caught and ignored.\n * - The periodic warmup is cleaned up automatically when the component unmounts.\n *\n * @example\n * ```tsx\n * const lookup = (arg?: string | WarmupMarker) => {\n * if (typeof arg === \"object\" && arg.__warmup) return;\n * // ...\n * };\n * useFunctionWarmup(lookup, { intervalMs: 60000 });\n * ```\n */\nexport function useFunctionWarmup<T extends (arg?: any) => any>(\n fn: Warmupable<T>,\n options: UseFunctionWarmupOptions = {}\n) {\n const { intervalMs = 5 * 60 * 1000, immediate = true } = options;\n\n useEffect(() => {\n const warmup = () => {\n try {\n fn({ __warmup: true });\n } catch {\n // ignore errors from warmup path\n }\n };\n\n if (immediate) {\n if (\"requestIdleCallback\" in window) {\n requestIdleCallback(warmup);\n } else {\n setTimeout(warmup, 1);\n }\n }\n\n const id = intervalMs ? setInterval(warmup, intervalMs) : null;\n return () => {\n if (id) clearInterval(id);\n };\n }, [fn, intervalMs, immediate]);\n}\n","import { RegionInfo } from \"../../models\";\n\nimport { kosAutoEffect } from \"../../core\";\nimport type {\n DateFormatOptions,\n RegionInfoModel,\n RegionInfoOptions,\n} from \"../../models\";\n\nimport { ChangeEvent, useCallback, useEffect, useState } from \"react\";\nimport { useKosModel } from \"./use-kos-model\";\n\ntype SelectCallback = string | ChangeEvent<HTMLSelectElement>;\ntype DateFormatMap<T extends {} = any> = (format: DateFormatOptions) => T;\nconst DEFAULT_FORMAT_MAP: DateFormatMap = (format: DateFormatOptions) => (\n <option title={format.id} key={format.id} value={format.format}>\n {format.format}\n </option>\n);\n\n/**\n * The data returned from the useKosDateFormats hook.\n * @typeParam T - the type of the options returned from the dateFormatMap function.\n */\nexport interface KosDateFormatHookData<T extends {} = any> {\n /** the ids of the available date formats. */\n raw: string[];\n\n /** the region info model. */\n regionModel?: RegionInfoModel;\n\n /** the currently selected date format. */\n selectedDateFormat: string;\n\n dateFormatId: string;\n /** updates the selected date format. */\n updateDateFormat: (e: SelectCallback) => void;\n\n /**the props that can be spread into a select box component. */\n props: {\n onChange: (e: SelectCallback) => void;\n value: string;\n options: T[];\n };\n}\n\n/**\n * Manages the region's date format: the available formats, the selected\n * format, and props for a date format select box.\n *\n * @param dateFormatMap - maps a date format to a select-box option. The\n * default returns an `<option>` with the format as value and label.\n * @returns KosDateFormatHookData - the data returned from the hook.\n * @example\n * ```tsx\n * const { props } = useKosDateFormats();\n * const { options, ...selectAttributes } = props;\n * return <select {...selectAttributes}>{options}</select>;\n * ```\n */\nexport const useKosDateFormats = <T extends {} = any>(\n dateFormatMap: DateFormatMap<T> = DEFAULT_FORMAT_MAP\n): KosDateFormatHookData<T> => {\n const [dateFormats, setDateFormats] = useState<T[]>([]);\n const [selectedDateFormat, setSelectedDateFormat] = useState<{\n id: string;\n value: string;\n }>();\n\n const { model, ready } = useKosModel<RegionInfoModel, RegionInfoOptions>({\n modelType: RegionInfo.type,\n modelId: RegionInfo.type,\n options: {},\n });\n\n useEffect(() => {\n const cleanup = kosAutoEffect(() => {\n setDateFormats(model?.dateFormatOptions.map(dateFormatMap) || []);\n });\n\n return () => {\n cleanup();\n };\n }, [model, ready, dateFormatMap]);\n\n useEffect(() => {\n const cleanup = kosAutoEffect(() => {\n if (model?.dateFormatId && model?.selectedDateFormat) {\n setSelectedDateFormat({\n id: model?.dateFormatId,\n value: model?.selectedDateFormat,\n });\n }\n });\n\n return () => {\n cleanup();\n };\n }, [model?.selectedDateFormat, model?.dateFormatId]);\n\n const handleDateFormatChange = useCallback(\n (e: SelectCallback) => {\n let value = \"\";\n if (typeof e === \"string\") {\n value = e;\n } else if (e?.target?.value) {\n value = e.target.value;\n }\n\n if (value) {\n model?.setSelectedDateFormat(value);\n }\n },\n [model]\n );\n\n return {\n raw: model?.dateFormatOptions.map((o) => o.id) ?? [],\n regionModel: model,\n selectedDateFormat: selectedDateFormat?.value || \"\",\n dateFormatId: selectedDateFormat?.id || \"\",\n updateDateFormat: handleDateFormatChange,\n props: {\n onChange: handleDateFormatChange,\n value: selectedDateFormat?.id || \"\",\n options: dateFormats,\n },\n };\n};\n","import { ChangeEvent, useCallback, useEffect, useState } from \"react\";\nimport { kosAutoEffect } from \"../../core\";\nimport {\n KosConfigProperty,\n KosConfigPropertySpec,\n RegionInfo,\n RegionInfoModel,\n RegionInfoOptions,\n updateTimeZone,\n} from \"../../models\";\nimport { useKosModel } from \"./use-kos-model\";\n\ntype SelectCallback = string | ChangeEvent<HTMLSelectElement>;\ntype OptionMap<T extends {} = any> = (option: string) => T;\n\nconst DEFAULT_OPTION_MAP: OptionMap = (option: string) => (\n <option title={option} key={option} value={option}>\n {option}\n </option>\n);\n\nconst REGION_SETTINGS_PATH = \"kos:service:region:settings\";\nconst TIMEZONE_ATTRIBUTE = \"timeZone\";\nconst REGION_TIMEZONE_ID = `${REGION_SETTINGS_PATH}-${TIMEZONE_ATTRIBUTE}`;\n\n/**\n * Custom React hook for managing and interacting with timezone data.\n * It fetches timezone information from the RegionInfoModel and facilitates\n * timezone selection in a React application.\n *\n * @typeparam T The type of the options that the hook will produce for use in UI components.\n * @param optionsMap A function that maps a timezone string to a JSX structure or other specified format.\n * @returns An object containing timezone options, raw timezone data, the selected timezone, and functions to handle updates.\n *\n * @example\n * ```tsx\n * const TimeZonePicker = kosComponent(() => {\n * const { selectProps } = useKosTimeZones();\n * const { options, ...props } = selectProps;\n * return <select {...props}>{options}</select>;\n * });\n * ```\n */\nexport const useKosTimeZones = <T extends {} = any>(\n optionsMap: OptionMap<T> = DEFAULT_OPTION_MAP\n) => {\n const [timeZones, setTimeZones] = useState<T[]>([]);\n const [selectedTimeZone, setSelectedTimeZone] = useState<string>(\"\");\n\n // Fetches the RegionInfoModel using the useKosModel hook.\n const { model, ready } = useKosModel<RegionInfoModel, RegionInfoOptions>({\n modelType: RegionInfo.type,\n modelId: RegionInfo.type,\n options: {},\n });\n\n // Defines a KosConfigProperty for timezone information.\n const timezoneInfo: KosConfigProperty<string> = KosConfigPropertySpec.factory(\n REGION_TIMEZONE_ID\n )({\n path: REGION_SETTINGS_PATH,\n attribute: TIMEZONE_ATTRIBUTE,\n }) as KosConfigProperty<string>;\n\n // Updates the timeZones state when the model changes.\n useEffect(() => {\n const cleanup = kosAutoEffect(() => {\n setTimeZones(model?.timeZones.map(optionsMap) || []);\n\n if (model?.timeZones.length) {\n updateTimeZone(model?.timeZones[0]);\n }\n });\n\n return () => {\n cleanup();\n };\n }, [model, ready, optionsMap]);\n\n // Updates the selectedTimeZone state based on the timezoneInfo value.\n useEffect(() => {\n const cleanup = kosAutoEffect(() => {\n setSelectedTimeZone(timezoneInfo.value || \"\");\n });\n\n return () => {\n cleanup();\n };\n }, [timezoneInfo.value]);\n\n // Callback function to handle timezone updates.\n const handleUpdate = useCallback((e: SelectCallback) => {\n let value = \"factory\";\n if (typeof e === \"string\") {\n value = e;\n } else if (e?.target?.value) {\n value = e.target.value;\n }\n\n if (value) {\n updateTimeZone(value);\n }\n }, []);\n\n return {\n options: timeZones,\n raw: model?.timeZones ?? [],\n regionModel: model,\n selectedTimeZone,\n timeZones: model?.timeZones ?? [],\n updateTimeZone: handleUpdate,\n selectProps: {\n onChange: handleUpdate,\n value: selectedTimeZone,\n options: timeZones,\n },\n };\n};\n","import { ChangeEvent, useCallback, useEffect, useState } from \"react\";\nimport { kosAutoEffect } from \"../../core\";\nimport {\n KosConfigPropertySpec,\n type KosConfigProperty,\n} from \"../../models/models/config-bean-prop\";\nimport {\n RegionInfo,\n RegionInfoOptions,\n RegionServices,\n type RegionInfoModel,\n} from \"../../models/models/region-info\";\nimport { updateRegion } from \"../../models/utils/region-utils\";\nimport { useKosModel } from \"./use-kos-model\";\n\nconst REGION_PATH = \"kos:service:region\";\nconst REGION_ATTRIBUTE = \"regionId\";\nconst REGION_ID = `${REGION_PATH}-${REGION_ATTRIBUTE}`;\n\ntype SelectCallback = string | ChangeEvent<HTMLSelectElement>;\ntype RegionMap<T extends object = any> = (region: string) => T;\nconst DEFAULT_REGION_MAP: RegionMap = (region: string) => (\n <option title={region} key={region} value={region}>\n {region}\n </option>\n);\n\n/**\n * The data returned from the useKosRegions hook.\n * @typeParam RegionData - the region data returned from the backend service. Must extend `RegionServices.BaseRegionResponse`.\n * @typeParam T - the type of the options returned from the regionMap function.\n */\nexport interface KosRegionHookData<\n RegionData extends RegionServices.BaseRegionResponse = RegionServices.BaseRegionResponse,\n T extends object = any\n> {\n /**the raw region data returned from the backend service. */\n raw: string[];\n\n /**the region model returned from the backend service. */\n regionModel?: RegionInfoModel<RegionData>;\n\n /** the region data returned from the backend service. */\n regionData?: RegionData;\n\n /**the currently selected region. */\n selectedRegion: string;\n\n /**a function that can be used to update the region. */\n updateRegion: (e: SelectCallback) => void;\n\n /**the props that can be spread into a select box component. */\n regionSelectProps: {\n onChange: (e: SelectCallback) => void;\n value: string;\n options: T[];\n };\n}\n\n/**\n * Manages the device region: the available regions, the selected region and\n * its data, and props for a region select box.\n *\n * @typeParam RegionData - the region data returned from the backend service. Must extend `RegionServices.BaseRegionResponse`.\n * @param regionMap - maps a region string to a select-box option. The default\n * returns an `<option>` with the region as value and label. Pass a custom map\n * when a third-party select component expects a different option shape.\n * @returns KosRegionHookData - the data returned from the hook.\n * @example\n * ```tsx\n * const { regionSelectProps, selectedRegion } = useKosRegions();\n * const { options, ...selectAttributes } = regionSelectProps;\n * return <select {...selectAttributes}>{options}</select>;\n * ```\n */\nexport const useKosRegions = <\n RegionData extends RegionServices.BaseRegionResponse = RegionServices.BaseRegionResponse,\n T extends {} = any\n>(\n regionMap: RegionMap<T> = DEFAULT_REGION_MAP\n): KosRegionHookData<RegionData, T> => {\n const [regions, setRegions] = useState<T[]>([]);\n const [selectedRegion, setSelectedRegion] = useState<string>(\"factory\");\n const { model, ready } = useKosModel<\n RegionInfoModel<RegionData>,\n RegionInfoOptions\n >({\n modelType: RegionInfo.type,\n modelId: RegionInfo.type,\n });\n\n const regionInfo: KosConfigProperty<string> = KosConfigPropertySpec.factory(\n REGION_ID\n )({\n path: REGION_PATH,\n attribute: REGION_ATTRIBUTE,\n }) as KosConfigProperty<string>;\n useEffect(() => {\n const cleanup = kosAutoEffect(() => {\n setRegions(model?.availableRegions.map(regionMap) || []);\n });\n\n return () => {\n cleanup();\n };\n }, [model, ready, regionMap]);\n\n useEffect(() => {\n const cleanup = kosAutoEffect(() => {\n setSelectedRegion(regionInfo.value || \"factory\");\n });\n\n return () => {\n cleanup();\n };\n }, [regionInfo.value]);\n\n const handleUpdate = useCallback((e: SelectCallback) => {\n let value = \"factory\";\n if (typeof e === \"string\") {\n value = e;\n } else if (e?.target?.value) {\n value = e.target.value;\n }\n\n if (value) {\n updateRegion(value);\n }\n }, []);\n\n return {\n raw: model?.availableRegions ?? [],\n regionModel: model,\n regionData: model?.selectedRegion,\n selectedRegion,\n updateRegion: handleUpdate,\n\n regionSelectProps: {\n onChange: handleUpdate,\n value: selectedRegion,\n options: regions,\n },\n };\n};\n","import { RegionInfo } from \"../../models/models/region-info\";\n\nimport { kosAutoEffect } from \"../../core\";\nimport type {\n RegionInfoModel,\n RegionInfoOptions,\n TimeFormatOptions,\n} from \"../../models/models/region-info\";\n\nimport { ChangeEvent, useCallback, useEffect, useState } from \"react\";\nimport { useKosModel } from \"./use-kos-model\";\n\ntype SelectCallback = string | ChangeEvent<HTMLSelectElement>;\ntype TimeFormatMap<T extends {} = any> = (format: TimeFormatOptions) => T;\nconst DEFAULT_FORMAT_MAP: TimeFormatMap = (format: TimeFormatOptions) => (\n <option title={format.id} key={format.id} value={format.format}>\n {format.format}\n </option>\n);\n\n/**\n * The data returned from the useKosTimeFormats hook.\n * @typeParam T - the type of the options returned from the timeFormatMap function.\n */\nexport interface KosTimeFormatHookData<T extends {} = any> {\n /** the ids of the available time formats. */\n raw: string[];\n\n /** the region info model. */\n regionModel?: RegionInfoModel;\n\n /** the currently selected time format. */\n selectedTimeFormat: string;\n\n timeFormatId: string;\n /** updates the selected time format. */\n updateTimeFormat: (e: SelectCallback) => void;\n\n /**the props that can be spread into a select box component. */\n props: {\n onChange: (e: SelectCallback) => void;\n value: string;\n options: T[];\n };\n}\n\n/**\n * Manages the region's time format: the available formats, the selected\n * format, and props for a time format select box.\n *\n * @param timeFormatMap - maps a time format to a select-box option. The\n * default returns an `<option>` with the format as value and label.\n * @returns KosTimeFormatHookData - the data returned from the hook.\n * @example\n * ```tsx\n * const { props } = useKosTimeFormats();\n * const { options, ...selectAttributes } = props;\n * return <select {...selectAttributes}>{options}</select>;\n * ```\n */\nexport const useKosTimeFormats = <T extends {} = any>(\n timeFormatMap: TimeFormatMap<T> = DEFAULT_FORMAT_MAP\n): KosTimeFormatHookData<T> => {\n const [timeFormats, setTimeFormats] = useState<T[]>([]);\n const [selectedTimeFormat, setSelectedTimeFormat] = useState<{\n id: string;\n value: string;\n }>();\n const { model, ready } = useKosModel<RegionInfoModel, RegionInfoOptions>({\n modelType: RegionInfo.type,\n modelId: RegionInfo.type,\n options: {},\n });\n\n useEffect(() => {\n const cleanup = kosAutoEffect(() => {\n setTimeFormats(model?.timeFormatOptions.map(timeFormatMap) || []);\n });\n\n return () => {\n cleanup();\n };\n }, [model, ready, timeFormatMap]);\n\n useEffect(() => {\n const cleanup = kosAutoEffect(() => {\n if (model?.timeFormatId && model?.selectedTimeFormat) {\n setSelectedTimeFormat({\n id: model?.timeFormatId,\n value: model?.selectedTimeFormat,\n });\n }\n });\n\n return () => {\n cleanup();\n };\n }, [model?.selectedTimeFormat, model?.timeFormatId]);\n\n const handleTimeFormatChange = useCallback(\n (e: SelectCallback) => {\n let value = \"\";\n if (typeof e === \"string\") {\n value = e;\n } else if (e?.target?.value) {\n value = e.target.value;\n }\n\n if (value) {\n model?.setSelectedTimeFormat(value);\n }\n },\n [model]\n );\n\n return {\n raw: model?.timeFormatOptions.map((o) => o.id) ?? [],\n regionModel: model,\n selectedTimeFormat: selectedTimeFormat?.value ?? \"\",\n timeFormatId: selectedTimeFormat?.id ?? \"\",\n updateTimeFormat: handleTimeFormatChange,\n props: {\n onChange: handleTimeFormatChange,\n value: selectedTimeFormat?.id ?? \"\",\n options: timeFormats,\n },\n };\n};\n","import { useMemo } from \"react\";\nimport { kosComputed } from \"../../core\";\n\n/**\n * @description An abstraction of React's useMemo for observable dependencies.\n * @param callback A function that returns a desired value.\n * @param dependencies An array of non-observable variables that are required to run the callback.\n */\nexport const useLocalComputed = <T>(\n callback: () => T,\n dependencies: ReadonlyArray<unknown>\n) => useMemo(() => kosComputed(callback), dependencies);\n","import { useEffect, useState } from \"react\";\nimport { KosLog } from \"../../core/core/log\";\n\ninterface MutationObserverOptions {\n config: MutationObserverInit;\n}\n\n// Default options for the MutationObserver\nconst DEFAULT_OPTIONS: MutationObserverOptions = {\n config: { attributes: true, childList: true, subtree: true },\n};\n\n/**\n * A hook that creates a MutationObserver and observes a DOM element for mutations. When a mutation occurs, the callback function is executed.\n *\n * @param targetEl The DOM element to observe\n * @param cb The callback function to execute when a mutation occurs\n * @param options Options to pass to the MutationObserver to configure what mutations to observe\n */\nexport function useMutationObserver<T extends Node>(\n targetEl: T,\n cb: MutationCallback,\n options: MutationObserverOptions = DEFAULT_OPTIONS\n) {\n const [observer, setObserver] = useState<MutationObserver | null>(null);\n useEffect(() => {\n // Validate the callback function\n if (!cb || typeof cb !== \"function\") {\n throw new Error(\"A valid callback function is required\");\n }\n const obs = new MutationObserver(cb);\n setObserver(obs);\n }, [cb, options, setObserver]);\n\n useEffect(() => {\n // Validate the observer\n if (!observer) return () => {};\n\n // Validate the target element\n if (!targetEl) {\n throw new Error(\"A valid DOM element is required\");\n }\n const { config } = options;\n try {\n // Start observing the target element for configured mutations\n observer.observe(targetEl, config);\n } catch (e) {\n KosLog.error(e);\n }\n return () => {\n // Stop observing the target element\n if (observer) {\n observer.disconnect();\n }\n };\n }, [observer, targetEl, options]);\n}\n","import {\n IntersectionStrategy,\n IntersectionStrategyState,\n} from \"./intersection-strategy\";\n\nexport const DomIntersectionStrategy: IntersectionStrategy = {\n validateStart: function (_state: IntersectionStrategyState): boolean {\n return true;\n },\n validateStop: function (state: IntersectionStrategyState): boolean {\n const boundingRect = (\n state.event.currentTarget as HTMLElement\n ).getBoundingClientRect();\n const [clientX, clientY] = state.xy;\n\n const isOutside =\n clientX < boundingRect.left ||\n clientX > boundingRect.right ||\n clientY < boundingRect.top ||\n clientY > boundingRect.bottom;\n\n return isOutside;\n },\n};\n","import { useGesture } from \"@use-gesture/react\";\nimport { useRef } from \"react\";\nimport { KosLog } from \"../../../core/core/log\";\nimport { DomIntersectionStrategy } from \"./strategy/dom-intersection-strategy\";\nimport { IntersectionStrategy } from \"./strategy/intersection-strategy\";\n\ninterface PressHandlers {\n onPressed?: () => void;\n onRelease?: () => void;\n intersectionStrategy?: IntersectionStrategy;\n}\n\nconst logger = KosLog.createLogger({\n name: \"usePressGesture\",\n group: \"kos-hooks\",\n});\nexport function usePressGesture({\n onPressed,\n onRelease,\n intersectionStrategy = DomIntersectionStrategy,\n}: PressHandlers) {\n const isDraggingInside = useRef<boolean>(false);\n\n const bind = useGesture({\n onDragStart: (state) => {\n logger.info(\"onDragStart\", state.type);\n if (!intersectionStrategy.validateStart(state)) return;\n\n if (onPressed) onPressed();\n isDraggingInside.current = true;\n },\n onDrag: (state) => {\n logger.info(\"onDrag\", state.type);\n if (!isDraggingInside.current) return;\n\n if (intersectionStrategy.validateStop(state)) {\n if (onRelease) onRelease();\n isDraggingInside.current = false;\n }\n },\n onDragEnd: (state) => {\n logger.info(\"onDragEnd\", state.type);\n if (isDraggingInside.current && onRelease) {\n onRelease();\n isDraggingInside.current = false;\n }\n },\n });\n\n const handlePointerDown = () => {\n if (onPressed) onPressed();\n isDraggingInside.current = true;\n };\n\n const handlePointerUp = () => {\n if (isDraggingInside.current && onRelease) {\n onRelease();\n isDraggingInside.current = false;\n }\n };\n\n const handlePointerOut = () => {\n if (isDraggingInside.current && onRelease) {\n onRelease();\n isDraggingInside.current = false;\n }\n };\n\n return {\n dom: bind,\n mesh: () => {\n return {\n onPointerDown: handlePointerDown,\n onPointerUp: handlePointerUp,\n onPointerOut: handlePointerOut,\n };\n },\n };\n}\n","import { useEffect, useState } from \"react\";\nimport { kosAutoEffect, KosCore } from \"../../core\";\nexport const useProjectReload = () => {\n const [reloading, setReloading] = useState(false);\n const core = KosCore.getInstance();\n useEffect(() => {\n const disposer = kosAutoEffect(() => {\n if (!core) return;\n if (core.reloading === reloading) return;\n setReloading(core.reloading);\n });\n\n return () => {\n disposer();\n };\n }, [core, reloading]);\n\n return [reloading];\n};\n","import { useCallback, useMemo, useState } from \"react\";\nimport { format } from \"date-fns\";\n\ntype TimeFormat = \"2-digit\" | \"numeric\";\n\nexport function useHourValues(hour12 = false, format: TimeFormat = \"2-digit\") {\n return useMemo(() => {\n const hours = hour12 ? 12 : 24;\n\n return Array.from({ length: hours }, (_, i) => {\n const hour = hour12 && i === 0 ? 12 : i % hours;\n\n return {\n id: i,\n label:\n format === \"2-digit\"\n ? hour.toString().padStart(2, \"0\")\n : hour.toString(),\n };\n });\n }, [format, hour12]);\n}\n\nexport function useTimeValues(\n length: number,\n format: TimeFormat = \"2-digit\",\n labelOffset = 0,\n valueOffset = 0\n) {\n return useMemo(\n () =>\n Array.from({ length }, (_, i) => {\n const label = String(i + labelOffset);\n\n return {\n id: i + valueOffset,\n label: format === \"2-digit\" ? label.padStart(2, \"0\") : label,\n };\n }),\n [length, labelOffset, valueOffset, format]\n );\n}\n\nexport function useAmPmValues(locale = \"en-US\") {\n return useMemo(\n () =>\n [\"AM\", \"PM\"].map((period) => {\n const formattedPeriod = new Intl.DateTimeFormat(locale, {\n hour: \"2-digit\",\n hour12: true,\n }).formatToParts(new Date().setHours(period === \"AM\" ? 0 : 12))[2]\n .value;\n\n return { id: formattedPeriod, label: formattedPeriod };\n }),\n [locale]\n );\n}\n\nexport interface UseTimeOptionsProps {\n formatOptions?: Intl.DateTimeFormatOptions;\n locale?: string;\n}\n\nexport function useTimeOptions({\n formatOptions: {\n hour12 = true,\n hour = \"2-digit\",\n minute = \"2-digit\",\n second = \"2-digit\",\n } = { hour12: true, hour: \"2-digit\", minute: \"2-digit\", second: \"2-digit\" },\n locale = \"en-US\",\n}: UseTimeOptionsProps) {\n const hourOptions = useHourValues(hour12, hour);\n const minuteOptions = useTimeValues(60, minute);\n const secondOptions = useTimeValues(60, second);\n const amPmOptions = useAmPmValues(locale);\n\n return {\n hourOptions,\n minuteOptions,\n secondOptions,\n amPmOptions,\n };\n}\n\nexport function useFormattedTime(date: Date, formatString: string): string {\n const formattedDate = format(date, formatString);\n\n return formattedDate;\n}\n\nexport interface UseTimeProps {\n formatOptions?: Intl.DateTimeFormatOptions;\n initialDate?: Date;\n locale?: string;\n format?: string;\n}\n\nexport function useTimeProps({\n formatOptions,\n initialDate = new Date(),\n locale = \"en-US\",\n format = \"HH:mm\",\n}: UseTimeProps) {\n const [date, setDate] = useState(initialDate);\n\n const setHours = useCallback((hours: number) => {\n setDate((prevDate) => {\n const newDate = new Date(prevDate);\n newDate.setHours(Number(hours));\n\n return newDate;\n });\n }, []);\n\n const setMinutes = useCallback((minutes: number) => {\n setDate((prevDate) => {\n const newDate = new Date(prevDate);\n newDate.setMinutes(Number(minutes));\n\n return newDate;\n });\n }, []);\n\n const setSeconds = useCallback((seconds: number) => {\n setDate((prevDate) => {\n const newDate = new Date(prevDate);\n newDate.setSeconds(Number(seconds));\n\n return newDate;\n });\n }, []);\n\n const setTime = useCallback((date: Date) => {\n const newDate = new Date(date);\n\n setDate(newDate);\n }, []);\n\n const formattedTime = useFormattedTime(date, format);\n\n const { hourOptions, minuteOptions, secondOptions, amPmOptions } =\n useTimeOptions({\n formatOptions,\n locale,\n });\n\n return {\n amPmOptions,\n formattedTime,\n hourOptions,\n minuteOptions,\n secondOptions,\n setHours,\n setMinutes,\n setSeconds,\n setTime,\n time: new Date(date),\n };\n}\n","import { useMemo } from \"react\";\nimport { useKosRegions } from \"./use-kos-regions\";\nimport { useTimeProps, type UseTimeProps } from \"./use-time-props\";\n\nexport const useRegionTimeProps = (props?: UseTimeProps) => {\n const { regionModel } = useKosRegions();\n\n const formatOptions = useMemo(() => {\n return { hour12: regionModel?.is12HourTimeFormat };\n }, [regionModel?.is12HourTimeFormat]);\n\n return useTimeProps({\n ...props,\n locale: regionModel?.regionId,\n format: regionModel?.selectedTimeFormat,\n formatOptions,\n });\n};\n","import { useEffect, useMemo, useRef, useState } from \"react\";\nimport {\n hasReadyHook,\n isDisposable,\n} from \"../../../core/core/decorators/kos-view-model\";\n\n/**\n * Configuration options for the useViewModel hook.\n */\nexport interface UseViewModelOptions {\n /**\n * When true, calls the ViewModel's dispose() method on unmount\n * and when dependencies change causing recreation.\n * Default: true (if dispose method exists)\n */\n disposeOnUnmount?: boolean;\n}\n\n/**\n * Result returned by useViewModel when the ViewModel implements IKosViewModelReady.\n */\nexport interface UseViewModelResult<T> {\n /** The ViewModel instance */\n viewModel: T;\n /** Whether the ViewModel's ready() hook has completed */\n ready: boolean;\n /** Error from the ready() hook, if any */\n error: Error | undefined;\n}\n\n/**\n * React hook for creating and managing ViewModel instances.\n *\n * The hook:\n * - Creates the ViewModel using the provided factory function\n * - Calls ready() if the ViewModel implements IKosViewModelReady\n * - Automatically calls dispose() on unmount (if the method exists)\n * - Re-creates the ViewModel when dependencies change\n * - Disposes the previous ViewModel when recreating\n *\n * @param factory - Function that creates the ViewModel instance\n * @param deps - Dependency array (similar to useEffect/useMemo)\n * @param options - Optional configuration\n * @returns UseViewModelResult with viewModel, ready state, and error\n *\n * @example\n * ```tsx\n * const OrderSummary = kosComponent(({ order }: Props) => {\n * const { viewModel: vm, ready, error } = useViewModel(\n * () => new OrderSummaryViewModel(order),\n * [order]\n * );\n * if (error) return <ErrorDisplay error={error} />;\n * if (!ready) return <Loading />;\n * return <div>Total: {vm.total}</div>;\n * });\n * ```\n *\n * @category KOS React Hook\n */\nexport function useViewModel<T>(\n factory: () => T,\n deps: React.DependencyList,\n options: UseViewModelOptions = {}\n): UseViewModelResult<T> {\n const { disposeOnUnmount = true } = options;\n\n // Track ready state and errors\n const [ready, setReady] = useState(false);\n const [error, setError] = useState<Error | undefined>(undefined);\n\n // Track the current ViewModel for disposal\n const viewModelRef = useRef<T | null>(null);\n const isFirstRender = useRef(true);\n // Track ready call to prevent duplicate calls\n const readyCalledRef = useRef(false);\n\n // Create ViewModel (memoized based on deps)\n const viewModel = useMemo(() => {\n // Dispose previous instance if deps changed (not on first render)\n if (\n !isFirstRender.current &&\n viewModelRef.current &&\n disposeOnUnmount &&\n isDisposable(viewModelRef.current)\n ) {\n const previous = viewModelRef.current;\n // Run dispose asynchronously to avoid React warnings during render\n Promise.resolve().then(() => {\n if (isDisposable(previous)) {\n previous.dispose();\n }\n });\n }\n\n isFirstRender.current = false;\n // Reset ready state for new instance\n readyCalledRef.current = false;\n\n // Create new instance\n const instance = factory();\n viewModelRef.current = instance;\n return instance;\n }, deps);\n\n // Handle ready() hook\n useEffect(() => {\n // Skip if already called for this instance\n if (readyCalledRef.current) return;\n\n // If ViewModel has ready hook, call it\n if (hasReadyHook(viewModel)) {\n readyCalledRef.current = true;\n setReady(false);\n setError(undefined);\n\n viewModel\n .ready()\n .then(() => {\n setReady(true);\n })\n .catch((err: Error) => {\n setError(err);\n setReady(false);\n });\n } else {\n // No ready hook - immediately ready\n setReady(true);\n setError(undefined);\n }\n }, [viewModel]);\n\n // Handle cleanup on unmount\n useEffect(\n () => () => {\n if (\n disposeOnUnmount &&\n viewModelRef.current &&\n isDisposable(viewModelRef.current)\n ) {\n viewModelRef.current.dispose();\n }\n viewModelRef.current = null;\n },\n [disposeOnUnmount]\n );\n\n return { viewModel, ready, error };\n}\n","import LoadingMessage from \"../components/loading-message\";\nimport { useProjectReload } from \"./use-project-reloading\";\n\ninterface ProjectReloadingProps {\n reloading: boolean;\n}\n// react HOC to provide a NodeTargetContainer to a component\nexport function withProjectReloading<\n T extends ProjectReloadingProps = ProjectReloadingProps\n>(WrappedComponent: React.ComponentType<T>) {\n return (props: Omit<T, keyof ProjectReloadingProps>) => {\n const [reloading] = useProjectReload();\n\n return reloading ? (\n <LoadingMessage message=\"Wait a moment while your project reloads...\" />\n ) : (\n <WrappedComponent {...(props as T)} />\n );\n };\n}\n","import { registerApiLevels } from \"@kosdev-code/kos-api-levels\";\n\n// Registers the package-level API integer for this SDK.\n// The level history (which tag boundaries changed the public surface and why) lives in\n// kos-api-levels/generated/api-archaeology-report.md, produced by the archaeology scanner.\nregisterApiLevels({ \"kos-ui-sdk\": 24 });\n\nexport * from \"./common\";\nexport * from \"./core\";\nexport * from \"./models\";\nexport * from \"./models/models/canvas-renderer\";\nexport * from \"./models/models/gpio-chip\";\nexport * from \"./models/models/gpio-pin\";\nexport * from \"./models/models/kos-expression-evaluator\";\nexport * from \"./models/models/kos-log-manager\";\nexport * from \"./models/models/log-block\";\nexport * from \"./models/models/studio-properties\";\nexport * from \"./ui\";\n"],"names":["debounce","buffer","request","dm","KosFetchMethods","index","getDaysInMonth","EventBus.subscribe","log","EventBus.publish","token","formatter","KosConfigPropertySpec","kosAutoEffect","REGION_PATH","REGION_ATTRIBUTE","REGION_ID","kosServiceRequest","baseKosServiceRequest","endpoint","serviceRequest","ep","api","REGION_SETTINGS_PATH","TIMEZONE_ATTRIBUTE","REGION_TIMEZONE_ID","configResponse","MODEL_TYPE","__publicField","__decorateClass","KOS_SERVICE.kosServiceRequest","KOS_SERVICE.api","API","message","kosModel","filter","ErrorBoundaryWithFallback","useSuspenseData","fetchModel","modelId","KosModelLoader","translations","locale","format","kosComponent","action","DateDisplayFormat","nextMonth","nextYear","RegionInfo","setDate","DEFAULT_FORMAT_MAP","cb","observer","setTime","date"],"mappings":";;;;;;;;;;;;;;AAAA,MAAM,8BAAc,IAAA;AAYb,SAAS,eACd,SACA,WACA,mBACA,aACA,eACM;AACN,MACE,OAAO,YAAY,eACnB,QAAQ,IAAI,UAAU,MAAM,cAC5B;AACA;AAAA,EACF;AACA,MAAI,QAAQ,IAAI,OAAO,EAAG;AAC1B,UAAQ,IAAI,OAAO;AACnB,UAAQ;AAAA,IACN,UAAU,OAAO,yBAAyB,SAAS,UAAU,iBAAiB,UACpE,WAAW,uCAAuC,aAAa;AAAA,EAAA;AAE7E;AC7BA,MAAM,YAAyB,CAAA;AAQxB,SAAS,kBAAkB,QAA2B;AAC3D,SAAO,OAAO,WAAW,MAAM;AACjC;ACKO,SAAS,KACd,WACA,UACY;AACZ,QAAM,eAAe,UAAU,WAAW,CAAC,QAAY;AAErD,iBAAa,YAAA;AACb,aAAS,GAAG;AAAA,EACd,CAAC;AAED,SAAO,aAAa;AACtB;AAYO,SAAS,QACd,WACA,SACY;AACZ,SAAO,IAAI,QAAQ,CAAC,SAAS,WAAW;AACtC,QAAI,YAAmC;AAEvC,UAAM,cAAc,KAAK,WAAW,CAAC,QAAY;AAC/C,UAAI,WAAW;AACb,qBAAa,SAAS;AAAA,MACxB;AACA,cAAQ,GAAI;AAAA,IACd,CAAC;AAED,QAAI,SAAS;AACX,kBAAY,WAAW,MAAM;AAC3B,oBAAA;AACA,eAAO,IAAI,MAAM,8BAA8B,SAAS,EAAE,CAAC;AAAA,MAC7D,GAAG,OAAO;AAAA,IACZ;AAAA,EAC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C,IAEtE,oBAAC,kBAAA,EAAkB,GAAI,MAAA,CAAa;AAAA,EAExC;AACF;ACdA,kBAAkB,EAAE,cAAc,IAAI;"}
1
+ {"version":3,"file":"index.js","sources":["../../../packages/kos-api-levels/src/deprecation.ts","../../../packages/kos-api-levels/src/registry.ts","../../../packages/kos-ui-sdk/src/common/events/eventBus.functional.ts","../../../packages/kos-ui-sdk/src/common/file-utils.ts","../../../packages/kos-ui-sdk/src/core/core/api/wrapPromise.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kos-companion.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kos-context.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kos-execute-service-request.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kos-multiple-future-aware.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kos-log.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kos-mixin.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kos-reference.ts","../../../packages/kos-ui-sdk/src/core/types/utils/kos-fetch.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kos-trouble-aware.ts","../../../packages/kos-ui-sdk/src/core/core/extension/initialize-extension.ts","../../../packages/kos-ui-sdk/src/core/core/extension/plugin-extension-manager.ts","../../../packages/kos-ui-sdk/src/core/util/debounce.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kosSubscribe.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kos-view-model.ts","../../../packages/kos-ui-sdk/src/core/util/ancestor-path-visitor.ts","../../../packages/kos-ui-sdk/src/core/util/apply-mixins.ts","../../../packages/kos-ui-sdk/src/core/util/array-utils.ts","../../../packages/kos-ui-sdk/src/core/util/date-utils.ts","../../../packages/kos-ui-sdk/src/core/util/hsl-to-hex.ts","../../../packages/kos-ui-sdk/src/core/util/middleware.ts","../../../packages/kos-ui-sdk/src/core/util/model-registration-utils.ts","../../../packages/kos-ui-sdk/src/core/util/paired-client-heartbeat.ts","../../../packages/kos-ui-sdk/src/core/util/retry-with-exponential-backoff.ts","../../../packages/kos-ui-sdk/src/core/util/service-response.ts","../../../packages/kos-ui-sdk/src/core/util/wait-for-request.ts","../../../packages/kos-ui-sdk/src/core/core/indexing/kos-index-aware.ts","../../../packages/kos-ui-sdk/src/core/core/indexing/kos-container-index-aware.ts","../../../packages/kos-ui-sdk/src/core/core/kos-registration.ts","../../../packages/kos-ui-sdk/src/core/core/kos-singleton-registration.ts","../../../packages/kos-ui-sdk/src/core/core/models/kos-token/index.ts","../../../packages/kos-ui-sdk/src/models/decorators/kos-config-bean.ts","../../../packages/kos-ui-sdk/src/models/decorators/kos-config-bean-prop.ts","../../../packages/kos-ui-sdk/src/models/decorators/kos-state-bean.ts","../../../packages/kos-ui-sdk/src/models/decorators/kos-state-prop.ts","../../../packages/kos-ui-sdk/src/models/types/cancellable-promise.ts","../../../packages/kos-ui-sdk/src/models/utils/cancellable-future-call.ts","../../../packages/kos-ui-sdk/src/models/models/translation/descriptor-merge.ts","../../../packages/kos-ui-sdk/src/models/models/translation/translation-context.ts","../../../packages/kos-ui-sdk/src/models/utils/extension-manager.ts","../../../packages/kos-ui-sdk/src/models/utils/persistence-store.ts","../../../packages/kos-ui-sdk/src/models/utils/region-utils.ts","../../../packages/kos-ui-sdk/src/models/utils/service-accessor.ts","../../../packages/kos-ui-sdk/src/models/utils/services/kos/daily/service.ts","../../../packages/kos-ui-sdk/src/models/utils/services/kos/1.6.5/service.ts","../../../packages/kos-ui-sdk/src/models/utils/services/kos/1.8.1/service.ts","../../../packages/kos-ui-sdk/src/models/utils/services/kos/1.9.x/service.ts","../../../packages/kos-ui-sdk/src/models/utils/services/vfs/daily/service.ts","../../../packages/kos-ui-sdk/src/models/utils/services/vfs/1.6.5/service.ts","../../../packages/kos-ui-sdk/src/models/utils/services/vfs/1.8.1/service.ts","../../../packages/kos-ui-sdk/src/models/utils/services/vfs/1.9.x/service.ts","../../../packages/kos-ui-sdk/src/models/utils/timezone-utils.ts","../../../packages/kos-ui-sdk/src/models/models/trouble/utils/is-trouble-aware.ts","../../../packages/kos-ui-sdk/src/models/services/login/index.ts","../../../packages/kos-ui-sdk/src/models/models/gpio-pin/gpio-pin-model.ts","../../../packages/kos-ui-sdk/src/models/models/gpio-pin/gpio-pin-container-model.ts","../../../packages/kos-ui-sdk/src/models/models/gpio-chip/gpio-chip-model.ts","../../../packages/kos-ui-sdk/src/models/models/gpio-chip/services/gpio-chip-services.ts","../../../packages/kos-ui-sdk/src/models/models/gpio-chip/gpio-chip-builders.ts","../../../packages/kos-ui-sdk/src/models/models/gpio-chip/gpio-chip-container-model.ts","../../../packages/kos-ui-sdk/src/models/models/studio-properties/services/studio-properties-services.ts","../../../packages/kos-ui-sdk/src/models/models/studio-properties/studio-properties-model.ts","../../../packages/kos-ui-sdk/src/models/models/studio-properties/studio-properties-registration.ts","../../../packages/kos-ui-sdk/src/ui/components/loading-message/loading-message-styles.ts","../../../packages/kos-ui-sdk/src/ui/components/loading-message/index.tsx","../../../packages/kos-ui-sdk/src/ui/components/error-boundary/error-boundary.tsx","../../../packages/kos-ui-sdk/src/ui/components/progress-bar/progress-bar.tsx","../../../packages/kos-ui-sdk/src/ui/components/kos-model-loader/contexts/kos-model-context.tsx","../../../packages/kos-ui-sdk/src/ui/components/kos-model-loader/contexts/kos-model-hierarchy-context.tsx","../../../packages/kos-ui-sdk/src/ui/components/kos-model-loader/kos-model-loader.tsx","../../../packages/kos-ui-sdk/src/ui/contexts/fetch-kos-core.ts","../../../packages/kos-ui-sdk/src/ui/contexts/kos-core-context.tsx","../../../packages/kos-ui-sdk/src/ui/policies/constants.ts","../../../packages/kos-ui-sdk/src/ui/policies/reload-on-disconnect-policy.tsx","../../../packages/kos-ui-sdk/src/ui/components/reconnecting-overlay/use-reconnecting-overlay-state.ts","../../../packages/kos-ui-sdk/src/ui/components/reconnecting-overlay/reconnecting-overlay-styles.ts","../../../packages/kos-ui-sdk/src/ui/components/reconnecting-overlay/index.tsx","../../../packages/kos-ui-sdk/src/ui/components/connection-dev-button/use-connection-dev-state.ts","../../../packages/kos-ui-sdk/src/ui/components/connection-dev-button/connection-dev-button-styles.ts","../../../packages/kos-ui-sdk/src/ui/components/connection-dev-button/index.tsx","../../../packages/kos-ui-sdk/src/ui/contexts/create-model-context.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/use-kos-model.ts","../../../packages/kos-ui-sdk/src/ui/hooks/kos-time/use-kos-time.ts","../../../packages/kos-ui-sdk/src/ui/contexts/kos-time/kos-time-provider.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/software-info/use-software-info.ts","../../../packages/kos-ui-sdk/src/ui/hooks/software-info/with-software-info.tsx","../../../packages/kos-ui-sdk/src/ui/contexts/software-info/software-info-provider.tsx","../../../packages/kos-ui-sdk/src/ui/contexts/token-context.tsx","../../../packages/kos-ui-sdk/src/ui/contexts/translation-container/kos-translations-provider.tsx","../../../packages/kos-ui-sdk/src/ui/features/canvas/hooks/canvas-dispatcher/use-canvas-dispatcher.ts","../../../packages/kos-ui-sdk/src/ui/features/canvas/hooks/canvas-dispatcher/with-canvas-dispatcher.tsx","../../../packages/kos-ui-sdk/src/ui/features/canvas/utils/preview-decoder.ts","../../../packages/kos-ui-sdk/src/ui/features/canvas/components/canvas-streamer/canvas-streamer.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/device/use-device.ts","../../../packages/kos-ui-sdk/src/ui/hooks/device/with-device.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/fetch-model.ts","../../../packages/kos-ui-sdk/src/ui/hooks/kos-time/with-kos-time.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/network-interface-container/use-network-interface-container.ts","../../../packages/kos-ui-sdk/src/ui/hooks/network-interface-container/with-network-interface-container.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/ota/use-ota.ts","../../../packages/kos-ui-sdk/src/ui/hooks/ota/with-ota.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/outside-alerter.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/state-prop/use-state-prop.ts","../../../packages/kos-ui-sdk/src/ui/hooks/storage-device-container/use-storage-device-container.ts","../../../packages/kos-ui-sdk/src/ui/hooks/storage-device-container/with-storage-device-container.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/timer/use-timer.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/translation-container/trans.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/translation-container/use-translation.ts","../../../packages/kos-ui-sdk/src/ui/hooks/translation-container/use-translation-container.ts","../../../packages/kos-ui-sdk/src/ui/hooks/translation-container/with-translation-container.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/trouble/use-trouble.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/trouble/use-trouble-container.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/trouble/use-trouble-visibility.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/trouble/with-trouble-container.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/usb-update-container/use-usb-update-container.ts","../../../packages/kos-ui-sdk/src/ui/hooks/usb-update-container/with-usb-update-container.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/use-config-bean.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/use-config-property.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/use-connection-state.ts","../../../packages/kos-ui-sdk/src/ui/utils/date.ts","../../../packages/kos-ui-sdk/src/ui/utils/date-utils.ts","../../../packages/kos-ui-sdk/src/ui/hooks/use-date-props.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/use-date-relative-prop.ts","../../../packages/kos-ui-sdk/src/ui/hooks/use-function-warmup.ts","../../../packages/kos-ui-sdk/src/ui/hooks/use-kos-date-formats.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/use-kos-region-timezones.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/use-kos-regions.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/use-kos-time-formats.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/use-local-computed.ts","../../../packages/kos-ui-sdk/src/ui/hooks/use-mutation-observer.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/use-press-gesture/strategy/dom-intersection-strategy.ts","../../../packages/kos-ui-sdk/src/ui/hooks/use-press-gesture/use-press-gesture.ts","../../../packages/kos-ui-sdk/src/ui/hooks/use-project-reloading.ts","../../../packages/kos-ui-sdk/src/ui/hooks/use-time-props.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/use-region-time-props.ts","../../../packages/kos-ui-sdk/src/ui/hooks/view-model/use-view-model.ts","../../../packages/kos-ui-sdk/src/ui/hooks/with-project-reload.tsx","../../../packages/kos-ui-sdk/src/index.ts"],"sourcesContent":["const _warned = new Set<string>();\n\n/**\n * Emits a one-time console warning in non-production environments when a\n * deprecated API is used.\n *\n * @param apiName - The name of the deprecated API (e.g. `@kosSubscribe`)\n * @param serviceId - The service the API belongs to (e.g. `core.subscribe`)\n * @param deprecatedAtLevel - The API level at which this API was deprecated\n * @param replacement - The recommended replacement (e.g. `@kosTopicHandler`)\n * @param removeAtLevel - The API level at which this API will be removed\n */\nexport function warnDeprecated(\n apiName: string,\n serviceId: string,\n deprecatedAtLevel: number,\n replacement: string,\n removeAtLevel: number\n): void {\n if (\n typeof process !== \"undefined\" &&\n process.env[\"NODE_ENV\"] === \"production\"\n ) {\n return;\n }\n if (_warned.has(apiName)) return;\n _warned.add(apiName);\n console.warn(\n `[KOS] \"${apiName}\" is deprecated since ${serviceId} level ${deprecatedAtLevel}. ` +\n `Use \"${replacement}\" instead. Will be removed at level ${removeAtLevel}.`\n );\n}\n","import type { ApiLevelMap } from \"./types\";\n\nconst _registry: ApiLevelMap = {};\n\n/**\n * Registers API levels for an SDK package. Each SDK package calls this on\n * import to populate the in-memory registry. Works in browser and Node.js.\n * The call lives in each package's index.ts; the release scanner\n * (`scanner/generate-release.ts`) updates its level number.\n */\nexport function registerApiLevels(levels: ApiLevelMap): void {\n Object.assign(_registry, levels);\n}\n\nexport function getRegistry(): Readonly<ApiLevelMap> {\n return _registry;\n}\n","/**\n * Functional programming utilities for the EventBus\n * Provides reactive and promise-based patterns for event handling\n */\n\nimport { ApiCallback, EventCallback, publish, subscribe } from \"./eventBus\";\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/**\n * Wait for multiple events to occur (Promise.all pattern)\n *\n * @param eventTypes - Array of event types to wait for\n * @param timeout - Optional timeout in milliseconds\n * @returns Promise that resolves when all events have occurred\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function waitForAll<T = ApiCallback>(\n eventTypes: string[],\n timeout?: number\n): Promise<T[]> {\n const promises = eventTypes.map((eventType) =>\n waitFor<T>(eventType, timeout)\n );\n return Promise.all(promises);\n}\n\n/**\n * Wait for the first event to occur from a list (Promise.race pattern)\n *\n * @param eventTypes - Array of event types to race\n * @param timeout - Optional timeout in milliseconds\n * @returns Promise that resolves with the first event\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function race<T = ApiCallback>(\n eventTypes: string[],\n timeout?: number\n): Promise<{ eventType: string; data: T }> {\n return new Promise((resolve, reject) => {\n const unsubscribers: (() => void)[] = [];\n let timeoutId: NodeJS.Timeout | null = null;\n let resolved = false;\n\n const cleanup = () => {\n unsubscribers.forEach((unsub) => unsub());\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n };\n\n eventTypes.forEach((eventType) => {\n const unsubscribe = once(eventType, (msg?: T) => {\n if (!resolved) {\n resolved = true;\n cleanup();\n resolve({ eventType, data: msg! });\n }\n });\n unsubscribers.push(unsubscribe);\n });\n\n if (timeout) {\n timeoutId = setTimeout(() => {\n if (!resolved) {\n resolved = true;\n cleanup();\n reject(\n new Error(`Timeout waiting for any event: ${eventTypes.join(\", \")}`)\n );\n }\n }, timeout);\n }\n });\n}\n\n/**\n * Filter events based on a predicate function\n *\n * @param eventType - The event type to filter\n * @param predicate - Function to test each event\n * @param callback - Callback for events that pass the filter\n * @returns Unsubscribe function\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function filter<T = ApiCallback>(\n eventType: string,\n predicate: (msg: T) => boolean,\n callback: EventCallback<T>\n): () => void {\n const subscription = subscribe(eventType, (msg?: T) => {\n if (msg && predicate(msg)) {\n callback(msg);\n }\n });\n\n return subscription.unsubscribe;\n}\n\n/**\n * Transform events using a map function\n *\n * @param eventType - The event type to transform\n * @param transform - Function to transform the event data\n * @param callback - Callback for transformed events\n * @returns Unsubscribe function\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function map<T = ApiCallback, R = any>(\n eventType: string,\n transform: (msg: T) => R,\n callback: (msg: R) => void\n): () => void {\n const subscription = subscribe(eventType, (msg?: T) => {\n if (msg) {\n const transformed = transform(msg);\n callback(transformed);\n }\n });\n\n return subscription.unsubscribe;\n}\n\n/**\n * Debounce events - only emit after a period of inactivity\n *\n * @param eventType - The event type to debounce\n * @param delay - Delay in milliseconds\n * @param callback - Callback for debounced events\n * @returns Unsubscribe function\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function debounce<T = ApiCallback>(\n eventType: string,\n delay: number,\n callback: EventCallback<T>\n): () => void {\n let timeoutId: NodeJS.Timeout | null = null;\n\n const subscription = subscribe(eventType, (msg?: T) => {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n timeoutId = setTimeout(() => {\n callback(msg);\n }, delay);\n });\n\n return () => {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n subscription.unsubscribe();\n };\n}\n\n/**\n * Throttle events - limit emissions to once per interval\n *\n * @param eventType - The event type to throttle\n * @param interval - Minimum interval between emissions in milliseconds\n * @param callback - Callback for throttled events\n * @returns Unsubscribe function\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function throttle<T = ApiCallback>(\n eventType: string,\n interval: number,\n callback: EventCallback<T>\n): () => void {\n let lastEmit = 0;\n let pendingTimeout: NodeJS.Timeout | null = null;\n\n const subscription = subscribe(eventType, (msg?: T) => {\n const now = Date.now();\n const timeSinceLastEmit = now - lastEmit;\n\n if (timeSinceLastEmit >= interval) {\n lastEmit = now;\n callback(msg);\n } else if (!pendingTimeout) {\n // Schedule emission for the remaining time\n pendingTimeout = setTimeout(() => {\n lastEmit = Date.now();\n callback(msg);\n pendingTimeout = null;\n }, interval - timeSinceLastEmit);\n }\n });\n\n return () => {\n if (pendingTimeout) {\n clearTimeout(pendingTimeout);\n }\n subscription.unsubscribe();\n };\n}\n\n/**\n * Buffer events and emit them as an array\n *\n * @param eventType - The event type to buffer\n * @param bufferTime - Time window to collect events in milliseconds\n * @param callback - Callback for buffered events\n * @returns Unsubscribe function\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function buffer<T = ApiCallback>(\n eventType: string,\n bufferTime: number,\n callback: (events: T[]) => void\n): () => void {\n let buffer: T[] = [];\n let timeoutId: NodeJS.Timeout | null = null;\n\n const flush = () => {\n if (buffer.length > 0) {\n callback([...buffer]);\n buffer = [];\n }\n };\n\n const subscription = subscribe(eventType, (msg?: T) => {\n if (msg) {\n buffer.push(msg);\n\n if (!timeoutId) {\n timeoutId = setTimeout(() => {\n flush();\n timeoutId = null;\n }, bufferTime);\n }\n }\n });\n\n return () => {\n if (timeoutId) {\n clearTimeout(timeoutId);\n flush(); // Emit any remaining buffered events\n }\n subscription.unsubscribe();\n };\n}\n\n/**\n * Create a replay subject that remembers the last N events\n *\n * @param eventType - The event type to replay\n * @param bufferSize - Number of events to remember\n * @returns Object with subscribe method that replays buffered events\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function replay<T = ApiCallback>(eventType: string, bufferSize = 1) {\n const buffer: T[] = [];\n\n // Subscribe to capture events\n subscribe(eventType, (msg?: T) => {\n if (msg) {\n buffer.push(msg);\n if (buffer.length > bufferSize) {\n buffer.shift();\n }\n }\n });\n\n return {\n subscribe: (callback: EventCallback<T>) => {\n // Replay buffered events immediately\n buffer.forEach((event) => callback(event));\n\n // Then subscribe for future events\n return subscribe(eventType, callback);\n },\n };\n}\n\n/**\n * Merge multiple event streams into one\n *\n * @param eventTypes - Array of event types to merge\n * @param callback - Callback for all merged events\n * @returns Unsubscribe function for all subscriptions\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function merge<T = ApiCallback>(\n eventTypes: string[],\n callback: (eventType: string, msg: T) => void\n): () => void {\n const subscriptions = eventTypes.map((eventType) =>\n subscribe(eventType, (msg?: T) => {\n if (msg) {\n callback(eventType, msg);\n }\n })\n );\n\n return () => {\n subscriptions.forEach((sub) => sub.unsubscribe());\n };\n}\n\n/**\n * Create a state machine that transitions based on events\n *\n * @param initialState - The initial state\n * @param transitions - Object mapping states to event handlers\n * @returns Object with current state and unsubscribe function\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function stateMachine<TState extends string, T = ApiCallback>(\n initialState: TState,\n transitions: Record<TState, Record<string, (msg: T) => TState>>\n) {\n let currentState = initialState;\n const subscriptions: (() => void)[] = [];\n\n // Subscribe to all events mentioned in transitions\n const allEvents = new Set<string>();\n Object.values(transitions).forEach((stateTransitions) => {\n Object.keys(stateTransitions as Record<string, any>).forEach((event) => {\n allEvents.add(event);\n });\n });\n\n allEvents.forEach((eventType) => {\n const { unsubscribe } = subscribe(eventType, (msg?: T) => {\n const stateTransitions = transitions[currentState];\n if (stateTransitions && stateTransitions[eventType]) {\n const nextState = stateTransitions[eventType](msg!);\n currentState = nextState;\n }\n });\n subscriptions.push(unsubscribe);\n });\n\n return {\n get state() {\n return currentState;\n },\n unsubscribe: () => {\n subscriptions.forEach((unsub) => unsub());\n },\n };\n}\n\n/**\n * Utility to create a promise that can be resolved by publishing an event\n *\n * @param requestEvent - Event type to publish the request\n * @param responseEvent - Event type to wait for the response\n * @param request - The request data to publish\n * @param timeout - Optional timeout in milliseconds\n * @returns Promise that resolves with the response\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function request<TRequest = any, TResponse = ApiCallback>(\n requestEvent: string,\n responseEvent: string,\n request: TRequest,\n timeout?: number\n): Promise<TResponse> {\n const responsePromise = waitFor<TResponse>(responseEvent, timeout);\n publish(requestEvent, request);\n return responsePromise;\n}\n\n/**\n * Create an async iterator for events\n *\n * @param eventType - The event type to iterate\n * @returns Async iterator for use with for-await-of\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport async function* eventIterator<T = ApiCallback>(\n eventType: string\n): AsyncIterableIterator<T> {\n const queue: T[] = [];\n const waiters: ((value: T) => void)[] = [];\n\n const subscription = subscribe(eventType, (msg?: T) => {\n if (msg) {\n if (waiters.length > 0) {\n const waiter = waiters.shift()!;\n waiter(msg);\n } else {\n queue.push(msg);\n }\n }\n });\n\n try {\n while (true) {\n if (queue.length > 0) {\n yield queue.shift()!;\n } else {\n yield await new Promise<T>((resolve) => {\n waiters.push(resolve);\n });\n }\n }\n } finally {\n subscription.unsubscribe();\n }\n}\n\n/**\n * Namespace collecting all functional event bus utilities.\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport const EventBusFunctional = {\n once,\n waitFor,\n waitForAll,\n race,\n filter,\n map,\n debounce,\n throttle,\n buffer,\n replay,\n merge,\n stateMachine,\n request,\n eventIterator,\n};\n","type Sizes = \"bytes\" | \"KB\" | \"MB\" | \"GB\" | \"TB\";\ninterface Convert {\n value: number;\n scale: Sizes;\n toString: () => string;\n}\nexport const convertFileSizeRaw = (bytes: number, decimals = 0): Convert => {\n if (!+bytes)\n return {\n value: 0,\n scale: \"bytes\",\n toString: () => `0 bytes`,\n };\n\n const k = 1024;\n const dm = decimals < 0 ? 0 : decimals;\n const sizes: Sizes[] = [\"bytes\", \"KB\", \"MB\", \"GB\", \"TB\"];\n\n const i = Math.floor(Math.log(bytes) / Math.log(k));\n const value = parseFloat((bytes / Math.pow(k, i)).toFixed(dm));\n const scale = sizes[i];\n return {\n value,\n scale,\n toString: () => `${value} ${scale}`,\n };\n};\n","/**\n * Utility function that will wrap an arbitrary promise in order for it to\n * conform to the React Suspense API. By utilizing this higher order function\n * React components can participate in the Suspense workflow and enable the application\n * to display fallback behaviour while KOS data models or APIs are being fetched.\n *\n * @param promise The promise to be resolved\n * @returns an Object with a single `read` function that will be used to broadcast\n * status back to the React framework.\n */\nexport function wrapPromise<T>(promise: Promise<T>) {\n let status = `pending`;\n let response;\n\n const suspender = promise.then(\n (res) => {\n status = `success`;\n response = res;\n },\n (err) => {\n status = `error`;\n response = err;\n }\n );\n\n const read = (): T => {\n switch (status) {\n case `pending`:\n throw suspender;\n case `error`:\n throw response;\n default:\n return response;\n }\n };\n\n return { read };\n}\n","/* eslint-disable no-param-reassign */\nimport type { DependencyLifecycle } from \"../../types\";\nimport type { IKosDataModel } from \"../kosModel\";\nimport { kosParentAware } from \"./kos-parent\";\nimport { CompanionParentModel } from \"./propKeys\";\n\n/**\n * @kosService core.companion\n * @kosApiLevel 13\n */\nexport interface KosCompanionOptions {\n /**\n * Pattern mode:\n * - 'decorator': Proxy all parent properties transparently (default)\n * - 'composition': Only provide getCompanionParent() and the parentProperty getter\n */\n mode?: \"decorator\" | \"composition\";\n /** Properties to exclude from proxying (only applies in decorator mode). Default: [] */\n excludeProperties?: string[];\n /** Custom parent property name. Default: 'companionParent' */\n parentProperty?: string;\n /**\n * Lifecycle phase of the parent at which this companion is created. Defaults to INIT\n * (created during parent instantiation); LOAD creates it after the parent's load()\n * completes, READY after ready(), and so on.\n *\n * @kosApiLevel 15\n */\n lifecycle?: DependencyLifecycle;\n}\n\n/**\n * Base interface for all companion models.\n * Provides the getCompanionParent() method available in both decorator and composition modes.\n *\n * @kosService core.companion\n * @kosApiLevel 13\n */\nexport interface KosCompanionAware<\n TParent extends IKosDataModel = IKosDataModel\n> {\n /**\n * Gets the companion's parent model instance.\n * Available in both decorator and composition modes.\n * Provides access to the model this companion extends.\n *\n * @returns The parent model instance that this companion enhances\n */\n getCompanionParent(): TParent;\n}\n\n/**\n * Members injected into a companion in composition mode. Declare an interface with the\n * same name as the class that extends this type (TypeScript interface merging).\n *\n * @kosService core.companion\n */\nexport type KosCompanionComposition<\n TParent extends IKosDataModel = IKosDataModel\n> = KosCompanionAware<TParent>;\n\n/**\n * Members injected into a companion in decorator mode (the default). Declare an\n * interface with the same name as the class that extends this type (TypeScript\n * interface merging); to type the proxied parent members as well, also extend the\n * parent model's interface.\n *\n * @kosService core.companion\n */\nexport type KosCompanionDecorator<\n TParent extends IKosDataModel = IKosDataModel\n> = KosCompanionAware<TParent>;\n\n/**\n * Class decorator that makes a KOS model a companion of a parent model, extending it\n * with behavior that lives in a separate model.\n *\n * Both modes provide `getCompanionParent()` and a read-only `companionParent` (or\n * `parentProperty`) getter.\n * - **decorator** (default): the parent's properties and methods are also proxied onto\n * the companion, so it can stand in for the parent. Lifecycle methods, topic\n * handlers, `_`-prefixed members, `excludeProperties` and members the companion\n * defines itself are not proxied.\n * - **composition**: the parent is reachable only through those two accessors.\n *\n * The decorator also applies @kosParentAware.\n *\n * @param options Configuration options for the companion decorator\n * @returns A class decorator\n *\n * @example\n * ```typescript\n * interface ServiceCompanionModelImpl extends KosCompanionComposition<ServiceModel> {}\n *\n * @kosModel(\"service-companion\")\n * @kosCompanion({ mode: 'composition' })\n * class ServiceCompanionModelImpl implements IKosDataModel {\n * get serviceInfo() {\n * return `Service: ${this.getCompanionParent().serviceName}`;\n * }\n * }\n * ```\n *\n * @category KOS Model Decorator\n * @since 2.1.0\n * @kosService core.companion\n * @kosApiLevel 2\n */\nexport function kosCompanion(options?: KosCompanionOptions): ClassDecorator {\n return (target: any) => {\n const mode = options?.mode || \"decorator\";\n const parentProperty = options?.parentProperty || \"companionParent\";\n const excludeProperties = options?.excludeProperties || [];\n const lifecycle = options?.lifecycle;\n\n // Companions by definition have parent relationships - automatically apply kosParentAware\n kosParentAware()(target);\n\n // Add the companion configuration to the prototype\n // This will be processed by kosModel.ts during model instantiation\n target.prototype[CompanionParentModel] = {\n mode,\n parentProperty,\n excludeProperties,\n lifecycle,\n };\n\n return target;\n };\n}\n","/**\n * @internal\n */\nimport { KosContextManager } from \"../context/kos-context-manager\";\n\n/**\n * Method decorator that injects the current KOS execution context into a method call.\n *\n * @kosService core.context\n * @kosApiLevel 2\n */\nexport function kosContext(\n _target: any,\n _propertyKey: string,\n descriptor: PropertyDescriptor\n) {\n // store the original method\n const originalMethod = descriptor.value;\n\n // modify the descriptor value\n descriptor.value = function (...args: any[]) {\n // get the kos context\n const ctx = KosContextManager.getContext((this as any).id);\n // add the context as the last argument\n args.push(ctx);\n\n // apply the original method\n return originalMethod.apply(this, args);\n };\n}\n","import type { ClientResponse } from \"../../util/kos-service-request\";\nimport type { KosExecutionContext } from \"./kos-execution-context\";\nimport type { KosLoggerAware } from \"./kos-logger-aware\";\nimport type { HttpMethod, ServiceRequestExecutor } from \"./kos-service-request\";\n\n/**\n * Runs a method-driven service request: checks the injected context, awaits the\n * error-first tuple, logs a failure and treats an empty body as a failure, so the\n * caller handles only the success path.\n *\n * ```typescript\n * const data = await executeServiceRequest(this, $ctx, {\n * body: { id: cartridgeId },\n * });\n * if (!data) return;\n * ```\n *\n * Failures are logged against the method name the decorator puts on `$ctx.$name`.\n *\n * Use it only with a @kosServiceRequest that has no `lifecycle`. A lifecycle-driven\n * handler receives `(error, data)` with the request already performed and never gets\n * a context.\n *\n * @param host Model the request belongs to; supplies the logger.\n * @param $ctx Context the decorator injected as the method's last parameter.\n * @param params `pathParams` / `queryParams` / `body` / `requestOptions`.\n * @returns The response body, or `undefined` when the request could not run,\n * failed, or came back empty.\n *\n * @kosService core.service-request\n * @kosApiLevel 24\n */\nexport async function executeServiceRequest<\n Paths extends Record<string, any>,\n Path extends keyof Paths,\n Method extends HttpMethod = \"get\",\n Transformed = ClientResponse<Paths, Path, Method>\n>(\n host: KosLoggerAware,\n $ctx: KosExecutionContext<Paths, Path, Method, Transformed> | undefined,\n params?: Parameters<ServiceRequestExecutor<Paths, Path, Method>>[0]\n): Promise<NonNullable<Transformed> | undefined> {\n const name = $ctx?.$name ?? \"service request\";\n if (!$ctx?.$request) {\n // Almost always a decorator with a `lifecycle`, which gets no context; say so,\n // because the symptom is a method that silently does nothing.\n host.logger.error(\n `${name}: missing execution context — executeServiceRequest is for method-driven requests; ` +\n `a @kosServiceRequest with a lifecycle receives (error, data) instead and needs no helper`\n );\n return undefined;\n }\n\n const [error, data] = await $ctx.$request(params);\n if (error) {\n host.logger.error(`${name}: request failed`, error);\n return undefined;\n }\n if (data == null) {\n host.logger.error(`${name}: no data returned`);\n return undefined;\n }\n // The context's Transformed type is the raw response, or the transform's output.\n return data as NonNullable<Transformed>;\n}\n","/* eslint-disable no-param-reassign */\nimport type { MultipleFutureHandler } from \"../../../models/models/future/future-aware\";\nimport type { IFutureModel } from \"../../../models/models/future/future-types\";\nimport { MultipleFutureContainerSetup } from \"./propKeys\";\n\n/**\n * @kosService core.future-aware\n * @kosApiLevel 14\n */\nexport interface KosMultipleFutureAwareOptions {\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 * Members injected by @kosMultipleFutureAware in minimal mode. Minimal mode also\n * injects an `<alias>Future` getter per @kosFuture alias; declare the ones you read on\n * the merged interface.\n *\n * @example\n * ```typescript\n * interface MaintenanceModelImpl extends KosMultipleFutureAwareMinimal {\n * calibrationFuture?: IFutureModel;\n * }\n * ```\n *\n * @kosService core.future-aware\n * @kosApiLevel 14\n */\nexport interface KosMultipleFutureAwareMinimal {\n /**\n * Container that tracks the model's concurrent Future operations by alias.\n */\n futureHandler: MultipleFutureHandler;\n}\n\n/**\n * Utility types to generate future property names for multiple futures (for internal use)\n */\ntype FutureGetters<T extends string> = {\n readonly [K in T as `${K}Future`]?: IFutureModel;\n};\n\ntype ProgressGetters<T extends string> = {\n readonly [K in T as `${K}Progress`]: number;\n};\n\ntype StatusGetters<T extends string> = {\n readonly [K in T as `${K}Status`]: string;\n};\n\ntype IsRunningGetters<T extends string> = {\n readonly [K in T as `${K}IsRunning`]: boolean;\n};\n\ntype IsCancelledGetters<T extends string> = {\n readonly [K in T as `${K}IsCancelled`]: boolean;\n};\n\ntype CancelMethods<T extends string> = {\n readonly [K in T as `cancel${Capitalize<K>}`]: () => Promise<void>;\n};\n\n/**\n * @kosService core.future-aware\n */\nexport type MultipleFutureProperties<T extends string> = FutureGetters<T> &\n ProgressGetters<T> &\n StatusGetters<T> &\n IsRunningGetters<T> &\n IsCancelledGetters<T> &\n CancelMethods<T>;\n\n/**\n * Members injected by @kosMultipleFutureAware in full mode (the default), where `T` is\n * the union of @kosFuture aliases. Declare an interface with the same name as the\n * class that extends this type (TypeScript interface merging).\n *\n * @kosService core.future-aware\n */\nexport type KosMultipleFutureAwareFull<T extends string = string> =\n KosMultipleFutureAwareMinimal & MultipleFutureProperties<T>;\n\n/**\n * Class decorator that lets a KOS model track several concurrent Futures, one per\n * @kosFuture `alias`. For a single Future, use @kosFutureAware.\n *\n * The model gets a `futureHandler` container and an `<alias>Future` getter per alias.\n * Full mode also adds `<alias>Progress`, `<alias>Status`, `<alias>IsRunning`,\n * `<alias>IsCancelled` and `cancel<Alias>()`. An optional\n * `onFutureUpdate(future, alias)` method on the model is called as each Future\n * progresses.\n *\n * @param options Configuration options for the decorator\n * @returns A class decorator\n *\n * @example\n * ```typescript\n * interface IceAgitatorModelImpl extends KosMultipleFutureAwareFull<\"pour\" | \"agitate\"> {}\n *\n * @kosModel(\"ice-agitator-model\")\n * @kosMultipleFutureAware()\n * class IceAgitatorModelImpl implements IKosDataModel {\n * @kosFuture({ alias: \"pour\" })\n * async pourIce(): Promise<FutureResponse | undefined> {\n * return startPourService();\n * }\n *\n * @kosFuture({ alias: \"agitate\" })\n * async agitate(): Promise<FutureResponse | undefined> {\n * return startAgitateService();\n * }\n * }\n * // this.pourProgress, this.agitateIsRunning, this.cancelPour(), ...\n * ```\n *\n * @category KOS Model Decorator\n * @since 2.0.0\n * @kosService core.future-aware\n * @kosApiLevel 14\n */\nexport function kosMultipleFutureAware(\n options?: KosMultipleFutureAwareOptions\n): ClassDecorator {\n return (target: any) => {\n const mode = options?.mode || \"full\";\n const handlerProperty = options?.handlerProperty || \"futureHandler\";\n\n // Add the MultipleFutureContainerSetup configuration to the prototype\n // This will be processed by kosModel.ts during model instantiation\n target.prototype[MultipleFutureContainerSetup] = {\n mode,\n handlerProperty,\n };\n\n return target;\n };\n}\n","/**\n * @internal\n */\nimport { IKosDataModel } from \"../kosModel\";\nimport { LogConfig } from \"./propKeys\";\n\ninterface DecoratedKosModel<T extends IKosDataModel = IKosDataModel> {\n new (...args: any[]): T;\n}\n\ninterface LogConfigProps {\n group?: string;\n}\n/**\n * @kosService core.logging\n * @kosApiLevel 2\n */\nexport const kosLogger =\n <T extends IKosDataModel>({ group }: LogConfigProps = { group: \"\" }) =>\n (constructor: DecoratedKosModel<T>): any => {\n constructor[LogConfig] = constructor[LogConfig] || {};\n constructor[LogConfig] = { group };\n };\n","/* eslint-disable no-param-reassign */\nimport type { IKosDataModel } from \"../kosModel\";\nimport type { KosModelRegistrationFactory } from \"../registration/base-kos-model-registration\";\nimport type { KosCompanionAware } from \"./kos-companion\";\nimport { CompanionParentModel, MixinModels } from \"./propKeys\";\n\n/**\n * A mixin declared on a host, keyed by the property that holds it.\n *\n * @internal\n */\nexport interface KosMixinDefinition {\n registration: KosModelRegistrationFactory<any, any>;\n options?: unknown;\n}\n\n/**\n * The host interface a mixin requires.\n *\n * @kosService core.mixin\n * @kosApiLevel 25\n */\nexport type KosMixinHost<TMixin> = TMixin extends KosCompanionAware<infer THost>\n ? THost\n : IKosDataModel;\n\n/**\n * The options a host passes to its mixin. Any option can be a prop key, resolved from the\n * host's data when the mixin is created.\n *\n * @kosService core.mixin\n * @kosApiLevel 25\n */\nexport type KosMixinOptions<O> = O extends { data?: infer D }\n ? { [K in keyof D]: D[K] | string }\n : never;\n\n/**\n * Mixes a reusable behaviour into a model. The host gets its own instance of the mixin\n * in the decorated property, there from the moment the host is created and observable,\n * so the host's effects can react to it.\n *\n * The mixin calls back into the host through a `host` getter (`parentProperty: \"host\"`),\n * typed by the host interface it declares; a host that does not implement that\n * interface does not compile.\n *\n * @param mixin The mixin model's registration.\n * @param options The mixin's model options, received as `options.data`. Any option can\n * be a prop key (`createPropKey`), resolved from the host's data when the mixin is\n * created.\n *\n * @example\n * ```typescript\n * interface DirtyHost extends IKosDataModel { onDirtyChanged?(dirty: boolean): void }\n * interface DirtyTrackingImpl extends KosCompanionComposition<DirtyHost> {\n * readonly host: DirtyHost;\n * }\n *\n * @kosModel(\"dirty-tracking\")\n * @kosCompanion({ mode: \"composition\", parentProperty: \"host\" })\n * class DirtyTrackingImpl implements IKosDataModel { ... }\n *\n * @kosModel(\"recipe\")\n * class RecipeImpl implements IKosDataModel, DirtyHost {\n * @kosMixin(DirtyTracking, { fields: [\"name\"] })\n * dirty!: DirtyTrackingModel;\n * }\n * ```\n *\n * @category KOS Model Decorator\n * @kosService core.mixin\n * @kosApiLevel 25\n */\nexport function kosMixin<TMixin extends IKosDataModel, O extends object>(\n mixin: KosModelRegistrationFactory<TMixin, O>,\n options?: KosMixinOptions<O>\n) {\n return (target: KosMixinHost<TMixin>, propertyKey: string): void => {\n const companion = mixin.class.prototype[CompanionParentModel];\n if (companion?.mode !== \"composition\") {\n throw new Error(\n `Mixin ${mixin.type} must be a @kosCompanion({ mode: \"composition\" }) model`\n );\n }\n if (companion.lifecycle !== undefined) {\n throw new Error(\n `Mixin ${mixin.type} cannot set a companion lifecycle; mixins are created with their host`\n );\n }\n\n const host = target as any;\n host[MixinModels] = host[MixinModels] || {};\n const mixins: Record<string, KosMixinDefinition> = host[MixinModels];\n if (Object.values(mixins).some((m) => m.registration.type === mixin.type)) {\n throw new Error(\n `Mixin ${mixin.type} is already mixed into this model; a host holds one instance of each mixin`\n );\n }\n mixins[propertyKey] = { registration: mixin, options };\n };\n}\n","/**\n * @ignore\n * @deprecated\n */\nimport { warnDeprecated } from \"@kosdev-code/kos-api-levels\";\nimport { ReferenceConfig } from \"./propKeys\";\n\n/**\n * @kosService core.reference\n * @kosApiLevel 2\n */\ninterface ReferenceProps {\n modelType: string;\n}\n\n/**\n * @kosService core.reference\n * @kosApiLevel 2\n * @kosDeprecated {replacement: @kosDependency, removeAt: 3}\n */\nexport const kosReference =\n (props: ReferenceProps) =>\n (target: {} | any, name: PropertyKey): any => {\n warnDeprecated(\"@kosReference\", \"core.reference\", 1, \"@kosDependency\", 3);\n target[ReferenceConfig] = target[ReferenceConfig] || {};\n target[ReferenceConfig][name] = props;\n };\n","/**\n * @kosService core.fetch\n * @kosApiLevel 1\n */\nexport enum KosFetchMethods {\n GET = `GET`,\n PUT = `PUT`,\n POST = `POST`,\n DELETE = `DELETE`,\n}\n\ntype FetchMethodStrings = keyof typeof KosFetchMethods;\n\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport interface Headers {\n append(name: string, value: string): void;\n delete(name: string): void;\n get(name: string): string | null;\n has(name: string): boolean;\n set(name: string, value: string): void;\n forEach(\n callbackfn: (value: string, key: string, parent: Headers) => void,\n thisArg?: any\n ): void;\n}\n\ninterface Body {\n readonly body: ReadableStream<Uint8Array> | null;\n readonly bodyUsed: boolean;\n arrayBuffer(): Promise<ArrayBuffer>;\n blob(): Promise<Blob>;\n formData(): Promise<FormData>;\n json<T = any>(): Promise<T | null>;\n text(): Promise<string>;\n}\n\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport interface Response extends Body {\n readonly headers: Headers;\n readonly ok: boolean;\n readonly redirected: boolean;\n readonly status: number;\n readonly statusText: string;\n readonly type: ResponseType;\n readonly url: string;\n clone(): Response;\n}\n\n/**\n * Configuration for retrying failed service requests with exponential backoff.\n *\n * @kosService core.fetch\n *\n * Applies to requests made through the service-request client. Setting `retry`\n * to `true` on {@link KosFetchOptions} uses the defaults below; a partial\n * `RetryConfig` overrides only the fields it sets:\n * - `maxAttempts`: 3\n * - `baseDelayMs`: 350\n * - `backoffFactor`: 2\n * - `retryMutations`: false (POST, PUT, DELETE and PATCH are not retried)\n * - `retryOn`: unset, so every error response is retried\n *\n * Only error responses are retried; timeouts and aborts are returned at once.\n *\n * @example\n * ```typescript\n * retry: { maxAttempts: 5, retryOn: (response) => response.status === 503 }\n * ```\n *\n * @category Service Request\n * @kosApiLevel 22\n */\nexport interface RetryConfig {\n /** Maximum number of attempts (including the initial request). @default 3 */\n maxAttempts?: number;\n\n /** Base delay in milliseconds before the first retry. @default 350 */\n baseDelayMs?: number;\n\n /** Multiplier applied to the delay after each attempt. @default 2 */\n backoffFactor?: number;\n\n /**\n * Whether to retry mutating methods (POST, PUT, DELETE, PATCH).\n * Set to `true` only if the endpoint is idempotent.\n * @default false\n */\n retryMutations?: boolean;\n\n /**\n * Predicate called with the error {@link Response} to decide whether to\n * retry. Return `true` to retry, `false` to stop immediately. When omitted,\n * every error response is retried up to `maxAttempts`.\n */\n retryOn?: (response: Response) => boolean;\n}\n\n/**\n * Represents the configuration options for performing a Kos WebSocket fetch operation.\n *\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport interface KosFetchOptions {\n /**\n * The HTTP method for the request (e.g., 'GET', 'POST', 'PUT', 'DELETE', etc.).\n */\n method: FetchMethodStrings;\n\n /**\n * The request body - can be string, ArrayBuffer, Blob, or FormData.\n */\n body?: string | ArrayBuffer | Blob | FormData | Uint8Array;\n\n /**\n * Indicates whether the request should be ordered.\n */\n ordered?: boolean;\n\n /**\n * The destination address for the WebSocket request.\n */\n destinationAddress?: string;\n\n /**\n * @internal\n */\n signal?: AbortSignal;\n\n /**\n * The tracker associated with the request.\n */\n tracker?: string;\n\n /**\n * @internal\n */\n studio?: boolean;\n\n /**\n * @internal\n */\n fos?: boolean;\n\n /**\n * @internal\n */\n bridge?: boolean;\n\n /**\n * Timeout budget for the entire call, in milliseconds: waiting for the\n * transport to become ready plus the request itself.\n *\n * A request issued while the socket is down rejects with a\n * `TransportNotReadyError` if the transport does not become ready within the\n * budget. Otherwise the remaining budget applies to the request, which\n * rejects with a `TimeoutError` `DOMException` when it runs out. The two\n * errors are distinct so callers can tell a slow service from a down\n * transport.\n *\n * Defaults to the `KOS_WS_TIMEOUT` environment value, or 30000. Pass `0` or\n * `Infinity` to queue until the transport recovers; such a request does not\n * settle while the socket is down.\n */\n timeout?: number;\n\n /**\n * @kosApiLevel 5\n */\n headers?: Record<string, string>;\n\n /**\n * Enable streaming mode for large responses\n * @kosApiLevel 11\n */\n stream?: boolean;\n\n /**\n * Response type hint for binary data handling\n * @kosApiLevel 11\n */\n responseType?: \"text\" | \"json\" | \"arraybuffer\" | \"blob\";\n\n /**\n * Retry configuration for transient failures.\n *\n * - `true`: enable retry with all defaults\n * - `RetryConfig`: partial overrides (unspecified fields use defaults)\n * - omitted: no retry\n *\n * Mutating methods (POST, PUT, DELETE, PATCH) are retried only when\n * `retryMutations` is `true`.\n * @kosApiLevel 22\n */\n retry?: boolean | RetryConfig;\n}\n\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport interface KosFetchResponse {\n headers: Headers;\n status: string | number | boolean;\n ok: boolean;\n json: <\n T = Record<string | number | symbol, string | number | symbol>\n >() => Promise<T>;\n body: ReadableStream<Uint8Array> | null;\n}\n\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport interface KosFetchReqeust {\n path: string;\n requestId: string;\n method: FetchMethodStrings;\n destinationAddress?: string;\n ordered?: boolean;\n tracker?: string;\n bridge?: boolean;\n /**\n * @kosApiLevel 5\n */\n headers?: Record<string, string | number | boolean>;\n}\n\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport interface KosMessageRequest\n extends Omit<KosFetchReqeust, \"method\" | \"path\" | \"requestId\"> {\n requestType: string;\n requestId?: string;\n headers?: Record<string, string>;\n}\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport interface KosBroadcastRequest {\n topic: string;\n}\n\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport interface KosMessageOptions extends KosBroadcastRequest {\n destinationAddress?: string;\n responseId?: string;\n type?: string;\n}\n\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport interface KosHttpMessageOptions {\n destinationAddress: string;\n sourceAddress: string;\n responseId: string;\n status: number;\n type: string;\n contentType?: string;\n}\n\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport interface KosFetchResponseParams {\n path: string;\n responseId?: string;\n destinationAddress: string;\n status: string | number | boolean;\n}\n\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport interface KosFetchPostReqeust extends KosFetchReqeust {\n body?: string;\n}\n","/* eslint-disable no-param-reassign */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { DependencyModels, TroubleAwareSetup } from \"./propKeys\";\n\n/**\n * @kosService core.trouble-aware\n * @kosApiLevel 13\n */\nexport interface KosTroubleAwareOptions {\n /** Path property name to use for trouble resolution. Default: 'path' */\n pathProperty?: string;\n}\n\n/**\n * Class decorator that makes a KOS model TroubleAware: it gets reactive `troubles`\n * (the troubles whose path matches the model's path), `troublesByType` and\n * `troubleStatus` (an empty string by default). The trouble container is added as a\n * dependency automatically.\n *\n * The model must expose its device path on `path`, or on the property named by\n * `pathProperty`. Declare an interface with the same name as the class that extends\n * `TroubleAware` (TypeScript interface merging) so the members are typed.\n *\n * @param options Configuration options for the decorator\n * @returns A class decorator\n *\n * @example\n * ```typescript\n * interface HolderModelImpl extends TroubleAware {}\n *\n * @kosModel(\"holder-model\")\n * @kosTroubleAware()\n * class HolderModelImpl implements IKosDataModel {\n * path: string;\n *\n * constructor(modelId: string, options: HolderOptions) {\n * this.path = options.path;\n * }\n * }\n * ```\n *\n * @category KOS Model Decorator\n * @since 2.0.0\n * @kosService core.trouble-aware\n * @kosApiLevel 13\n */\nexport function kosTroubleAware(\n options?: KosTroubleAwareOptions\n): ClassDecorator {\n return (target: any) => {\n const pathProperty = options?.pathProperty || \"path\";\n\n // Add the TroubleAwareSetup configuration to the prototype\n // This will be processed by kosModel.ts during model instantiation\n target.prototype[TroubleAwareSetup] = {\n pathProperty,\n };\n\n // Add troubleContainer as a managed dependency\n target.prototype[DependencyModels] =\n target.prototype[DependencyModels] || {};\n target.prototype[DependencyModels][\"troubleContainer\"] = {\n modelType: \"trouble-container-model\",\n id: \"trouble-container-model\", // TroubleContainer is a singleton\n options: {},\n lazy: false, // Ensure it's created immediately\n };\n\n return target;\n };\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { KosContext } from \"../context\";\nimport { ExtensionManager } from \"../extension\";\n\n/**\n * @kosService core.extension\n * @kosApiLevel 2\n */\nexport interface ExtensionPointOptions {\n extension: string;\n}\n/**\n * @kosService core.extension\n * @kosApiLevel 2\n */\nexport interface InitializeContextExtensionPointOptions\n extends ExtensionPointOptions {\n context?: KosContext;\n}\n\n/**\n * @kosService core.extension\n * @kosApiLevel 2\n */\nexport interface ContextDataExtensionPoint<D extends object, T extends object>\n extends ExtensionPointOptions {\n data: D;\n contextData: T;\n}\n/**\n * Executes an extension point and adds the value to the specified context\n * @param options The options for the extension point\n * @param options.context The KOS model context to add the value to. If not specified, the value will not be added to any context.\n * @param options.extension The extension point to execute\n *\n * @returns The value returned from the extension point\n * */\n/**\n * @kosService core.extension\n * @kosApiLevel 2\n */\nexport const executeLoaderExtension = async ({\n context,\n extension,\n}: InitializeContextExtensionPointOptions) => {\n const contextData = await ExtensionManager.loader.executeLoader(\n extension,\n {}\n );\n\n context?.set(extension, contextData);\n\n return contextData;\n};\n\n/**\n * Executes a registered data transformation extension point. This extension point is used to transform data from the backend into a format that is\n * usable by the application.\n *\n * @param options The options for the extension point\n * @param options.contextData The context data to pass to the extension point\n * @param options.data The data to transform\n * @param options.extension The extension point to execute\n * @returns The transformed data\n * */\n/**\n * @kosService core.extension\n * @kosApiLevel 2\n */\nexport const executeDataMapperExtension = async <\n D extends object = any,\n R extends object = any,\n T extends object = any\n>({\n extension,\n contextData,\n data,\n}: ContextDataExtensionPoint<D, T>) => {\n const transformed = await ExtensionManager.dataMapper.executeMapper<D, R>(\n extension,\n data,\n contextData\n );\n\n return transformed;\n};\n\n/**\n * Executes a registered data transformation extension point. This extension point is used to map a single property value and\n * is typically used to map a property value from the backend into a format that is usable by the application.\n *\n *\n * @param options The options for the extension point\n * @param options.contextData The context data to pass to the extension point\n * @param options.data The data to transform\n * @param options.extension The extension point to execute\n * @returns The transformed data\n * */\n/**\n * @kosService core.extension\n * @kosApiLevel 2\n */\nexport const executePropertyMapperExtension = async <\n D extends object = any,\n T extends object = any\n>({\n extension,\n contextData,\n data,\n}: ContextDataExtensionPoint<D, T>) => {\n const value = await ExtensionManager.propertyMapper.executeMapper(\n extension,\n data,\n contextData\n );\n\n return value;\n};\n","/**\n * @kosService core.extension\n * @kosApiLevel 2\n */\nexport const PLUGIN_EXTENSION_NAME = \"Extensions\";\n\n/**\n * Represents the type for the extensions.\n */\n/**\n * @kosService core.extension\n */\nexport interface PluginExtensionsType {\n [k: string]: {\n [k: string]: {\n component?: string;\n remote?: string;\n };\n };\n}\n/**\n * @kosService core.extension\n * @kosApiLevel 2\n */\nexport class PluginExtensionManager {\n private extensions: PluginExtensionsType;\n\n constructor() {\n this.extensions = {};\n }\n register(extensionPoint: string, name: string, component: string) {\n this.extensions[extensionPoint] = this.extensions[extensionPoint] || {};\n this.extensions[extensionPoint][name] = { component };\n }\n\n get(extension: string, id: string) {\n if (!this.extensions[extension]) {\n throw new Error(`Extension point ${extension} not found`);\n }\n return this.extensions[extension][id];\n }\n\n get allExtensions() {\n return this.extensions;\n }\n}\n","/**\n * Debounces a function so it runs once the timeout has passed since the last call.\n *\n * @param context - The context (this value) to be used when calling the debounced function.\n * @param func - The function to debounce.\n * @param timeout - The duration (in milliseconds) to wait after the last invocation before calling the function.\n * Defaults to 300 milliseconds.\n * @returns A debounced version of the provided function.\n *\n * @kosService core.utils\n * @kosApiLevel 2\n */\nfunction debounce(context: any, func: Function, timeout = 300) {\n let timer: ReturnType<typeof setTimeout>;\n\n /**\n * Returns a debounced version of the provided function.\n *\n * @param args - The arguments to pass to the debounced function.\n */\n return (...args: any) => {\n /**\n * Clears the previous timer.\n */\n clearTimeout(timer);\n\n /**\n * Sets a new timer to call the provided function after the specified timeout.\n */\n timer = setTimeout(() => {\n func.apply(context, args);\n }, timeout);\n };\n}\n\nexport default debounce;\n","/**\n * @deprecated\n * @internal\n */\nimport { warnDeprecated } from \"@kosdev-code/kos-api-levels\";\nimport { action } from \"mobx\";\nimport debounce from \"../../util/debounce\";\nimport { SubscriptionHandlers } from \"./propKeys\";\n\n/**\n * @kosService core.subscribe\n * @kosApiLevel 2\n */\nexport interface IKosSubscriptionHandlerParams<T, M> {\n topic: string;\n condition?: (payload: T, model: M) => boolean;\n handler: Function;\n websocket?: boolean;\n skipParse?: boolean;\n}\n\n/**\n * @kosService core.subscribe\n * @kosApiLevel 2\n * @kosDeprecated {replacement: @kosTopicHandler, removeAt: 3}\n */\nexport const kosSubscribe =\n <T = unknown, M = unknown>({\n topic,\n handler,\n websocket = false,\n condition = () => true,\n }: IKosSubscriptionHandlerParams<T, M>) =>\n (target: T) => {\n warnDeprecated(\"@kosSubscribe\", \"core.subscribe\", 1, \"@kosTopicHandler\", 3);\n target[SubscriptionHandlers] = target[SubscriptionHandlers] || {};\n if (Array.isArray(topic)) {\n topic.forEach((t) => {\n target[SubscriptionHandlers][t] = {\n websocket,\n handler,\n condition,\n };\n });\n } else {\n target[SubscriptionHandlers][topic] = {\n websocket,\n handler: debounce(target, action(handler), 200),\n condition,\n };\n }\n };\n","/* eslint-disable no-param-reassign */\nimport { autorun, makeAutoObservable, reaction, runInAction } from \"mobx\";\nimport { DependencyLifecycle } from \"../../types\";\nimport type { KosContextLogger } from \"../kosModel\";\nimport {\n initializeStateMachine,\n injectStateMachineSupport,\n} from \"./fsm-injection-utils\";\nimport {\n KosViewModelSymbol,\n ModelEffects,\n StateMachineSetup,\n ViewModelConfig,\n} from \"./propKeys\";\n\n/**\n * Configuration options for the @kosViewModel decorator.\n *\n * @kosService core.view-model\n * @kosApiLevel 20\n */\nexport interface KosViewModelOptions {\n /**\n * Optional type identifier for this ViewModel.\n * Used for logging, debugging, and optional DevTools registration.\n * If not provided, defaults to the class name.\n */\n typeId?: string;\n\n /**\n * When true, registers this ViewModel with KOS DevTools for inspection.\n * Default: false (ViewModels are not tracked by default)\n */\n devToolsEnabled?: boolean;\n}\n\n/**\n * Interface for ViewModels that support cleanup. `useViewModel` calls `dispose()` when\n * the ViewModel is replaced or the component unmounts.\n *\n * @kosService core.view-model\n * @kosApiLevel 20\n */\nexport interface IKosViewModelDisposable {\n dispose(): void | Promise<void>;\n}\n\n/**\n * Interface for ViewModels that require async initialization, such as waiting for the\n * models they wrap to be ready. `useViewModel` calls `ready()` after construction and\n * reports its progress through the `ready` and `error` fields of its result.\n *\n * @kosService core.view-model\n * @kosApiLevel 20\n */\nexport interface IKosViewModelReady {\n ready(): Promise<void>;\n}\n\n/**\n * Type guard to check if an object implements IKosViewModelReady.\n */\nexport function hasReadyHook(obj: unknown): obj is IKosViewModelReady {\n return (\n obj !== null &&\n typeof obj === \"object\" &&\n \"ready\" in obj &&\n typeof (obj as IKosViewModelReady).ready === \"function\"\n );\n}\n\n/**\n * Members injected by @kosLoggerAware into a ViewModel. Declare an interface with the\n * same name as the class that extends this type (TypeScript interface merging).\n *\n * @kosService core.view-model\n * @kosApiLevel 20\n */\nexport interface KosViewModelLoggerAware {\n logger: KosContextLogger;\n}\n\n/**\n * Type guard to check if an object implements IKosViewModelDisposable.\n */\nexport function isDisposable(obj: unknown): obj is IKosViewModelDisposable {\n return (\n obj !== null &&\n typeof obj === \"object\" &&\n \"dispose\" in obj &&\n typeof (obj as IKosViewModelDisposable).dispose === \"function\"\n );\n}\n\n// Counter for generating unique instance IDs\nlet viewModelCounter = 0;\n\n// Symbol for storing effect disposers on ViewModel instances\nconst ViewModelEffectDisposers = Symbol(\"ViewModelEffectDisposers\");\n\n/**\n * Checks if a ViewModel has model effects defined.\n */\nfunction hasViewModelEffects(instance: Record<string, unknown>): boolean {\n const effects = instance[ModelEffects as unknown as string];\n return !!effects && Object.keys(effects as object).length > 0;\n}\n\n/**\n * Injects model effect support into a ViewModel instance.\n * Effects are set up immediately and disposers are stored for cleanup.\n */\nfunction injectViewModelEffects(\n instance: Record<string, unknown>,\n typeId: string\n): void {\n if (!hasViewModelEffects(instance)) return;\n\n const modelEffects = instance[ModelEffects as unknown as string] as Record<\n string,\n {\n value: (...args: unknown[]) => void;\n dependencies?: (model: unknown) => unknown[];\n options?: { fireImmediately?: boolean };\n }\n >;\n\n const disposers: VoidFunction[] = [];\n\n for (const effectName of Object.keys(modelEffects)) {\n const { value, dependencies, options } = modelEffects[effectName];\n const handler = value.bind(instance);\n\n const effectHandler = () => {\n runInAction(() => handler());\n };\n\n const disposer = dependencies\n ? reaction(() => dependencies(instance), effectHandler, {\n fireImmediately: !!options?.fireImmediately,\n })\n : autorun(effectHandler);\n\n disposers.push(disposer);\n }\n\n // Store disposers for cleanup\n // configurable: true so makeAutoObservable can redefine it\n Object.defineProperty(instance, ViewModelEffectDisposers, {\n value: disposers,\n writable: false,\n enumerable: false,\n configurable: true,\n });\n\n // Cast to any for dynamic property access\n const inst = instance as unknown as Record<string, unknown>;\n const originalDispose = inst[\"dispose\"] as\n | ((...args: unknown[]) => void | Promise<void>)\n | undefined;\n\n // Create effect disposal function\n const disposeEffects = () => {\n for (const dispose of disposers) {\n try {\n dispose();\n } catch (e) {\n console.warn(\n `[kosViewModel] Failed to dispose effect for ${typeId}:`,\n e\n );\n }\n }\n };\n\n // If the instance already has a dispose method, wrap it to also dispose effects\n if (typeof originalDispose === \"function\") {\n inst[\"dispose\"] = function (this: unknown) {\n disposeEffects();\n return originalDispose.call(this);\n };\n } else {\n // Add a dispose method that cleans up effects\n inst[\"dispose\"] = disposeEffects;\n }\n}\n\n/**\n * Injects state machine support into a ViewModel instance and initializes it.\n * ViewModels have no lifecycle phases, so the FSM initializes at construction:\n * the state property holds `initial`, `isFsmInitialized` is true, and the\n * entry handler for `initial` runs once.\n * Logs a warning if initializeAt was given explicitly with a value other than\n * INIT, since it has no effect on a ViewModel.\n */\nfunction injectViewModelStateMachine(\n instance: Record<string, unknown>,\n typeId: string\n): void {\n const fsmSetup = instance[StateMachineSetup as unknown as string] as\n | {\n config: { initializeAt?: DependencyLifecycle };\n initializeAtExplicit?: boolean;\n }\n | undefined;\n if (!fsmSetup) return;\n\n const { config, initializeAtExplicit } = fsmSetup;\n\n if (\n initializeAtExplicit &&\n config.initializeAt !== DependencyLifecycle.INIT\n ) {\n console.warn(\n `[kosViewModel] ViewModel \"${typeId}\" has @kosStateMachine with ` +\n `initializeAt: ${config.initializeAt}. ViewModels do not have lifecycle phases, ` +\n `so the FSM will initialize immediately. Consider removing initializeAt or using ` +\n `@kosModel if lifecycle-aware FSM initialization is required.`\n );\n }\n\n injectStateMachineSupport(instance);\n initializeStateMachine(instance, config.initializeAt as string);\n}\n\n/**\n * Safely wraps makeAutoObservable with error handling.\n */\nfunction makeSafeObservable<T extends object>(instance: T): T {\n try {\n return makeAutoObservable(instance);\n } catch (e) {\n console.error(\"[kosViewModel] Failed to make observable:\", e);\n return instance;\n }\n}\n\n/**\n * Proxy handler for ViewModel construction.\n * Intercepts new() calls to inject observability.\n */\nconst viewModelConstructorProxy: ProxyHandler<any> = {\n construct(TargetClass, args) {\n const config = (TargetClass.prototype[ViewModelConfig] ||\n {}) as KosViewModelOptions;\n const typeId = config.typeId || TargetClass.name;\n const instanceId = `${typeId}-${++viewModelCounter}`;\n\n // Create the instance\n const instance = new TargetClass(...args);\n\n // Inject state machine support if @kosStateMachine is stacked\n injectViewModelStateMachine(instance, typeId);\n\n // Inject model effect support if @kosModelEffect is used\n injectViewModelEffects(instance, typeId);\n\n // Store metadata as non-enumerable properties for debugging\n // configurable: true so makeAutoObservable can redefine it\n Object.defineProperty(instance, \"__viewModelTypeId\", {\n value: typeId,\n writable: false,\n enumerable: false,\n configurable: true,\n });\n\n Object.defineProperty(instance, \"__viewModelInstanceId\", {\n value: instanceId,\n writable: false,\n enumerable: false,\n configurable: true,\n });\n\n // Make the instance observable\n const observableInstance = makeSafeObservable(instance);\n\n // Optional DevTools registration\n if (\n config.devToolsEnabled &&\n (globalThis as any).__KOS_DEVTOOLS__?.registerViewModel\n ) {\n (globalThis as any).__KOS_DEVTOOLS__.registerViewModel(\n instanceId,\n observableInstance\n );\n }\n\n return observableInstance;\n },\n};\n\n/**\n * Class decorator for a ViewModel: a plain class made into a reactive model without the\n * KOS model lifecycle.\n *\n * Use it for state derived from one or more KOS models for a component. Dependencies\n * are passed to the constructor, instances are created with `new` (usually inside\n * `useViewModel`), and there are no lifecycle phases or dependency resolution. A\n * ViewModel may also use @kosLoggerAware, @kosModelEffect and @kosStateMachine; its\n * state machine initializes at construction.\n *\n * @param options Configuration options for the ViewModel\n * @returns A class decorator\n *\n * @example\n * ```typescript\n * @kosViewModel({ typeId: 'order-summary' })\n * export class OrderSummaryViewModel {\n * constructor(private readonly order: IOrderModel) {}\n *\n * get total(): number {\n * return this.order.items.reduce((sum, i) => sum + i.price, 0);\n * }\n * }\n *\n * const OrderSummary = kosComponent(({ order }: Props) => {\n * const { viewModel } = useViewModel(() => new OrderSummaryViewModel(order), [order]);\n * return <p>Total: {viewModel.total}</p>;\n * });\n * ```\n *\n * @category KOS ViewModel Decorator\n * @kosService core.view-model\n * @kosApiLevel 20\n */\nexport function kosViewModel(options?: KosViewModelOptions): ClassDecorator {\n return (target: any) => {\n const config = options || {};\n const typeId = config.typeId || target.name;\n\n // Store configuration on prototype for the proxy to access\n // Use same structure as KosModelSymbol for @kosLoggerAware compatibility\n target.prototype[KosViewModelSymbol] = { type: typeId };\n target.prototype[ViewModelConfig] = config;\n\n // Preserve class name for debugging\n const ProxiedClass = new Proxy(target, viewModelConstructorProxy);\n Object.defineProperty(ProxiedClass, \"name\", { value: target.name });\n\n return ProxiedClass;\n };\n}\n","/**\n * (C) Copyright 2025, TCCC, All rights reserved.\n */\n\nimport type { IKosDataModel, IKosModel } from \"../core/kosModel\";\nimport { KosModelVisitor } from \"./kos-model-visitor\";\n\n/**\n * Visitor that finds the ids of a target model's ancestors in any KOS model\n * hierarchy that implements the visitor pattern.\n *\n * It walks the tree depth-first and tracks the current path, so when the\n * target is found the accumulated path is the ancestor list. The traversal\n * visits every model until the target is found, which suits hierarchies of\n * up to a few hundred models.\n *\n * @example\n * ```typescript\n * const visitor = new AncestorPathVisitor(\"target-item-id\");\n * visitor.start(rootContainerModel);\n * const ancestors = visitor.getAncestorPath(); // [\"root\", \"parent\"]\n * ```\n *\n * @category Core\n * @kosService core.utils\n * @kosApiLevel 20\n */\nexport class AncestorPathVisitor extends KosModelVisitor {\n private targetId: string;\n private currentPath: string[] = [];\n private foundPath: string[] | null = null;\n\n constructor(targetId: string) {\n super();\n this.targetId = targetId;\n }\n\n /**\n * Wraps the visit with path tracking: push the model, check whether it is\n * the target, visit its children, then pop it again if the target was not\n * found in this subtree.\n *\n * The base class logic is inlined rather than calling super.visit() so the\n * push and pop happen at the right points relative to cycle detection and\n * child traversal.\n */\n override visit(model: IKosModel): void {\n // Cycle detection from base class\n if (this.visitedModels.has(model.modelId)) {\n return;\n }\n\n // Push to path BEFORE processing\n this.currentPath.push(model.modelId);\n\n // Mark as visited\n this.visitedModels.add(model.modelId);\n\n // Check if this is the target\n const stopVisiting = !!this.visitModel(model.modelData);\n\n if (!stopVisiting) {\n // Visit children (depth-first)\n model.getChildren?.().forEach((child) => {\n // Early exit if target was found in a sibling subtree\n if (this.foundPath) {\n return;\n }\n child.accept?.(this);\n });\n }\n\n // Backtrack: pop from path if target not found in this subtree\n if (!this.foundPath) {\n this.currentPath.pop();\n }\n }\n\n /**\n * Called for each model during traversal.\n * Returns true to stop traversal when target is found.\n */\n visitModel<T extends IKosDataModel>(model: T): boolean | void {\n // Check if this is the target\n if (model.id === this.targetId) {\n // Save ancestor path (everything except the target itself)\n this.foundPath = this.currentPath.slice(0, -1);\n return true; // Stop traversal\n }\n\n // Continue depth-first traversal\n return false;\n }\n\n /**\n * Get the ancestor path (IDs from root to parent, not including target).\n * Returns empty array if target not found or target is at root level.\n */\n getAncestorPath(): string[] {\n return this.foundPath ?? [];\n }\n\n /**\n * Check if target was found during traversal.\n */\n wasFound(): boolean {\n return this.foundPath !== null;\n }\n}\n","/**\n * @kosService core.kos-model\n * @kosApiLevel 2\n */\nexport function applyMixins(derivedCtor: any, baseCtors: any[]) {\n baseCtors.forEach((baseCtor) => {\n Object.getOwnPropertyNames(baseCtor.prototype).forEach((name) => {\n const descriptor = Object.getOwnPropertyDescriptor(\n baseCtor.prototype,\n name\n );\n Object.defineProperty(\n derivedCtor.prototype,\n name,\n <PropertyDescriptor & ThisType<any>>descriptor\n );\n });\n });\n}\n","/**\n * @kosService core.utils\n * @kosApiLevel 5\n */\nexport function arraysEqual(_a?: any[], _b?: any[]): boolean {\n const a = _a ?? [];\n const b = _b ?? [];\n if (a.length !== b.length) return false;\n return a.every((val, index) => val === b[index]);\n}\n","const formatter = new Intl.RelativeTimeFormat(undefined, {\n numeric: \"auto\",\n});\n\nconst DIVISIONS: { amount: number; name: Intl.RelativeTimeFormatUnit }[] = [\n { amount: 60, name: \"seconds\" },\n { amount: 60, name: \"minutes\" },\n { amount: 24, name: \"hours\" },\n { amount: 7, name: \"days\" },\n { amount: 4.34524, name: \"weeks\" },\n { amount: 12, name: \"months\" },\n { amount: Number.POSITIVE_INFINITY, name: \"years\" },\n];\n\n/**\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport function formatDateSince(date: Date) {\n let duration = (date.getTime() - Date.now()) / 1000;\n\n for (let i = 0; i <= DIVISIONS.length; i++) {\n const division = DIVISIONS[i];\n if (Math.abs(duration) < division.amount) {\n return formatter.format(Math.round(duration), division.name);\n }\n duration /= division.amount;\n }\n return formatter.format(Math.round(duration), \"years\");\n}\n\n/**\n * @kosService core.utils\n * @kosApiLevel 3\n */\nexport const isLeapYear = (year: number): boolean =>\n (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;\n\n/**\n * @kosService core.utils\n * @kosApiLevel 3\n */\nexport const getDaysInMonth = (year: number, month: number): number =>\n [31, isLeapYear(year) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][\n month\n ];\n\n/**\n * @kosService core.utils\n * @kosApiLevel 3\n */\nexport const addMonthsToDate = (date: Date, value: number) => {\n const d = new Date(date),\n n = date.getDate();\n d.setDate(1);\n d.setMonth(d.getMonth() + value);\n d.setDate(Math.min(n, getDaysInMonth(d.getFullYear(), d.getMonth())));\n return d;\n};\n\n/**\n * @kosService core.utils\n * @kosApiLevel 3\n */\nexport const addDaysToDate = (date: Date, value: number) => {\n const d = new Date(date);\n d.setDate(d.getDate() + value);\n return d;\n};\n\nconst DEFAULT_LOCALE = \"en-US\";\n\ninterface FormatDateOptions {\n dateStyle?: \"short\" | \"medium\" | \"long\" | \"full\";\n locales?: string | string[];\n}\n\ninterface FormatTimeOptions {\n timeStyle?: \"short\" | \"medium\" | \"long\" | \"full\";\n locales?: string | string[];\n}\n\ninterface FormatDateTimeOptions extends FormatDateOptions, FormatTimeOptions {}\n\ninterface FormatOptions {\n year?: \"numeric\" | \"2-digit\";\n month?: \"short\" | \"long\" | \"numeric\" | \"2-digit\" | \"narrow\";\n day?: \"numeric\" | \"2-digit\";\n weekday?: \"short\" | \"long\" | \"narrow\";\n hour?: \"numeric\" | \"2-digit\";\n minute?: \"numeric\" | \"2-digit\";\n second?: \"numeric\" | \"2-digit\";\n hour12?: boolean;\n timeZoneName?:\n | \"short\"\n | \"long\"\n | \"shortOffset\"\n | \"longOffset\"\n | \"shortGeneric\"\n | \"longGeneric\";\n}\n\nconst dateStyleMap: Record<\n NonNullable<FormatDateTimeOptions[\"dateStyle\"]>,\n Partial<FormatOptions>\n> = {\n short: { year: \"numeric\", month: \"2-digit\", day: \"2-digit\" },\n medium: { year: \"numeric\", month: \"short\", day: \"2-digit\" },\n long: { year: \"numeric\", month: \"long\", day: \"numeric\" },\n full: {\n year: \"numeric\",\n month: \"long\",\n day: \"numeric\",\n weekday: \"long\",\n },\n};\n\nconst timeStyleMap: Record<\n NonNullable<FormatDateTimeOptions[\"timeStyle\"]>,\n Partial<FormatOptions>\n> = {\n short: { hour: \"2-digit\", minute: \"2-digit\", hour12: true },\n medium: {\n hour: \"2-digit\",\n minute: \"2-digit\",\n second: \"2-digit\",\n hour12: true,\n },\n long: {\n hour: \"2-digit\",\n minute: \"2-digit\",\n second: \"2-digit\",\n hour12: true,\n timeZoneName: \"short\",\n },\n full: {\n hour: \"2-digit\",\n minute: \"2-digit\",\n hour12: true,\n timeZoneName: \"long\",\n },\n};\n\n/**\n * Formats a date with `Intl.DateTimeFormat` according to `dateStyle` and locale.\n *\n * `\"short\"` uses a numeric year with two-digit month and day in the locale's\n * order (`12/31/2025` in en-US); the other styles use the built-in `Intl` styles.\n *\n * @param date - The date object or timestamp to format.\n * @param options - Options to customize formatting.\n * @param options.dateStyle - One of `\"short\"`, `\"medium\"`, `\"long\"`, or `\"full\"`.\n * @param options.locales - Optional locale string or array of locale strings.\n * @returns A formatted date string.\n *\n * @kosService core.utils\n * @kosApiLevel 3\n */\n\nexport const formatDate = (\n date?: Date | number,\n { dateStyle = \"short\", locales = DEFAULT_LOCALE }: FormatDateOptions = {\n dateStyle: \"short\",\n locales: DEFAULT_LOCALE,\n }\n) => {\n const options = dateStyle === \"short\" ? dateStyleMap.short : { dateStyle }; // Let Intl handle medium/long/full\n return new Intl.DateTimeFormat(locales, options).format(date);\n};\n\n/**\n * Formats a time with `Intl.DateTimeFormat` according to `timeStyle` and\n * locale. All styles use a 12-hour clock; `\"medium\"` and `\"long\"` add seconds,\n * and `\"long\"` and `\"full\"` add the time zone name.\n *\n * @param date - The date object or timestamp to extract the time from.\n * @param options - Options to customize time formatting.\n * @param options.timeStyle - One of `\"short\"`, `\"medium\"`, `\"long\"`, or `\"full\"`.\n * @param options.locales - Optional locale string or locale array.\n * @returns A formatted time string.\n *\n * @kosService core.utils\n * @kosApiLevel 3\n */\n\nexport const formatTime = (\n date?: Date | number,\n { locales = DEFAULT_LOCALE, timeStyle = \"short\" }: FormatTimeOptions = {\n locales: DEFAULT_LOCALE,\n timeStyle: \"short\",\n }\n) => {\n const options = timeStyleMap[timeStyle];\n return new Intl.DateTimeFormat(locales, options).format(date);\n};\n\n/**\n * Formats a date and time in one string with `Intl.DateTimeFormat`. It takes\n * the same `dateStyle` and `timeStyle` names as {@link formatDate} and\n * {@link formatTime}; both default to `\"short\"` (`12/31/2025, 11:59 PM` in en-US).\n *\n * @param date - The `Date` object or timestamp to format.\n * @param options - Formatting options.\n * @param options.dateStyle - Custom date format: `\"short\"`, `\"medium\"`, `\"long\"`, or `\"full\"`.\n * @param options.timeStyle - Custom time format: `\"short\"`, `\"medium\"`, `\"long\"`, or `\"full\"`.\n * @param options.locales - Optional locale string or locale array.\n * @returns A string representing the formatted date and/or time.\n *\n * @kosService core.utils\n * @kosApiLevel 3\n */\n\nexport const formatDateTime = (\n date?: Date | number,\n {\n dateStyle = \"short\",\n locales = DEFAULT_LOCALE,\n timeStyle = \"short\",\n }: FormatDateTimeOptions = {\n dateStyle: \"short\",\n locales: DEFAULT_LOCALE,\n timeStyle: \"short\",\n }\n) => {\n const options: FormatOptions = {\n ...(dateStyle && dateStyleMap[dateStyle]),\n ...(timeStyle && timeStyleMap[timeStyle]),\n };\n return new Intl.DateTimeFormat(locales, options).format(date);\n};\n","/**\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport const hslToHex = (h: number, s: number, l: number) => {\n l /= 100;\n const a = (s * Math.min(l, 1 - l)) / 100;\n const f = (n) => {\n const k = (n + h / 30) % 12;\n const color = l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);\n return Math.round(255 * color)\n .toString(16)\n .padStart(2, \"0\"); // convert to Hex and prefix \"0\" if needed\n };\n return `#${f(0)}${f(8)}${f(4)}`;\n};\n\n/**\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport const hslStringToHex = (hsl: string) => {\n const reg = new RegExp(\"hsl\\\\((\\\\d+),\\\\s+(\\\\d+)\\\\%,\\\\s+(\\\\d+)\\\\%\\\\)\");\n const match = reg.exec(hsl);\n if (!match) {\n throw Error(\"Invalid HSL string\");\n }\n return hslToHex(parseInt(match[1]), parseInt(match[2]), parseInt(match[3]));\n};\n\n/**\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport const resolveVariable = (element: Element, variable: string) =>\n getComputedStyle(element).getPropertyValue(variable);\n/**\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport const variableToHex = (element: Element, variable: string) =>\n hslStringToHex(resolveVariable(element, variable));\n","/**\n * @kosService core.middleware\n */\nexport type Middleware<\n D extends object = Record<string, ScalarValue>,\n R extends object = Record<string, ScalarValue>\n> = (context: Context<D, R>, next: () => Promise<void>) => Promise<void>;\n\n/**\n * @kosService core.middleware\n * @kosApiLevel 2\n */\nexport interface Context<\n D extends object = Record<string, ScalarValue>,\n R extends object = Record<string, ScalarValue>\n> {\n data: D;\n result: Partial<R>;\n}\n\ntype ScalarValue = string | number | boolean | null | undefined;\n/**\n * @kosService core.middleware\n * @kosApiLevel 2\n */\nexport class MiddlewareChain<\n D extends object = Record<string, ScalarValue>,\n R extends object = Record<string, ScalarValue>,\n T extends Context<D, R> = Context<D, R>\n> {\n private middlewares: Middleware<D, R>[] = [];\n\n use(middleware: Middleware<D, R>): void {\n this.middlewares.push(middleware);\n }\n\n async execute(context: T): Promise<void> {\n let index = 0;\n\n const next = async (): Promise<void> => {\n index++;\n if (index < this.middlewares.length) {\n await this.middlewares[index](context, next);\n }\n };\n\n await this.middlewares[index](context, next);\n }\n}\n\n/**\n * @kosService core.middleware\n * @kosApiLevel 2\n */\nexport const processMiddleware = async <\n D extends object = Record<string, ScalarValue>,\n R extends object = Record<string, ScalarValue>\n>(\n data: D,\n middleware: Middleware<D, R>[]\n) => {\n const chain = new MiddlewareChain<D, R>();\n middleware.forEach((m) => chain.use(m));\n\n const context: Context<D, R> = { data, result: {} as R };\n await chain.execute(context);\n return context.result as R;\n};\n","import { KosCore } from \"../core/kosCore\";\nimport type { KosCompanionModelType } from \"../core/types/registration\";\nimport type { BaseKosModelRegistrationBean } from \"../types/model\";\n\n/**\n * @kosService core.kos-model\n * @kosApiLevel 2\n */\nexport const updateModelRegistration = <\n T extends BaseKosModelRegistrationBean<any, any>\n>(\n modelRegistration: T\n): void => {\n KosCore.getInstance().modelManager.registerModel(modelRegistration);\n};\n\n/**\n * @kosService core.kos-model\n * @kosApiLevel 2\n */\nexport const updateCompanionModelRegistration = (\n typeId: string,\n companionRegistration: KosCompanionModelType<any>\n): void => {\n KosCore.getInstance().modelManager.registerCompanionModel(\n typeId,\n companionRegistration\n );\n};\n","import { KosCore } from \"../core/kosCore\";\nimport { sendKosMessageResponse } from \"./kos-message-utils\";\n\nconst TOPIC = \"/kos/ui/internal/heartbeat/\";\n\ninterface HeartbeatOptions {\n // An ID to identify the pairing between the two clients.\n relationshipId: string;\n // The websocket client ID that the active one should pair with.\n destinationAddress: string;\n // A function called if the pairing is aborted.\n onAbort?: () => void;\n // By default the utlity will emit a beat every 2000 miliseconds. Use this\n // to change that.\n beatTime?: number;\n // By default the utlity will wait 3 seconds without a beat from the paired client\n // before aborting. Use this to change that.\n waitTime?: number;\n}\n\n/**\n * Sets up a connection between two clients such that\n * if one is closed, the other is notified of its closure.\n *\n * @category Utility\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport const pairedClientHeartbeat = ({\n relationshipId,\n destinationAddress,\n onAbort,\n waitTime,\n beatTime,\n}: HeartbeatOptions) => {\n const transport = KosCore.getInstance().transport;\n\n // Create an abort controller so we can cancel any requests that depend\n // on both clients being open (e.g in the case where one client is waiting for a response from another)\n const controller = new AbortController();\n\n let lastHeartBeat: number = performance.now();\n\n // Subscribe to the client heartbeat topic using the intent reponse id.\n const unsubscribe = transport.subscribeTopic({\n topic: `${TOPIC}${relationshipId}`,\n callback: () => {\n lastHeartBeat = performance.now();\n },\n });\n\n const _waitTime = waitTime ?? 3000;\n\n // If the last heartbeat was more than 5 seconds ago, abort the operation.\n const waitInterval = window.setInterval(() => {\n let timeDiff = performance.now() - lastHeartBeat;\n timeDiff = timeDiff / 1000;\n\n if (timeDiff > _waitTime / 1000) {\n controller.abort();\n }\n // Check that the last pulse was within the last 3 seconds.\n }, _waitTime);\n\n const _beatTime = beatTime ?? 2000;\n\n const beatInterval = window.setInterval(() => {\n sendKosMessageResponse({\n msg: {},\n options: {\n topic: `${TOPIC}${relationshipId}`,\n destinationAddress,\n },\n });\n }, _beatTime);\n\n const cleanUpHeartbeat = () => {\n window.clearInterval(beatInterval);\n window.clearInterval(waitInterval);\n unsubscribe();\n };\n\n const handleAbort = () => {\n cleanUpHeartbeat();\n if (onAbort) {\n onAbort();\n }\n controller.signal.removeEventListener(\"abort\", handleAbort);\n };\n\n controller.signal.addEventListener(\"abort\", handleAbort);\n\n return { cleanUpHeartbeat };\n};\n","import { KosLog } from \"../core/log\";\n\ninterface BackoffOptions {\n /** the maximum number of attempts to make */\n maxAttempts: number;\n\n /** the base delay (in ms) between attempts */\n baseDelayMs: number;\n\n /** the factor by which to increase the delay with each attempt */\n backoffFactor: number;\n}\n/**\n * Default backoff options.\n */\nconst BASE_OPTIONS: BackoffOptions = {\n maxAttempts: 5,\n baseDelayMs: 100,\n backoffFactor: 1.5,\n};\n\n/**\n * Provides exponential backoff for a given operation.\n * @param operation - the async operation to perform\n * @param options - optional backoff options\n * @returns - the result of the operation if successful\n * @throws - the last error if all attempts fail\n *\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport async function retryWithExponentialBackoff<T>(\n operation: () => Promise<T>,\n options?: Partial<BackoffOptions>\n): Promise<T> {\n let attempt = 1;\n const _options = { ...BASE_OPTIONS, ...options };\n const { maxAttempts, baseDelayMs, backoffFactor } = _options;\n let delayMs = baseDelayMs;\n\n while (attempt <= maxAttempts) {\n try {\n const result = await operation();\n return result; // If the operation succeeds, return the result\n } catch (error) {\n KosLog.error(`Attempt ${attempt} failed: ${error}`);\n\n if (attempt < maxAttempts) {\n // Exponential backoff: increase the delay exponentially with each attempt\n delayMs = baseDelayMs * Math.pow(backoffFactor, attempt);\n await new Promise((resolve) => setTimeout(resolve, delayMs));\n attempt++;\n } else {\n throw error; // If all attempts fail, re-throw the error\n }\n }\n }\n\n // If we reach this point, all attempts have failed, so reject with the last error\n throw new Error(\"All attempts failed\");\n}\n","import type {\n ApiPath,\n HttpMethod,\n} from \"../core/decorators/kos-service-request\";\nimport type { IKosDataModel } from \"../core/kosModel\";\n\n/**\n * Helpers for reading and clearing the responses that `@kosServiceRequest`\n * methods cache on a model. Responses are keyed by HTTP method and the\n * resolved request path.\n */\n\n/**\n * Returns the response data a `@kosServiceRequest` method cached for the given\n * path and method. The return type defaults to `any`; pass a type parameter to\n * type the result. For a path with parameters, pass the resolved path.\n *\n * @param model - The KOS model instance\n * @param path - The API path constant\n * @param method - The HTTP method (defaults to 'get')\n * @returns The cached response data, or undefined if not found/expired\n *\n * @kosService core.service-response\n *\n * @example\n * ```typescript\n * const status = getServiceResponse<DeviceStatus>(this, PATH_DEVICE_STATUS);\n * ```\n * @kosApiLevel 15\n */\nexport function getServiceResponse<T = any>(\n model: IKosDataModel,\n path: ApiPath,\n method: HttpMethod = \"get\"\n): T | undefined {\n const store = (model as any).serviceResponses;\n if (!store) {\n return undefined;\n }\n\n return store.getByPath(path, method);\n}\n\n/**\n * Checks whether an unexpired cached response exists for the given path and method.\n *\n * @param model - The KOS model instance\n * @param path - The API path constant\n * @param method - The HTTP method (defaults to 'get')\n * @returns true if a valid cached response exists\n *\n * @kosService core.service-response\n * @kosApiLevel 15\n */\nexport function hasCachedResponse(\n model: IKosDataModel,\n path: ApiPath,\n method: HttpMethod = \"get\"\n): boolean {\n const store = (model as any).serviceResponses;\n if (!store) {\n return false;\n }\n\n return store.has(`${method.toUpperCase()}:${path}`);\n}\n\n/**\n * Clears the cached response for one path and method.\n *\n * @param model - The KOS model instance\n * @param path - The API path constant\n * @param method - The HTTP method (defaults to 'get')\n *\n * @kosService core.service-response\n * @kosApiLevel 15\n */\nexport function clearServiceResponse(\n model: IKosDataModel,\n path: ApiPath,\n method: HttpMethod = \"get\"\n): void {\n const store = (model as any).serviceResponses;\n if (!store) {\n return;\n }\n\n store.delete(`${method.toUpperCase()}:${path}`);\n}\n\n/**\n * Clears the cached responses for a path across all HTTP methods.\n *\n * @param model - The KOS model instance\n * @param path - The API path constant\n *\n * @kosService core.service-response\n * @kosApiLevel 15\n */\nexport function clearPath(model: IKosDataModel, path: ApiPath): void {\n const store = (model as any).serviceResponses;\n if (!store) {\n return;\n }\n\n store.clearPath(path);\n}\n\n/**\n * Clears every cached service response on the model.\n *\n * @param model - The KOS model instance\n *\n * @kosService core.service-response\n * @kosApiLevel 15\n */\nexport function clearAllServiceResponses(model: IKosDataModel): void {\n const store = (model as any).serviceResponses;\n if (!store) {\n return;\n }\n\n store.clear();\n}\n","import log from \"loglevel\";\nimport { EventBus } from \"../../common\";\n\nimport { uuid } from \"./api-request-id\";\nimport { KosServiceResponse } from \"./kos-fetch\";\n\n/**\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport interface ErrorResponse {\n error?: string;\n}\n\n/**\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport const waitForRequest = async <ResponseType extends ErrorResponse>(\n requestId: string,\n timeout = 60000\n) =>\n new Promise<ResponseType>((resolve, reject) => {\n const { unsubscribe } = EventBus.subscribe(requestId, (op) => {\n log.debug(`recieved response for refId ${requestId}: ${op}`);\n unsubscribe();\n clearTimeout(cancel);\n try {\n const body: ResponseType = op?.body ? JSON.parse(op.body) : {};\n resolve(body);\n } catch {\n const body = (op?.body as unknown) || {};\n resolve(body as ResponseType);\n }\n });\n\n const cancel = setTimeout(() => {\n unsubscribe();\n reject(Error(`Request with ID ${requestId} timed out. Cancelling.`));\n }, timeout);\n });\n\n/**\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport const sendRequest = async <R, T extends KosServiceResponse<any>>(\n requestPromise: (param: R) => Promise<T | undefined>,\n params: R,\n refId: string\n) => {\n const op = waitForRequest(refId);\n const result = await Promise.allSettled([requestPromise(params), op]);\n\n if (result[0].status === \"fulfilled\") {\n if (result[1].status === \"rejected\") {\n throw Error(result[1].reason);\n } else {\n if (result[0].value) {\n if (result[1].value.error) {\n throw Error(result[1].value.error);\n }\n result[0].value.data = result[1].value;\n return result[0].value;\n }\n }\n } else {\n throw Error(result[0].reason);\n }\n return undefined;\n};\n\ninterface SyncPublishParams<T> {\n topic: string;\n msg: T;\n requestId?: string;\n}\n/**\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport const syncPublish = async <T, R extends ErrorResponse>({\n topic,\n msg,\n requestId,\n}: SyncPublishParams<T>) => {\n const _requestId = requestId ?? uuid();\n const responsePromise = waitForRequest<R>(_requestId);\n EventBus.publish(topic, msg, { sync: _requestId });\n const response = await responsePromise;\n if (response.error) {\n throw Error(response.error);\n }\n return response;\n};\n","/* eslint-disable no-param-reassign */\n/**\n * Item-level decorator that makes a model contribute to the kos-ui-sdk\n * container indexing system.\n *\n * It installs an accessor at `INDEX_RECORD_SYMBOL` that returns the\n * instance's current index record (`KosModelContainer` reads it when\n * publishing ADDED, and containers re-read it on REQUEST_SEED), and a model\n * effect that publishes CHANGED when one of the declared `fields` changes.\n *\n * @kosService core.indexing\n * @kosApiLevel 22\n */\n\nimport * as EventBus from \"../../../common/events/eventBus\";\nimport { KosContextManager } from \"../context/kos-context-manager\";\nimport { ModelEffects } from \"../decorators/propKeys\";\n\nimport { KosContainerIndexEvents } from \"./topics\";\nimport {\n INDEX_COLLECTION_KEY,\n INDEX_RECORD_SYMBOL,\n type IndexChangedEvent,\n type IndexRecordContribution,\n} from \"./types\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Options\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface KosIndexAwareOptions {\n /**\n * Per-item collection tag. May be:\n *\n * - A static string.\n * - A function called with the instance, returning the tag\n * (heterogeneous case where one container holds items belonging\n * to multiple collections, distinguished by some item property).\n * - Undefined: the item resolves its collection from its\n * `KosContext`, walking up the parent chain. Under a\n * `@kosContainerIndexAware` container that declares a collection,\n * this picks up the container's value.\n */\n collection?: string | ((self: any) => string | undefined);\n\n /**\n * Field names projected into the index record and watched for\n * change. Empty/absent means no CHANGED events are emitted; the\n * record still exposes `id`, `modelType`, and `collection`.\n */\n fields?: string[];\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Companion interface for TS interface merging\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Merge this interface into a `@kosIndexAware` model class\n * (`interface MyItemModelImpl extends KosIndexAware {}`) to type the\n * index record accessor.\n */\nexport interface KosIndexAware {\n readonly [INDEX_RECORD_SYMBOL]: IndexRecordContribution;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Decorator\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Class decorator that registers a model as a publisher of index\n * records.\n *\n * The record always carries the instance's `id` and `modelTypeId`, plus the\n * resolved collection and the declared `fields`.\n *\n * @example\n * ```ts\n * interface VirtualMachineModelImpl extends KosIndexAware {}\n *\n * @kosModel(\"virtual-machine-model\")\n * @kosIndexAware({ collection: (self) => self.type, fields: [\"name\"] })\n * class VirtualMachineModelImpl implements IKosDataModel { ... }\n * ```\n *\n * @category KOS Model Decorator\n * @kosService core.indexing\n * @kosApiLevel 22\n */\nexport function kosIndexAware(options?: KosIndexAwareOptions): ClassDecorator {\n return (target: any) => {\n const collection = options?.collection;\n const fields = options?.fields ?? [];\n\n installRecordAccessor(target, collection, fields);\n if (fields.length > 0) {\n installChangeEffect(target, fields);\n }\n\n return target;\n };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Helpers\n// ─────────────────────────────────────────────────────────────────────────────\n\nfunction installRecordAccessor(\n target: any,\n collection: KosIndexAwareOptions[\"collection\"],\n fields: string[]\n): void {\n Object.defineProperty(target.prototype, INDEX_RECORD_SYMBOL, {\n get(): IndexRecordContribution {\n const record: IndexRecordContribution = {\n id: this.id,\n modelType: this.modelTypeId,\n };\n const resolved =\n typeof collection === \"function\" ? collection(this) : collection;\n // Fall back to the inherited context value when the item\n // declared nothing of its own. `KosContextManager.getContext`\n // looks up the bean by id; `.get` auto-walks the parent chain,\n // so a container-declared collection is visible here without\n // any explicit plumbing.\n const inherited =\n resolved === undefined\n ? (KosContextManager.getContext(this.id)?.get(\n INDEX_COLLECTION_KEY\n ) as string | undefined)\n : undefined;\n const finalCollection = resolved ?? inherited;\n if (finalCollection !== undefined) {\n record.collection = finalCollection;\n }\n for (const field of fields) {\n record[field] = this[field];\n }\n return record;\n },\n enumerable: false,\n configurable: true,\n });\n}\n\nfunction installChangeEffect(target: any, fields: string[]): void {\n target.prototype[ModelEffects] = target.prototype[ModelEffects] || {};\n target.prototype[ModelEffects].handleIndexFieldChange = {\n dependencies: (model: any) => fields.map((field) => model[field]),\n value: function (this: any) {\n const record: IndexRecordContribution = this[INDEX_RECORD_SYMBOL];\n // Skip if no collection resolved — neither item-declared nor\n // inherited from a container's context. Without a collection\n // the consumer can't route the record.\n if (!record.collection) {\n return;\n }\n const payload: IndexChangedEvent = {\n record: record as IndexChangedEvent[\"record\"],\n };\n EventBus.publish(KosContainerIndexEvents.CHANGED, payload);\n },\n };\n}\n","/* eslint-disable no-param-reassign */\n/**\n * Container-level decorator for the kos-ui-sdk container indexing system.\n * Works with `@kosContainerAware` or `@kosChild`-based containers; it needs\n * only an `itemsProperty` naming the array of items the container exposes.\n *\n * - On `init`, writes the declared collection onto the container's\n * `KosContext`, where items resolve it by walking up the parent chain.\n * - On `KosContainerIndexEvents.REQUEST_SEED`, publishes one SEED event with\n * the records of the current items, so consumers can subscribe at any time.\n * - On `unload`, publishes one PURGE per distinct collection in the current\n * items so consumers can drop those records.\n *\n * ADDED and REMOVED events come from `KosModelContainer` itself at the moment\n * of mutation.\n *\n * @kosService core.indexing\n * @kosApiLevel 22\n */\n\nimport * as EventBus from \"../../../common/events/eventBus\";\nimport type { KosContext } from \"../context/kos-context-manager\";\nimport { SubscriptionHandlers } from \"../decorators/propKeys\";\n\nimport { KosContainerIndexEvents } from \"./topics\";\nimport {\n INDEX_COLLECTION_KEY,\n INDEX_RECORD_SYMBOL,\n isIndexableItem,\n type IndexPurgeEvent,\n type IndexRecord,\n type IndexRecordContribution,\n type IndexSeedEvent,\n} from \"./types\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Options\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface KosContainerIndexAwareOptions {\n /**\n * Name of the property on the container that exposes its items\n * as an array, such as the `data` getter from `@kosContainerAware` or a\n * custom getter on a `@kosChild`-managed collection. Used for SEED and\n * PURGE; ADDED and REMOVED do not depend on it.\n */\n itemsProperty: string;\n\n /**\n * Collection tag written onto the container's own `KosContext`\n * so child items inherit it. Optional when items declare their own\n * `collection` through `@kosIndexAware`.\n */\n collection?: string;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Decorator\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Class decorator that wires a container model into the kos-ui-sdk\n * indexing system.\n *\n * @example\n * ```ts\n * @kosModel(\"image-container-model\")\n * @kosContainerAware<IImageModel>()\n * @kosContainerIndexAware({ itemsProperty: \"data\", collection: \"images\" })\n * class ImageContainerModelImpl implements IKosDataModel { ... }\n * ```\n *\n * @category KOS Model Decorator\n * @kosService core.indexing\n * @kosApiLevel 22\n */\nexport function kosContainerIndexAware(\n options: KosContainerIndexAwareOptions\n): ClassDecorator {\n return (target: any) => {\n const itemsProperty = options.itemsProperty;\n const declaredCollection = options.collection;\n\n installContextWriter(target, declaredCollection);\n installRequestSeedHandler(target, itemsProperty);\n installPurgeOnUnload(target, itemsProperty);\n\n return target;\n };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Helpers\n// ─────────────────────────────────────────────────────────────────────────────\n\nfunction installContextWriter(\n target: any,\n declaredCollection: string | undefined\n): void {\n if (declaredCollection === undefined) return;\n\n const originalInit = target.prototype.init;\n target.prototype.init = async function (context?: KosContext) {\n context?.set(INDEX_COLLECTION_KEY, declaredCollection);\n if (originalInit) {\n await originalInit.call(this, context);\n }\n };\n}\n\nfunction installRequestSeedHandler(target: any, itemsProperty: string): void {\n target.prototype[SubscriptionHandlers] =\n target.prototype[SubscriptionHandlers] || {};\n target.prototype[SubscriptionHandlers][KosContainerIndexEvents.REQUEST_SEED] =\n {\n websocket: false,\n skipParse: true,\n // The subscription manager calls transform(body) before\n // condition/handler. For an internal EventBus event with a\n // plain object payload we just want to pass it through\n // untouched.\n transform: (payload: unknown) => payload,\n condition: () => true,\n handler: function (this: any) {\n const items = (this[itemsProperty] ?? []) as unknown[];\n const records = collectRecords(items);\n if (records.size === 0) return;\n const payload: IndexSeedEvent = {\n modelType: this.modelTypeId,\n items: Array.from(records.values()),\n };\n EventBus.publish(KosContainerIndexEvents.SEED, payload);\n },\n };\n}\n\nfunction installPurgeOnUnload(target: any, itemsProperty: string): void {\n const originalUnload = target.prototype.unload;\n target.prototype.unload = function (context?: KosContext) {\n const items = (this[itemsProperty] ?? []) as unknown[];\n const collections = new Set<string>();\n for (const item of items) {\n if (!isIndexableItem(item)) continue;\n const contribution: IndexRecordContribution = item[INDEX_RECORD_SYMBOL];\n if (contribution.collection) {\n collections.add(contribution.collection);\n }\n }\n for (const collection of collections) {\n const payload: IndexPurgeEvent = {\n modelType: this.modelTypeId,\n collection,\n };\n EventBus.publish(KosContainerIndexEvents.PURGE, payload);\n }\n if (originalUnload) {\n return originalUnload.call(this, context);\n }\n return undefined;\n };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Record collection (shared with the request-seed handler)\n// ─────────────────────────────────────────────────────────────────────────────\n\nfunction collectRecords(items: unknown[]): Map<string, IndexRecord> {\n const result = new Map<string, IndexRecord>();\n for (const item of items) {\n if (!isIndexableItem(item)) continue;\n const contribution: IndexRecordContribution = item[INDEX_RECORD_SYMBOL];\n if (!contribution.collection) continue;\n result.set(contribution.id, contribution as IndexRecord);\n }\n return result;\n}\n","import {\n IdentifiableModelFactory,\n KosIdentifiableModelRegistration,\n KosModelClassRegistration,\n KosSingletonModelClassRegistration,\n SingletonFactory,\n} from \"../types\";\nimport { isKosModel } from \"../util\";\nimport { Kos } from \"./kos-model-factory\";\nimport type { IKosDataModel, KosCreationContext } from \"./kosModel\";\n\ntype IdentifiableChildRegistration<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> = KosModelClassRegistration<T, O> & {\n singleton: false;\n factory: IdentifiableModelFactory<T, O>;\n};\n\ntype SingletonChildRegistration<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> = KosSingletonModelClassRegistration<T, O> & {\n singleton: true;\n factory: SingletonFactory<T, O>;\n};\n\ntype _ChildRegistration<\n T extends IKosDataModel = any,\n O extends object = Record<string, any>\n> = IdentifiableChildRegistration<T, O> | SingletonChildRegistration<T, O>;\n\ntype Reg<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> = KosIdentifiableModelRegistration<T, O> & {\n singleton: false;\n factory: IdentifiableModelFactory<T, O>;\n};\ninterface ModelRegistration<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> {\n [k: string]: Reg<T, O>;\n}\ninterface RegistrationProps<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> {\n type: string;\n model: new (modelId: string, options: O, context: KosCreationContext) => T;\n childRegistration?: any;\n}\nexport class KosRegistration<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> {\n type: string;\n childRegistration?: any;\n model: new (modelId: string, options: O, context: KosCreationContext) => T;\n constructor({ type, model, childRegistration }: RegistrationProps<T, O>) {\n this.type = type;\n this.model = model;\n this.childRegistration = childRegistration;\n }\n\n get factory() {\n return Kos.Factory.create<T, O>(this.type);\n }\n\n get registration(): ModelRegistration<T, O> {\n return {\n [this.type]: {\n class: this.model,\n singleton: false,\n factory: this.factory,\n },\n ...this.childRegistration,\n } as ModelRegistration<T, O>;\n }\n\n get predicate() {\n return isKosModel<T>(this.type);\n }\n}\n","import {\n IdentifiableModelFactory,\n KosIdentifiableModelRegistration,\n KosSingletonModelClassRegistration,\n SingletonFactory,\n} from \"../types\";\nimport { isKosModel } from \"../util\";\nimport { Kos } from \"./kos-model-factory\";\nimport type { IKosDataModel, KosCreationContext } from \"./kosModel\";\n\ntype IdentifiableChildRegistration<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> = KosIdentifiableModelRegistration<T, O> & {\n factory: IdentifiableModelFactory<T, O>;\n};\n\ntype SingletonChildRegistration<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> = KosSingletonModelClassRegistration<T, O> & {\n factory: SingletonFactory<T, O>;\n};\n\ntype _ChildRegistration<\n T extends IKosDataModel = any,\n O extends object = Record<string, any>\n> = IdentifiableChildRegistration<T, O> | SingletonChildRegistration<T, O>;\n\ntype Reg<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> = KosSingletonModelClassRegistration<T, O> & {\n factory: SingletonFactory<T, O>;\n};\ninterface Singleton<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> {\n [k: string]: Reg<T, O>;\n}\n\ninterface RegistrationProps<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> {\n type: string;\n model: new (modelId: string, options: O, context: KosCreationContext) => T;\n childRegistration?: any;\n}\nexport class KosSingletonRegistration<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> {\n type: string;\n model: new (modelId: string, options: O, context: KosCreationContext) => T;\n childRegistration?: any;\n constructor({ type, model, childRegistration }: RegistrationProps<T, O>) {\n this.type = type;\n this.model = model;\n this.childRegistration = childRegistration;\n }\n\n get factory() {\n return Kos.Singleton.create<T, O>(this.type);\n }\n\n get registration(): Singleton<T, O> {\n return {\n [this.type]: {\n class: this.model,\n singleton: true,\n factory: this.factory,\n },\n ...this.childRegistration,\n } as Singleton<T, O>;\n }\n\n get predicate() {\n return isKosModel<T>(this.type);\n }\n}\n","import { makeAutoObservable } from \"mobx\";\nimport { EventBus } from \"../../../../common\";\n\nexport interface IKosToken {\n token?: string;\n}\nclass KosToken implements IKosToken {\n private _token?: string;\n constructor() {\n makeAutoObservable(this);\n EventBus.subscribe(\"token\", (token) => {\n this.token = token?.body;\n });\n }\n\n get token() {\n return this._token;\n }\n\n set token(token) {\n this._token = token;\n }\n}\n\nexport default KosToken;\n","/* eslint-disable no-param-reassign */\nimport { DependencyLifecycle, DependencyModels } from \"../../core\";\nimport { ConfigBean } from \"../models/config-bean\";\nimport { configBeanModelId } from \"../models/config-bean/config-bean-model\";\n\ninterface KosConfigParams {\n path: string;\n lazy?: boolean;\n serviceBasePath?: string;\n /**\n * Connection the bean's requests and topic subscription are routed to.\n * Accepts a prop key so a host model can bind it per device.\n * When set, the bean's model id includes it so beans never collide across devices.\n */\n destinationAddress?: string;\n}\n\nexport const kosConfigBean =\n ({ path, lazy, serviceBasePath, destinationAddress }: KosConfigParams) =>\n (target: {} | any, name: PropertyKey): any => {\n target[DependencyModels] = target[DependencyModels] || {};\n // eslint-disable-next-line max-len\n target[DependencyModels][name] = {\n modelType: ConfigBean.type,\n id: configBeanModelId(path, destinationAddress),\n options: {\n path,\n serviceBasePath,\n destinationAddress,\n },\n lifecycle: DependencyLifecycle.INIT,\n lazy,\n };\n };\n","/* eslint-disable no-param-reassign */\n\nimport { DependencyLifecycle, DependencyModels } from \"../../core\";\nimport { KosConfigPropertySpec } from \"../models/config-bean-prop\";\nimport { OptionsExpander } from \"../models/config-bean-prop/types\";\n\nexport interface ToUnitConverterSystem {\n iface: \"system\";\n system: string;\n}\n\nexport interface ToUnitConverterSystemUnit {\n iface: \"systemunit\";\n system: string;\n unit: string;\n}\n\nexport interface ToUnitConverterMeasure {\n iface: \"measure\";\n measure: string;\n}\n\nexport interface ToUnitConverterUnit {\n iface: \"unit\";\n unit: string;\n}\n\nexport type ToUnitConverter =\n | ToUnitConverterSystem\n | ToUnitConverterSystemUnit\n | ToUnitConverterMeasure\n | ToUnitConverterUnit;\nexport interface UnitConverter {\n system?: string;\n measure?: string;\n unit?: string;\n alias?: string;\n}\ninterface KosConfigParams {\n path: string;\n attribute: string;\n formatter?:\n | Intl.NumberFormatOptions\n | ((system: string) => Intl.NumberFormatOptions);\n optionsExpander?: OptionsExpander;\n lazy?: boolean;\n serviceBasePath?: string;\n /**\n * Connection the property's bean is routed to. Accepts a prop key so a host\n * model can bind it per device; the property and bean ids include it.\n */\n destinationAddress?: string;\n converter?: {\n measure?: string;\n from?: UnitConverter | string;\n to?: UnitConverter | string;\n };\n}\n\nexport function kosConfigProperty(params: KosConfigParams) {\n const {\n path,\n attribute,\n converter,\n formatter,\n lazy,\n optionsExpander,\n serviceBasePath,\n destinationAddress,\n } = params;\n const _converter = converter;\n if (_converter) {\n if (\n typeof _converter !== \"function\" &&\n typeof _converter.from === \"string\"\n ) {\n _converter.from = { unit: _converter.from };\n }\n\n if (typeof _converter !== \"function\" && typeof _converter.to === \"string\") {\n _converter.to = { unit: _converter.to };\n }\n }\n return (target: {} | any, name: PropertyKey): any => {\n target[DependencyModels] = target[DependencyModels] || {};\n // eslint-disable-next-line max-len\n target[DependencyModels][name] = {\n modelType: KosConfigPropertySpec.type,\n id: destinationAddress\n ? `${destinationAddress}-${path}-${attribute}`\n : `${path}-${attribute}`,\n options: {\n path,\n attribute,\n serviceBasePath,\n destinationAddress,\n converter: _converter,\n formatter,\n optionsExpander,\n },\n\n lifecycle: DependencyLifecycle.INIT,\n lazy,\n };\n };\n}\n","import { DependencyLifecycle, DependencyModels } from \"../../core\";\nimport { StateBean } from \"../models/state-bean\";\n\ninterface KosStateParams {\n path: string;\n}\n\nexport const kosStateBean =\n ({ path }: KosStateParams) =>\n (target: {} | any, name: PropertyKey): any => {\n target[DependencyModels] = target[DependencyModels] || {};\n // eslint-disable-next-line max-len\n target[DependencyModels][name] = {\n modelType: StateBean.type,\n id: `${StateBean.type}-${path}`,\n options: {\n path,\n },\n lifecycle: DependencyLifecycle.INIT,\n };\n };\n","import { DependencyLifecycle, DependencyModels } from \"../../core\";\n\nimport { StateProp } from \"../models/state-prop\";\nimport { StatePropertyTypes } from \"../models/types\";\n\ntype StateKeys<T extends Record<string, StatePropertyTypes>> = keyof T;\n\ninterface KosStateParams<T extends Record<string, StatePropertyTypes> = any> {\n path: string;\n attribute: `${string & StateKeys<T>}`;\n}\n\nexport function kosStateProp<\n T extends Record<string, StatePropertyTypes> = any\n>(params: KosStateParams<T>) {\n const { path, attribute } = params;\n\n return (target: {} | any, name: PropertyKey): any => {\n target[DependencyModels] = target[DependencyModels] || {};\n // eslint-disable-next-line max-len\n target[DependencyModels][name] = {\n modelType: StateProp.type,\n id: `${path}-${attribute}`,\n options: {\n path,\n attribute,\n },\n\n lifecycle: DependencyLifecycle.INIT,\n };\n };\n}\n","import { autorun as kosAutoEffect } from \"mobx\";\n\n/**\n * A long-running operation whose progress can be observed imperatively.\n *\n * Progress surfaces (notifications, status indicators, modals) depend on this\n * interface rather than on any producer. `awaitFutureCall` adapts a KOS Future\n * to it; an upload or an aggregate of several operations can implement it too.\n */\nexport interface ProgressOperation<T = unknown> extends Promise<T> {\n /**\n * Percent complete, 0-100. A value of 0 or less means the operation has not\n * reported progress yet, so consumers should show an indeterminate state.\n */\n readonly progress: number;\n\n /**\n * Current status of the operation.\n * Common values: \"NOT_ACTIVE\", \"IN_PROGRESS\", a terminal end state\n * (\"SUCCESS\" | \"FAIL\" | \"ABORT\" | \"CANCEL\"), or consumer-defined.\n */\n readonly status: string;\n\n /**\n * Whether the operation is currently running\n */\n readonly isRunning: boolean;\n\n /**\n * Human-readable time remaining (e.g. \"2 minutes\"), when the source can\n * estimate it. Empty/undefined when unknown.\n */\n readonly timeRemaining?: string;\n\n /**\n * Cancel this specific operation\n */\n cancel(): Promise<void>;\n\n /**\n * Whether the operation was cancelled. Treat a missing implementation as unknown.\n */\n isCancelled?(): boolean;\n\n /**\n * Subscribe to progress updates\n * Returns a dispose function to clean up the subscription\n */\n onProgressUpdate(\n callback: (progress: number, status: string) => void\n ): () => void;\n}\n\n/**\n * A Promise that can be cancelled and provides progress/state tracking\n */\nexport interface CancellablePromise<T> extends ProgressOperation<T> {\n /**\n * Get the underlying AbortController for this operation\n */\n getController(): AbortController | undefined;\n\n /**\n * Check if this operation is cancelled\n */\n isCancelled(): boolean;\n}\n\n/**\n * Options for creating a cancellable promise with progress tracking\n */\nexport interface CancellablePromiseOptions<T> {\n promise: Promise<T>;\n abortController?: AbortController;\n cancelFuture?: () => Promise<void>;\n future?: any; // The KOS Future object for progress tracking\n}\n\n/**\n * Create a cancellable promise wrapper with reactive progress tracking\n */\nexport function createCancellablePromise<T>(\n promise: Promise<T>,\n abortController?: AbortController,\n cancelFuture?: () => Promise<void>,\n future?: any\n): CancellablePromise<T>;\nexport function createCancellablePromise<T>(\n options: CancellablePromiseOptions<T>\n): CancellablePromise<T>;\nexport function createCancellablePromise<T>(\n promiseOrOptions: Promise<T> | CancellablePromiseOptions<T>,\n abortController?: AbortController,\n cancelFuture?: () => Promise<void>,\n future?: any\n): CancellablePromise<T> {\n // Handle both call signatures\n const options =\n promiseOrOptions instanceof Promise\n ? { promise: promiseOrOptions, abortController, cancelFuture, future }\n : promiseOrOptions;\n\n const {\n promise,\n abortController: controller,\n cancelFuture: cancelFn,\n future: futureRef,\n } = options;\n\n // Create the base promise\n const cancellablePromise = promise as CancellablePromise<T>;\n\n // Progress tracking state\n let currentProgress = 0;\n let currentStatus = \"PENDING\";\n let isRunning = true;\n const progressCallbacks = new Set<\n (progress: number, status: string) => void\n >();\n\n // Update progress from Future if available\n let effectDisposer: (() => void) | undefined;\n if (futureRef && typeof futureRef === \"object\") {\n // Use kosAutoEffect to track Future changes\n effectDisposer = kosAutoEffect(() => {\n const newProgress = futureRef.progress || 0;\n const newStatus = futureRef.status || \"PENDING\";\n const newIsRunning = !futureRef.endState;\n\n if (\n newProgress !== currentProgress ||\n newStatus !== currentStatus ||\n newIsRunning !== isRunning\n ) {\n currentProgress = newProgress;\n currentStatus = newStatus;\n isRunning = newIsRunning;\n\n // Notify all subscribers\n progressCallbacks.forEach((callback) => {\n try {\n callback(currentProgress, currentStatus);\n } catch (error) {\n console.warn(\"Progress callback error:\", error);\n }\n });\n }\n });\n }\n\n // Clean up effect when promise completes\n promise.finally(() => {\n isRunning = false;\n if (!controller?.signal.aborted) {\n currentStatus = \"COMPLETED\";\n progressCallbacks.forEach((callback) => {\n try {\n callback(currentProgress, currentStatus);\n } catch (error) {\n console.warn(\"Progress callback error:\", error);\n }\n });\n }\n if (effectDisposer) {\n effectDisposer();\n }\n progressCallbacks.clear();\n });\n\n // Add cancellation methods\n cancellablePromise.cancel = async () => {\n if (controller && !controller.signal.aborted) {\n controller.abort();\n }\n if (cancelFn) {\n await cancelFn();\n }\n isRunning = false;\n currentStatus = \"CANCELLED\";\n progressCallbacks.forEach((callback) => {\n try {\n callback(currentProgress, currentStatus);\n } catch (error) {\n console.warn(\"Progress callback error:\", error);\n }\n });\n if (effectDisposer) {\n effectDisposer();\n }\n };\n\n cancellablePromise.getController = () => controller;\n\n cancellablePromise.isCancelled = () => controller?.signal.aborted ?? false;\n\n // Add progress tracking properties\n Object.defineProperty(cancellablePromise, \"progress\", {\n get: () => currentProgress,\n enumerable: true,\n });\n\n Object.defineProperty(cancellablePromise, \"status\", {\n get: () => currentStatus,\n enumerable: true,\n });\n\n Object.defineProperty(cancellablePromise, \"isRunning\", {\n get: () => isRunning,\n enumerable: true,\n });\n\n cancellablePromise.onProgressUpdate = (\n callback: (progress: number, status: string) => void\n ) => {\n progressCallbacks.add(callback);\n\n // Call immediately with current state\n callback(currentProgress, currentStatus);\n\n // Return dispose function\n return () => progressCallbacks.delete(callback);\n };\n\n return cancellablePromise;\n}\n","/**\n * Helpers that make a @kosFuture method call cancellable without reaching for\n * the model's future.\n */\n\nimport { KosLog } from \"../../core\";\nimport type { FutureContainer } from \"../models/future/future-types\";\nimport type { CancellablePromise } from \"../types/cancellable-promise\";\nimport { createCancellablePromise } from \"../types/cancellable-promise\";\n\n/**\n * Calls a @kosFuture method and returns a CancellablePromise whose `cancel()`\n * cancels the future the call started.\n *\n * @example\n * ```typescript\n * const call = makeCancellable(model, (m) => m.performOperation(\"data\"));\n * await call.cancel();\n * ```\n */\nexport function makeCancellable<T extends FutureContainer, R>(\n model: T,\n methodCall: (model: T) => Promise<R>\n): CancellablePromise<R> {\n // Store the current future before the call\n const initialFuture = model.futureHandler.future;\n\n // Execute the method call\n const promise = methodCall(model);\n\n // Wait a tick to get the new future created by the method\n let newFuture: any = null;\n setTimeout(() => {\n newFuture = model.futureHandler.future;\n // Only use the new future if it's different from the initial one\n if (newFuture === initialFuture) {\n newFuture = null;\n }\n }, 0);\n\n return createCancellablePromise({\n promise,\n abortController: undefined, // No direct AbortController access\n cancelFuture: async () => {\n // Cancel through the Future system\n if (newFuture) {\n await newFuture.cancelFuture();\n } else {\n // Fallback to current future\n const currentFuture = model.futureHandler.future;\n if (currentFuture) {\n await currentFuture.cancelFuture();\n }\n }\n },\n future: newFuture, // Pass the future for progress tracking\n });\n}\n\n/**\n * {@link makeCancellable} for a method given by name and arguments.\n *\n * @example\n * ```typescript\n * const call = withCancellation(model, \"performOperation\", \"data\");\n * ```\n */\nexport function withCancellation<T extends FutureContainer, K extends keyof T>(\n model: T,\n methodName: K,\n ...args: T[K] extends (...args: infer A) => any ? A : never\n): CancellablePromise<\n T[K] extends (...args: any[]) => Promise<infer R> ? R : never\n> {\n const method = model[methodName];\n if (typeof method !== \"function\") {\n throw new Error(`${String(methodName)} is not a method`);\n }\n\n // Store the current future state\n const initialFuture = model.futureHandler.future;\n\n // Call the method\n const promise = (method as any).apply(model, args);\n\n // Get the new future after method execution\n let targetFuture: any = null;\n setTimeout(() => {\n const currentFuture = model.futureHandler.future;\n if (currentFuture && currentFuture !== initialFuture) {\n targetFuture = currentFuture;\n }\n }, 0);\n\n return createCancellablePromise({\n promise,\n abortController: undefined,\n cancelFuture: async () => {\n if (targetFuture) {\n await targetFuture.cancelFuture();\n } else {\n const fallbackFuture = model.futureHandler.future;\n if (fallbackFuture) {\n await fallbackFuture.cancelFuture();\n }\n }\n },\n future: targetFuture, // Pass the future for progress tracking\n });\n}\n\n/**\n * Collects cancellable calls so they can be cancelled together.\n *\n * @example\n * ```typescript\n * const batch = createCancellationBatch();\n * batch.add(model, (m) => m.performOperation());\n * await batch.cancelAll();\n * ```\n */\nexport class CancellationBatch {\n private operations: Array<CancellablePromise<any>> = [];\n\n add<T extends FutureContainer, R>(\n model: T,\n methodCall: (model: T) => Promise<R>\n ): CancellablePromise<R> {\n const cancellable = makeCancellable(model, methodCall);\n this.operations.push(cancellable);\n return cancellable;\n }\n\n async cancelAll(): Promise<void> {\n await Promise.all(\n this.operations.map((op) =>\n op.cancel().catch(() => {\n // Ignore cancellation errors, just log them if needed\n KosLog.warn(\"Cancellation failed for operation:\", op);\n })\n )\n );\n }\n\n getAllControllers(): Array<AbortController | undefined> {\n return this.operations.map((op) => op.getController());\n }\n\n getActiveCount(): number {\n return this.operations.filter((op) => !op.isCancelled()).length;\n }\n\n clear(): void {\n this.operations = [];\n }\n}\n\nexport function createCancellationBatch(): CancellationBatch {\n return new CancellationBatch();\n}\n","/**\n * Folds several localization contexts into the one descriptor a\n * TranslationContainer is built from. Kept separate from\n * KosTranslationProvider so the merge rules can be tested without a DOM.\n */\nimport type { Localization } from \"./services\";\n\n/** A locale code paired with its name, rendered in that locale's own language. */\nexport interface LocaleOption {\n locale: string;\n label: string;\n}\n\n/**\n * Fold contexts into one descriptor, earlier entries winning.\n *\n * Precedence is per namespace, not per key or per locale: a namespace declared\n * by two contexts is taken whole from the earlier one, and the later context's\n * locales for that namespace are dropped even where the winner has none. A later\n * context can add namespaces but cannot extend one an earlier context declared.\n *\n * Each namespace's `basePath` is set to its own context's `path`, so namespaces\n * from different contexts keep resolving against the URL their context is\n * served from. The merged descriptor has no top-level `path`, since\n * `defaultResolver` reads `basePath` per namespace.\n */\nexport function mergeLocalizationDescriptors(\n descriptors: Localization[]\n): Localization {\n const merged: Localization[\"namespaces\"] = {};\n\n // Reverse, so the first context's namespaces are applied last and win.\n for (const descriptor of [...descriptors].reverse()) {\n for (const [name, namespace] of Object.entries(\n descriptor.namespaces ?? {}\n )) {\n merged[name] = { ...namespace, basePath: descriptor.path };\n }\n }\n\n return { namespaces: merged } as Localization;\n}\n\n/**\n * Every locale any namespace offers, as picker options.\n *\n * The result is a union across namespaces: one namespace translated into a\n * locale is enough to offer it for the whole app, and namespaces without it fall\n * back at resolve time. Excluded namespaces contribute nothing, which keeps a\n * content-bearing namespace (a brandset) from advertising locales the UI itself\n * cannot render.\n *\n * Labels come from `Intl.DisplayNames` and are rendered in the locale's own\n * language (\"italiano\", not \"Italian\").\n */\nexport function collectLocaleOptions(\n descriptors: Localization[],\n excludeNamespaces: string[] = []\n): LocaleOption[] {\n const codes = new Set<string>();\n\n for (const descriptor of descriptors) {\n for (const [name, namespace] of Object.entries(\n descriptor.namespaces ?? {}\n )) {\n if (excludeNamespaces.includes(name)) continue;\n for (const locale of Object.keys(namespace.locales ?? {})) {\n codes.add(locale);\n }\n }\n }\n\n return Array.from(codes).map((locale) => {\n return {\n locale,\n label: new Intl.DisplayNames([locale], { type: \"language\" }).of(\n locale\n ) as string,\n };\n });\n}\n","import { KosContextManager, whenReady } from \"../../../core\";\nimport { TranslationContainer } from \"./translation-container-registration\";\nimport type { TranslationContainerOptions } from \"./types\";\n\nexport const TranslationContext = {\n set(name: string, value: any) {\n const context = KosContextManager.getContext(TranslationContainer.type);\n if (context) {\n context.set(name, value);\n }\n },\n get(name: string) {\n const context = KosContextManager.getContext(TranslationContainer.type);\n return context?.get(name);\n },\n};\n\nexport const KosTranslations = {\n async init(options: TranslationContainerOptions) {\n const tc = TranslationContainer.factory(options);\n await whenReady(tc);\n return { translations: tc };\n },\n};\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport {\n ExtensionManager,\n ExtensionOptions,\n PropertyMapper,\n type DataLoader,\n} from \"../../core\";\nimport { KosCoreModelPropertyMapper } from \"../constants\";\nimport type { IConfigBeanModel, RegionInfoModel } from \"../models\";\nimport { CanvasDispatcher } from \"../models/canvas-dispatcher\";\nimport type { TroubleResponse } from \"../models/trouble/services\";\n\nexport type TroubleRankMapper = PropertyMapper<TroubleResponse, number, any>;\n\nexport type TroubleColorMapper = PropertyMapper<TroubleResponse, string, any>;\n\nexport type TroubleRoleMapper = PropertyMapper<TroubleResponse, string, any>;\n\nexport type RegionServicePathMapper = PropertyMapper<\n RegionInfoModel,\n string,\n any\n>;\n\nexport type ConfigServicePathMapper = PropertyMapper<\n IConfigBeanModel,\n string,\n any\n>;\nexport class CoreExtensionManager {\n /**\n * Maps the rank property of the trouble into the {@link TroubleModel}.\n *\n * @param troubleRankMapper - Mapping function that derives a numeric rank from a {@link TroubleResponse}\n * @param options - Optional {@link ExtensionOptions} to control failure behavior.\n * Defaults to `failurePolicy: \"throw\"`, which throws an {@link ExtensionException} on mapper failure.\n * Set to `\"continue\"` to log the error and return a fallback value instead.\n * @returns this instance for chaining\n * */\n registerTroubleRankMapper(\n troubleRankMapper: TroubleRankMapper,\n options?: ExtensionOptions\n ) {\n ExtensionManager.propertyMapper.registerPropertyMapper(\n KosCoreModelPropertyMapper.TroubleRank,\n troubleRankMapper,\n options\n );\n return this;\n }\n\n /**\n * Maps the role property of the trouble into the {@link TroubleModel}.\n *\n * @param troubleRoleMapper - Mapping function that derives a role string from a {@link TroubleResponse}\n * @param options - Optional {@link ExtensionOptions} to control failure behavior.\n * Defaults to `failurePolicy: \"throw\"`, which throws an {@link ExtensionException} on mapper failure.\n * Set to `\"continue\"` to log the error and return a fallback value instead.\n * @returns this instance for chaining\n * */\n registerTroubleRoleMapper(\n troubleRoleMapper: TroubleRoleMapper,\n options?: ExtensionOptions\n ) {\n ExtensionManager.propertyMapper.registerPropertyMapper(\n KosCoreModelPropertyMapper.TroubleRole,\n troubleRoleMapper,\n options\n );\n return this;\n }\n\n /**\n * Maps the color property of the trouble into the {@link TroubleModel}.\n *\n * @param troubleColorMapper - Mapping function that derives a color string from a {@link TroubleResponse}\n * @param options - Optional {@link ExtensionOptions} to control failure behavior.\n * Defaults to `failurePolicy: \"throw\"`, which throws an {@link ExtensionException} on mapper failure.\n * Set to `\"continue\"` to log the error and return a fallback value instead.\n * @returns this instance for chaining\n * */\n registerTroubleColorMapper(\n troubleColorMapper: TroubleColorMapper,\n options?: ExtensionOptions\n ) {\n ExtensionManager.propertyMapper.registerPropertyMapper(\n KosCoreModelPropertyMapper.TroubleColor,\n troubleColorMapper,\n options\n );\n return this;\n }\n\n /**\n * Registers a data loader for a given model id. The loader is invoked during model\n * initialization to fetch data that is provided as context to associated mappers.\n *\n * @param id - The model identifier to associate the loader with\n * @param loader - Async function that loads and returns data for the model\n * @param options - Optional {@link ExtensionOptions} to control failure behavior.\n * Defaults to `failurePolicy: \"throw\"`, which throws an {@link ExtensionException} on loader failure.\n * Set to `\"continue\"` to log the error and return `undefined` instead.\n */\n registerModelLoader(\n id: string,\n loader: DataLoader,\n options?: ExtensionOptions\n ) {\n ExtensionManager.loader.registerLoader(id, loader, options);\n }\n\n registerRegionServicePathMapper(\n regionServicePathMapper: RegionServicePathMapper\n ) {\n ExtensionManager.propertyMapper.registerPropertyMapper(\n KosCoreModelPropertyMapper.RegionServicePath,\n regionServicePathMapper\n );\n return this;\n }\n\n /**\n * Registers a data loader for the {@link CanvasDispatcher} pattern data.\n *\n * @param loader - Async function that loads canvas pattern data\n * @param options - Optional {@link ExtensionOptions} to control failure behavior.\n * Defaults to `failurePolicy: \"throw\"`, which throws an {@link ExtensionException} on loader failure.\n * Set to `\"continue\"` to log the error and return `undefined` instead.\n */\n registerCanvasPatternLoader(loader: DataLoader, options?: ExtensionOptions) {\n ExtensionManager.loader.registerLoader(\n CanvasDispatcher.loader,\n loader,\n options\n );\n }\n\n registerConfigServicePathMapper(\n configServicePathMapper: ConfigServicePathMapper\n ) {\n ExtensionManager.propertyMapper.registerPropertyMapper(\n KosCoreModelPropertyMapper.ConfigServicePath,\n configServicePathMapper\n );\n return this;\n }\n}\n","import { destroyKosModel, whenReady } from \"../../core\";\nimport { KeyValue } from \"../models/key-value\";\n\n/**\n * A persistence store that can be used to store data for a given session id and key\n * The store is namespaced by the stateKey and the sessionId allows for multiple instances\n * of data to be created with the same store using the session id as the discriminator.\n * The store is backed by a {@link KeyValue} model.\n * @public\n * @interface\n */\nexport interface PersistenceStoreAware {\n /** The key value data store */\n store: KosPersistenceStore;\n\n /** The sessionId to be used when multiple instances of a persistence store are required for a given namespace */\n sessionId: string;\n\n /** The stateKey used to namespace the store */\n stateKey: string;\n}\nexport interface KosPersistenceStore {\n /**\n * Update the state of the store for a given key. The session id of the store instance\n * will be used to segregate the data. For example, if the session id is \"my-session\" and the\n * key is \"my-key\", the data will be stored as \"my-session-my-key\". However the session id is not\n * externally visible and is managed by the store.\n *\n * @param key - the key to update\n * @param value - the value to update\n *\n */\n updateState(\n key: string,\n value: string | number | boolean | undefined\n ): Promise<void>;\n\n /**\n * Clean all the data from the store for the given session id\n */\n clean(): void;\n\n /**\n * Retrieve the state of the store for a given key. The session id of the store instance\n * will be used to retrieve the data.\n * @param key - the key to retrieve\n * @returns the value of the key or undefined if the key does not exist\n */\n getState(key: string): string | number | boolean | undefined;\n\n /**\n * Unsubscribe from the store. This will remove the store from the persistence layer\n */\n unsubscribe(): void;\n}\n\n/**\n * Subscribe to a KOS Persistence Store or create a new one\n * The store will be namespaced by the stateKey and the sessionId allows\n * for multiple instances of data to be created with the same store using the session id\n * as the discriminator.\n *\n * If the sessionId is not provided, the store will be global\n *\n * @param stateKey - the namespace of the given persistence store\n * @param sessionId - the data partition with the namespace that the store will operate within\n * @returns a {@link KosPersistenceStore} instance\n */\nexport const subscribeStore = async (\n stateKey: string,\n sessionId?: string\n): Promise<KosPersistenceStore> => {\n const toolState = KeyValue.instance(stateKey).options({}).build();\n const prefix = sessionId ? `${sessionId}-` : \"\";\n await whenReady(toolState);\n return {\n getState: (key: string) => toolState.data[`${prefix}${key}`],\n updateState: async (\n key: string,\n value: string | number | boolean | undefined\n ) => {\n await toolState.updateState(`${prefix}${key}`, value);\n },\n clean: async () => {\n for (const key of toolState.data.keys) {\n await toolState.updateState(`${prefix}${key}`, undefined);\n }\n },\n unsubscribe: () => {\n destroyKosModel(toolState);\n },\n };\n};\n","import { whenReady } from \"../../core\";\nimport { KosConfigPropertySpec } from \"../models/config-bean-prop\";\n\nconst REGION_PATH = \"kos:service:region\";\nconst REGION_ATTRIBUTE = \"regionId\";\nconst REGION_ID = `${REGION_PATH}-${REGION_ATTRIBUTE}`;\n\nexport const updateRegion = async (region: string) => {\n const regionInfo = KosConfigPropertySpec.factory(REGION_ID)({\n path: REGION_PATH,\n attribute: REGION_ATTRIBUTE,\n });\n await whenReady(regionInfo);\n\n regionInfo.updateProperty(region);\n};\n","/**\n * Public accessor for the KOS API service client.\n *\n * Encapsulates the dynamic import of the internal `service` module,\n * preserving the lazy-load pattern while providing a stable import\n * path for external consumers (e.g., @matrica-code/kos-declarative-model).\n */\nexport async function getKosServiceApi() {\n const { default: API } = await import(\"./service\");\n return API;\n}\n","import type { KosExecutionContext } from \"../../../../../core/core/decorators/kos-execution-context\";\nimport type {\n HttpMethod,\n IKosServiceRequestParams,\n} from \"../../../../../core/core/decorators/kos-service-request\";\nimport { kosServiceRequest as baseKosServiceRequest } from \"../../../../../core/core/decorators/kos-service-request\";\nimport type { ClientResponse } from \"../../../../../core/util/kos-service-request\";\nimport { createClient } from \"../../../../../core/util/kos-service-request\";\n\nimport type { PathsByMethod } from \"../../../../../core/util/kos-service-request\";\nimport type { paths } from \"./openapi\";\n\n/**\n * Type aliases for kos API\n */\nexport type Api = paths;\nexport type ApiPath = keyof paths;\nexport type ValidPaths = PathsByMethod<paths>;\n\n/**\n * Methods a response type can be derived for: the lowercase subset of\n * HttpMethod. The uppercase spellings HttpMethod also permits do not match the\n * keys of an OpenAPI `paths` object, so they would silently yield `unknown`.\n */\nexport type SupportedMethod = \"get\" | \"post\" | \"put\" | \"delete\";\n\n/**\n * Get client response type for kos API\n */\nexport type ApiResponse<\n Path extends ApiPath,\n Method extends SupportedMethod = \"get\"\n> = ClientResponse<paths, Path, Method>;\n\n/**\n * Get execution context type for kos API\n */\nexport type ExecutionContext<\n Path extends ApiPath = ApiPath,\n Method extends HttpMethod = \"get\",\n Transformed = ApiResponse<Path, SupportedMethod & Method>\n> = KosExecutionContext<paths, Path, Method, Transformed>;\n\n/**\n * Typed decorator factory for @kosServiceRequest with kos API types\n *\n * Provides full IntelliSense and type safety for path, query params, and body\n * based on the kos OpenAPI schema.\n *\n * @example\n * ```typescript\n * import { kosServiceRequest } from '../../utils/services/kos/daily/service';\n * import { DependencyLifecycle } from '@kosdev-code/kos-ui-sdk';\n *\n * @kosServiceRequest({\n * path: '/api/...',\n * method: 'get',\n * lifecycle: DependencyLifecycle.LOAD\n * })\n * private onDataLoaded(): void {\n * // Fully typed based on kos API\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\n/**\n * One endpoint of the kos API: a path and the method it is called with.\n */\nexport interface Endpoint {\n path: ApiPath;\n method: SupportedMethod;\n}\n\n/**\n * Declare an endpoint once. The decorator config, the execution context type\n * and the response type are all derived from the result, so the path string\n * is written once and cannot drift between them.\n *\n * @example\n * ```typescript\n * export const BoardApi = {\n * list: endpoint(\"/api/board\", \"get\"),\n * update: endpoint(\"/api/board/{id}\", \"put\"),\n * } as const;\n * ```\n */\nexport function endpoint<Path extends ApiPath, Method extends SupportedMethod>(\n path: Path,\n method: Method\n) {\n return { path, method } as const;\n}\n\n/**\n * Execution context for an endpoint: the method-driven `$ctx` parameter type.\n * Pass `Transformed` when the decorator declares a `transform`, so what the\n * method receives is typed as the mapper's output rather than the raw response.\n */\nexport type EndpointCtx<\n E extends Endpoint,\n Transformed = EndpointResponse<E>\n> = ExecutionContext<E[\"path\"], E[\"method\"], Transformed>;\n\n/** Response body type for an endpoint. */\nexport type EndpointResponse<E extends Endpoint> = ApiResponse<\n E[\"path\"],\n E[\"method\"]\n>;\n\n/**\n * @kosServiceRequest preconfigured from an endpoint descriptor, defaulting to\n * log-and-continue error handling. Pass overrides (lifecycle, errorHandler,\n * cache, …) as the second argument.\n *\n * A `transform` narrows what the model receives: its return type becomes the\n * handler's data type, so the raw response shape stops at the mapper.\n *\n * @example\n * ```typescript\n * @serviceRequest(BoardApi.update)\n * async renameBoard(name: string, $ctx?: EndpointCtx<typeof BoardApi.update>) {\n * const data = await executeServiceRequest(this, $ctx, {\n * pathParams: { id: this.id },\n * body: { name },\n * });\n * if (!data) return;\n * }\n * ```\n */\nexport function serviceRequest<\n E extends Endpoint,\n Transformed = EndpointResponse<E>\n>(\n ep: E,\n opts?: Partial<\n IKosServiceRequestParams<\n paths,\n E[\"path\"],\n E[\"method\"],\n EndpointResponse<E>,\n Transformed\n >\n >\n) {\n return kosServiceRequest<\n E[\"path\"],\n E[\"method\"],\n EndpointResponse<E>,\n Transformed\n >({\n path: ep.path,\n method: ep.method,\n errorHandler: { strategy: \"log\", defaultValue: null },\n ...opts,\n });\n}\n\n/**\n * Create an API client for kos\n */\nexport const api = createClient<paths>();\n\nexport default api;\n","import type { KosExecutionContext } from \"../../../../../core/core/decorators/kos-execution-context\";\nimport type {\n HttpMethod,\n IKosServiceRequestParams,\n} from \"../../../../../core/core/decorators/kos-service-request\";\nimport { kosServiceRequest as baseKosServiceRequest } from \"../../../../../core/core/decorators/kos-service-request\";\nimport type { ClientResponse } from \"../../../../../core/util/kos-service-request\";\nimport { createClient } from \"../../../../../core/util/kos-service-request\";\n\nimport type { PathsByMethod } from \"../../../../../core/util/kos-service-request\";\nimport type { paths } from \"./openapi\";\n\n/**\n * Type aliases for kos API\n */\nexport type Api = paths;\nexport type ApiPath = keyof paths;\nexport type ValidPaths = PathsByMethod<paths>;\n\n/**\n * Get client response type for kos API\n */\nexport type ApiResponse<\n Path extends ApiPath,\n Method extends \"get\" | \"post\" | \"put\" | \"delete\" = \"get\"\n> = ClientResponse<paths, Path, Method>;\n\n/**\n * Get execution context type for kos API\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 API types\n *\n * Provides full IntelliSense and type safety for path, query params, and body\n * based on the kos OpenAPI schema.\n *\n * @example\n * ```typescript\n * import { kosServiceRequest } from '../../utils/services/kos/1.6.5/service';\n * import { DependencyLifecycle } from '@kosdev-code/kos-ui-sdk';\n *\n * @kosServiceRequest({\n * path: '/api/...',\n * method: 'get',\n * lifecycle: DependencyLifecycle.LOAD\n * })\n * private onDataLoaded(): void {\n * // Fully typed based on kos API\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\n/**\n * Create an API client for kos\n */\nexport const api = createClient<paths>();\n\nexport default api;\n","import type { KosExecutionContext } from \"../../../../../core/core/decorators/kos-execution-context\";\nimport type {\n HttpMethod,\n IKosServiceRequestParams,\n} from \"../../../../../core/core/decorators/kos-service-request\";\nimport { kosServiceRequest as baseKosServiceRequest } from \"../../../../../core/core/decorators/kos-service-request\";\nimport type { ClientResponse } from \"../../../../../core/util/kos-service-request\";\nimport { createClient } from \"../../../../../core/util/kos-service-request\";\n\nimport type { PathsByMethod } from \"../../../../../core/util/kos-service-request\";\nimport type { paths } from \"./openapi\";\n\n/**\n * Type aliases for kos API\n */\nexport type Api = paths;\nexport type ApiPath = keyof paths;\nexport type ValidPaths = PathsByMethod<paths>;\n\n/**\n * Get client response type for kos API\n */\nexport type ApiResponse<\n Path extends ApiPath,\n Method extends \"get\" | \"post\" | \"put\" | \"delete\" = \"get\"\n> = ClientResponse<paths, Path, Method>;\n\n/**\n * Get execution context type for kos API\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 API types\n *\n * Provides full IntelliSense and type safety for path, query params, and body\n * based on the kos OpenAPI schema.\n *\n * @example\n * ```typescript\n * import { kosServiceRequest } from '../../utils/services/kos/1.8.1/service';\n * import { DependencyLifecycle } from '@kosdev-code/kos-ui-sdk';\n *\n * @kosServiceRequest({\n * path: '/api/...',\n * method: 'get',\n * lifecycle: DependencyLifecycle.LOAD\n * })\n * private onDataLoaded(): void {\n * // Fully typed based on kos API\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\n/**\n * Create an API client for kos\n */\nexport const api = createClient<paths>();\n\nexport default api;\n","import type { KosExecutionContext } from \"../../../../../core/core/decorators/kos-execution-context\";\nimport type {\n HttpMethod,\n IKosServiceRequestParams,\n} from \"../../../../../core/core/decorators/kos-service-request\";\nimport { kosServiceRequest as baseKosServiceRequest } from \"../../../../../core/core/decorators/kos-service-request\";\nimport type { ClientResponse } from \"../../../../../core/util/kos-service-request\";\nimport { createClient } from \"../../../../../core/util/kos-service-request\";\n\nimport type { PathsByMethod } from \"../../../../../core/util/kos-service-request\";\nimport type { paths } from \"./openapi\";\n\n/**\n * Type aliases for kos API\n */\nexport type Api = paths;\nexport type ApiPath = keyof paths;\nexport type ValidPaths = PathsByMethod<paths>;\n\n/**\n * Get client response type for kos API\n */\nexport type ApiResponse<\n Path extends ApiPath,\n Method extends \"get\" | \"post\" | \"put\" | \"delete\" = \"get\"\n> = ClientResponse<paths, Path, Method>;\n\n/**\n * Get execution context type for kos API\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 API types\n *\n * Provides full IntelliSense and type safety for path, query params, and body\n * based on the kos OpenAPI schema.\n *\n * @example\n * ```typescript\n * import { kosServiceRequest } from '../../utils/services/kos/1.9.x/service';\n * import { DependencyLifecycle } from '@kosdev-code/kos-ui-sdk';\n *\n * @kosServiceRequest({\n * path: '/api/...',\n * method: 'get',\n * lifecycle: DependencyLifecycle.LOAD\n * })\n * private onDataLoaded(): void {\n * // Fully typed based on kos API\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\n/**\n * Create an API client for kos\n */\nexport const api = createClient<paths>();\n\nexport default api;\n","import type { KosExecutionContext } from \"../../../../../core/core/decorators/kos-execution-context\";\nimport type {\n HttpMethod,\n IKosServiceRequestParams,\n} from \"../../../../../core/core/decorators/kos-service-request\";\nimport { kosServiceRequest as baseKosServiceRequest } from \"../../../../../core/core/decorators/kos-service-request\";\nimport type { ClientResponse } from \"../../../../../core/util/kos-service-request\";\nimport { createClient } from \"../../../../../core/util/kos-service-request\";\n\nimport type { PathsByMethod } from \"../../../../../core/util/kos-service-request\";\nimport type { paths } from \"./openapi\";\n\n/**\n * Type aliases for vfs API\n */\nexport type Api = paths;\nexport type ApiPath = keyof paths;\nexport type ValidPaths = PathsByMethod<paths>;\n\n/**\n * Methods a response type can be derived for: the lowercase subset of\n * HttpMethod. The uppercase spellings HttpMethod also permits do not match the\n * keys of an OpenAPI `paths` object, so they would silently yield `unknown`.\n */\nexport type SupportedMethod = \"get\" | \"post\" | \"put\" | \"delete\";\n\n/**\n * Get client response type for vfs API\n */\nexport type ApiResponse<\n Path extends ApiPath,\n Method extends SupportedMethod = \"get\"\n> = ClientResponse<paths, Path, Method>;\n\n/**\n * Get execution context type for vfs API\n */\nexport type ExecutionContext<\n Path extends ApiPath = ApiPath,\n Method extends HttpMethod = \"get\",\n Transformed = ApiResponse<Path, SupportedMethod & Method>\n> = KosExecutionContext<paths, Path, Method, Transformed>;\n\n/**\n * Typed decorator factory for @kosServiceRequest with vfs API types\n *\n * Provides full IntelliSense and type safety for path, query params, and body\n * based on the vfs OpenAPI schema.\n *\n * @example\n * ```typescript\n * import { kosServiceRequest } from '../../utils/services/vfs/daily/service';\n * import { DependencyLifecycle } from '@kosdev-code/kos-ui-sdk';\n *\n * @kosServiceRequest({\n * path: '/api/...',\n * method: 'get',\n * lifecycle: DependencyLifecycle.LOAD\n * })\n * private onDataLoaded(): void {\n * // Fully typed based on vfs API\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\n/**\n * One endpoint of the vfs API: a path and the method it is called with.\n */\nexport interface Endpoint {\n path: ApiPath;\n method: SupportedMethod;\n}\n\n/**\n * Declare an endpoint once. The decorator config, the execution context type\n * and the response type are all derived from the result, so the path string\n * is written once and cannot drift between them.\n *\n * @example\n * ```typescript\n * export const BoardApi = {\n * list: endpoint(\"/api/board\", \"get\"),\n * update: endpoint(\"/api/board/{id}\", \"put\"),\n * } as const;\n * ```\n */\nexport function endpoint<Path extends ApiPath, Method extends SupportedMethod>(\n path: Path,\n method: Method\n) {\n return { path, method } as const;\n}\n\n/**\n * Execution context for an endpoint: the method-driven `$ctx` parameter type.\n * Pass `Transformed` when the decorator declares a `transform`, so what the\n * method receives is typed as the mapper's output rather than the raw response.\n */\nexport type EndpointCtx<\n E extends Endpoint,\n Transformed = EndpointResponse<E>\n> = ExecutionContext<E[\"path\"], E[\"method\"], Transformed>;\n\n/** Response body type for an endpoint. */\nexport type EndpointResponse<E extends Endpoint> = ApiResponse<\n E[\"path\"],\n E[\"method\"]\n>;\n\n/**\n * @kosServiceRequest preconfigured from an endpoint descriptor, defaulting to\n * log-and-continue error handling. Pass overrides (lifecycle, errorHandler,\n * cache, …) as the second argument.\n *\n * A `transform` narrows what the model receives: its return type becomes the\n * handler's data type, so the raw response shape stops at the mapper.\n *\n * @example\n * ```typescript\n * @serviceRequest(BoardApi.update)\n * async renameBoard(name: string, $ctx?: EndpointCtx<typeof BoardApi.update>) {\n * const data = await executeServiceRequest(this, $ctx, {\n * pathParams: { id: this.id },\n * body: { name },\n * });\n * if (!data) return;\n * }\n * ```\n */\nexport function serviceRequest<\n E extends Endpoint,\n Transformed = EndpointResponse<E>\n>(\n ep: E,\n opts?: Partial<\n IKosServiceRequestParams<\n paths,\n E[\"path\"],\n E[\"method\"],\n EndpointResponse<E>,\n Transformed\n >\n >\n) {\n return kosServiceRequest<\n E[\"path\"],\n E[\"method\"],\n EndpointResponse<E>,\n Transformed\n >({\n path: ep.path,\n method: ep.method,\n errorHandler: { strategy: \"log\", defaultValue: null },\n ...opts,\n });\n}\n\n/**\n * Create an API client for vfs\n */\nexport const api = createClient<paths>();\n\nexport default api;\n","import type { KosExecutionContext } from \"../../../../../core/core/decorators/kos-execution-context\";\nimport type {\n HttpMethod,\n IKosServiceRequestParams,\n} from \"../../../../../core/core/decorators/kos-service-request\";\nimport { kosServiceRequest as baseKosServiceRequest } from \"../../../../../core/core/decorators/kos-service-request\";\nimport type { ClientResponse } from \"../../../../../core/util/kos-service-request\";\nimport { createClient } from \"../../../../../core/util/kos-service-request\";\n\nimport type { PathsByMethod } from \"../../../../../core/util/kos-service-request\";\nimport type { paths } from \"./openapi\";\n\n/**\n * Type aliases for vfs API\n */\nexport type Api = paths;\nexport type ApiPath = keyof paths;\nexport type ValidPaths = PathsByMethod<paths>;\n\n/**\n * Get client response type for vfs API\n */\nexport type ApiResponse<\n Path extends ApiPath,\n Method extends \"get\" | \"post\" | \"put\" | \"delete\" = \"get\"\n> = ClientResponse<paths, Path, Method>;\n\n/**\n * Get execution context type for vfs API\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 vfs API types\n *\n * Provides full IntelliSense and type safety for path, query params, and body\n * based on the vfs OpenAPI schema.\n *\n * @example\n * ```typescript\n * import { kosServiceRequest } from '../../utils/services/vfs/1.6.5/service';\n * import { DependencyLifecycle } from '@kosdev-code/kos-ui-sdk';\n *\n * @kosServiceRequest({\n * path: '/api/...',\n * method: 'get',\n * lifecycle: DependencyLifecycle.LOAD\n * })\n * private onDataLoaded(): void {\n * // Fully typed based on vfs API\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\n/**\n * Create an API client for vfs\n */\nexport const api = createClient<paths>();\n\nexport default api;\n","import type { KosExecutionContext } from \"../../../../../core/core/decorators/kos-execution-context\";\nimport type {\n HttpMethod,\n IKosServiceRequestParams,\n} from \"../../../../../core/core/decorators/kos-service-request\";\nimport { kosServiceRequest as baseKosServiceRequest } from \"../../../../../core/core/decorators/kos-service-request\";\nimport type { ClientResponse } from \"../../../../../core/util/kos-service-request\";\nimport { createClient } from \"../../../../../core/util/kos-service-request\";\n\nimport type { PathsByMethod } from \"../../../../../core/util/kos-service-request\";\nimport type { paths } from \"./openapi\";\n\n/**\n * Type aliases for vfs API\n */\nexport type Api = paths;\nexport type ApiPath = keyof paths;\nexport type ValidPaths = PathsByMethod<paths>;\n\n/**\n * Get client response type for vfs API\n */\nexport type ApiResponse<\n Path extends ApiPath,\n Method extends \"get\" | \"post\" | \"put\" | \"delete\" = \"get\"\n> = ClientResponse<paths, Path, Method>;\n\n/**\n * Get execution context type for vfs API\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 vfs API types\n *\n * Provides full IntelliSense and type safety for path, query params, and body\n * based on the vfs OpenAPI schema.\n *\n * @example\n * ```typescript\n * import { kosServiceRequest } from '../../utils/services/vfs/1.8.1/service';\n * import { DependencyLifecycle } from '@kosdev-code/kos-ui-sdk';\n *\n * @kosServiceRequest({\n * path: '/api/...',\n * method: 'get',\n * lifecycle: DependencyLifecycle.LOAD\n * })\n * private onDataLoaded(): void {\n * // Fully typed based on vfs API\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\n/**\n * Create an API client for vfs\n */\nexport const api = createClient<paths>();\n\nexport default api;\n","import type { KosExecutionContext } from \"../../../../../core/core/decorators/kos-execution-context\";\nimport type {\n HttpMethod,\n IKosServiceRequestParams,\n} from \"../../../../../core/core/decorators/kos-service-request\";\nimport { kosServiceRequest as baseKosServiceRequest } from \"../../../../../core/core/decorators/kos-service-request\";\nimport type { ClientResponse } from \"../../../../../core/util/kos-service-request\";\nimport { createClient } from \"../../../../../core/util/kos-service-request\";\n\nimport type { PathsByMethod } from \"../../../../../core/util/kos-service-request\";\nimport type { paths } from \"./openapi\";\n\n/**\n * Type aliases for vfs API\n */\nexport type Api = paths;\nexport type ApiPath = keyof paths;\nexport type ValidPaths = PathsByMethod<paths>;\n\n/**\n * Get client response type for vfs API\n */\nexport type ApiResponse<\n Path extends ApiPath,\n Method extends \"get\" | \"post\" | \"put\" | \"delete\" = \"get\"\n> = ClientResponse<paths, Path, Method>;\n\n/**\n * Get execution context type for vfs API\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 vfs API types\n *\n * Provides full IntelliSense and type safety for path, query params, and body\n * based on the vfs OpenAPI schema.\n *\n * @example\n * ```typescript\n * import { kosServiceRequest } from '../../utils/services/vfs/1.9.x/service';\n * import { DependencyLifecycle } from '@kosdev-code/kos-ui-sdk';\n *\n * @kosServiceRequest({\n * path: '/api/...',\n * method: 'get',\n * lifecycle: DependencyLifecycle.LOAD\n * })\n * private onDataLoaded(): void {\n * // Fully typed based on vfs API\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\n/**\n * Create an API client for vfs\n */\nexport const api = createClient<paths>();\n\nexport default api;\n","import { whenReady } from \"../../core\";\nimport { KosConfigPropertySpec } from \"../models/config-bean-prop\";\n\nconst REGION_SETTINGS_PATH = \"kos:service:region:settings\";\nconst TIMEZONE_ATTRIBUTE = \"timeZone\";\nconst REGION_TIMEZONE_ID = `${REGION_SETTINGS_PATH}-${TIMEZONE_ATTRIBUTE}`;\n\nexport const updateTimeZone = async (timezone: string) => {\n const timezoneInfo = KosConfigPropertySpec.factory(REGION_TIMEZONE_ID)({\n path: REGION_SETTINGS_PATH,\n attribute: TIMEZONE_ATTRIBUTE,\n });\n await whenReady(timezoneInfo);\n\n timezoneInfo.updateProperty(timezone);\n};\n","import type { TroubleAware } from \"../types\";\n\n/**\n * Type guard for {@link TroubleAware}: true when `obj` has a `troubles` array\n * and a `troublesByType` object. It checks structure only, not the contents.\n *\n * @category Utilities\n * @category Trouble Management\n *\n * @param obj - The object to check\n * @returns `true` if the object implements TroubleAware\n *\n * @see {@link TroubleAware} - The interface this function checks for\n * @see {@link useTroubleDecoration} - Hook that uses this guard internally\n */\nexport function isTroubleAware(obj?: any): obj is TroubleAware {\n return (\n obj?.troubles !== undefined &&\n obj?.troubles instanceof Array &&\n obj?.troublesByType !== undefined &&\n typeof obj?.troublesByType === \"object\"\n );\n}\n","import { BASE_URL, kosFetch, KosLog, KosServiceResponse } from \"../../../core\";\n\nconst log = KosLog.createLogger({ name: \"services\", group: \"Services\" });\n\ninterface LoginResponse {\n token: string;\n}\n\n/**\n * Convienience function to provide Studio specific login functions defaulting the url\n * Studio endpoint.\n * @param username - the username of the user to log in\n * @param password - the password of the user to log in\n * @returns a login response with the token of the logged in user\n *\n * @internal\n * @see login\n */\nexport const studioLogin = async (username: string, password: string) =>\n login(username, password, `${BASE_URL}/api/server/login`);\n\n/**\n * Attempts a log in against the specified URL.\n * @param username - the username of the user to log in\n * @param password - the password of the user to log in\n * @param url - the url to send the login request to.\n * @defaultValue - defaults to the Admin server URL.\n *\n * @returns a login response with the token of the logged in user\n */\nexport const login = async (\n username: string,\n password: string,\n url = `${BASE_URL}/api/login`\n) => {\n const response = await kosFetch(`${url}`, {\n method: `POST`,\n destinationAddress: \"\",\n body: JSON.stringify({\n email: username,\n password,\n }),\n });\n if (!response.ok) {\n const configResponse = await response.json();\n\n throw Error(`${configResponse?.error}`);\n }\n const configResponse: KosServiceResponse<LoginResponse> | null =\n await response.json();\n return configResponse;\n};\n\n/**\n * Convienience function to provide Studio specific password reset functions defaulting the url\n * Studio endpoint.\n * @param username - the userID of the user to start the password reset process.\n * @returns an API response with no value.\n *\n * @see startPasswordReset\n * @internal\n */\nexport const studioStartPasswordReset = async (userId: string) =>\n startPasswordReset(userId, `${BASE_URL}/api/server/startPasswordReset`, \"\");\n\n/**\n * When a user is first created or if the password is forgotten. A user can request\n * a password reset from thier Organization administrator. The administrator will end\n * up calling this function in order to initiate the request and have reset token sent\n * to the user on thier specified e-mail address (or other method.)\n * The token, received by the user, can be used as part of the reset call to provide a new password.\n *\n * @param userId - the user ID of the suer to start the password reset process.\n * @param url - the url to send the login request to.\n * @defaultValue - defaults to the Admin server URL.\n * @returns an API response with no value.\n * @internal\n * @see resetPassword\n */\nexport const startPasswordReset = async (\n userId: string,\n url = `${BASE_URL}/api/startPasswordReset`,\n destinationAddress = \"server\"\n) => {\n const response = await kosFetch(`${url}?email=${userId}`, {\n method: `POST`,\n destinationAddress,\n });\n if (!response.ok) {\n throw Error(\n `There was a problem reseting config; returned status ${response.status}`\n );\n }\n const configResponse: KosServiceResponse<unknown> | null =\n await response.json();\n return configResponse;\n};\n\n/**\n * Convienience function to provide Studio specific password reset functions defaulting the url\n * Studio endpoint.\n * @param token - the reset token recieved as part of the `startPasswordReset` process\n * @param password - the new password to be used by the user specified in the token.\n * @returns an API response with no value.\n * @internal\n * @see startPasswordReset\n */\nexport const studioResetPassword = async (token: string, password: string) =>\n resetPassword(token, password, `${BASE_URL}/api/server/resetPassword`);\n\n/**\n * Resets the password for the user.\n *\n * @param token - the reset token recieved as part of the `startPasswordReset` process\n * @param password - the new password to be used by the user specified in the token.\n * @param url - the url to send the login request to.\n * @defaultValue - defaults to the Admin server URL.\n * @returns an API response with no value.\n *\n * @internal\n * @see resetPassword\n */\nexport const resetPassword = async (\n token: string,\n password: string,\n url = `${BASE_URL}/api/resetPassword`\n) => {\n log.debug(\n `resetting password with token ${token} and password ${password.replace(\n /./g,\n \"*\"\n )}`\n );\n const response = await kosFetch(`${url}`, {\n method: `POST`,\n destinationAddress: \"\",\n body: JSON.stringify({\n token,\n password,\n }),\n });\n log.debug(`password reset returned status ${response.status}`);\n if (!response.ok) {\n log.error(`password reset failed with message ${response.statusText}`);\n\n const configResponse = await response.json();\n\n throw Error(\n `${configResponse?.error}:There was a problem resetting the password.`\n );\n }\n const configResponse: KosServiceResponse<unknown> | null =\n await response.json();\n return configResponse;\n};\n\nexport const studioAcceptOrgInvitation = async (\n token: string,\n password: string,\n name: string\n) =>\n acceptOrgInvitation(\n token,\n password,\n name,\n `${BASE_URL}/api/server/acceptInvite`\n );\nexport const acceptOrgInvitation = async (\n token: string,\n password: string,\n name: string,\n url = `${BASE_URL}/api/server/acceptInvite`\n) => {\n log.debug(\n `accepting invite with token ${token} and password ${password.replace(\n /./g,\n \"*\"\n )}`\n );\n const response = await kosFetch(`${url}`, {\n method: `POST`,\n destinationAddress: \"\",\n body: JSON.stringify({\n token,\n password,\n name,\n }),\n });\n log.debug(`invitation accept returned status ${response.status}`);\n if (!response.ok) {\n log.error(`invite failed with message ${response.statusText}`);\n\n const configResponse = await response.json();\n\n throw Error(\n `${configResponse?.error}:There was a problem accepting the invite.`\n );\n }\n const configResponse: KosServiceResponse<unknown> | null =\n await response.json();\n return configResponse;\n};\n","/* eslint-disable @typescript-eslint/no-unsafe-declaration-merging */\n\nimport {\n kosLoggerAware,\n KosLoggerAware,\n kosModel,\n} from \"../../../core/core/decorators\";\nimport type { IKosDataModel } from \"../../../core/core/kosModel\";\nimport type { KosModelRegistrationType } from \"../../../core/core/registration/model-registration\";\nimport type { IKosIdentifiable } from \"../../../core/core/types\";\nimport type { PublicModelInterface } from \"../../../core/types\";\n\nimport type { GpioPinOptions } from \"./types\";\n\nexport const MODEL_TYPE = \"gpio-pin-model\";\n\nexport type GpioPinModel = PublicModelInterface<GpioPinModelImpl>;\n\n// Interface merging for decorator type safety\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface GpioPinModelImpl extends KosLoggerAware {}\n\n@kosModel({ modelTypeId: MODEL_TYPE, singleton: false })\n@kosLoggerAware()\nexport class GpioPinModelImpl implements IKosDataModel, IKosIdentifiable {\n // Registration property for type safety - actual value injected by @kosModel decorator\n static Registration: KosModelRegistrationType<GpioPinModel, GpioPinOptions>;\n\n id: string;\n pinNum: number;\n chipNum: number;\n name: string;\n status: \"bound\" | \"pending\" | \"invalid\" | \"free\";\n connected: boolean;\n // logger property is automatically provided by @kosLoggerAware decorator\n\n constructor(modelId: string, options: GpioPinOptions) {\n this.id = modelId;\n this.chipNum = options.chipNum;\n this.pinNum = options.pinNum;\n this.name = options.name;\n this.status = \"free\";\n this.connected = options.connected ?? false;\n }\n\n updateModel(\n options: Partial<Omit<GpioPinOptions, \"chipNum\" | \"pinNum\" | \"name\">>\n ): void {\n this.status = options.status ?? this.status;\n this.connected = options.connected ?? this.connected;\n\n // Update model properties here.\n }\n\n // -------------------LIFECYCLE----------------------------\n\n async init(): Promise<void> {\n this.logger.debug(`initializing gpio-pin ${this.id}`);\n }\n\n async load(): Promise<void> {\n this.logger.debug(`loading gpio-pin ${this.id}`);\n }\n}\n\nexport const GpioPin = GpioPinModelImpl.Registration;\n","/* eslint-disable @typescript-eslint/no-unsafe-declaration-merging */\nimport {\n kosContainerAware,\n kosLoggerAware,\n kosModel,\n type KosContainerAware,\n type KosLoggerAware,\n} from \"../../../core/core/decorators\";\nimport type { IKosDataModel } from \"../../../core/core/kosModel\";\nimport type { KosModelRegistrationType } from \"../../../core/core/registration/model-registration\";\nimport type { IKosIdentifiable } from \"../../../core/core/types\";\nimport type { PublicModelInterface } from \"../../../core/types\";\n\nimport { GpioPin, type GpioPinModel } from \"./gpio-pin-model\";\nimport type { GpioPinContainerOptions } from \"./types\";\n\nexport const MODEL_TYPE = \"gpio-pin-container-model\";\n\nexport type GpioPinContainerModel =\n PublicModelInterface<GpioPinContainerModelImpl>;\n\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface GpioPinContainerModelImpl\n extends KosLoggerAware,\n KosContainerAware<GpioPinModel> {}\n\n@kosModel({ modelTypeId: MODEL_TYPE, singleton: false })\n@kosContainerAware<GpioPinModel>({\n containerOptions: {\n sortKey: \"pinNum\",\n },\n})\n@kosLoggerAware()\nexport class GpioPinContainerModelImpl\n implements IKosIdentifiable, IKosDataModel\n{\n // Registration property for type safety - actual value injected by @kosModel decorator\n static Registration: KosModelRegistrationType<\n GpioPinContainerModel,\n GpioPinContainerOptions\n >;\n\n id: string;\n\n constructor(modelId: string, _options: GpioPinContainerOptions) {\n this.id = modelId;\n // Container is automatically injected with parentId: modelId\n }\n\n updateModel(_options: GpioPinContainerOptions): void {\n // Update model properties here.\n }\n\n getPin(pinNum: number) {\n const pin = this.data[pinNum];\n if (!pin) {\n this.logger.warn(\n `Pin number ${pinNum} not found in container ${this.id}`\n );\n return undefined;\n }\n if (pin.pinNum !== pinNum) {\n this.logger.warn(\n `Pin number mismatch for pin ${pin.id} in container ${this.id}: expected ${pinNum}, got ${pin.pinNum}`\n );\n return undefined;\n }\n return this.data[pinNum];\n }\n // -------------------LIFECYCLE----------------------------\n\n async init(): Promise<void> {\n this.logger.debug(`initializing gpio-pin-container container ${this.id}`);\n }\n\n async load(): Promise<void> {\n this.logger.debug(`loading gpio-pin-container container ${this.id}`);\n }\n}\nexport const GpioPinContainer = GpioPinContainerModelImpl.Registration;\n\nGpioPinContainer.addRelatedModel(GpioPin);\n","/* eslint-disable @typescript-eslint/no-unsafe-declaration-merging */\n\nimport {\n kosChild,\n kosLoggerAware,\n KosLoggerAware,\n kosModel,\n} from \"../../../core/core/decorators\";\nimport type { IKosDataModel } from \"../../../core/core/kosModel\";\nimport type { KosModelRegistrationType } from \"../../../core/core/registration/model-registration\";\nimport type { IKosIdentifiable } from \"../../../core/core/types\";\nimport type { PublicModelInterface } from \"../../../core/types\";\nimport { GpioPinContainer, type GpioPinContainerModel } from \"../gpio-pin\";\n\nimport type { GpioChipOptions } from \"./types\";\n\nexport const MODEL_TYPE = \"gpio-chip-model\";\n\nexport type GpioChipModel = PublicModelInterface<GpioChipModelImpl>;\n\n// Interface merging for decorator type safety\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface GpioChipModelImpl extends KosLoggerAware {}\n\n@kosModel({ modelTypeId: MODEL_TYPE, singleton: false })\n@kosLoggerAware()\nexport class GpioChipModelImpl implements IKosDataModel, IKosIdentifiable {\n // Registration property for type safety - actual value injected by @kosModel decorator\n static Registration: KosModelRegistrationType<GpioChipModel, GpioChipOptions>;\n\n id: string;\n\n num: number;\n devName: string;\n name: string;\n pinCount: number;\n pinNames: string[];\n\n @kosChild private _pins: GpioPinContainerModel;\n // logger property is automatically provided by @kosLoggerAware decorator\n\n constructor(modelId: string, options: GpioChipOptions) {\n this.id = modelId;\n // logger is automatically injected by @kosLoggerAware decorator\n\n this.num = options.num;\n this.devName = options.devName;\n this.name = options.name;\n this.pinCount = options.pinCount;\n this.pinNames = options.pinNames;\n this._pins = GpioPinContainer.instance(`${this.id}-pins`)\n .options({})\n .build();\n }\n\n get pinManager() {\n return this._pins;\n }\n\n updateModel(_options: GpioChipOptions): void {\n // Update model properties here.\n }\n\n // -------------------LIFECYCLE----------------------------\n\n async handleGpioChipLoad(): Promise<void> {}\n async init(): Promise<void> {\n this.logger.debug(`initializing gpio-chip ${this.id}`);\n }\n\n async load(): Promise<void> {\n this.logger.debug(`loading gpio-chip ${this.id}`);\n }\n}\n\nexport const GpioChip = GpioChipModelImpl.Registration;\n","import { KOS_SERVICE_1_9_X as KOS_SERVICE } from \"../../../utils/services-index\";\n\nexport const GPIO_CHIP_PATH: KOS_SERVICE.ApiPath = \"/api/kos/gpio/chips\";\nexport type GpioChipContainerResponse = KOS_SERVICE.ApiResponse<\n typeof GPIO_CHIP_PATH,\n \"get\"\n>;\n\nexport const GPIO_PIN_PATH: KOS_SERVICE.ApiPath = \"/api/kos/gpio/pins\";\nexport type GpioPinContainerResponse = KOS_SERVICE.ApiResponse<\n typeof GPIO_PIN_PATH,\n \"get\"\n>;\n\nexport const gpioServiceRequest = KOS_SERVICE.kosServiceRequest;\nexport const gpioApi = KOS_SERVICE.api;\n","import { GpioPin } from \"../gpio-pin\";\nimport { GpioChip, type GpioChipModel } from \"./gpio-chip-model\";\nimport { type GpioChipContainerResponse } from \"./services\";\nimport { type GpioChipOptions } from \"./types\";\n\nexport type GpioChipResponse = GpioChipContainerResponse[number];\n\nexport interface GpioChipDto extends GpioChipOptions {\n id: string;\n}\n\nexport function mapGpioChipToOptions(dto: GpioChipDto): GpioChipOptions {\n return dto;\n}\n\nexport function createGpioChipModel(dto: GpioChipDto): GpioChipModel {\n return GpioChip.instance(dto.id).options(mapGpioChipToOptions(dto)).build();\n}\n\nexport function updateGpioChipModel(\n dto: GpioChipDto,\n model: GpioChipModel\n): void {\n model.updateModel(mapGpioChipToOptions(dto));\n}\n\nexport function filterGpioChipDto(chip: GpioChipResponse): boolean {\n return !!chip.num || chip.num === 0;\n}\n\nexport function mapGpioChipId(chip: GpioChipResponse): GpioChipDto {\n return {\n id: `${GpioChip.type}-${chip.num}`,\n num: chip.num ?? 0,\n devName: chip.devName ?? \"\",\n name: chip.name ?? \"\",\n pinCount: chip.pinCount ?? 0,\n pinNames: chip.pinNames ?? [],\n };\n}\n\nexport function afterGpioChipCreated(\n model: GpioChipModel,\n dto: GpioChipDto\n): void {\n dto.pinNames.forEach((pinName, index) => {\n const pinModel = GpioPin.instance(`${model.name}-${pinName}`)\n .options({\n name: pinName,\n pinNum: index,\n chipNum: dto.num,\n })\n .build();\n model.pinManager.addModel(pinModel);\n });\n}\n","/* eslint-disable @typescript-eslint/no-unsafe-declaration-merging */\nimport type { SingletonKosModelRegistrationFactory } from \"../../../core\";\nimport {\n kosContainerAware,\n kosLoggerAware,\n kosModel,\n type KosContainerAware,\n type KosLoggerAware,\n} from \"../../../core/core/decorators\";\nimport type { IKosDataModel } from \"../../../core/core/kosModel\";\nimport type { IKosIdentifiable } from \"../../../core/core/types\";\nimport {\n DependencyLifecycle,\n type PublicModelInterface,\n} from \"../../../core/types\";\n\nimport { GpioChip, type GpioChipModel } from \"./gpio-chip-model\";\nimport {\n GPIO_CHIP_PATH,\n gpioApi,\n gpioServiceRequest,\n type GpioChipContainerResponse,\n} from \"./services\";\nimport type { GpioChipContainerOptions } from \"./types\";\nimport {\n afterGpioChipCreated,\n createGpioChipModel,\n filterGpioChipDto,\n mapGpioChipId,\n updateGpioChipModel,\n type GpioChipResponse,\n} from \"./gpio-chip-builders\";\n\nexport const MODEL_TYPE = \"gpio-chip-container-model\";\n\nexport type GpioChipContainerModel =\n PublicModelInterface<GpioChipContainerModelImpl>;\n\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface GpioChipContainerModelImpl\n extends KosLoggerAware,\n KosContainerAware<GpioChipModel, GpioChipResponse> {}\n\n@kosModel({ modelTypeId: MODEL_TYPE, singleton: true })\n@kosContainerAware<GpioChipModel>({\n containerOptions: {\n sortKey: \"num\",\n },\n reconcile: {\n create: createGpioChipModel,\n update: updateGpioChipModel,\n filter: filterGpioChipDto,\n idMapper: mapGpioChipId,\n afterCreate: afterGpioChipCreated,\n },\n})\n@kosLoggerAware()\nexport class GpioChipContainerModelImpl\n implements IKosIdentifiable, IKosDataModel\n{\n // Registration property for type safety - actual value injected by @kosModel decorator\n static Registration: SingletonKosModelRegistrationFactory<\n GpioChipContainerModel,\n GpioChipContainerOptions\n >;\n\n id: string;\n destinationAddress: string;\n\n constructor(modelId: string, options: GpioChipContainerOptions) {\n this.id = modelId;\n this.destinationAddress = options.destinationAddress ?? \"\";\n }\n\n updateModel(_options: GpioChipContainerOptions): void {\n // Update model properties here.\n }\n // -------------------LIFECYCLE----------------------------\n\n @gpioServiceRequest({\n path: GPIO_CHIP_PATH,\n method: \"get\",\n errorHandler: {\n strategy: \"log\",\n defaultValue: [],\n },\n lifecycle: DependencyLifecycle.INIT,\n requestOptions: (model) => {\n return {\n destinationAddress: (model as GpioChipContainerModelImpl)\n .destinationAddress,\n };\n },\n })\n async handleGpioChipInit(\n _error: never,\n response: Record<string, GpioChipContainerResponse>\n ): Promise<void> {\n const [error, pinData] = await gpioApi.get(\n \"/api/kos/gpio/pins\",\n undefined,\n {\n destinationAddress: this.destinationAddress,\n }\n );\n\n if (error) {\n this.logger.error(\"Failed to fetch GPIO pins\", error);\n return;\n }\n\n this.reconcile(Object.values(response).flat());\n\n const statuses = [\"bound\", \"pending\", \"invalid\", \"free\"] as const;\n for (const status of statuses) {\n Object.entries(pinData as Record<string, any>).forEach(\n ([_key, value]) => {\n value?.[status]?.forEach((pin) => {\n const pinNum = pin.pinNum;\n const chipNum = pin.chipNum;\n if (chipNum === undefined || pinNum === undefined) {\n this.logger.warn(\n \"Skipping pin with missing chipNum or pinNum\",\n pin\n );\n return;\n }\n const chipModel = this.data[chipNum];\n if (!chipModel || chipModel.num !== chipNum) {\n this.logger.warn(\n `No chip model found for chipNum ${chipNum} when processing pin ${pinNum}`\n );\n return;\n }\n const pinModel = chipModel.pinManager.getPin(pinNum);\n if (!pinModel) {\n this.logger.warn(\n `No pin model found for pinNum ${pinNum} in chipNum ${chipNum}`\n );\n return;\n }\n\n pinModel.updateModel({\n connected: pin.connected,\n status: status,\n });\n });\n }\n );\n }\n }\n async init(): Promise<void> {\n this.logger.debug(`initializing gpio-chip-container container ${this.id}`);\n }\n\n async load(): Promise<void> {\n this.logger.debug(`loading gpio-chip-container container ${this.id}`);\n }\n}\nexport const GpioChipContainer = GpioChipContainerModelImpl.Registration;\n\nGpioChipContainer.addRelatedModel(GpioChip);\n","import { KosLog, type ServiceResponse } from \"../../../../core\";\nimport API, { type ApiPath, type ApiResponse } from \"../../../utils/service\";\n\nconst log = KosLog.createLogger({\n name: \"studio-properties-service\",\n group: \"Services\",\n});\n\nconst SERVICE_PATH: ApiPath = \"/api/kos/studio/properties\";\nexport type StudioPropertiesClientResponse = ApiResponse<\n typeof SERVICE_PATH,\n \"get\"\n>;\nexport interface StudioPropertiesResponse {\n data?: Record<string, any>;\n}\n\n/**\n * @category Service\n * Retrieves the initial studio-properties data.\n */\nexport const getStudioProperties = async (\n connectionId: string\n): Promise<ServiceResponse<StudioPropertiesResponse>> => {\n log.debug(\"sending GET for studio-properties\");\n if (!connectionId) {\n log.error(\"connectionId is undefined\");\n throw new Error(\"connectionId is undefined\");\n }\n return await API.get(\n SERVICE_PATH,\n {},\n {\n destinationAddress: connectionId,\n timeout: 500,\n }\n );\n};\n","import {\n kosComputed,\n KosLog,\n ObservableData,\n WebSocketTransport,\n type KosData,\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\";\nimport { getStudioProperties } from \"./services\";\n\nimport type { StudioPropertiesOptions } from \"./types\";\n\nexport const MODEL_TYPE = \"studio-properties-model\";\n\nconst TOPIC_PROPERTIES = \"/kos/studio/properties\";\n\n/**\n * Runtime properties of one KOS Studio connection, such as which Studio tools\n * are enabled. `initializePropertiesSession` loads the properties for the\n * connection and subscribes to its `/kos/studio/properties` topic; when the\n * properties cannot be loaded it falls back to defaults.\n * `terminatePropertiesSession` ends the subscription.\n *\n * @interface\n * @example\n * ```typescript\n * const studioProps = StudioProperties.instance(\"studio-conn-1\")\n * .options({ connectionId })\n * .build();\n * await studioProps.initializePropertiesSession();\n * const legacyTools = studioProps.get(\"kos.studio.tool.legacy\");\n * ```\n *\n * @group KOS Model\n * @category System Integration\n * @useDeclaredType\n *\n * @see {@link StudioPropertiesOptions} - Configuration options for StudioPropertiesModel instances\n */\nexport type StudioPropertiesModel =\n PublicModelInterface<StudioPropertiesModelImpl>;\n\nconst DEFAULT_STUDIO_PROPERTIES = {\n \"kos.studio.tool.legacy\": 1,\n};\n\n/**\n * @ignore\n * @internal\n */\n@kosModel(MODEL_TYPE)\nexport class StudioPropertiesModelImpl\n implements IKosDataModel, IKosIdentifiable\n{\n /** Unique identifier for the model instance */\n id: string;\n /** Studio VM connection identifier for property routing */\n connectionId: string;\n /** WebSocket subscription cleanup function */\n private unsubscribe: VoidFunction | null = null;\n /** Context logger for debugging and diagnostics */\n private logger: KosContextLogger;\n /** Observable data store for Studio properties */\n private data: KosData<Record<string, any>>;\n constructor(\n modelId: string,\n options: StudioPropertiesOptions,\n context: KosCreationContext\n ) {\n this.id = modelId;\n this.logger = context.logger;\n\n this.data = ObservableData();\n this.connectionId = options.connectionId;\n }\n\n // -------------------LIFECYCLE----------------------------\n\n /**\n * @internal\n */\n async init(): Promise<void> {\n this.logger.debug(`initializing studio-properties ${this.id}`);\n }\n\n /**\n * @internal\n */\n async load(): Promise<void> {\n this.logger.debug(`loading studio-properties ${this.id}`);\n }\n\n /** Ends the `/kos/studio/properties` subscription. */\n async terminatePropertiesSession(): Promise<void> {\n this.unsubscribe?.();\n }\n\n /**\n * Loads the connection's properties and subscribes to its `/kos/studio/properties` topic.\n */\n async initializePropertiesSession() {\n this.unsubscribe = WebSocketTransport.getInstance().subscribeTopic({\n topic: TOPIC_PROPERTIES,\n destinationAddress: this.connectionId,\n callback: (msg) => {\n this.logger.error(\n `Received studio-properties message for connection ${\n this.connectionId\n }: ${JSON.stringify(msg)}`\n );\n },\n });\n const [error, data] = await getStudioProperties(this.connectionId);\n if (error) {\n this.logger.error(`Error loading studio-properties: ${error}`);\n this.data.setValues(DEFAULT_STUDIO_PROPERTIES);\n return;\n }\n if (data) {\n const update = Object.keys(data).reduce((acc, key) => {\n acc[key] = data[key] ?? key;\n return acc;\n }, {});\n this.data.setValues(update ?? DEFAULT_STUDIO_PROPERTIES);\n KosLog.ifDebug(() =>\n this.logger.debug(`studio-properties loaded: ${JSON.stringify(update)}`)\n );\n }\n }\n\n /**\n * Retrieves a Studio property value by key.\n * @param key Property key to retrieve\n * @returns The property value or undefined if not set\n */\n get(key: string): any {\n return this.data[key];\n }\n\n /**\n * A computed value that tracks one property.\n * @param key Property key to observe\n * @returns Computed value of the property\n */\n createObservableProperty(key: string) {\n return kosComputed(() => this.get(key));\n }\n}\n","import { KosModelRegistrationFactory } from \"../../../core/core/registration\";\nimport type { StudioPropertiesOptions } from \"./types\";\nimport {\n StudioPropertiesModelImpl,\n MODEL_TYPE,\n} from \"./studio-properties-model\";\nimport type { StudioPropertiesModel } from \"./studio-properties-model\";\n\n/**\n * Registration for {@link StudioPropertiesModel}.\n *\n * `type` identifies the model in the registry and in `@kosDependency` declarations.\n * `register()` adds the model to the registry. `instance(id)` builds the model, or returns the existing one when the id is already in use.\n *\n * @example\n * ```typescript\n * const model = StudioProperties.instance(\"studioPropertiesId\").options(options).build();\n * ```\n */\nexport const StudioProperties = new KosModelRegistrationFactory<\n StudioPropertiesModel,\n StudioPropertiesOptions\n>({\n class: StudioPropertiesModelImpl,\n type: MODEL_TYPE,\n});\n","import { css, keyframes } from \"@emotion/react\";\n\nexport const run = keyframes`\n 0% {\n left: -90px;\n color: #eee;\n }\n 50% {\n color: #666;\n }\n 100% {\n left: 90px;\n color: #eee;\n }\n`;\n\nexport const loadingDot = css`\n font-size: 100px;\n margin-top: -80px;\n position: relative;\n animation: ${run} ease-in-out infinite alternate;\n animation-duration: 1.2s;\n`;\n","import styled from \"@emotion/styled\";\nimport { createPortal } from \"react-dom\";\nimport { loadingDot } from \"./loading-message-styles\";\n\ninterface PortalProps {\n children: React.ReactNode;\n}\n\nexport const Portal = ({ children }: PortalProps) =>\n createPortal(children, document.body);\ninterface Props {\n message?: string;\n theme?: \"light\" | \"dark\";\n}\nfunction LoadingMessage({\n message = \"Wait a moment while we load your app.\",\n theme = \"light\",\n}: Props) {\n return (\n <Portal>\n <MessageContainer theme={theme}>\n {message}\n <div css={loadingDot}>.</div>\n </MessageContainer>\n </Portal>\n );\n}\n\nexport default LoadingMessage;\n\nconst MessageContainer = styled.div<{ theme: \"light\" | \"dark\" }>`\n padding-inline: 20px;\n width: 100%;\n height: 100vh;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n position: fixed;\n font-size: 14px;\n top: 0;\n left: 0;\n color: ${({ theme }) => (theme === \"light\" ? \"black\" : \"white\")};\n z-index: 10000;\n`;\n","import React, { ErrorInfo } from \"react\";\nimport { KosLog } from \"../../../core\";\n\nconst log = KosLog.createLogger({ name: \"error-boundary\" });\n\nexport interface ErrorBoundaryState {\n error: Error | null;\n errorInfo: ErrorInfo | null;\n}\n\nexport interface ErrorBoundaryProps extends React.PropsWithChildren {\n fallback?: React.ReactNode;\n /** Names the guarded region so a caught error is traceable to its seam. */\n name?: string;\n}\nclass ErrorBoundary extends React.Component<\n ErrorBoundaryProps,\n ErrorBoundaryState\n> {\n constructor(props: ErrorBoundaryProps) {\n super(props);\n this.state = { error: null, errorInfo: null };\n }\n\n /**\n * Recovers during the render phase. Without this React renders the boundary\n * with `null` children and waits for `componentDidCatch` to schedule a\n * fallback, and a second error in the same batch escalates past the boundary\n * to the root, unmounting the whole tree.\n */\n static getDerivedStateFromError(\n error: Error\n ): Pick<ErrorBoundaryState, \"error\"> {\n return { error };\n }\n\n override componentDidCatch(error: Error, errorInfo: ErrorInfo) {\n // A boundary that swallows the cause leaves nothing to diagnose, so the\n // error is reported before the fallback replaces the subtree.\n const seam = this.props.name ? ` in ${this.props.name}` : \"\";\n // The message carries the cause inline: an Error passed as a bare argument\n // serialises to `{}` under some log sinks.\n log.error(\n `Error boundary caught${seam}: ${error?.message ?? error}`,\n error,\n errorInfo.componentStack\n );\n this.setState({\n error: error,\n errorInfo: errorInfo,\n });\n }\n\n override render() {\n // Keyed on `error` because that is what the render phase sets; `errorInfo`\n // only arrives later, from the commit phase.\n if (this.state.error) {\n // Error path\n return (\n this.props.fallback || (\n <div>\n <h2>Something went wrong.</h2>\n <details style={{ whiteSpace: `pre-wrap` }}>\n {this.state.error.toString()}\n <br />\n {this.state.errorInfo?.componentStack}\n </details>\n </div>\n )\n );\n }\n // Normally, just render children\n return this.props.children;\n }\n}\n\nexport default ErrorBoundary;\n","import { css } from \"@emotion/react\";\ntype Status = \"error\" | \"warn\" | \"normal\";\ninterface Props {\n value: number;\n title?: JSX.Element;\n subtitle?: string;\n status?: Status;\n}\n\nconst statusMap: Record<Status, string> = {\n normal: \"#B5F7F6\",\n warn: \"#F3D78A\",\n error: \"#FC8486\",\n};\nexport const ProgressBar = ({\n value = 0,\n title,\n status = \"normal\",\n subtitle,\n}: Props) => {\n const progressBarContainer = css`\n display: flex;\n flex-direction: column;\n `;\n const progressContainer = css`\n position: relative;\n height: 18px;\n width: 100%;\n background-color: #ddd;\n border-radius: 5px;\n overflow: hidden;\n `;\n\n const titleContainer = css`\n position: absolute;\n top: 50%; /* position the top edge of the element at the middle of the parent */\n left: 50%; /* position the left edge of the element at the middle of the parent */\n z-index: 5;\n transform: translate(-50%, -50%);\n font-size: smaller;\n `;\n\n const progress = css`\n width: ${value}%;\n height: 35px;\n background-color: ${statusMap[status]};\n text-align: center;\n line-height: 32px;\n color: black;\n `;\n\n const indeterminate = css`\n animation: indeterminateAnimation 1s infinite linear;\n transform-origin: 0% 50%;\n @keyframes indeterminateAnimation {\n 0% {\n transform: translateX(0) scaleX(0);\n }\n 40% {\n transform: translateX(0) scaleX(0.4);\n }\n 100% {\n transform: translateX(100%) scaleX(0.5);\n }\n }\n `;\n\n return (\n <div css={progressBarContainer}>\n <div css={progressContainer}>\n <div css={titleContainer}>{title}</div>\n <div css={[progress, value < 0 ? indeterminate : \"\"]}></div>\n </div>\n <div>{subtitle}</div>\n </div>\n );\n};\n","import {\n createContext,\n PropsWithChildren,\n useCallback,\n useContext,\n useState,\n} from \"react\";\nimport { IKosDataModel } from \"../../../../core\";\n\ninterface KosModelContextProps {\n model?: IKosDataModel;\n setModel: (model: IKosDataModel) => boolean;\n}\n\nconst defaultProps: KosModelContextProps = {\n setModel: () => false,\n};\n\nexport const KosModelContext =\n createContext<KosModelContextProps>(defaultProps);\n\nexport const useContextModel = <T extends IKosDataModel>(): T | undefined => {\n const context = useContext(KosModelContext);\n if (context == undefined) {\n throw new Error(`useModels must be used within a KosModelProvider`);\n }\n return context.model as T;\n};\n\nexport const KosModelProvider: React.FunctionComponent<PropsWithChildren> = ({\n children,\n}) => {\n const [model, setModel] = useState<IKosDataModel>();\n const setKosModel = useCallback(\n (kosModel: IKosDataModel) => {\n setModel(kosModel);\n return true;\n },\n [setModel]\n );\n return (\n <KosModelContext.Provider value={{ model, setModel: setKosModel }}>\n {children}\n </KosModelContext.Provider>\n );\n};\n","import {\n createContext,\n PropsWithChildren,\n useCallback,\n useContext,\n useMemo,\n useState,\n} from \"react\";\nimport { getKosModelSync, IKosDataModel, KosLog } from \"../../../../core\";\n\ninterface KosNestedModelContextProps {\n models: IKosDataModel[];\n addModel: (model: IKosDataModel) => void;\n}\n\nconst log = KosLog.createLogger({ name: \"kos-model-hierarchy-context\" });\nconst defaultNestedProps: KosNestedModelContextProps = {\n models: [],\n addModel: () => {\n log.debug(\"Default implementation being used. Do Nothing.\");\n },\n};\n\nexport const NestedModelContext =\n createContext<KosNestedModelContextProps>(defaultNestedProps);\n\nexport const KosModelCollectionProvider: React.FunctionComponent<\n PropsWithChildren\n> = ({ children }) => {\n const [models, setModels] = useState<IKosDataModel[]>([]);\n const addModel = useCallback(\n (model: IKosDataModel) => {\n if (!models.includes(model)) {\n log.debug(\"adding to hierarchy context\", model.id);\n setModels((prevModels) => [...prevModels, model]);\n }\n },\n [models]\n );\n return (\n <NestedModelContext.Provider value={{ models, addModel }}>\n {children}\n </NestedModelContext.Provider>\n );\n};\n\ninterface ModelHierarchyProps {\n filter?: (model: IKosDataModel) => boolean;\n}\n\nconst DEFAULT_FILTER = () => true;\nexport const useContextModelHierarchy = (\n props?: ModelHierarchyProps\n): IKosDataModel[] => {\n const context = useContext(NestedModelContext);\n if (!context) {\n throw new Error(\n `useContextModelHierarchy must be used within a KosModelCollectionProvider`\n );\n }\n\n const filter = props?.filter || DEFAULT_FILTER;\n const filteredModels = useMemo(\n () => context.models.filter(filter),\n [context.models, filter]\n );\n return filteredModels;\n};\n\nexport const useModelFromHierarchy = <T extends IKosDataModel = IKosDataModel>(\n type: string\n): T | undefined => {\n const context = useContextModelHierarchy({\n filter: (model) => {\n const _model = getKosModelSync(model.id);\n return _model?.type === type;\n },\n });\n return context[0] as T;\n};\n","import {\n PropsWithChildren,\n Suspense,\n useContext,\n useEffect,\n useState,\n} from \"react\";\nimport { IKosDataModel, KosLog } from \"../../../core\";\nimport { ErrorBoundaryWithFallback } from \"../error-boundary\";\nimport { ErrorBoundaryProps } from \"../error-boundary/error-boundary\";\nimport {\n KosModelContext,\n KosModelProvider,\n} from \"./contexts/kos-model-context\";\nimport { NestedModelContext } from \"./contexts/kos-model-hierarchy-context\";\n\nconst log = KosLog.createLogger({ name: \"kos-model-loader\" });\nexport interface KosModelLoaderProps {\n model?: IKosDataModel;\n ready: boolean;\n error?: string;\n loading?: React.ReactElement;\n}\n\nconst DefaultLoader = () => <div></div>;\n\nexport const KosModelLoader: React.FunctionComponent<\n PropsWithChildren<ErrorBoundaryProps & KosModelLoaderProps>\n> = ({ fallback, children, ...modelProps }) => (\n <KosModelProvider>\n <ErrorBoundaryWithFallback fallback={fallback}>\n <Suspense>\n <KosModelLoaderDisplay {...modelProps}>\n {children}\n </KosModelLoaderDisplay>\n </Suspense>\n </ErrorBoundaryWithFallback>\n </KosModelProvider>\n);\nexport const KosModelLoaderDisplay: React.FunctionComponent<\n PropsWithChildren<KosModelLoaderProps>\n> = (props) => {\n const [model, setCurrentModel] = useState<IKosDataModel>();\n const [isReady, setIsReady] = useState(false);\n const { setModel } = useContext(KosModelContext);\n const hierarchyContext = useContext(NestedModelContext);\n useEffect(() => {\n if (props.model) {\n setCurrentModel(props.model);\n setModel(props.model);\n setIsReady(true);\n if (hierarchyContext) {\n hierarchyContext.addModel(props.model);\n }\n }\n }, [hierarchyContext, props.model, setModel]);\n\n if (props.error) {\n log.error(props.error);\n throw new Error(props.error);\n }\n\n const loader = props.loading || <DefaultLoader></DefaultLoader>;\n return <>{model && isReady ? props.children : loader}</>;\n};\n","import type { IKosCoreManager, IKosRegistry } from \"../../core\";\nimport { KosCore, wrapPromise } from \"../../core\";\n\nexport function fetchKosCore(registration: IKosRegistry, alias?: string) {\n const kosCore = KosCore.create(registration, false, alias);\n const promise = kosCore.whenReady().then(() => kosCore);\n return wrapPromise<IKosCoreManager>(promise);\n}\n","import { observer } from \"mobx-react-lite\";\nimport React, { useEffect, useMemo } from \"react\";\nimport { IKosCoreManager, IKosRegistry, kosAutoEffect } from \"../../core\";\nimport { fetchKosCore } from \"./fetch-kos-core\";\n\nexport interface ProviderProps {\n children?: React.ReactNode;\n}\n\ninterface IKosContext {\n kosCore: IKosCoreManager;\n online: boolean;\n}\nconst KosContext = React.createContext<IKosContext | undefined>(undefined);\nconst initKosProvider = (\n registration: IKosRegistry = { models: {}, preloadModels: [] },\n alias?: string\n) => {\n const resource = fetchKosCore(registration, alias);\n\n const KosCoreContextProvider: React.FC<ProviderProps> = ({ children }) => {\n const kosCore = resource.read();\n const [online, setOnline] = React.useState(kosCore.isOnline);\n\n useEffect(() => {\n const disposer = kosAutoEffect(() => {\n setOnline(kosCore.isOnline);\n });\n\n return () => {\n disposer();\n };\n }, [kosCore]);\n\n const value = useMemo<IKosContext>(() => {\n return { kosCore, online };\n }, [kosCore, online]);\n\n return <KosContext.Provider value={value}>{children}</KosContext.Provider>;\n };\n\n return { KosCoreContextProvider: observer(KosCoreContextProvider) };\n};\n\nexport const useKosCore = () => {\n const context = React.useContext(KosContext);\n if (context === undefined) {\n throw new Error(`useKosCore must be used within a KosCoreContextProvider`);\n }\n\n return context;\n};\n\nexport default initKosProvider;\n","/**\n * sessionStorage key used to signal to the next page load that a\n * reload-on-disconnect recovery just occurred. Overlay components read it\n * on mount so the \"reconnecting\" UI can persist across the reload without\n * a visible gap.\n *\n * @kosService core.reload-on-disconnect-policy\n * @kosApiLevel 23\n */\nexport const KOS_RECOVERING_SESSION_KEY = \"kos:recovering\";\n","import { useEffect, useRef } from \"react\";\nimport { EventBus } from \"../../common\";\nimport { WebSocketEvents } from \"../../core/core/transport/base-message-transport\";\nimport { KosLog } from \"../../core/core/log\";\nimport { KOS_RECOVERING_SESSION_KEY } from \"./constants\";\n\n/**\n * Metadata the policy records about the triggering disconnect.\n *\n * @kosService core.reload-on-disconnect-policy\n * @kosApiLevel 23\n */\nexport interface ReloadOnDisconnectInfo {\n code: number;\n reason: string;\n wasClean: boolean;\n at: number;\n}\n\n/**\n * Props for ReloadOnDisconnectPolicy.\n *\n * @kosService core.reload-on-disconnect-policy\n * @kosApiLevel 23\n */\nexport interface ReloadOnDisconnectPolicyProps {\n /**\n * Delay before reloading, in milliseconds. Lets rapid-fire reconnect\n * attempts settle without stacking reloads. Default: 3000.\n */\n graceMs?: number;\n /**\n * Called synchronously immediately before the reload. Useful for\n * telemetry. Keep it synchronous, since the reload may preempt async work.\n */\n onBeforeReload?: (info: ReloadOnDisconnectInfo) => void;\n /**\n * Test seam. Replace the reload function. Defaults to\n * () => window.location.reload().\n */\n reloadFn?: () => void;\n}\n\nconst DEFAULT_GRACE_MS = 3000;\n\nconst defaultReloadFn = () => {\n window.location.reload();\n};\n\n/**\n * Mounts a connection-recovery policy: when the WebSocket disconnects, wait\n * a short grace window, record the disconnect in sessionStorage, then\n * `window.location.reload()` the page. Renders nothing.\n *\n * The grace window only de-bounces rapid disconnect/reconnect flapping. Even\n * a sub-second reconnect triggers the reload, because the data layer cannot\n * guarantee freshness across the gap.\n *\n * Apps that reconcile on reconnect instead (Studio, for example) do not mount\n * this policy.\n *\n * Pair with an overlay that reads `KOS_RECOVERING_SESSION_KEY` on mount to\n * keep a \"reconnecting\" message visible across the reload boundary.\n *\n * @kosService core.reload-on-disconnect-policy\n * @kosApiLevel 23\n */\nexport const ReloadOnDisconnectPolicy: React.FC<\n ReloadOnDisconnectPolicyProps\n> = ({\n graceMs = DEFAULT_GRACE_MS,\n onBeforeReload,\n reloadFn = defaultReloadFn,\n}) => {\n const pendingReloadRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n useEffect(() => {\n const { unsubscribe } = EventBus.subscribe(\n WebSocketEvents.DISCONNECTED,\n (msg) => {\n if (pendingReloadRef.current) {\n return;\n }\n\n const payload = msg?.body as\n | { code: number; reason: string; wasClean: boolean }\n | undefined;\n if (!payload || typeof payload.code !== \"number\") {\n return;\n }\n\n const info: ReloadOnDisconnectInfo = {\n code: payload.code,\n reason: payload.reason,\n wasClean: payload.wasClean,\n at: Date.now(),\n };\n\n try {\n sessionStorage.setItem(\n KOS_RECOVERING_SESSION_KEY,\n JSON.stringify(info)\n );\n } catch (err) {\n KosLog.warn(\n \"ReloadOnDisconnectPolicy: failed to write sessionStorage\",\n err\n );\n }\n\n KosLog.warn(\n `ReloadOnDisconnectPolicy: scheduling reload in ${graceMs}ms ` +\n `(code=${info.code}, wasClean=${info.wasClean})`\n );\n\n pendingReloadRef.current = setTimeout(() => {\n pendingReloadRef.current = null;\n try {\n onBeforeReload?.(info);\n } catch (err) {\n KosLog.error(\"ReloadOnDisconnectPolicy: onBeforeReload threw\", err);\n }\n reloadFn();\n }, graceMs);\n }\n );\n\n return () => {\n unsubscribe();\n if (pendingReloadRef.current) {\n clearTimeout(pendingReloadRef.current);\n pendingReloadRef.current = null;\n }\n };\n }, [graceMs, onBeforeReload, reloadFn]);\n\n return null;\n};\n","import { useEffect, useState } from \"react\";\nimport { EventBus } from \"../../../common\";\nimport { WebSocketEvents } from \"../../../core/core/transport/base-message-transport\";\nimport { useKosCore } from \"../../contexts/kos-core-context\";\nimport {\n KOS_RECOVERING_SESSION_KEY,\n type ReloadOnDisconnectInfo,\n} from \"../../policies\";\n\n/**\n * Snapshot of the overlay's state, returned by useReconnectingOverlayState.\n *\n * @kosService core.use-reconnecting-overlay-state\n * @kosApiLevel 23\n */\nexport interface ReconnectingOverlayState {\n /** Whether the overlay should currently be displayed. */\n visible: boolean;\n /** Details of the disconnect, if one is being recovered from. */\n info: ReloadOnDisconnectInfo | null;\n /** Milliseconds since the tracked disconnect, or null. */\n sinceMs: number | null;\n /** Force-hide the overlay. Does not clear `info`. */\n dismiss: () => void;\n}\n\n/**\n * Options for useReconnectingOverlayState.\n *\n * @kosService core.use-reconnecting-overlay-state\n * @kosApiLevel 23\n */\nexport interface UseReconnectingOverlayStateOptions {\n /**\n * Predicate evaluated after a CONNECTED event. When true, the overlay\n * hides. Defaults to `({ online }) => online`, i.e. hide as soon as KOS\n * Core reports online. Apps that need to wait for specific model state\n * can pass a stricter predicate.\n */\n isReady?: (state: {\n online: boolean;\n info: ReloadOnDisconnectInfo | null;\n }) => boolean;\n /**\n * Whether to read `sessionStorage[KOS_RECOVERING_SESSION_KEY]` on mount\n * to carry overlay state across a page reload. Default: true. Set false\n * for apps that don't use the reload-on-disconnect policy.\n */\n readSessionStorage?: boolean;\n}\n\nconst defaultIsReady = ({ online }: { online: boolean }) => online;\n\nconst readRecoveringInfo = (): ReloadOnDisconnectInfo | null => {\n try {\n const raw = sessionStorage.getItem(KOS_RECOVERING_SESSION_KEY);\n if (!raw) return null;\n sessionStorage.removeItem(KOS_RECOVERING_SESSION_KEY);\n const parsed = JSON.parse(raw);\n if (\n parsed &&\n typeof parsed === \"object\" &&\n typeof parsed.code === \"number\"\n ) {\n return parsed as ReloadOnDisconnectInfo;\n }\n } catch {\n // sessionStorage may be unavailable or payload malformed; ignore\n }\n return null;\n};\n\n/**\n * Headless state hook for the reconnecting overlay.\n *\n * Becomes `visible` when a WebSocket disconnect is observed, or when the\n * page load carries a `KOS_RECOVERING_SESSION_KEY` in sessionStorage from\n * a prior reload-on-disconnect cycle. Becomes hidden when the ready\n * predicate reports the app is fully connected again.\n *\n * Returns { visible, info, sinceMs, dismiss }. Apps pair this with their\n * own overlay markup, or use the default `<ReconnectingOverlay />`.\n *\n * @kosService core.use-reconnecting-overlay-state\n * @kosApiLevel 23\n */\nexport const useReconnectingOverlayState = (\n options: UseReconnectingOverlayStateOptions = {}\n): ReconnectingOverlayState => {\n const { isReady = defaultIsReady, readSessionStorage = true } = options;\n const { online } = useKosCore();\n\n const [info, setInfo] = useState<ReloadOnDisconnectInfo | null>(() =>\n readSessionStorage ? readRecoveringInfo() : null\n );\n const [dismissed, setDismissed] = useState(false);\n\n useEffect(() => {\n const { unsubscribe } = EventBus.subscribe(\n WebSocketEvents.DISCONNECTED,\n (msg) => {\n const payload = msg?.body as\n | { code: number; reason: string; wasClean: boolean }\n | undefined;\n if (!payload || typeof payload.code !== \"number\") return;\n setInfo({\n code: payload.code,\n reason: payload.reason,\n wasClean: payload.wasClean,\n at: Date.now(),\n });\n setDismissed(false);\n }\n );\n return () => {\n unsubscribe();\n };\n }, []);\n\n const ready = isReady({ online, info });\n const visible = !dismissed && !!info && !ready;\n\n return {\n visible,\n info,\n sinceMs: info ? Date.now() - info.at : null,\n dismiss: () => setDismissed(true),\n };\n};\n","import { css, keyframes } from \"@emotion/react\";\n\nconst spin = keyframes`\n to { transform: rotate(360deg); }\n`;\n\nexport const overlayRoot = css`\n position: fixed;\n inset: 0;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n gap: 16px;\n background: rgba(0, 0, 0, 0.72);\n color: #ffffff;\n font-family: system-ui, -apple-system, \"Segoe UI\", sans-serif;\n z-index: 2147483647;\n pointer-events: auto;\n user-select: none;\n`;\n\nexport const spinner = css`\n width: 48px;\n height: 48px;\n border-radius: 50%;\n border: 4px solid rgba(255, 255, 255, 0.25);\n border-top-color: #ffffff;\n animation: ${spin} 1s linear infinite;\n`;\n\nexport const message = css`\n font-size: 18px;\n font-weight: 500;\n letter-spacing: 0.02em;\n`;\n","import type React from \"react\";\nimport {\n useReconnectingOverlayState,\n type ReconnectingOverlayState,\n type UseReconnectingOverlayStateOptions,\n} from \"./use-reconnecting-overlay-state\";\nimport { message, overlayRoot, spinner } from \"./reconnecting-overlay-styles\";\n\nexport {\n useReconnectingOverlayState,\n type ReconnectingOverlayState,\n type UseReconnectingOverlayStateOptions,\n} from \"./use-reconnecting-overlay-state\";\n\n/**\n * Props for the default ReconnectingOverlay.\n *\n * @kosService core.reconnecting-overlay\n * @kosApiLevel 23\n */\nexport interface ReconnectingOverlayProps\n extends UseReconnectingOverlayStateOptions {\n /** Override the default message (\"Reconnecting…\"). */\n messageText?: string;\n /**\n * Fully replace the rendered content with a custom renderer. Receives the\n * overlay state. If provided, the default layout (spinner + message) is\n * not rendered.\n */\n renderContent?: (state: ReconnectingOverlayState) => React.ReactNode;\n className?: string;\n}\n\n/**\n * Minimal, unbranded overlay that displays while the app is recovering\n * from a WebSocket disconnect (or immediately after a reload triggered by\n * ReloadOnDisconnectPolicy). Pair with that policy — or use in isolation\n * for apps that want to show the overlay without reloading.\n *\n * Apps with design-system requirements should wrap\n * `useReconnectingOverlayState` in their own component rather than relying\n * on these default styles.\n *\n * @kosService core.reconnecting-overlay\n * @kosApiLevel 23\n */\nexport const ReconnectingOverlay: React.FC<ReconnectingOverlayProps> = ({\n messageText = \"Reconnecting…\",\n renderContent,\n className,\n isReady,\n readSessionStorage,\n}) => {\n const state = useReconnectingOverlayState({ isReady, readSessionStorage });\n\n if (!state.visible) return null;\n\n return (\n <div\n css={overlayRoot}\n className={className}\n role=\"alertdialog\"\n aria-live=\"assertive\"\n aria-label=\"Reconnecting\"\n >\n {renderContent ? (\n renderContent(state)\n ) : (\n <>\n <div css={spinner} aria-hidden=\"true\" />\n <div css={message}>{messageText}</div>\n </>\n )}\n </div>\n );\n};\n","import { useEffect, useState } from \"react\";\nimport { KosCore, kosAutoEffect, type IKosCoreManager } from \"../../../core\";\n\n/**\n * Connection status shown by ConnectionDevButton.\n *\n * @kosService core.use-connection-dev-state\n * @kosApiLevel 25\n */\nexport type ConnectionDevStatus = \"online\" | \"offline\" | \"reconnecting\";\n\n/**\n * Snapshot of the connection, returned by useConnectionDevState.\n *\n * @kosService core.use-connection-dev-state\n * @kosApiLevel 25\n */\nexport interface ConnectionDevState {\n /**\n * `reconnecting` while KOS Core reloads or runs its reconnect sequence,\n * otherwise `online` or `offline` from the core's connection.\n */\n status: ConnectionDevStatus;\n}\n\nconst readStatus = (core: IKosCoreManager): ConnectionDevStatus => {\n if (core.reloading) return \"reconnecting\";\n return core.isOnline ? \"online\" : \"offline\";\n};\n\n/**\n * Headless state hook for ConnectionDevButton. Tracks KOS Core's `isOnline`\n * and `reloading` reactively and reports them as one status.\n *\n * @kosService core.use-connection-dev-state\n * @kosApiLevel 25\n */\nexport const useConnectionDevState = (): ConnectionDevState => {\n const [status, setStatus] = useState<ConnectionDevStatus>(() =>\n readStatus(KosCore.getInstance())\n );\n\n useEffect(() => {\n const core = KosCore.getInstance();\n const disposer = kosAutoEffect(() => {\n setStatus(readStatus(core));\n });\n return () => {\n disposer();\n };\n }, []);\n\n return { status };\n};\n","import { css } from \"@emotion/react\";\n\nconst OFFSET = \"16px\";\n\nexport const buttonRoot = css`\n position: fixed;\n display: inline-flex;\n align-items: center;\n gap: 8px;\n padding: 6px 12px;\n border: 1px solid rgba(255, 255, 255, 0.25);\n border-radius: 6px;\n background: rgba(0, 0, 0, 0.72);\n color: #ffffff;\n font-family: system-ui, -apple-system, \"Segoe UI\", sans-serif;\n font-size: 12px;\n line-height: 1.4;\n cursor: pointer;\n z-index: 2147483646;\n\n &:disabled {\n cursor: default;\n opacity: 0.6;\n }\n`;\n\nexport const positions = {\n \"bottom-left\": css`\n bottom: ${OFFSET};\n left: ${OFFSET};\n `,\n \"bottom-right\": css`\n bottom: ${OFFSET};\n right: ${OFFSET};\n `,\n \"top-left\": css`\n top: ${OFFSET};\n left: ${OFFSET};\n `,\n \"top-right\": css`\n top: ${OFFSET};\n right: ${OFFSET};\n `,\n} as const;\n\nexport const statusText = css`\n font-weight: 600;\n text-transform: uppercase;\n letter-spacing: 0.04em;\n`;\n","import type React from \"react\";\nimport { KosCore } from \"../../../core\";\nimport {\n useConnectionDevState,\n type ConnectionDevState,\n} from \"./use-connection-dev-state\";\nimport {\n buttonRoot,\n positions,\n statusText,\n} from \"./connection-dev-button-styles\";\n\nexport {\n useConnectionDevState,\n type ConnectionDevState,\n type ConnectionDevStatus,\n} from \"./use-connection-dev-state\";\n\n/**\n * Props for ConnectionDevButton.\n *\n * @kosService core.connection-dev-button\n * @kosApiLevel 25\n */\nexport interface ConnectionDevButtonProps {\n /** Screen corner the button is fixed to. Default: \"bottom-right\". */\n position?: \"bottom-left\" | \"bottom-right\" | \"top-left\" | \"top-right\";\n /** Button label. Default: \"Drop connection\". */\n label?: string;\n className?: string;\n /**\n * Fully replace the button's content with a custom renderer. Receives the\n * connection state. If provided, the default label and status are not\n * rendered.\n */\n renderContent?: (state: ConnectionDevState) => React.ReactNode;\n}\n\n/**\n * Minimal, unbranded development button that drops the KOS websocket so the\n * reconnect path can be exercised from any KOS application. Shows the live\n * connection status and, on click, calls the transport's `dropConnection()`;\n * the transport reconnects on its own and KOS Core runs its reconnect\n * sequence. Disabled while the core is not online.\n *\n * Pair with ReconnectingOverlay to see the reconnect as users do.\n *\n * @kosService core.connection-dev-button\n * @kosApiLevel 25\n */\nexport const ConnectionDevButton: React.FC<ConnectionDevButtonProps> = ({\n position = \"bottom-right\",\n label = \"Drop connection\",\n className,\n renderContent,\n}) => {\n const state = useConnectionDevState();\n\n return (\n <button\n type=\"button\"\n css={[buttonRoot, positions[position]]}\n className={className}\n disabled={state.status !== \"online\"}\n onClick={() => KosCore.getInstance().transport.dropConnection()}\n >\n {renderContent ? (\n renderContent(state)\n ) : (\n <>\n <span>{label}</span>\n <span css={statusText}>{state.status}</span>\n </>\n )}\n </button>\n );\n};\n","import React from \"react\";\n\ninterface HeaderTranslations {\n title: string;\n createLabel: string;\n deleteLabel: string;\n}\ninterface ModalTranslations {\n okText: string;\n cancelText: string;\n title: string;\n}\nexport interface Translations {\n header?: Partial<HeaderTranslations>;\n createModal?: Partial<ModalTranslations>;\n}\nconst DEFAULT_TRANSLATIONS: ContextTranslations = {\n header: {\n title: \"Model\",\n createLabel: \"Create new Model\",\n deleteLabel: \"Delete\",\n },\n createModal: {\n okText: \"OK\",\n cancelText: \"Cancel\",\n title: \"Create New Model\",\n },\n};\n\ninterface ContextTranslations {\n header: HeaderTranslations;\n createModal: ModalTranslations;\n}\ninterface Props {\n translations?: Translations;\n children: React.ReactNode;\n}\nconst CreateModelTranslationsContext =\n React.createContext<ContextTranslations>(DEFAULT_TRANSLATIONS);\n\nconst CreateModelTranslationsProvider: React.FC<Props> = ({\n translations = DEFAULT_TRANSLATIONS,\n children,\n}) => {\n const merged: ContextTranslations = {\n header: { ...DEFAULT_TRANSLATIONS.header, ...translations.header },\n createModal: {\n ...DEFAULT_TRANSLATIONS.createModal,\n ...translations.createModal,\n },\n };\n return (\n <CreateModelTranslationsContext.Provider value={merged}>\n {children}\n </CreateModelTranslationsContext.Provider>\n );\n};\n\nexport { CreateModelTranslationsContext, CreateModelTranslationsProvider };\n","import {\n clearModelHookCacheEntry,\n destroyKosModel,\n modelHookCache,\n IKosCoreManager,\n IKosDataModel,\n kosAutoEffect,\n KosCore,\n ModelFactory,\n} from \"../../core\";\n\nimport { useEffect, useState } from \"react\";\nimport { useKosCore } from \"../contexts/kos-core-context\";\n\nimport type { IReactionDisposer } from \"mobx\";\nimport { KosModelEvents, KosModelState } from \"../../core\";\nimport { isUpdateable } from \"../../core/core/registration/model-registration\";\nimport { KosModelLoader } from \"../components/kos-model-loader\";\ninterface Options<T extends IKosDataModel, O extends Object = {}> {\n modelId?: string;\n factory?: ModelFactory<T, O>;\n modelType?: string;\n options?: O;\n activate?: boolean;\n destroyOnUnmount?: boolean;\n forceUpdate?: boolean;\n}\n\nconst MAX_RETRIES = 8;\nconst waitForRetry = (depth = 0) =>\n new Promise((resolve) => {\n setTimeout(() => {\n resolve(true);\n }, 2 ** depth * 10);\n });\n\n/**\n * Reads a model out of the suspense cache, suspending or rethrowing as the\n * entry requires. Exported for tests.\n */\nexport function readModelHookEntry(\n key: string,\n fetcher: () => Promise<unknown>\n) {\n const entry = modelHookCache.get(key);\n\n if (entry) {\n if (entry.status === \"finished\") {\n const kosModel = KosCore.getInstance().modelManager.getModelById(key);\n return { kosModel, model: kosModel?.modelData };\n }\n\n // An error entry has no promise to suspend on, so rethrow the cause.\n if (entry.status === \"error\") {\n throw entry.error;\n }\n\n throw entry.promise;\n }\n\n const promise = fetcher().then(\n () => {\n modelHookCache.set(key, { status: \"finished\", key });\n },\n (error) => {\n modelHookCache.set(key, { status: \"error\", error });\n throw error;\n }\n );\n\n modelHookCache.set(key, { status: \"pending\", promise });\n\n throw promise;\n}\n\nfunction useSuspenseData<T>(\n key: string,\n fetcher: (...args: any[]) => Promise<T>\n) {\n // Attempt to fetch the data (or retrieve from cache), throwing a promise if it's not ready.\n const data = readModelHookEntry(key, fetcher) as T;\n\n // If the data is available, return it.\n return data;\n}\n\nasync function fetchModel<T extends IKosDataModel, O extends Object = {}>(\n kosCore: IKosCoreManager,\n modelOptions: Options<T, O>\n) {\n const { modelId, factory, modelType, options } = modelOptions;\n let retryCount = 0;\n await kosCore.whenReady();\n let _model: T;\n if (options) {\n const _factory =\n typeof modelType === \"string\"\n ? kosCore.modelManager.getModelFactory<T>(modelType)\n : factory;\n\n if (!_factory) {\n throw Error(\"No Factory Specified. Cannot create a new instance\");\n }\n // build the model first\n _model = _factory.build(modelId!, options);\n }\n const kosModel = kosCore.modelManager.getModelById<T>(modelId!);\n\n if (!kosModel) {\n if (retryCount > MAX_RETRIES) {\n throw Error(`KOS Model ${modelId} has not been found`);\n }\n\n await waitForRetry(retryCount);\n const count = retryCount + 1;\n retryCount = count;\n }\n await kosModel?.whenReady();\n\n if (kosModel) {\n _model = kosModel.modelData;\n return { kosModel, model: _model };\n }\n\n return { kosModel: undefined, model: undefined };\n}\n/**\n * Primary hook for consuming KOS models in React components.\n *\n * @kosService core.use-kos-model\n * @kosApiLevel 2\n */\nexport const useKosModel = <T extends IKosDataModel, O extends Object = {}>(\n modelOptions: Options<T, O>\n) => {\n const { modelId, modelType, activate, destroyOnUnmount } = modelOptions;\n const kosCoreContext = useKosCore();\n const [ready, setReady] = useState(false);\n\n const [error, setError] = useState<string | undefined>();\n\n const { kosModel, model } = useSuspenseData(\n modelId || modelType || \"\",\n () => {\n const response = fetchModel(kosCoreContext.kosCore, modelOptions);\n return response;\n }\n );\n\n useEffect(() => {\n if (modelOptions.forceUpdate && model) {\n if (isUpdateable(model)) {\n model.updateModel(modelOptions.options || {});\n }\n }\n }, [model]);\n useEffect(() => {\n async function waitForModel() {\n try {\n await kosCoreContext.kosCore.whenReady();\n if (activate) {\n await kosModel?.fsm.transitionTo(\n KosModelEvents.GO_ACTIVE,\n KosModelState.ACTIVE\n );\n }\n setReady(true);\n return kosModel;\n } catch (e) {\n setError((e as Error).message);\n throw e;\n }\n }\n\n let disposer: IReactionDisposer | undefined = undefined;\n if (kosCoreContext.kosCore && modelId) {\n waitForModel()\n .then((kosModel) => {\n disposer = kosAutoEffect(() => {\n const _ready = kosModel?.status === KosModelState.READY;\n setReady(_ready);\n });\n })\n .catch((e) => {\n console.error(e);\n });\n }\n return () => {\n if (activate) {\n if (model?.id) {\n const kosModel = kosCoreContext.kosCore.modelManager.getModelById<T>(\n model.id\n );\n\n kosModel?.fsm\n .transitionTo(KosModelEvents.GO_INACTIVE, KosModelState.INACTIVE)\n .then(() => {\n if (destroyOnUnmount) {\n const modelId = model.id;\n destroyKosModel(model).then(() => {\n clearModelHookCacheEntry(modelId);\n disposer?.();\n });\n }\n });\n }\n } else {\n if (destroyOnUnmount && model) {\n destroyKosModel(model).then(() => {\n clearModelHookCacheEntry(modelId);\n disposer?.();\n });\n }\n }\n };\n }, [\n activate,\n destroyOnUnmount,\n kosCoreContext.kosCore,\n kosModel,\n model,\n modelId,\n ]);\n\n return {\n model,\n ready,\n error,\n status: {\n model,\n ready,\n error,\n },\n KosModelLoader,\n };\n};\n","import { KosTime, KosTimeModel } from \"../../../models\";\nimport { useKosModel } from \"../use-kos-model\";\n\n/**\n * Hook for accessing the KOS time model.\n *\n * @kosService core.use-kos-time\n * @kosApiLevel 2\n */\nexport const useKosTime = () => {\n const modelId = KosTime.type;\n const result = useKosModel<KosTimeModel>({\n modelId,\n modelType: KosTime.type,\n options: {},\n });\n\n return result;\n};\n","import { PropsWithChildren, createContext, useContext, useMemo } from \"react\";\nimport { KosTimeModel } from \"../../../models\";\nimport { useKosTime } from \"../../hooks/kos-time/use-kos-time\";\n\ninterface KosTimeType {\n model?: KosTimeModel;\n}\nexport const KosTimeContext = createContext<KosTimeType | undefined>(undefined);\n\ninterface KosTimeProviderProps {}\n\nexport const KosTimeProvider: React.FunctionComponent<\n PropsWithChildren<KosTimeProviderProps>\n> = ({ children }) => {\n const { model, ready } = useKosTime();\n const value: KosTimeType = useMemo(() => {\n if (ready && model) {\n return { model };\n }\n return {};\n }, [ready, model]);\n return (\n <KosTimeContext.Provider value={value}>{children}</KosTimeContext.Provider>\n );\n};\nexport const useKosTimeContext = () => {\n const context = useContext(KosTimeContext);\n if (!context) {\n throw new Error(\"useKosTimeContext must be used within a KosTimeProvider\");\n }\n return context;\n};\n","import { SoftwareInfo, type SoftwareInfoModel } from \"../../../models\";\nimport { useKosModel } from \"../use-kos-model\";\n\n/**\n * Hook for accessing the KOS software info model.\n *\n * @kosService core.use-software-info\n * @kosApiLevel 2\n */\nexport const useSoftwareInfo = () => {\n const modelId = SoftwareInfo.type;\n const result = useKosModel<SoftwareInfoModel>({\n modelId,\n modelType: SoftwareInfo.type,\n options: {},\n });\n\n return result;\n};\n","import type { SoftwareInfoModel } from \"../../../models\";\nimport { useSoftwareInfo } from \"./use-software-info\";\n\ninterface SoftwareInfoProps {\n softwareInfo: SoftwareInfoModel;\n}\n// react HOC to provide a SoftwareInfo to a component\nexport function withSoftwareInfo<\n T extends SoftwareInfoProps = SoftwareInfoProps\n>(WrappedComponent: React.ComponentType<T>) {\n return () => (props: Omit<T, keyof SoftwareInfoProps>) => {\n const { model, status, KosModelLoader } = useSoftwareInfo();\n\n return (\n <KosModelLoader {...status}>\n <WrappedComponent {...(props as T)} softwareInfo={model} />\n </KosModelLoader>\n );\n };\n}\n","import { PropsWithChildren, createContext, useContext, useMemo } from \"react\";\nimport type { SoftwareInfoModel } from \"../../../models\";\nimport { useSoftwareInfo } from \"../../hooks/software-info\";\n\ninterface SoftwareInfoType {\n model?: SoftwareInfoModel;\n}\nexport const SoftwareInfoContext = createContext<SoftwareInfoType | undefined>(\n undefined\n);\n\ninterface SoftwareInfoProviderProps {\n id: string;\n}\n\nexport const SoftwareInfoProvider: React.FunctionComponent<\n PropsWithChildren<SoftwareInfoProviderProps>\n> = ({ children }) => {\n const { model, ready } = useSoftwareInfo();\n const value: SoftwareInfoType = useMemo(() => {\n if (ready && model) {\n return { model };\n }\n return {};\n }, [ready, model]);\n return (\n <SoftwareInfoContext.Provider value={value}>\n {children}\n </SoftwareInfoContext.Provider>\n );\n};\nexport const useSoftwareInfoContext = () => {\n const context = useContext(SoftwareInfoContext);\n if (!context) {\n throw new Error(\n \"useSoftwareInfoContext must be used within a SoftwareInfoProvider\"\n );\n }\n return context;\n};\n","import React from \"react\";\nimport { KosToken } from \"../../core\";\n\nconst token = new KosToken();\nconst TokenContext = React.createContext<KosToken>(token);\n\nfunction TokenProvider({ children }: { children: React.ReactNode }) {\n return (\n <TokenContext.Provider value={token}>{children}</TokenContext.Provider>\n );\n}\nexport { TokenContext, TokenProvider };\n","import { KosLog, getQueryParams } from \"../../../core\";\nimport {\n KosTranslations,\n Localization,\n TranslationContainerModel,\n collectLocaleOptions,\n getKosLocalizationDescriptor,\n mergeLocalizationDescriptors,\n} from \"../../../models\";\n\nimport {\n PropsWithChildren,\n createContext,\n useContext,\n useEffect,\n useMemo,\n useState,\n} from \"react\";\n\ninterface TranslationContainerType {\n setLocale: (locale: string) => void;\n allLocales: { locale: string; label: string }[];\n}\nexport const TranslationContainerContext = createContext<\n TranslationContainerType | undefined\n>(undefined);\n\ninterface TranslationContainerProviderProps {\n appContext?: string | string[];\n rootUrl?: string;\n locale?: string;\n descriptorResolver?: () => Promise<Localization>;\n excludeNamespaces?: string[];\n resolver?: (\n this: TranslationContainerModel,\n namespace: string,\n locale: string\n ) => string;\n}\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\nexport const KosTranslationProvider: React.FunctionComponent<\n PropsWithChildren<TranslationContainerProviderProps>\n> = ({\n children,\n appContext,\n locale = \"en\",\n resolver,\n rootUrl,\n descriptorResolver,\n excludeNamespaces = [],\n}) => {\n const [ready, setReady] = useState(false);\n const [localization, setLocalization] = useState<Localization>();\n const [translations, setTranslations] = useState<TranslationContainerModel>();\n const [allLocales, setAllLocales] = useState<\n { locale: string; label: string }[]\n >([]);\n const resolvedRootUrl = rootUrl || getDefaultHost();\n const _appContext = useMemo(() => appContext ?? \"app/system\", [appContext]);\n useEffect(() => {\n async function initTools() {\n const contexts = Array.isArray(_appContext) ? _appContext : [_appContext];\n\n const descriptorPromises = contexts.map((context) => {\n const localizationResolver =\n descriptorResolver || getKosLocalizationDescriptor(context);\n return localizationResolver();\n });\n\n const descriptorsResults = await Promise.allSettled(descriptorPromises);\n const descriptors: Localization[] = descriptorsResults\n .map((d) => {\n if (d.status === \"rejected\") {\n KosLog.warn(\"Failed to load localization descriptor\", d.reason);\n return undefined;\n }\n return d.value;\n })\n .filter((d) => !!d) as Localization[];\n\n setLocalization(mergeLocalizationDescriptors(descriptors));\n setAllLocales(collectLocaleOptions(descriptors, excludeNamespaces));\n }\n initTools();\n }, [_appContext, descriptorResolver]);\n\n useEffect(() => {\n async function initLocalization() {\n if (localization) {\n const _rootUrl = resolvedRootUrl;\n const { translations } = await KosTranslations.init({\n lang: locale,\n descriptor: localization,\n defaultNamespace: \"common\",\n resolver: resolver,\n rootUrl: _rootUrl,\n });\n setTranslations(translations);\n setReady(true);\n }\n }\n\n initLocalization();\n }, [locale, localization, resolver, resolvedRootUrl]);\n\n const value: TranslationContainerType = useMemo(() => {\n if (ready) {\n return {\n setLocale: (locale: string) => {\n if (translations) {\n translations.currentLocale = locale;\n }\n },\n allLocales,\n };\n }\n return {\n setLocale: () => {\n throw new Error(\"Translations not ready\");\n },\n allLocales: [],\n };\n }, [ready, translations]);\n\n const content = ready ? children : null;\n return (\n <TranslationContainerContext.Provider value={value}>\n {content}\n </TranslationContainerContext.Provider>\n );\n};\nexport const useKosTranslationContext = () => {\n const context = useContext(TranslationContainerContext);\n if (!context) {\n throw new Error(\n \"useTranslationContainerContext must be used within a TranslationContainerProvider\"\n );\n }\n return context;\n};\n","import {\n CanvasDispatcher,\n type CanvasDispatcherModel,\n type CanvasDispatcherOptions,\n} from \"../../../../../models/models/canvas-dispatcher\";\nimport { useKosModel } from \"../../../../hooks/use-kos-model\";\n\nexport const useCanvasDispatcher = () => {\n const modelId = CanvasDispatcher.type;\n const result = useKosModel<CanvasDispatcherModel, CanvasDispatcherOptions>({\n modelId,\n modelType: CanvasDispatcher.type,\n options: {},\n });\n\n return result;\n};\n","import type { CanvasDispatcherModel } from \"../../../../../models/models/canvas-dispatcher\";\nimport { useCanvasDispatcher } from \"./use-canvas-dispatcher\";\n\ninterface CanvasDispatcherProps {\n canvasDispatcher: CanvasDispatcherModel;\n}\n\ntype HoCCanvasDispatcherProps = CanvasDispatcherProps;\n// react HOC to provide a CanvasDispatcher to a component\nexport function withCanvasDispatcher<\n T extends HoCCanvasDispatcherProps = HoCCanvasDispatcherProps\n>(WrappedComponent: React.ComponentType<T>) {\n return (props: Omit<T, keyof CanvasDispatcherProps>) => {\n const { model, status, KosModelLoader } = useCanvasDispatcher();\n\n return (\n <KosModelLoader {...status}>\n <WrappedComponent {...(props as T)} canvasDispatcher={model} />\n </KosModelLoader>\n );\n };\n}\n","export const decodeBase64RGB = (\n base64: string,\n width: number,\n height: number\n): Uint8ClampedArray => {\n const binary = atob(base64);\n const rgba = new Uint8ClampedArray(width * height * 4);\n for (let i = 0, j = 0; i < binary.length && j < rgba.length; i += 3, j += 4) {\n rgba[j] = binary.charCodeAt(i);\n rgba[j + 1] = binary.charCodeAt(i + 1);\n rgba[j + 2] = binary.charCodeAt(i + 2);\n rgba[j + 3] = 255;\n }\n return rgba;\n};\n\nexport const decodeRGB332 = (\n data: string,\n width: number,\n height: number\n): Uint8ClampedArray => {\n const rgba = new Uint8ClampedArray(width * height * 4);\n for (let i = 0; i < data.length; i++) {\n const byte = data.charCodeAt(i);\n const r = (((byte >> 5) & 0x07) * 255) / 7;\n const g = (((byte >> 2) & 0x07) * 255) / 7;\n const b = ((byte & 0x03) * 255) / 3;\n const j = i * 4;\n rgba[j] = r;\n rgba[j + 1] = g;\n rgba[j + 2] = b;\n rgba[j + 3] = 255;\n }\n return rgba;\n};\n\n/**\n * Renders a decoded preview onto a canvas context by decoding image data\n * from a specified format and scaling it to the desired size.\n *\n * @param ctx - The 2D rendering context of the target canvas.\n * @param format - The format of the input data string. Can be either 'base64' or 'rgb332'.\n * @param dataString - The encoded image data as a string.\n * @param width - The width of the image in pixels.\n * @param height - The height of the image in pixels.\n * @param pixelSize - The scaling factor for each pixel in the rendered image.\n *\n * @remarks\n * - If `format` is 'base64', the `dataString` is decoded using `decodeBase64RGB`.\n * - If `format` is 'rgb332', the `dataString` is decoded using `decodeRGB332`.\n * - The function creates a temporary canvas to decode and render the image data\n * before scaling it onto the target canvas.\n * - Image smoothing is disabled to preserve the pixelated appearance of the image.\n */\nexport function renderDecodedPreview({\n ctx,\n format,\n dataString,\n width,\n height,\n pixelSize,\n}: {\n ctx: CanvasRenderingContext2D;\n format: \"base64\" | \"rgb332\";\n dataString: string;\n width: number;\n height: number;\n pixelSize: number;\n}) {\n const decode =\n format === \"base64\"\n ? decodeBase64RGB(dataString, width, height)\n : decodeRGB332(dataString, width, height);\n\n const img = new ImageData(\n decode as unknown as Uint8ClampedArray<ArrayBuffer>,\n width,\n height\n );\n const tempCanvas = document.createElement(\"canvas\");\n tempCanvas.width = width;\n tempCanvas.height = height;\n const tempCtx = tempCanvas.getContext(\"2d\");\n tempCtx?.putImageData(img, 0, 0);\n ctx.imageSmoothingEnabled = false;\n ctx.clearRect(0, 0, width * pixelSize, height * pixelSize);\n ctx.drawImage(tempCanvas, 0, 0, width * pixelSize, height * pixelSize);\n}\n","import styled from \"@emotion/styled\";\n\nimport { useCallback, useEffect, useRef, useState } from \"react\";\n\nimport { observer as kosComponent } from \"mobx-react-lite\";\nimport { createPortal } from \"react-dom\";\nimport { KosLog } from \"../../../../../core\";\nimport type { CanvasDispatcherModel } from \"../../../../../models/models/canvas-dispatcher\";\nimport type { CanvasRendererModel } from \"../../../../../models/models/canvas-renderer\";\nimport { withCanvasDispatcher } from \"../../hooks/canvas-dispatcher\";\nimport { renderDecodedPreview } from \"../../utils/preview-decoder\";\n\nconst log = KosLog.createLogger({ name: \"canvas-streamer\" });\nlog.debug(\"main-view component loaded\");\nconst PIXEL_SIZE = 10;\n\ninterface CanvasStreamerProps {\n height?: number;\n width?: number;\n defaultFps?: number;\n showPreview?: boolean;\n name: string;\n apiPath?: string;\n canvasDispatcher: CanvasDispatcherModel;\n}\n\nexport const CanvasStreamerBase: React.FunctionComponent<CanvasStreamerProps> =\n kosComponent(\n ({\n canvasDispatcher,\n height = 30,\n width = 50,\n defaultFps = 10,\n showPreview = false,\n name,\n apiPath = \"/api/system/canvas\",\n }) => {\n const canvasRef = useRef<HTMLCanvasElement>(null);\n\n const [renderer, setRenderer] = useState<CanvasRendererModel>();\n\n useEffect(() => {\n const _endpoint = canvasDispatcher.addNamedEndpoint(name, {\n apiPath,\n fps: defaultFps,\n width,\n height,\n id: name,\n });\n\n setRenderer(_endpoint);\n }, [canvasDispatcher]);\n /**\n * Callback function to handle frame processing.\n *\n * @param rgba - A `Uint8ClampedArray` representing the RGBA pixel data of the frame.\n *\n * This function performs the following operations:\n * If a preview canvas is available and `showPreview` is enabled, renders a decoded\n * preview of the frame onto the canvas using `renderDecodedPreview`.\n *\n * Dependencies:\n * - `width` and `height`: Dimensions of the grid for encoding and rendering.\n * - `showPreview`: A flag to determine whether to render a preview.\n * - `canvasRef`: A reference to the preview canvas element.\n * - `PIXEL_SIZE`: The size of each pixel in the preview rendering.\n */\n const onFrame = useCallback(\n (dataString: string) => {\n if (canvasRef.current && showPreview) {\n const previewCtx = canvasRef.current.getContext(\"2d\");\n if (previewCtx) {\n renderDecodedPreview({\n ctx: previewCtx,\n format: \"base64\",\n dataString,\n height,\n width,\n pixelSize: PIXEL_SIZE,\n });\n }\n }\n },\n [width, height, showPreview]\n );\n\n useEffect(() => {\n if (!renderer) return;\n renderer.onFrame = onFrame;\n renderer.width = width;\n renderer.height = height;\n renderer.fps = defaultFps;\n }, [renderer, onFrame, width, height, defaultFps]);\n\n return (\n showPreview &&\n createPortal(\n <Main>\n <PreviewContainer>\n <canvas\n ref={canvasRef}\n width={width * PIXEL_SIZE}\n height={height * PIXEL_SIZE}\n style={{ border: \"1px solid black\" }}\n />\n </PreviewContainer>\n </Main>,\n document.body\n )\n );\n }\n );\n\nexport const CanvasStreamer = withCanvasDispatcher(CanvasStreamerBase);\n\nconst Main = styled.div`\n display: flex;\n flex-direction: column;\n gap: 8px;\n\n width: 100%;\n justify-content: space-between;\n align-items: center;\n`;\n\nconst PreviewContainer = styled.div`\n display: flex;\n flex-direction: column;\n align-items: center;\n`;\n","import { Device, DeviceModel } from \"../../../models\";\nimport { useKosModel } from \"../use-kos-model\";\n\n/**\n * Hook for accessing the KOS device model.\n *\n * @kosService core.use-device\n * @kosApiLevel 2\n */\nexport const useDevice = () => {\n const modelId = Device.type;\n const result = useKosModel<DeviceModel>({\n modelId,\n modelType: Device.type,\n options: {},\n });\n\n return result;\n};\n","import { DeviceModel } from \"../../../models\";\nimport { useDevice } from \"./use-device\";\n\nexport interface DeviceProps {\n device: DeviceModel;\n}\n\ntype HoCDeviceProps = DeviceProps;\n// react HOC to provide a Device to a component\nexport function withDevice<T extends HoCDeviceProps = HoCDeviceProps>(\n WrappedComponent: React.ComponentType<T>\n) {\n return (props: Omit<T, keyof DeviceProps>) => {\n const { model, status, KosModelLoader } = useDevice();\n\n return (\n <KosModelLoader {...status}>\n <WrappedComponent {...(props as T)} device={model} />\n </KosModelLoader>\n );\n };\n}\n","import { IKosDataModel, KosCore, wrapPromise } from \"../../core\";\n\nexport default function fetchModel<\n T extends IKosDataModel,\n O extends object = Record<string, unknown>\n>(modelType: string, id?: string, options?: O) {\n const corePromise = new Promise<T>((resolve) => {\n KosCore.getInstance()\n .whenReady()\n .then(() => {\n const { model } =\n KosCore.getInstance().modelManager.createModelInstance<T>(\n modelType,\n id ?? modelType,\n options\n );\n return model.whenReady().then(() => {\n resolve(model.modelData);\n });\n });\n });\n\n return wrapPromise<T>(corePromise);\n}\n","import { KosTimeModel } from \"../../../models\";\nimport { useKosTime } from \"./use-kos-time\";\n\ninterface KosTimeProps {\n kosTime: KosTimeModel;\n}\n// react HOC to provide a KosTime to a component\nexport function withKosTime<T extends KosTimeProps = KosTimeProps>(\n WrappedComponent: React.ComponentType<T>\n) {\n return (props: Omit<T, keyof KosTimeProps>) => {\n const { model, status, KosModelLoader } = useKosTime();\n\n return (\n <KosModelLoader {...status}>\n <WrappedComponent {...(props as T)} kosTime={model} />\n </KosModelLoader>\n );\n };\n}\n","import {\n NetworkInterfaceContainer,\n NetworkInterfaceContainerModel,\n} from \"../../../models\";\nimport { useKosModel } from \"../use-kos-model\";\n\n/**\n * Hook for accessing the KOS network interface container model.\n *\n * @kosService core.use-network\n * @kosApiLevel 2\n */\nexport const useNetworkInterfaceContainer = () => {\n const modelId = NetworkInterfaceContainer.type;\n const result = useKosModel<NetworkInterfaceContainerModel>({\n modelId,\n modelType: NetworkInterfaceContainer.type,\n options: {},\n });\n\n return result;\n};\n","import { NetworkInterfaceContainerModel } from \"../../../models\";\nimport { useNetworkInterfaceContainer } from \"./use-network-interface-container\";\n\ninterface NetworkInterfaceContainerProps {\n networkInterfaceContainer: NetworkInterfaceContainerModel;\n}\n\ntype HoCNetworkInterfaceContainerProps = NetworkInterfaceContainerProps;\n// react HOC to provide a NetworkInterfaceContainer to a component\nexport function withNetworkInterfaceContainer<\n T extends HoCNetworkInterfaceContainerProps = HoCNetworkInterfaceContainerProps\n>(WrappedComponent: React.ComponentType<T>) {\n return (props: Omit<T, keyof NetworkInterfaceContainerProps>) => {\n const { model, status, KosModelLoader } = useNetworkInterfaceContainer();\n\n return (\n <KosModelLoader {...status}>\n <WrappedComponent {...(props as T)} networkInterfaceContainer={model} />\n </KosModelLoader>\n );\n };\n}\n","import { Ota, type OtaModel } from \"../../../models\";\nimport { useKosModel } from \"../use-kos-model\";\n\n/**\n * Hook for accessing the KOS OTA (over-the-air update) model.\n *\n * @kosService core.use-ota\n * @kosApiLevel 2\n */\nexport const useOta = () => {\n const modelId = Ota.type;\n const result = useKosModel<OtaModel>({\n modelId,\n modelType: Ota.type,\n options: {},\n });\n\n return result;\n};\n","import type { OtaModel } from \"../../../models\";\nimport { useOta } from \"./use-ota\";\n\ninterface OtaProps {\n oTA: OtaModel;\n}\n\ntype HoCOtaProps = OtaProps;\n// react HOC to provide a Ota to a component\nexport function withOta<T extends HoCOtaProps = HoCOtaProps>(\n WrappedComponent: React.ComponentType<T>\n) {\n return (props: Omit<T, keyof OtaProps>) => {\n const { model, status, KosModelLoader } = useOta();\n\n return (\n <KosModelLoader {...status}>\n <WrappedComponent {...(props as T)} oTA={model} />\n </KosModelLoader>\n );\n };\n}\n","import { useRef, useEffect, PropsWithChildren } from \"react\";\n\n/**\n * Hook that alerts clicks outside of the passed ref\n */\nfunction useOutsideAlerter(ref, onAction) {\n useEffect(() => {\n /**\n * Alert if clicked on outside of element\n */\n function handleClickOutside(event) {\n if (ref.current && !ref.current.contains(event.target)) {\n onAction();\n }\n }\n\n function handleEscFunction(event) {\n if (event.key === \"Escape\") {\n onAction();\n }\n }\n // Bind the event listener\n document.addEventListener(\"mousedown\", handleClickOutside);\n document.addEventListener(\"keydown\", handleEscFunction, false);\n return () => {\n // Unbind the event listener on clean up\n document.removeEventListener(\"mousedown\", handleClickOutside);\n document.removeEventListener(\"keydown\", handleEscFunction, false);\n };\n }, [ref, onAction]);\n}\n\ninterface Props {\n onAlert: () => void;\n}\n/**\n * Component that alerts if you click outside of it\n */\nexport default function OutsideAlerter(props: PropsWithChildren<Props>) {\n const wrapperRef = useRef(null);\n const onAction = props.onAlert;\n useOutsideAlerter(wrapperRef, onAction);\n\n return (\n <div ref={wrapperRef} style={{ width: \"100%\" }}>\n {props.children}\n </div>\n );\n}\n","import { KosStateProp, StatePropertyTypes } from \"../../../models\";\n\nimport { useEffect, useState } from \"react\";\nimport { kosAutoEffect, whenReady } from \"../../../core\";\n\ninterface UseStatePropertyProps<T extends StatePropertyTypes = any> {\n stateProp?: KosStateProp<T>;\n}\n\ntype StatePropertyStatus<T extends StatePropertyTypes = any> = [\n value: T | undefined,\n status: { ready: boolean; error?: string }\n];\nexport const useStateProperty = <T extends StatePropertyTypes = any>(\n props: UseStatePropertyProps<T>\n): StatePropertyStatus<T> => {\n const { stateProp } = props;\n const [value, setValue] = useState<T | undefined>(props.stateProp?.value);\n const [ready, setReady] = useState(false);\n const [error, setError] = useState<string | undefined>(undefined);\n\n useEffect(() => {\n async function waitForProp(prop?: KosStateProp) {\n try {\n if (prop) {\n await whenReady(prop);\n setReady(true);\n }\n } catch (e) {\n setError((e as Error).message);\n }\n }\n\n waitForProp(stateProp);\n }, [stateProp]);\n\n useEffect(() => {\n const disposer = kosAutoEffect(() => {\n if (stateProp && ready) {\n setValue(stateProp.value);\n }\n });\n return () => {\n disposer();\n };\n }, [ready, stateProp]);\n\n const status = { ready, error };\n return [value, status];\n};\n","import { useEffect, useState } from \"react\";\nimport { kosAutoEffect } from \"../../../core\";\nimport {\n StorageDeviceContainer,\n StorageDeviceContainerModel,\n type StorageDeviceModel,\n} from \"../../../models\";\nimport { useKosModel } from \"../use-kos-model\";\n\n/**\n * Hook for accessing the KOS storage device container model.\n *\n * @kosService core.use-storage\n * @kosApiLevel 2\n */\nexport const useStorageDeviceContainer = () => {\n const [inserted, setInserted] = useState<boolean>(false);\n const [devices, setDevices] = useState<StorageDeviceModel[]>([]);\n const modelId = StorageDeviceContainer.type;\n const result = useKosModel<StorageDeviceContainerModel>({\n modelId,\n modelType: StorageDeviceContainer.type,\n options: {},\n });\n\n useEffect(() => {\n const disposer = kosAutoEffect(() => {\n setInserted(result.model?.isStorageInserted ?? false);\n setDevices(result.model?.data ?? []);\n });\n\n return () => {\n disposer();\n };\n }, [result.model]);\n\n return { ...result, inserted, devices };\n};\n","import { StorageDeviceContainerModel } from \"../../../models\";\nimport { useStorageDeviceContainer } from \"./use-storage-device-container\";\n\ninterface StorageDeviceContainerProps {\n storageDeviceContainer: StorageDeviceContainerModel;\n}\n\ntype HoCStorageDeviceContainerProps = StorageDeviceContainerProps;\n// react HOC to provide a StorageDeviceContainer to a component\nexport function withStorageDeviceContainer<\n T extends HoCStorageDeviceContainerProps = HoCStorageDeviceContainerProps\n>(WrappedComponent: React.ComponentType<T>) {\n return (props: Omit<T, keyof StorageDeviceContainerProps>) => {\n const { model, status, KosModelLoader } = useStorageDeviceContainer();\n\n return (\n <KosModelLoader {...status}>\n <WrappedComponent {...(props as T)} storageDeviceContainer={model} />\n </KosModelLoader>\n );\n };\n}\n","import { useCallback, useEffect } from \"react\";\nimport { EventBus } from \"../../../common\";\nimport { KosLog } from \"../../../core\";\nimport {\n KosTimer,\n TIMER_END,\n TIMER_EVENT,\n TimerEvent,\n TimerManager,\n TOPIC_TIMER_TICK_EVENT,\n} from \"../../../models\";\n\nconst LOG = KosLog.createLogger({ name: \"use-timer\" });\ninterface TimerHookProps {\n timerName: string;\n onTimerExpired: (event: TimerHookEvent) => void;\n onTimerTick?: (event: TimerTickEvent) => void;\n timerEventActions?: Record<string, (event: TimerHookEvent) => void>;\n autoStart?: boolean;\n}\ntype TimerHookEvent = TimerEvent & { timer: KosTimer };\n\ntype TimerTickEvent = Omit<TimerHookEvent, \"action\"> & {\n timer: KosTimer;\n};\nexport const useTimer = ({\n timerName,\n onTimerExpired,\n onTimerTick,\n timerEventActions,\n autoStart,\n}: TimerHookProps) => {\n const t = TimerManager.getTimer(timerName);\n\n useEffect(() => {\n if (!t) {\n console.warn(`Timer with name ${timerName} does not exist.`);\n return undefined;\n }\n const result = EventBus.subscribe(TIMER_EVENT, (data) => {\n const { name, action, remainingTime } =\n data?.body as unknown as TimerEvent;\n if (name === timerName) {\n if (action === TIMER_END) {\n onTimerExpired({ name, action, remainingTime, timer: t });\n } else if (timerEventActions?.[action]) {\n timerEventActions[action]({ name, action, remainingTime, timer: t });\n }\n }\n });\n if (autoStart) t.start();\n return () => {\n result.unsubscribe();\n };\n }, [autoStart, onTimerExpired, timerEventActions, timerName, t]);\n\n useEffect(() => {\n if (!t || !onTimerTick) {\n return undefined;\n }\n const TOPIC_TIMER_TICK = `${TOPIC_TIMER_TICK_EVENT}/${timerName}`;\n const result = EventBus.subscribe(TOPIC_TIMER_TICK, (data) => {\n const { name, remainingTime } = data?.body as unknown as TimerEvent;\n if (name === timerName) {\n onTimerTick({ name, remainingTime, timer: t });\n }\n });\n return () => {\n result.unsubscribe();\n };\n }, [onTimerTick, timerName, t]);\n\n const start = useCallback(() => {\n if (t) {\n t.start();\n } else {\n LOG.warn(`Timer with name ${timerName} does not exist.`);\n }\n }, [t, timerName]);\n\n const reset = useCallback(() => {\n if (t) {\n t.reset();\n } else {\n LOG.warn(`Timer with name ${timerName} does not exist.`);\n }\n }, [t, timerName]);\n\n const pause = useCallback(() => {\n if (t) {\n t.pause();\n } else {\n LOG.warn(`Timer with name ${timerName} does not exist.`);\n }\n }, [t, timerName]);\n\n return {\n timer: t,\n start,\n reset,\n pause,\n };\n};\n","import React, { type ReactNode, type ReactElement } from \"react\";\nimport { TFunction } from \"./use-translation\";\n\nconst escapeRegExp = (toEscape: string) => {\n const escapableChars = /[\\\\^$.*+?()[\\]{}|]/g;\n const hasEscapableChar = RegExp(escapableChars.source);\n\n return hasEscapableChar.test(toEscape)\n ? toEscape.replace(escapableChars, \"\\\\$&\")\n : toEscape;\n};\n\nconst isRegExp = (toTest: string | RegExp): toTest is RegExp =>\n toTest instanceof RegExp;\n\nconst isString = (toTest: string | RegExp | ReactNode): toTest is string =>\n typeof toTest === \"string\";\n\nconst replaceString = (\n source: string,\n _toMatch: string | RegExp,\n callback: (match: string, index: number) => ReactNode\n) => {\n if (source === \"\" || _toMatch === \"\") return source;\n\n let toMatch = _toMatch;\n\n if (!isRegExp(toMatch)) {\n toMatch = new RegExp(\"(\" + escapeRegExp(toMatch) + \")\", \"gi\");\n }\n\n const result: ReactNode[] = source.split(toMatch);\n\n // Matches will be every odd string in the array, iterate over them and\n // call the callback to insert our component for each match.\n for (let i = 1, length = result.length; i < length; i += 2) {\n result[i] = callback(result[i] as string, i);\n }\n\n return result;\n};\n\nexport const stringComponentInsert = (\n _source: string | (string | ReactNode)[],\n toMatch: string | RegExp,\n callback: (match: string, index: number) => string | ReactElement\n) => {\n let source = _source;\n if (!Array.isArray(source)) source = [source];\n\n return source.flatMap((x) =>\n isString(x) ? replaceString(x, toMatch, callback) : x\n );\n};\n\ninterface Components {\n [key: string]: JSX.Element;\n}\n\ntype ComponentArray = JSX.Element[];\n\ntype ComponentMap = Components | ComponentArray;\ninterface TransProps {\n t: TFunction;\n i18nKey: string;\n defaults?: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n values?: Record<string, any | undefined>;\n components?: ComponentMap;\n context?: string;\n className?: string;\n}\n\nfunction substituteBlocks(stringValue: string, componentsMap: ComponentMap) {\n let blocks: string | ReactNode[] = stringValue;\n\n Object.entries(componentsMap).forEach(([key, value]) => {\n const regex = new RegExp(`<${key}>(.*?)</${key}>|<${key}/>`, \"g\");\n\n blocks = stringComponentInsert(blocks, regex, (match, index) => {\n if (value.type === \"br\") {\n return <br />;\n }\n return React.cloneElement(value, { key: `${key}-${index}` }, match);\n });\n });\n\n return blocks;\n}\n\n/**\n * React component for rendering translated strings with embedded components or markup.\n *\n * @kosService core.use-translation\n * @kosApiLevel 2\n */\nexport const Trans: React.FunctionComponent<TransProps> = (props) => {\n const { i18nKey, t, defaults, components, values = {}, context } = props;\n const translated = t(i18nKey, {\n defaultValue: defaults,\n data: values,\n context,\n returnObjects: true,\n });\n\n const element = substituteBlocks(translated, components || {});\n return <span className={props.className}>{element}</span>;\n};\n","import { useCallback, useMemo } from \"react\";\nimport { KosLog, getKosModel, whenReady } from \"../../../core\";\nimport {\n ResolveTranslationOptions,\n TranslationContainer,\n TranslationContainerModel,\n} from \"../../../models\";\n\nconst cache = new Map();\n\nfunction fetchData(key, fetcher) {\n // Check if there's already a cached promise or result.\n if (cache.has(key)) {\n const entry = cache.get(key);\n if (entry.status === \"finished\") {\n return entry.result;\n }\n\n // An error entry has no promise to suspend on, so rethrow the cause.\n if (entry.status === \"error\") {\n throw entry.error;\n }\n\n throw entry.promise;\n } else {\n // If no cache exists, create a new promise.\n const promise = fetcher().then(\n (result) => {\n cache.set(key, { status: \"finished\", result });\n },\n (error) => {\n cache.set(key, { status: \"error\", error });\n throw error;\n }\n );\n\n // Store the promise in the cache with a pending status.\n const entry = { status: \"pending\", promise };\n cache.set(key, entry);\n\n // Suspend by throwing the promise.\n throw promise;\n }\n}\n\nexport function useSuspenseData<T>(\n key: string,\n fetcher: (...args: any[]) => Promise<T>\n) {\n // Attempt to fetch the data (or retrieve from cache), throwing a promise if it's not ready.\n const data = fetchData(key, fetcher) as T;\n\n // If the data is available, return it.\n return data;\n}\n\nconst fetchTranslationContainer = async () => {\n const container = await getKosModel(TranslationContainer.type);\n await whenReady(container.model);\n return container.model as TranslationContainerModel;\n};\nconst fetchTranslations = async (\n parent: TranslationContainerModel,\n namespace: string,\n additionalNamespaces: string[]\n) => {\n const trans = parent.resolveNamespace(namespace);\n await whenReady(trans);\n for (const ns of additionalNamespaces) {\n const additional = parent.resolveNamespace(ns);\n await whenReady(additional);\n\n //TODO: This is a hack to force the model to resolve the translations\n cache.set(ns, { status: \"finished\", result: additional });\n }\n return trans;\n};\n\nexport type TFunction = <T = string>(\n key: string,\n options?: ResolveTranslationOptions<T> | string\n) => T | string;\n\nexport interface UseKosTranslationOptions {\n keyPrefix?: string;\n}\n/**\n * Primary hook for consuming KOS translations in React components.\n * Resolves a translation namespace and returns a `t` function for key lookup.\n *\n * @kosService core.use-translation\n * @kosApiLevel 2\n */\nexport const useKosTranslation = (\n namespace: string | string[],\n baseOptions?: UseKosTranslationOptions\n) => {\n const allNamespaces = [namespace].flat();\n const [defaultNamespace, ...additionalNamespaces] = allNamespaces;\n\n const model = useSuspenseData(\n TranslationContainer.type,\n fetchTranslationContainer\n );\n\n const allKeys = allNamespaces.join(\"__\");\n const translationModel = useSuspenseData(allKeys, () =>\n fetchTranslations(model, defaultNamespace, additionalNamespaces)\n );\n\n const i18n = useMemo(() => {\n return {\n exists: (key: string) => {\n const expandedKey = baseOptions?.keyPrefix\n ? `${baseOptions.keyPrefix}.${key}`\n : key;\n if (translationModel) {\n return translationModel.exists(expandedKey);\n }\n\n return false;\n },\n };\n }, [baseOptions?.keyPrefix, translationModel]);\n const t = useCallback<TFunction>(\n <T = string>(\n key: string,\n options?: ResolveTranslationOptions<T> | string\n ) => {\n const expandedKey = baseOptions?.keyPrefix\n ? `${baseOptions.keyPrefix}.${key}`\n : key;\n if (translationModel) {\n return translationModel.resolveKey(expandedKey, options) as T;\n }\n\n KosLog.debug(\n `Translation model ${namespace} not ready for key: ${expandedKey}`\n );\n return expandedKey;\n },\n [baseOptions?.keyPrefix, namespace, translationModel]\n );\n return { t, i18n };\n};\n","import {\n TranslationContainer,\n type TranslationContainerModel,\n} from \"../../../models\";\nimport { useKosModel } from \"../use-kos-model\";\n\n/**\n * Hook for accessing the KOS translation container model.\n *\n * @kosService core.use-translation\n * @kosApiLevel 2\n */\nexport const useTranslationContainer = () => {\n const modelId = TranslationContainer.type;\n const result = useKosModel<TranslationContainerModel>({\n modelId,\n modelType: TranslationContainer.type,\n options: {},\n });\n\n return result;\n};\n","import type { TranslationContainerModel } from \"../../../models\";\nimport { useTranslationContainer } from \"./use-translation-container\";\n\ninterface TranslationContainerProps {\n translationContainer: TranslationContainerModel;\n}\n\ntype HoCTranslationContainerProps = TranslationContainerProps;\n/**\n * Higher-order component that injects a `TranslationContainerModel` into a wrapped component.\n *\n * @kosService core.use-translation\n * @kosApiLevel 2\n */\nexport function withTranslationContainer<\n T extends HoCTranslationContainerProps = HoCTranslationContainerProps\n>(WrappedComponent: React.ComponentType<T>) {\n return (props: Omit<T, keyof TranslationContainerProps>) => {\n const { model, status, KosModelLoader } = useTranslationContainer();\n\n return (\n <KosModelLoader {...status}>\n <WrappedComponent {...(props as T)} translationContainer={model} />\n </KosModelLoader>\n );\n };\n}\n","import { Trouble, type TroubleModel } from \"../../../models\";\nimport { useKosModel } from \"../use-kos-model\";\n\nexport const useTroubleModel = (id: string) => {\n const modelId = id;\n\n const result = useKosModel<TroubleModel>({\n modelId,\n modelType: Trouble.type,\n });\n\n return result;\n};\n","import { TroubleContainer, type TroubleContainerModel } from \"../../../models\";\nimport { useKosModel } from \"../use-kos-model\";\n\nexport const useTroubleContainerModel = () => {\n const result = useKosModel<TroubleContainerModel>({\n modelId: TroubleContainer.type,\n modelType: TroubleContainer.type,\n options: {},\n });\n return result;\n};\n","import { useCallback, useEffect, useState } from \"react\";\nimport { kosAutoEffect } from \"../../../core\";\nimport type { TroubleModel } from \"../../../models/models/trouble\";\nimport type { FutureResponse } from \"../../../models/services/future\";\nimport { useTroubleContainerModel } from \"../trouble/use-trouble-container\";\n\ninterface Props {\n troubleType?: string;\n condition?: (trouble: TroubleModel) => boolean;\n}\n\ntype TroubleVisibility = [\n boolean,\n () => Promise<FutureResponse | undefined>,\n TroubleModel | undefined,\n TroubleModel[]\n];\nexport const useTroublePresence = ({\n troubleType,\n condition,\n}: Props): TroubleVisibility => {\n const { model } = useTroubleContainerModel();\n const [active, setActive] = useState<boolean>(false);\n const [troubles, setTroubles] = useState<TroubleModel[]>([]);\n\n const onComplete = useCallback(() => {\n if (troubles.length > 0 && troubles[0]?.resolvable) {\n return troubles[0]?.resolve();\n }\n return Promise.resolve(undefined);\n }, [troubles]);\n useEffect(() => {\n const disposer = kosAutoEffect(() => {\n const troublesByType =\n (troubleType\n ? model?.troubles.getIndexByKey(\"byType\", troubleType)\n : model?.troubles.data) || [];\n const activeTroubles = condition\n ? troublesByType.filter(condition)\n : troublesByType;\n setActive(activeTroubles.length > 0);\n setTroubles(activeTroubles);\n });\n return disposer;\n }, [condition, model, troubleType]);\n\n return [\n active,\n onComplete,\n troubles.length > 0 ? troubles[0] : undefined,\n troubles,\n ];\n};\n","import type { TroubleContainerModel } from \"../../../models\";\nimport { useTroubleContainerModel } from \"./use-trouble-container\";\n\ninterface TroubleContainerProps {\n troubleContainer: TroubleContainerModel;\n}\n// react HOC to provide a BoardContainer to a component\nexport function withTroubleContainer<\n T extends TroubleContainerProps = TroubleContainerProps\n>(WrappedComponent: React.ComponentType<T>) {\n return (props: Omit<T, keyof TroubleContainerProps>) => {\n const { model, status, KosModelLoader } = useTroubleContainerModel();\n\n return (\n <KosModelLoader {...status}>\n <WrappedComponent {...(props as T)} troubleContainer={model} />\n </KosModelLoader>\n );\n };\n}\n","import { useEffect, useState } from \"react\";\nimport { kosAutoEffect } from \"../../../core\";\nimport {\n UsbUpdateContainer,\n type UsbUpdateContainerModel,\n type UsbUpdateModel,\n} from \"../../../models\";\nimport { useKosModel } from \"../use-kos-model\";\n\n/**\n * Hook for accessing the KOS USB update container model.\n *\n * @kosService core.use-usb-update\n * @kosApiLevel 2\n */\nexport const useUsbUpdateContainer = () => {\n const modelId = UsbUpdateContainer.type;\n const result = useKosModel<UsbUpdateContainerModel>({\n modelId,\n modelType: UsbUpdateContainer.type,\n options: {},\n activate: true,\n destroyOnUnmount: true,\n });\n\n const [inserted, setInserted] = useState<boolean>(false);\n const [updateAvailable, setUpdateAvailable] = useState<boolean>(false);\n const [updates, setUpdates] = useState<UsbUpdateModel[]>([]);\n const [isSearching, setIsSearching] = useState<boolean>(false);\n const [noUpdates, setNoUpdates] = useState<boolean>(false);\n\n useEffect(() => {\n const disposer = kosAutoEffect(() => {\n setInserted(result.model?.isUsbInserted ?? false);\n setUpdateAvailable(result.model?.hasAvailableUpdates ?? false);\n setUpdates(result.model?.data ?? []);\n setIsSearching(result.model?.isSearchingUpdates ?? false);\n setNoUpdates(result.model?.noAvailableUpdates ?? false);\n });\n\n return () => {\n disposer();\n };\n }, [result.model]);\n\n return {\n ...result,\n inserted,\n updateAvailable,\n updates,\n isSearching,\n noUpdates,\n };\n};\n","import type { UsbUpdateContainerModel } from \"../../../models\";\nimport { useUsbUpdateContainer } from \"./use-usb-update-container\";\n\ninterface UsbUpdateContainerProps {\n usbUpdateContainer: UsbUpdateContainerModel;\n}\n\ntype HoCUsbUpdateContainerProps = UsbUpdateContainerProps;\n// react HOC to provide a UsbUpdateContainer to a component\nexport function withUsbUpdateContainer<\n T extends HoCUsbUpdateContainerProps = HoCUsbUpdateContainerProps\n>(WrappedComponent: React.ComponentType<T>) {\n return (props: Omit<T, keyof UsbUpdateContainerProps>) => {\n const { model, status, KosModelLoader } = useUsbUpdateContainer();\n\n return (\n <KosModelLoader {...status}>\n <WrappedComponent {...(props as T)} usbUpdateContainer={model} />\n </KosModelLoader>\n );\n };\n}\n","import { autorun } from \"mobx\";\nimport { useEffect, useState } from \"react\";\nimport type { IConfigBeanModel, IConfigBeanModelOptions } from \"../../models\";\nimport { ConfigBean, ConfigPropertyTypes } from \"../../models\";\nimport { useKosModel } from \"./use-kos-model\";\n\ninterface UseConfigBeanParams {\n path: string;\n propKey?: string;\n}\n/**\n * Hook for binding to a KOS configuration bean.\n *\n * @kosService core.use-config-property\n * @kosApiLevel 2\n */\nexport const useConfigBean = ({ path, propKey }: UseConfigBeanParams) => {\n const { status } = useKosModel<IConfigBeanModel, IConfigBeanModelOptions>({\n modelType: ConfigBean.type,\n modelId: path,\n options: {\n path,\n },\n });\n const [ready, setReady] = useState(false);\n const [config, setConfig] = useState<IConfigBeanModel>();\n const [value, setValue] = useState<ConfigPropertyTypes>(\"\");\n const [error, setError] = useState<string>();\n const updateValue = (val: string) => {\n if (config && propKey) {\n config.updateProperty(propKey, val);\n }\n };\n useEffect(() => {\n if (status.model) {\n setConfig(status.model);\n }\n\n if (status.model && propKey) {\n if (status.model?.props.has(propKey)) {\n setValue(status.model.props[propKey]!);\n } else {\n setError(`property ${propKey} not found`);\n }\n }\n\n if (status.ready) {\n setReady(status.ready);\n }\n }, [status.ready, status.model, propKey]);\n\n useEffect(() => {\n if (propKey) {\n autorun(() => {\n const prop = config?.props[propKey];\n setValue(prop || \"\");\n });\n }\n }, [config, propKey]);\n\n return {\n config,\n ready,\n value,\n error,\n updateValue,\n };\n};\n","import {\n ChangeEvent,\n Reducer,\n useCallback,\n useEffect,\n useReducer,\n useState,\n} from \"react\";\nimport { kosAutoEffect, whenReady } from \"../../core\";\nimport type {\n ConfigPropertyTypes,\n OptionsType,\n SchemaOptionsType,\n} from \"../../models\";\nimport { KosConfigProperty } from \"../../models\";\n\ntype SelectCallback = string | ChangeEvent<HTMLSelectElement>;\nexport type OptionsTransformer = (options?: OptionsType[]) => any[];\n\ntype KosConfigProp =\n | KosConfigProperty<ConfigPropertyTypes>\n | KosConfigProperty<string>\n | KosConfigProperty<number>\n | KosConfigProperty<boolean>;\ninterface Props {\n configProperty?: KosConfigProp;\n optionsTransformer?: OptionsTransformer;\n}\n\ninterface UpdateAction<T extends object = any> {\n type: \"UPDATE\";\n payload: Partial<ConfigPropertyState<T>>;\n}\ninterface ConfigPropertyState<O extends object = any> {\n value: string;\n displayValue: string;\n significantValue: any;\n unit: string;\n options: OptionsType[];\n mappedOptions: O[];\n updateProperty?: (value: string) => void;\n displayOptions?: SchemaOptionsType;\n}\nconst reducer = <T extends object = any>(\n state: Partial<ConfigPropertyState<T>>,\n action: UpdateAction\n) => {\n switch (action.type) {\n case \"UPDATE\":\n return action.payload;\n default:\n return state;\n }\n};\n/**\n * Hook for binding to a KOS configuration property.\n *\n * @kosService core.use-config-property\n * @kosApiLevel 2\n */\nexport const useConfigProperty = <T extends object = any>({\n configProperty,\n optionsTransformer,\n}: Props) => {\n const [ready, setReady] = useState(false);\n const [error, setError] = useState(\"\");\n\n const [state, dispatch] = useReducer<\n Reducer<Partial<ConfigPropertyState<T>>, UpdateAction<T>>\n >(reducer, {\n value: String(configProperty?.value),\n displayValue: configProperty?.displayValue,\n significantValue: configProperty?.significantValue,\n unit: configProperty?.unit,\n options: configProperty?.options,\n mappedOptions: [],\n updateProperty: configProperty?.updateProperty,\n displayOptions: configProperty?.displayOptions,\n });\n\n const handleUpdate = useCallback(\n (e: SelectCallback) => {\n let value = \"factory\";\n if (typeof e === \"string\") {\n value = e;\n } else if (e?.target?.value) {\n value = e.target.value;\n }\n\n if (value) {\n configProperty?.updateProperty(value);\n }\n },\n [configProperty]\n );\n useEffect(() => {\n async function waitForProp(prop?: KosConfigProp) {\n try {\n if (prop) {\n await whenReady(prop);\n setReady(true);\n }\n } catch (e) {\n setError((e as Error).message);\n }\n }\n\n waitForProp(configProperty);\n }, [configProperty]);\n\n useEffect(() => {\n const disposer = kosAutoEffect(() => {\n if (configProperty && ready) {\n let mapped: any[] = [];\n if (optionsTransformer) {\n mapped = optionsTransformer(configProperty.options);\n }\n dispatch({\n type: \"UPDATE\",\n payload: {\n value: String(configProperty.value),\n displayValue: configProperty.displayValue,\n significantValue: configProperty.significantValue,\n unit: configProperty.unit,\n options: configProperty.options,\n mappedOptions: mapped,\n updateProperty: configProperty.updateProperty,\n displayOptions: configProperty?.displayOptions,\n },\n });\n }\n });\n return () => {\n disposer();\n };\n }, [configProperty, optionsTransformer, ready]);\n\n return {\n ...state,\n configSelectProps: {\n onChange: handleUpdate,\n value: state.value,\n options: optionsTransformer\n ? state.mappedOptions || []\n : state.options || [],\n },\n ready,\n error,\n };\n};\n","import { useEffect, useState } from \"react\";\nimport { EventBus } from \"../../common\";\nimport { WebSocketEvents } from \"../../core/core/transport/base-message-transport\";\nimport { useKosCore } from \"../contexts/kos-core-context\";\n\n/**\n * Details of the most recent WebSocket close event.\n *\n * @kosService core.use-connection-state\n * @kosApiLevel 23\n */\nexport interface DisconnectInfo {\n code: number;\n reason: string;\n wasClean: boolean;\n /** Wall-clock time (Date.now()) when the disconnect was observed. */\n at: number;\n}\n\n/**\n * Current KOS Core connection state plus info about the last disconnect.\n *\n * @kosService core.use-connection-state\n * @kosApiLevel 23\n */\nexport interface ConnectionState {\n online: boolean;\n lastDisconnect: DisconnectInfo | null;\n /** Milliseconds since the last disconnect, or null if none observed. */\n sinceLastDisconnectMs: number | null;\n}\n\n/**\n * Observes KOS Core connection state.\n *\n * Returns the current `online` status plus information about the most recent\n * disconnect (code, reason, wasClean, timestamp). `sinceLastDisconnectMs` is\n * recomputed on each render; components that need it to tick continuously\n * should re-render themselves via an interval.\n *\n * @kosService core.use-connection-state\n * @kosApiLevel 23\n */\nexport const useConnectionState = (): ConnectionState => {\n const { online } = useKosCore();\n const [lastDisconnect, setLastDisconnect] = useState<DisconnectInfo | null>(\n null\n );\n\n useEffect(() => {\n const { unsubscribe } = EventBus.subscribe(\n WebSocketEvents.DISCONNECTED,\n (msg) => {\n const payload = msg?.body as\n | { code: number; reason: string; wasClean: boolean }\n | undefined;\n if (\n payload &&\n typeof payload === \"object\" &&\n typeof payload.code === \"number\"\n ) {\n setLastDisconnect({\n code: payload.code,\n reason: payload.reason,\n wasClean: payload.wasClean,\n at: Date.now(),\n });\n }\n }\n );\n return () => {\n unsubscribe();\n };\n }, []);\n\n return {\n online,\n lastDisconnect,\n sinceLastDisconnectMs: lastDisconnect\n ? Date.now() - lastDisconnect.at\n : null,\n };\n};\n","/**\n * Type for month represented as zero-based (0 for January, 11 for December).\n */\ntype Month = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11;\n\n/**\n * Utility method to get an array of zero-based month options (0 through 11).\n */\nexport function getMonthOptions(): Month[] {\n return Array.from({ length: 12 }, (_, index) => index as Month);\n}\n\n/**\n * Utility method to determine the number of days in a given month of a particular year.\n * @param month - Zero-based month (0 for January, 11 for December).\n * @param year - The year to account for leap years (optional, default is current year).\n * @returns The number of days in the specified month.\n */\nexport function getDaysInMonth(month: Month, year?: number): number {\n const yearToUse = year ?? new Date().getFullYear();\n const daysInEachMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];\n\n // Adjust for leap year\n if (\n month === 1 &&\n ((yearToUse % 4 === 0 && yearToUse % 100 !== 0) || yearToUse % 400 === 0)\n ) {\n return 29;\n }\n\n return daysInEachMonth[month] ?? 0;\n}\n\n/**\n * Utility method to get an array of zero-based day options for a specific month and year.\n * @param month - Zero-based month (0 for January, 11 for December).\n * @param year - The year to account for leap years (optional, default is current year).\n * @returns The array of zero-based day options.\n */\nexport function getDayOptions(month: Month, year?: number): number[] {\n const daysInMonth = getDaysInMonth(month, year);\n return Array.from({ length: daysInMonth }, (_, index) => index);\n}\n\n/**\n * Utility method to get an array of year options.\n * @param startYear - The starting year for the array.\n * @param endYear - The ending year for the array.\n * @returns The array of year options.\n */\nexport function getYearOptions(startYear: number, endYear: number): number[] {\n if (startYear > endYear) {\n throw new Error(\"Start year must be less than or equal to end year\");\n }\n return Array.from(\n { length: endYear - startYear + 1 },\n (_, index) => startYear + index\n );\n}\n","import { getDaysInMonth } from \"./date\";\n\n// Returns the number of days in a given month & year\nexport function getDays(year: number, month: number): number {\n return new Date(year, month, 0).getDate();\n}\n\n// Returns an array of all days in a given month & year\n// TODO: Make numbers locale specific\nexport function getDaysArray(year: number, month: number): number[] {\n const numberOfDays = getDaysInMonth(month as any, year);\n const daysAry: number[] = [];\n for (let i = 1; i <= numberOfDays; i++) {\n daysAry.push(i);\n }\n return daysAry;\n}\n\n// Returns an array of months from 0 - 11\n// Note: The array needs to be 0-11 for date functions\nexport function getMonthsArray(): number[] {\n const months = [...Array(12).keys()].map((key) =>\n new Date(0, key).getMonth()\n );\n return months;\n}\n\n// Returns an array of full years\n// When passed a tupple of numbers, it will generate an array with the\n// provided year range.\nexport function getYearsArray(\n number: [number, number] = [2018, 2028]\n): number[] {\n // Create an array +- number of years from current year\n const yearsArray: number[] = [];\n for (let i = number[0]; i <= number[1]; i++) {\n yearsArray.push(i);\n }\n // Return the array\n return yearsArray;\n}\n\nexport type YearFormat = \"short\" | \"long\";\n\nexport function getFormattedYearsArray(\n format: YearFormat,\n range: [number, number] = [2018, 2028]\n): number[] {\n const fullYearsArray = getYearsArray(range);\n if (format === \"long\") {\n return fullYearsArray;\n }\n // Modify the values of the full years array to only return YY instead\n return fullYearsArray.map((year) => Number(year.toString().substring(2)));\n}\n\nexport type MonthFormat = \"numeric\" | \"short\" | \"long\";\n\nexport function getFormattedMonthsArray(\n monthFormat: MonthFormat = \"numeric\",\n locale = \"en-US\"\n) {\n const format = new Intl.DateTimeFormat(locale, {\n month: monthFormat,\n timeZone: \"UTC\",\n }).format;\n\n return [...Array(12).keys()].map((m) => format(new Date(Date.UTC(0, m, 1))));\n}\n\ninterface GetFormattedDateProps {\n locale?: string;\n year: number;\n month: number;\n day: number;\n formatOptions?: Intl.DateTimeFormatOptions;\n displayOrder?: string;\n}\n\n// Formats a given year, month, date based on an optional local and format options\nexport function getFormattedDate({\n locale = \"en-US\",\n year,\n month,\n day,\n formatOptions = {\n weekday: \"long\",\n year: \"numeric\",\n month: \"long\",\n day: \"numeric\",\n },\n displayOrder,\n}: GetFormattedDateProps): string {\n // Correct the month, due to it being an index in the Date method\n const correctedMonth = month - 1;\n const dateFormat = new Date(year, correctedMonth, day);\n const monthName = new Intl.DateTimeFormat(locale, {\n month: formatOptions.month,\n }).format(dateFormat);\n const yearName = new Intl.DateTimeFormat(locale, {\n year: formatOptions.year,\n }).format(dateFormat);\n const dayName = new Intl.DateTimeFormat(locale, {\n day: formatOptions.day,\n }).format(dateFormat);\n\n if (displayOrder) {\n if (displayOrder == \"MMDDYY\") {\n return `${monthName} ${dayName} ${yearName}`;\n } else if (displayOrder === \"DDMMYY\") {\n return `${dayName} ${monthName} ${yearName}`;\n } else if (displayOrder === \"YYMMDD\") {\n return `${yearName} ${monthName} ${dayName}`;\n } else {\n return `${yearName} ${dayName} ${monthName}`;\n }\n }\n // If a displayOrder override isn't provided, format according to the locale:\n return new Intl.DateTimeFormat(locale, formatOptions).format(dateFormat);\n}\n\n// Formats a year to the full 4 digit year to be used in Date methods\nexport function getFormattedYear(year: number): number {\n const formattedYear =\n year.toString().length === 2\n ? new Date(Date.parse(`01 Jan 20${year}`)).getFullYear()\n : year;\n return formattedYear;\n}\n\n// Formats a month to the 2 digit month code to be used in Date methods\nexport function getFormattedMonth(month: number | string): number {\n const formattedMonth =\n typeof month === \"string\"\n ? new Date(Date.parse(`01 ${month.substring(0, 3)} 2023`)).getMonth() + 1\n : month;\n return formattedMonth;\n}\n\n// Return an array assuming the calendar week starts on Sunday\nexport function getCalendarMonthArray(\n month,\n year,\n dayOptions: { label: string; value: number; disabled: boolean }[]\n): { label: string; value: number; disabled: boolean }[] {\n const formattedYear = getFormattedYear(year);\n const firstDay = new Date(formattedYear, month, 1).getDay();\n const numberOfDays = new Date(formattedYear, month + 1, 0).getDate();\n\n const monthArray = [...Array(42).keys()].map((index) => {\n if (index < firstDay || index > numberOfDays + firstDay - 1) {\n return { label: \"\", value: 0, disabled: true };\n } else {\n return dayOptions[index - firstDay];\n }\n });\n\n return monthArray;\n}\n\n// Returns a boolean value of if a provided month, day and year form a valid date\nexport function isValidDate(year, month, day): boolean {\n const zeroIndexedMonth = month - 1;\n const d = new Date(year, zeroIndexedMonth, day);\n return (\n new Date(d).getMonth() === zeroIndexedMonth && new Date(d).getDate() === day\n );\n}\n\n// Returns the last of the month in a provided month and year\nexport function getLastDayOfMonth(year, month): number {\n const lastDay = new Date(year, month, 0).getDate();\n return lastDay;\n}\n\nexport type DayFormatOptions = \"short\" | \"long\" | \"narrow\" | undefined;\n\nexport function getDayStrings(\n locale = \"en-US\",\n dayFormat: DayFormatOptions = \"short\"\n) {\n const format = new Intl.DateTimeFormat(locale, { weekday: dayFormat }).format;\n return [...Array(7).keys()].map((day) =>\n format(new Date(Date.UTC(2021, 5, day)))\n );\n}\n","import { format, parseISO } from \"date-fns\";\nimport { Dispatch, SetStateAction, useEffect, useMemo, useState } from \"react\";\nimport { RegionInfo, RegionInfoModel, RegionInfoOptions } from \"../../models\";\nimport {\n DayFormatOptions,\n MonthFormat,\n YearFormat,\n getCalendarMonthArray,\n getDayStrings,\n getDaysArray,\n getFormattedMonthsArray,\n getFormattedYear,\n getFormattedYearsArray,\n getLastDayOfMonth,\n getMonthsArray,\n isValidDate,\n} from \"../utils/date-utils\";\nimport { useKosModel } from \"./use-kos-model\";\n\nexport type DaysOfWeekFilter = [\n number?,\n number?,\n number?,\n number?,\n number?,\n number?,\n number?\n];\n\nexport interface UseDateArrayFormatOptions {\n yearFormat?: YearFormat;\n monthFormat?: MonthFormat;\n dayFormat?: DayFormatOptions;\n}\nexport interface UseDateArraysProps {\n locale?: string;\n // TODO: Can we tighten the typing on the number?\n year?: number;\n // TODO: Can we tighten the typing on the number?\n month?: number;\n // TODO: Can we tighten the typing on the number?\n day?: number;\n formatOptions?: UseDateArrayFormatOptions;\n yearRange?: [number, number];\n daysOfWeekFilter?: DaysOfWeekFilter;\n}\n\nexport function useDateArrays({\n locale = \"en-US\",\n year = new Date().getFullYear(),\n month = new Date().getMonth(),\n yearRange = [2018, 2028],\n daysOfWeekFilter = [],\n formatOptions: {\n yearFormat = \"long\",\n monthFormat = \"long\",\n dayFormat = \"short\",\n } = {},\n}: UseDateArraysProps) {\n const yearsArray = useYears(yearFormat, yearRange);\n const yearsOptionsArray = useYearsOptions(yearFormat, yearRange, locale);\n const monthsArray = useMonths(monthFormat, locale);\n const monthsOptionsArray = useMonthsOptions(monthFormat, locale);\n const daysArray = useDays(year, month);\n const daysOptionsArray = useDayOptions(year, month, locale, daysOfWeekFilter);\n const calendarDayArray = useCalendarDayArray(month, year, daysOptionsArray);\n const dayNamesArray = useDayNames(locale, dayFormat);\n\n return {\n daysArray,\n monthsArray,\n yearsArray,\n yearsOptionsArray,\n monthsOptionsArray,\n daysOptionsArray,\n calendarDayArray,\n dayNamesArray,\n };\n}\n\n// TODO: Tighten the range type to only be positive numbers within a range\nexport function useYears(\n format: YearFormat = \"long\",\n range: [number, number] = [2018, 2028]\n): number[] {\n const yearsArray = useMemo(\n () => getFormattedYearsArray(format, range),\n [format, range]\n );\n return yearsArray;\n}\n\nexport function useYearsOptions(\n format: YearFormat = \"long\",\n range: [number, number] = [2018, 2028],\n locale = \"en-US\"\n): { label: string; value: number }[] {\n const rawYearsArray = useYears(format, range);\n const yearsOptionsArray = useMemo(\n () =>\n rawYearsArray.map((year) => {\n return {\n label: year.toLocaleString(locale).replace(\",\", \"\"),\n value: year,\n };\n }),\n [locale, rawYearsArray]\n );\n return yearsOptionsArray;\n}\n\nexport function useMonths(\n format: MonthFormat,\n locale = \"en-US\"\n): number[] | string[] {\n const monthsArray = useMemo(\n () => getFormattedMonthsArray(format, locale),\n [format, locale]\n );\n return monthsArray;\n}\n\nexport function useMonthsOptions(\n format: MonthFormat,\n locale = \"en-US\"\n): { label: string; value: number }[] {\n const monthsArray = useMemo(() => getMonthsArray(), []);\n const monthLabelsArray = useMemo(\n () => getFormattedMonthsArray(format, locale),\n [format, locale]\n );\n const monthsOptionsArray = useMemo(\n () =>\n [...Array(12).keys()].map((index) => {\n return {\n label: monthLabelsArray[index],\n value: Number(monthsArray[index]),\n };\n }),\n [monthLabelsArray, monthsArray]\n );\n\n return monthsOptionsArray;\n}\n\nexport function useDays(year: number, month: number): number[] {\n // Convert year\n const formattedYear = getFormattedYear(year);\n\n const daysArray = useMemo(\n () => getDaysArray(formattedYear, month),\n [month, formattedYear]\n );\n\n return daysArray;\n}\n\nconst isFilteredDayOfWeek = (\n year: number,\n month: number,\n day: number,\n filters: DaysOfWeekFilter = []\n): boolean => {\n const dateToCheck: number = new Date(year, month, day).getDay();\n return filters.length > 0 && filters.includes(dateToCheck);\n};\n\nexport function useDayOptions(\n year: number,\n month: number,\n locale = \"en-US\",\n daysOfWeekFilter: DaysOfWeekFilter = []\n): { label: string; value: number; disabled: boolean }[] {\n // TODO: Refactor to be able to pass in additional metadata\n const rawDaysArray = useDays(year, month);\n\n const daysOptionsArray = useMemo(\n () =>\n rawDaysArray.map((day) => {\n return {\n label: day.toLocaleString(locale),\n value: day,\n disabled: isFilteredDayOfWeek(year, month, day, daysOfWeekFilter),\n };\n }),\n [daysOfWeekFilter, locale, month, rawDaysArray, year]\n );\n\n return daysOptionsArray;\n}\nexport function useDayNames(\n locale = \"en-US\",\n dayFormat: DayFormatOptions = \"short\"\n): string[] {\n const dayNamesArray = useMemo(\n () => getDayStrings(locale, dayFormat),\n [locale, dayFormat]\n );\n return dayNamesArray;\n}\n\ninterface UseFormattedDateProps {\n // TODO: Can we tighten the typing on the number?\n year: number;\n // TODO: Can we tighten the typing on the number?\n month: number;\n // TODO: Can we tighten the typing on the number?\n day: number;\n yearRange?: number;\n formatString: string;\n}\n\nexport function useFormattedDate({\n year = new Date().getFullYear(),\n month = new Date().getMonth(),\n day = new Date().getDate(),\n formatString,\n}: UseFormattedDateProps): { formattedDate: string } {\n const indexedMonth = month;\n const date = new Date(year, indexedMonth, day);\n const formattedDate = format(date, formatString);\n\n return { formattedDate };\n}\n\nexport function useCalendarDayArray(\n month: number,\n year: number,\n dayOptionsArray: { label: string; value: number; disabled: boolean }[]\n): { label: string; value: number; disabled: boolean }[] {\n const calendarDayArray = useMemo(\n () => getCalendarMonthArray(month, year, dayOptionsArray),\n [month, year, dayOptionsArray]\n );\n return calendarDayArray;\n}\n\nexport interface UseDatePropsReturnActions {\n setYear: Dispatch<SetStateAction<number>>;\n setYearRange: Dispatch<SetStateAction<[number, number]>>;\n setMonth: Dispatch<SetStateAction<number>>;\n setDay: Dispatch<SetStateAction<number>>;\n nextMonth: () => void;\n previousMonth: () => void;\n nextYear: () => void;\n previousYear: () => void;\n}\n\nexport interface UseDatePropsReturnState {\n year: number;\n yearRange: [number, number];\n month: number;\n day: number;\n yearsArray: number[];\n yearsOptionsArray: { label: string; value: number; disabled?: boolean }[];\n monthsArray: string[] | number[];\n monthsOptionsArray: {\n label: string | number;\n value: number;\n disabled?: boolean;\n }[];\n daysArray: number[];\n daysOptionsArray: { label: string; value: number; disabled?: boolean }[];\n calendarDayNames: string[];\n calendarDayArray: {\n label: string;\n value: number;\n disabled?: boolean;\n }[];\n formattedDate: string;\n}\n\nexport interface UseDatePropsReturn {\n dateActions: UseDatePropsReturnActions;\n dateState: UseDatePropsReturnState;\n}\n\nexport enum DateDisplayFormat {\n \"MMDDYY\" = \"MMDDYY\",\n \"DDMMYY\" = \"DDMMYY\",\n \"YYMMDD\" = \"YYMMDD\",\n \"YYDDMM\" = \"YYDDMM\",\n}\n\ninterface UseDatePropsFormatOptions extends UseDateArrayFormatOptions {\n formatString?: string;\n}\ninterface UseDatePropsFilterOptions {\n yearsRange?: [number, number];\n daysOfWeekFilter?: DaysOfWeekFilter;\n}\n\ninterface UseDateProps {\n locale?: string;\n date?: { day?: number; month?: number; year?: number };\n formatOptions?: UseDatePropsFormatOptions;\n filterOptions?: UseDatePropsFilterOptions;\n}\n\nexport function useDateProps({\n locale = \"en-US\",\n date: {\n year: yearProp = new Date().getFullYear(),\n month: monthProp = new Date().getMonth(),\n day: dayProp = new Date().getDate(),\n } = {\n year: new Date().getFullYear(),\n month: new Date().getMonth(),\n day: new Date().getDate(),\n },\n formatOptions: {\n yearFormat = \"long\",\n monthFormat = \"long\",\n dayFormat = \"short\",\n formatString = \"yyyy/MM/dd\",\n } = {},\n filterOptions: {\n yearsRange = [2018, 2028] as [number, number],\n daysOfWeekFilter = [] as DaysOfWeekFilter,\n } = {},\n}: UseDateProps): UseDatePropsReturn {\n const [year, setYear] = useState<number>(yearProp);\n const [yearRange, setYearRange] = useState<[number, number]>(yearsRange);\n const [month, setMonth] = useState<number>(monthProp);\n const [day, setDay] = useState<number>(dayProp);\n\n useEffect(() => {\n setYear(yearProp);\n }, [yearProp]);\n\n useEffect(() => {\n setMonth(monthProp);\n }, [monthProp]);\n\n useEffect(() => {\n setDay(dayProp);\n }, [dayProp]);\n\n const {\n yearsArray,\n yearsOptionsArray,\n monthsArray,\n monthsOptionsArray,\n daysArray,\n daysOptionsArray,\n calendarDayArray,\n dayNamesArray,\n } = useDateArrays({\n locale,\n year,\n yearRange,\n month,\n formatOptions: {\n yearFormat,\n monthFormat,\n dayFormat,\n },\n daysOfWeekFilter,\n });\n\n const { formattedDate } = useFormattedDate({\n year,\n month,\n day,\n formatString,\n });\n\n const nextMonth = (): void => {\n // Account for going past December\n const formattedYear =\n month < 11 ? getFormattedYear(year) : getFormattedYear(year + 1);\n const nextMonth = month < 11 ? month + 1 : 0;\n\n // Account for the day and if it's valid in the month\n if (!isValidDate(formattedYear, nextMonth, day)) {\n const lastValidDay = getLastDayOfMonth(formattedYear, nextMonth);\n setDay(lastValidDay);\n }\n if (nextMonth === 0) {\n setYear(formattedYear);\n }\n setMonth(nextMonth);\n };\n\n const previousMonth = (): void => {\n // Account for going before January\n const formattedYear =\n month === 0 ? getFormattedYear(year - 1) : getFormattedYear(year);\n\n const prevMonth = month === 0 ? 11 : month - 1;\n // Account for the day and if it's valid in the month\n if (!isValidDate(formattedYear, prevMonth, day)) {\n const lastValidDay = getLastDayOfMonth(formattedYear, prevMonth);\n setDay(lastValidDay);\n }\n if (prevMonth === 11) {\n setYear(formattedYear);\n }\n setMonth(prevMonth);\n };\n\n const nextYear = (): void => {\n const nextYear = year < yearRange[1] ? year + 1 : yearRange[0];\n // Account for the day and if it's valid in the month\n const formattedYear = getFormattedYear(nextYear);\n\n if (isValidDate(formattedYear, month, day)) {\n setYear(nextYear);\n } else {\n // If it's not a valid day, change the day to the last day of the month\n const lastValidDay = getLastDayOfMonth(getFormattedYear(year + 1), month);\n setDay(lastValidDay);\n setYear(nextYear);\n }\n };\n\n const previousYear = (): void => {\n const prevYear = year > yearRange[0] ? year - 1 : yearRange[0];\n const formattedYear = getFormattedYear(prevYear);\n\n if (isValidDate(formattedYear, month, day)) {\n setYear(prevYear);\n } else {\n // If it's not a valid day, change the day to the last day of the month\n const lastValidDay = getLastDayOfMonth(getFormattedYear(year - 1), month);\n setDay(lastValidDay);\n setYear(prevYear);\n }\n };\n\n return {\n dateActions: {\n setYear,\n setYearRange,\n setMonth,\n setDay,\n nextMonth,\n previousMonth,\n nextYear,\n previousYear,\n },\n dateState: {\n year,\n yearRange,\n month,\n day,\n yearsArray,\n yearsOptionsArray,\n monthsArray,\n monthsOptionsArray,\n daysArray,\n daysOptionsArray,\n calendarDayNames: dayNamesArray,\n calendarDayArray,\n formattedDate,\n },\n };\n}\n\nexport interface UseRegionalFormatProps {\n date?: Date | string;\n dateFormat?: string;\n timeFormat?: string;\n options?: {\n ignoreDateFormat?: boolean;\n };\n}\n\nexport function useRegionalTimeDate({\n date = new Date(),\n dateFormat,\n timeFormat,\n options = {},\n}: UseRegionalFormatProps): { formattedDate: string; formattedTime: string } {\n const [formattedTime, setFormattedTime] = useState(\"Formatting Time...\");\n const [formattedDate, setFormattedDate] = useState(\"Formatting Date...\");\n\n const ignoreDate = !!options.ignoreDateFormat;\n const { model, ready } = useKosModel<RegionInfoModel, RegionInfoOptions>({\n modelId: RegionInfo.type,\n modelType: RegionInfo.type,\n options: {},\n });\n const dateToFormat = typeof date === \"string\" ? parseISO(date) : date;\n\n useEffect(() => {\n if (ignoreDate) {\n setFormattedDate(\"\");\n } else if (dateFormat) {\n // Set date according to format string\n setFormattedDate(format(dateToFormat, dateFormat));\n } else {\n // Set date according to model if no date format string provided\n if (ready) {\n setFormattedDate(\n format(\n dateToFormat,\n model?.selectedDateFormat ? model?.selectedDateFormat : \"\"\n )\n );\n }\n }\n }, [ignoreDate, date, dateFormat, dateToFormat, model, ready]);\n\n useEffect(() => {\n if (timeFormat) {\n // Set date according to format string\n setFormattedTime(format(dateToFormat, timeFormat));\n } else {\n // Set date according to model if no time format string provided\n if (ready) {\n setFormattedTime(\n format(\n dateToFormat,\n model?.selectedTimeFormat ? model?.selectedTimeFormat : \"\"\n )\n );\n }\n }\n }, [date, timeFormat, dateToFormat, model, ready]);\n\n return { formattedDate, formattedTime };\n}\n","import { useEffect, useRef, useState } from \"react\";\nimport type { KosConfigProperty } from \"../../models\";\nimport { useConfigProperty } from \"./use-config-property\";\nimport { useRegionalTimeDate } from \"./use-date-props\";\n\ninterface Props {\n configProperty?: KosConfigProperty<number>;\n is24Hr?: boolean;\n}\n\ninterface DateRelative {\n hours: number;\n minutes: number;\n seconds: number;\n formattedTime;\n timeActions: {\n setHours: (hours: number) => void;\n setMinutes: (minutes: number) => void;\n setSeconds: (seconds: number) => void;\n };\n}\ninterface DateRelativeDataProps {\n secondsFromMidnight?: number;\n}\n\n/**\n * Hook to convert seconds from midnight to a human readable time format\n *\n * The hook will use the time format based on the regional settings\n *\n * @param secondsFromMidnight - The number of seconds from midnight\n * @returns The hours, minutes, seconds, formatted time and actions to update the time\n */\nexport const useDateRelativeData = ({\n secondsFromMidnight = 0,\n}: DateRelativeDataProps) => {\n const [hours, setHours] = useState(0);\n const [minutes, setMinutes] = useState(0);\n const [seconds, setSeconds] = useState(0);\n const [date, setDate] = useState(new Date());\n const { formattedTime } = useRegionalTimeDate({\n date,\n options: {\n ignoreDateFormat: true,\n },\n });\n useEffect(() => {\n const numericValue = Number(secondsFromMidnight);\n const _hours = Math.floor(numericValue / 3600);\n const _minutes = Math.floor((numericValue % 3600) / 60);\n const _seconds = numericValue % 60;\n setHours(_hours);\n setMinutes(_minutes);\n setSeconds(_seconds);\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() + numericValue * 1000);\n setDate(new Date(time));\n }, [secondsFromMidnight]);\n\n return {\n hours,\n minutes,\n seconds,\n formattedTime,\n timeActions: {\n setHours,\n setMinutes,\n setSeconds,\n },\n };\n};\n\n/**\n * Hook to translate date relative configuration properties to human readable time\n *\n * @param configProperty - The configuration property to use\n * @returns\n * @see useDateRelativeData\n */\nexport const useDateRelativeConfig = ({\n configProperty,\n}: Props): DateRelative => {\n const { value } = useConfigProperty({ configProperty });\n\n const secondsFromMidnight = parseInt(value || \"0\", 10);\n const { hours, minutes, seconds, formattedTime, timeActions } =\n useDateRelativeData({\n secondsFromMidnight,\n });\n\n const timeoutRef = useRef<NodeJS.Timeout>();\n\n useEffect(() => {\n // Calculate the new value only once per effect run\n const newValue = hours * 3600 + minutes * 60 + seconds;\n\n // Clear any previously set timeout to ensure only the latest update is applied\n if (timeoutRef.current) {\n clearTimeout(timeoutRef.current);\n }\n\n // Set a new timeout to update the property after 100ms\n timeoutRef.current = setTimeout(() => {\n if (configProperty) {\n configProperty.updateProperty(newValue.toString());\n }\n }, 100); // 100 milliseconds delay\n\n // Cleanup function to clear the timeout if the component is unmounted or dependencies change\n return () => {\n if (timeoutRef.current) {\n clearTimeout(timeoutRef.current);\n }\n };\n }, [configProperty, hours, minutes, seconds]); // Dependencies list\n return {\n hours,\n minutes,\n seconds,\n formattedTime,\n timeActions,\n };\n};\n","import { useEffect } from \"react\";\n\n// A warmup marker to simulate a special execution path\n/**\n * Represents a marker type used to indicate that a function or process\n * has been warmed up and is ready for use.\n *\n * This type is typically used as a flag or annotation in scenarios\n * where initialization or preparation steps are required before\n * execution.\n */\nexport type WarmupMarker = { __warmup: true };\n\n// Accepts a function that takes 0 or 1 argument\ntype Warmupable<T extends (arg?: any) => any> = (\n arg?: any | WarmupMarker\n) => ReturnType<T>;\n\ninterface UseFunctionWarmupOptions {\n intervalMs?: number; // How often to re-warm (ms)\n immediate?: boolean; // Should warmup run on mount\n}\n\n/**\n * A React hook that periodically invokes a given function to keep it \"warmed up.\"\n * This can be useful for functions that require initialization or caching to\n * improve performance during actual usage.\n *\n * @template T - The type of the function to be warmed up.\n * @param fn - The function to be warmed up. It should accept an optional argument\n * and handle a special warmup call with `{ __warmup: true }`.\n * @param options - Configuration options for the warmup behavior.\n * @param options.intervalMs - The interval in milliseconds at which the function\n * should be warmed up. Defaults to 5 minutes (300,000 ms).\n * If set to `null` or `0`, periodic warmup is disabled.\n * @param options.immediate - Whether to perform an immediate warmup when the hook\n * is first invoked. Defaults to `true`.\n *\n * @returns void\n *\n * @remarks\n * - If the `immediate` option is enabled, the function will be warmed up immediately\n * using `requestIdleCallback` if available, or a `setTimeout` fallback.\n * - Errors thrown during the warmup process are caught and ignored.\n * - The periodic warmup is cleaned up automatically when the component unmounts.\n *\n * @example\n * ```tsx\n * const lookup = (arg?: string | WarmupMarker) => {\n * if (typeof arg === \"object\" && arg.__warmup) return;\n * // ...\n * };\n * useFunctionWarmup(lookup, { intervalMs: 60000 });\n * ```\n */\nexport function useFunctionWarmup<T extends (arg?: any) => any>(\n fn: Warmupable<T>,\n options: UseFunctionWarmupOptions = {}\n) {\n const { intervalMs = 5 * 60 * 1000, immediate = true } = options;\n\n useEffect(() => {\n const warmup = () => {\n try {\n fn({ __warmup: true });\n } catch {\n // ignore errors from warmup path\n }\n };\n\n if (immediate) {\n if (\"requestIdleCallback\" in window) {\n requestIdleCallback(warmup);\n } else {\n setTimeout(warmup, 1);\n }\n }\n\n const id = intervalMs ? setInterval(warmup, intervalMs) : null;\n return () => {\n if (id) clearInterval(id);\n };\n }, [fn, intervalMs, immediate]);\n}\n","import { RegionInfo } from \"../../models\";\n\nimport { kosAutoEffect } from \"../../core\";\nimport type {\n DateFormatOptions,\n RegionInfoModel,\n RegionInfoOptions,\n} from \"../../models\";\n\nimport { ChangeEvent, useCallback, useEffect, useState } from \"react\";\nimport { useKosModel } from \"./use-kos-model\";\n\ntype SelectCallback = string | ChangeEvent<HTMLSelectElement>;\ntype DateFormatMap<T extends {} = any> = (format: DateFormatOptions) => T;\nconst DEFAULT_FORMAT_MAP: DateFormatMap = (format: DateFormatOptions) => (\n <option title={format.id} key={format.id} value={format.format}>\n {format.format}\n </option>\n);\n\n/**\n * The data returned from the useKosDateFormats hook.\n * @typeParam T - the type of the options returned from the dateFormatMap function.\n */\nexport interface KosDateFormatHookData<T extends {} = any> {\n /** the ids of the available date formats. */\n raw: string[];\n\n /** the region info model. */\n regionModel?: RegionInfoModel;\n\n /** the currently selected date format. */\n selectedDateFormat: string;\n\n dateFormatId: string;\n /** updates the selected date format. */\n updateDateFormat: (e: SelectCallback) => void;\n\n /**the props that can be spread into a select box component. */\n props: {\n onChange: (e: SelectCallback) => void;\n value: string;\n options: T[];\n };\n}\n\n/**\n * Manages the region's date format: the available formats, the selected\n * format, and props for a date format select box.\n *\n * @param dateFormatMap - maps a date format to a select-box option. The\n * default returns an `<option>` with the format as value and label.\n * @returns KosDateFormatHookData - the data returned from the hook.\n * @example\n * ```tsx\n * const { props } = useKosDateFormats();\n * const { options, ...selectAttributes } = props;\n * return <select {...selectAttributes}>{options}</select>;\n * ```\n */\nexport const useKosDateFormats = <T extends {} = any>(\n dateFormatMap: DateFormatMap<T> = DEFAULT_FORMAT_MAP\n): KosDateFormatHookData<T> => {\n const [dateFormats, setDateFormats] = useState<T[]>([]);\n const [selectedDateFormat, setSelectedDateFormat] = useState<{\n id: string;\n value: string;\n }>();\n\n const { model, ready } = useKosModel<RegionInfoModel, RegionInfoOptions>({\n modelType: RegionInfo.type,\n modelId: RegionInfo.type,\n options: {},\n });\n\n useEffect(() => {\n const cleanup = kosAutoEffect(() => {\n setDateFormats(model?.dateFormatOptions.map(dateFormatMap) || []);\n });\n\n return () => {\n cleanup();\n };\n }, [model, ready, dateFormatMap]);\n\n useEffect(() => {\n const cleanup = kosAutoEffect(() => {\n if (model?.dateFormatId && model?.selectedDateFormat) {\n setSelectedDateFormat({\n id: model?.dateFormatId,\n value: model?.selectedDateFormat,\n });\n }\n });\n\n return () => {\n cleanup();\n };\n }, [model?.selectedDateFormat, model?.dateFormatId]);\n\n const handleDateFormatChange = useCallback(\n (e: SelectCallback) => {\n let value = \"\";\n if (typeof e === \"string\") {\n value = e;\n } else if (e?.target?.value) {\n value = e.target.value;\n }\n\n if (value) {\n model?.setSelectedDateFormat(value);\n }\n },\n [model]\n );\n\n return {\n raw: model?.dateFormatOptions.map((o) => o.id) ?? [],\n regionModel: model,\n selectedDateFormat: selectedDateFormat?.value || \"\",\n dateFormatId: selectedDateFormat?.id || \"\",\n updateDateFormat: handleDateFormatChange,\n props: {\n onChange: handleDateFormatChange,\n value: selectedDateFormat?.id || \"\",\n options: dateFormats,\n },\n };\n};\n","import { ChangeEvent, useCallback, useEffect, useState } from \"react\";\nimport { kosAutoEffect } from \"../../core\";\nimport {\n KosConfigProperty,\n KosConfigPropertySpec,\n RegionInfo,\n RegionInfoModel,\n RegionInfoOptions,\n updateTimeZone,\n} from \"../../models\";\nimport { useKosModel } from \"./use-kos-model\";\n\ntype SelectCallback = string | ChangeEvent<HTMLSelectElement>;\ntype OptionMap<T extends {} = any> = (option: string) => T;\n\nconst DEFAULT_OPTION_MAP: OptionMap = (option: string) => (\n <option title={option} key={option} value={option}>\n {option}\n </option>\n);\n\nconst REGION_SETTINGS_PATH = \"kos:service:region:settings\";\nconst TIMEZONE_ATTRIBUTE = \"timeZone\";\nconst REGION_TIMEZONE_ID = `${REGION_SETTINGS_PATH}-${TIMEZONE_ATTRIBUTE}`;\n\n/**\n * Custom React hook for managing and interacting with timezone data.\n * It fetches timezone information from the RegionInfoModel and facilitates\n * timezone selection in a React application.\n *\n * @typeparam T The type of the options that the hook will produce for use in UI components.\n * @param optionsMap A function that maps a timezone string to a JSX structure or other specified format.\n * @returns An object containing timezone options, raw timezone data, the selected timezone, and functions to handle updates.\n *\n * @example\n * ```tsx\n * const TimeZonePicker = kosComponent(() => {\n * const { selectProps } = useKosTimeZones();\n * const { options, ...props } = selectProps;\n * return <select {...props}>{options}</select>;\n * });\n * ```\n */\nexport const useKosTimeZones = <T extends {} = any>(\n optionsMap: OptionMap<T> = DEFAULT_OPTION_MAP\n) => {\n const [timeZones, setTimeZones] = useState<T[]>([]);\n const [selectedTimeZone, setSelectedTimeZone] = useState<string>(\"\");\n\n // Fetches the RegionInfoModel using the useKosModel hook.\n const { model, ready } = useKosModel<RegionInfoModel, RegionInfoOptions>({\n modelType: RegionInfo.type,\n modelId: RegionInfo.type,\n options: {},\n });\n\n // Defines a KosConfigProperty for timezone information.\n const timezoneInfo: KosConfigProperty<string> = KosConfigPropertySpec.factory(\n REGION_TIMEZONE_ID\n )({\n path: REGION_SETTINGS_PATH,\n attribute: TIMEZONE_ATTRIBUTE,\n }) as KosConfigProperty<string>;\n\n // Updates the timeZones state when the model changes.\n useEffect(() => {\n const cleanup = kosAutoEffect(() => {\n setTimeZones(model?.timeZones.map(optionsMap) || []);\n\n if (model?.timeZones.length) {\n updateTimeZone(model?.timeZones[0]);\n }\n });\n\n return () => {\n cleanup();\n };\n }, [model, ready, optionsMap]);\n\n // Updates the selectedTimeZone state based on the timezoneInfo value.\n useEffect(() => {\n const cleanup = kosAutoEffect(() => {\n setSelectedTimeZone(timezoneInfo.value || \"\");\n });\n\n return () => {\n cleanup();\n };\n }, [timezoneInfo.value]);\n\n // Callback function to handle timezone updates.\n const handleUpdate = useCallback((e: SelectCallback) => {\n let value = \"factory\";\n if (typeof e === \"string\") {\n value = e;\n } else if (e?.target?.value) {\n value = e.target.value;\n }\n\n if (value) {\n updateTimeZone(value);\n }\n }, []);\n\n return {\n options: timeZones,\n raw: model?.timeZones ?? [],\n regionModel: model,\n selectedTimeZone,\n timeZones: model?.timeZones ?? [],\n updateTimeZone: handleUpdate,\n selectProps: {\n onChange: handleUpdate,\n value: selectedTimeZone,\n options: timeZones,\n },\n };\n};\n","import { ChangeEvent, useCallback, useEffect, useState } from \"react\";\nimport { kosAutoEffect } from \"../../core\";\nimport {\n KosConfigPropertySpec,\n type KosConfigProperty,\n} from \"../../models/models/config-bean-prop\";\nimport {\n RegionInfo,\n RegionInfoOptions,\n RegionServices,\n type RegionInfoModel,\n} from \"../../models/models/region-info\";\nimport { updateRegion } from \"../../models/utils/region-utils\";\nimport { useKosModel } from \"./use-kos-model\";\n\nconst REGION_PATH = \"kos:service:region\";\nconst REGION_ATTRIBUTE = \"regionId\";\nconst REGION_ID = `${REGION_PATH}-${REGION_ATTRIBUTE}`;\n\ntype SelectCallback = string | ChangeEvent<HTMLSelectElement>;\ntype RegionMap<T extends object = any> = (region: string) => T;\nconst DEFAULT_REGION_MAP: RegionMap = (region: string) => (\n <option title={region} key={region} value={region}>\n {region}\n </option>\n);\n\n/**\n * The data returned from the useKosRegions hook.\n * @typeParam RegionData - the region data returned from the backend service. Must extend `RegionServices.BaseRegionResponse`.\n * @typeParam T - the type of the options returned from the regionMap function.\n */\nexport interface KosRegionHookData<\n RegionData extends RegionServices.BaseRegionResponse = RegionServices.BaseRegionResponse,\n T extends object = any\n> {\n /**the raw region data returned from the backend service. */\n raw: string[];\n\n /**the region model returned from the backend service. */\n regionModel?: RegionInfoModel<RegionData>;\n\n /** the region data returned from the backend service. */\n regionData?: RegionData;\n\n /**the currently selected region. */\n selectedRegion: string;\n\n /**a function that can be used to update the region. */\n updateRegion: (e: SelectCallback) => void;\n\n /**the props that can be spread into a select box component. */\n regionSelectProps: {\n onChange: (e: SelectCallback) => void;\n value: string;\n options: T[];\n };\n}\n\n/**\n * Manages the device region: the available regions, the selected region and\n * its data, and props for a region select box.\n *\n * @typeParam RegionData - the region data returned from the backend service. Must extend `RegionServices.BaseRegionResponse`.\n * @param regionMap - maps a region string to a select-box option. The default\n * returns an `<option>` with the region as value and label. Pass a custom map\n * when a third-party select component expects a different option shape.\n * @returns KosRegionHookData - the data returned from the hook.\n * @example\n * ```tsx\n * const { regionSelectProps, selectedRegion } = useKosRegions();\n * const { options, ...selectAttributes } = regionSelectProps;\n * return <select {...selectAttributes}>{options}</select>;\n * ```\n */\nexport const useKosRegions = <\n RegionData extends RegionServices.BaseRegionResponse = RegionServices.BaseRegionResponse,\n T extends {} = any\n>(\n regionMap: RegionMap<T> = DEFAULT_REGION_MAP\n): KosRegionHookData<RegionData, T> => {\n const [regions, setRegions] = useState<T[]>([]);\n const [selectedRegion, setSelectedRegion] = useState<string>(\"factory\");\n const { model, ready } = useKosModel<\n RegionInfoModel<RegionData>,\n RegionInfoOptions\n >({\n modelType: RegionInfo.type,\n modelId: RegionInfo.type,\n });\n\n const regionInfo: KosConfigProperty<string> = KosConfigPropertySpec.factory(\n REGION_ID\n )({\n path: REGION_PATH,\n attribute: REGION_ATTRIBUTE,\n }) as KosConfigProperty<string>;\n useEffect(() => {\n const cleanup = kosAutoEffect(() => {\n setRegions(model?.availableRegions.map(regionMap) || []);\n });\n\n return () => {\n cleanup();\n };\n }, [model, ready, regionMap]);\n\n useEffect(() => {\n const cleanup = kosAutoEffect(() => {\n setSelectedRegion(regionInfo.value || \"factory\");\n });\n\n return () => {\n cleanup();\n };\n }, [regionInfo.value]);\n\n const handleUpdate = useCallback((e: SelectCallback) => {\n let value = \"factory\";\n if (typeof e === \"string\") {\n value = e;\n } else if (e?.target?.value) {\n value = e.target.value;\n }\n\n if (value) {\n updateRegion(value);\n }\n }, []);\n\n return {\n raw: model?.availableRegions ?? [],\n regionModel: model,\n regionData: model?.selectedRegion,\n selectedRegion,\n updateRegion: handleUpdate,\n\n regionSelectProps: {\n onChange: handleUpdate,\n value: selectedRegion,\n options: regions,\n },\n };\n};\n","import { RegionInfo } from \"../../models/models/region-info\";\n\nimport { kosAutoEffect } from \"../../core\";\nimport type {\n RegionInfoModel,\n RegionInfoOptions,\n TimeFormatOptions,\n} from \"../../models/models/region-info\";\n\nimport { ChangeEvent, useCallback, useEffect, useState } from \"react\";\nimport { useKosModel } from \"./use-kos-model\";\n\ntype SelectCallback = string | ChangeEvent<HTMLSelectElement>;\ntype TimeFormatMap<T extends {} = any> = (format: TimeFormatOptions) => T;\nconst DEFAULT_FORMAT_MAP: TimeFormatMap = (format: TimeFormatOptions) => (\n <option title={format.id} key={format.id} value={format.format}>\n {format.format}\n </option>\n);\n\n/**\n * The data returned from the useKosTimeFormats hook.\n * @typeParam T - the type of the options returned from the timeFormatMap function.\n */\nexport interface KosTimeFormatHookData<T extends {} = any> {\n /** the ids of the available time formats. */\n raw: string[];\n\n /** the region info model. */\n regionModel?: RegionInfoModel;\n\n /** the currently selected time format. */\n selectedTimeFormat: string;\n\n timeFormatId: string;\n /** updates the selected time format. */\n updateTimeFormat: (e: SelectCallback) => void;\n\n /**the props that can be spread into a select box component. */\n props: {\n onChange: (e: SelectCallback) => void;\n value: string;\n options: T[];\n };\n}\n\n/**\n * Manages the region's time format: the available formats, the selected\n * format, and props for a time format select box.\n *\n * @param timeFormatMap - maps a time format to a select-box option. The\n * default returns an `<option>` with the format as value and label.\n * @returns KosTimeFormatHookData - the data returned from the hook.\n * @example\n * ```tsx\n * const { props } = useKosTimeFormats();\n * const { options, ...selectAttributes } = props;\n * return <select {...selectAttributes}>{options}</select>;\n * ```\n */\nexport const useKosTimeFormats = <T extends {} = any>(\n timeFormatMap: TimeFormatMap<T> = DEFAULT_FORMAT_MAP\n): KosTimeFormatHookData<T> => {\n const [timeFormats, setTimeFormats] = useState<T[]>([]);\n const [selectedTimeFormat, setSelectedTimeFormat] = useState<{\n id: string;\n value: string;\n }>();\n const { model, ready } = useKosModel<RegionInfoModel, RegionInfoOptions>({\n modelType: RegionInfo.type,\n modelId: RegionInfo.type,\n options: {},\n });\n\n useEffect(() => {\n const cleanup = kosAutoEffect(() => {\n setTimeFormats(model?.timeFormatOptions.map(timeFormatMap) || []);\n });\n\n return () => {\n cleanup();\n };\n }, [model, ready, timeFormatMap]);\n\n useEffect(() => {\n const cleanup = kosAutoEffect(() => {\n if (model?.timeFormatId && model?.selectedTimeFormat) {\n setSelectedTimeFormat({\n id: model?.timeFormatId,\n value: model?.selectedTimeFormat,\n });\n }\n });\n\n return () => {\n cleanup();\n };\n }, [model?.selectedTimeFormat, model?.timeFormatId]);\n\n const handleTimeFormatChange = useCallback(\n (e: SelectCallback) => {\n let value = \"\";\n if (typeof e === \"string\") {\n value = e;\n } else if (e?.target?.value) {\n value = e.target.value;\n }\n\n if (value) {\n model?.setSelectedTimeFormat(value);\n }\n },\n [model]\n );\n\n return {\n raw: model?.timeFormatOptions.map((o) => o.id) ?? [],\n regionModel: model,\n selectedTimeFormat: selectedTimeFormat?.value ?? \"\",\n timeFormatId: selectedTimeFormat?.id ?? \"\",\n updateTimeFormat: handleTimeFormatChange,\n props: {\n onChange: handleTimeFormatChange,\n value: selectedTimeFormat?.id ?? \"\",\n options: timeFormats,\n },\n };\n};\n","import { useMemo } from \"react\";\nimport { kosComputed } from \"../../core\";\n\n/**\n * @description An abstraction of React's useMemo for observable dependencies.\n * @param callback A function that returns a desired value.\n * @param dependencies An array of non-observable variables that are required to run the callback.\n */\nexport const useLocalComputed = <T>(\n callback: () => T,\n dependencies: ReadonlyArray<unknown>\n) => useMemo(() => kosComputed(callback), dependencies);\n","import { useEffect, useState } from \"react\";\nimport { KosLog } from \"../../core/core/log\";\n\ninterface MutationObserverOptions {\n config: MutationObserverInit;\n}\n\n// Default options for the MutationObserver\nconst DEFAULT_OPTIONS: MutationObserverOptions = {\n config: { attributes: true, childList: true, subtree: true },\n};\n\n/**\n * A hook that creates a MutationObserver and observes a DOM element for mutations. When a mutation occurs, the callback function is executed.\n *\n * @param targetEl The DOM element to observe\n * @param cb The callback function to execute when a mutation occurs\n * @param options Options to pass to the MutationObserver to configure what mutations to observe\n */\nexport function useMutationObserver<T extends Node>(\n targetEl: T,\n cb: MutationCallback,\n options: MutationObserverOptions = DEFAULT_OPTIONS\n) {\n const [observer, setObserver] = useState<MutationObserver | null>(null);\n useEffect(() => {\n // Validate the callback function\n if (!cb || typeof cb !== \"function\") {\n throw new Error(\"A valid callback function is required\");\n }\n const obs = new MutationObserver(cb);\n setObserver(obs);\n }, [cb, options, setObserver]);\n\n useEffect(() => {\n // Validate the observer\n if (!observer) return () => {};\n\n // Validate the target element\n if (!targetEl) {\n throw new Error(\"A valid DOM element is required\");\n }\n const { config } = options;\n try {\n // Start observing the target element for configured mutations\n observer.observe(targetEl, config);\n } catch (e) {\n KosLog.error(e);\n }\n return () => {\n // Stop observing the target element\n if (observer) {\n observer.disconnect();\n }\n };\n }, [observer, targetEl, options]);\n}\n","import {\n IntersectionStrategy,\n IntersectionStrategyState,\n} from \"./intersection-strategy\";\n\nexport const DomIntersectionStrategy: IntersectionStrategy = {\n validateStart: function (_state: IntersectionStrategyState): boolean {\n return true;\n },\n validateStop: function (state: IntersectionStrategyState): boolean {\n const boundingRect = (\n state.event.currentTarget as HTMLElement\n ).getBoundingClientRect();\n const [clientX, clientY] = state.xy;\n\n const isOutside =\n clientX < boundingRect.left ||\n clientX > boundingRect.right ||\n clientY < boundingRect.top ||\n clientY > boundingRect.bottom;\n\n return isOutside;\n },\n};\n","import { useGesture } from \"@use-gesture/react\";\nimport { useRef } from \"react\";\nimport { KosLog } from \"../../../core/core/log\";\nimport { DomIntersectionStrategy } from \"./strategy/dom-intersection-strategy\";\nimport { IntersectionStrategy } from \"./strategy/intersection-strategy\";\n\ninterface PressHandlers {\n onPressed?: () => void;\n onRelease?: () => void;\n intersectionStrategy?: IntersectionStrategy;\n}\n\nconst logger = KosLog.createLogger({\n name: \"usePressGesture\",\n group: \"kos-hooks\",\n});\nexport function usePressGesture({\n onPressed,\n onRelease,\n intersectionStrategy = DomIntersectionStrategy,\n}: PressHandlers) {\n const isDraggingInside = useRef<boolean>(false);\n\n const bind = useGesture({\n onDragStart: (state) => {\n logger.info(\"onDragStart\", state.type);\n if (!intersectionStrategy.validateStart(state)) return;\n\n if (onPressed) onPressed();\n isDraggingInside.current = true;\n },\n onDrag: (state) => {\n logger.info(\"onDrag\", state.type);\n if (!isDraggingInside.current) return;\n\n if (intersectionStrategy.validateStop(state)) {\n if (onRelease) onRelease();\n isDraggingInside.current = false;\n }\n },\n onDragEnd: (state) => {\n logger.info(\"onDragEnd\", state.type);\n if (isDraggingInside.current && onRelease) {\n onRelease();\n isDraggingInside.current = false;\n }\n },\n });\n\n const handlePointerDown = () => {\n if (onPressed) onPressed();\n isDraggingInside.current = true;\n };\n\n const handlePointerUp = () => {\n if (isDraggingInside.current && onRelease) {\n onRelease();\n isDraggingInside.current = false;\n }\n };\n\n const handlePointerOut = () => {\n if (isDraggingInside.current && onRelease) {\n onRelease();\n isDraggingInside.current = false;\n }\n };\n\n return {\n dom: bind,\n mesh: () => {\n return {\n onPointerDown: handlePointerDown,\n onPointerUp: handlePointerUp,\n onPointerOut: handlePointerOut,\n };\n },\n };\n}\n","import { useEffect, useState } from \"react\";\nimport { kosAutoEffect, KosCore } from \"../../core\";\nexport const useProjectReload = () => {\n const [reloading, setReloading] = useState(false);\n const core = KosCore.getInstance();\n useEffect(() => {\n const disposer = kosAutoEffect(() => {\n if (!core) return;\n if (core.reloading === reloading) return;\n setReloading(core.reloading);\n });\n\n return () => {\n disposer();\n };\n }, [core, reloading]);\n\n return [reloading];\n};\n","import { useCallback, useMemo, useState } from \"react\";\nimport { format } from \"date-fns\";\n\ntype TimeFormat = \"2-digit\" | \"numeric\";\n\nexport function useHourValues(hour12 = false, format: TimeFormat = \"2-digit\") {\n return useMemo(() => {\n const hours = hour12 ? 12 : 24;\n\n return Array.from({ length: hours }, (_, i) => {\n const hour = hour12 && i === 0 ? 12 : i % hours;\n\n return {\n id: i,\n label:\n format === \"2-digit\"\n ? hour.toString().padStart(2, \"0\")\n : hour.toString(),\n };\n });\n }, [format, hour12]);\n}\n\nexport function useTimeValues(\n length: number,\n format: TimeFormat = \"2-digit\",\n labelOffset = 0,\n valueOffset = 0\n) {\n return useMemo(\n () =>\n Array.from({ length }, (_, i) => {\n const label = String(i + labelOffset);\n\n return {\n id: i + valueOffset,\n label: format === \"2-digit\" ? label.padStart(2, \"0\") : label,\n };\n }),\n [length, labelOffset, valueOffset, format]\n );\n}\n\nexport function useAmPmValues(locale = \"en-US\") {\n return useMemo(\n () =>\n [\"AM\", \"PM\"].map((period) => {\n const formattedPeriod = new Intl.DateTimeFormat(locale, {\n hour: \"2-digit\",\n hour12: true,\n }).formatToParts(new Date().setHours(period === \"AM\" ? 0 : 12))[2]\n .value;\n\n return { id: formattedPeriod, label: formattedPeriod };\n }),\n [locale]\n );\n}\n\nexport interface UseTimeOptionsProps {\n formatOptions?: Intl.DateTimeFormatOptions;\n locale?: string;\n}\n\nexport function useTimeOptions({\n formatOptions: {\n hour12 = true,\n hour = \"2-digit\",\n minute = \"2-digit\",\n second = \"2-digit\",\n } = { hour12: true, hour: \"2-digit\", minute: \"2-digit\", second: \"2-digit\" },\n locale = \"en-US\",\n}: UseTimeOptionsProps) {\n const hourOptions = useHourValues(hour12, hour);\n const minuteOptions = useTimeValues(60, minute);\n const secondOptions = useTimeValues(60, second);\n const amPmOptions = useAmPmValues(locale);\n\n return {\n hourOptions,\n minuteOptions,\n secondOptions,\n amPmOptions,\n };\n}\n\nexport function useFormattedTime(date: Date, formatString: string): string {\n const formattedDate = format(date, formatString);\n\n return formattedDate;\n}\n\nexport interface UseTimeProps {\n formatOptions?: Intl.DateTimeFormatOptions;\n initialDate?: Date;\n locale?: string;\n format?: string;\n}\n\nexport function useTimeProps({\n formatOptions,\n initialDate = new Date(),\n locale = \"en-US\",\n format = \"HH:mm\",\n}: UseTimeProps) {\n const [date, setDate] = useState(initialDate);\n\n const setHours = useCallback((hours: number) => {\n setDate((prevDate) => {\n const newDate = new Date(prevDate);\n newDate.setHours(Number(hours));\n\n return newDate;\n });\n }, []);\n\n const setMinutes = useCallback((minutes: number) => {\n setDate((prevDate) => {\n const newDate = new Date(prevDate);\n newDate.setMinutes(Number(minutes));\n\n return newDate;\n });\n }, []);\n\n const setSeconds = useCallback((seconds: number) => {\n setDate((prevDate) => {\n const newDate = new Date(prevDate);\n newDate.setSeconds(Number(seconds));\n\n return newDate;\n });\n }, []);\n\n const setTime = useCallback((date: Date) => {\n const newDate = new Date(date);\n\n setDate(newDate);\n }, []);\n\n const formattedTime = useFormattedTime(date, format);\n\n const { hourOptions, minuteOptions, secondOptions, amPmOptions } =\n useTimeOptions({\n formatOptions,\n locale,\n });\n\n return {\n amPmOptions,\n formattedTime,\n hourOptions,\n minuteOptions,\n secondOptions,\n setHours,\n setMinutes,\n setSeconds,\n setTime,\n time: new Date(date),\n };\n}\n","import { useMemo } from \"react\";\nimport { useKosRegions } from \"./use-kos-regions\";\nimport { useTimeProps, type UseTimeProps } from \"./use-time-props\";\n\nexport const useRegionTimeProps = (props?: UseTimeProps) => {\n const { regionModel } = useKosRegions();\n\n const formatOptions = useMemo(() => {\n return { hour12: regionModel?.is12HourTimeFormat };\n }, [regionModel?.is12HourTimeFormat]);\n\n return useTimeProps({\n ...props,\n locale: regionModel?.regionId,\n format: regionModel?.selectedTimeFormat,\n formatOptions,\n });\n};\n","import { useEffect, useMemo, useRef, useState } from \"react\";\nimport {\n hasReadyHook,\n isDisposable,\n} from \"../../../core/core/decorators/kos-view-model\";\n\n/**\n * Configuration options for the useViewModel hook.\n */\nexport interface UseViewModelOptions {\n /**\n * When true, calls the ViewModel's dispose() method on unmount\n * and when dependencies change causing recreation.\n * Default: true (if dispose method exists)\n */\n disposeOnUnmount?: boolean;\n}\n\n/**\n * Result returned by useViewModel when the ViewModel implements IKosViewModelReady.\n */\nexport interface UseViewModelResult<T> {\n /** The ViewModel instance */\n viewModel: T;\n /** Whether the ViewModel's ready() hook has completed */\n ready: boolean;\n /** Error from the ready() hook, if any */\n error: Error | undefined;\n}\n\n/**\n * React hook for creating and managing ViewModel instances.\n *\n * The hook:\n * - Creates the ViewModel using the provided factory function\n * - Calls ready() if the ViewModel implements IKosViewModelReady\n * - Automatically calls dispose() on unmount (if the method exists)\n * - Re-creates the ViewModel when dependencies change\n * - Disposes the previous ViewModel when recreating\n *\n * @param factory - Function that creates the ViewModel instance\n * @param deps - Dependency array (similar to useEffect/useMemo)\n * @param options - Optional configuration\n * @returns UseViewModelResult with viewModel, ready state, and error\n *\n * @example\n * ```tsx\n * const OrderSummary = kosComponent(({ order }: Props) => {\n * const { viewModel: vm, ready, error } = useViewModel(\n * () => new OrderSummaryViewModel(order),\n * [order]\n * );\n * if (error) return <ErrorDisplay error={error} />;\n * if (!ready) return <Loading />;\n * return <div>Total: {vm.total}</div>;\n * });\n * ```\n *\n * @category KOS React Hook\n */\nexport function useViewModel<T>(\n factory: () => T,\n deps: React.DependencyList,\n options: UseViewModelOptions = {}\n): UseViewModelResult<T> {\n const { disposeOnUnmount = true } = options;\n\n // Track ready state and errors\n const [ready, setReady] = useState(false);\n const [error, setError] = useState<Error | undefined>(undefined);\n\n // Track the current ViewModel for disposal\n const viewModelRef = useRef<T | null>(null);\n const isFirstRender = useRef(true);\n // Track ready call to prevent duplicate calls\n const readyCalledRef = useRef(false);\n\n // Create ViewModel (memoized based on deps)\n const viewModel = useMemo(() => {\n // Dispose previous instance if deps changed (not on first render)\n if (\n !isFirstRender.current &&\n viewModelRef.current &&\n disposeOnUnmount &&\n isDisposable(viewModelRef.current)\n ) {\n const previous = viewModelRef.current;\n // Run dispose asynchronously to avoid React warnings during render\n Promise.resolve().then(() => {\n if (isDisposable(previous)) {\n previous.dispose();\n }\n });\n }\n\n isFirstRender.current = false;\n // Reset ready state for new instance\n readyCalledRef.current = false;\n\n // Create new instance\n const instance = factory();\n viewModelRef.current = instance;\n return instance;\n }, deps);\n\n // Handle ready() hook\n useEffect(() => {\n // Skip if already called for this instance\n if (readyCalledRef.current) return;\n\n // If ViewModel has ready hook, call it\n if (hasReadyHook(viewModel)) {\n readyCalledRef.current = true;\n setReady(false);\n setError(undefined);\n\n viewModel\n .ready()\n .then(() => {\n setReady(true);\n })\n .catch((err: Error) => {\n setError(err);\n setReady(false);\n });\n } else {\n // No ready hook - immediately ready\n setReady(true);\n setError(undefined);\n }\n }, [viewModel]);\n\n // Handle cleanup on unmount\n useEffect(\n () => () => {\n if (\n disposeOnUnmount &&\n viewModelRef.current &&\n isDisposable(viewModelRef.current)\n ) {\n viewModelRef.current.dispose();\n }\n viewModelRef.current = null;\n },\n [disposeOnUnmount]\n );\n\n return { viewModel, ready, error };\n}\n","import LoadingMessage from \"../components/loading-message\";\nimport { useProjectReload } from \"./use-project-reloading\";\n\ninterface ProjectReloadingProps {\n reloading: boolean;\n}\n// react HOC to provide a NodeTargetContainer to a component\nexport function withProjectReloading<\n T extends ProjectReloadingProps = ProjectReloadingProps\n>(WrappedComponent: React.ComponentType<T>) {\n return (props: Omit<T, keyof ProjectReloadingProps>) => {\n const [reloading] = useProjectReload();\n\n return reloading ? (\n <LoadingMessage message=\"Wait a moment while your project reloads...\" />\n ) : (\n <WrappedComponent {...(props as T)} />\n );\n };\n}\n","import { registerApiLevels } from \"@kosdev-code/kos-api-levels\";\n\n// Registers the package-level API integer for this SDK.\n// The level history (which tag boundaries changed the public surface and why) lives in\n// kos-api-levels/generated/api-archaeology-report.md, produced by the archaeology scanner.\nregisterApiLevels({ \"kos-ui-sdk\": 24 });\n\nexport * from \"./common\";\nexport * from \"./core\";\nexport * from \"./models\";\nexport * from \"./models/models/canvas-renderer\";\nexport * from \"./models/models/gpio-chip\";\nexport * from \"./models/models/gpio-pin\";\nexport * from \"./models/models/kos-expression-evaluator\";\nexport * from \"./models/models/kos-log-manager\";\nexport * from \"./models/models/log-block\";\nexport * from \"./models/models/studio-properties\";\nexport * from \"./ui\";\n"],"names":["debounce","buffer","request","dm","KosFetchMethods","index","getDaysInMonth","EventBus.subscribe","log","EventBus.publish","token","formatter","KosConfigPropertySpec","kosAutoEffect","REGION_PATH","REGION_ATTRIBUTE","REGION_ID","kosServiceRequest","baseKosServiceRequest","endpoint","serviceRequest","ep","api","REGION_SETTINGS_PATH","TIMEZONE_ATTRIBUTE","REGION_TIMEZONE_ID","configResponse","MODEL_TYPE","__publicField","__decorateClass","KOS_SERVICE.kosServiceRequest","KOS_SERVICE.api","API","message","kosModel","filter","ErrorBoundaryWithFallback","useSuspenseData","fetchModel","modelId","KosModelLoader","translations","locale","format","kosComponent","action","DateDisplayFormat","nextMonth","nextYear","RegionInfo","setDate","DEFAULT_FORMAT_MAP","cb","observer","setTime","date"],"mappings":";;;;;;;;;;;;;;AAAA,MAAM,8BAAc,IAAA;AAYb,SAAS,eACd,SACA,WACA,mBACA,aACA,eACM;AACN,MACE,OAAO,YAAY,eACnB,QAAQ,IAAI,UAAU,MAAM,cAC5B;AACA;AAAA,EACF;AACA,MAAI,QAAQ,IAAI,OAAO,EAAG;AAC1B,UAAQ,IAAI,OAAO;AACnB,UAAQ;AAAA,IACN,UAAU,OAAO,yBAAyB,SAAS,UAAU,iBAAiB,UACpE,WAAW,uCAAuC,aAAa;AAAA,EAAA;AAE7E;AC7BA,MAAM,YAAyB,CAAA;AAQxB,SAAS,kBAAkB,QAA2B;AAC3D,SAAO,OAAO,WAAW,MAAM;AACjC;ACKO,SAAS,KACd,WACA,UACY;AACZ,QAAM,eAAe,UAAU,WAAW,CAAC,QAAY;AAErD,iBAAa,YAAA;AACb,aAAS,GAAG;AAAA,EACd,CAAC;AAED,SAAO,aAAa;AACtB;AAYO,SAAS,QACd,WACA,SACY;AACZ,SAAO,IAAI,QAAQ,CAAC,SAAS,WAAW;AACtC,QAAI,YAAmC;AAEvC,UAAM,cAAc,KAAK,WAAW,CAAC,QAAY;AAC/C,UAAI,WAAW;AACb,qBAAa,SAAS;AAAA,MACxB;AACA,cAAQ,GAAI;AAAA,IACd,CAAC;AAED,QAAI,SAAS;AACX,kBAAY,WAAW,MAAM;AAC3B,oBAAA;AACA,eAAO,IAAI,MAAM,8BAA8B,SAAS,EAAE,CAAC;AAAA,MAC7D,GAAG,OAAO;AAAA,IACZ;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