@camstack/server 1.2.943 → 1.2.945

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (170) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/closure-pins.json +350 -0
  3. package/dist/api/core/auth-sessions.procedures.js +18 -0
  4. package/dist/api/core/auth.router.js +19 -6
  5. package/dist/api/server-upload.js +17 -1
  6. package/dist/api/trpc/generated-cap-mounts.js +18 -1
  7. package/dist/api/trpc/generated-cap-routers.js +2662 -2542
  8. package/dist/auth/native-return.js +9 -3
  9. package/dist/auth/sso-routes.js +5 -1
  10. package/dist/core/addon/instance-lifecycle.js +4 -1
  11. package/dist/core/auth/handoff-code.service.js +35 -1
  12. package/dist/server-root/index.js +313 -70
  13. package/package.json +15 -11
  14. package/system/assets/apps-aggregator/icon.svg +5 -0
  15. package/system/dist/{action-index-B_cLRwXJ.js → action-index-Bcnb-jyg.js} +9 -1
  16. package/system/dist/{action-index-B1fgpQBt.mjs → action-index-DwPHO2nz.mjs} +9 -1
  17. package/system/dist/{addon-settings.cap-CZ4MC7ha.mjs → addon-settings.cap-CHpmuaQG.mjs} +1 -1
  18. package/system/dist/{addon-settings.cap-DrLdMFIe.js → addon-settings.cap-nZVHPo3X.js} +1 -1
  19. package/system/dist/{alert-episode-Be--PngO.mjs → alert-episode-D-1VUUkZ.mjs} +1 -1
  20. package/system/dist/{alert-episode-Bqktmt-i.js → alert-episode-DaQ3prSe.js} +1 -1
  21. package/system/dist/apps.cap-Bqb9NpYx.mjs +130 -0
  22. package/system/dist/apps.cap-CLjgnuUe.js +141 -0
  23. package/system/dist/{base-addon-CRsXtYFG.js → base-addon-BG7p06Hb.js} +136 -15
  24. package/system/dist/{base-addon-BcS6r1cT.mjs → base-addon-BcVoYZbC.mjs} +136 -15
  25. package/system/dist/{base-device-DAdWzDOl.js → base-device-DeSNiwZ4.js} +4 -4
  26. package/system/dist/{base-device-DJXF5eDN.mjs → base-device-w_MD0Bf4.mjs} +4 -4
  27. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.js +1 -1
  28. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.mjs +1 -1
  29. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js +1 -1
  30. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs +1 -1
  31. package/system/dist/builtins/alerts/alerts.addon.js +3 -3
  32. package/system/dist/builtins/alerts/alerts.addon.mjs +3 -3
  33. package/system/dist/builtins/apps-aggregator/aggregate-apps.d.ts +24 -0
  34. package/system/dist/builtins/apps-aggregator/apps-aggregator.addon.d.ts +16 -0
  35. package/system/dist/builtins/apps-aggregator/apps-aggregator.addon.js +109 -0
  36. package/system/dist/builtins/apps-aggregator/apps-aggregator.addon.mjs +103 -0
  37. package/system/dist/builtins/apps-aggregator/index.d.ts +1 -0
  38. package/system/dist/builtins/apps-aggregator/index.js +8 -0
  39. package/system/dist/builtins/apps-aggregator/index.mjs +2 -0
  40. package/system/dist/builtins/autotrack/index.js +1 -1
  41. package/system/dist/builtins/autotrack/index.mjs +1 -1
  42. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.js +1 -1
  43. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.mjs +1 -1
  44. package/system/dist/builtins/calendars/calendars.addon.js +1 -1
  45. package/system/dist/builtins/calendars/calendars.addon.mjs +1 -1
  46. package/system/dist/builtins/camera-grid/index.js +3 -3
  47. package/system/dist/builtins/camera-grid/index.mjs +3 -3
  48. package/system/dist/builtins/composer/composer.addon.js +7 -7
  49. package/system/dist/builtins/composer/composer.addon.mjs +7 -7
  50. package/system/dist/builtins/console-logging/index.js +1 -1
  51. package/system/dist/builtins/console-logging/index.mjs +1 -1
  52. package/system/dist/builtins/core-blocks/actions-store.d.ts +2 -0
  53. package/system/dist/builtins/core-blocks/block-supervisor.d.ts +16 -4
  54. package/system/dist/builtins/core-blocks/core-block-store.d.ts +2 -0
  55. package/system/dist/builtins/core-blocks/core-blocks.addon.js +1018 -323
  56. package/system/dist/builtins/core-blocks/core-blocks.addon.mjs +986 -291
  57. package/system/dist/builtins/core-blocks/migrations/index.d.ts +5 -2
  58. package/system/dist/builtins/core-blocks/migrations/tag-ids.d.ts +42 -0
  59. package/system/dist/builtins/core-blocks/migrations/tags-as-records.d.ts +47 -0
  60. package/system/dist/builtins/core-blocks/record-kinds.d.ts +12 -1
  61. package/system/dist/builtins/core-blocks/runs-api.d.ts +3 -1
  62. package/system/dist/builtins/core-blocks/runs-ledger.d.ts +3 -1
  63. package/system/dist/builtins/core-blocks/scheduler/scheduler-store.d.ts +2 -0
  64. package/system/dist/builtins/core-blocks/tags-service.d.ts +52 -27
  65. package/system/dist/builtins/core-blocks/tags-wiring.d.ts +2 -0
  66. package/system/dist/builtins/core-notifier/core-notifier.addon.js +76 -67
  67. package/system/dist/builtins/core-notifier/core-notifier.addon.mjs +76 -67
  68. package/system/dist/builtins/device-history/device-history.addon.js +4 -4
  69. package/system/dist/builtins/device-history/device-history.addon.mjs +4 -4
  70. package/system/dist/builtins/device-manager/device-manager.addon.js +1618 -755
  71. package/system/dist/builtins/device-manager/device-manager.addon.mjs +1604 -741
  72. package/system/dist/builtins/device-manager/device-meta-actions.d.ts +13 -136
  73. package/system/dist/builtins/device-manager/device-meta-types.d.ts +5 -1
  74. package/system/dist/builtins/device-manager/device-provider-context.d.ts +9 -0
  75. package/system/dist/builtins/device-manager/device-row-store.d.ts +21 -4
  76. package/system/dist/builtins/device-manager/device-search.d.ts +6 -0
  77. package/system/dist/builtins/device-manager/location-alignment.d.ts +9 -2
  78. package/system/dist/builtins/device-manager/migrate-device.d.ts +7 -2
  79. package/system/dist/builtins/device-manager/migrate-hardware-state.d.ts +132 -1
  80. package/system/dist/builtins/device-manager/migrations/device-tag-ids.d.ts +25 -0
  81. package/system/dist/builtins/device-manager/migrations/index.d.ts +16 -0
  82. package/system/dist/builtins/device-manager/migrations/orphan-children.d.ts +33 -0
  83. package/system/dist/builtins/device-manager/migrations/ports.d.ts +17 -0
  84. package/system/dist/builtins/device-manager/migrations/rooms-as-records.d.ts +52 -0
  85. package/system/dist/builtins/device-manager/record-kinds.d.ts +3 -1
  86. package/system/dist/builtins/device-manager/removal-cleanup.d.ts +7 -0
  87. package/system/dist/builtins/device-manager/room-actions.d.ts +27 -0
  88. package/system/dist/builtins/device-manager/room-store.d.ts +19 -0
  89. package/system/dist/builtins/device-manager/tag-names.d.ts +32 -0
  90. package/system/dist/builtins/device-manager/wireable-enum-catalog.d.ts +18 -0
  91. package/system/dist/builtins/hub-forwarder/index.js +1 -1
  92. package/system/dist/builtins/hub-forwarder/index.mjs +1 -1
  93. package/system/dist/builtins/keychain/index.js +3 -3
  94. package/system/dist/builtins/keychain/index.mjs +3 -3
  95. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.js +1 -1
  96. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.mjs +1 -1
  97. package/system/dist/builtins/local-auth/local-auth.addon.js +1 -1
  98. package/system/dist/builtins/local-auth/local-auth.addon.mjs +1 -1
  99. package/system/dist/builtins/local-network/local-network.addon.js +2 -2
  100. package/system/dist/builtins/local-network/local-network.addon.mjs +2 -2
  101. package/system/dist/builtins/loki-logging/index.js +2 -2
  102. package/system/dist/builtins/loki-logging/index.mjs +2 -2
  103. package/system/dist/builtins/native-metrics/native-metrics.addon.js +1 -1
  104. package/system/dist/builtins/native-metrics/native-metrics.addon.mjs +1 -1
  105. package/system/dist/builtins/platform-probe/index.js +1 -1
  106. package/system/dist/builtins/platform-probe/index.mjs +1 -1
  107. package/system/dist/builtins/record-entries/index.js +1 -1
  108. package/system/dist/builtins/record-entries/index.mjs +1 -1
  109. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.js +1 -1
  110. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.mjs +1 -1
  111. package/system/dist/builtins/snapshot/index.js +1 -1
  112. package/system/dist/builtins/snapshot/index.mjs +1 -1
  113. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.js +1 -1
  114. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.mjs +1 -1
  115. package/system/dist/builtins/sqlite-storage/index.js +1 -1
  116. package/system/dist/builtins/sqlite-storage/index.mjs +1 -1
  117. package/system/dist/builtins/sqlite-storage/migrations/migration-engine.d.ts +3 -1
  118. package/system/dist/builtins/sqlite-storage/migrations/migrations-provider.d.ts +1 -0
  119. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.js +15 -10
  120. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs +15 -10
  121. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.js +1 -1
  122. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.mjs +1 -1
  123. package/system/dist/builtins/system-config/system-config.addon.js +2 -2
  124. package/system/dist/builtins/system-config/system-config.addon.mjs +2 -2
  125. package/system/dist/builtins/winston-logging/index.js +2 -2
  126. package/system/dist/builtins/winston-logging/index.mjs +2 -2
  127. package/system/dist/{command-catalog-C29hVOOg.js → command-catalog-A_ONlLfF.js} +1 -1
  128. package/system/dist/{command-catalog-xAeqxbZk.mjs → command-catalog-CZDlLhxO.mjs} +1 -1
  129. package/system/dist/{composition-sources-Do5qM6EB.js → composition-sources-D1nPv7dJ.js} +1 -1
  130. package/system/dist/{composition-sources-C327LGFn.mjs → composition-sources-DubMf_ii.mjs} +1 -1
  131. package/system/dist/{core-blocks.cap-CdTGUKtr.js → core-blocks.cap-DEYCvF9J.js} +125 -373
  132. package/system/dist/{core-blocks.cap-DLkEfV5b.mjs → core-blocks.cap-sW5HLDlB.mjs} +109 -327
  133. package/system/dist/{device-manager.cap-DJs8izI6.js → device-manager.cap-B9qVf7ag.js} +163 -22
  134. package/system/dist/{device-manager.cap-eYrj1Ezp.mjs → device-manager.cap-CV4KGp3e.mjs} +134 -17
  135. package/system/dist/{error.cap-CU1FB6uE.mjs → error.cap-B8l7L8e4.mjs} +7 -1
  136. package/system/dist/{error.cap-BuKbL3Ac.js → error.cap-BqlvgBJd.js} +7 -1
  137. package/system/dist/file-host-worker.js +1 -1
  138. package/system/dist/file-host-worker.mjs +1 -1
  139. package/system/dist/index.js +8 -8
  140. package/system/dist/index.mjs +7 -7
  141. package/system/dist/{legacy-integration-rows-door-CdqYAj-o.js → legacy-integration-rows-door-BK8eoGlF.js} +1 -1
  142. package/system/dist/{legacy-integration-rows-door-LSgpClpX.mjs → legacy-integration-rows-door-CwzC5XNk.mjs} +1 -1
  143. package/system/dist/{migration-DGAc6ywR.mjs → migration-BvbfW9g-.mjs} +6 -0
  144. package/system/dist/{migration-BOQlFZCN.js → migration-CHPdAdNh.js} +6 -0
  145. package/system/dist/{prefix-walk-Mtij0NNT.mjs → named-entity-store-Cq2oVrN5.mjs} +195 -89
  146. package/system/dist/{prefix-walk-BFnw8NBu.js → named-entity-store-O_hi1y_o.js} +244 -90
  147. package/system/dist/{notification-rules.cap-BUIuYPlQ.mjs → notification-rules.cap-ClvK6QT1.mjs} +10 -5
  148. package/system/dist/{notification-rules.cap-BJKUjizS.js → notification-rules.cap-uSLoe2pA.js} +10 -5
  149. package/system/dist/{notification-targets-DMW7xgR2.js → notification-targets-ChqpBbtR.js} +2 -2
  150. package/system/dist/{notification-targets-4bGYH5J7.mjs → notification-targets-DUA6-F2t.mjs} +2 -2
  151. package/system/dist/{device-row-store-CTocYKqC.mjs → record-kinds-BD2xv4Pd.mjs} +222 -93
  152. package/system/dist/{device-row-store-C0P2H18h.js → record-kinds-BV8Gcpsx.js} +246 -93
  153. package/system/dist/records/named-entity-store.d.ts +60 -0
  154. package/system/dist/{rename-composition-block-D9Uc1AF7.js → rename-composition-block-C60O0P16.js} +137 -33
  155. package/system/dist/{rename-composition-block-Cdh-dRmY.mjs → rename-composition-block-DcX3vkwS.mjs} +137 -33
  156. package/system/dist/{retention-source.cap-C6Hy0hlM.js → retention-source.cap-A-TMhU5O.js} +1 -1
  157. package/system/dist/{retention-source.cap-550kkyp5.mjs → retention-source.cap-Ct07pM30.mjs} +1 -1
  158. package/system/dist/{storage-admin.cap-Ci4QbL6P.mjs → storage-admin.cap-C54s9_B9.mjs} +8 -2
  159. package/system/dist/{storage-admin.cap-DqW1ol4j.js → storage-admin.cap-DSPHi7ut.js} +8 -2
  160. package/system/dist/{stream-catalog.cap-CjEQFknc.js → stream-catalog.cap-7WPsugOy.js} +1 -1
  161. package/system/dist/{stream-catalog.cap-DVniDdRD.mjs → stream-catalog.cap-CzwRDaqT.mjs} +1 -1
  162. package/system/dist/{tag-BxLazvVb.js → tag-BLraBqvp.js} +12 -0
  163. package/system/dist/{tag-uZBAq6ox.mjs → tag-DU8pm9Bi.mjs} +7 -1
  164. package/system/dist/time-window-B6UhCArd.js +679 -0
  165. package/system/dist/time-window-BnUBULgu.mjs +578 -0
  166. package/system/dist/{wal-maintenance-BgYiAy5b.js → wal-maintenance-CkPfVApC.js} +0 -0
  167. package/system/dist/{wal-maintenance-Bey5ChBb.mjs → wal-maintenance-u84_1sVl.mjs} +0 -0
  168. package/system/package.json +16 -1
  169. /package/system/dist/{constants-Ba3FTIHl.js → constants-Ba3FTIHl2.js} +0 -0
  170. /package/system/dist/{constants-DB4piTD5.mjs → constants-DB4piTD52.mjs} +0 -0
@@ -1,27 +1,28 @@
1
- import { E as deviceStatusCapability, T as DeviceStatusSchema } from "../../stream-catalog.cap-DVniDdRD.mjs";
2
- import { b as EventCategory$1, g as WELL_KNOWN_TAB_MAP, n as secretTreeFromPaths, o as resolveSecretMarkers, s as transformSecretWrite, t as BaseAddon } from "../../base-addon-BcS6r1cT.mjs";
3
- import { B as SECRET_CLEAR, G as isSecretMarkerLike, H as isSecretClear, W as isSecretMarker, X as isKeychainStoredField, Z as errMsg$1, q as toSecretFieldView } from "../../scoped-settings-DVWUIP7Z.mjs";
4
- import { Jn as ExportNameRefusedError, _n as deviceStateCapability, b as workloadTransition, c as kebabToCamel, fn as PUSH_CONFIRM_WINDOW_MS, g as WorkloadStateSchema, gn as FieldClaimSchema, h as WORKLOAD_TRANSITION_CATEGORY, hn as FieldClaimModeSchema, m as ALL_CAPABILITY_DEFINITIONS, mn as effectiveRefreshIntervalMs, n as renameCompositionBlock, pn as commandBurstOffsets, t as composedBlockIdOf, v as isWorkloadSettled, vn as deviceExtensionCapability, y as workloadCapability, yn as EXTENSION_SLOTS } from "../../rename-composition-block-Cdh-dRmY.mjs";
1
+ import { E as deviceStatusCapability, T as DeviceStatusSchema } from "../../stream-catalog.cap-CzwRDaqT.mjs";
2
+ import { b as EventCategory$1, f as defineAddonMigrations, g as WELL_KNOWN_TAB_MAP, n as secretTreeFromPaths, o as resolveSecretMarkers, s as transformSecretWrite, t as BaseAddon } from "../../base-addon-BcVoYZbC.mjs";
3
+ import { B as SECRET_CLEAR, G as isSecretMarkerLike, H as isSecretClear, K as makeSecretMarker, W as isSecretMarker, X as isKeychainStoredField, Z as errMsg$1, b as buildSecretRef, q as toSecretFieldView, w as parseSecretRef } from "../../scoped-settings-DVWUIP7Z.mjs";
4
+ import { Jn as ExportNameRefusedError, _n as deviceStateCapability, b as workloadTransition, c as kebabToCamel, fn as PUSH_CONFIRM_WINDOW_MS, g as WorkloadStateSchema, gn as FieldClaimSchema, h as WORKLOAD_TRANSITION_CATEGORY, hn as FieldClaimModeSchema, m as ALL_CAPABILITY_DEFINITIONS, mn as effectiveRefreshIntervalMs, n as renameCompositionBlock, pn as commandBurstOffsets, t as composedBlockIdOf, v as isWorkloadSettled, vn as deviceExtensionCapability, y as workloadCapability, yn as EXTENSION_SLOTS } from "../../rename-composition-block-DcX3vkwS.mjs";
5
5
  import { t as userError } from "../../camstack-error-viZYfcj9.mjs";
6
6
  import { a as expandCapMethods$1, s as isDeviceConfigCap } from "../../capability-definition-C1TLUVJR.mjs";
7
7
  import { t as collectZodSecretPaths$1 } from "../../zod-secret-zY4nM61M.mjs";
8
- import { _ as resolveTemplateRef, a as deviceManagerCapability, d as siteZoneKey, f as DEVICE_TEMPLATE_FILTERS, g as DEVICE_TEMPLATE_VALUES_CAP, l as identityLinkId, m as DEVICE_TEMPLATE_MAX_OUTPUT, p as DEVICE_TEMPLATE_MAX_LENGTH, u as identityLinkSidesRefusal, v as checkDeviceAlias, y as generateDeviceAlias } from "../../device-manager.cap-eYrj1Ezp.mjs";
8
+ import { C as generateDeviceAlias, S as checkDeviceAlias, _ as DEVICE_TEMPLATE_MAX_LENGTH, a as deviceManagerCapability, b as DEVICE_TEMPLATE_VALUES_CAP, d as ZoneBodySchema, g as DEVICE_TEMPLATE_FILTERS, h as identityLinkSidesRefusal, m as identityLinkId, s as RoomBodySchema, v as DEVICE_TEMPLATE_MAX_OUTPUT, x as resolveTemplateRef } from "../../device-manager.cap-CV4KGp3e.mjs";
9
9
  import { a as isEmptyIdentifiers, c as sameIdentifiers, i as identifierStrength, l as CAMERA_SWITCH_ORDER, o as mergeIdentifiers, r as DeviceIdentifiersSchema, t as DEVICE_IDENTIFIER_KEYS } from "../../device-identifiers-iSuQCKmK.mjs";
10
- import { d as canonicalIconKey, o as normalizeTags } from "../../tag-uZBAq6ox.mjs";
10
+ import { a as deviceRowBackendOf, c as recordUpsertEdit, i as DeviceRowStore, n as DEVICE_ROWS_COLLECTION, o as MigrationRefusedError, r as DEVICE_ROWS_FLEET_LIMIT, t as deviceManagerRecordKinds } from "../../record-kinds-BD2xv4Pd.mjs";
11
+ import { u as preconditionOf } from "../../migration-BvbfW9g-.mjs";
12
+ import { f as canonicalIconKey, s as normalizeTags, u as tagKey } from "../../tag-DU8pm9Bi.mjs";
11
13
  import { n as DeviceRole, r as DeviceType$1, t as DeviceFeature } from "../../device-type-TUGqGmaI.mjs";
12
14
  import { n as capAppliesToDeviceKind } from "../../device-kind-C37Ra2wd.mjs";
13
- import { c as CAP_VOCABULARY_BY_NAME, o as vocabActionIdFor } from "../../action-index-B1fgpQBt.mjs";
14
- import { u as locationIconKey } from "../../addon-settings.cap-CZ4MC7ha.mjs";
15
- import { $ as CAP_RUNTIME_FIELD_UNITS, Xt as enumerateSchemaFields, Yt as enumerateItemArrayFields } from "../../core-blocks.cap-DLkEfV5b.mjs";
15
+ import { $ as CAP_RUNTIME_FIELD_UNITS, Xt as enumerateItemArrayFields, Zt as enumerateSchemaFields } from "../../core-blocks.cap-sW5HLDlB.mjs";
16
+ import { c as CAP_VOCABULARY_BY_NAME, o as vocabActionIdFor } from "../../action-index-DwPHO2nz.mjs";
17
+ import { u as locationIconKey } from "../../addon-settings.cap-CHpmuaQG.mjs";
16
18
  import "../../compile-OBMHlqD-.mjs";
17
19
  import { a as normalizeUnit, r as extractSourceInfoFromMetadata } from "../../source-info-DGB7SdB_.mjs";
18
- import { r as ConditionMirror, t as loadPrefixed } from "../../prefix-walk-Mtij0NNT.mjs";
19
- import { a as effectConditionHolds, i as commandHoldMs, n as commandEffect, o as isCommand$1, r as commandEffects, s as resolveSideEffect } from "../../command-catalog-xAeqxbZk.mjs";
20
+ import { a as loadPrefixed, c as roomIdFromKey, d as ConditionMirror, i as createWriteLock, l as tagIdFromKey, n as EntityNotFoundError, r as NamedEntityStore, s as entityNameKey, t as EntityNameTakenError, u as zoneIdFromKey } from "../../named-entity-store-Cq2oVrN5.mjs";
21
+ import { a as effectConditionHolds, i as commandHoldMs, n as commandEffect, o as isCommand$1, r as commandEffects, s as resolveSideEffect } from "../../command-catalog-CZDlLhxO.mjs";
20
22
  import { t as require_read_all_rows } from "../../read-all-rows-TaPqdWNF.mjs";
21
23
  import { a as redactLogText, i as redactLogMeta, n as isSecretArgumentKey } from "../../log-redactor-XLDrPzOi.mjs";
22
24
  import { t as prefixRange } from "../../prefix-range-Dl0znowN.mjs";
23
25
  import { n as purgeRetiredSettingsRows } from "../../retired-settings-keys-u6xQA6r7.mjs";
24
- import { a as MigrationRefusedError, i as deviceManagerRecordKinds, n as DeviceRowStore, r as deviceRowBackendOf } from "../../device-row-store-CTocYKqC.mjs";
25
26
  import { n as isRenderResponse, r as analyzeTemplate } from "../../template-protocol-SgPDx3Hw.mjs";
26
27
  import { s as normalizeServiceType } from "../../dns-wire-Dm3H_7ST.mjs";
27
28
  import { createRequire } from "node:module";
@@ -1247,6 +1248,27 @@ var METHOD_ACCESS_MAP = /* @__PURE__ */ Object.freeze({
1247
1248
  access: "view",
1248
1249
  role: "viewer"
1249
1250
  },
1251
+ "apps.getNavBadges": {
1252
+ capName: "apps",
1253
+ capScope: "system",
1254
+ addonId: null,
1255
+ access: "view",
1256
+ role: "viewer"
1257
+ },
1258
+ "apps.listApps": {
1259
+ capName: "apps",
1260
+ capScope: "system",
1261
+ addonId: null,
1262
+ access: "view",
1263
+ role: "viewer"
1264
+ },
1265
+ "appSource.listApps": {
1266
+ capName: "app-source",
1267
+ capScope: "system",
1268
+ addonId: null,
1269
+ access: "view",
1270
+ role: "admin"
1271
+ },
1250
1272
  "audioAnalysis.applyDeviceSettingsPatch": {
1251
1273
  capName: "audio-analysis",
1252
1274
  capScope: "device",
@@ -2941,6 +2963,13 @@ var METHOD_ACCESS_MAP = /* @__PURE__ */ Object.freeze({
2941
2963
  access: "create",
2942
2964
  role: "admin"
2943
2965
  },
2966
+ "deviceManager.deleteRoom": {
2967
+ capName: "device-manager",
2968
+ capScope: "system",
2969
+ addonId: null,
2970
+ access: "delete",
2971
+ role: "admin"
2972
+ },
2944
2973
  "deviceManager.disable": {
2945
2974
  capName: "device-manager",
2946
2975
  capScope: "system",
@@ -2997,6 +3026,13 @@ var METHOD_ACCESS_MAP = /* @__PURE__ */ Object.freeze({
2997
3026
  access: "create",
2998
3027
  role: "admin"
2999
3028
  },
3029
+ "deviceManager.ensureRoom": {
3030
+ capName: "device-manager",
3031
+ capScope: "system",
3032
+ addonId: null,
3033
+ access: "create",
3034
+ role: "admin"
3035
+ },
3000
3036
  "deviceManager.getAllBindings": {
3001
3037
  capName: "device-manager",
3002
3038
  capScope: "system",
@@ -3221,6 +3257,13 @@ var METHOD_ACCESS_MAP = /* @__PURE__ */ Object.freeze({
3221
3257
  access: "view",
3222
3258
  role: "admin"
3223
3259
  },
3260
+ "deviceManager.listRooms": {
3261
+ capName: "device-manager",
3262
+ capScope: "system",
3263
+ addonId: null,
3264
+ access: "view",
3265
+ role: "viewer"
3266
+ },
3224
3267
  "deviceManager.listSiteZones": {
3225
3268
  capName: "device-manager",
3226
3269
  capScope: "system",
@@ -3361,6 +3404,13 @@ var METHOD_ACCESS_MAP = /* @__PURE__ */ Object.freeze({
3361
3404
  access: "view",
3362
3405
  role: "admin"
3363
3406
  },
3407
+ "deviceManager.repairMigrationSecrets": {
3408
+ capName: "device-manager",
3409
+ capScope: "system",
3410
+ addonId: null,
3411
+ access: "create",
3412
+ role: "admin"
3413
+ },
3364
3414
  "deviceManager.reportDiscoveryObservations": {
3365
3415
  capName: "device-manager",
3366
3416
  capScope: "system",
@@ -3592,6 +3642,13 @@ var METHOD_ACCESS_MAP = /* @__PURE__ */ Object.freeze({
3592
3642
  access: "create",
3593
3643
  role: "admin"
3594
3644
  },
3645
+ "deviceManager.updateRoom": {
3646
+ capName: "device-manager",
3647
+ capScope: "system",
3648
+ addonId: null,
3649
+ access: "create",
3650
+ role: "admin"
3651
+ },
3595
3652
  "deviceOps.getConfigEntries": {
3596
3653
  capName: "device-ops",
3597
3654
  capScope: "device",
@@ -10438,6 +10495,20 @@ var METHOD_ACCESS_MAP = /* @__PURE__ */ Object.freeze({
10438
10495
  access: "create",
10439
10496
  role: "admin"
10440
10497
  },
10498
+ "tags.deleteTag": {
10499
+ capName: "tags",
10500
+ capScope: "system",
10501
+ addonId: null,
10502
+ access: "delete",
10503
+ role: "admin"
10504
+ },
10505
+ "tags.ensureTag": {
10506
+ capName: "tags",
10507
+ capScope: "system",
10508
+ addonId: null,
10509
+ access: "create",
10510
+ role: "admin"
10511
+ },
10441
10512
  "tags.list": {
10442
10513
  capName: "tags",
10443
10514
  capScope: "system",
@@ -10445,6 +10516,13 @@ var METHOD_ACCESS_MAP = /* @__PURE__ */ Object.freeze({
10445
10516
  access: "view",
10446
10517
  role: "admin"
10447
10518
  },
10519
+ "tags.listTags": {
10520
+ capName: "tags",
10521
+ capScope: "system",
10522
+ addonId: null,
10523
+ access: "view",
10524
+ role: "admin"
10525
+ },
10448
10526
  "tags.remove": {
10449
10527
  capName: "tags",
10450
10528
  capScope: "system",
@@ -10466,6 +10544,13 @@ var METHOD_ACCESS_MAP = /* @__PURE__ */ Object.freeze({
10466
10544
  access: "create",
10467
10545
  role: "admin"
10468
10546
  },
10547
+ "tags.updateTag": {
10548
+ capName: "tags",
10549
+ capScope: "system",
10550
+ addonId: null,
10551
+ access: "create",
10552
+ role: "admin"
10553
+ },
10469
10554
  "tamper.getStatus": {
10470
10555
  capName: "tamper",
10471
10556
  capScope: "device",
@@ -12513,97 +12598,622 @@ function resolveCommandHold(cap, method, args, current, option, shown = current)
12513
12598
  };
12514
12599
  }
12515
12600
  //#endregion
12516
- //#region src/builtins/device-manager/adoption-job-engine.ts
12517
- /** How many finished jobs are kept per (addonId, integrationId). */
12518
- var JOB_HISTORY = 20;
12519
- function snapshot(j) {
12520
- let adopted = 0;
12521
- let alreadyAdopted = 0;
12522
- let failed = 0;
12523
- let processed = 0;
12524
- let accessoriesCreated = 0;
12525
- for (const r of j.results) {
12526
- if (r.outcome === "cancelled") continue;
12527
- processed += 1;
12528
- accessoriesCreated += r.accessoryCount;
12529
- if (r.outcome === "adopted") adopted += 1;
12530
- else if (r.outcome === "already-adopted") alreadyAdopted += 1;
12531
- else if (r.outcome === "failed") failed += 1;
12601
+ //#region src/builtins/device-manager/migrations/device-tag-ids.ts
12602
+ /**
12603
+ * A device row gets the ids of its tags (D1089, the device-manager step of the tags
12604
+ * migration): `tagIds` is added beside the kept `tags` names, aligned by index, with each id
12605
+ * derived from the folded name (`tagIdFromKey`) so every owner of that name mints the same
12606
+ * one. The names stay for one release; the `tags` records are written later by the
12607
+ * core-blocks tags-as-records procedure, which `dependsOn` this step.
12608
+ *
12609
+ * ONE plan, one transaction. A row that already has `tagIds` is left alone (a rerun is
12610
+ * empty); a row whose names repeat one tag in two spellings is rewritten with both columns
12611
+ * de-duplicated, so the index alignment holds.
12612
+ */
12613
+ var DEVICE_TAG_IDS_ID = "device-manager/2026-11-23-device-tag-ids";
12614
+ async function planDeviceTagIds(ports) {
12615
+ const rows = await ports.readDeviceTags();
12616
+ const edits = [];
12617
+ for (const row of rows) {
12618
+ if (row.hasTagIds) continue;
12619
+ const names = normalizeTags(row.tags);
12620
+ if (names.length === 0) continue;
12621
+ const sameNames = names.length === row.tags.length;
12622
+ edits.push({
12623
+ op: "putRow",
12624
+ table: DEVICE_ROWS_COLLECTION,
12625
+ key: { deviceId: row.deviceId },
12626
+ row: {
12627
+ tagIds: names.map((name) => tagIdFromKey(tagKey(name))),
12628
+ ...sameNames ? {} : { tags: names }
12629
+ },
12630
+ preconditionColumns: ["tagIds"],
12631
+ precondition: preconditionOf({ tagIds: null })
12632
+ });
12633
+ }
12634
+ return { edits };
12635
+ }
12636
+ //#endregion
12637
+ //#region src/builtins/device-manager/migrations/orphan-children.ts
12638
+ /** The rows that name a parent no row answers to. */
12639
+ function orphansOf(rows) {
12640
+ const ids = new Set(rows.map((r) => r.id));
12641
+ return rows.filter((r) => r.parentDeviceId !== null && !ids.has(r.parentDeviceId));
12642
+ }
12643
+ /**
12644
+ * Destructive on one read is never enough (D49): a row is removed only when TWO
12645
+ * reads agree it is an orphan, and nothing is removed from a read that may have
12646
+ * been cut short at the row limit. The candidate ids are recorded in the summary
12647
+ * and the log BEFORE any removal.
12648
+ */
12649
+ async function removeOrphanChildren(ports) {
12650
+ const first = await ports.listRows();
12651
+ if (first.length >= ports.rowLimit) throw new Error(`device-manager: ${first.length} rows read, the limit is ${ports.rowLimit} — the read may be truncated, nothing removed`);
12652
+ const candidates = orphansOf(first);
12653
+ if (candidates.length === 0) return {
12654
+ outcome: "already-done",
12655
+ summary: {
12656
+ candidates: [],
12657
+ removed: []
12658
+ }
12659
+ };
12660
+ const second = await ports.listRows();
12661
+ const stillOrphans = new Set(orphansOf(second).map((r) => r.id));
12662
+ const confirmed = candidates.filter((r) => stillOrphans.has(r.id));
12663
+ const candidateIds = candidates.map((r) => r.id);
12664
+ ports.summary({
12665
+ rows: first.length,
12666
+ candidateCount: candidateIds.length,
12667
+ candidates: candidateIds,
12668
+ confirmedCount: confirmed.length,
12669
+ confirmed: confirmed.map((r) => r.id)
12670
+ });
12671
+ const removed = [];
12672
+ for (const orphan of confirmed) {
12673
+ if (orphan.parentDeviceId === null) continue;
12674
+ ports.info("device-manager: removing an orphan child, its parent no longer exists", orphan.id, orphan.parentDeviceId);
12675
+ await ports.removeDevice(orphan.id);
12676
+ removed.push(orphan.id);
12532
12677
  }
12533
12678
  return {
12534
- jobId: j.jobId,
12535
- addonId: j.addonId,
12536
- integrationId: j.integrationId,
12537
- state: j.state,
12538
- total: j.total,
12539
- processed,
12540
- adopted,
12541
- alreadyAdopted,
12542
- failed,
12543
- accessoriesCreated,
12544
- currentChildNativeId: j.currentChildNativeId,
12545
- results: j.results.map((r) => ({
12546
- childNativeId: r.childNativeId,
12547
- outcome: r.outcome,
12548
- parentDeviceId: r.parentDeviceId,
12549
- accessoryCount: r.accessoryCount,
12550
- error: r.error
12551
- })),
12552
- startedAt: j.startedAt,
12553
- finishedAt: j.finishedAt,
12554
- error: j.error
12679
+ outcome: "done",
12680
+ summary: {
12681
+ candidates: candidateIds,
12682
+ removed
12683
+ }
12555
12684
  };
12556
12685
  }
12557
- var AdoptionJobEngine = class {
12558
- deps;
12559
- jobs = /* @__PURE__ */ new Map();
12560
- seq = 0;
12561
- constructor(deps) {
12562
- this.deps = deps;
12563
- }
12564
- now() {
12565
- return this.deps.now?.() ?? Date.now();
12686
+ //#endregion
12687
+ //#region src/builtins/device-manager/device-meta-types.ts
12688
+ /**
12689
+ * Decode the raw `ctx.settings.readAddonStore()` record into {@link AddonStore}.
12690
+ *
12691
+ * A field of the wrong shape reads as ABSENT rather than being trusted through
12692
+ * a cast: the store is JSON on disk and a hand-edit or a partial restore must
12693
+ * cost the caller its default, never a downstream `TypeError`.
12694
+ */
12695
+ function decodeAddonStore(raw) {
12696
+ const nextDeviceId = raw["nextDeviceId"];
12697
+ const locations = raw["locations"];
12698
+ const roleDisplayDefaults = raw["roleDisplayDefaults"];
12699
+ const locationIcons = decodeLocationIcons(raw["locationIcons"]);
12700
+ const locationDescriptions = decodeLocationDescriptions(raw["locationDescriptions"]);
12701
+ const siteZones = decodeSiteZones(raw["siteZones"]);
12702
+ const locationZones = decodeStringMap(raw["locationZones"]);
12703
+ return {
12704
+ ...typeof nextDeviceId === "number" && Number.isFinite(nextDeviceId) ? { nextDeviceId } : {},
12705
+ ...Array.isArray(locations) ? { locations: locations.filter((l) => typeof l === "string") } : {},
12706
+ ...isRoleDisplayDefaults(roleDisplayDefaults) ? { roleDisplayDefaults } : {},
12707
+ ...locationIcons !== null ? { locationIcons } : {},
12708
+ ...locationDescriptions !== null ? { locationDescriptions } : {},
12709
+ ...siteZones !== null ? { siteZones } : {},
12710
+ ...locationZones !== null ? { locationZones } : {}
12711
+ };
12712
+ }
12713
+ /**
12714
+ * Decode the `locationIcons` map, dropping every entry whose value is not a
12715
+ * member of the closed vocabulary.
12716
+ *
12717
+ * Dropping, not passing through: the icon's whole point is that both surfaces
12718
+ * can draw it, and an id from a hand-edit or a newer hub is exactly the value
12719
+ * that draws nothing. Absent reads as "no icon chosen", which every renderer
12720
+ * already degrades to the fallback pin. Returns `null` when the key itself is
12721
+ * absent or of the wrong shape, so the field stays OMITTED rather than being
12722
+ * written back as an empty object.
12723
+ */
12724
+ function decodeLocationIcons(raw) {
12725
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return null;
12726
+ const out = {};
12727
+ for (const [key, value] of Object.entries(raw)) {
12728
+ const icon = canonicalIconKey(value);
12729
+ if (icon === void 0) continue;
12730
+ out[key] = icon;
12566
12731
  }
12567
- newId() {
12568
- if (this.deps.newId) return this.deps.newId();
12569
- this.seq += 1;
12570
- return `adopt-${Date.now().toString(36)}-${this.seq}`;
12732
+ return out;
12733
+ }
12734
+ /**
12735
+ * Decode the `locationDescriptions` map, dropping every entry that is not a
12736
+ * non-blank string.
12737
+ *
12738
+ * Same posture as the icons: a blank description and a missing one are the
12739
+ * same instruction to every reader, and storing the first would send an empty
12740
+ * line to a vision model. Over-long text is TRUNCATED rather than dropped —
12741
+ * losing the whole description because a hand-edit ran long is a worse answer
12742
+ * than losing its tail.
12743
+ */
12744
+ function decodeLocationDescriptions(raw) {
12745
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return null;
12746
+ const out = {};
12747
+ for (const [key, value] of Object.entries(raw)) {
12748
+ if (typeof value !== "string") continue;
12749
+ const text = value.trim();
12750
+ if (text.length === 0) continue;
12751
+ out[key] = text.slice(0, 400);
12571
12752
  }
12572
- /**
12573
- * Accept the batch and return immediately. The provider is resolved BEFORE
12574
- * returning so an unroutable `addonId` is refused at the call the operator
12575
- * made, not buried in a job they have to go looking for.
12576
- */
12577
- async start(input) {
12578
- const provider = await this.deps.resolveProvider(input.addonId);
12579
- const job = {
12580
- jobId: this.newId(),
12581
- addonId: input.addonId,
12582
- integrationId: input.integrationId,
12583
- state: "running",
12584
- total: input.childNativeIds.length,
12585
- currentChildNativeId: null,
12586
- results: [],
12587
- startedAt: this.now(),
12588
- finishedAt: null,
12589
- error: null,
12590
- cancelRequested: false,
12591
- done: Promise.resolve()
12753
+ return out;
12754
+ }
12755
+ /**
12756
+ * Decode the zone registry, dropping any entry without a usable label.
12757
+ *
12758
+ * A zone whose label did not survive a hand-edit cannot be shown or renamed —
12759
+ * it would be a row the operator can see the effects of and never name. An
12760
+ * icon outside the vocabulary is dropped on its own, leaving the zone: losing
12761
+ * a glyph is a smaller loss than losing the grouping.
12762
+ */
12763
+ function decodeSiteZones(raw) {
12764
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return null;
12765
+ const out = {};
12766
+ for (const [key, value] of Object.entries(raw)) {
12767
+ if (value === null || typeof value !== "object" || Array.isArray(value)) continue;
12768
+ const rec = value;
12769
+ const label = typeof rec["label"] === "string" ? rec["label"].trim() : "";
12770
+ if (label.length === 0) continue;
12771
+ const icon = canonicalIconKey(rec["icon"]);
12772
+ out[key] = icon === void 0 ? { label } : {
12773
+ label,
12774
+ icon
12592
12775
  };
12593
- this.jobs.set(job.jobId, job);
12594
- this.prune(input.addonId, input.integrationId);
12595
- this.deps.logger.info("adoption job started", {
12596
- tags: { addonId: input.addonId },
12597
- meta: {
12598
- jobId: job.jobId,
12599
- integrationId: input.integrationId,
12600
- total: job.total
12601
- }
12602
- });
12603
- job.done = this.run(job, provider, input);
12604
- return { jobId: job.jobId };
12605
12776
  }
12606
- get(jobId) {
12777
+ return out;
12778
+ }
12779
+ /** Decode a plain `string → string` map, dropping anything else. */
12780
+ function decodeStringMap(raw) {
12781
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return null;
12782
+ const out = {};
12783
+ for (const [key, value] of Object.entries(raw)) {
12784
+ if (typeof value !== "string" || value.trim().length === 0) continue;
12785
+ out[key] = value;
12786
+ }
12787
+ return out;
12788
+ }
12789
+ function isRoleDisplayDefaults(value) {
12790
+ return value !== null && typeof value === "object" && !Array.isArray(value);
12791
+ }
12792
+ //#endregion
12793
+ //#region src/builtins/device-manager/migrations/rooms-as-records.ts
12794
+ /**
12795
+ * Rooms and site zones become records with an id (D1089, step 1 of the migration).
12796
+ *
12797
+ * Before: a room was a LABEL. The registry (`locations`), its icon and description maps
12798
+ * and the two zone maps (`siteZones`, `locationZones`) lived as keys of the addon store,
12799
+ * and a device carried the label in its `location` column.
12800
+ *
12801
+ * After: one `rooms` record per label and one `zones` record per site zone, with an id
12802
+ * derived from the folded name (`roomIdFromKey` / `zoneIdFromKey`, so a rerun and a
12803
+ * restored older snapshot reach the same ids); a device carries `locationId`; the maps and
12804
+ * the `location` column are gone.
12805
+ *
12806
+ * ONE plan, so ONE transaction with the ledger row: the records, the device rows and the
12807
+ * deleted keys land together or not at all. A rerun finds no legacy key and no device with
12808
+ * a `location`, and the plan is empty. A record that already exists is never rewritten (a
12809
+ * seed never overwrites): a room an operator edited after a partial restore keeps its edit.
12810
+ *
12811
+ * The display spelling is the registry's, else the one most devices use (the first
12812
+ * alphabetically on a tie), else the folded key a map entry carries.
12813
+ */
12814
+ var DEVICE_MANAGER_ID = "device-manager";
12815
+ var ROOMS_AS_RECORDS_ID = "device-manager/2026-11-23-rooms-as-records";
12816
+ /** The canonical settings table: one row per key, id `<addonId>.<key>`. */
12817
+ var ADDON_SETTINGS_TABLE = "addon-settings";
12818
+ /** The addon-store keys this migration retires. */
12819
+ var LEGACY_ROOM_KEYS = [
12820
+ "locations",
12821
+ "locationIcons",
12822
+ "locationDescriptions",
12823
+ "siteZones",
12824
+ "locationZones"
12825
+ ];
12826
+ var isPlainMap = (raw) => raw !== null && typeof raw === "object" && !Array.isArray(raw);
12827
+ /** The entries the decode drops or shortens, raw, before the keys are deleted. */
12828
+ function droppedLegacyEntries(stored) {
12829
+ const out = [];
12830
+ const icons = stored["locationIcons"];
12831
+ if (isPlainMap(icons)) {
12832
+ for (const [key, value] of Object.entries(icons)) if (canonicalIconKey(value) === void 0) out.push({
12833
+ map: "locationIcons",
12834
+ key,
12835
+ reason: "icon not in the catalogue",
12836
+ value
12837
+ });
12838
+ }
12839
+ const descriptions = stored["locationDescriptions"];
12840
+ if (isPlainMap(descriptions)) {
12841
+ for (const [key, value] of Object.entries(descriptions)) if (typeof value !== "string" || value.trim().length === 0) out.push({
12842
+ map: "locationDescriptions",
12843
+ key,
12844
+ reason: "blank description",
12845
+ value
12846
+ });
12847
+ else if (value.trim().length > 400) out.push({
12848
+ map: "locationDescriptions",
12849
+ key,
12850
+ reason: "description truncated",
12851
+ value
12852
+ });
12853
+ }
12854
+ const zones = stored["siteZones"];
12855
+ if (isPlainMap(zones)) {
12856
+ for (const [key, value] of Object.entries(zones)) if ((isPlainMap(value) && typeof value["label"] === "string" ? value["label"].trim() : "").length === 0) out.push({
12857
+ map: "siteZones",
12858
+ key,
12859
+ reason: "zone without a label",
12860
+ value
12861
+ });
12862
+ else if (isPlainMap(value) && value["icon"] !== void 0 && canonicalIconKey(value["icon"]) === void 0) out.push({
12863
+ map: "siteZones",
12864
+ key,
12865
+ reason: "zone icon not in the catalogue",
12866
+ value
12867
+ });
12868
+ }
12869
+ const membership = stored["locationZones"];
12870
+ if (isPlainMap(membership)) {
12871
+ for (const [key, value] of Object.entries(membership)) if (typeof value !== "string" || value.trim().length === 0) out.push({
12872
+ map: "locationZones",
12873
+ key,
12874
+ reason: "blank zone",
12875
+ value
12876
+ });
12877
+ else if (!isPlainMap(zones) || zones[value] === void 0) out.push({
12878
+ map: "locationZones",
12879
+ key,
12880
+ reason: "zone not in the registry",
12881
+ value
12882
+ });
12883
+ }
12884
+ return out;
12885
+ }
12886
+ /** A map keyed by the FOLDED room key: a legacy key that was never folded still matches. */
12887
+ function foldedBy(map) {
12888
+ const out = /* @__PURE__ */ new Map();
12889
+ for (const [key, value] of Object.entries(map ?? {})) {
12890
+ const folded = locationIconKey(key);
12891
+ if (folded.length > 0 && !out.has(folded)) out.set(folded, value);
12892
+ }
12893
+ return out;
12894
+ }
12895
+ var settingsRowId = (key) => `${DEVICE_MANAGER_ID}.${key}`;
12896
+ function clip(name) {
12897
+ return name.trim().slice(0, 80);
12898
+ }
12899
+ /** The spelling to show for each folded room key: registry first, else the most used on devices. */
12900
+ function spellings(registry, devices) {
12901
+ const out = /* @__PURE__ */ new Map();
12902
+ for (const label of registry) {
12903
+ const key = locationIconKey(label);
12904
+ if (key.length > 0 && !out.has(key)) out.set(key, clip(label));
12905
+ }
12906
+ const used = /* @__PURE__ */ new Map();
12907
+ for (const { location } of devices) {
12908
+ if (location === null) continue;
12909
+ const key = locationIconKey(location);
12910
+ if (key.length === 0) continue;
12911
+ const counts = used.get(key) ?? /* @__PURE__ */ new Map();
12912
+ counts.set(location.trim(), (counts.get(location.trim()) ?? 0) + 1);
12913
+ used.set(key, counts);
12914
+ }
12915
+ for (const [key, counts] of used) {
12916
+ if (out.has(key)) continue;
12917
+ const best = [...counts.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))[0];
12918
+ if (best !== void 0) out.set(key, clip(best[0]));
12919
+ }
12920
+ return out;
12921
+ }
12922
+ async function planRoomsAsRecords(ports) {
12923
+ const stored = await ports.readStored(LEGACY_ROOM_KEYS);
12924
+ const store = decodeAddonStore(stored);
12925
+ const devices = await ports.readDeviceLocations();
12926
+ const existingRooms = await ports.readRoomIds();
12927
+ const existingZones = await ports.readZoneIds();
12928
+ const names = spellings(store.locations ?? [], devices);
12929
+ for (const key of [
12930
+ ...Object.keys(store.locationIcons ?? {}),
12931
+ ...Object.keys(store.locationDescriptions ?? {}),
12932
+ ...Object.keys(store.locationZones ?? {})
12933
+ ]) {
12934
+ const folded = locationIconKey(key);
12935
+ if (folded.length > 0 && !names.has(folded)) names.set(folded, clip(key));
12936
+ }
12937
+ const zones = store.siteZones ?? {};
12938
+ const membership = foldedBy(store.locationZones);
12939
+ const iconsByRoom = foldedBy(store.locationIcons);
12940
+ const descriptionsByRoom = foldedBy(store.locationDescriptions);
12941
+ const dropped = droppedLegacyEntries(stored);
12942
+ if (dropped.length > 0) {
12943
+ const counts = {};
12944
+ for (const entry of dropped) counts[entry.map] = (counts[entry.map] ?? 0) + 1;
12945
+ ports.report?.("rooms migration: legacy entries not carried over", {
12946
+ counts,
12947
+ dropped
12948
+ });
12949
+ }
12950
+ const edits = [];
12951
+ for (const [zoneKey, zone] of Object.entries(zones)) {
12952
+ const id = zoneIdFromKey(zoneKey);
12953
+ if (existingZones.has(id)) continue;
12954
+ const body = {
12955
+ name: clip(zone.label),
12956
+ ...zone.icon === void 0 ? {} : { icon: zone.icon }
12957
+ };
12958
+ edits.push(recordUpsertEdit({
12959
+ owner: DEVICE_MANAGER_ID,
12960
+ kind: deviceManagerRecordKinds.zones,
12961
+ id,
12962
+ data: body,
12963
+ read: null
12964
+ }));
12965
+ }
12966
+ for (const [key, name] of names) {
12967
+ const id = roomIdFromKey(key);
12968
+ if (existingRooms.has(id)) continue;
12969
+ const icon = iconsByRoom.get(key);
12970
+ const description = descriptionsByRoom.get(key);
12971
+ const zoneKey = membership.get(key);
12972
+ const zoneId = zoneKey !== void 0 && zones[zoneKey] !== void 0 ? zoneIdFromKey(zoneKey) : void 0;
12973
+ const body = {
12974
+ name,
12975
+ ...icon === void 0 ? {} : { icon },
12976
+ ...description === void 0 ? {} : { description },
12977
+ ...zoneId === void 0 ? {} : { zoneId }
12978
+ };
12979
+ edits.push(recordUpsertEdit({
12980
+ owner: DEVICE_MANAGER_ID,
12981
+ kind: deviceManagerRecordKinds.rooms,
12982
+ id,
12983
+ data: body,
12984
+ read: null
12985
+ }));
12986
+ }
12987
+ for (const device of devices) {
12988
+ if (device.location === null) continue;
12989
+ const folded = locationIconKey(device.location);
12990
+ const locationId = device.locationId ?? (folded.length === 0 ? null : roomIdFromKey(folded));
12991
+ edits.push({
12992
+ op: "putRow",
12993
+ table: DEVICE_ROWS_COLLECTION,
12994
+ key: { deviceId: device.deviceId },
12995
+ row: {
12996
+ locationId,
12997
+ location: null
12998
+ },
12999
+ preconditionColumns: ["location", "locationId"],
13000
+ precondition: preconditionOf({
13001
+ location: device.location,
13002
+ locationId: device.locationId
13003
+ })
13004
+ });
13005
+ }
13006
+ const present = LEGACY_ROOM_KEYS.filter((key) => key in stored);
13007
+ if (present.length > 0) edits.push({
13008
+ op: "deleteKeys",
13009
+ scope: ADDON_SETTINGS_TABLE,
13010
+ keys: present.map(settingsRowId),
13011
+ precondition: preconditionOf(Object.fromEntries(present.map((key) => [settingsRowId(key), {
13012
+ addonId: DEVICE_MANAGER_ID,
13013
+ key,
13014
+ value: stored[key]
13015
+ }])))
13016
+ });
13017
+ return { edits };
13018
+ }
13019
+ //#endregion
13020
+ //#region src/builtins/device-manager/migrations/index.ts
13021
+ var REMOVE_ORPHAN_CHILDREN_ID = "device-manager/2026-11-23-remove-orphan-children";
13022
+ /** Rooms, zones and tag ids: run BEFORE the first read resolves a name (D1089). */
13023
+ var ROOMS_AND_TAGS_MIGRATIONS = [{
13024
+ meta: {
13025
+ id: ROOMS_AS_RECORDS_ID,
13026
+ owner: DEVICE_MANAGER_ID,
13027
+ level: "addon-state",
13028
+ seq: 1,
13029
+ dependsOn: [],
13030
+ store: "settings",
13031
+ scope: "cluster",
13032
+ onFailure: "tolerate",
13033
+ bodyKind: "plan",
13034
+ description: "Rooms and site zones become records with an id: one record per label, a locationId on each device, and the label maps and the location column deleted, in one transaction",
13035
+ fixtureMark: "a device column and a room icon the migration does not know"
13036
+ },
13037
+ plan: (ports) => planRoomsAsRecords(ports)
13038
+ }, {
13039
+ meta: {
13040
+ id: DEVICE_TAG_IDS_ID,
13041
+ owner: DEVICE_MANAGER_ID,
13042
+ level: "addon-state",
13043
+ seq: 2,
13044
+ dependsOn: [],
13045
+ store: "settings",
13046
+ scope: "cluster",
13047
+ onFailure: "tolerate",
13048
+ bodyKind: "plan",
13049
+ description: "Add the ids of its tags to each device row beside the kept names, derived from the folded name",
13050
+ fixtureMark: "a device column the migration does not know"
13051
+ },
13052
+ plan: (ports) => planDeviceTagIds(ports)
13053
+ }];
13054
+ /** Accessory rows left behind by a removal that did not cascade: run once the fleet is up (D987). */
13055
+ var ORPHAN_CHILDREN_MIGRATIONS = [{
13056
+ meta: {
13057
+ id: REMOVE_ORPHAN_CHILDREN_ID,
13058
+ owner: DEVICE_MANAGER_ID,
13059
+ level: "addon-state",
13060
+ seq: 3,
13061
+ dependsOn: [],
13062
+ store: "settings",
13063
+ scope: "cluster",
13064
+ onFailure: "tolerate",
13065
+ bodyKind: "procedure",
13066
+ description: "Remove every device row whose parentDeviceId names no row, through the tombstoned removal, each one logged",
13067
+ fixtureMark: "a child of a live parent and a top-level row, both kept"
13068
+ },
13069
+ procedure: removeOrphanChildren
13070
+ }];
13071
+ [...ROOMS_AND_TAGS_MIGRATIONS, ...ORPHAN_CHILDREN_MIGRATIONS];
13072
+ //#endregion
13073
+ //#region src/builtins/device-manager/migrations/ports.ts
13074
+ var import_read_all_rows = require_read_all_rows();
13075
+ var stringOrNull = (value) => typeof value === "string" ? value : null;
13076
+ function stringArray(value) {
13077
+ return Array.isArray(value) ? value.filter((v) => typeof v === "string") : [];
13078
+ }
13079
+ function deviceManagerMigrationPorts(source) {
13080
+ return {
13081
+ readStored: async (keys) => {
13082
+ const found = {};
13083
+ for (const key of keys) {
13084
+ const answer = await source.readStoredKey(key);
13085
+ if (answer.kind === "unreadable") throw new Error(`${DEVICE_MANAGER_ID}: the setting ${key} cannot be read (${answer.reason})`);
13086
+ if (answer.kind === "present") found[key] = answer.value;
13087
+ }
13088
+ return found;
13089
+ },
13090
+ readDeviceLocations: async () => {
13091
+ return (await source.rows.readRawColumns([
13092
+ "deviceId",
13093
+ "location",
13094
+ "locationId"
13095
+ ])).flatMap((row) => {
13096
+ const deviceId = row["deviceId"];
13097
+ if (typeof deviceId !== "number") return [];
13098
+ return [{
13099
+ deviceId,
13100
+ location: stringOrNull(row["location"]),
13101
+ locationId: stringOrNull(row["locationId"])
13102
+ }];
13103
+ });
13104
+ },
13105
+ readDeviceTags: async () => {
13106
+ return (await source.rows.readRawColumns([
13107
+ "deviceId",
13108
+ "tags",
13109
+ "tagIds"
13110
+ ])).flatMap((row) => {
13111
+ const deviceId = row["deviceId"];
13112
+ if (typeof deviceId !== "number") return [];
13113
+ return [{
13114
+ deviceId,
13115
+ tags: stringArray(row["tags"]),
13116
+ hasTagIds: row["tagIds"] !== null && row["tagIds"] !== void 0
13117
+ }];
13118
+ });
13119
+ },
13120
+ readRoomIds: async () => new Set((await (0, import_read_all_rows.readAllRows)(source.rooms)).map((row) => row.id)),
13121
+ readZoneIds: async () => new Set((await (0, import_read_all_rows.readAllRows)(source.zones)).map((row) => row.id)),
13122
+ ...source.report === void 0 ? {} : { report: source.report }
13123
+ };
13124
+ }
13125
+ //#endregion
13126
+ //#region src/builtins/device-manager/adoption-job-engine.ts
13127
+ /** How many finished jobs are kept per (addonId, integrationId). */
13128
+ var JOB_HISTORY = 20;
13129
+ function snapshot(j) {
13130
+ let adopted = 0;
13131
+ let alreadyAdopted = 0;
13132
+ let failed = 0;
13133
+ let processed = 0;
13134
+ let accessoriesCreated = 0;
13135
+ for (const r of j.results) {
13136
+ if (r.outcome === "cancelled") continue;
13137
+ processed += 1;
13138
+ accessoriesCreated += r.accessoryCount;
13139
+ if (r.outcome === "adopted") adopted += 1;
13140
+ else if (r.outcome === "already-adopted") alreadyAdopted += 1;
13141
+ else if (r.outcome === "failed") failed += 1;
13142
+ }
13143
+ return {
13144
+ jobId: j.jobId,
13145
+ addonId: j.addonId,
13146
+ integrationId: j.integrationId,
13147
+ state: j.state,
13148
+ total: j.total,
13149
+ processed,
13150
+ adopted,
13151
+ alreadyAdopted,
13152
+ failed,
13153
+ accessoriesCreated,
13154
+ currentChildNativeId: j.currentChildNativeId,
13155
+ results: j.results.map((r) => ({
13156
+ childNativeId: r.childNativeId,
13157
+ outcome: r.outcome,
13158
+ parentDeviceId: r.parentDeviceId,
13159
+ accessoryCount: r.accessoryCount,
13160
+ error: r.error
13161
+ })),
13162
+ startedAt: j.startedAt,
13163
+ finishedAt: j.finishedAt,
13164
+ error: j.error
13165
+ };
13166
+ }
13167
+ var AdoptionJobEngine = class {
13168
+ deps;
13169
+ jobs = /* @__PURE__ */ new Map();
13170
+ seq = 0;
13171
+ constructor(deps) {
13172
+ this.deps = deps;
13173
+ }
13174
+ now() {
13175
+ return this.deps.now?.() ?? Date.now();
13176
+ }
13177
+ newId() {
13178
+ if (this.deps.newId) return this.deps.newId();
13179
+ this.seq += 1;
13180
+ return `adopt-${Date.now().toString(36)}-${this.seq}`;
13181
+ }
13182
+ /**
13183
+ * Accept the batch and return immediately. The provider is resolved BEFORE
13184
+ * returning so an unroutable `addonId` is refused at the call the operator
13185
+ * made, not buried in a job they have to go looking for.
13186
+ */
13187
+ async start(input) {
13188
+ const provider = await this.deps.resolveProvider(input.addonId);
13189
+ const job = {
13190
+ jobId: this.newId(),
13191
+ addonId: input.addonId,
13192
+ integrationId: input.integrationId,
13193
+ state: "running",
13194
+ total: input.childNativeIds.length,
13195
+ currentChildNativeId: null,
13196
+ results: [],
13197
+ startedAt: this.now(),
13198
+ finishedAt: null,
13199
+ error: null,
13200
+ cancelRequested: false,
13201
+ done: Promise.resolve()
13202
+ };
13203
+ this.jobs.set(job.jobId, job);
13204
+ this.prune(input.addonId, input.integrationId);
13205
+ this.deps.logger.info("adoption job started", {
13206
+ tags: { addonId: input.addonId },
13207
+ meta: {
13208
+ jobId: job.jobId,
13209
+ integrationId: input.integrationId,
13210
+ total: job.total
13211
+ }
13212
+ });
13213
+ job.done = this.run(job, provider, input);
13214
+ return { jobId: job.jobId };
13215
+ }
13216
+ get(jobId) {
12607
13217
  const j = this.jobs.get(jobId);
12608
13218
  return j ? snapshot(j) : null;
12609
13219
  }
@@ -13488,6 +14098,104 @@ function sleep$1(ms) {
13488
14098
  });
13489
14099
  }
13490
14100
  //#endregion
14101
+ //#region src/builtins/device-manager/wireable-enum-catalog.ts
14102
+ /**
14103
+ * Per-device value catalogs for wireable fields (`status.fieldEnums` on a cap).
14104
+ *
14105
+ * A status field such as `error.code` or `event-emitter.lastEvent.eventType` is a
14106
+ * plain string in the schema, but the device's integration DECLARES the closed set
14107
+ * of values at runtime (`error.listFaultTypes`, the event vocabulary). This module
14108
+ * asks the device's own provider and returns the values the editor offers as a
14109
+ * dropdown. A read that fails answers `null` — the caller leaves `enumValues`
14110
+ * absent (free text stays) and logs; it is never an empty list (D393, D315).
14111
+ */
14112
+ var RecordSchema = z.record(z.string(), z.unknown());
14113
+ function isProviderShape(value) {
14114
+ return typeof value === "object" && value !== null;
14115
+ }
14116
+ function listOf(answer, source) {
14117
+ const record = RecordSchema.safeParse(answer);
14118
+ if (!record.success) return null;
14119
+ const list = z.array(RecordSchema).safeParse(record.data[source.listKey]);
14120
+ if (!list.success) return null;
14121
+ const values = [];
14122
+ for (const entry of list.data) {
14123
+ const value = entry[source.valueKey];
14124
+ if (typeof value !== "string") return null;
14125
+ if (!values.includes(value)) values.push(value);
14126
+ }
14127
+ return values;
14128
+ }
14129
+ async function readAnswer(provider, source, deviceId) {
14130
+ const fn = provider[source.from === "method" ? source.method : "getStatus"];
14131
+ if (typeof fn !== "function") return void 0;
14132
+ return await Reflect.apply(fn, provider, [{ deviceId }]);
14133
+ }
14134
+ var TIMED_OUT = Symbol("catalog-read-timed-out");
14135
+ async function raceBudget(work, budgetMs) {
14136
+ let timer;
14137
+ const deadline = new Promise((resolve) => {
14138
+ timer = setTimeout(() => resolve(TIMED_OUT), budgetMs);
14139
+ timer.unref?.();
14140
+ });
14141
+ try {
14142
+ return await Promise.race([work, deadline]);
14143
+ } finally {
14144
+ if (timer !== void 0) clearTimeout(timer);
14145
+ }
14146
+ }
14147
+ /**
14148
+ * The device's declared values for one field, or `null` when there are none to
14149
+ * offer. A provider without the catalog, a cold (null) slice or an empty catalog
14150
+ * is a quiet absence; a thrown read, a timeout or a malformed answer is warned
14151
+ * with the device tag. Either way the field stays free text.
14152
+ */
14153
+ async function readFieldCatalog(read) {
14154
+ const { registry, logger, capName, deviceId, path, source, budgetMs } = read;
14155
+ try {
14156
+ const provider = registry.getProviderForDevice(capName, deviceId);
14157
+ if (!isProviderShape(provider)) return null;
14158
+ const answer = await raceBudget(readAnswer(provider, source, deviceId), budgetMs);
14159
+ if (answer === TIMED_OUT) {
14160
+ logger.warn("wireable field catalog: read timed out, field stays free text", {
14161
+ tags: { deviceId },
14162
+ meta: {
14163
+ deviceId,
14164
+ capName,
14165
+ path,
14166
+ budgetMs
14167
+ }
14168
+ });
14169
+ return null;
14170
+ }
14171
+ if (answer === void 0 || answer === null) return null;
14172
+ const values = listOf(answer, source);
14173
+ if (values === null) {
14174
+ logger.warn("wireable field catalog: answer has an unexpected shape", {
14175
+ tags: { deviceId },
14176
+ meta: {
14177
+ deviceId,
14178
+ capName,
14179
+ path
14180
+ }
14181
+ });
14182
+ return null;
14183
+ }
14184
+ return values.length > 0 ? values : null;
14185
+ } catch (err) {
14186
+ logger.warn("wireable field catalog: read failed, field stays free text", {
14187
+ tags: { deviceId },
14188
+ meta: {
14189
+ deviceId,
14190
+ capName,
14191
+ path,
14192
+ error: err instanceof Error ? err.message : String(err)
14193
+ }
14194
+ });
14195
+ return null;
14196
+ }
14197
+ }
14198
+ //#endregion
13491
14199
  //#region src/builtins/device-manager/device-aggregation-merge.ts
13492
14200
  /**
13493
14201
  * Pure aggregator-merge + field-tagging helpers for the device-manager
@@ -13657,11 +14365,11 @@ function mergeAggregates(parts) {
13657
14365
  * per-row path (`connection.password`, `rows[].pin`) is not mapped onto a form
13658
14366
  * field and keeps the driver's hydration.
13659
14367
  */
13660
- function isRecord$3(value) {
14368
+ function isRecord$4(value) {
13661
14369
  return typeof value === "object" && value !== null && !Array.isArray(value);
13662
14370
  }
13663
14371
  function isConfigFieldWithValue(field) {
13664
- if (!isRecord$3(field)) return false;
14372
+ if (!isRecord$4(field)) return false;
13665
14373
  return typeof field.type === "string" && typeof field.key === "string" && "value" in field;
13666
14374
  }
13667
14375
  /** The declared paths that name a top-level config key. */
@@ -13669,7 +14377,7 @@ function topLevelKeys(paths) {
13669
14377
  return new Set(paths.filter((p) => p.length > 0 && !p.includes(".") && !p.includes("[")));
13670
14378
  }
13671
14379
  function viewField(field, stored, declared) {
13672
- if (!isRecord$3(field)) return field;
14380
+ if (!isRecord$4(field)) return field;
13673
14381
  const nested = field["fields"];
13674
14382
  if (Array.isArray(nested)) return {
13675
14383
  ...field,
@@ -13678,7 +14386,7 @@ function viewField(field, stored, declared) {
13678
14386
  const tabs = field["tabs"];
13679
14387
  if (Array.isArray(tabs)) return {
13680
14388
  ...field,
13681
- tabs: tabs.map((tab) => isRecord$3(tab) && Array.isArray(tab["fields"]) ? {
14389
+ tabs: tabs.map((tab) => isRecord$4(tab) && Array.isArray(tab["fields"]) ? {
13682
14390
  ...tab,
13683
14391
  fields: tab["fields"].map((f) => viewField(f, stored, declared))
13684
14392
  } : tab)
@@ -13787,7 +14495,7 @@ function isDeclaredCollectionCap(capName) {
13787
14495
  function isDeclaredNonWrapperCap(capName) {
13788
14496
  return DECLARED_NON_WRAPPER_CAPS.has(capName);
13789
14497
  }
13790
- function isRecord$2(value) {
14498
+ function isRecord$3(value) {
13791
14499
  return typeof value === "object" && value !== null && !Array.isArray(value);
13792
14500
  }
13793
14501
  /** A persisted activation of a wrapper on a cap that has none (see module docblock). */
@@ -13830,12 +14538,12 @@ var StaleWrapperActivations = class {
13830
14538
  if (this.checked) return;
13831
14539
  this.checked = true;
13832
14540
  const devices = store.deviceBindings;
13833
- if (!isRecord$2(devices)) return;
14541
+ if (!isRecord$3(devices)) return;
13834
14542
  for (const [deviceKey, perDevice] of Object.entries(devices)) {
13835
14543
  const deviceId = Number(deviceKey);
13836
- if (!Number.isInteger(deviceId) || !isRecord$2(perDevice)) continue;
14544
+ if (!Number.isInteger(deviceId) || !isRecord$3(perDevice)) continue;
13837
14545
  for (const [capName, row] of Object.entries(perDevice)) {
13838
- const wrapperAddonId = isRecord$2(row) ? row["wrapperAddonId"] : void 0;
14546
+ const wrapperAddonId = isRecord$3(row) ? row["wrapperAddonId"] : void 0;
13839
14547
  if (typeof wrapperAddonId === "string" && isDeclaredNonWrapperCap(capName)) this.report(deviceId, capName, wrapperAddonId);
13840
14548
  }
13841
14549
  }
@@ -15488,6 +16196,7 @@ async function readDeviceConfigs(pctx, deviceIds) {
15488
16196
  return pctx.settings.readDeviceStoreBatch(deviceIds);
15489
16197
  }
15490
16198
  async function listAll(pctx, input) {
16199
+ await pctx.freshTagNames();
15491
16200
  const ownerFilter = Reflect.get(input, "addonId");
15492
16201
  if (ownerFilter !== void 0 && (typeof ownerFilter !== "string" || ownerFilter.length === 0)) throw new Error(`deviceManager.listAll: addonId must be a non-empty string or be omitted — got ${JSON.stringify(ownerFilter)}. An owner filter that is present but empty is never widened to every device. On an addon context the id is \`ctx.id\`; there is no \`ctx.addonId\`.`);
15493
16202
  const callerAddonId = pctx.metaStore.rows.censusArmed ? extractCallerAddonId(input) : void 0;
@@ -15575,6 +16284,7 @@ async function listAll(pctx, input) {
15575
16284
  }
15576
16285
  async function getDevice(pctx, input) {
15577
16286
  const { deviceId } = input;
16287
+ await pctx.freshTagNames();
15578
16288
  if (pctx.registry) {
15579
16289
  const found = resolveDeviceById(pctx.registry, deviceId);
15580
16290
  if (found) {
@@ -17169,6 +17879,36 @@ function wireableEntryForDef(capName, def) {
17169
17879
  };
17170
17880
  }
17171
17881
  /**
17882
+ * Fill `enumValues` of the fields the cap declares a per-device catalog for
17883
+ * (`status.fieldEnums`) from the device's own provider. A failed or empty read
17884
+ * leaves the field untouched (free text), never an empty list.
17885
+ */
17886
+ async function withDeclaredCatalogs(deps, registry, deviceId, entry, def) {
17887
+ const declared = def.status?.fieldEnums;
17888
+ if (!declared) return entry;
17889
+ const fields = await Promise.all(entry.fields.map(async (field) => {
17890
+ const source = declared[field.path];
17891
+ if (!source || field.item === true) return field;
17892
+ const values = await readFieldCatalog({
17893
+ registry,
17894
+ logger: deps.ctx.logger,
17895
+ capName: entry.cap,
17896
+ deviceId,
17897
+ path: field.path,
17898
+ source,
17899
+ budgetMs: CONTRIBUTION_BUDGET_MS
17900
+ });
17901
+ return values === null ? field : {
17902
+ ...field,
17903
+ enumValues: values
17904
+ };
17905
+ }));
17906
+ return {
17907
+ ...entry,
17908
+ fields
17909
+ };
17910
+ }
17911
+ /**
17172
17912
  * Per-device wireable-field catalog — the domain status fields a device's
17173
17913
  * bound caps expose, for the operator's cross-device wiring UI. Binding-driven:
17174
17914
  * walks `getBindings(deviceId)`, skips wrapper caps (their status schemas are
@@ -17189,14 +17929,19 @@ async function getWireableFields(deps, input) {
17189
17929
  const { entries } = await getBindings(deps.bindingsDeps, { deviceId });
17190
17930
  const seen = /* @__PURE__ */ new Set();
17191
17931
  const caps = [];
17932
+ const pending = [];
17192
17933
  for (const entry of entries) {
17193
17934
  if (seen.has(entry.capName)) continue;
17194
17935
  seen.add(entry.capName);
17195
17936
  const def = reg.getDefinition(entry.capName);
17196
17937
  if (!def || def.kind === "wrapper") continue;
17197
17938
  const wireable = wireableEntryForDef(entry.capName, def);
17198
- if (wireable) caps.push(wireable);
17939
+ if (wireable) pending.push({
17940
+ wireable,
17941
+ def
17942
+ });
17199
17943
  }
17944
+ caps.push(...await Promise.all(pending.map(({ wireable, def }) => withDeclaredCatalogs(deps, reg, deviceId, wireable, def))));
17200
17945
  if (input.includeSynthesizable === true) {
17201
17946
  const deviceType = (await deps.bindingsDeps.rows.get(deviceId))?.meta.type;
17202
17947
  if (deviceType !== void 0) for (const def of ALL_CAPABILITY_DEFINITIONS) {
@@ -17394,8 +18139,9 @@ async function searchDevices(deps, input) {
17394
18139
  let compatibleTotal = 0;
17395
18140
  let hiddenIncompatible = 0;
17396
18141
  const filters = input.filters;
18142
+ const locationFilter = filters?.locations?.map((value) => deps.roomNameOf?.(value) ?? value);
17397
18143
  for (const c of textPass) {
17398
- const okLocation = matches(filters?.locations, c.device.location);
18144
+ const okLocation = matches(locationFilter, c.device.location);
17399
18145
  const okIntegration = matches(filters?.integrationIds, c.integrationId);
17400
18146
  const okType = matches(filters?.types, c.device.type);
17401
18147
  if (c.compatible) {
@@ -17728,7 +18474,7 @@ async function setWrapperActive(deps, input) {
17728
18474
  }
17729
18475
  });
17730
18476
  }
17731
- function isRecord$1(value) {
18477
+ function isRecord$2(value) {
17732
18478
  return typeof value === "object" && value !== null && !Array.isArray(value);
17733
18479
  }
17734
18480
  /** The key of this addon's store that holds every wrapper activation. */
@@ -17768,19 +18514,19 @@ async function readWrapperActivation(deps, query) {
17768
18514
  error: "the store holds no deviceBindings row — an empty snapshot is not evidence of an unbind"
17769
18515
  };
17770
18516
  const deviceBindings = read.value;
17771
- if (!isRecord$1(deviceBindings)) return {
18517
+ if (!isRecord$2(deviceBindings)) return {
17772
18518
  kind: "failed",
17773
18519
  error: "stored deviceBindings is not a map"
17774
18520
  };
17775
18521
  const perDevice = deviceBindings[String(query.deviceId)];
17776
18522
  if (perDevice === void 0) return { kind: "missing" };
17777
- if (!isRecord$1(perDevice)) return {
18523
+ if (!isRecord$2(perDevice)) return {
17778
18524
  kind: "failed",
17779
18525
  error: `stored bindings of device ${query.deviceId} are not a map`
17780
18526
  };
17781
18527
  const activation = perDevice[query.capName];
17782
18528
  if (activation === void 0) return { kind: "missing" };
17783
- if (!isRecord$1(activation)) return {
18529
+ if (!isRecord$2(activation)) return {
17784
18530
  kind: "failed",
17785
18531
  error: `stored "${query.capName}" activation is not a record`
17786
18532
  };
@@ -18911,7 +19657,7 @@ function nearestLocatedAncestor(byId, startParentId) {
18911
19657
  visited.add(cursor);
18912
19658
  const ancestor = byId.get(cursor);
18913
19659
  if (!ancestor) return null;
18914
- if (ancestor.location !== null) return ancestor;
19660
+ if (ancestor.locationId !== void 0 && ancestor.locationId !== null) return ancestor;
18915
19661
  cursor = ancestor.parentDeviceId;
18916
19662
  }
18917
19663
  return null;
@@ -18941,15 +19687,16 @@ function planNullLocationFills(rows) {
18941
19687
  const byId = new Map(rows.map((r) => [r.id, r]));
18942
19688
  const plan = [];
18943
19689
  for (const row of rows) {
18944
- if (row.location !== null) continue;
19690
+ if (row.locationId !== void 0 && row.locationId !== null) continue;
18945
19691
  if (row.parentDeviceId === null) continue;
18946
19692
  const hit = nearestLocatedAncestor(byId, row.parentDeviceId);
18947
19693
  if (hit === null) continue;
18948
19694
  if (hit.type !== DeviceType$1.Container) continue;
18949
- if (hit.location === null) continue;
19695
+ if (hit.locationId === void 0 || hit.locationId === null) continue;
18950
19696
  plan.push({
18951
19697
  id: row.id,
18952
19698
  location: hit.location,
19699
+ locationId: hit.locationId,
18953
19700
  ancestorId: hit.id
18954
19701
  });
18955
19702
  }
@@ -18974,8 +19721,15 @@ async function resolveInheritedLocation(rows, parentDeviceId) {
18974
19721
  visited.add(cursor);
18975
19722
  const ancestor = await rows.get(cursor);
18976
19723
  if (ancestor === null) return null;
18977
- if (ancestor.meta.location !== null) return ancestor.meta.type === DeviceType$1.Container ? ancestor.meta.location : null;
18978
- cursor = ancestor.meta.parentDeviceId;
19724
+ const locationId = ancestor.meta.locationId ?? null;
19725
+ if (locationId !== null) {
19726
+ if (ancestor.meta.type !== DeviceType$1.Container) return null;
19727
+ return {
19728
+ locationId,
19729
+ location: ancestor.meta.location
19730
+ };
19731
+ }
19732
+ cursor = ancestor.meta.parentDeviceId;
18979
19733
  }
18980
19734
  return null;
18981
19735
  }
@@ -19009,8 +19763,8 @@ async function runLocationBackfillAtBoot(pctx, bootRows) {
19009
19763
  const plan = planNullLocationFills((await pctx.metaStore.rows.listAll()).map((r) => r.meta));
19010
19764
  for (const fill of plan) try {
19011
19765
  const current = await pctx.metaStore.rows.get(fill.id);
19012
- if (current === null || current.meta.location !== null) continue;
19013
- await pctx.metaStore.rows.patch(fill.id, { location: fill.location });
19766
+ if (current === null || (current.meta.locationId ?? null) !== null) continue;
19767
+ await pctx.metaStore.rows.patch(fill.id, { locationId: fill.locationId });
19014
19768
  patched.push(fill);
19015
19769
  } catch (err) {
19016
19770
  failed.push({
@@ -19223,8 +19977,9 @@ async function migrateDevice$1(deps, input) {
19223
19977
  alarmPartialMigration(deps, ids, "swapIds", err);
19224
19978
  throw err;
19225
19979
  }
19980
+ let secretScopes;
19226
19981
  try {
19227
- await deps.swapHardwareState(sourceId, targetId);
19982
+ secretScopes = await deps.swapHardwareState(sourceId, targetId);
19228
19983
  } catch (err) {
19229
19984
  alarmPartialMigration(deps, ids, "swapHardwareState", err);
19230
19985
  throw err;
@@ -19250,7 +20005,8 @@ async function migrateDevice$1(deps, input) {
19250
20005
  targetId,
19251
20006
  switches: [...down, ...up],
19252
20007
  sourceStillLive,
19253
- swapped: true
20008
+ swapped: true,
20009
+ secretScopes
19254
20010
  };
19255
20011
  }
19256
20012
  //#endregion
@@ -19287,6 +20043,15 @@ async function migrateDevice$1(deps, input) {
19287
20043
  * stream-profile assignment (the live authority is the stream broker's own
19288
20044
  * map — see `StreamsTab.tsx`, which stopped writing it), and either copy
19289
20045
  * names stream ids of the wrong hardware after a swap.
20046
+ * - A secret marker inside the swapped config names the keychain scope of ONE
20047
+ * number (`secret://<owner>/device/<id>/<field>`; the ref is the AAD of the
20048
+ * ciphertext). Swapping the marker alone left each number pointing at the
20049
+ * other's scope, so removing either device purged the secret the other still
20050
+ * used (D1093, live 2026-11-23). The configs swap with their markers
20051
+ * unchanged (each still reads its value), then `repairCrossedSecretScopes`
20052
+ * brings every value under the number whose config holds it, through staged
20053
+ * copies, so a crash at any step is finished by a re-run of the repair.
20054
+ * - The location (room) is role state and stays on the number (`swapIds`).
19290
20055
  * - The runtime-state blobs (`__device-state:<id>` — battery snapshot, sleep
19291
20056
  * flag, feature probe) SWAP wholesale: every slice mirrors the box — never
19292
20057
  * while either carries `$owned` (D663): the migration is refused first
@@ -19412,11 +20177,21 @@ function splitConfig(config) {
19412
20177
  * incident this module exists to prevent, and it must never be reported as a
19413
20178
  * success.
19414
20179
  */
19415
- async function swapHardwareState(settings, sourceId, targetId) {
20180
+ async function swapHardwareState(settings, sourceId, targetId, secrets) {
19416
20181
  const sourceConfig = await settings.readDeviceStore(sourceId);
19417
20182
  const targetConfig = await settings.readDeviceStore(targetId);
20183
+ const crossed = [{
20184
+ deviceId: sourceId,
20185
+ markers: crossedIn(sourceConfig, targetId)
20186
+ }, {
20187
+ deviceId: targetId,
20188
+ markers: crossedIn(targetConfig, sourceId)
20189
+ }].filter((c) => c.markers > 0);
20190
+ if (crossed.length > 0) throw new Error(new SecretScopesCrossedError(sourceId, targetId, crossed).message);
19418
20191
  const source = splitConfig(sourceConfig);
19419
20192
  const target = splitConfig(targetConfig);
20193
+ const marked = hasDeviceMarkers(source.hardware, sourceId, targetId) || hasDeviceMarkers(target.hardware, sourceId, targetId);
20194
+ if (secrets === void 0 && marked) throw new Error(`keychain door unavailable - devices ${sourceId} and ${targetId} hold keychain secrets and the migration cannot move them; nothing was changed`);
19420
20195
  await settings.clearDeviceStore(sourceId);
19421
20196
  await settings.writeDeviceStore(sourceId, {
19422
20197
  ...target.hardware,
@@ -19431,14 +20206,216 @@ async function swapHardwareState(settings, sourceId, targetId) {
19431
20206
  const targetRuntimeState = await settings.readDeviceRuntimeState(targetId);
19432
20207
  await settings.writeDeviceRuntimeState(sourceId, targetRuntimeState);
19433
20208
  await settings.writeDeviceRuntimeState(targetId, sourceRuntimeState);
20209
+ let secretScopes = {
20210
+ exchanged: false,
20211
+ markersRepointed: 0,
20212
+ refsAtSource: [],
20213
+ refsAtTarget: []
20214
+ };
20215
+ if (marked) try {
20216
+ const repaired = await repairCrossedSecretScopes(settings, secrets, sourceId, targetId, true);
20217
+ secretScopes = {
20218
+ exchanged: repaired.outcome === "repaired",
20219
+ markersRepointed: repaired.markersRepointedAtA + repaired.markersRepointedAtB,
20220
+ refsAtSource: repaired.refsNowAtA,
20221
+ refsAtTarget: repaired.refsNowAtB
20222
+ };
20223
+ } catch (err) {
20224
+ throw new Error(`migration: configs swapped but the secrets are not yet under their own numbers (${err instanceof Error ? err.message : String(err)}); every marker still reads its value - run deviceManager.repairMigrationSecrets { deviceA: ${sourceId}, deviceB: ${targetId}, apply: true }`, { cause: err });
20225
+ }
19434
20226
  return {
19435
20227
  runtimeStateNowAtSource: targetRuntimeState,
19436
20228
  runtimeStateNowAtTarget: sourceRuntimeState,
19437
20229
  hardwareKeysToSource: Object.keys(target.hardware).toSorted(),
19438
20230
  hardwareKeysToTarget: Object.keys(source.hardware).toSorted(),
19439
20231
  roleKeysKeptAtSource: Object.keys(source.role).toSorted(),
19440
- roleKeysKeptAtTarget: Object.keys(target.role).toSorted()
20232
+ roleKeysKeptAtTarget: Object.keys(target.role).toSorted(),
20233
+ secretScopes
20234
+ };
20235
+ }
20236
+ /** The suffix of the staging copy a repair keeps while a value changes scope. */
20237
+ var REPAIR_STAGING_SUFFIX = "~repair";
20238
+ function refWithin(parts, deviceId, fieldPath) {
20239
+ return buildSecretRef({
20240
+ ...parts,
20241
+ scope: {
20242
+ kind: "device",
20243
+ deviceId
20244
+ },
20245
+ fieldPath
20246
+ });
20247
+ }
20248
+ /**
20249
+ * The markers of `config` (the config of `ownId`) the repair must move: those
20250
+ * naming `otherId`'s scope, and the staging copies of an interrupted run.
20251
+ */
20252
+ function repairMarkers(config, ownId, otherId) {
20253
+ const found = [];
20254
+ for (const current of collectMarkerRefs(config)) {
20255
+ const parts = parseSecretRef(current);
20256
+ if (parts === null || parts.scope.kind !== "device") continue;
20257
+ const staged = parts.fieldPath.endsWith(REPAIR_STAGING_SUFFIX);
20258
+ if (!(parts.scope.deviceId === otherId || staged && parts.scope.deviceId === ownId)) continue;
20259
+ const fieldPath = staged ? parts.fieldPath.slice(0, -7) : parts.fieldPath;
20260
+ found.push({
20261
+ current,
20262
+ staging: staged ? current : refWithin(parts, ownId, `${fieldPath}${REPAIR_STAGING_SUFFIX}`),
20263
+ dest: refWithin(parts, ownId, fieldPath),
20264
+ owner: parts.owner,
20265
+ staged
20266
+ });
20267
+ }
20268
+ return found;
20269
+ }
20270
+ /**
20271
+ * Repair a pair a migration left with CROSSED secrets (it ran before the
20272
+ * secrets followed the config): a number's config carries markers naming the
20273
+ * OTHER number's keychain scope, so removing either device would purge the
20274
+ * secret the other still reads. Each such marker's value is brought under the
20275
+ * number whose config holds it.
20276
+ *
20277
+ * The configs ARE the state machine, so a crash at any step is re-run to the
20278
+ * right end state — never a double exchange, never a value lost:
20279
+ * 1. stage: copy each value to a staging ref in its own number's scope
20280
+ * (idempotent puts; the originals are untouched);
20281
+ * 2. point both configs at the staging refs — from here every marker reads a
20282
+ * value that is not about to be overwritten;
20283
+ * 3. put each value at its end ref (idempotent: the source is the staging ref);
20284
+ * 4. point both configs at the end refs;
20285
+ * 5. delete the staging refs and any original no config names any more.
20286
+ * A re-run reads each marker's CURRENT ref, so a marker already at a staging
20287
+ * or end ref continues from there. One-sided pairs and a pair where only some
20288
+ * fields are crossed work the same way, field by field.
20289
+ *
20290
+ * Idempotent: a pair with no marker to move is left alone. `apply: false` is
20291
+ * the dry run: counts only. A missing keychain door with markers to move THROWS.
20292
+ */
20293
+ async function repairCrossedSecretScopes(settings, secrets, deviceA, deviceB, apply) {
20294
+ const configA = await settings.readDeviceStore(deviceA);
20295
+ const configB = await settings.readDeviceStore(deviceB);
20296
+ const markersA = repairMarkers(configA, deviceA, deviceB);
20297
+ const markersB = repairMarkers(configB, deviceB, deviceA);
20298
+ const counts = {
20299
+ markersRepointedAtA: markersA.length,
20300
+ markersRepointedAtB: markersB.length
20301
+ };
20302
+ if (markersA.length === 0 && markersB.length === 0) return {
20303
+ outcome: "nothing-to-repair",
20304
+ ...counts,
20305
+ refsNowAtA: [],
20306
+ refsNowAtB: []
20307
+ };
20308
+ if (secrets === void 0) throw new Error(`repairMigrationSecrets: no keychain door on this node — devices ${deviceA} and ${deviceB} hold markers that must move; nothing was changed`);
20309
+ if (!apply) return {
20310
+ outcome: "would-repair",
20311
+ ...counts,
20312
+ refsNowAtA: [],
20313
+ refsNowAtB: []
20314
+ };
20315
+ const all = [...markersA, ...markersB];
20316
+ const valueOf = async (owner, ref) => {
20317
+ const answer = (await secrets.forOwner(owner).resolve([ref]))[ref];
20318
+ if (answer?.kind === "value") return answer.value;
20319
+ throw new Error(`repairMigrationSecrets: ${ref} cannot be read (${answer?.kind ?? "no answer"}); nothing was changed`);
20320
+ };
20321
+ const rewritten = (pick) => {
20322
+ const mapOf = (markers) => {
20323
+ const byCurrent = new Map(markers.map((m) => [m.current, pick(m)]));
20324
+ return (ref) => byCurrent.get(ref);
20325
+ };
20326
+ return [rewriteMarkerRefs(configA, mapOf(markersA)), rewriteMarkerRefs(configB, mapOf(markersB))];
19441
20327
  };
20328
+ const writeBoth = async (pick) => {
20329
+ const [nextA, nextB] = rewritten(pick);
20330
+ await settings.writeDeviceStore(deviceA, nextA);
20331
+ await settings.writeDeviceStore(deviceB, nextB);
20332
+ };
20333
+ for (const m of all) if (!m.staged) await secrets.forOwner(m.owner).put(m.staging, await valueOf(m.owner, m.current));
20334
+ await writeBoth((m) => m.staging);
20335
+ for (const m of all) await secrets.forOwner(m.owner).put(m.dest, await valueOf(m.owner, m.staging));
20336
+ await writeBoth((m) => m.dest);
20337
+ const finalRefs = new Set(rewritten((m) => m.dest).flatMap(collectMarkerRefs));
20338
+ for (const m of all) {
20339
+ const stale = [m.staging, ...m.staged || finalRefs.has(m.current) ? [] : [m.current]];
20340
+ await secrets.forOwner(m.owner).delete(stale);
20341
+ }
20342
+ for (const ref of finalRefs) {
20343
+ const parts = parseSecretRef(ref);
20344
+ if (parts === null || parts.scope.kind !== "device") continue;
20345
+ const strays = [deviceA, deviceB].map((id) => refWithin(parts, id, `${parts.fieldPath.replace(/~repair$/, "")}${REPAIR_STAGING_SUFFIX}`)).filter((stray) => !finalRefs.has(stray));
20346
+ await secrets.forOwner(parts.owner).delete(strays);
20347
+ }
20348
+ return {
20349
+ outcome: "repaired",
20350
+ ...counts,
20351
+ refsNowAtA: markersA.map((m) => m.dest),
20352
+ refsNowAtB: markersB.map((m) => m.dest)
20353
+ };
20354
+ }
20355
+ /**
20356
+ * The refusal of a migration over a pair whose configs hold markers naming the
20357
+ * OTHER number's keychain scope (an earlier migration crossed them): swapping
20358
+ * again would mix the passwords. Nothing moved; run the repair first.
20359
+ */
20360
+ var SecretScopesCrossedError = class extends MigrationRefusedError {
20361
+ sourceId;
20362
+ targetId;
20363
+ crossed;
20364
+ constructor(sourceId, targetId, crossed) {
20365
+ super(`secret-scopes-crossed: migration ${sourceId} → ${targetId} refused: ${crossed.map((c) => `device ${c.deviceId} holds ${c.markers} secret marker(s) naming the other number's keychain scope`).join("; ")} — run deviceManager.repairMigrationSecrets first (nothing moved)`);
20366
+ this.sourceId = sourceId;
20367
+ this.targetId = targetId;
20368
+ this.crossed = crossed;
20369
+ this.name = "SecretScopesCrossedError";
20370
+ }
20371
+ };
20372
+ /** True when `config` holds a marker in the keychain scope of device `a` or `b`. */
20373
+ function hasDeviceMarkers(config, a, b) {
20374
+ return collectMarkerRefs(config).some((ref) => {
20375
+ const parts = parseSecretRef(ref);
20376
+ return parts !== null && parts.scope.kind === "device" && (parts.scope.deviceId === a || parts.scope.deviceId === b);
20377
+ });
20378
+ }
20379
+ function crossedIn(config, otherId) {
20380
+ return collectMarkerRefs(config).filter((ref) => {
20381
+ const parts = parseSecretRef(ref);
20382
+ return parts !== null && parts.scope.kind === "device" && parts.scope.deviceId === otherId;
20383
+ }).length;
20384
+ }
20385
+ /**
20386
+ * Refuse a migration when either config already names the other number's
20387
+ * keychain scope. Read from the stored configs (D49: an unreadable config
20388
+ * throws, never reads as "not crossed").
20389
+ */
20390
+ async function assertNoCrossedSecretScopes(settings, sourceId, targetId) {
20391
+ const crossed = [{
20392
+ deviceId: sourceId,
20393
+ markers: crossedIn(await settings.readDeviceStore(sourceId), targetId)
20394
+ }, {
20395
+ deviceId: targetId,
20396
+ markers: crossedIn(await settings.readDeviceStore(targetId), sourceId)
20397
+ }].filter((c) => c.markers > 0);
20398
+ if (crossed.length > 0) throw new SecretScopesCrossedError(sourceId, targetId, crossed);
20399
+ }
20400
+ /** Every secret marker's ref in a config, at any depth. */
20401
+ function collectMarkerRefs(value) {
20402
+ if (Array.isArray(value)) return value.flatMap(collectMarkerRefs);
20403
+ if (isSecretMarker(value)) return [value.$secret];
20404
+ if (isRecord$1(value)) return Object.values(value).flatMap(collectMarkerRefs);
20405
+ return [];
20406
+ }
20407
+ /** A copy of `value` whose markers name `map(ref)` where it answers (others untouched). */
20408
+ function rewriteMarkerRefs(value, map) {
20409
+ const walk = (node) => {
20410
+ if (Array.isArray(node)) return node.map(walk);
20411
+ if (isSecretMarker(node)) return makeSecretMarker(map(node.$secret) ?? node.$secret);
20412
+ if (isRecord$1(node)) return Object.fromEntries(Object.entries(node).map(([k, v]) => [k, walk(v)]));
20413
+ return node;
20414
+ };
20415
+ return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, walk(v)]));
20416
+ }
20417
+ function isRecord$1(value) {
20418
+ return typeof value === "object" && value !== null && !Array.isArray(value);
19442
20419
  }
19443
20420
  //#endregion
19444
20421
  //#region src/builtins/device-manager/migrate-reload.ts
@@ -19487,6 +20464,274 @@ async function reloadMigratedDevices(pctx, targets) {
19487
20464
  }));
19488
20465
  }
19489
20466
  //#endregion
20467
+ //#region src/builtins/device-manager/room-actions.ts
20468
+ /**
20469
+ * Rooms and site zones as records with an id (D1089).
20470
+ *
20471
+ * The entity methods (`ensureRoom`, `listRooms`, `updateRoom`, `deleteRoom`) are
20472
+ * the model: a rename, a new icon or a new description is ONE write to ONE
20473
+ * `rooms` record, and no device is rewritten (a device meta carries only
20474
+ * `locationId`; its `location` name is derived at read). A delete clears the
20475
+ * references in one operation.
20476
+ *
20477
+ * Everything else here — `listLocations`, `addLocation`, `removeLocation`,
20478
+ * `renameLocation`, the icon / description maps, the site-zone methods and
20479
+ * `setLocationZone` — is a thin SHIM over those, answering the same shapes as
20480
+ * before so the admin UI and the viewer keep working until they move to the ids.
20481
+ * A shim is removed once nothing calls it (D1089).
20482
+ */
20483
+ /** Room record → the wire shape. */
20484
+ function toRoom(entity) {
20485
+ return entity;
20486
+ }
20487
+ function requireName(name, code, what) {
20488
+ const trimmed = name.trim();
20489
+ if (trimmed.length === 0) throw userError(code, void 0, `[device-manager] ${what}: name must be non-empty`);
20490
+ return trimmed;
20491
+ }
20492
+ /** Drop a field when the patch says `null`, keep it when absent, set it otherwise. */
20493
+ function applied(patch, current) {
20494
+ if (patch === void 0) return current;
20495
+ if (patch === null) return void 0;
20496
+ return patch;
20497
+ }
20498
+ function emitLocationChanged(pctx, deviceId, value) {
20499
+ pctx.host.ctx.eventBus.emit({
20500
+ id: randomUUID(),
20501
+ timestamp: /* @__PURE__ */ new Date(),
20502
+ source: {
20503
+ type: "device",
20504
+ id: deviceId
20505
+ },
20506
+ category: EventCategory$1.DeviceMetaChanged,
20507
+ data: {
20508
+ deviceId,
20509
+ field: "location",
20510
+ value
20511
+ }
20512
+ });
20513
+ }
20514
+ /** The ids of every device whose room is `roomId`. */
20515
+ async function devicesInRoom(pctx, roomId) {
20516
+ return (await pctx.metaStore.rows.listAll()).filter((row) => row.meta.locationId === roomId).map((row) => row.meta.id);
20517
+ }
20518
+ async function ensureRoom(pctx, input) {
20519
+ const name = requireName(input.name, "system.location-name-required", "ensureRoom");
20520
+ return toRoom(await pctx.rooms.rooms.ensure(name, {}));
20521
+ }
20522
+ async function listRooms(pctx) {
20523
+ return pctx.rooms.rooms.list().map(toRoom);
20524
+ }
20525
+ async function updateRoom(pctx, input) {
20526
+ const { id, patch } = input;
20527
+ const before = pctx.rooms.rooms.get(id);
20528
+ let updated;
20529
+ try {
20530
+ updated = await pctx.rooms.rooms.update(id, (current) => {
20531
+ return {
20532
+ name: patch.name ?? current.name,
20533
+ icon: applied(patch.icon, current.icon),
20534
+ description: applied(patch.description, current.description),
20535
+ zoneId: applied(patch.zoneId, current.zoneId),
20536
+ colour: applied(patch.colour, current.colour),
20537
+ order: applied(patch.order, current.order)
20538
+ };
20539
+ });
20540
+ } catch (err) {
20541
+ if (err instanceof EntityNotFoundError) throw userError("system.room-not-found", void 0, `[device-manager] room not found: ${id}`);
20542
+ if (err instanceof EntityNameTakenError) throw userError("system.room-name-taken", void 0, `[device-manager] ${err.message}`);
20543
+ throw err;
20544
+ }
20545
+ if (before !== null && before.name !== updated.name) for (const deviceId of await devicesInRoom(pctx, id)) emitLocationChanged(pctx, deviceId, updated.name);
20546
+ return toRoom(updated);
20547
+ }
20548
+ async function deleteRoom(pctx, input) {
20549
+ if (!await pctx.rooms.rooms.delete(input.id)) return { cleared: 0 };
20550
+ const cleared = await pctx.metaStore.withMetaWriteLock(async () => {
20551
+ const out = [];
20552
+ for (const row of await pctx.metaStore.rows.listAll()) {
20553
+ if (row.meta.locationId !== input.id) continue;
20554
+ await pctx.metaStore.rows.patch(row.meta.id, { locationId: null });
20555
+ out.push(row.meta.id);
20556
+ }
20557
+ return out;
20558
+ });
20559
+ for (const deviceId of cleared) emitLocationChanged(pctx, deviceId, null);
20560
+ return { cleared: cleared.length };
20561
+ }
20562
+ /**
20563
+ * The id a write names: `locationId` wins, else `location` (text) is resolved
20564
+ * through `ensureRoom`. `undefined` = the caller named neither, `null` = clear.
20565
+ */
20566
+ async function resolveRoomId(pctx, input) {
20567
+ if (input.locationId !== void 0) {
20568
+ if (input.locationId !== null && pctx.rooms.rooms.get(input.locationId) === null) throw userError("system.room-not-found", void 0, `[device-manager] room not found: ${input.locationId}`);
20569
+ return input.locationId;
20570
+ }
20571
+ if (input.location === void 0) return void 0;
20572
+ if (input.location === null || input.location.trim().length === 0) return null;
20573
+ return (await pctx.rooms.rooms.ensure(input.location.trim(), {})).id;
20574
+ }
20575
+ async function listLocations(pctx) {
20576
+ return pctx.rooms.rooms.list().map((room) => room.name).toSorted((a, b) => a.localeCompare(b, void 0, { sensitivity: "base" }));
20577
+ }
20578
+ async function addLocation(pctx, input) {
20579
+ const name = requireName(input.name, "system.location-name-required", "addLocation");
20580
+ await pctx.rooms.rooms.ensure(name, {});
20581
+ }
20582
+ async function removeLocation(pctx, input) {
20583
+ const room = pctx.rooms.rooms.findByName(input.name);
20584
+ if (room === null) return;
20585
+ if (input.cascade === true) {
20586
+ await deleteRoom(pctx, { id: room.id });
20587
+ return;
20588
+ }
20589
+ if ((await devicesInRoom(pctx, room.id)).length > 0) {
20590
+ await updateRoom(pctx, {
20591
+ id: room.id,
20592
+ patch: {
20593
+ icon: null,
20594
+ description: null,
20595
+ zoneId: null
20596
+ }
20597
+ });
20598
+ return;
20599
+ }
20600
+ await pctx.rooms.rooms.delete(room.id);
20601
+ }
20602
+ async function renameLocation(pctx, input) {
20603
+ const from = requireName(input.from, "system.location-name-required", "renameLocation");
20604
+ const to = requireName(input.to, "system.location-name-required", "renameLocation");
20605
+ const source = pctx.rooms.rooms.findByName(from);
20606
+ if (source === null) return { moved: 0 };
20607
+ const target = pctx.rooms.rooms.findByName(to);
20608
+ if (target === null || target.id === source.id) {
20609
+ await updateRoom(pctx, {
20610
+ id: source.id,
20611
+ patch: { name: to }
20612
+ });
20613
+ return { moved: (await devicesInRoom(pctx, source.id)).length };
20614
+ }
20615
+ const moved = await pctx.metaStore.withMetaWriteLock(async () => {
20616
+ const out = [];
20617
+ for (const row of await pctx.metaStore.rows.listAll()) {
20618
+ if (row.meta.locationId !== source.id) continue;
20619
+ await pctx.metaStore.rows.patch(row.meta.id, { locationId: target.id });
20620
+ out.push(row.meta.id);
20621
+ }
20622
+ return out;
20623
+ });
20624
+ await pctx.rooms.rooms.delete(source.id);
20625
+ for (const deviceId of moved) emitLocationChanged(pctx, deviceId, target.name);
20626
+ return { moved: moved.length };
20627
+ }
20628
+ async function listLocationIcons(pctx) {
20629
+ return pctx.rooms.rooms.list().flatMap((room) => room.icon === void 0 ? [] : [{
20630
+ locationKey: entityNameKey(room.name),
20631
+ icon: room.icon
20632
+ }]).toSorted((a, b) => a.locationKey.localeCompare(b.locationKey));
20633
+ }
20634
+ async function setLocationIcon(pctx, input) {
20635
+ const name = requireName(input.location, "system.location-required", "setLocationIcon");
20636
+ const existing = pctx.rooms.rooms.findByName(name);
20637
+ if (existing === null && input.icon === null) return;
20638
+ const room = existing ?? await pctx.rooms.rooms.ensure(name, {});
20639
+ const icon = input.icon;
20640
+ await updateRoom(pctx, {
20641
+ id: room.id,
20642
+ patch: { icon }
20643
+ });
20644
+ }
20645
+ async function listLocationDescriptions(pctx) {
20646
+ return pctx.rooms.rooms.list().flatMap((room) => room.description === void 0 ? [] : [{
20647
+ locationKey: entityNameKey(room.name),
20648
+ description: room.description
20649
+ }]).toSorted((a, b) => a.locationKey.localeCompare(b.locationKey));
20650
+ }
20651
+ async function setLocationDescription(pctx, input) {
20652
+ const name = requireName(input.location, "system.location-required", "setLocationDescription");
20653
+ const text = input.description === null ? "" : input.description.trim();
20654
+ const existing = pctx.rooms.rooms.findByName(name);
20655
+ if (existing === null && text.length === 0) return;
20656
+ await updateRoom(pctx, {
20657
+ id: (existing ?? await pctx.rooms.rooms.ensure(name, {})).id,
20658
+ patch: { description: text.length === 0 ? null : text }
20659
+ });
20660
+ }
20661
+ function zoneFolded(zone) {
20662
+ return entityNameKey(zone.name);
20663
+ }
20664
+ async function listSiteZones(pctx) {
20665
+ const rooms = pctx.rooms.rooms.list();
20666
+ return pctx.rooms.zones.list().map((zone) => ({
20667
+ zoneKey: zoneFolded(zone),
20668
+ label: zone.name,
20669
+ icon: zone.icon ?? null,
20670
+ locationKeys: rooms.filter((room) => room.zoneId === zone.id).map((room) => entityNameKey(room.name)).toSorted((a, b) => a.localeCompare(b))
20671
+ })).toSorted((a, b) => a.zoneKey.localeCompare(b.zoneKey));
20672
+ }
20673
+ async function setSiteZone(pctx, input) {
20674
+ const label = requireName(input.name, "system.site-zone-name-required", "setSiteZone");
20675
+ const zone = await pctx.rooms.zones.ensure(label, {});
20676
+ await pctx.rooms.zones.update(zone.id, (current) => {
20677
+ const next = { name: label };
20678
+ const icon = input.icon === void 0 ? current.icon : input.icon === null ? void 0 : input.icon;
20679
+ if (icon !== void 0) next.icon = icon;
20680
+ return next;
20681
+ });
20682
+ }
20683
+ /** Clear `zoneId` on every room that names `zoneId`; one record write per room. */
20684
+ async function detachRooms(pctx, zoneId, to) {
20685
+ for (const room of pctx.rooms.rooms.list()) {
20686
+ if (room.zoneId !== zoneId) continue;
20687
+ await updateRoom(pctx, {
20688
+ id: room.id,
20689
+ patch: { zoneId: to }
20690
+ });
20691
+ }
20692
+ }
20693
+ async function removeSiteZone(pctx, input) {
20694
+ const zone = pctx.rooms.zones.findByName(input.name);
20695
+ if (zone === null) return;
20696
+ await detachRooms(pctx, zone.id, null);
20697
+ await pctx.rooms.zones.delete(zone.id);
20698
+ }
20699
+ async function renameSiteZone(pctx, input) {
20700
+ const to = requireName(input.to, "system.site-zone-name-required", "renameSiteZone");
20701
+ const source = pctx.rooms.zones.findByName(input.from);
20702
+ if (source === null) return;
20703
+ const target = pctx.rooms.zones.findByName(to);
20704
+ if (target === null || target.id === source.id) {
20705
+ await pctx.rooms.zones.update(source.id, (current) => ({
20706
+ ...current,
20707
+ name: to
20708
+ }));
20709
+ return;
20710
+ }
20711
+ await detachRooms(pctx, source.id, target.id);
20712
+ await pctx.rooms.zones.delete(source.id);
20713
+ }
20714
+ async function setLocationZone(pctx, input) {
20715
+ const name = requireName(input.location, "system.location-required", "setLocationZone");
20716
+ if (input.zone === null) {
20717
+ const existing = pctx.rooms.rooms.findByName(name);
20718
+ if (existing === null || existing.zoneId === void 0) return;
20719
+ await updateRoom(pctx, {
20720
+ id: existing.id,
20721
+ patch: { zoneId: null }
20722
+ });
20723
+ return;
20724
+ }
20725
+ const zoneName = requireName(input.zone, "system.site-zone-name-required", "setLocationZone");
20726
+ const zone = await pctx.rooms.zones.ensure(zoneName, {});
20727
+ const room = await pctx.rooms.rooms.ensure(name, {});
20728
+ if (room.zoneId === zone.id) return;
20729
+ await updateRoom(pctx, {
20730
+ id: room.id,
20731
+ patch: { zoneId: zone.id }
20732
+ });
20733
+ }
20734
+ //#endregion
19490
20735
  //#region src/builtins/device-manager/device-meta-actions.ts
19491
20736
  /**
19492
20737
  * Device meta-mutation + persistence actions for the device-manager addon —
@@ -19562,6 +20807,7 @@ async function allocateDeviceId(pctx, input) {
19562
20807
  type: "generic",
19563
20808
  name: stableId,
19564
20809
  location: null,
20810
+ locationId: null,
19565
20811
  disabled: false,
19566
20812
  parentDeviceId: null,
19567
20813
  id
@@ -19656,7 +20902,16 @@ async function migrateDevice(pctx, input) {
19656
20902
  assertNoFieldClaims: async (a, b) => {
19657
20903
  try {
19658
20904
  await assertNoFieldClaims(pctx.settings, a, b);
20905
+ await assertNoCrossedSecretScopes(pctx.settings, a, b);
19659
20906
  } catch (err) {
20907
+ if (err instanceof SecretScopesCrossedError) for (const c of err.crossed) ctx.logger.warn("migrateDevice refused: secret scopes crossed", {
20908
+ tags: { deviceId: c.deviceId },
20909
+ meta: {
20910
+ sourceId: a,
20911
+ targetId: b,
20912
+ markers: c.markers
20913
+ }
20914
+ });
19660
20915
  if (err instanceof FieldClaimsBlockMigrationError) for (const blocked of err.blocked) ctx.logger.warn("migrateDevice refused: fields claimed by a customization", {
19661
20916
  tags: { deviceId: blocked.deviceId },
19662
20917
  meta: {
@@ -19669,7 +20924,8 @@ async function migrateDevice(pctx, input) {
19669
20924
  }
19670
20925
  },
19671
20926
  swapHardwareState: async (a, b) => {
19672
- const swapped = await swapHardwareState(pctx.settings, a, b);
20927
+ const forOwner = pctx.host.ctx.secrets?.forOwner;
20928
+ const swapped = await swapHardwareState(pctx.settings, a, b, forOwner === void 0 || forOwner === null ? void 0 : { forOwner });
19673
20929
  pctx.host.seedMirror(a, pctx.host.withResetSessionProbe(swapped.runtimeStateNowAtSource), "replace");
19674
20930
  pctx.host.seedMirror(b, pctx.host.withResetSessionProbe(swapped.runtimeStateNowAtTarget), "replace");
19675
20931
  ctx.logger.info("migration: hardware-scoped device state swapped", {
@@ -19680,9 +20936,11 @@ async function migrateDevice(pctx, input) {
19680
20936
  hardwareKeysToSource: swapped.hardwareKeysToSource,
19681
20937
  hardwareKeysToTarget: swapped.hardwareKeysToTarget,
19682
20938
  roleKeysKeptAtSource: swapped.roleKeysKeptAtSource,
19683
- roleKeysKeptAtTarget: swapped.roleKeysKeptAtTarget
20939
+ roleKeysKeptAtTarget: swapped.roleKeysKeptAtTarget,
20940
+ secretScopes: swapped.secretScopes
19684
20941
  }
19685
20942
  });
20943
+ return swapped.secretScopes;
19686
20944
  },
19687
20945
  forgetStreamState: async (deviceId) => {
19688
20946
  await ctx.api.streamBroker.forgetDeviceHardware.mutate({ deviceId });
@@ -19766,10 +21024,10 @@ async function registerDevice(pctx, input) {
19766
21024
  deviceType: type,
19767
21025
  features: settledFeatures
19768
21026
  });
19769
- const priorLocation = existingMeta?.location ?? null;
21027
+ const priorLocationId = existingMeta?.locationId ?? null;
19770
21028
  const resolvedParentId = parentDeviceId ?? null;
19771
21029
  const parentChanged = existingMeta !== void 0 && (existingMeta.parentDeviceId ?? null) !== resolvedParentId;
19772
- const inherited = priorLocation === null && resolvedParentId !== null && (isFirst || parentChanged) ? await resolveInheritedLocation(pctx.metaStore.rows, resolvedParentId) : null;
21030
+ const inherited = priorLocationId === null && resolvedParentId !== null && (isFirst || parentChanged) ? await resolveInheritedLocation(pctx.metaStore.rows, resolvedParentId) : null;
19773
21031
  await pctx.metaStore.rows.upsertRegistration({
19774
21032
  deviceId: id,
19775
21033
  addonId,
@@ -19777,7 +21035,7 @@ async function registerDevice(pctx, input) {
19777
21035
  type,
19778
21036
  name: resolvedName,
19779
21037
  userNamed: wasUserNamed,
19780
- location: priorLocation ?? inherited,
21038
+ locationId: priorLocationId ?? inherited?.locationId ?? null,
19781
21039
  disabled: existingMeta?.disabled ?? false,
19782
21040
  parentDeviceId: resolvedParentId,
19783
21041
  registered: true,
@@ -19793,7 +21051,7 @@ async function registerDevice(pctx, input) {
19793
21051
  if (inherited !== null) for (const descendant of await collectDescendants(pctx.metaStore, id)) {
19794
21052
  if (descendant.location !== null) continue;
19795
21053
  try {
19796
- await pctx.metaStore.rows.patch(descendant.id, { location: inherited });
21054
+ await pctx.metaStore.rows.patch(descendant.id, { locationId: inherited.locationId });
19797
21055
  descendantsFilled.push(descendant.id);
19798
21056
  } catch (err) {
19799
21057
  descendantsFailed.push({
@@ -19807,7 +21065,7 @@ async function registerDevice(pctx, input) {
19807
21065
  storedFeatures: settledFeatures,
19808
21066
  exportFingerprint: fingerprint,
19809
21067
  fingerprintChanged: existingMeta?.exportFingerprint !== fingerprint,
19810
- inheritedLocation: inherited,
21068
+ inheritedLocation: inherited?.location ?? null,
19811
21069
  inheritedDescendantIds: descendantsFilled,
19812
21070
  inheritFailed: descendantsFailed,
19813
21071
  filledRole: roleToFill
@@ -20073,8 +21331,38 @@ function removalSteps(pctx, deviceId, providerAddonId, deletedAt) {
20073
21331
  })
20074
21332
  ];
20075
21333
  }
21334
+ /**
21335
+ * The rows that belong to `deviceId` and cannot outlive it: its accessory
21336
+ * children (`parentDeviceId === id`). A row that merely LINKS to it
21337
+ * (`linkDeviceId`: an operator-picked link, or an entity of another integration
21338
+ * adopted under its own container) is a device of its own and stays.
21339
+ */
21340
+ async function ownedRowIds(pctx, deviceId) {
21341
+ return (await pctx.metaStore.rows.listByParent(deviceId)).map((row) => row.meta.id).filter((id) => id !== deviceId);
21342
+ }
21343
+ /**
21344
+ * Removing a device removes what it owns (an accessory child never outlives its
21345
+ * parent: a Reolink siren row survived its camera with a dangling
21346
+ * `parentDeviceId`). Each child goes through the same tombstoned removal, so
21347
+ * its data stores, its removal hooks and its identity fence are the parent's.
21348
+ */
20076
21349
  async function removeDevice(pctx, input) {
20077
- const { deviceId } = input;
21350
+ await removeDeviceTree(pctx, input.deviceId, /* @__PURE__ */ new Set());
21351
+ }
21352
+ async function removeDeviceTree(pctx, deviceId, seen) {
21353
+ if (seen.has(deviceId)) return;
21354
+ seen.add(deviceId);
21355
+ const ownedIds = await ownedRowIds(pctx, deviceId);
21356
+ await removeOneDevice(pctx, deviceId);
21357
+ for (const childId of ownedIds) {
21358
+ pctx.host.ctx.logger.info("removed device: cascading to an owned child", {
21359
+ tags: { deviceId: childId },
21360
+ meta: { parentDeviceId: deviceId }
21361
+ });
21362
+ await removeDeviceTree(pctx, childId, seen);
21363
+ }
21364
+ }
21365
+ async function removeOneDevice(pctx, deviceId) {
20078
21366
  const persisted = await pctx.metaStore.resolvePersistedById(deviceId);
20079
21367
  if (!persisted) return;
20080
21368
  const { addonId, stableId, meta: persistedMeta } = persisted;
@@ -20341,15 +21629,18 @@ async function collectDescendants(metaStore, rootId) {
20341
21629
  * consumers (the linked-devices picker, which suggests by location) see exactly what landed.
20342
21630
  */
20343
21631
  async function setLocation(pctx, input) {
20344
- const { deviceId, location } = input;
21632
+ const { deviceId } = input;
21633
+ const locationId = await resolveRoomId(pctx, input);
21634
+ if (locationId === void 0) throw new Error("[device-manager] setLocation: name `location` or `locationId`");
21635
+ const location = pctx.rooms.nameOf(locationId);
20345
21636
  const cascaded = [];
20346
21637
  const failed = [];
20347
21638
  await pctx.metaStore.withMetaWriteLock(async () => {
20348
21639
  if (!await pctx.metaStore.resolvePersistedById(deviceId)) throw new Error(`[device-manager] setLocation: unknown device id=${deviceId}`);
20349
- await pctx.metaStore.rows.patch(deviceId, { location });
21640
+ await pctx.metaStore.rows.patch(deviceId, { locationId });
20350
21641
  const descendants = await collectDescendants(pctx.metaStore, deviceId);
20351
21642
  for (const descendant of descendants) try {
20352
- await pctx.metaStore.rows.patch(descendant.id, { location });
21643
+ await pctx.metaStore.rows.patch(descendant.id, { locationId });
20353
21644
  cascaded.push(descendant.id);
20354
21645
  } catch (err) {
20355
21646
  failed.push({
@@ -20403,10 +21694,24 @@ async function setLocation(pctx, input) {
20403
21694
  }
20404
21695
  });
20405
21696
  }
20406
- /** The tags a write stores: normalised, `null` (the column's absent form) when none are left. */
20407
- function storedTags(tags) {
20408
- const normalized = normalizeTags(tags);
20409
- return normalized.length === 0 ? null : normalized;
21697
+ /** The current names of tag ids; an id with no tag record is left out, never shown raw. */
21698
+ function tagNamesOf(pctx, ids) {
21699
+ if (ids === null) return null;
21700
+ return ids.flatMap((id) => {
21701
+ const name = pctx.tagNameOf(id);
21702
+ return name === null ? [] : [name];
21703
+ });
21704
+ }
21705
+ /**
21706
+ * The tag ids a write names: `tagIds` wins, else `tags` (text) is resolved through
21707
+ * `ensureTag` (D1089, accepted for one release). `[]` stays `[]`: the operator cleared
21708
+ * them, and `null` would let the kept names of an older row read back as tags again.
21709
+ */
21710
+ async function resolveTagIds(pctx, input) {
21711
+ if (input.tagIds !== void 0) return [...new Set(input.tagIds)];
21712
+ const names = normalizeTags(input.tags ?? []);
21713
+ if (names.length === 0) return [];
21714
+ return [...new Set(await pctx.ensureTagIds(names))];
20410
21715
  }
20411
21716
  /**
20412
21717
  * Replace the operator tags of one device (D1054). Normalised on write; `[]`
@@ -20415,10 +21720,11 @@ function storedTags(tags) {
20415
21720
  */
20416
21721
  async function setTags(pctx, input) {
20417
21722
  const { deviceId } = input;
20418
- const tags = storedTags(input.tags);
21723
+ const tagIds = await resolveTagIds(pctx, input);
21724
+ const tags = tagNamesOf(pctx, tagIds);
20419
21725
  await pctx.metaStore.withMetaWriteLock(async () => {
20420
21726
  if (!await pctx.metaStore.resolvePersistedById(deviceId)) throw new Error(`[device-manager] setTags: unknown device id=${deviceId}`);
20421
- await pctx.metaStore.rows.patch(deviceId, { tags });
21727
+ await pctx.metaStore.rows.patch(deviceId, { tagIds });
20422
21728
  });
20423
21729
  pctx.host.ctx.eventBus.emit({
20424
21730
  id: randomUUID(),
@@ -20710,12 +22016,14 @@ async function setRoleDisplayDefaults(pctx, input) {
20710
22016
  */
20711
22017
  async function applyInitialMeta(pctx, input) {
20712
22018
  const { deviceId, name, location, tags, type, integrationId, linkDeviceId, role } = input;
22019
+ const locationId = location === void 0 && input.locationId === void 0 ? void 0 : await resolveRoomId(pctx, input);
22020
+ const tagIds = tags === void 0 && input.tagIds === void 0 ? void 0 : await resolveTagIds(pctx, input);
20713
22021
  await pctx.metaStore.withMetaWriteLock(async () => {
20714
22022
  if (!await pctx.metaStore.resolvePersistedById(deviceId)) throw new Error(`[device-manager] applyInitialMeta: unknown device id=${deviceId}`);
20715
22023
  await pctx.metaStore.rows.patch(deviceId, {
20716
22024
  ...name !== void 0 ? { name } : {},
20717
- ...location !== void 0 ? { location } : {},
20718
- ...tags !== void 0 ? { tags: storedTags(tags) } : {},
22025
+ ...locationId !== void 0 ? { locationId } : {},
22026
+ ...tagIds !== void 0 ? { tagIds } : {},
20719
22027
  ...type !== void 0 ? { type } : {},
20720
22028
  ...integrationId !== void 0 ? { integrationId } : {},
20721
22029
  ...linkDeviceId !== void 0 ? { linkDeviceId } : {},
@@ -20739,8 +22047,8 @@ async function applyInitialMeta(pctx, input) {
20739
22047
  });
20740
22048
  };
20741
22049
  if (name !== void 0) emitMetaChanged("name", name);
20742
- if (location !== void 0) emitMetaChanged("location", location);
20743
- if (tags !== void 0) emitMetaChanged("tags", storedTags(tags) ?? []);
22050
+ if (locationId !== void 0) emitMetaChanged("location", pctx.rooms.nameOf(locationId));
22051
+ if (tagIds !== void 0) emitMetaChanged("tags", tagNamesOf(pctx, tagIds) ?? []);
20744
22052
  if (type !== void 0) emitMetaChanged("type", type);
20745
22053
  if (integrationId !== void 0) emitMetaChanged("integrationId", integrationId);
20746
22054
  if (linkDeviceId !== void 0) emitMetaChanged("linkDeviceId", linkDeviceId);
@@ -20852,480 +22160,109 @@ async function loadRuntimeState(pctx, input) {
20852
22160
  return splitRuntimeBlob(pctx.host.seedMirrorFromRow(deviceId, data, pctx.settings)).native;
20853
22161
  }
20854
22162
  /**
20855
- * Union of (1) operator-curated location registry and (2) labels
20856
- * currently in use on persisted devices. Case-insensitive
20857
- * dedupe (preserves the first-seen casing). Sorted
20858
- * case-insensitively for stable UI. Drives the Device Info
20859
- * location autocomplete.
20860
- */
20861
- async function listLocations(pctx) {
20862
- const locations = (await pctx.metaStore.readStore()).locations ?? [];
20863
- const seen = /* @__PURE__ */ new Map();
20864
- const consider = (raw) => {
20865
- if (typeof raw !== "string") return;
20866
- const trimmed = raw.trim();
20867
- if (trimmed.length === 0) return;
20868
- const key = trimmed.toLowerCase();
20869
- if (!seen.has(key)) seen.set(key, trimmed);
20870
- };
20871
- for (const label of locations) consider(label);
20872
- for (const row of await pctx.metaStore.rows.listAll()) consider(row.meta.location);
20873
- return [...seen.values()].toSorted((a, b) => a.localeCompare(b, void 0, { sensitivity: "base" }));
20874
- }
20875
- /**
20876
- * Add a label to the curated location registry. Idempotent:
20877
- * existing entries (case-insensitive match) are silently kept.
20878
- * Empty / whitespace-only inputs throw — operators must supply a
20879
- * meaningful label.
20880
- */
20881
- async function addLocation(pctx, input) {
20882
- const trimmed = input.name.trim();
20883
- if (trimmed.length === 0) throw userError("system.location-name-required", void 0, "[device-manager] addLocation: name must be non-empty");
20884
- await pctx.bindingsDeps.withAddonStoreWriteLock(async () => {
20885
- const current = (await pctx.metaStore.readStore()).locations ?? [];
20886
- if (current.some((l) => l.toLowerCase() === trimmed.toLowerCase())) return;
20887
- await pctx.settings.writeAddonStore({ locations: [...current, trimmed] });
20888
- });
20889
- }
20890
- /**
20891
- * Every location that carries an icon, as `(locationKey, icon)` pairs.
20892
- *
20893
- * ADDITIVE beside `listLocations`, which still answers `string[]` — the
20894
- * autocomplete, the HA adoption import and the recorder all read a list of
20895
- * LABELS and a shape change there would break every one of them. A surface
20896
- * that wants icons asks for them and joins on `locationIconKey`.
20897
- *
20898
- * Returns only what was actually stored. A location with no assignment is
20899
- * ABSENT, never `map-pin`: the fallback belongs to the renderer
20900
- * (`resolveIconKey`), and folding it in here would make "the operator
20901
- * picked the pin" indistinguishable from "the operator picked nothing" —
20902
- * which is the difference an icon picker has to draw.
20903
- */
20904
- async function listLocationIcons(pctx) {
20905
- const icons = (await pctx.metaStore.readStore()).locationIcons ?? {};
20906
- return Object.entries(icons).map(([locationKey, icon]) => ({
20907
- locationKey,
20908
- icon
20909
- })).toSorted((a, b) => a.locationKey.localeCompare(b.locationKey));
20910
- }
20911
- /**
20912
- * Set (or clear) the icon of a location label.
20913
- *
20914
- * Keyed on `locationIconKey` — trimmed + lower-cased, the equality the
20915
- * registry matches on everywhere — so a case-only rename keeps the icon and
20916
- * two spellings of one room can never carry two different icons.
20917
- *
20918
- * The label need NOT be registered: `setLocation` accepts a free-form string
20919
- * and `listLocations` folds in whatever devices carry, so requiring
20920
- * registration here would leave exactly the ad-hoc rooms unable to have an
20921
- * icon. An empty label throws — there is no room to name.
20922
- *
20923
- * Same read-modify-write and same lock as `addLocation`: the map is one key of
20924
- * the addon store, and `writeAddonStore` re-inserts the whole key range, so an
20925
- * unordered write carries a stale copy of every other key.
22163
+ * `deviceManager.repairMigrationSecrets` — the live repair for a pair a
22164
+ * migration left with crossed keychain scopes (see `repairCrossedSecretScopes`).
22165
+ * Under the meta write lock the migration itself ran under: a config write
22166
+ * racing it would read the half this repair is moving. The running devices
22167
+ * keep their loaded config until the next reload.
20926
22168
  */
20927
- async function setLocationIcon(pctx, input) {
20928
- const trimmed = input.location.trim();
20929
- if (trimmed.length === 0) throw userError("system.location-required", void 0, "[device-manager] setLocationIcon: location must be non-empty");
20930
- const key = locationIconKey(trimmed);
20931
- await pctx.bindingsDeps.withAddonStoreWriteLock(async () => {
20932
- const icons = (await pctx.metaStore.readStore()).locationIcons ?? {};
20933
- if (input.icon === null) {
20934
- if (!(key in icons)) return;
20935
- const { [key]: _cleared, ...kept } = icons;
20936
- await pctx.settings.writeAddonStore({ locationIcons: kept });
20937
- return;
20938
- }
20939
- if (icons[key] === input.icon) return;
20940
- await pctx.settings.writeAddonStore({ locationIcons: {
20941
- ...icons,
20942
- [key]: input.icon
20943
- } });
20944
- });
20945
- }
20946
- /**
20947
- * Every location that carries a description, sorted by key.
20948
- *
20949
- * Only what was WRITTEN — a location with no description is absent, and the
20950
- * digest then tells the model the location name alone, exactly as it did
20951
- * before descriptions existed.
20952
- */
20953
- async function listLocationDescriptions(pctx) {
20954
- const descriptions = (await pctx.metaStore.readStore()).locationDescriptions ?? {};
20955
- return Object.entries(descriptions).map(([locationKey, description]) => ({
20956
- locationKey,
20957
- description
20958
- })).toSorted((a, b) => a.locationKey.localeCompare(b.locationKey));
20959
- }
20960
- /**
20961
- * Set (or clear) a location's description.
20962
- *
20963
- * A BLANK description clears, exactly as `null` does: an empty line handed to
20964
- * a vision model costs attention and says nothing, so the two must not be
20965
- * different states. The label is folded with `locationIconKey` — the same key
20966
- * the icon uses, which is the whole point of this living here.
20967
- *
20968
- * Same read-modify-write and same lock as `setLocationIcon`; `writeAddonStore`
20969
- * re-inserts the whole key range, so an unordered write carries a stale copy
20970
- * of every other key.
20971
- */
20972
- async function setLocationDescription(pctx, input) {
20973
- const trimmed = input.location.trim();
20974
- if (trimmed.length === 0) throw new Error("[device-manager] setLocationDescription: location must be non-empty");
20975
- const key = locationIconKey(trimmed);
20976
- const text = input.description === null ? "" : input.description.trim();
20977
- await pctx.bindingsDeps.withAddonStoreWriteLock(async () => {
20978
- const descriptions = (await pctx.metaStore.readStore()).locationDescriptions ?? {};
20979
- if (text.length === 0) {
20980
- if (!(key in descriptions)) return;
20981
- const { [key]: _cleared, ...kept } = descriptions;
20982
- await pctx.settings.writeAddonStore({ locationDescriptions: kept });
20983
- return;
22169
+ async function repairMigrationSecrets(pctx, input) {
22170
+ const { deviceA, deviceB, apply } = input;
22171
+ const ctx = pctx.host.ctx;
22172
+ const forOwner = ctx.secrets?.forOwner ?? null;
22173
+ const report = await pctx.metaStore.withMetaWriteLock(() => repairCrossedSecretScopes(pctx.settings, forOwner === null ? void 0 : { forOwner }, deviceA, deviceB, apply));
22174
+ for (const deviceId of [deviceA, deviceB]) ctx.logger.info("repairMigrationSecrets", {
22175
+ tags: { deviceId },
22176
+ meta: {
22177
+ deviceA,
22178
+ deviceB,
22179
+ apply,
22180
+ outcome: report.outcome
20984
22181
  }
20985
- if (descriptions[key] === text) return;
20986
- await pctx.settings.writeAddonStore({ locationDescriptions: {
20987
- ...descriptions,
20988
- [key]: text
20989
- } });
20990
- });
20991
- }
20992
- /**
20993
- * Every site zone, with its rooms, sorted by key.
20994
- *
20995
- * Membership is inverted HERE rather than stored both ways: the store keeps
20996
- * `location → zone`, which is what makes "one zone per room" structural, and a
20997
- * second copy keyed the other way is a second thing that can disagree with the
20998
- * first.
20999
- */
21000
- async function listSiteZones(pctx) {
21001
- const store = await pctx.metaStore.readStore();
21002
- const zones = store.siteZones ?? {};
21003
- const membership = store.locationZones ?? {};
21004
- const rooms = /* @__PURE__ */ new Map();
21005
- for (const [locationKey, zoneKey] of Object.entries(membership)) {
21006
- const list = rooms.get(zoneKey);
21007
- if (list === void 0) rooms.set(zoneKey, [locationKey]);
21008
- else list.push(locationKey);
21009
- }
21010
- return Object.entries(zones).map(([zoneKey, record]) => ({
21011
- zoneKey,
21012
- label: record.label,
21013
- icon: record.icon ?? null,
21014
- locationKeys: (rooms.get(zoneKey) ?? []).toSorted((a, b) => a.localeCompare(b))
21015
- })).toSorted((a, b) => a.zoneKey.localeCompare(b.zoneKey));
21016
- }
21017
- /**
21018
- * Create a zone, or set the icon of one that already exists.
21019
- *
21020
- * `icon: null` clears the icon and KEEPS the zone. Conflating the two would
21021
- * make a mis-click on "no icon" delete every room's membership — the icon is a
21022
- * decoration and the grouping is the data.
21023
- *
21024
- * `icon` OMITTED leaves whatever icon is there: creating a zone from a screen
21025
- * with no picker must not silently clear the glyph a previous screen set.
21026
- */
21027
- async function setSiteZone(pctx, input) {
21028
- const label = input.name.trim();
21029
- if (label.length === 0) throw userError("system.site-zone-name-required", void 0, "[device-manager] setSiteZone: name must be non-empty");
21030
- const key = siteZoneKey(label);
21031
- await pctx.bindingsDeps.withAddonStoreWriteLock(async () => {
21032
- const zones = (await pctx.metaStore.readStore()).siteZones ?? {};
21033
- const existing = zones[key];
21034
- const icon = input.icon === void 0 ? existing?.icon : input.icon === null ? void 0 : input.icon;
21035
- const next = icon === void 0 ? { label } : {
21036
- label,
21037
- icon
21038
- };
21039
- if (existing?.label === next.label && existing.icon === next.icon) return;
21040
- await pctx.settings.writeAddonStore({ siteZones: {
21041
- ...zones,
21042
- [key]: next
21043
- } });
21044
- });
21045
- }
21046
- /**
21047
- * Delete a zone. Its LOCATIONS survive, unattached.
21048
- *
21049
- * Deleting a grouping must never delete what was grouped — the rooms exist
21050
- * independently and the devices in them were never touched to begin with.
21051
- */
21052
- async function removeSiteZone(pctx, input) {
21053
- const key = siteZoneKey(input.name);
21054
- await pctx.bindingsDeps.withAddonStoreWriteLock(async () => {
21055
- const store = await pctx.metaStore.readStore();
21056
- const zones = store.siteZones ?? {};
21057
- const membership = store.locationZones ?? {};
21058
- const hadZone = key in zones;
21059
- const orphaned = Object.entries(membership).filter(([, zoneKey]) => zoneKey === key);
21060
- if (!hadZone && orphaned.length === 0) return;
21061
- const { [key]: _dropped, ...keptZones } = zones;
21062
- const keptMembership = Object.fromEntries(Object.entries(membership).filter(([, zoneKey]) => zoneKey !== key));
21063
- await pctx.settings.writeAddonStore({
21064
- ...hadZone ? { siteZones: keptZones } : {},
21065
- ...orphaned.length > 0 ? { locationZones: keptMembership } : {}
21066
- });
21067
- });
21068
- }
21069
- /**
21070
- * Rename a zone, carrying its icon AND every room in it.
21071
- *
21072
- * It exists so that renaming is not delete-then-recreate, which drops both.
21073
- * A rename onto an existing zone MERGES: the target keeps its own icon and the
21074
- * rooms are unioned, the same rule `renameLocation` follows.
21075
- */
21076
- async function renameSiteZone(pctx, input) {
21077
- const toLabel = input.to.trim();
21078
- if (toLabel.length === 0) throw new Error("[device-manager] renameSiteZone: target name must be non-empty");
21079
- const fromKey = siteZoneKey(input.from);
21080
- const toKey = siteZoneKey(toLabel);
21081
- await pctx.bindingsDeps.withAddonStoreWriteLock(async () => {
21082
- const store = await pctx.metaStore.readStore();
21083
- const zones = store.siteZones ?? {};
21084
- const moved = zones[fromKey];
21085
- if (moved === void 0) return;
21086
- const { [fromKey]: _dropped, ...rest } = zones;
21087
- const target = rest[toKey];
21088
- const nextZones = {
21089
- ...rest,
21090
- [toKey]: target ?? (moved.icon === void 0 ? { label: toLabel } : {
21091
- label: toLabel,
21092
- icon: moved.icon
21093
- })
21094
- };
21095
- const membership = store.locationZones ?? {};
21096
- const nextMembership = Object.fromEntries(Object.entries(membership).map(([locationKey, zoneKey]) => [locationKey, zoneKey === fromKey ? toKey : zoneKey]));
21097
- await pctx.settings.writeAddonStore({
21098
- siteZones: nextZones,
21099
- locationZones: nextMembership
21100
- });
21101
22182
  });
22183
+ return report;
21102
22184
  }
22185
+ //#endregion
22186
+ //#region src/builtins/device-manager/room-store.ts
21103
22187
  /**
21104
- * Put a location in a zone, or take it out with `zone: null`.
22188
+ * The rooms and site zones of the property, as records with an id (D1089).
21105
22189
  *
21106
- * ONE slot per location, so a second call moves the room rather than listing it
21107
- * twice. The zone is created if it does not exist — a screen that assigns
21108
- * before creating is a normal order, and refusing it would be the only place in
21109
- * this registry that demands registration first.
22190
+ * `rooms` and `zones` are record kinds the device manager owns; a device meta
22191
+ * carries `locationId`, a room carries `zoneId`. The store keeps both in memory
22192
+ * once read — a device read resolves a room name through {@link RoomStore.nameOf}
22193
+ * without a query, and an unknown id reads as unset.
21110
22194
  */
21111
- async function setLocationZone(pctx, input) {
21112
- const location = input.location.trim();
21113
- if (location.length === 0) throw new Error("[device-manager] setLocationZone: location must be non-empty");
21114
- const locationKey = locationIconKey(location);
21115
- const label = input.zone === null ? null : input.zone.trim();
21116
- if (label !== null && label.length === 0) throw new Error("[device-manager] setLocationZone: zone must be non-empty or null");
21117
- await pctx.bindingsDeps.withAddonStoreWriteLock(async () => {
21118
- const store = await pctx.metaStore.readStore();
21119
- const membership = store.locationZones ?? {};
21120
- if (label === null) {
21121
- if (!(locationKey in membership)) return;
21122
- const { [locationKey]: _cleared, ...kept } = membership;
21123
- await pctx.settings.writeAddonStore({ locationZones: kept });
21124
- return;
21125
- }
21126
- const zoneKey = siteZoneKey(label);
21127
- const zones = store.siteZones ?? {};
21128
- const needsZone = !(zoneKey in zones);
21129
- if (membership[locationKey] === zoneKey && !needsZone) return;
21130
- await pctx.settings.writeAddonStore({
21131
- ...needsZone ? { siteZones: {
21132
- ...zones,
21133
- [zoneKey]: { label }
21134
- } } : {},
21135
- locationZones: {
21136
- ...membership,
21137
- [locationKey]: zoneKey
22195
+ var RoomStore = class RoomStore {
22196
+ rooms;
22197
+ zones;
22198
+ constructor(rooms, zones) {
22199
+ this.rooms = rooms;
22200
+ this.zones = zones;
22201
+ }
22202
+ static of(records) {
22203
+ return new RoomStore(new NamedEntityStore("room", records.kind(deviceManagerRecordKinds.rooms), (body) => RoomBodySchema.parse(body)), new NamedEntityStore("zone", records.kind(deviceManagerRecordKinds.zones), (body) => ZoneBodySchema.parse(body)));
22204
+ }
22205
+ async load() {
22206
+ await this.rooms.load();
22207
+ await this.zones.load();
22208
+ }
22209
+ /** The current name of room `id`; `null` when unset or unknown. */
22210
+ nameOf(id) {
22211
+ return this.rooms.nameOf(id);
22212
+ }
22213
+ };
22214
+ var TagNames = class {
22215
+ source;
22216
+ logger;
22217
+ now;
22218
+ names = /* @__PURE__ */ new Map();
22219
+ refreshedAt = 0;
22220
+ inFlight = null;
22221
+ constructor(source, logger, now = Date.now) {
22222
+ this.source = source;
22223
+ this.logger = logger;
22224
+ this.now = now;
22225
+ }
22226
+ nameOf(id) {
22227
+ return this.names.get(id) ?? null;
22228
+ }
22229
+ /** Revalidate when older than the window. A failed read keeps the last answer. */
22230
+ async fresh() {
22231
+ if (this.source === null) return;
22232
+ if (this.now() - this.refreshedAt < 5e3) return;
22233
+ await this.refresh();
22234
+ }
22235
+ async refresh() {
22236
+ const source = this.source;
22237
+ if (source === null) return;
22238
+ if (this.inFlight !== null) return this.inFlight;
22239
+ const run = (async () => {
22240
+ try {
22241
+ const tags = await source.list();
22242
+ this.names = new Map(tags.map((tag) => [tag.id, tag.name]));
22243
+ this.refreshedAt = this.now();
22244
+ } catch (err) {
22245
+ this.logger.warn("tag names not refreshed — keeping the last answer", { meta: { error: errMsg$1(err) } });
22246
+ } finally {
22247
+ this.inFlight = null;
21138
22248
  }
21139
- });
21140
- });
21141
- }
21142
- /**
21143
- * Move a location's zone membership from one key to another, for
21144
- * `renameLocation`. Same shape as the icon and description movers.
21145
- */
21146
- function renameLocationZone(membership, fromKey, toKey) {
21147
- const moved = membership[fromKey];
21148
- if (moved === void 0) return null;
21149
- if (fromKey === toKey) return null;
21150
- const { [fromKey]: _dropped, ...rest } = membership;
21151
- return toKey in rest ? rest : {
21152
- ...rest,
21153
- [toKey]: moved
21154
- };
21155
- }
21156
- /**
21157
- * Move a location's description from one key to another, for `renameLocation`.
21158
- *
21159
- * Identical rule to {@link renameLocationIcon}, deliberately: a merge keeps the
21160
- * TARGET's description, because renaming "Sala" into "Hall" moves devices
21161
- * into Hall and does not re-describe it. Split from the icon mover only
21162
- * because the value types differ; if one ever changes, the other must.
21163
- */
21164
- function renameLocationDescription(descriptions, fromKey, toKey) {
21165
- const moved = descriptions[fromKey];
21166
- if (moved === void 0) return null;
21167
- if (fromKey === toKey) return null;
21168
- const { [fromKey]: _dropped, ...rest } = descriptions;
21169
- return toKey in rest ? rest : {
21170
- ...rest,
21171
- [toKey]: moved
21172
- };
21173
- }
21174
- /**
21175
- * Move a location's icon from one key to another, for `renameLocation`.
21176
- *
21177
- * Returns `null` when NOTHING changes, so the caller can leave the key out of
21178
- * its `writeAddonStore` patch instead of re-writing an identical map.
21179
- *
21180
- * A rename onto a room that already has an icon is a MERGE, and the surviving
21181
- * room keeps its own: the operator renaming "Sala" into "Hall" is moving
21182
- * devices into Hall, not restyling it. The source key is dropped either way.
21183
- * Pure — builds a new record, mutates nothing.
21184
- */
21185
- function renameLocationIcon(icons, fromKey, toKey) {
21186
- const moved = icons[fromKey];
21187
- if (moved === void 0) return null;
21188
- if (fromKey === toKey) return null;
21189
- const { [fromKey]: _dropped, ...rest } = icons;
21190
- return toKey in rest ? rest : {
21191
- ...rest,
21192
- [toKey]: moved
21193
- };
21194
- }
21195
- /**
21196
- * Remove a label from the curated registry. Match is
21197
- * case-insensitive. Devices that still reference this label keep
21198
- * their `meta.location` value (the registry is a suggestion
21199
- * list, not a foreign key) — pass `cascade: true` to also clear
21200
- * `setLocation` on every device that referenced this exact
21201
- * label. Cascade only matches case-insensitively + trimmed, same
21202
- * as the registry equality check.
21203
- */
21204
- /**
21205
- * Rename a room in ONE server operation: the registry label in place, then
21206
- * every device that carried it.
21207
- *
21208
- * The lock order is the one `removeLocation` documents and must not be
21209
- * "simplified": the registry edit takes the addon-store lock and RELEASES it
21210
- * before the cascade takes the meta lock. Holding both, in that order, is the
21211
- * reverse of `allocateNextDeviceId`'s meta ⊃ addon-store nesting — the pair
21212
- * that deadlocks.
21213
- *
21214
- * Validation happens BEFORE either lock. A rename that throws halfway is the
21215
- * exact failure this function exists to remove, so an empty target must be
21216
- * refused while nothing has been written yet.
21217
- */
21218
- async function renameLocation(pctx, input) {
21219
- const from = input.from.trim();
21220
- const to = input.to.trim();
21221
- if (from.length === 0) throw new Error("[device-manager] renameLocation: `from` must be non-empty");
21222
- if (to.length === 0) throw new Error("[device-manager] renameLocation: `to` must be non-empty");
21223
- const fromKey = from.toLowerCase();
21224
- const toKey = to.toLowerCase();
21225
- await pctx.bindingsDeps.withAddonStoreWriteLock(async () => {
21226
- const store = await pctx.metaStore.readStore();
21227
- const current = store.locations ?? [];
21228
- const registered = current.some((l) => l.trim().toLowerCase() === fromKey);
21229
- const movedIcons = renameLocationIcon(store.locationIcons ?? {}, fromKey, toKey);
21230
- const movedDescriptions = renameLocationDescription(store.locationDescriptions ?? {}, fromKey, toKey);
21231
- const movedZones = renameLocationZone(store.locationZones ?? {}, fromKey, toKey);
21232
- if (!registered && movedIcons === null && movedDescriptions === null && movedZones === null) return;
21233
- const kept = current.filter((l) => {
21234
- const key = l.trim().toLowerCase();
21235
- return key !== fromKey && key !== toKey;
21236
- });
21237
- await pctx.settings.writeAddonStore({
21238
- ...registered ? { locations: [...kept, to] } : {},
21239
- ...movedIcons !== null ? { locationIcons: movedIcons } : {},
21240
- ...movedDescriptions !== null ? { locationDescriptions: movedDescriptions } : {},
21241
- ...movedZones !== null ? { locationZones: movedZones } : {}
21242
- });
21243
- });
21244
- const moved = await pctx.metaStore.withMetaWriteLock(async () => {
21245
- const out = [];
21246
- for (const row of await pctx.metaStore.rows.listAll()) {
21247
- const location = row.meta.location;
21248
- if (typeof location !== "string") continue;
21249
- if (location.trim().toLowerCase() !== fromKey) continue;
21250
- await pctx.metaStore.rows.patch(row.meta.id, { location: to });
21251
- out.push(row.meta.id);
21252
- }
21253
- return out;
21254
- });
21255
- for (const deviceId of moved) pctx.host.ctx.eventBus.emit({
21256
- id: randomUUID(),
21257
- timestamp: /* @__PURE__ */ new Date(),
21258
- source: {
21259
- type: "device",
21260
- id: deviceId
21261
- },
21262
- category: EventCategory$1.DeviceMetaChanged,
21263
- data: {
21264
- deviceId,
21265
- field: "location",
21266
- value: to
21267
- }
21268
- });
21269
- pctx.host.ctx.logger.info("renameLocation: room renamed", { meta: {
21270
- from,
21271
- to,
21272
- moved: moved.length
21273
- } });
21274
- return { moved: moved.length };
21275
- }
21276
- async function removeLocation(pctx, input) {
21277
- const trimmed = input.name.trim();
21278
- if (trimmed.length === 0) return;
21279
- await pctx.bindingsDeps.withAddonStoreWriteLock(async () => {
21280
- const store = await pctx.metaStore.readStore();
21281
- const current = store.locations ?? [];
21282
- const key = locationIconKey(trimmed);
21283
- const remaining = current.filter((l) => l.toLowerCase() !== key);
21284
- const droppedLabel = remaining.length !== current.length;
21285
- const icons = store.locationIcons ?? {};
21286
- const droppedIcon = key in icons;
21287
- const descriptions = store.locationDescriptions ?? {};
21288
- const droppedDescription = key in descriptions;
21289
- const membership = store.locationZones ?? {};
21290
- const droppedZone = key in membership;
21291
- if (!droppedLabel && !droppedIcon && !droppedDescription && !droppedZone) return;
21292
- const { [key]: _removedIcon, ...keptIcons } = icons;
21293
- const { [key]: _removedDescription, ...keptDescriptions } = descriptions;
21294
- const { [key]: _removedZone, ...keptMembership } = membership;
21295
- await pctx.settings.writeAddonStore({
21296
- ...droppedLabel ? { locations: remaining } : {},
21297
- ...droppedIcon ? { locationIcons: keptIcons } : {},
21298
- ...droppedDescription ? { locationDescriptions: keptDescriptions } : {},
21299
- ...droppedZone ? { locationZones: keptMembership } : {}
21300
- });
21301
- });
21302
- if (input.cascade !== true) return;
21303
- const cleared = await pctx.metaStore.withMetaWriteLock(async () => {
21304
- const out = [];
21305
- for (const row of await pctx.metaStore.rows.listAll()) {
21306
- const location = row.meta.location;
21307
- if (typeof location !== "string") continue;
21308
- if (location.trim().toLowerCase() !== trimmed.toLowerCase()) continue;
21309
- await pctx.metaStore.rows.patch(row.meta.id, { location: null });
21310
- out.push(row.meta.id);
21311
- }
21312
- return out;
21313
- });
21314
- for (const deviceId of cleared) pctx.host.ctx.eventBus.emit({
21315
- id: randomUUID(),
21316
- timestamp: /* @__PURE__ */ new Date(),
21317
- source: {
21318
- type: "device",
21319
- id: deviceId
21320
- },
21321
- category: EventCategory$1.DeviceMetaChanged,
21322
- data: {
21323
- deviceId,
21324
- field: "location",
21325
- value: null
22249
+ })();
22250
+ this.inFlight = run;
22251
+ return run;
22252
+ }
22253
+ /** Resolve text names to ids through `ensureTag`; a name no tag cap can mint is left out. */
22254
+ async ensureIds(names) {
22255
+ const source = this.source;
22256
+ if (source === null) return [];
22257
+ const ids = [];
22258
+ for (const name of names) {
22259
+ const tag = await source.ensure(name);
22260
+ ids.push(tag.id);
21326
22261
  }
21327
- });
21328
- }
22262
+ await this.refresh();
22263
+ return ids;
22264
+ }
22265
+ };
21329
22266
  //#endregion
21330
22267
  //#region src/builtins/device-manager/device-identifiers-action.ts
21331
22268
  /**
@@ -21775,7 +22712,6 @@ var IdentityLinkReconciler = class {
21775
22712
  };
21776
22713
  //#endregion
21777
22714
  //#region src/builtins/device-manager/identity-links-store.ts
21778
- var import_read_all_rows = require_read_all_rows();
21779
22715
  var IdentityLinksStore = class IdentityLinksStore {
21780
22716
  kind;
21781
22717
  links = null;
@@ -22859,130 +23795,6 @@ var DeviceTemplateActions = class {
22859
23795
  }
22860
23796
  };
22861
23797
  //#endregion
22862
- //#region src/builtins/device-manager/device-meta-types.ts
22863
- /**
22864
- * Decode the raw `ctx.settings.readAddonStore()` record into {@link AddonStore}.
22865
- *
22866
- * A field of the wrong shape reads as ABSENT rather than being trusted through
22867
- * a cast: the store is JSON on disk and a hand-edit or a partial restore must
22868
- * cost the caller its default, never a downstream `TypeError`.
22869
- */
22870
- function decodeAddonStore(raw) {
22871
- const nextDeviceId = raw["nextDeviceId"];
22872
- const locations = raw["locations"];
22873
- const roleDisplayDefaults = raw["roleDisplayDefaults"];
22874
- const locationIcons = decodeLocationIcons(raw["locationIcons"]);
22875
- const locationDescriptions = decodeLocationDescriptions(raw["locationDescriptions"]);
22876
- const siteZones = decodeSiteZones(raw["siteZones"]);
22877
- const locationZones = decodeStringMap(raw["locationZones"]);
22878
- return {
22879
- ...typeof nextDeviceId === "number" && Number.isFinite(nextDeviceId) ? { nextDeviceId } : {},
22880
- ...Array.isArray(locations) ? { locations: locations.filter((l) => typeof l === "string") } : {},
22881
- ...isRoleDisplayDefaults(roleDisplayDefaults) ? { roleDisplayDefaults } : {},
22882
- ...locationIcons !== null ? { locationIcons } : {},
22883
- ...locationDescriptions !== null ? { locationDescriptions } : {},
22884
- ...siteZones !== null ? { siteZones } : {},
22885
- ...locationZones !== null ? { locationZones } : {}
22886
- };
22887
- }
22888
- /**
22889
- * Decode the `locationIcons` map, dropping every entry whose value is not a
22890
- * member of the closed vocabulary.
22891
- *
22892
- * Dropping, not passing through: the icon's whole point is that both surfaces
22893
- * can draw it, and an id from a hand-edit or a newer hub is exactly the value
22894
- * that draws nothing. Absent reads as "no icon chosen", which every renderer
22895
- * already degrades to the fallback pin. Returns `null` when the key itself is
22896
- * absent or of the wrong shape, so the field stays OMITTED rather than being
22897
- * written back as an empty object.
22898
- */
22899
- function decodeLocationIcons(raw) {
22900
- if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return null;
22901
- const out = {};
22902
- for (const [key, value] of Object.entries(raw)) {
22903
- const icon = canonicalIconKey(value);
22904
- if (icon === void 0) continue;
22905
- out[key] = icon;
22906
- }
22907
- return out;
22908
- }
22909
- /**
22910
- * Decode the `locationDescriptions` map, dropping every entry that is not a
22911
- * non-blank string.
22912
- *
22913
- * Same posture as the icons: a blank description and a missing one are the
22914
- * same instruction to every reader, and storing the first would send an empty
22915
- * line to a vision model. Over-long text is TRUNCATED rather than dropped —
22916
- * losing the whole description because a hand-edit ran long is a worse answer
22917
- * than losing its tail.
22918
- */
22919
- function decodeLocationDescriptions(raw) {
22920
- if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return null;
22921
- const out = {};
22922
- for (const [key, value] of Object.entries(raw)) {
22923
- if (typeof value !== "string") continue;
22924
- const text = value.trim();
22925
- if (text.length === 0) continue;
22926
- out[key] = text.slice(0, 400);
22927
- }
22928
- return out;
22929
- }
22930
- /**
22931
- * Decode the zone registry, dropping any entry without a usable label.
22932
- *
22933
- * A zone whose label did not survive a hand-edit cannot be shown or renamed —
22934
- * it would be a row the operator can see the effects of and never name. An
22935
- * icon outside the vocabulary is dropped on its own, leaving the zone: losing
22936
- * a glyph is a smaller loss than losing the grouping.
22937
- */
22938
- function decodeSiteZones(raw) {
22939
- if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return null;
22940
- const out = {};
22941
- for (const [key, value] of Object.entries(raw)) {
22942
- if (value === null || typeof value !== "object" || Array.isArray(value)) continue;
22943
- const rec = value;
22944
- const label = typeof rec["label"] === "string" ? rec["label"].trim() : "";
22945
- if (label.length === 0) continue;
22946
- const icon = canonicalIconKey(rec["icon"]);
22947
- out[key] = icon === void 0 ? { label } : {
22948
- label,
22949
- icon
22950
- };
22951
- }
22952
- return out;
22953
- }
22954
- /** Decode a plain `string → string` map, dropping anything else. */
22955
- function decodeStringMap(raw) {
22956
- if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return null;
22957
- const out = {};
22958
- for (const [key, value] of Object.entries(raw)) {
22959
- if (typeof value !== "string" || value.trim().length === 0) continue;
22960
- out[key] = value;
22961
- }
22962
- return out;
22963
- }
22964
- function isRoleDisplayDefaults(value) {
22965
- return value !== null && typeof value === "object" && !Array.isArray(value);
22966
- }
22967
- //#endregion
22968
- //#region src/builtins/device-manager/write-lock.ts
22969
- function createWriteLock() {
22970
- let chain = Promise.resolve();
22971
- return async (fn) => {
22972
- const previous = chain;
22973
- let release = () => {};
22974
- chain = new Promise((resolve) => {
22975
- release = resolve;
22976
- });
22977
- try {
22978
- await previous.catch(() => {});
22979
- return await fn();
22980
- } finally {
22981
- release();
22982
- }
22983
- };
22984
- }
22985
- //#endregion
22986
23798
  //#region src/builtins/device-manager/device-meta-store.ts
22987
23799
  var DeviceMetaStore = class {
22988
23800
  settings;
@@ -26699,16 +27511,20 @@ var REMOVAL_RETRY_DELAYS_MS = [
26699
27511
  12e4,
26700
27512
  6e5
26701
27513
  ];
26702
- async function attempt(steps) {
27514
+ async function attempt(steps, concurrent) {
26703
27515
  const counts = {};
26704
27516
  const failed = [];
26705
27517
  const errors = {};
26706
- for (const step of steps) try {
26707
- counts[step.store] = await step.run();
26708
- } catch (err) {
26709
- failed.push(step);
26710
- errors[step.store] = errMsg$1(err);
26711
- }
27518
+ const runOne = async (step) => {
27519
+ try {
27520
+ counts[step.store] = await step.run();
27521
+ } catch (err) {
27522
+ failed.push(step);
27523
+ errors[step.store] = errMsg$1(err);
27524
+ }
27525
+ };
27526
+ if (concurrent) await Promise.all(steps.map(runOne));
27527
+ else for (const step of steps) await runOne(step);
26712
27528
  return {
26713
27529
  counts,
26714
27530
  failed,
@@ -26717,6 +27533,7 @@ async function attempt(steps) {
26717
27533
  }
26718
27534
  function createRemovalCleanup(opts) {
26719
27535
  const label = opts.label ?? "device removal cleanup";
27536
+ const concurrent = opts.concurrent ?? false;
26720
27537
  const delays = opts.retryDelaysMs ?? REMOVAL_RETRY_DELAYS_MS;
26721
27538
  const setTimer = opts.setTimer ?? ((fn, ms) => setTimeout(fn, ms));
26722
27539
  const clearTimer = opts.clearTimer ?? ((handle) => clearTimeout(handle));
@@ -26743,7 +27560,7 @@ function createRemovalCleanup(opts) {
26743
27560
  pending.add(handle);
26744
27561
  };
26745
27562
  const retry = async (deviceId, steps, retryIndex) => {
26746
- const result = await attempt(steps);
27563
+ const result = await attempt(steps, concurrent);
26747
27564
  opts.logger.info(`${label} retried`, {
26748
27565
  tags: { deviceId },
26749
27566
  meta: {
@@ -26756,7 +27573,7 @@ function createRemovalCleanup(opts) {
26756
27573
  };
26757
27574
  return {
26758
27575
  async run(deviceId, steps) {
26759
- const result = await attempt(steps);
27576
+ const result = await attempt(steps, concurrent);
26760
27577
  const failedStores = result.failed.map((s) => s.store);
26761
27578
  const meta = {
26762
27579
  counts: result.counts,
@@ -27168,6 +27985,7 @@ var DeviceManagerAddon = class extends BaseAddon {
27168
27985
  return /* @__PURE__ */ new Map();
27169
27986
  }
27170
27987
  },
27988
+ roomNameOf: (value) => pctx.rooms.nameOf(value),
27171
27989
  logger: this.ctx.logger
27172
27990
  }, input);
27173
27991
  }
@@ -27226,6 +28044,24 @@ var DeviceManagerAddon = class extends BaseAddon {
27226
28044
  const records = this.ctx.records;
27227
28045
  if (records === void 0) throw new Error("[device-manager] ctx.records is required on the hub");
27228
28046
  await records.declare(deviceManagerRecordKinds);
28047
+ await this.runMigrations(defineAddonMigrations(ROOMS_AND_TAGS_MIGRATIONS, deviceManagerMigrationPorts({
28048
+ readStoredKey: (key) => this.readStoredGlobalKey(key),
28049
+ rows: deviceRows,
28050
+ rooms: records.kind(deviceManagerRecordKinds.rooms),
28051
+ zones: records.kind(deviceManagerRecordKinds.zones),
28052
+ report: (message, meta) => this.ctx.logger.info(message, { meta })
28053
+ })));
28054
+ const rooms = RoomStore.of(records);
28055
+ await rooms.load();
28056
+ const tagApi = this.ctx.api?.tags;
28057
+ const tagNames = new TagNames(tagApi === void 0 ? null : {
28058
+ list: () => tagApi.listTags.query({}),
28059
+ ensure: (name) => tagApi.ensureTag.mutate({ name })
28060
+ }, this.ctx.logger.child("tag-names"));
28061
+ deviceRows.setDerivedNames({
28062
+ room: (id) => rooms.nameOf(id),
28063
+ tag: (id) => tagNames.nameOf(id)
28064
+ });
27229
28065
  const tombstones = DeviceTombstoneStore.of(records, this.ctx.logger.child("tombstones"));
27230
28066
  const identityLinksStore = IdentityLinksStore.of(records);
27231
28067
  await identityLinksStore.load();
@@ -27330,6 +28166,10 @@ var DeviceManagerAddon = class extends BaseAddon {
27330
28166
  const templates = this.makeTemplateActions();
27331
28167
  const pctx = {
27332
28168
  host: this.providerHost,
28169
+ rooms,
28170
+ freshTagNames: () => tagNames.fresh(),
28171
+ tagNameOf: (id) => tagNames.nameOf(id),
28172
+ ensureTagIds: (names) => tagNames.ensureIds(names),
27333
28173
  metaStore,
27334
28174
  settings,
27335
28175
  registry,
@@ -27375,11 +28215,29 @@ var DeviceManagerAddon = class extends BaseAddon {
27375
28215
  } catch (err) {
27376
28216
  this.ctx.logger.warn("linked-devices manual backfill failed — auto links are NOT materialised", { meta: { error: errMsg$1(err) } });
27377
28217
  }
28218
+ try {
28219
+ await this.runMigrations(defineAddonMigrations(ORPHAN_CHILDREN_MIGRATIONS, {
28220
+ listRows: async () => (await deviceRows.listAll()).map((row) => ({
28221
+ id: row.meta.id,
28222
+ parentDeviceId: row.meta.parentDeviceId
28223
+ })),
28224
+ rowLimit: DEVICE_ROWS_FLEET_LIMIT,
28225
+ removeDevice: (deviceId) => removeDevice(pctx, { deviceId }),
28226
+ summary: (counts) => this.ctx.logger.info("device-manager: orphan children found", { meta: counts }),
28227
+ info: (message, deviceId, parentDeviceId) => this.ctx.logger.info(message, {
28228
+ tags: { deviceId },
28229
+ meta: { parentDeviceId }
28230
+ })
28231
+ }));
28232
+ } catch (err) {
28233
+ this.ctx.logger.warn("orphan-children migration failed — rows stay as they are", { meta: { error: errMsg$1(err) } });
28234
+ }
27378
28235
  const provider = {
27379
28236
  resolveDeviceOwnerSync: (deviceId) => resolveDeviceOwnerSync(pctx, deviceId),
27380
28237
  resolveNativeCapOwnerSync: (capName, deviceId) => resolveNativeCapOwnerSync(pctx, capName, deviceId),
27381
28238
  allocateDeviceId: (input) => allocateDeviceId(pctx, input),
27382
28239
  migrateDevice: (input) => migrateDevice(pctx, input),
28240
+ repairMigrationSecrets: (input) => repairMigrationSecrets(pctx, input),
27383
28241
  registerDevice: (input) => registerDevice(pctx, input),
27384
28242
  removeDevice: (input) => removeDevice(pctx, input),
27385
28243
  listDeletedSince: ({ sinceMs }) => tombstones.listSince(sinceMs),
@@ -27425,6 +28283,10 @@ var DeviceManagerAddon = class extends BaseAddon {
27425
28283
  setMetadata: (input) => setMetadata(pctx, input),
27426
28284
  setDisabled: (input) => setDisabled(pctx, input),
27427
28285
  loadRuntimeState: (input) => loadRuntimeState(pctx, input),
28286
+ ensureRoom: (input) => ensureRoom(pctx, input),
28287
+ listRooms: () => listRooms(pctx),
28288
+ updateRoom: (input) => updateRoom(pctx, input),
28289
+ deleteRoom: (input) => deleteRoom(pctx, input),
27428
28290
  listLocations: () => listLocations(pctx),
27429
28291
  addLocation: (input) => addLocation(pctx, input),
27430
28292
  removeLocation: (input) => removeLocation(pctx, input),
@@ -27644,7 +28506,8 @@ var DeviceManagerAddon = class extends BaseAddon {
27644
28506
  get removalHooksCleanup() {
27645
28507
  if (this.removalHooksCleanupImpl === null) this.removalHooksCleanupImpl = createRemovalCleanup({
27646
28508
  logger: this.ctx.logger,
27647
- label: "device removal hooks"
28509
+ label: "device removal hooks",
28510
+ concurrent: true
27648
28511
  });
27649
28512
  return this.removalHooksCleanupImpl;
27650
28513
  }