@camstack/server 1.2.942 → 1.2.944

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 (158) 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-routers.js +83 -0
  7. package/dist/auth/native-return.js +9 -3
  8. package/dist/auth/sso-routes.js +5 -1
  9. package/dist/core/addon/instance-lifecycle.js +4 -1
  10. package/dist/core/auth/handoff-code.service.js +35 -1
  11. package/dist/server-root/index.js +313 -70
  12. package/package.json +22 -26
  13. package/system/dist/{action-index-B1fgpQBt.mjs → action-index-DpYmsOKh.mjs} +1 -1
  14. package/system/dist/{action-index-B_cLRwXJ.js → action-index-Dz9rd1qa.js} +1 -1
  15. package/system/dist/{addon-settings.cap-CZ4MC7ha.mjs → addon-settings.cap-CHpmuaQG.mjs} +1 -1
  16. package/system/dist/{addon-settings.cap-DrLdMFIe.js → addon-settings.cap-nZVHPo3X.js} +1 -1
  17. package/system/dist/{alert-episode-Be--PngO.mjs → alert-episode-D-1VUUkZ.mjs} +1 -1
  18. package/system/dist/{alert-episode-Bqktmt-i.js → alert-episode-DaQ3prSe.js} +1 -1
  19. package/system/dist/{base-addon-CRsXtYFG.js → base-addon-BG7p06Hb.js} +136 -15
  20. package/system/dist/{base-addon-BcS6r1cT.mjs → base-addon-BcVoYZbC.mjs} +136 -15
  21. package/system/dist/{base-device-DAdWzDOl.js → base-device-DeSNiwZ4.js} +4 -4
  22. package/system/dist/{base-device-DJXF5eDN.mjs → base-device-w_MD0Bf4.mjs} +4 -4
  23. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.js +1 -1
  24. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.mjs +1 -1
  25. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js +1 -1
  26. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs +1 -1
  27. package/system/dist/builtins/alerts/alerts.addon.js +3 -3
  28. package/system/dist/builtins/alerts/alerts.addon.mjs +3 -3
  29. package/system/dist/builtins/autotrack/index.js +1 -1
  30. package/system/dist/builtins/autotrack/index.mjs +1 -1
  31. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.js +1 -1
  32. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.mjs +1 -1
  33. package/system/dist/builtins/calendars/calendars.addon.js +1 -1
  34. package/system/dist/builtins/calendars/calendars.addon.mjs +1 -1
  35. package/system/dist/builtins/camera-grid/index.js +3 -3
  36. package/system/dist/builtins/camera-grid/index.mjs +3 -3
  37. package/system/dist/builtins/composer/composer.addon.js +7 -7
  38. package/system/dist/builtins/composer/composer.addon.mjs +7 -7
  39. package/system/dist/builtins/console-logging/index.js +1 -1
  40. package/system/dist/builtins/console-logging/index.mjs +1 -1
  41. package/system/dist/builtins/core-blocks/actions-store.d.ts +2 -0
  42. package/system/dist/builtins/core-blocks/block-supervisor.d.ts +16 -4
  43. package/system/dist/builtins/core-blocks/core-block-store.d.ts +2 -0
  44. package/system/dist/builtins/core-blocks/core-blocks.addon.js +1018 -323
  45. package/system/dist/builtins/core-blocks/core-blocks.addon.mjs +986 -291
  46. package/system/dist/builtins/core-blocks/migrations/index.d.ts +5 -2
  47. package/system/dist/builtins/core-blocks/migrations/tag-ids.d.ts +42 -0
  48. package/system/dist/builtins/core-blocks/migrations/tags-as-records.d.ts +47 -0
  49. package/system/dist/builtins/core-blocks/record-kinds.d.ts +12 -1
  50. package/system/dist/builtins/core-blocks/runs-api.d.ts +3 -1
  51. package/system/dist/builtins/core-blocks/runs-ledger.d.ts +3 -1
  52. package/system/dist/builtins/core-blocks/scheduler/scheduler-store.d.ts +2 -0
  53. package/system/dist/builtins/core-blocks/tags-service.d.ts +52 -27
  54. package/system/dist/builtins/core-blocks/tags-wiring.d.ts +2 -0
  55. package/system/dist/builtins/core-notifier/core-notifier.addon.js +76 -67
  56. package/system/dist/builtins/core-notifier/core-notifier.addon.mjs +76 -67
  57. package/system/dist/builtins/device-history/device-history.addon.js +4 -4
  58. package/system/dist/builtins/device-history/device-history.addon.mjs +4 -4
  59. package/system/dist/builtins/device-manager/device-config-secrets.d.ts +14 -0
  60. package/system/dist/builtins/device-manager/device-manager.addon.js +1655 -764
  61. package/system/dist/builtins/device-manager/device-manager.addon.mjs +1641 -750
  62. package/system/dist/builtins/device-manager/device-meta-actions.d.ts +13 -136
  63. package/system/dist/builtins/device-manager/device-meta-types.d.ts +5 -1
  64. package/system/dist/builtins/device-manager/device-provider-context.d.ts +9 -0
  65. package/system/dist/builtins/device-manager/device-row-store.d.ts +21 -4
  66. package/system/dist/builtins/device-manager/device-search.d.ts +6 -0
  67. package/system/dist/builtins/device-manager/location-alignment.d.ts +9 -2
  68. package/system/dist/builtins/device-manager/migrate-device.d.ts +7 -2
  69. package/system/dist/builtins/device-manager/migrate-hardware-state.d.ts +132 -1
  70. package/system/dist/builtins/device-manager/migrations/device-tag-ids.d.ts +25 -0
  71. package/system/dist/builtins/device-manager/migrations/index.d.ts +16 -0
  72. package/system/dist/builtins/device-manager/migrations/orphan-children.d.ts +33 -0
  73. package/system/dist/builtins/device-manager/migrations/ports.d.ts +17 -0
  74. package/system/dist/builtins/device-manager/migrations/rooms-as-records.d.ts +52 -0
  75. package/system/dist/builtins/device-manager/record-kinds.d.ts +3 -1
  76. package/system/dist/builtins/device-manager/removal-cleanup.d.ts +7 -0
  77. package/system/dist/builtins/device-manager/room-actions.d.ts +27 -0
  78. package/system/dist/builtins/device-manager/room-store.d.ts +19 -0
  79. package/system/dist/builtins/device-manager/tag-names.d.ts +32 -0
  80. package/system/dist/builtins/device-manager/wireable-enum-catalog.d.ts +18 -0
  81. package/system/dist/builtins/hub-forwarder/index.js +1 -1
  82. package/system/dist/builtins/hub-forwarder/index.mjs +1 -1
  83. package/system/dist/builtins/keychain/index.js +2 -2
  84. package/system/dist/builtins/keychain/index.mjs +2 -2
  85. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.js +1 -1
  86. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.mjs +1 -1
  87. package/system/dist/builtins/local-auth/local-auth.addon.js +1 -1
  88. package/system/dist/builtins/local-auth/local-auth.addon.mjs +1 -1
  89. package/system/dist/builtins/local-network/local-network.addon.js +2 -2
  90. package/system/dist/builtins/local-network/local-network.addon.mjs +2 -2
  91. package/system/dist/builtins/loki-logging/index.js +2 -2
  92. package/system/dist/builtins/loki-logging/index.mjs +2 -2
  93. package/system/dist/builtins/native-metrics/native-metrics.addon.js +1 -1
  94. package/system/dist/builtins/native-metrics/native-metrics.addon.mjs +1 -1
  95. package/system/dist/builtins/platform-probe/index.js +1 -1
  96. package/system/dist/builtins/platform-probe/index.mjs +1 -1
  97. package/system/dist/builtins/record-entries/index.js +1 -1
  98. package/system/dist/builtins/record-entries/index.mjs +1 -1
  99. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.js +1 -1
  100. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.mjs +1 -1
  101. package/system/dist/builtins/snapshot/index.js +1 -1
  102. package/system/dist/builtins/snapshot/index.mjs +1 -1
  103. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.js +1 -1
  104. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.mjs +1 -1
  105. package/system/dist/builtins/sqlite-storage/index.js +1 -1
  106. package/system/dist/builtins/sqlite-storage/index.mjs +1 -1
  107. package/system/dist/builtins/sqlite-storage/migrations/migration-engine.d.ts +3 -1
  108. package/system/dist/builtins/sqlite-storage/migrations/migrations-provider.d.ts +1 -0
  109. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.js +15 -10
  110. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs +15 -10
  111. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.js +1 -1
  112. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.mjs +1 -1
  113. package/system/dist/builtins/system-config/system-config.addon.js +1 -1
  114. package/system/dist/builtins/system-config/system-config.addon.mjs +1 -1
  115. package/system/dist/builtins/winston-logging/index.js +2 -2
  116. package/system/dist/builtins/winston-logging/index.mjs +2 -2
  117. package/system/dist/{command-catalog-C29hVOOg.js → command-catalog-CI0tu1Nt.js} +1 -1
  118. package/system/dist/{command-catalog-xAeqxbZk.mjs → command-catalog-zwlIA3T5.mjs} +1 -1
  119. package/system/dist/{composition-sources-C327LGFn.mjs → composition-sources-CXxXfh1z.mjs} +1 -1
  120. package/system/dist/{composition-sources-Do5qM6EB.js → composition-sources-DNgSItK-.js} +1 -1
  121. package/system/dist/{core-blocks.cap-CdTGUKtr.js → core-blocks.cap-BHEok4VO.js} +125 -373
  122. package/system/dist/{core-blocks.cap-DLkEfV5b.mjs → core-blocks.cap-CPgZRcpj.mjs} +109 -327
  123. package/system/dist/{device-manager.cap-DJs8izI6.js → device-manager.cap-B9qVf7ag.js} +163 -22
  124. package/system/dist/{device-manager.cap-eYrj1Ezp.mjs → device-manager.cap-CV4KGp3e.mjs} +134 -17
  125. package/system/dist/{error.cap-CU1FB6uE.mjs → error.cap-B8l7L8e4.mjs} +7 -1
  126. package/system/dist/{error.cap-BuKbL3Ac.js → error.cap-BqlvgBJd.js} +7 -1
  127. package/system/dist/file-host-worker.js +1 -1
  128. package/system/dist/file-host-worker.mjs +1 -1
  129. package/system/dist/index.js +7 -7
  130. package/system/dist/index.mjs +6 -6
  131. package/system/dist/{legacy-integration-rows-door-CdqYAj-o.js → legacy-integration-rows-door-BK8eoGlF.js} +1 -1
  132. package/system/dist/{legacy-integration-rows-door-LSgpClpX.mjs → legacy-integration-rows-door-CwzC5XNk.mjs} +1 -1
  133. package/system/dist/{migration-DGAc6ywR.mjs → migration-BvbfW9g-.mjs} +6 -0
  134. package/system/dist/{migration-BOQlFZCN.js → migration-CHPdAdNh.js} +6 -0
  135. package/system/dist/{prefix-walk-BFnw8NBu.js → named-entity-store-DFwLij9c.js} +244 -90
  136. package/system/dist/{prefix-walk-Mtij0NNT.mjs → named-entity-store-DOnyyFFf.mjs} +195 -89
  137. package/system/dist/{notification-rules.cap-BUIuYPlQ.mjs → notification-rules.cap-ClvK6QT1.mjs} +10 -5
  138. package/system/dist/{notification-rules.cap-BJKUjizS.js → notification-rules.cap-uSLoe2pA.js} +10 -5
  139. package/system/dist/{notification-targets-DMW7xgR2.js → notification-targets-ChqpBbtR.js} +2 -2
  140. package/system/dist/{notification-targets-4bGYH5J7.mjs → notification-targets-DUA6-F2t.mjs} +2 -2
  141. package/system/dist/{device-row-store-CTocYKqC.mjs → record-kinds-BD2xv4Pd.mjs} +222 -93
  142. package/system/dist/{device-row-store-C0P2H18h.js → record-kinds-BV8Gcpsx.js} +246 -93
  143. package/system/dist/records/named-entity-store.d.ts +60 -0
  144. package/system/dist/{rename-composition-block-Cdh-dRmY.mjs → rename-composition-block-C3QQ9UUE.mjs} +134 -33
  145. package/system/dist/{rename-composition-block-D9Uc1AF7.js → rename-composition-block-Cx3X8QSm.js} +134 -33
  146. package/system/dist/{retention-source.cap-C6Hy0hlM.js → retention-source.cap-A-TMhU5O.js} +1 -1
  147. package/system/dist/{retention-source.cap-550kkyp5.mjs → retention-source.cap-Ct07pM30.mjs} +1 -1
  148. package/system/dist/{storage-admin.cap-Ci4QbL6P.mjs → storage-admin.cap-C54s9_B9.mjs} +8 -2
  149. package/system/dist/{storage-admin.cap-DqW1ol4j.js → storage-admin.cap-DSPHi7ut.js} +8 -2
  150. package/system/dist/{stream-catalog.cap-CjEQFknc.js → stream-catalog.cap-7WPsugOy.js} +1 -1
  151. package/system/dist/{stream-catalog.cap-DVniDdRD.mjs → stream-catalog.cap-CzwRDaqT.mjs} +1 -1
  152. package/system/dist/{tag-BxLazvVb.js → tag-BLraBqvp.js} +12 -0
  153. package/system/dist/{tag-uZBAq6ox.mjs → tag-DU8pm9Bi.mjs} +7 -1
  154. package/system/dist/time-window-B6UhCArd.js +679 -0
  155. package/system/dist/time-window-BnUBULgu.mjs +578 -0
  156. package/system/dist/{wal-maintenance-BgYiAy5b.js → wal-maintenance-CkPfVApC.js} +0 -0
  157. package/system/dist/{wal-maintenance-Bey5ChBb.mjs → wal-maintenance-u84_1sVl.mjs} +0 -0
  158. package/system/package.json +1 -1
@@ -3,30 +3,31 @@ Object.defineProperties(exports, {
3
3
  [Symbol.toStringTag]: { value: "Module" }
4
4
  });
5
5
  const require_chunk = require("../../chunk-Cek0wNdY.js");
6
- const require_stream_catalog_cap = require("../../stream-catalog.cap-CjEQFknc.js");
7
- const require_base_addon = require("../../base-addon-CRsXtYFG.js");
6
+ const require_stream_catalog_cap = require("../../stream-catalog.cap-7WPsugOy.js");
7
+ const require_base_addon = require("../../base-addon-BG7p06Hb.js");
8
8
  const require_scoped_settings = require("../../scoped-settings-CylSSq_8.js");
9
- const require_rename_composition_block = require("../../rename-composition-block-D9Uc1AF7.js");
9
+ const require_rename_composition_block = require("../../rename-composition-block-Cx3X8QSm.js");
10
10
  const require_camstack_error = require("../../camstack-error-DJ-TUAi1.js");
11
11
  const require_capability_definition = require("../../capability-definition-BEVd01Xj.js");
12
12
  const require_zod_secret = require("../../zod-secret-DS7mj1bk.js");
13
- const require_device_manager_cap = require("../../device-manager.cap-DJs8izI6.js");
13
+ const require_device_manager_cap = require("../../device-manager.cap-B9qVf7ag.js");
14
14
  const require_device_identifiers = require("../../device-identifiers-BQg9EQi1.js");
15
- const require_tag = require("../../tag-BxLazvVb.js");
15
+ const require_record_kinds = require("../../record-kinds-BV8Gcpsx.js");
16
+ const require_migration = require("../../migration-CHPdAdNh.js");
17
+ const require_tag = require("../../tag-BLraBqvp.js");
16
18
  const require_device_type = require("../../device-type-Cnc0NiSX.js");
17
19
  const require_device_kind = require("../../device-kind-FMhJg8uC.js");
18
- const require_action_index = require("../../action-index-B_cLRwXJ.js");
19
- const require_addon_settings_cap = require("../../addon-settings.cap-DrLdMFIe.js");
20
- const require_core_blocks_cap = require("../../core-blocks.cap-CdTGUKtr.js");
20
+ const require_core_blocks_cap = require("../../core-blocks.cap-BHEok4VO.js");
21
+ const require_action_index = require("../../action-index-Dz9rd1qa.js");
22
+ const require_addon_settings_cap = require("../../addon-settings.cap-nZVHPo3X.js");
21
23
  require("../../compile-SpeAhaZ6.js");
22
24
  const require_source_info = require("../../source-info-DtWf4k2j.js");
23
- const require_prefix_walk = require("../../prefix-walk-BFnw8NBu.js");
24
- const require_command_catalog = require("../../command-catalog-C29hVOOg.js");
25
+ const require_named_entity_store = require("../../named-entity-store-DFwLij9c.js");
26
+ const require_command_catalog = require("../../command-catalog-CI0tu1Nt.js");
25
27
  const require_read_all_rows$1 = require("../../read-all-rows-CVoO1ONM.js");
26
28
  const require_log_redactor = require("../../log-redactor-BhIEMaG9.js");
27
29
  const require_prefix_range = require("../../prefix-range-D_KueXbQ.js");
28
30
  const require_retired_settings_keys = require("../../retired-settings-keys-C8nOOr5H.js");
29
- const require_device_row_store = require("../../device-row-store-C0P2H18h.js");
30
31
  const require_template_protocol = require("../../template-protocol-D5ogm1rj.js");
31
32
  const require_dns_wire = require("../../dns-wire-B1BvF9Ao.js");
32
33
  let zod = require("zod");
@@ -2947,6 +2948,13 @@ var METHOD_ACCESS_MAP = /* @__PURE__ */ Object.freeze({
2947
2948
  access: "create",
2948
2949
  role: "admin"
2949
2950
  },
2951
+ "deviceManager.deleteRoom": {
2952
+ capName: "device-manager",
2953
+ capScope: "system",
2954
+ addonId: null,
2955
+ access: "delete",
2956
+ role: "admin"
2957
+ },
2950
2958
  "deviceManager.disable": {
2951
2959
  capName: "device-manager",
2952
2960
  capScope: "system",
@@ -3003,6 +3011,13 @@ var METHOD_ACCESS_MAP = /* @__PURE__ */ Object.freeze({
3003
3011
  access: "create",
3004
3012
  role: "admin"
3005
3013
  },
3014
+ "deviceManager.ensureRoom": {
3015
+ capName: "device-manager",
3016
+ capScope: "system",
3017
+ addonId: null,
3018
+ access: "create",
3019
+ role: "admin"
3020
+ },
3006
3021
  "deviceManager.getAllBindings": {
3007
3022
  capName: "device-manager",
3008
3023
  capScope: "system",
@@ -3227,6 +3242,13 @@ var METHOD_ACCESS_MAP = /* @__PURE__ */ Object.freeze({
3227
3242
  access: "view",
3228
3243
  role: "admin"
3229
3244
  },
3245
+ "deviceManager.listRooms": {
3246
+ capName: "device-manager",
3247
+ capScope: "system",
3248
+ addonId: null,
3249
+ access: "view",
3250
+ role: "viewer"
3251
+ },
3230
3252
  "deviceManager.listSiteZones": {
3231
3253
  capName: "device-manager",
3232
3254
  capScope: "system",
@@ -3367,6 +3389,13 @@ var METHOD_ACCESS_MAP = /* @__PURE__ */ Object.freeze({
3367
3389
  access: "view",
3368
3390
  role: "admin"
3369
3391
  },
3392
+ "deviceManager.repairMigrationSecrets": {
3393
+ capName: "device-manager",
3394
+ capScope: "system",
3395
+ addonId: null,
3396
+ access: "create",
3397
+ role: "admin"
3398
+ },
3370
3399
  "deviceManager.reportDiscoveryObservations": {
3371
3400
  capName: "device-manager",
3372
3401
  capScope: "system",
@@ -3598,6 +3627,13 @@ var METHOD_ACCESS_MAP = /* @__PURE__ */ Object.freeze({
3598
3627
  access: "create",
3599
3628
  role: "admin"
3600
3629
  },
3630
+ "deviceManager.updateRoom": {
3631
+ capName: "device-manager",
3632
+ capScope: "system",
3633
+ addonId: null,
3634
+ access: "create",
3635
+ role: "admin"
3636
+ },
3601
3637
  "deviceOps.getConfigEntries": {
3602
3638
  capName: "device-ops",
3603
3639
  capScope: "device",
@@ -10444,6 +10480,20 @@ var METHOD_ACCESS_MAP = /* @__PURE__ */ Object.freeze({
10444
10480
  access: "create",
10445
10481
  role: "admin"
10446
10482
  },
10483
+ "tags.deleteTag": {
10484
+ capName: "tags",
10485
+ capScope: "system",
10486
+ addonId: null,
10487
+ access: "delete",
10488
+ role: "admin"
10489
+ },
10490
+ "tags.ensureTag": {
10491
+ capName: "tags",
10492
+ capScope: "system",
10493
+ addonId: null,
10494
+ access: "create",
10495
+ role: "admin"
10496
+ },
10447
10497
  "tags.list": {
10448
10498
  capName: "tags",
10449
10499
  capScope: "system",
@@ -10451,6 +10501,13 @@ var METHOD_ACCESS_MAP = /* @__PURE__ */ Object.freeze({
10451
10501
  access: "view",
10452
10502
  role: "admin"
10453
10503
  },
10504
+ "tags.listTags": {
10505
+ capName: "tags",
10506
+ capScope: "system",
10507
+ addonId: null,
10508
+ access: "view",
10509
+ role: "admin"
10510
+ },
10454
10511
  "tags.remove": {
10455
10512
  capName: "tags",
10456
10513
  capScope: "system",
@@ -10472,6 +10529,13 @@ var METHOD_ACCESS_MAP = /* @__PURE__ */ Object.freeze({
10472
10529
  access: "create",
10473
10530
  role: "admin"
10474
10531
  },
10532
+ "tags.updateTag": {
10533
+ capName: "tags",
10534
+ capScope: "system",
10535
+ addonId: null,
10536
+ access: "create",
10537
+ role: "admin"
10538
+ },
10475
10539
  "tamper.getStatus": {
10476
10540
  capName: "tamper",
10477
10541
  capScope: "device",
@@ -12519,104 +12583,629 @@ function resolveCommandHold(cap, method, args, current, option, shown = current)
12519
12583
  };
12520
12584
  }
12521
12585
  //#endregion
12522
- //#region src/builtins/device-manager/adoption-job-engine.ts
12523
- /** How many finished jobs are kept per (addonId, integrationId). */
12524
- var JOB_HISTORY = 20;
12525
- function snapshot(j) {
12526
- let adopted = 0;
12527
- let alreadyAdopted = 0;
12528
- let failed = 0;
12529
- let processed = 0;
12530
- let accessoriesCreated = 0;
12531
- for (const r of j.results) {
12532
- if (r.outcome === "cancelled") continue;
12533
- processed += 1;
12534
- accessoriesCreated += r.accessoryCount;
12535
- if (r.outcome === "adopted") adopted += 1;
12536
- else if (r.outcome === "already-adopted") alreadyAdopted += 1;
12537
- else if (r.outcome === "failed") failed += 1;
12586
+ //#region src/builtins/device-manager/migrations/device-tag-ids.ts
12587
+ /**
12588
+ * A device row gets the ids of its tags (D1089, the device-manager step of the tags
12589
+ * migration): `tagIds` is added beside the kept `tags` names, aligned by index, with each id
12590
+ * derived from the folded name (`tagIdFromKey`) so every owner of that name mints the same
12591
+ * one. The names stay for one release; the `tags` records are written later by the
12592
+ * core-blocks tags-as-records procedure, which `dependsOn` this step.
12593
+ *
12594
+ * ONE plan, one transaction. A row that already has `tagIds` is left alone (a rerun is
12595
+ * empty); a row whose names repeat one tag in two spellings is rewritten with both columns
12596
+ * de-duplicated, so the index alignment holds.
12597
+ */
12598
+ var DEVICE_TAG_IDS_ID = "device-manager/2026-11-23-device-tag-ids";
12599
+ async function planDeviceTagIds(ports) {
12600
+ const rows = await ports.readDeviceTags();
12601
+ const edits = [];
12602
+ for (const row of rows) {
12603
+ if (row.hasTagIds) continue;
12604
+ const names = require_tag.normalizeTags(row.tags);
12605
+ if (names.length === 0) continue;
12606
+ const sameNames = names.length === row.tags.length;
12607
+ edits.push({
12608
+ op: "putRow",
12609
+ table: require_record_kinds.DEVICE_ROWS_COLLECTION,
12610
+ key: { deviceId: row.deviceId },
12611
+ row: {
12612
+ tagIds: names.map((name) => require_named_entity_store.tagIdFromKey(require_tag.tagKey(name))),
12613
+ ...sameNames ? {} : { tags: names }
12614
+ },
12615
+ preconditionColumns: ["tagIds"],
12616
+ precondition: require_migration.preconditionOf({ tagIds: null })
12617
+ });
12618
+ }
12619
+ return { edits };
12620
+ }
12621
+ //#endregion
12622
+ //#region src/builtins/device-manager/migrations/orphan-children.ts
12623
+ /** The rows that name a parent no row answers to. */
12624
+ function orphansOf(rows) {
12625
+ const ids = new Set(rows.map((r) => r.id));
12626
+ return rows.filter((r) => r.parentDeviceId !== null && !ids.has(r.parentDeviceId));
12627
+ }
12628
+ /**
12629
+ * Destructive on one read is never enough (D49): a row is removed only when TWO
12630
+ * reads agree it is an orphan, and nothing is removed from a read that may have
12631
+ * been cut short at the row limit. The candidate ids are recorded in the summary
12632
+ * and the log BEFORE any removal.
12633
+ */
12634
+ async function removeOrphanChildren(ports) {
12635
+ const first = await ports.listRows();
12636
+ 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`);
12637
+ const candidates = orphansOf(first);
12638
+ if (candidates.length === 0) return {
12639
+ outcome: "already-done",
12640
+ summary: {
12641
+ candidates: [],
12642
+ removed: []
12643
+ }
12644
+ };
12645
+ const second = await ports.listRows();
12646
+ const stillOrphans = new Set(orphansOf(second).map((r) => r.id));
12647
+ const confirmed = candidates.filter((r) => stillOrphans.has(r.id));
12648
+ const candidateIds = candidates.map((r) => r.id);
12649
+ ports.summary({
12650
+ rows: first.length,
12651
+ candidateCount: candidateIds.length,
12652
+ candidates: candidateIds,
12653
+ confirmedCount: confirmed.length,
12654
+ confirmed: confirmed.map((r) => r.id)
12655
+ });
12656
+ const removed = [];
12657
+ for (const orphan of confirmed) {
12658
+ if (orphan.parentDeviceId === null) continue;
12659
+ ports.info("device-manager: removing an orphan child, its parent no longer exists", orphan.id, orphan.parentDeviceId);
12660
+ await ports.removeDevice(orphan.id);
12661
+ removed.push(orphan.id);
12538
12662
  }
12539
12663
  return {
12540
- jobId: j.jobId,
12541
- addonId: j.addonId,
12542
- integrationId: j.integrationId,
12543
- state: j.state,
12544
- total: j.total,
12545
- processed,
12546
- adopted,
12547
- alreadyAdopted,
12548
- failed,
12549
- accessoriesCreated,
12550
- currentChildNativeId: j.currentChildNativeId,
12551
- results: j.results.map((r) => ({
12552
- childNativeId: r.childNativeId,
12553
- outcome: r.outcome,
12554
- parentDeviceId: r.parentDeviceId,
12555
- accessoryCount: r.accessoryCount,
12556
- error: r.error
12557
- })),
12558
- startedAt: j.startedAt,
12559
- finishedAt: j.finishedAt,
12560
- error: j.error
12664
+ outcome: "done",
12665
+ summary: {
12666
+ candidates: candidateIds,
12667
+ removed
12668
+ }
12561
12669
  };
12562
12670
  }
12563
- var AdoptionJobEngine = class {
12564
- deps;
12565
- jobs = /* @__PURE__ */ new Map();
12566
- seq = 0;
12567
- constructor(deps) {
12568
- this.deps = deps;
12569
- }
12570
- now() {
12571
- return this.deps.now?.() ?? Date.now();
12671
+ //#endregion
12672
+ //#region src/builtins/device-manager/device-meta-types.ts
12673
+ /**
12674
+ * Decode the raw `ctx.settings.readAddonStore()` record into {@link AddonStore}.
12675
+ *
12676
+ * A field of the wrong shape reads as ABSENT rather than being trusted through
12677
+ * a cast: the store is JSON on disk and a hand-edit or a partial restore must
12678
+ * cost the caller its default, never a downstream `TypeError`.
12679
+ */
12680
+ function decodeAddonStore(raw) {
12681
+ const nextDeviceId = raw["nextDeviceId"];
12682
+ const locations = raw["locations"];
12683
+ const roleDisplayDefaults = raw["roleDisplayDefaults"];
12684
+ const locationIcons = decodeLocationIcons(raw["locationIcons"]);
12685
+ const locationDescriptions = decodeLocationDescriptions(raw["locationDescriptions"]);
12686
+ const siteZones = decodeSiteZones(raw["siteZones"]);
12687
+ const locationZones = decodeStringMap(raw["locationZones"]);
12688
+ return {
12689
+ ...typeof nextDeviceId === "number" && Number.isFinite(nextDeviceId) ? { nextDeviceId } : {},
12690
+ ...Array.isArray(locations) ? { locations: locations.filter((l) => typeof l === "string") } : {},
12691
+ ...isRoleDisplayDefaults(roleDisplayDefaults) ? { roleDisplayDefaults } : {},
12692
+ ...locationIcons !== null ? { locationIcons } : {},
12693
+ ...locationDescriptions !== null ? { locationDescriptions } : {},
12694
+ ...siteZones !== null ? { siteZones } : {},
12695
+ ...locationZones !== null ? { locationZones } : {}
12696
+ };
12697
+ }
12698
+ /**
12699
+ * Decode the `locationIcons` map, dropping every entry whose value is not a
12700
+ * member of the closed vocabulary.
12701
+ *
12702
+ * Dropping, not passing through: the icon's whole point is that both surfaces
12703
+ * can draw it, and an id from a hand-edit or a newer hub is exactly the value
12704
+ * that draws nothing. Absent reads as "no icon chosen", which every renderer
12705
+ * already degrades to the fallback pin. Returns `null` when the key itself is
12706
+ * absent or of the wrong shape, so the field stays OMITTED rather than being
12707
+ * written back as an empty object.
12708
+ */
12709
+ function decodeLocationIcons(raw) {
12710
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return null;
12711
+ const out = {};
12712
+ for (const [key, value] of Object.entries(raw)) {
12713
+ const icon = require_tag.canonicalIconKey(value);
12714
+ if (icon === void 0) continue;
12715
+ out[key] = icon;
12572
12716
  }
12573
- newId() {
12574
- if (this.deps.newId) return this.deps.newId();
12575
- this.seq += 1;
12576
- return `adopt-${Date.now().toString(36)}-${this.seq}`;
12717
+ return out;
12718
+ }
12719
+ /**
12720
+ * Decode the `locationDescriptions` map, dropping every entry that is not a
12721
+ * non-blank string.
12722
+ *
12723
+ * Same posture as the icons: a blank description and a missing one are the
12724
+ * same instruction to every reader, and storing the first would send an empty
12725
+ * line to a vision model. Over-long text is TRUNCATED rather than dropped —
12726
+ * losing the whole description because a hand-edit ran long is a worse answer
12727
+ * than losing its tail.
12728
+ */
12729
+ function decodeLocationDescriptions(raw) {
12730
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return null;
12731
+ const out = {};
12732
+ for (const [key, value] of Object.entries(raw)) {
12733
+ if (typeof value !== "string") continue;
12734
+ const text = value.trim();
12735
+ if (text.length === 0) continue;
12736
+ out[key] = text.slice(0, 400);
12577
12737
  }
12578
- /**
12579
- * Accept the batch and return immediately. The provider is resolved BEFORE
12580
- * returning so an unroutable `addonId` is refused at the call the operator
12581
- * made, not buried in a job they have to go looking for.
12582
- */
12583
- async start(input) {
12584
- const provider = await this.deps.resolveProvider(input.addonId);
12585
- const job = {
12586
- jobId: this.newId(),
12587
- addonId: input.addonId,
12588
- integrationId: input.integrationId,
12589
- state: "running",
12590
- total: input.childNativeIds.length,
12591
- currentChildNativeId: null,
12592
- results: [],
12593
- startedAt: this.now(),
12594
- finishedAt: null,
12595
- error: null,
12596
- cancelRequested: false,
12597
- done: Promise.resolve()
12738
+ return out;
12739
+ }
12740
+ /**
12741
+ * Decode the zone registry, dropping any entry without a usable label.
12742
+ *
12743
+ * A zone whose label did not survive a hand-edit cannot be shown or renamed —
12744
+ * it would be a row the operator can see the effects of and never name. An
12745
+ * icon outside the vocabulary is dropped on its own, leaving the zone: losing
12746
+ * a glyph is a smaller loss than losing the grouping.
12747
+ */
12748
+ function decodeSiteZones(raw) {
12749
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return null;
12750
+ const out = {};
12751
+ for (const [key, value] of Object.entries(raw)) {
12752
+ if (value === null || typeof value !== "object" || Array.isArray(value)) continue;
12753
+ const rec = value;
12754
+ const label = typeof rec["label"] === "string" ? rec["label"].trim() : "";
12755
+ if (label.length === 0) continue;
12756
+ const icon = require_tag.canonicalIconKey(rec["icon"]);
12757
+ out[key] = icon === void 0 ? { label } : {
12758
+ label,
12759
+ icon
12598
12760
  };
12599
- this.jobs.set(job.jobId, job);
12600
- this.prune(input.addonId, input.integrationId);
12601
- this.deps.logger.info("adoption job started", {
12602
- tags: { addonId: input.addonId },
12603
- meta: {
12604
- jobId: job.jobId,
12605
- integrationId: input.integrationId,
12606
- total: job.total
12607
- }
12608
- });
12609
- job.done = this.run(job, provider, input);
12610
- return { jobId: job.jobId };
12611
12761
  }
12612
- get(jobId) {
12613
- const j = this.jobs.get(jobId);
12614
- return j ? snapshot(j) : null;
12615
- }
12616
- list(filter) {
12617
- return [...this.jobs.values()].filter((j) => (filter.addonId === void 0 || j.addonId === filter.addonId) && (filter.integrationId === void 0 || j.integrationId === filter.integrationId)).sort((a, b) => b.startedAt - a.startedAt || b.jobId.localeCompare(a.jobId)).map(snapshot);
12762
+ return out;
12763
+ }
12764
+ /** Decode a plain `string → string` map, dropping anything else. */
12765
+ function decodeStringMap(raw) {
12766
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return null;
12767
+ const out = {};
12768
+ for (const [key, value] of Object.entries(raw)) {
12769
+ if (typeof value !== "string" || value.trim().length === 0) continue;
12770
+ out[key] = value;
12618
12771
  }
12619
- /** Cooperative cancel — the in-flight candidate finishes, the rest do not start. */
12772
+ return out;
12773
+ }
12774
+ function isRoleDisplayDefaults(value) {
12775
+ return value !== null && typeof value === "object" && !Array.isArray(value);
12776
+ }
12777
+ //#endregion
12778
+ //#region src/builtins/device-manager/migrations/rooms-as-records.ts
12779
+ /**
12780
+ * Rooms and site zones become records with an id (D1089, step 1 of the migration).
12781
+ *
12782
+ * Before: a room was a LABEL. The registry (`locations`), its icon and description maps
12783
+ * and the two zone maps (`siteZones`, `locationZones`) lived as keys of the addon store,
12784
+ * and a device carried the label in its `location` column.
12785
+ *
12786
+ * After: one `rooms` record per label and one `zones` record per site zone, with an id
12787
+ * derived from the folded name (`roomIdFromKey` / `zoneIdFromKey`, so a rerun and a
12788
+ * restored older snapshot reach the same ids); a device carries `locationId`; the maps and
12789
+ * the `location` column are gone.
12790
+ *
12791
+ * ONE plan, so ONE transaction with the ledger row: the records, the device rows and the
12792
+ * deleted keys land together or not at all. A rerun finds no legacy key and no device with
12793
+ * a `location`, and the plan is empty. A record that already exists is never rewritten (a
12794
+ * seed never overwrites): a room an operator edited after a partial restore keeps its edit.
12795
+ *
12796
+ * The display spelling is the registry's, else the one most devices use (the first
12797
+ * alphabetically on a tie), else the folded key a map entry carries.
12798
+ */
12799
+ var DEVICE_MANAGER_ID = "device-manager";
12800
+ var ROOMS_AS_RECORDS_ID = "device-manager/2026-11-23-rooms-as-records";
12801
+ /** The canonical settings table: one row per key, id `<addonId>.<key>`. */
12802
+ var ADDON_SETTINGS_TABLE = "addon-settings";
12803
+ /** The addon-store keys this migration retires. */
12804
+ var LEGACY_ROOM_KEYS = [
12805
+ "locations",
12806
+ "locationIcons",
12807
+ "locationDescriptions",
12808
+ "siteZones",
12809
+ "locationZones"
12810
+ ];
12811
+ var isPlainMap = (raw) => raw !== null && typeof raw === "object" && !Array.isArray(raw);
12812
+ /** The entries the decode drops or shortens, raw, before the keys are deleted. */
12813
+ function droppedLegacyEntries(stored) {
12814
+ const out = [];
12815
+ const icons = stored["locationIcons"];
12816
+ if (isPlainMap(icons)) {
12817
+ for (const [key, value] of Object.entries(icons)) if (require_tag.canonicalIconKey(value) === void 0) out.push({
12818
+ map: "locationIcons",
12819
+ key,
12820
+ reason: "icon not in the catalogue",
12821
+ value
12822
+ });
12823
+ }
12824
+ const descriptions = stored["locationDescriptions"];
12825
+ if (isPlainMap(descriptions)) {
12826
+ for (const [key, value] of Object.entries(descriptions)) if (typeof value !== "string" || value.trim().length === 0) out.push({
12827
+ map: "locationDescriptions",
12828
+ key,
12829
+ reason: "blank description",
12830
+ value
12831
+ });
12832
+ else if (value.trim().length > 400) out.push({
12833
+ map: "locationDescriptions",
12834
+ key,
12835
+ reason: "description truncated",
12836
+ value
12837
+ });
12838
+ }
12839
+ const zones = stored["siteZones"];
12840
+ if (isPlainMap(zones)) {
12841
+ for (const [key, value] of Object.entries(zones)) if ((isPlainMap(value) && typeof value["label"] === "string" ? value["label"].trim() : "").length === 0) out.push({
12842
+ map: "siteZones",
12843
+ key,
12844
+ reason: "zone without a label",
12845
+ value
12846
+ });
12847
+ else if (isPlainMap(value) && value["icon"] !== void 0 && require_tag.canonicalIconKey(value["icon"]) === void 0) out.push({
12848
+ map: "siteZones",
12849
+ key,
12850
+ reason: "zone icon not in the catalogue",
12851
+ value
12852
+ });
12853
+ }
12854
+ const membership = stored["locationZones"];
12855
+ if (isPlainMap(membership)) {
12856
+ for (const [key, value] of Object.entries(membership)) if (typeof value !== "string" || value.trim().length === 0) out.push({
12857
+ map: "locationZones",
12858
+ key,
12859
+ reason: "blank zone",
12860
+ value
12861
+ });
12862
+ else if (!isPlainMap(zones) || zones[value] === void 0) out.push({
12863
+ map: "locationZones",
12864
+ key,
12865
+ reason: "zone not in the registry",
12866
+ value
12867
+ });
12868
+ }
12869
+ return out;
12870
+ }
12871
+ /** A map keyed by the FOLDED room key: a legacy key that was never folded still matches. */
12872
+ function foldedBy(map) {
12873
+ const out = /* @__PURE__ */ new Map();
12874
+ for (const [key, value] of Object.entries(map ?? {})) {
12875
+ const folded = require_addon_settings_cap.locationIconKey(key);
12876
+ if (folded.length > 0 && !out.has(folded)) out.set(folded, value);
12877
+ }
12878
+ return out;
12879
+ }
12880
+ var settingsRowId = (key) => `${DEVICE_MANAGER_ID}.${key}`;
12881
+ function clip(name) {
12882
+ return name.trim().slice(0, 80);
12883
+ }
12884
+ /** The spelling to show for each folded room key: registry first, else the most used on devices. */
12885
+ function spellings(registry, devices) {
12886
+ const out = /* @__PURE__ */ new Map();
12887
+ for (const label of registry) {
12888
+ const key = require_addon_settings_cap.locationIconKey(label);
12889
+ if (key.length > 0 && !out.has(key)) out.set(key, clip(label));
12890
+ }
12891
+ const used = /* @__PURE__ */ new Map();
12892
+ for (const { location } of devices) {
12893
+ if (location === null) continue;
12894
+ const key = require_addon_settings_cap.locationIconKey(location);
12895
+ if (key.length === 0) continue;
12896
+ const counts = used.get(key) ?? /* @__PURE__ */ new Map();
12897
+ counts.set(location.trim(), (counts.get(location.trim()) ?? 0) + 1);
12898
+ used.set(key, counts);
12899
+ }
12900
+ for (const [key, counts] of used) {
12901
+ if (out.has(key)) continue;
12902
+ const best = [...counts.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))[0];
12903
+ if (best !== void 0) out.set(key, clip(best[0]));
12904
+ }
12905
+ return out;
12906
+ }
12907
+ async function planRoomsAsRecords(ports) {
12908
+ const stored = await ports.readStored(LEGACY_ROOM_KEYS);
12909
+ const store = decodeAddonStore(stored);
12910
+ const devices = await ports.readDeviceLocations();
12911
+ const existingRooms = await ports.readRoomIds();
12912
+ const existingZones = await ports.readZoneIds();
12913
+ const names = spellings(store.locations ?? [], devices);
12914
+ for (const key of [
12915
+ ...Object.keys(store.locationIcons ?? {}),
12916
+ ...Object.keys(store.locationDescriptions ?? {}),
12917
+ ...Object.keys(store.locationZones ?? {})
12918
+ ]) {
12919
+ const folded = require_addon_settings_cap.locationIconKey(key);
12920
+ if (folded.length > 0 && !names.has(folded)) names.set(folded, clip(key));
12921
+ }
12922
+ const zones = store.siteZones ?? {};
12923
+ const membership = foldedBy(store.locationZones);
12924
+ const iconsByRoom = foldedBy(store.locationIcons);
12925
+ const descriptionsByRoom = foldedBy(store.locationDescriptions);
12926
+ const dropped = droppedLegacyEntries(stored);
12927
+ if (dropped.length > 0) {
12928
+ const counts = {};
12929
+ for (const entry of dropped) counts[entry.map] = (counts[entry.map] ?? 0) + 1;
12930
+ ports.report?.("rooms migration: legacy entries not carried over", {
12931
+ counts,
12932
+ dropped
12933
+ });
12934
+ }
12935
+ const edits = [];
12936
+ for (const [zoneKey, zone] of Object.entries(zones)) {
12937
+ const id = require_named_entity_store.zoneIdFromKey(zoneKey);
12938
+ if (existingZones.has(id)) continue;
12939
+ const body = {
12940
+ name: clip(zone.label),
12941
+ ...zone.icon === void 0 ? {} : { icon: zone.icon }
12942
+ };
12943
+ edits.push(require_record_kinds.recordUpsertEdit({
12944
+ owner: DEVICE_MANAGER_ID,
12945
+ kind: require_record_kinds.deviceManagerRecordKinds.zones,
12946
+ id,
12947
+ data: body,
12948
+ read: null
12949
+ }));
12950
+ }
12951
+ for (const [key, name] of names) {
12952
+ const id = require_named_entity_store.roomIdFromKey(key);
12953
+ if (existingRooms.has(id)) continue;
12954
+ const icon = iconsByRoom.get(key);
12955
+ const description = descriptionsByRoom.get(key);
12956
+ const zoneKey = membership.get(key);
12957
+ const zoneId = zoneKey !== void 0 && zones[zoneKey] !== void 0 ? require_named_entity_store.zoneIdFromKey(zoneKey) : void 0;
12958
+ const body = {
12959
+ name,
12960
+ ...icon === void 0 ? {} : { icon },
12961
+ ...description === void 0 ? {} : { description },
12962
+ ...zoneId === void 0 ? {} : { zoneId }
12963
+ };
12964
+ edits.push(require_record_kinds.recordUpsertEdit({
12965
+ owner: DEVICE_MANAGER_ID,
12966
+ kind: require_record_kinds.deviceManagerRecordKinds.rooms,
12967
+ id,
12968
+ data: body,
12969
+ read: null
12970
+ }));
12971
+ }
12972
+ for (const device of devices) {
12973
+ if (device.location === null) continue;
12974
+ const folded = require_addon_settings_cap.locationIconKey(device.location);
12975
+ const locationId = device.locationId ?? (folded.length === 0 ? null : require_named_entity_store.roomIdFromKey(folded));
12976
+ edits.push({
12977
+ op: "putRow",
12978
+ table: require_record_kinds.DEVICE_ROWS_COLLECTION,
12979
+ key: { deviceId: device.deviceId },
12980
+ row: {
12981
+ locationId,
12982
+ location: null
12983
+ },
12984
+ preconditionColumns: ["location", "locationId"],
12985
+ precondition: require_migration.preconditionOf({
12986
+ location: device.location,
12987
+ locationId: device.locationId
12988
+ })
12989
+ });
12990
+ }
12991
+ const present = LEGACY_ROOM_KEYS.filter((key) => key in stored);
12992
+ if (present.length > 0) edits.push({
12993
+ op: "deleteKeys",
12994
+ scope: ADDON_SETTINGS_TABLE,
12995
+ keys: present.map(settingsRowId),
12996
+ precondition: require_migration.preconditionOf(Object.fromEntries(present.map((key) => [settingsRowId(key), {
12997
+ addonId: DEVICE_MANAGER_ID,
12998
+ key,
12999
+ value: stored[key]
13000
+ }])))
13001
+ });
13002
+ return { edits };
13003
+ }
13004
+ //#endregion
13005
+ //#region src/builtins/device-manager/migrations/index.ts
13006
+ var REMOVE_ORPHAN_CHILDREN_ID = "device-manager/2026-11-23-remove-orphan-children";
13007
+ /** Rooms, zones and tag ids: run BEFORE the first read resolves a name (D1089). */
13008
+ var ROOMS_AND_TAGS_MIGRATIONS = [{
13009
+ meta: {
13010
+ id: ROOMS_AS_RECORDS_ID,
13011
+ owner: DEVICE_MANAGER_ID,
13012
+ level: "addon-state",
13013
+ seq: 1,
13014
+ dependsOn: [],
13015
+ store: "settings",
13016
+ scope: "cluster",
13017
+ onFailure: "tolerate",
13018
+ bodyKind: "plan",
13019
+ 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",
13020
+ fixtureMark: "a device column and a room icon the migration does not know"
13021
+ },
13022
+ plan: (ports) => planRoomsAsRecords(ports)
13023
+ }, {
13024
+ meta: {
13025
+ id: DEVICE_TAG_IDS_ID,
13026
+ owner: DEVICE_MANAGER_ID,
13027
+ level: "addon-state",
13028
+ seq: 2,
13029
+ dependsOn: [],
13030
+ store: "settings",
13031
+ scope: "cluster",
13032
+ onFailure: "tolerate",
13033
+ bodyKind: "plan",
13034
+ description: "Add the ids of its tags to each device row beside the kept names, derived from the folded name",
13035
+ fixtureMark: "a device column the migration does not know"
13036
+ },
13037
+ plan: (ports) => planDeviceTagIds(ports)
13038
+ }];
13039
+ /** Accessory rows left behind by a removal that did not cascade: run once the fleet is up (D987). */
13040
+ var ORPHAN_CHILDREN_MIGRATIONS = [{
13041
+ meta: {
13042
+ id: REMOVE_ORPHAN_CHILDREN_ID,
13043
+ owner: DEVICE_MANAGER_ID,
13044
+ level: "addon-state",
13045
+ seq: 3,
13046
+ dependsOn: [],
13047
+ store: "settings",
13048
+ scope: "cluster",
13049
+ onFailure: "tolerate",
13050
+ bodyKind: "procedure",
13051
+ description: "Remove every device row whose parentDeviceId names no row, through the tombstoned removal, each one logged",
13052
+ fixtureMark: "a child of a live parent and a top-level row, both kept"
13053
+ },
13054
+ procedure: removeOrphanChildren
13055
+ }];
13056
+ [...ROOMS_AND_TAGS_MIGRATIONS, ...ORPHAN_CHILDREN_MIGRATIONS];
13057
+ //#endregion
13058
+ //#region src/builtins/device-manager/migrations/ports.ts
13059
+ var import_read_all_rows = require_read_all_rows$1.require_read_all_rows();
13060
+ var stringOrNull = (value) => typeof value === "string" ? value : null;
13061
+ function stringArray(value) {
13062
+ return Array.isArray(value) ? value.filter((v) => typeof v === "string") : [];
13063
+ }
13064
+ function deviceManagerMigrationPorts(source) {
13065
+ return {
13066
+ readStored: async (keys) => {
13067
+ const found = {};
13068
+ for (const key of keys) {
13069
+ const answer = await source.readStoredKey(key);
13070
+ if (answer.kind === "unreadable") throw new Error(`${DEVICE_MANAGER_ID}: the setting ${key} cannot be read (${answer.reason})`);
13071
+ if (answer.kind === "present") found[key] = answer.value;
13072
+ }
13073
+ return found;
13074
+ },
13075
+ readDeviceLocations: async () => {
13076
+ return (await source.rows.readRawColumns([
13077
+ "deviceId",
13078
+ "location",
13079
+ "locationId"
13080
+ ])).flatMap((row) => {
13081
+ const deviceId = row["deviceId"];
13082
+ if (typeof deviceId !== "number") return [];
13083
+ return [{
13084
+ deviceId,
13085
+ location: stringOrNull(row["location"]),
13086
+ locationId: stringOrNull(row["locationId"])
13087
+ }];
13088
+ });
13089
+ },
13090
+ readDeviceTags: async () => {
13091
+ return (await source.rows.readRawColumns([
13092
+ "deviceId",
13093
+ "tags",
13094
+ "tagIds"
13095
+ ])).flatMap((row) => {
13096
+ const deviceId = row["deviceId"];
13097
+ if (typeof deviceId !== "number") return [];
13098
+ return [{
13099
+ deviceId,
13100
+ tags: stringArray(row["tags"]),
13101
+ hasTagIds: row["tagIds"] !== null && row["tagIds"] !== void 0
13102
+ }];
13103
+ });
13104
+ },
13105
+ readRoomIds: async () => new Set((await (0, import_read_all_rows.readAllRows)(source.rooms)).map((row) => row.id)),
13106
+ readZoneIds: async () => new Set((await (0, import_read_all_rows.readAllRows)(source.zones)).map((row) => row.id)),
13107
+ ...source.report === void 0 ? {} : { report: source.report }
13108
+ };
13109
+ }
13110
+ //#endregion
13111
+ //#region src/builtins/device-manager/adoption-job-engine.ts
13112
+ /** How many finished jobs are kept per (addonId, integrationId). */
13113
+ var JOB_HISTORY = 20;
13114
+ function snapshot(j) {
13115
+ let adopted = 0;
13116
+ let alreadyAdopted = 0;
13117
+ let failed = 0;
13118
+ let processed = 0;
13119
+ let accessoriesCreated = 0;
13120
+ for (const r of j.results) {
13121
+ if (r.outcome === "cancelled") continue;
13122
+ processed += 1;
13123
+ accessoriesCreated += r.accessoryCount;
13124
+ if (r.outcome === "adopted") adopted += 1;
13125
+ else if (r.outcome === "already-adopted") alreadyAdopted += 1;
13126
+ else if (r.outcome === "failed") failed += 1;
13127
+ }
13128
+ return {
13129
+ jobId: j.jobId,
13130
+ addonId: j.addonId,
13131
+ integrationId: j.integrationId,
13132
+ state: j.state,
13133
+ total: j.total,
13134
+ processed,
13135
+ adopted,
13136
+ alreadyAdopted,
13137
+ failed,
13138
+ accessoriesCreated,
13139
+ currentChildNativeId: j.currentChildNativeId,
13140
+ results: j.results.map((r) => ({
13141
+ childNativeId: r.childNativeId,
13142
+ outcome: r.outcome,
13143
+ parentDeviceId: r.parentDeviceId,
13144
+ accessoryCount: r.accessoryCount,
13145
+ error: r.error
13146
+ })),
13147
+ startedAt: j.startedAt,
13148
+ finishedAt: j.finishedAt,
13149
+ error: j.error
13150
+ };
13151
+ }
13152
+ var AdoptionJobEngine = class {
13153
+ deps;
13154
+ jobs = /* @__PURE__ */ new Map();
13155
+ seq = 0;
13156
+ constructor(deps) {
13157
+ this.deps = deps;
13158
+ }
13159
+ now() {
13160
+ return this.deps.now?.() ?? Date.now();
13161
+ }
13162
+ newId() {
13163
+ if (this.deps.newId) return this.deps.newId();
13164
+ this.seq += 1;
13165
+ return `adopt-${Date.now().toString(36)}-${this.seq}`;
13166
+ }
13167
+ /**
13168
+ * Accept the batch and return immediately. The provider is resolved BEFORE
13169
+ * returning so an unroutable `addonId` is refused at the call the operator
13170
+ * made, not buried in a job they have to go looking for.
13171
+ */
13172
+ async start(input) {
13173
+ const provider = await this.deps.resolveProvider(input.addonId);
13174
+ const job = {
13175
+ jobId: this.newId(),
13176
+ addonId: input.addonId,
13177
+ integrationId: input.integrationId,
13178
+ state: "running",
13179
+ total: input.childNativeIds.length,
13180
+ currentChildNativeId: null,
13181
+ results: [],
13182
+ startedAt: this.now(),
13183
+ finishedAt: null,
13184
+ error: null,
13185
+ cancelRequested: false,
13186
+ done: Promise.resolve()
13187
+ };
13188
+ this.jobs.set(job.jobId, job);
13189
+ this.prune(input.addonId, input.integrationId);
13190
+ this.deps.logger.info("adoption job started", {
13191
+ tags: { addonId: input.addonId },
13192
+ meta: {
13193
+ jobId: job.jobId,
13194
+ integrationId: input.integrationId,
13195
+ total: job.total
13196
+ }
13197
+ });
13198
+ job.done = this.run(job, provider, input);
13199
+ return { jobId: job.jobId };
13200
+ }
13201
+ get(jobId) {
13202
+ const j = this.jobs.get(jobId);
13203
+ return j ? snapshot(j) : null;
13204
+ }
13205
+ list(filter) {
13206
+ return [...this.jobs.values()].filter((j) => (filter.addonId === void 0 || j.addonId === filter.addonId) && (filter.integrationId === void 0 || j.integrationId === filter.integrationId)).sort((a, b) => b.startedAt - a.startedAt || b.jobId.localeCompare(a.jobId)).map(snapshot);
13207
+ }
13208
+ /** Cooperative cancel — the in-flight candidate finishes, the rest do not start. */
12620
13209
  cancel(jobId) {
12621
13210
  const job = this.jobs.get(jobId);
12622
13211
  if (!job || job.state !== "running") return false;
@@ -13494,6 +14083,104 @@ function sleep(ms) {
13494
14083
  });
13495
14084
  }
13496
14085
  //#endregion
14086
+ //#region src/builtins/device-manager/wireable-enum-catalog.ts
14087
+ /**
14088
+ * Per-device value catalogs for wireable fields (`status.fieldEnums` on a cap).
14089
+ *
14090
+ * A status field such as `error.code` or `event-emitter.lastEvent.eventType` is a
14091
+ * plain string in the schema, but the device's integration DECLARES the closed set
14092
+ * of values at runtime (`error.listFaultTypes`, the event vocabulary). This module
14093
+ * asks the device's own provider and returns the values the editor offers as a
14094
+ * dropdown. A read that fails answers `null` — the caller leaves `enumValues`
14095
+ * absent (free text stays) and logs; it is never an empty list (D393, D315).
14096
+ */
14097
+ var RecordSchema = zod.z.record(zod.z.string(), zod.z.unknown());
14098
+ function isProviderShape(value) {
14099
+ return typeof value === "object" && value !== null;
14100
+ }
14101
+ function listOf(answer, source) {
14102
+ const record = RecordSchema.safeParse(answer);
14103
+ if (!record.success) return null;
14104
+ const list = zod.z.array(RecordSchema).safeParse(record.data[source.listKey]);
14105
+ if (!list.success) return null;
14106
+ const values = [];
14107
+ for (const entry of list.data) {
14108
+ const value = entry[source.valueKey];
14109
+ if (typeof value !== "string") return null;
14110
+ if (!values.includes(value)) values.push(value);
14111
+ }
14112
+ return values;
14113
+ }
14114
+ async function readAnswer(provider, source, deviceId) {
14115
+ const fn = provider[source.from === "method" ? source.method : "getStatus"];
14116
+ if (typeof fn !== "function") return void 0;
14117
+ return await Reflect.apply(fn, provider, [{ deviceId }]);
14118
+ }
14119
+ var TIMED_OUT = Symbol("catalog-read-timed-out");
14120
+ async function raceBudget(work, budgetMs) {
14121
+ let timer;
14122
+ const deadline = new Promise((resolve) => {
14123
+ timer = setTimeout(() => resolve(TIMED_OUT), budgetMs);
14124
+ timer.unref?.();
14125
+ });
14126
+ try {
14127
+ return await Promise.race([work, deadline]);
14128
+ } finally {
14129
+ if (timer !== void 0) clearTimeout(timer);
14130
+ }
14131
+ }
14132
+ /**
14133
+ * The device's declared values for one field, or `null` when there are none to
14134
+ * offer. A provider without the catalog, a cold (null) slice or an empty catalog
14135
+ * is a quiet absence; a thrown read, a timeout or a malformed answer is warned
14136
+ * with the device tag. Either way the field stays free text.
14137
+ */
14138
+ async function readFieldCatalog(read) {
14139
+ const { registry, logger, capName, deviceId, path, source, budgetMs } = read;
14140
+ try {
14141
+ const provider = registry.getProviderForDevice(capName, deviceId);
14142
+ if (!isProviderShape(provider)) return null;
14143
+ const answer = await raceBudget(readAnswer(provider, source, deviceId), budgetMs);
14144
+ if (answer === TIMED_OUT) {
14145
+ logger.warn("wireable field catalog: read timed out, field stays free text", {
14146
+ tags: { deviceId },
14147
+ meta: {
14148
+ deviceId,
14149
+ capName,
14150
+ path,
14151
+ budgetMs
14152
+ }
14153
+ });
14154
+ return null;
14155
+ }
14156
+ if (answer === void 0 || answer === null) return null;
14157
+ const values = listOf(answer, source);
14158
+ if (values === null) {
14159
+ logger.warn("wireable field catalog: answer has an unexpected shape", {
14160
+ tags: { deviceId },
14161
+ meta: {
14162
+ deviceId,
14163
+ capName,
14164
+ path
14165
+ }
14166
+ });
14167
+ return null;
14168
+ }
14169
+ return values.length > 0 ? values : null;
14170
+ } catch (err) {
14171
+ logger.warn("wireable field catalog: read failed, field stays free text", {
14172
+ tags: { deviceId },
14173
+ meta: {
14174
+ deviceId,
14175
+ capName,
14176
+ path,
14177
+ error: err instanceof Error ? err.message : String(err)
14178
+ }
14179
+ });
14180
+ return null;
14181
+ }
14182
+ }
14183
+ //#endregion
13497
14184
  //#region src/builtins/device-manager/device-aggregation-merge.ts
13498
14185
  /**
13499
14186
  * Pure aggregator-merge + field-tagging helpers for the device-manager
@@ -13663,11 +14350,11 @@ function mergeAggregates(parts) {
13663
14350
  * per-row path (`connection.password`, `rows[].pin`) is not mapped onto a form
13664
14351
  * field and keeps the driver's hydration.
13665
14352
  */
13666
- function isRecord$3(value) {
14353
+ function isRecord$4(value) {
13667
14354
  return typeof value === "object" && value !== null && !Array.isArray(value);
13668
14355
  }
13669
14356
  function isConfigFieldWithValue(field) {
13670
- if (!isRecord$3(field)) return false;
14357
+ if (!isRecord$4(field)) return false;
13671
14358
  return typeof field.type === "string" && typeof field.key === "string" && "value" in field;
13672
14359
  }
13673
14360
  /** The declared paths that name a top-level config key. */
@@ -13675,7 +14362,7 @@ function topLevelKeys(paths) {
13675
14362
  return new Set(paths.filter((p) => p.length > 0 && !p.includes(".") && !p.includes("[")));
13676
14363
  }
13677
14364
  function viewField(field, stored, declared) {
13678
- if (!isRecord$3(field)) return field;
14365
+ if (!isRecord$4(field)) return field;
13679
14366
  const nested = field["fields"];
13680
14367
  if (Array.isArray(nested)) return {
13681
14368
  ...field,
@@ -13684,7 +14371,7 @@ function viewField(field, stored, declared) {
13684
14371
  const tabs = field["tabs"];
13685
14372
  if (Array.isArray(tabs)) return {
13686
14373
  ...field,
13687
- tabs: tabs.map((tab) => isRecord$3(tab) && Array.isArray(tab["fields"]) ? {
14374
+ tabs: tabs.map((tab) => isRecord$4(tab) && Array.isArray(tab["fields"]) ? {
13688
14375
  ...tab,
13689
14376
  fields: tab["fields"].map((f) => viewField(f, stored, declared))
13690
14377
  } : tab)
@@ -13793,7 +14480,7 @@ function isDeclaredCollectionCap(capName) {
13793
14480
  function isDeclaredNonWrapperCap(capName) {
13794
14481
  return DECLARED_NON_WRAPPER_CAPS.has(capName);
13795
14482
  }
13796
- function isRecord$2(value) {
14483
+ function isRecord$3(value) {
13797
14484
  return typeof value === "object" && value !== null && !Array.isArray(value);
13798
14485
  }
13799
14486
  /** A persisted activation of a wrapper on a cap that has none (see module docblock). */
@@ -13836,12 +14523,12 @@ var StaleWrapperActivations = class {
13836
14523
  if (this.checked) return;
13837
14524
  this.checked = true;
13838
14525
  const devices = store.deviceBindings;
13839
- if (!isRecord$2(devices)) return;
14526
+ if (!isRecord$3(devices)) return;
13840
14527
  for (const [deviceKey, perDevice] of Object.entries(devices)) {
13841
14528
  const deviceId = Number(deviceKey);
13842
- if (!Number.isInteger(deviceId) || !isRecord$2(perDevice)) continue;
14529
+ if (!Number.isInteger(deviceId) || !isRecord$3(perDevice)) continue;
13843
14530
  for (const [capName, row] of Object.entries(perDevice)) {
13844
- const wrapperAddonId = isRecord$2(row) ? row["wrapperAddonId"] : void 0;
14531
+ const wrapperAddonId = isRecord$3(row) ? row["wrapperAddonId"] : void 0;
13845
14532
  if (typeof wrapperAddonId === "string" && isDeclaredNonWrapperCap(capName)) this.report(deviceId, capName, wrapperAddonId);
13846
14533
  }
13847
14534
  }
@@ -15494,6 +16181,7 @@ async function readDeviceConfigs(pctx, deviceIds) {
15494
16181
  return pctx.settings.readDeviceStoreBatch(deviceIds);
15495
16182
  }
15496
16183
  async function listAll(pctx, input) {
16184
+ await pctx.freshTagNames();
15497
16185
  const ownerFilter = Reflect.get(input, "addonId");
15498
16186
  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\`.`);
15499
16187
  const callerAddonId = pctx.metaStore.rows.censusArmed ? extractCallerAddonId(input) : void 0;
@@ -15581,6 +16269,7 @@ async function listAll(pctx, input) {
15581
16269
  }
15582
16270
  async function getDevice(pctx, input) {
15583
16271
  const { deviceId } = input;
16272
+ await pctx.freshTagNames();
15584
16273
  if (pctx.registry) {
15585
16274
  const found = resolveDeviceById(pctx.registry, deviceId);
15586
16275
  if (found) {
@@ -17175,6 +17864,36 @@ function wireableEntryForDef(capName, def) {
17175
17864
  };
17176
17865
  }
17177
17866
  /**
17867
+ * Fill `enumValues` of the fields the cap declares a per-device catalog for
17868
+ * (`status.fieldEnums`) from the device's own provider. A failed or empty read
17869
+ * leaves the field untouched (free text), never an empty list.
17870
+ */
17871
+ async function withDeclaredCatalogs(deps, registry, deviceId, entry, def) {
17872
+ const declared = def.status?.fieldEnums;
17873
+ if (!declared) return entry;
17874
+ const fields = await Promise.all(entry.fields.map(async (field) => {
17875
+ const source = declared[field.path];
17876
+ if (!source || field.item === true) return field;
17877
+ const values = await readFieldCatalog({
17878
+ registry,
17879
+ logger: deps.ctx.logger,
17880
+ capName: entry.cap,
17881
+ deviceId,
17882
+ path: field.path,
17883
+ source,
17884
+ budgetMs: CONTRIBUTION_BUDGET_MS
17885
+ });
17886
+ return values === null ? field : {
17887
+ ...field,
17888
+ enumValues: values
17889
+ };
17890
+ }));
17891
+ return {
17892
+ ...entry,
17893
+ fields
17894
+ };
17895
+ }
17896
+ /**
17178
17897
  * Per-device wireable-field catalog — the domain status fields a device's
17179
17898
  * bound caps expose, for the operator's cross-device wiring UI. Binding-driven:
17180
17899
  * walks `getBindings(deviceId)`, skips wrapper caps (their status schemas are
@@ -17195,14 +17914,19 @@ async function getWireableFields(deps, input) {
17195
17914
  const { entries } = await getBindings(deps.bindingsDeps, { deviceId });
17196
17915
  const seen = /* @__PURE__ */ new Set();
17197
17916
  const caps = [];
17917
+ const pending = [];
17198
17918
  for (const entry of entries) {
17199
17919
  if (seen.has(entry.capName)) continue;
17200
17920
  seen.add(entry.capName);
17201
17921
  const def = reg.getDefinition(entry.capName);
17202
17922
  if (!def || def.kind === "wrapper") continue;
17203
17923
  const wireable = wireableEntryForDef(entry.capName, def);
17204
- if (wireable) caps.push(wireable);
17924
+ if (wireable) pending.push({
17925
+ wireable,
17926
+ def
17927
+ });
17205
17928
  }
17929
+ caps.push(...await Promise.all(pending.map(({ wireable, def }) => withDeclaredCatalogs(deps, reg, deviceId, wireable, def))));
17206
17930
  if (input.includeSynthesizable === true) {
17207
17931
  const deviceType = (await deps.bindingsDeps.rows.get(deviceId))?.meta.type;
17208
17932
  if (deviceType !== void 0) for (const def of require_rename_composition_block.ALL_CAPABILITY_DEFINITIONS) {
@@ -17400,8 +18124,9 @@ async function searchDevices(deps, input) {
17400
18124
  let compatibleTotal = 0;
17401
18125
  let hiddenIncompatible = 0;
17402
18126
  const filters = input.filters;
18127
+ const locationFilter = filters?.locations?.map((value) => deps.roomNameOf?.(value) ?? value);
17403
18128
  for (const c of textPass) {
17404
- const okLocation = matches(filters?.locations, c.device.location);
18129
+ const okLocation = matches(locationFilter, c.device.location);
17405
18130
  const okIntegration = matches(filters?.integrationIds, c.integrationId);
17406
18131
  const okType = matches(filters?.types, c.device.type);
17407
18132
  if (c.compatible) {
@@ -17734,7 +18459,7 @@ async function setWrapperActive(deps, input) {
17734
18459
  }
17735
18460
  });
17736
18461
  }
17737
- function isRecord$1(value) {
18462
+ function isRecord$2(value) {
17738
18463
  return typeof value === "object" && value !== null && !Array.isArray(value);
17739
18464
  }
17740
18465
  /** The key of this addon's store that holds every wrapper activation. */
@@ -17774,19 +18499,19 @@ async function readWrapperActivation(deps, query) {
17774
18499
  error: "the store holds no deviceBindings row — an empty snapshot is not evidence of an unbind"
17775
18500
  };
17776
18501
  const deviceBindings = read.value;
17777
- if (!isRecord$1(deviceBindings)) return {
18502
+ if (!isRecord$2(deviceBindings)) return {
17778
18503
  kind: "failed",
17779
18504
  error: "stored deviceBindings is not a map"
17780
18505
  };
17781
18506
  const perDevice = deviceBindings[String(query.deviceId)];
17782
18507
  if (perDevice === void 0) return { kind: "missing" };
17783
- if (!isRecord$1(perDevice)) return {
18508
+ if (!isRecord$2(perDevice)) return {
17784
18509
  kind: "failed",
17785
18510
  error: `stored bindings of device ${query.deviceId} are not a map`
17786
18511
  };
17787
18512
  const activation = perDevice[query.capName];
17788
18513
  if (activation === void 0) return { kind: "missing" };
17789
- if (!isRecord$1(activation)) return {
18514
+ if (!isRecord$2(activation)) return {
17790
18515
  kind: "failed",
17791
18516
  error: `stored "${query.capName}" activation is not a record`
17792
18517
  };
@@ -18256,7 +18981,7 @@ function deviceIdOfSuffix(suffix) {
18256
18981
  }
18257
18982
  /** Every field row of one device scope, or a throw. */
18258
18983
  async function readScope(door, addonId, deviceId) {
18259
- return require_prefix_walk.loadPrefixed(door, DEVICE_SETTINGS_COLLECTION, scopeOf(addonId, deviceId));
18984
+ return require_named_entity_store.loadPrefixed(door, DEVICE_SETTINGS_COLLECTION, scopeOf(addonId, deviceId));
18260
18985
  }
18261
18986
  function createDeviceSettingsStore(door, addonId) {
18262
18987
  return {
@@ -18280,7 +19005,7 @@ function createDeviceSettingsStore(door, addonId) {
18280
19005
  if (deviceIds.length === 0) return out;
18281
19006
  for (const id of deviceIds) out.set(id, {});
18282
19007
  const wanted = new Set(deviceIds);
18283
- const all = await require_prefix_walk.loadPrefixed(door, DEVICE_SETTINGS_COLLECTION, `${addonId}:`);
19008
+ const all = await require_named_entity_store.loadPrefixed(door, DEVICE_SETTINGS_COLLECTION, `${addonId}:`);
18284
19009
  for (const [suffix, value] of Object.entries(all)) {
18285
19010
  const id = deviceIdOfSuffix(suffix);
18286
19011
  if (id === null || !wanted.has(id)) continue;
@@ -18290,7 +19015,7 @@ function createDeviceSettingsStore(door, addonId) {
18290
19015
  return out;
18291
19016
  },
18292
19017
  async listIds() {
18293
- const all = await require_prefix_walk.loadPrefixed(door, DEVICE_SETTINGS_COLLECTION, `${addonId}:`, () => null);
19018
+ const all = await require_named_entity_store.loadPrefixed(door, DEVICE_SETTINGS_COLLECTION, `${addonId}:`, () => null);
18294
19019
  const ids = /* @__PURE__ */ new Set();
18295
19020
  for (const suffix of Object.keys(all)) {
18296
19021
  const id = deviceIdOfSuffix(suffix);
@@ -18610,11 +19335,39 @@ async function loadDeviceConfigWithSecrets(ctx, input) {
18610
19335
  });
18611
19336
  return value;
18612
19337
  }
18613
- //#endregion
18614
- //#region src/builtins/device-manager/device-removal-hooks.ts
18615
19338
  /**
18616
- * device-manager's side of `device-removal-hook` (D865): tell every implementer
18617
- * a device was deleted, and answer the admin question "which stored data belongs
19339
+ * The CREATE write reaches the door before the device class exists, so the
19340
+ * paths its schema declares secret are not known yet and the blob lands raw.
19341
+ * The first registration brings those paths: move every declared TOP-LEVEL
19342
+ * secret still raw (a non-empty string, not a marker) into the keychain.
19343
+ * Only the first registration of a row — this completes the create write; a
19344
+ * re-registration of an older row converts nothing (no silent migration).
19345
+ * Returns the converted path names (never values).
19346
+ */
19347
+ async function secureRawDeclaredSecrets(deps, input) {
19348
+ if (ownerSecrets(deps.ctx, input.ownerAddonId) === null) return [];
19349
+ const stored = await deps.readStored();
19350
+ const rawKeys = input.secretPaths.filter((path) => {
19351
+ if (path.includes(".") || path.includes("[")) return false;
19352
+ const value = stored[path];
19353
+ return typeof value === "string" && value.length > 0;
19354
+ });
19355
+ if (rawKeys.length === 0) return [];
19356
+ const patch = Object.fromEntries(rawKeys.map((key) => [key, stored[key]]));
19357
+ await persistDeviceConfigWithSecrets(deps, {
19358
+ deviceId: input.deviceId,
19359
+ ownerAddonId: input.ownerAddonId,
19360
+ data: patch,
19361
+ secretPaths: rawKeys,
19362
+ operatorWrite: true
19363
+ });
19364
+ return rawKeys;
19365
+ }
19366
+ //#endregion
19367
+ //#region src/builtins/device-manager/device-removal-hooks.ts
19368
+ /**
19369
+ * device-manager's side of `device-removal-hook` (D865): tell every implementer
19370
+ * a device was deleted, and answer the admin question "which stored data belongs
18618
19371
  * to devices that no longer exist?".
18619
19372
  *
18620
19373
  * Two entry points, one rule: **an implementer is told to delete only on a
@@ -18889,7 +19642,7 @@ function nearestLocatedAncestor(byId, startParentId) {
18889
19642
  visited.add(cursor);
18890
19643
  const ancestor = byId.get(cursor);
18891
19644
  if (!ancestor) return null;
18892
- if (ancestor.location !== null) return ancestor;
19645
+ if (ancestor.locationId !== void 0 && ancestor.locationId !== null) return ancestor;
18893
19646
  cursor = ancestor.parentDeviceId;
18894
19647
  }
18895
19648
  return null;
@@ -18919,15 +19672,16 @@ function planNullLocationFills(rows) {
18919
19672
  const byId = new Map(rows.map((r) => [r.id, r]));
18920
19673
  const plan = [];
18921
19674
  for (const row of rows) {
18922
- if (row.location !== null) continue;
19675
+ if (row.locationId !== void 0 && row.locationId !== null) continue;
18923
19676
  if (row.parentDeviceId === null) continue;
18924
19677
  const hit = nearestLocatedAncestor(byId, row.parentDeviceId);
18925
19678
  if (hit === null) continue;
18926
19679
  if (hit.type !== require_device_type.DeviceType.Container) continue;
18927
- if (hit.location === null) continue;
19680
+ if (hit.locationId === void 0 || hit.locationId === null) continue;
18928
19681
  plan.push({
18929
19682
  id: row.id,
18930
19683
  location: hit.location,
19684
+ locationId: hit.locationId,
18931
19685
  ancestorId: hit.id
18932
19686
  });
18933
19687
  }
@@ -18952,7 +19706,14 @@ async function resolveInheritedLocation(rows, parentDeviceId) {
18952
19706
  visited.add(cursor);
18953
19707
  const ancestor = await rows.get(cursor);
18954
19708
  if (ancestor === null) return null;
18955
- if (ancestor.meta.location !== null) return ancestor.meta.type === require_device_type.DeviceType.Container ? ancestor.meta.location : null;
19709
+ const locationId = ancestor.meta.locationId ?? null;
19710
+ if (locationId !== null) {
19711
+ if (ancestor.meta.type !== require_device_type.DeviceType.Container) return null;
19712
+ return {
19713
+ locationId,
19714
+ location: ancestor.meta.location
19715
+ };
19716
+ }
18956
19717
  cursor = ancestor.meta.parentDeviceId;
18957
19718
  }
18958
19719
  return null;
@@ -18987,8 +19748,8 @@ async function runLocationBackfillAtBoot(pctx, bootRows) {
18987
19748
  const plan = planNullLocationFills((await pctx.metaStore.rows.listAll()).map((r) => r.meta));
18988
19749
  for (const fill of plan) try {
18989
19750
  const current = await pctx.metaStore.rows.get(fill.id);
18990
- if (current === null || current.meta.location !== null) continue;
18991
- await pctx.metaStore.rows.patch(fill.id, { location: fill.location });
19751
+ if (current === null || (current.meta.locationId ?? null) !== null) continue;
19752
+ await pctx.metaStore.rows.patch(fill.id, { locationId: fill.locationId });
18992
19753
  patched.push(fill);
18993
19754
  } catch (err) {
18994
19755
  failed.push({
@@ -19197,12 +19958,13 @@ async function migrateDevice$1(deps, input) {
19197
19958
  try {
19198
19959
  await deps.swapIds(sourceId, targetId);
19199
19960
  } catch (err) {
19200
- if (err instanceof require_device_row_store.MigrationRefusedError) return rollBackRefusal(deps, ids, prior, err);
19961
+ if (err instanceof require_record_kinds.MigrationRefusedError) return rollBackRefusal(deps, ids, prior, err);
19201
19962
  alarmPartialMigration(deps, ids, "swapIds", err);
19202
19963
  throw err;
19203
19964
  }
19965
+ let secretScopes;
19204
19966
  try {
19205
- await deps.swapHardwareState(sourceId, targetId);
19967
+ secretScopes = await deps.swapHardwareState(sourceId, targetId);
19206
19968
  } catch (err) {
19207
19969
  alarmPartialMigration(deps, ids, "swapHardwareState", err);
19208
19970
  throw err;
@@ -19228,7 +19990,8 @@ async function migrateDevice$1(deps, input) {
19228
19990
  targetId,
19229
19991
  switches: [...down, ...up],
19230
19992
  sourceStillLive,
19231
- swapped: true
19993
+ swapped: true,
19994
+ secretScopes
19232
19995
  };
19233
19996
  }
19234
19997
  //#endregion
@@ -19265,6 +20028,15 @@ async function migrateDevice$1(deps, input) {
19265
20028
  * stream-profile assignment (the live authority is the stream broker's own
19266
20029
  * map — see `StreamsTab.tsx`, which stopped writing it), and either copy
19267
20030
  * names stream ids of the wrong hardware after a swap.
20031
+ * - A secret marker inside the swapped config names the keychain scope of ONE
20032
+ * number (`secret://<owner>/device/<id>/<field>`; the ref is the AAD of the
20033
+ * ciphertext). Swapping the marker alone left each number pointing at the
20034
+ * other's scope, so removing either device purged the secret the other still
20035
+ * used (D1093, live 2026-11-23). The configs swap with their markers
20036
+ * unchanged (each still reads its value), then `repairCrossedSecretScopes`
20037
+ * brings every value under the number whose config holds it, through staged
20038
+ * copies, so a crash at any step is finished by a re-run of the repair.
20039
+ * - The location (room) is role state and stays on the number (`swapIds`).
19268
20040
  * - The runtime-state blobs (`__device-state:<id>` — battery snapshot, sleep
19269
20041
  * flag, feature probe) SWAP wholesale: every slice mirrors the box — never
19270
20042
  * while either carries `$owned` (D663): the migration is refused first
@@ -19309,7 +20081,7 @@ var FieldClaimsBlockMigrationError = class extends Error {
19309
20081
  * moved — so it is a {@link MigrationRefusedError}: both cameras' switches are
19310
20082
  * restored, and the claim stays on the number it names.
19311
20083
  */
19312
- var ClaimLandedDuringMigrationError = class extends require_device_row_store.MigrationRefusedError {
20084
+ var ClaimLandedDuringMigrationError = class extends require_record_kinds.MigrationRefusedError {
19313
20085
  sourceId;
19314
20086
  targetId;
19315
20087
  blocked;
@@ -19390,11 +20162,21 @@ function splitConfig(config) {
19390
20162
  * incident this module exists to prevent, and it must never be reported as a
19391
20163
  * success.
19392
20164
  */
19393
- async function swapHardwareState(settings, sourceId, targetId) {
20165
+ async function swapHardwareState(settings, sourceId, targetId, secrets) {
19394
20166
  const sourceConfig = await settings.readDeviceStore(sourceId);
19395
20167
  const targetConfig = await settings.readDeviceStore(targetId);
20168
+ const crossed = [{
20169
+ deviceId: sourceId,
20170
+ markers: crossedIn(sourceConfig, targetId)
20171
+ }, {
20172
+ deviceId: targetId,
20173
+ markers: crossedIn(targetConfig, sourceId)
20174
+ }].filter((c) => c.markers > 0);
20175
+ if (crossed.length > 0) throw new Error(new SecretScopesCrossedError(sourceId, targetId, crossed).message);
19396
20176
  const source = splitConfig(sourceConfig);
19397
20177
  const target = splitConfig(targetConfig);
20178
+ const marked = hasDeviceMarkers(source.hardware, sourceId, targetId) || hasDeviceMarkers(target.hardware, sourceId, targetId);
20179
+ 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`);
19398
20180
  await settings.clearDeviceStore(sourceId);
19399
20181
  await settings.writeDeviceStore(sourceId, {
19400
20182
  ...target.hardware,
@@ -19409,14 +20191,216 @@ async function swapHardwareState(settings, sourceId, targetId) {
19409
20191
  const targetRuntimeState = await settings.readDeviceRuntimeState(targetId);
19410
20192
  await settings.writeDeviceRuntimeState(sourceId, targetRuntimeState);
19411
20193
  await settings.writeDeviceRuntimeState(targetId, sourceRuntimeState);
20194
+ let secretScopes = {
20195
+ exchanged: false,
20196
+ markersRepointed: 0,
20197
+ refsAtSource: [],
20198
+ refsAtTarget: []
20199
+ };
20200
+ if (marked) try {
20201
+ const repaired = await repairCrossedSecretScopes(settings, secrets, sourceId, targetId, true);
20202
+ secretScopes = {
20203
+ exchanged: repaired.outcome === "repaired",
20204
+ markersRepointed: repaired.markersRepointedAtA + repaired.markersRepointedAtB,
20205
+ refsAtSource: repaired.refsNowAtA,
20206
+ refsAtTarget: repaired.refsNowAtB
20207
+ };
20208
+ } catch (err) {
20209
+ 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 });
20210
+ }
19412
20211
  return {
19413
20212
  runtimeStateNowAtSource: targetRuntimeState,
19414
20213
  runtimeStateNowAtTarget: sourceRuntimeState,
19415
20214
  hardwareKeysToSource: Object.keys(target.hardware).toSorted(),
19416
20215
  hardwareKeysToTarget: Object.keys(source.hardware).toSorted(),
19417
20216
  roleKeysKeptAtSource: Object.keys(source.role).toSorted(),
19418
- roleKeysKeptAtTarget: Object.keys(target.role).toSorted()
20217
+ roleKeysKeptAtTarget: Object.keys(target.role).toSorted(),
20218
+ secretScopes
20219
+ };
20220
+ }
20221
+ /** The suffix of the staging copy a repair keeps while a value changes scope. */
20222
+ var REPAIR_STAGING_SUFFIX = "~repair";
20223
+ function refWithin(parts, deviceId, fieldPath) {
20224
+ return require_scoped_settings.buildSecretRef({
20225
+ ...parts,
20226
+ scope: {
20227
+ kind: "device",
20228
+ deviceId
20229
+ },
20230
+ fieldPath
20231
+ });
20232
+ }
20233
+ /**
20234
+ * The markers of `config` (the config of `ownId`) the repair must move: those
20235
+ * naming `otherId`'s scope, and the staging copies of an interrupted run.
20236
+ */
20237
+ function repairMarkers(config, ownId, otherId) {
20238
+ const found = [];
20239
+ for (const current of collectMarkerRefs(config)) {
20240
+ const parts = require_scoped_settings.parseSecretRef(current);
20241
+ if (parts === null || parts.scope.kind !== "device") continue;
20242
+ const staged = parts.fieldPath.endsWith(REPAIR_STAGING_SUFFIX);
20243
+ if (!(parts.scope.deviceId === otherId || staged && parts.scope.deviceId === ownId)) continue;
20244
+ const fieldPath = staged ? parts.fieldPath.slice(0, -7) : parts.fieldPath;
20245
+ found.push({
20246
+ current,
20247
+ staging: staged ? current : refWithin(parts, ownId, `${fieldPath}${REPAIR_STAGING_SUFFIX}`),
20248
+ dest: refWithin(parts, ownId, fieldPath),
20249
+ owner: parts.owner,
20250
+ staged
20251
+ });
20252
+ }
20253
+ return found;
20254
+ }
20255
+ /**
20256
+ * Repair a pair a migration left with CROSSED secrets (it ran before the
20257
+ * secrets followed the config): a number's config carries markers naming the
20258
+ * OTHER number's keychain scope, so removing either device would purge the
20259
+ * secret the other still reads. Each such marker's value is brought under the
20260
+ * number whose config holds it.
20261
+ *
20262
+ * The configs ARE the state machine, so a crash at any step is re-run to the
20263
+ * right end state — never a double exchange, never a value lost:
20264
+ * 1. stage: copy each value to a staging ref in its own number's scope
20265
+ * (idempotent puts; the originals are untouched);
20266
+ * 2. point both configs at the staging refs — from here every marker reads a
20267
+ * value that is not about to be overwritten;
20268
+ * 3. put each value at its end ref (idempotent: the source is the staging ref);
20269
+ * 4. point both configs at the end refs;
20270
+ * 5. delete the staging refs and any original no config names any more.
20271
+ * A re-run reads each marker's CURRENT ref, so a marker already at a staging
20272
+ * or end ref continues from there. One-sided pairs and a pair where only some
20273
+ * fields are crossed work the same way, field by field.
20274
+ *
20275
+ * Idempotent: a pair with no marker to move is left alone. `apply: false` is
20276
+ * the dry run: counts only. A missing keychain door with markers to move THROWS.
20277
+ */
20278
+ async function repairCrossedSecretScopes(settings, secrets, deviceA, deviceB, apply) {
20279
+ const configA = await settings.readDeviceStore(deviceA);
20280
+ const configB = await settings.readDeviceStore(deviceB);
20281
+ const markersA = repairMarkers(configA, deviceA, deviceB);
20282
+ const markersB = repairMarkers(configB, deviceB, deviceA);
20283
+ const counts = {
20284
+ markersRepointedAtA: markersA.length,
20285
+ markersRepointedAtB: markersB.length
20286
+ };
20287
+ if (markersA.length === 0 && markersB.length === 0) return {
20288
+ outcome: "nothing-to-repair",
20289
+ ...counts,
20290
+ refsNowAtA: [],
20291
+ refsNowAtB: []
20292
+ };
20293
+ 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`);
20294
+ if (!apply) return {
20295
+ outcome: "would-repair",
20296
+ ...counts,
20297
+ refsNowAtA: [],
20298
+ refsNowAtB: []
20299
+ };
20300
+ const all = [...markersA, ...markersB];
20301
+ const valueOf = async (owner, ref) => {
20302
+ const answer = (await secrets.forOwner(owner).resolve([ref]))[ref];
20303
+ if (answer?.kind === "value") return answer.value;
20304
+ throw new Error(`repairMigrationSecrets: ${ref} cannot be read (${answer?.kind ?? "no answer"}); nothing was changed`);
20305
+ };
20306
+ const rewritten = (pick) => {
20307
+ const mapOf = (markers) => {
20308
+ const byCurrent = new Map(markers.map((m) => [m.current, pick(m)]));
20309
+ return (ref) => byCurrent.get(ref);
20310
+ };
20311
+ return [rewriteMarkerRefs(configA, mapOf(markersA)), rewriteMarkerRefs(configB, mapOf(markersB))];
20312
+ };
20313
+ const writeBoth = async (pick) => {
20314
+ const [nextA, nextB] = rewritten(pick);
20315
+ await settings.writeDeviceStore(deviceA, nextA);
20316
+ await settings.writeDeviceStore(deviceB, nextB);
20317
+ };
20318
+ for (const m of all) if (!m.staged) await secrets.forOwner(m.owner).put(m.staging, await valueOf(m.owner, m.current));
20319
+ await writeBoth((m) => m.staging);
20320
+ for (const m of all) await secrets.forOwner(m.owner).put(m.dest, await valueOf(m.owner, m.staging));
20321
+ await writeBoth((m) => m.dest);
20322
+ const finalRefs = new Set(rewritten((m) => m.dest).flatMap(collectMarkerRefs));
20323
+ for (const m of all) {
20324
+ const stale = [m.staging, ...m.staged || finalRefs.has(m.current) ? [] : [m.current]];
20325
+ await secrets.forOwner(m.owner).delete(stale);
20326
+ }
20327
+ for (const ref of finalRefs) {
20328
+ const parts = require_scoped_settings.parseSecretRef(ref);
20329
+ if (parts === null || parts.scope.kind !== "device") continue;
20330
+ const strays = [deviceA, deviceB].map((id) => refWithin(parts, id, `${parts.fieldPath.replace(/~repair$/, "")}${REPAIR_STAGING_SUFFIX}`)).filter((stray) => !finalRefs.has(stray));
20331
+ await secrets.forOwner(parts.owner).delete(strays);
20332
+ }
20333
+ return {
20334
+ outcome: "repaired",
20335
+ ...counts,
20336
+ refsNowAtA: markersA.map((m) => m.dest),
20337
+ refsNowAtB: markersB.map((m) => m.dest)
20338
+ };
20339
+ }
20340
+ /**
20341
+ * The refusal of a migration over a pair whose configs hold markers naming the
20342
+ * OTHER number's keychain scope (an earlier migration crossed them): swapping
20343
+ * again would mix the passwords. Nothing moved; run the repair first.
20344
+ */
20345
+ var SecretScopesCrossedError = class extends require_record_kinds.MigrationRefusedError {
20346
+ sourceId;
20347
+ targetId;
20348
+ crossed;
20349
+ constructor(sourceId, targetId, crossed) {
20350
+ 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)`);
20351
+ this.sourceId = sourceId;
20352
+ this.targetId = targetId;
20353
+ this.crossed = crossed;
20354
+ this.name = "SecretScopesCrossedError";
20355
+ }
20356
+ };
20357
+ /** True when `config` holds a marker in the keychain scope of device `a` or `b`. */
20358
+ function hasDeviceMarkers(config, a, b) {
20359
+ return collectMarkerRefs(config).some((ref) => {
20360
+ const parts = require_scoped_settings.parseSecretRef(ref);
20361
+ return parts !== null && parts.scope.kind === "device" && (parts.scope.deviceId === a || parts.scope.deviceId === b);
20362
+ });
20363
+ }
20364
+ function crossedIn(config, otherId) {
20365
+ return collectMarkerRefs(config).filter((ref) => {
20366
+ const parts = require_scoped_settings.parseSecretRef(ref);
20367
+ return parts !== null && parts.scope.kind === "device" && parts.scope.deviceId === otherId;
20368
+ }).length;
20369
+ }
20370
+ /**
20371
+ * Refuse a migration when either config already names the other number's
20372
+ * keychain scope. Read from the stored configs (D49: an unreadable config
20373
+ * throws, never reads as "not crossed").
20374
+ */
20375
+ async function assertNoCrossedSecretScopes(settings, sourceId, targetId) {
20376
+ const crossed = [{
20377
+ deviceId: sourceId,
20378
+ markers: crossedIn(await settings.readDeviceStore(sourceId), targetId)
20379
+ }, {
20380
+ deviceId: targetId,
20381
+ markers: crossedIn(await settings.readDeviceStore(targetId), sourceId)
20382
+ }].filter((c) => c.markers > 0);
20383
+ if (crossed.length > 0) throw new SecretScopesCrossedError(sourceId, targetId, crossed);
20384
+ }
20385
+ /** Every secret marker's ref in a config, at any depth. */
20386
+ function collectMarkerRefs(value) {
20387
+ if (Array.isArray(value)) return value.flatMap(collectMarkerRefs);
20388
+ if (require_scoped_settings.isSecretMarker(value)) return [value.$secret];
20389
+ if (isRecord$1(value)) return Object.values(value).flatMap(collectMarkerRefs);
20390
+ return [];
20391
+ }
20392
+ /** A copy of `value` whose markers name `map(ref)` where it answers (others untouched). */
20393
+ function rewriteMarkerRefs(value, map) {
20394
+ const walk = (node) => {
20395
+ if (Array.isArray(node)) return node.map(walk);
20396
+ if (require_scoped_settings.isSecretMarker(node)) return require_scoped_settings.makeSecretMarker(map(node.$secret) ?? node.$secret);
20397
+ if (isRecord$1(node)) return Object.fromEntries(Object.entries(node).map(([k, v]) => [k, walk(v)]));
20398
+ return node;
19419
20399
  };
20400
+ return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, walk(v)]));
20401
+ }
20402
+ function isRecord$1(value) {
20403
+ return typeof value === "object" && value !== null && !Array.isArray(value);
19420
20404
  }
19421
20405
  //#endregion
19422
20406
  //#region src/builtins/device-manager/migrate-reload.ts
@@ -19465,6 +20449,274 @@ async function reloadMigratedDevices(pctx, targets) {
19465
20449
  }));
19466
20450
  }
19467
20451
  //#endregion
20452
+ //#region src/builtins/device-manager/room-actions.ts
20453
+ /**
20454
+ * Rooms and site zones as records with an id (D1089).
20455
+ *
20456
+ * The entity methods (`ensureRoom`, `listRooms`, `updateRoom`, `deleteRoom`) are
20457
+ * the model: a rename, a new icon or a new description is ONE write to ONE
20458
+ * `rooms` record, and no device is rewritten (a device meta carries only
20459
+ * `locationId`; its `location` name is derived at read). A delete clears the
20460
+ * references in one operation.
20461
+ *
20462
+ * Everything else here — `listLocations`, `addLocation`, `removeLocation`,
20463
+ * `renameLocation`, the icon / description maps, the site-zone methods and
20464
+ * `setLocationZone` — is a thin SHIM over those, answering the same shapes as
20465
+ * before so the admin UI and the viewer keep working until they move to the ids.
20466
+ * A shim is removed once nothing calls it (D1089).
20467
+ */
20468
+ /** Room record → the wire shape. */
20469
+ function toRoom(entity) {
20470
+ return entity;
20471
+ }
20472
+ function requireName(name, code, what) {
20473
+ const trimmed = name.trim();
20474
+ if (trimmed.length === 0) throw require_camstack_error.userError(code, void 0, `[device-manager] ${what}: name must be non-empty`);
20475
+ return trimmed;
20476
+ }
20477
+ /** Drop a field when the patch says `null`, keep it when absent, set it otherwise. */
20478
+ function applied(patch, current) {
20479
+ if (patch === void 0) return current;
20480
+ if (patch === null) return void 0;
20481
+ return patch;
20482
+ }
20483
+ function emitLocationChanged(pctx, deviceId, value) {
20484
+ pctx.host.ctx.eventBus.emit({
20485
+ id: (0, node_crypto.randomUUID)(),
20486
+ timestamp: /* @__PURE__ */ new Date(),
20487
+ source: {
20488
+ type: "device",
20489
+ id: deviceId
20490
+ },
20491
+ category: require_base_addon.EventCategory.DeviceMetaChanged,
20492
+ data: {
20493
+ deviceId,
20494
+ field: "location",
20495
+ value
20496
+ }
20497
+ });
20498
+ }
20499
+ /** The ids of every device whose room is `roomId`. */
20500
+ async function devicesInRoom(pctx, roomId) {
20501
+ return (await pctx.metaStore.rows.listAll()).filter((row) => row.meta.locationId === roomId).map((row) => row.meta.id);
20502
+ }
20503
+ async function ensureRoom(pctx, input) {
20504
+ const name = requireName(input.name, "system.location-name-required", "ensureRoom");
20505
+ return toRoom(await pctx.rooms.rooms.ensure(name, {}));
20506
+ }
20507
+ async function listRooms(pctx) {
20508
+ return pctx.rooms.rooms.list().map(toRoom);
20509
+ }
20510
+ async function updateRoom(pctx, input) {
20511
+ const { id, patch } = input;
20512
+ const before = pctx.rooms.rooms.get(id);
20513
+ let updated;
20514
+ try {
20515
+ updated = await pctx.rooms.rooms.update(id, (current) => {
20516
+ return {
20517
+ name: patch.name ?? current.name,
20518
+ icon: applied(patch.icon, current.icon),
20519
+ description: applied(patch.description, current.description),
20520
+ zoneId: applied(patch.zoneId, current.zoneId),
20521
+ colour: applied(patch.colour, current.colour),
20522
+ order: applied(patch.order, current.order)
20523
+ };
20524
+ });
20525
+ } catch (err) {
20526
+ if (err instanceof require_named_entity_store.EntityNotFoundError) throw require_camstack_error.userError("system.room-not-found", void 0, `[device-manager] room not found: ${id}`);
20527
+ if (err instanceof require_named_entity_store.EntityNameTakenError) throw require_camstack_error.userError("system.room-name-taken", void 0, `[device-manager] ${err.message}`);
20528
+ throw err;
20529
+ }
20530
+ if (before !== null && before.name !== updated.name) for (const deviceId of await devicesInRoom(pctx, id)) emitLocationChanged(pctx, deviceId, updated.name);
20531
+ return toRoom(updated);
20532
+ }
20533
+ async function deleteRoom(pctx, input) {
20534
+ if (!await pctx.rooms.rooms.delete(input.id)) return { cleared: 0 };
20535
+ const cleared = await pctx.metaStore.withMetaWriteLock(async () => {
20536
+ const out = [];
20537
+ for (const row of await pctx.metaStore.rows.listAll()) {
20538
+ if (row.meta.locationId !== input.id) continue;
20539
+ await pctx.metaStore.rows.patch(row.meta.id, { locationId: null });
20540
+ out.push(row.meta.id);
20541
+ }
20542
+ return out;
20543
+ });
20544
+ for (const deviceId of cleared) emitLocationChanged(pctx, deviceId, null);
20545
+ return { cleared: cleared.length };
20546
+ }
20547
+ /**
20548
+ * The id a write names: `locationId` wins, else `location` (text) is resolved
20549
+ * through `ensureRoom`. `undefined` = the caller named neither, `null` = clear.
20550
+ */
20551
+ async function resolveRoomId(pctx, input) {
20552
+ if (input.locationId !== void 0) {
20553
+ if (input.locationId !== null && pctx.rooms.rooms.get(input.locationId) === null) throw require_camstack_error.userError("system.room-not-found", void 0, `[device-manager] room not found: ${input.locationId}`);
20554
+ return input.locationId;
20555
+ }
20556
+ if (input.location === void 0) return void 0;
20557
+ if (input.location === null || input.location.trim().length === 0) return null;
20558
+ return (await pctx.rooms.rooms.ensure(input.location.trim(), {})).id;
20559
+ }
20560
+ async function listLocations(pctx) {
20561
+ return pctx.rooms.rooms.list().map((room) => room.name).toSorted((a, b) => a.localeCompare(b, void 0, { sensitivity: "base" }));
20562
+ }
20563
+ async function addLocation(pctx, input) {
20564
+ const name = requireName(input.name, "system.location-name-required", "addLocation");
20565
+ await pctx.rooms.rooms.ensure(name, {});
20566
+ }
20567
+ async function removeLocation(pctx, input) {
20568
+ const room = pctx.rooms.rooms.findByName(input.name);
20569
+ if (room === null) return;
20570
+ if (input.cascade === true) {
20571
+ await deleteRoom(pctx, { id: room.id });
20572
+ return;
20573
+ }
20574
+ if ((await devicesInRoom(pctx, room.id)).length > 0) {
20575
+ await updateRoom(pctx, {
20576
+ id: room.id,
20577
+ patch: {
20578
+ icon: null,
20579
+ description: null,
20580
+ zoneId: null
20581
+ }
20582
+ });
20583
+ return;
20584
+ }
20585
+ await pctx.rooms.rooms.delete(room.id);
20586
+ }
20587
+ async function renameLocation(pctx, input) {
20588
+ const from = requireName(input.from, "system.location-name-required", "renameLocation");
20589
+ const to = requireName(input.to, "system.location-name-required", "renameLocation");
20590
+ const source = pctx.rooms.rooms.findByName(from);
20591
+ if (source === null) return { moved: 0 };
20592
+ const target = pctx.rooms.rooms.findByName(to);
20593
+ if (target === null || target.id === source.id) {
20594
+ await updateRoom(pctx, {
20595
+ id: source.id,
20596
+ patch: { name: to }
20597
+ });
20598
+ return { moved: (await devicesInRoom(pctx, source.id)).length };
20599
+ }
20600
+ const moved = await pctx.metaStore.withMetaWriteLock(async () => {
20601
+ const out = [];
20602
+ for (const row of await pctx.metaStore.rows.listAll()) {
20603
+ if (row.meta.locationId !== source.id) continue;
20604
+ await pctx.metaStore.rows.patch(row.meta.id, { locationId: target.id });
20605
+ out.push(row.meta.id);
20606
+ }
20607
+ return out;
20608
+ });
20609
+ await pctx.rooms.rooms.delete(source.id);
20610
+ for (const deviceId of moved) emitLocationChanged(pctx, deviceId, target.name);
20611
+ return { moved: moved.length };
20612
+ }
20613
+ async function listLocationIcons(pctx) {
20614
+ return pctx.rooms.rooms.list().flatMap((room) => room.icon === void 0 ? [] : [{
20615
+ locationKey: require_named_entity_store.entityNameKey(room.name),
20616
+ icon: room.icon
20617
+ }]).toSorted((a, b) => a.locationKey.localeCompare(b.locationKey));
20618
+ }
20619
+ async function setLocationIcon(pctx, input) {
20620
+ const name = requireName(input.location, "system.location-required", "setLocationIcon");
20621
+ const existing = pctx.rooms.rooms.findByName(name);
20622
+ if (existing === null && input.icon === null) return;
20623
+ const room = existing ?? await pctx.rooms.rooms.ensure(name, {});
20624
+ const icon = input.icon;
20625
+ await updateRoom(pctx, {
20626
+ id: room.id,
20627
+ patch: { icon }
20628
+ });
20629
+ }
20630
+ async function listLocationDescriptions(pctx) {
20631
+ return pctx.rooms.rooms.list().flatMap((room) => room.description === void 0 ? [] : [{
20632
+ locationKey: require_named_entity_store.entityNameKey(room.name),
20633
+ description: room.description
20634
+ }]).toSorted((a, b) => a.locationKey.localeCompare(b.locationKey));
20635
+ }
20636
+ async function setLocationDescription(pctx, input) {
20637
+ const name = requireName(input.location, "system.location-required", "setLocationDescription");
20638
+ const text = input.description === null ? "" : input.description.trim();
20639
+ const existing = pctx.rooms.rooms.findByName(name);
20640
+ if (existing === null && text.length === 0) return;
20641
+ await updateRoom(pctx, {
20642
+ id: (existing ?? await pctx.rooms.rooms.ensure(name, {})).id,
20643
+ patch: { description: text.length === 0 ? null : text }
20644
+ });
20645
+ }
20646
+ function zoneFolded(zone) {
20647
+ return require_named_entity_store.entityNameKey(zone.name);
20648
+ }
20649
+ async function listSiteZones(pctx) {
20650
+ const rooms = pctx.rooms.rooms.list();
20651
+ return pctx.rooms.zones.list().map((zone) => ({
20652
+ zoneKey: zoneFolded(zone),
20653
+ label: zone.name,
20654
+ icon: zone.icon ?? null,
20655
+ locationKeys: rooms.filter((room) => room.zoneId === zone.id).map((room) => require_named_entity_store.entityNameKey(room.name)).toSorted((a, b) => a.localeCompare(b))
20656
+ })).toSorted((a, b) => a.zoneKey.localeCompare(b.zoneKey));
20657
+ }
20658
+ async function setSiteZone(pctx, input) {
20659
+ const label = requireName(input.name, "system.site-zone-name-required", "setSiteZone");
20660
+ const zone = await pctx.rooms.zones.ensure(label, {});
20661
+ await pctx.rooms.zones.update(zone.id, (current) => {
20662
+ const next = { name: label };
20663
+ const icon = input.icon === void 0 ? current.icon : input.icon === null ? void 0 : input.icon;
20664
+ if (icon !== void 0) next.icon = icon;
20665
+ return next;
20666
+ });
20667
+ }
20668
+ /** Clear `zoneId` on every room that names `zoneId`; one record write per room. */
20669
+ async function detachRooms(pctx, zoneId, to) {
20670
+ for (const room of pctx.rooms.rooms.list()) {
20671
+ if (room.zoneId !== zoneId) continue;
20672
+ await updateRoom(pctx, {
20673
+ id: room.id,
20674
+ patch: { zoneId: to }
20675
+ });
20676
+ }
20677
+ }
20678
+ async function removeSiteZone(pctx, input) {
20679
+ const zone = pctx.rooms.zones.findByName(input.name);
20680
+ if (zone === null) return;
20681
+ await detachRooms(pctx, zone.id, null);
20682
+ await pctx.rooms.zones.delete(zone.id);
20683
+ }
20684
+ async function renameSiteZone(pctx, input) {
20685
+ const to = requireName(input.to, "system.site-zone-name-required", "renameSiteZone");
20686
+ const source = pctx.rooms.zones.findByName(input.from);
20687
+ if (source === null) return;
20688
+ const target = pctx.rooms.zones.findByName(to);
20689
+ if (target === null || target.id === source.id) {
20690
+ await pctx.rooms.zones.update(source.id, (current) => ({
20691
+ ...current,
20692
+ name: to
20693
+ }));
20694
+ return;
20695
+ }
20696
+ await detachRooms(pctx, source.id, target.id);
20697
+ await pctx.rooms.zones.delete(source.id);
20698
+ }
20699
+ async function setLocationZone(pctx, input) {
20700
+ const name = requireName(input.location, "system.location-required", "setLocationZone");
20701
+ if (input.zone === null) {
20702
+ const existing = pctx.rooms.rooms.findByName(name);
20703
+ if (existing === null || existing.zoneId === void 0) return;
20704
+ await updateRoom(pctx, {
20705
+ id: existing.id,
20706
+ patch: { zoneId: null }
20707
+ });
20708
+ return;
20709
+ }
20710
+ const zoneName = requireName(input.zone, "system.site-zone-name-required", "setLocationZone");
20711
+ const zone = await pctx.rooms.zones.ensure(zoneName, {});
20712
+ const room = await pctx.rooms.rooms.ensure(name, {});
20713
+ if (room.zoneId === zone.id) return;
20714
+ await updateRoom(pctx, {
20715
+ id: room.id,
20716
+ patch: { zoneId: zone.id }
20717
+ });
20718
+ }
20719
+ //#endregion
19468
20720
  //#region src/builtins/device-manager/device-meta-actions.ts
19469
20721
  /**
19470
20722
  * Device meta-mutation + persistence actions for the device-manager addon —
@@ -19540,6 +20792,7 @@ async function allocateDeviceId(pctx, input) {
19540
20792
  type: "generic",
19541
20793
  name: stableId,
19542
20794
  location: null,
20795
+ locationId: null,
19543
20796
  disabled: false,
19544
20797
  parentDeviceId: null,
19545
20798
  id
@@ -19634,7 +20887,16 @@ async function migrateDevice(pctx, input) {
19634
20887
  assertNoFieldClaims: async (a, b) => {
19635
20888
  try {
19636
20889
  await assertNoFieldClaims(pctx.settings, a, b);
20890
+ await assertNoCrossedSecretScopes(pctx.settings, a, b);
19637
20891
  } catch (err) {
20892
+ if (err instanceof SecretScopesCrossedError) for (const c of err.crossed) ctx.logger.warn("migrateDevice refused: secret scopes crossed", {
20893
+ tags: { deviceId: c.deviceId },
20894
+ meta: {
20895
+ sourceId: a,
20896
+ targetId: b,
20897
+ markers: c.markers
20898
+ }
20899
+ });
19638
20900
  if (err instanceof FieldClaimsBlockMigrationError) for (const blocked of err.blocked) ctx.logger.warn("migrateDevice refused: fields claimed by a customization", {
19639
20901
  tags: { deviceId: blocked.deviceId },
19640
20902
  meta: {
@@ -19647,7 +20909,8 @@ async function migrateDevice(pctx, input) {
19647
20909
  }
19648
20910
  },
19649
20911
  swapHardwareState: async (a, b) => {
19650
- const swapped = await swapHardwareState(pctx.settings, a, b);
20912
+ const forOwner = pctx.host.ctx.secrets?.forOwner;
20913
+ const swapped = await swapHardwareState(pctx.settings, a, b, forOwner === void 0 || forOwner === null ? void 0 : { forOwner });
19651
20914
  pctx.host.seedMirror(a, pctx.host.withResetSessionProbe(swapped.runtimeStateNowAtSource), "replace");
19652
20915
  pctx.host.seedMirror(b, pctx.host.withResetSessionProbe(swapped.runtimeStateNowAtTarget), "replace");
19653
20916
  ctx.logger.info("migration: hardware-scoped device state swapped", {
@@ -19658,9 +20921,11 @@ async function migrateDevice(pctx, input) {
19658
20921
  hardwareKeysToSource: swapped.hardwareKeysToSource,
19659
20922
  hardwareKeysToTarget: swapped.hardwareKeysToTarget,
19660
20923
  roleKeysKeptAtSource: swapped.roleKeysKeptAtSource,
19661
- roleKeysKeptAtTarget: swapped.roleKeysKeptAtTarget
20924
+ roleKeysKeptAtTarget: swapped.roleKeysKeptAtTarget,
20925
+ secretScopes: swapped.secretScopes
19662
20926
  }
19663
20927
  });
20928
+ return swapped.secretScopes;
19664
20929
  },
19665
20930
  forgetStreamState: async (deviceId) => {
19666
20931
  await ctx.api.streamBroker.forgetDeviceHardware.mutate({ deviceId });
@@ -19744,10 +21009,10 @@ async function registerDevice(pctx, input) {
19744
21009
  deviceType: type,
19745
21010
  features: settledFeatures
19746
21011
  });
19747
- const priorLocation = existingMeta?.location ?? null;
21012
+ const priorLocationId = existingMeta?.locationId ?? null;
19748
21013
  const resolvedParentId = parentDeviceId ?? null;
19749
21014
  const parentChanged = existingMeta !== void 0 && (existingMeta.parentDeviceId ?? null) !== resolvedParentId;
19750
- const inherited = priorLocation === null && resolvedParentId !== null && (isFirst || parentChanged) ? await resolveInheritedLocation(pctx.metaStore.rows, resolvedParentId) : null;
21015
+ const inherited = priorLocationId === null && resolvedParentId !== null && (isFirst || parentChanged) ? await resolveInheritedLocation(pctx.metaStore.rows, resolvedParentId) : null;
19751
21016
  await pctx.metaStore.rows.upsertRegistration({
19752
21017
  deviceId: id,
19753
21018
  addonId,
@@ -19755,7 +21020,7 @@ async function registerDevice(pctx, input) {
19755
21020
  type,
19756
21021
  name: resolvedName,
19757
21022
  userNamed: wasUserNamed,
19758
- location: priorLocation ?? inherited,
21023
+ locationId: priorLocationId ?? inherited?.locationId ?? null,
19759
21024
  disabled: existingMeta?.disabled ?? false,
19760
21025
  parentDeviceId: resolvedParentId,
19761
21026
  registered: true,
@@ -19771,7 +21036,7 @@ async function registerDevice(pctx, input) {
19771
21036
  if (inherited !== null) for (const descendant of await collectDescendants(pctx.metaStore, id)) {
19772
21037
  if (descendant.location !== null) continue;
19773
21038
  try {
19774
- await pctx.metaStore.rows.patch(descendant.id, { location: inherited });
21039
+ await pctx.metaStore.rows.patch(descendant.id, { locationId: inherited.locationId });
19775
21040
  descendantsFilled.push(descendant.id);
19776
21041
  } catch (err) {
19777
21042
  descendantsFailed.push({
@@ -19785,7 +21050,7 @@ async function registerDevice(pctx, input) {
19785
21050
  storedFeatures: settledFeatures,
19786
21051
  exportFingerprint: fingerprint,
19787
21052
  fingerprintChanged: existingMeta?.exportFingerprint !== fingerprint,
19788
- inheritedLocation: inherited,
21053
+ inheritedLocation: inherited?.location ?? null,
19789
21054
  inheritedDescendantIds: descendantsFilled,
19790
21055
  inheritFailed: descendantsFailed,
19791
21056
  filledRole: roleToFill
@@ -19844,6 +21109,27 @@ async function registerDevice(pctx, input) {
19844
21109
  }
19845
21110
  });
19846
21111
  }
21112
+ const declaredSecretPaths = input.secretConfigPaths ?? [];
21113
+ if (isFirstRegistration && declaredSecretPaths.length > 0) try {
21114
+ const converted = await secureRawDeclaredSecrets({
21115
+ ctx: pctx.host.ctx,
21116
+ readStored: () => pctx.settings.readDeviceStore(id),
21117
+ write: (patch) => pctx.settings.writeDeviceStore(id, patch)
21118
+ }, {
21119
+ deviceId: id,
21120
+ ownerAddonId: addonId,
21121
+ secretPaths: declaredSecretPaths
21122
+ });
21123
+ if (converted.length > 0) pctx.host.ctx.logger.info("registerDevice: secured raw secret fields from the create write", {
21124
+ tags: { deviceId: id },
21125
+ meta: { paths: [...converted] }
21126
+ });
21127
+ } catch (err) {
21128
+ pctx.host.ctx.logger.warn("registerDevice: could not secure raw secret fields from the create write", {
21129
+ tags: { deviceId: id },
21130
+ meta: { error: err instanceof Error ? err.message : String(err) }
21131
+ });
21132
+ }
19847
21133
  if (isFirstRegistration) pctx.host.ctx.eventBus.emit({
19848
21134
  id: (0, node_crypto.randomUUID)(),
19849
21135
  timestamp: /* @__PURE__ */ new Date(),
@@ -20030,8 +21316,38 @@ function removalSteps(pctx, deviceId, providerAddonId, deletedAt) {
20030
21316
  })
20031
21317
  ];
20032
21318
  }
21319
+ /**
21320
+ * The rows that belong to `deviceId` and cannot outlive it: its accessory
21321
+ * children (`parentDeviceId === id`). A row that merely LINKS to it
21322
+ * (`linkDeviceId`: an operator-picked link, or an entity of another integration
21323
+ * adopted under its own container) is a device of its own and stays.
21324
+ */
21325
+ async function ownedRowIds(pctx, deviceId) {
21326
+ return (await pctx.metaStore.rows.listByParent(deviceId)).map((row) => row.meta.id).filter((id) => id !== deviceId);
21327
+ }
21328
+ /**
21329
+ * Removing a device removes what it owns (an accessory child never outlives its
21330
+ * parent: a Reolink siren row survived its camera with a dangling
21331
+ * `parentDeviceId`). Each child goes through the same tombstoned removal, so
21332
+ * its data stores, its removal hooks and its identity fence are the parent's.
21333
+ */
20033
21334
  async function removeDevice(pctx, input) {
20034
- const { deviceId } = input;
21335
+ await removeDeviceTree(pctx, input.deviceId, /* @__PURE__ */ new Set());
21336
+ }
21337
+ async function removeDeviceTree(pctx, deviceId, seen) {
21338
+ if (seen.has(deviceId)) return;
21339
+ seen.add(deviceId);
21340
+ const ownedIds = await ownedRowIds(pctx, deviceId);
21341
+ await removeOneDevice(pctx, deviceId);
21342
+ for (const childId of ownedIds) {
21343
+ pctx.host.ctx.logger.info("removed device: cascading to an owned child", {
21344
+ tags: { deviceId: childId },
21345
+ meta: { parentDeviceId: deviceId }
21346
+ });
21347
+ await removeDeviceTree(pctx, childId, seen);
21348
+ }
21349
+ }
21350
+ async function removeOneDevice(pctx, deviceId) {
20035
21351
  const persisted = await pctx.metaStore.resolvePersistedById(deviceId);
20036
21352
  if (!persisted) return;
20037
21353
  const { addonId, stableId, meta: persistedMeta } = persisted;
@@ -20298,15 +21614,18 @@ async function collectDescendants(metaStore, rootId) {
20298
21614
  * consumers (the linked-devices picker, which suggests by location) see exactly what landed.
20299
21615
  */
20300
21616
  async function setLocation(pctx, input) {
20301
- const { deviceId, location } = input;
21617
+ const { deviceId } = input;
21618
+ const locationId = await resolveRoomId(pctx, input);
21619
+ if (locationId === void 0) throw new Error("[device-manager] setLocation: name `location` or `locationId`");
21620
+ const location = pctx.rooms.nameOf(locationId);
20302
21621
  const cascaded = [];
20303
21622
  const failed = [];
20304
21623
  await pctx.metaStore.withMetaWriteLock(async () => {
20305
21624
  if (!await pctx.metaStore.resolvePersistedById(deviceId)) throw new Error(`[device-manager] setLocation: unknown device id=${deviceId}`);
20306
- await pctx.metaStore.rows.patch(deviceId, { location });
21625
+ await pctx.metaStore.rows.patch(deviceId, { locationId });
20307
21626
  const descendants = await collectDescendants(pctx.metaStore, deviceId);
20308
21627
  for (const descendant of descendants) try {
20309
- await pctx.metaStore.rows.patch(descendant.id, { location });
21628
+ await pctx.metaStore.rows.patch(descendant.id, { locationId });
20310
21629
  cascaded.push(descendant.id);
20311
21630
  } catch (err) {
20312
21631
  failed.push({
@@ -20360,10 +21679,24 @@ async function setLocation(pctx, input) {
20360
21679
  }
20361
21680
  });
20362
21681
  }
20363
- /** The tags a write stores: normalised, `null` (the column's absent form) when none are left. */
20364
- function storedTags(tags) {
20365
- const normalized = require_tag.normalizeTags(tags);
20366
- return normalized.length === 0 ? null : normalized;
21682
+ /** The current names of tag ids; an id with no tag record is left out, never shown raw. */
21683
+ function tagNamesOf(pctx, ids) {
21684
+ if (ids === null) return null;
21685
+ return ids.flatMap((id) => {
21686
+ const name = pctx.tagNameOf(id);
21687
+ return name === null ? [] : [name];
21688
+ });
21689
+ }
21690
+ /**
21691
+ * The tag ids a write names: `tagIds` wins, else `tags` (text) is resolved through
21692
+ * `ensureTag` (D1089, accepted for one release). `[]` stays `[]`: the operator cleared
21693
+ * them, and `null` would let the kept names of an older row read back as tags again.
21694
+ */
21695
+ async function resolveTagIds(pctx, input) {
21696
+ if (input.tagIds !== void 0) return [...new Set(input.tagIds)];
21697
+ const names = require_tag.normalizeTags(input.tags ?? []);
21698
+ if (names.length === 0) return [];
21699
+ return [...new Set(await pctx.ensureTagIds(names))];
20367
21700
  }
20368
21701
  /**
20369
21702
  * Replace the operator tags of one device (D1054). Normalised on write; `[]`
@@ -20372,10 +21705,11 @@ function storedTags(tags) {
20372
21705
  */
20373
21706
  async function setTags(pctx, input) {
20374
21707
  const { deviceId } = input;
20375
- const tags = storedTags(input.tags);
21708
+ const tagIds = await resolveTagIds(pctx, input);
21709
+ const tags = tagNamesOf(pctx, tagIds);
20376
21710
  await pctx.metaStore.withMetaWriteLock(async () => {
20377
21711
  if (!await pctx.metaStore.resolvePersistedById(deviceId)) throw new Error(`[device-manager] setTags: unknown device id=${deviceId}`);
20378
- await pctx.metaStore.rows.patch(deviceId, { tags });
21712
+ await pctx.metaStore.rows.patch(deviceId, { tagIds });
20379
21713
  });
20380
21714
  pctx.host.ctx.eventBus.emit({
20381
21715
  id: (0, node_crypto.randomUUID)(),
@@ -20667,12 +22001,14 @@ async function setRoleDisplayDefaults(pctx, input) {
20667
22001
  */
20668
22002
  async function applyInitialMeta(pctx, input) {
20669
22003
  const { deviceId, name, location, tags, type, integrationId, linkDeviceId, role } = input;
22004
+ const locationId = location === void 0 && input.locationId === void 0 ? void 0 : await resolveRoomId(pctx, input);
22005
+ const tagIds = tags === void 0 && input.tagIds === void 0 ? void 0 : await resolveTagIds(pctx, input);
20670
22006
  await pctx.metaStore.withMetaWriteLock(async () => {
20671
22007
  if (!await pctx.metaStore.resolvePersistedById(deviceId)) throw new Error(`[device-manager] applyInitialMeta: unknown device id=${deviceId}`);
20672
22008
  await pctx.metaStore.rows.patch(deviceId, {
20673
22009
  ...name !== void 0 ? { name } : {},
20674
- ...location !== void 0 ? { location } : {},
20675
- ...tags !== void 0 ? { tags: storedTags(tags) } : {},
22010
+ ...locationId !== void 0 ? { locationId } : {},
22011
+ ...tagIds !== void 0 ? { tagIds } : {},
20676
22012
  ...type !== void 0 ? { type } : {},
20677
22013
  ...integrationId !== void 0 ? { integrationId } : {},
20678
22014
  ...linkDeviceId !== void 0 ? { linkDeviceId } : {},
@@ -20696,8 +22032,8 @@ async function applyInitialMeta(pctx, input) {
20696
22032
  });
20697
22033
  };
20698
22034
  if (name !== void 0) emitMetaChanged("name", name);
20699
- if (location !== void 0) emitMetaChanged("location", location);
20700
- if (tags !== void 0) emitMetaChanged("tags", storedTags(tags) ?? []);
22035
+ if (locationId !== void 0) emitMetaChanged("location", pctx.rooms.nameOf(locationId));
22036
+ if (tagIds !== void 0) emitMetaChanged("tags", tagNamesOf(pctx, tagIds) ?? []);
20701
22037
  if (type !== void 0) emitMetaChanged("type", type);
20702
22038
  if (integrationId !== void 0) emitMetaChanged("integrationId", integrationId);
20703
22039
  if (linkDeviceId !== void 0) emitMetaChanged("linkDeviceId", linkDeviceId);
@@ -20809,480 +22145,109 @@ async function loadRuntimeState(pctx, input) {
20809
22145
  return splitRuntimeBlob(pctx.host.seedMirrorFromRow(deviceId, data, pctx.settings)).native;
20810
22146
  }
20811
22147
  /**
20812
- * Union of (1) operator-curated location registry and (2) labels
20813
- * currently in use on persisted devices. Case-insensitive
20814
- * dedupe (preserves the first-seen casing). Sorted
20815
- * case-insensitively for stable UI. Drives the Device Info
20816
- * location autocomplete.
20817
- */
20818
- async function listLocations(pctx) {
20819
- const locations = (await pctx.metaStore.readStore()).locations ?? [];
20820
- const seen = /* @__PURE__ */ new Map();
20821
- const consider = (raw) => {
20822
- if (typeof raw !== "string") return;
20823
- const trimmed = raw.trim();
20824
- if (trimmed.length === 0) return;
20825
- const key = trimmed.toLowerCase();
20826
- if (!seen.has(key)) seen.set(key, trimmed);
20827
- };
20828
- for (const label of locations) consider(label);
20829
- for (const row of await pctx.metaStore.rows.listAll()) consider(row.meta.location);
20830
- return [...seen.values()].toSorted((a, b) => a.localeCompare(b, void 0, { sensitivity: "base" }));
20831
- }
20832
- /**
20833
- * Add a label to the curated location registry. Idempotent:
20834
- * existing entries (case-insensitive match) are silently kept.
20835
- * Empty / whitespace-only inputs throw — operators must supply a
20836
- * meaningful label.
20837
- */
20838
- async function addLocation(pctx, input) {
20839
- const trimmed = input.name.trim();
20840
- if (trimmed.length === 0) throw require_camstack_error.userError("system.location-name-required", void 0, "[device-manager] addLocation: name must be non-empty");
20841
- await pctx.bindingsDeps.withAddonStoreWriteLock(async () => {
20842
- const current = (await pctx.metaStore.readStore()).locations ?? [];
20843
- if (current.some((l) => l.toLowerCase() === trimmed.toLowerCase())) return;
20844
- await pctx.settings.writeAddonStore({ locations: [...current, trimmed] });
20845
- });
20846
- }
20847
- /**
20848
- * Every location that carries an icon, as `(locationKey, icon)` pairs.
20849
- *
20850
- * ADDITIVE beside `listLocations`, which still answers `string[]` — the
20851
- * autocomplete, the HA adoption import and the recorder all read a list of
20852
- * LABELS and a shape change there would break every one of them. A surface
20853
- * that wants icons asks for them and joins on `locationIconKey`.
20854
- *
20855
- * Returns only what was actually stored. A location with no assignment is
20856
- * ABSENT, never `map-pin`: the fallback belongs to the renderer
20857
- * (`resolveIconKey`), and folding it in here would make "the operator
20858
- * picked the pin" indistinguishable from "the operator picked nothing" —
20859
- * which is the difference an icon picker has to draw.
20860
- */
20861
- async function listLocationIcons(pctx) {
20862
- const icons = (await pctx.metaStore.readStore()).locationIcons ?? {};
20863
- return Object.entries(icons).map(([locationKey, icon]) => ({
20864
- locationKey,
20865
- icon
20866
- })).toSorted((a, b) => a.locationKey.localeCompare(b.locationKey));
20867
- }
20868
- /**
20869
- * Set (or clear) the icon of a location label.
20870
- *
20871
- * Keyed on `locationIconKey` — trimmed + lower-cased, the equality the
20872
- * registry matches on everywhere — so a case-only rename keeps the icon and
20873
- * two spellings of one room can never carry two different icons.
20874
- *
20875
- * The label need NOT be registered: `setLocation` accepts a free-form string
20876
- * and `listLocations` folds in whatever devices carry, so requiring
20877
- * registration here would leave exactly the ad-hoc rooms unable to have an
20878
- * icon. An empty label throws — there is no room to name.
20879
- *
20880
- * Same read-modify-write and same lock as `addLocation`: the map is one key of
20881
- * the addon store, and `writeAddonStore` re-inserts the whole key range, so an
20882
- * unordered write carries a stale copy of every other key.
22148
+ * `deviceManager.repairMigrationSecrets` — the live repair for a pair a
22149
+ * migration left with crossed keychain scopes (see `repairCrossedSecretScopes`).
22150
+ * Under the meta write lock the migration itself ran under: a config write
22151
+ * racing it would read the half this repair is moving. The running devices
22152
+ * keep their loaded config until the next reload.
20883
22153
  */
20884
- async function setLocationIcon(pctx, input) {
20885
- const trimmed = input.location.trim();
20886
- if (trimmed.length === 0) throw require_camstack_error.userError("system.location-required", void 0, "[device-manager] setLocationIcon: location must be non-empty");
20887
- const key = require_addon_settings_cap.locationIconKey(trimmed);
20888
- await pctx.bindingsDeps.withAddonStoreWriteLock(async () => {
20889
- const icons = (await pctx.metaStore.readStore()).locationIcons ?? {};
20890
- if (input.icon === null) {
20891
- if (!(key in icons)) return;
20892
- const { [key]: _cleared, ...kept } = icons;
20893
- await pctx.settings.writeAddonStore({ locationIcons: kept });
20894
- return;
20895
- }
20896
- if (icons[key] === input.icon) return;
20897
- await pctx.settings.writeAddonStore({ locationIcons: {
20898
- ...icons,
20899
- [key]: input.icon
20900
- } });
20901
- });
20902
- }
20903
- /**
20904
- * Every location that carries a description, sorted by key.
20905
- *
20906
- * Only what was WRITTEN — a location with no description is absent, and the
20907
- * digest then tells the model the location name alone, exactly as it did
20908
- * before descriptions existed.
20909
- */
20910
- async function listLocationDescriptions(pctx) {
20911
- const descriptions = (await pctx.metaStore.readStore()).locationDescriptions ?? {};
20912
- return Object.entries(descriptions).map(([locationKey, description]) => ({
20913
- locationKey,
20914
- description
20915
- })).toSorted((a, b) => a.locationKey.localeCompare(b.locationKey));
20916
- }
20917
- /**
20918
- * Set (or clear) a location's description.
20919
- *
20920
- * A BLANK description clears, exactly as `null` does: an empty line handed to
20921
- * a vision model costs attention and says nothing, so the two must not be
20922
- * different states. The label is folded with `locationIconKey` — the same key
20923
- * the icon uses, which is the whole point of this living here.
20924
- *
20925
- * Same read-modify-write and same lock as `setLocationIcon`; `writeAddonStore`
20926
- * re-inserts the whole key range, so an unordered write carries a stale copy
20927
- * of every other key.
20928
- */
20929
- async function setLocationDescription(pctx, input) {
20930
- const trimmed = input.location.trim();
20931
- if (trimmed.length === 0) throw new Error("[device-manager] setLocationDescription: location must be non-empty");
20932
- const key = require_addon_settings_cap.locationIconKey(trimmed);
20933
- const text = input.description === null ? "" : input.description.trim();
20934
- await pctx.bindingsDeps.withAddonStoreWriteLock(async () => {
20935
- const descriptions = (await pctx.metaStore.readStore()).locationDescriptions ?? {};
20936
- if (text.length === 0) {
20937
- if (!(key in descriptions)) return;
20938
- const { [key]: _cleared, ...kept } = descriptions;
20939
- await pctx.settings.writeAddonStore({ locationDescriptions: kept });
20940
- return;
22154
+ async function repairMigrationSecrets(pctx, input) {
22155
+ const { deviceA, deviceB, apply } = input;
22156
+ const ctx = pctx.host.ctx;
22157
+ const forOwner = ctx.secrets?.forOwner ?? null;
22158
+ const report = await pctx.metaStore.withMetaWriteLock(() => repairCrossedSecretScopes(pctx.settings, forOwner === null ? void 0 : { forOwner }, deviceA, deviceB, apply));
22159
+ for (const deviceId of [deviceA, deviceB]) ctx.logger.info("repairMigrationSecrets", {
22160
+ tags: { deviceId },
22161
+ meta: {
22162
+ deviceA,
22163
+ deviceB,
22164
+ apply,
22165
+ outcome: report.outcome
20941
22166
  }
20942
- if (descriptions[key] === text) return;
20943
- await pctx.settings.writeAddonStore({ locationDescriptions: {
20944
- ...descriptions,
20945
- [key]: text
20946
- } });
20947
- });
20948
- }
20949
- /**
20950
- * Every site zone, with its rooms, sorted by key.
20951
- *
20952
- * Membership is inverted HERE rather than stored both ways: the store keeps
20953
- * `location → zone`, which is what makes "one zone per room" structural, and a
20954
- * second copy keyed the other way is a second thing that can disagree with the
20955
- * first.
20956
- */
20957
- async function listSiteZones(pctx) {
20958
- const store = await pctx.metaStore.readStore();
20959
- const zones = store.siteZones ?? {};
20960
- const membership = store.locationZones ?? {};
20961
- const rooms = /* @__PURE__ */ new Map();
20962
- for (const [locationKey, zoneKey] of Object.entries(membership)) {
20963
- const list = rooms.get(zoneKey);
20964
- if (list === void 0) rooms.set(zoneKey, [locationKey]);
20965
- else list.push(locationKey);
20966
- }
20967
- return Object.entries(zones).map(([zoneKey, record]) => ({
20968
- zoneKey,
20969
- label: record.label,
20970
- icon: record.icon ?? null,
20971
- locationKeys: (rooms.get(zoneKey) ?? []).toSorted((a, b) => a.localeCompare(b))
20972
- })).toSorted((a, b) => a.zoneKey.localeCompare(b.zoneKey));
20973
- }
20974
- /**
20975
- * Create a zone, or set the icon of one that already exists.
20976
- *
20977
- * `icon: null` clears the icon and KEEPS the zone. Conflating the two would
20978
- * make a mis-click on "no icon" delete every room's membership — the icon is a
20979
- * decoration and the grouping is the data.
20980
- *
20981
- * `icon` OMITTED leaves whatever icon is there: creating a zone from a screen
20982
- * with no picker must not silently clear the glyph a previous screen set.
20983
- */
20984
- async function setSiteZone(pctx, input) {
20985
- const label = input.name.trim();
20986
- if (label.length === 0) throw require_camstack_error.userError("system.site-zone-name-required", void 0, "[device-manager] setSiteZone: name must be non-empty");
20987
- const key = require_device_manager_cap.siteZoneKey(label);
20988
- await pctx.bindingsDeps.withAddonStoreWriteLock(async () => {
20989
- const zones = (await pctx.metaStore.readStore()).siteZones ?? {};
20990
- const existing = zones[key];
20991
- const icon = input.icon === void 0 ? existing?.icon : input.icon === null ? void 0 : input.icon;
20992
- const next = icon === void 0 ? { label } : {
20993
- label,
20994
- icon
20995
- };
20996
- if (existing?.label === next.label && existing.icon === next.icon) return;
20997
- await pctx.settings.writeAddonStore({ siteZones: {
20998
- ...zones,
20999
- [key]: next
21000
- } });
21001
- });
21002
- }
21003
- /**
21004
- * Delete a zone. Its LOCATIONS survive, unattached.
21005
- *
21006
- * Deleting a grouping must never delete what was grouped — the rooms exist
21007
- * independently and the devices in them were never touched to begin with.
21008
- */
21009
- async function removeSiteZone(pctx, input) {
21010
- const key = require_device_manager_cap.siteZoneKey(input.name);
21011
- await pctx.bindingsDeps.withAddonStoreWriteLock(async () => {
21012
- const store = await pctx.metaStore.readStore();
21013
- const zones = store.siteZones ?? {};
21014
- const membership = store.locationZones ?? {};
21015
- const hadZone = key in zones;
21016
- const orphaned = Object.entries(membership).filter(([, zoneKey]) => zoneKey === key);
21017
- if (!hadZone && orphaned.length === 0) return;
21018
- const { [key]: _dropped, ...keptZones } = zones;
21019
- const keptMembership = Object.fromEntries(Object.entries(membership).filter(([, zoneKey]) => zoneKey !== key));
21020
- await pctx.settings.writeAddonStore({
21021
- ...hadZone ? { siteZones: keptZones } : {},
21022
- ...orphaned.length > 0 ? { locationZones: keptMembership } : {}
21023
- });
21024
- });
21025
- }
21026
- /**
21027
- * Rename a zone, carrying its icon AND every room in it.
21028
- *
21029
- * It exists so that renaming is not delete-then-recreate, which drops both.
21030
- * A rename onto an existing zone MERGES: the target keeps its own icon and the
21031
- * rooms are unioned, the same rule `renameLocation` follows.
21032
- */
21033
- async function renameSiteZone(pctx, input) {
21034
- const toLabel = input.to.trim();
21035
- if (toLabel.length === 0) throw new Error("[device-manager] renameSiteZone: target name must be non-empty");
21036
- const fromKey = require_device_manager_cap.siteZoneKey(input.from);
21037
- const toKey = require_device_manager_cap.siteZoneKey(toLabel);
21038
- await pctx.bindingsDeps.withAddonStoreWriteLock(async () => {
21039
- const store = await pctx.metaStore.readStore();
21040
- const zones = store.siteZones ?? {};
21041
- const moved = zones[fromKey];
21042
- if (moved === void 0) return;
21043
- const { [fromKey]: _dropped, ...rest } = zones;
21044
- const target = rest[toKey];
21045
- const nextZones = {
21046
- ...rest,
21047
- [toKey]: target ?? (moved.icon === void 0 ? { label: toLabel } : {
21048
- label: toLabel,
21049
- icon: moved.icon
21050
- })
21051
- };
21052
- const membership = store.locationZones ?? {};
21053
- const nextMembership = Object.fromEntries(Object.entries(membership).map(([locationKey, zoneKey]) => [locationKey, zoneKey === fromKey ? toKey : zoneKey]));
21054
- await pctx.settings.writeAddonStore({
21055
- siteZones: nextZones,
21056
- locationZones: nextMembership
21057
- });
21058
22167
  });
22168
+ return report;
21059
22169
  }
22170
+ //#endregion
22171
+ //#region src/builtins/device-manager/room-store.ts
21060
22172
  /**
21061
- * Put a location in a zone, or take it out with `zone: null`.
22173
+ * The rooms and site zones of the property, as records with an id (D1089).
21062
22174
  *
21063
- * ONE slot per location, so a second call moves the room rather than listing it
21064
- * twice. The zone is created if it does not exist — a screen that assigns
21065
- * before creating is a normal order, and refusing it would be the only place in
21066
- * this registry that demands registration first.
22175
+ * `rooms` and `zones` are record kinds the device manager owns; a device meta
22176
+ * carries `locationId`, a room carries `zoneId`. The store keeps both in memory
22177
+ * once read — a device read resolves a room name through {@link RoomStore.nameOf}
22178
+ * without a query, and an unknown id reads as unset.
21067
22179
  */
21068
- async function setLocationZone(pctx, input) {
21069
- const location = input.location.trim();
21070
- if (location.length === 0) throw new Error("[device-manager] setLocationZone: location must be non-empty");
21071
- const locationKey = require_addon_settings_cap.locationIconKey(location);
21072
- const label = input.zone === null ? null : input.zone.trim();
21073
- if (label !== null && label.length === 0) throw new Error("[device-manager] setLocationZone: zone must be non-empty or null");
21074
- await pctx.bindingsDeps.withAddonStoreWriteLock(async () => {
21075
- const store = await pctx.metaStore.readStore();
21076
- const membership = store.locationZones ?? {};
21077
- if (label === null) {
21078
- if (!(locationKey in membership)) return;
21079
- const { [locationKey]: _cleared, ...kept } = membership;
21080
- await pctx.settings.writeAddonStore({ locationZones: kept });
21081
- return;
21082
- }
21083
- const zoneKey = require_device_manager_cap.siteZoneKey(label);
21084
- const zones = store.siteZones ?? {};
21085
- const needsZone = !(zoneKey in zones);
21086
- if (membership[locationKey] === zoneKey && !needsZone) return;
21087
- await pctx.settings.writeAddonStore({
21088
- ...needsZone ? { siteZones: {
21089
- ...zones,
21090
- [zoneKey]: { label }
21091
- } } : {},
21092
- locationZones: {
21093
- ...membership,
21094
- [locationKey]: zoneKey
22180
+ var RoomStore = class RoomStore {
22181
+ rooms;
22182
+ zones;
22183
+ constructor(rooms, zones) {
22184
+ this.rooms = rooms;
22185
+ this.zones = zones;
22186
+ }
22187
+ static of(records) {
22188
+ return new RoomStore(new require_named_entity_store.NamedEntityStore("room", records.kind(require_record_kinds.deviceManagerRecordKinds.rooms), (body) => require_device_manager_cap.RoomBodySchema.parse(body)), new require_named_entity_store.NamedEntityStore("zone", records.kind(require_record_kinds.deviceManagerRecordKinds.zones), (body) => require_device_manager_cap.ZoneBodySchema.parse(body)));
22189
+ }
22190
+ async load() {
22191
+ await this.rooms.load();
22192
+ await this.zones.load();
22193
+ }
22194
+ /** The current name of room `id`; `null` when unset or unknown. */
22195
+ nameOf(id) {
22196
+ return this.rooms.nameOf(id);
22197
+ }
22198
+ };
22199
+ var TagNames = class {
22200
+ source;
22201
+ logger;
22202
+ now;
22203
+ names = /* @__PURE__ */ new Map();
22204
+ refreshedAt = 0;
22205
+ inFlight = null;
22206
+ constructor(source, logger, now = Date.now) {
22207
+ this.source = source;
22208
+ this.logger = logger;
22209
+ this.now = now;
22210
+ }
22211
+ nameOf(id) {
22212
+ return this.names.get(id) ?? null;
22213
+ }
22214
+ /** Revalidate when older than the window. A failed read keeps the last answer. */
22215
+ async fresh() {
22216
+ if (this.source === null) return;
22217
+ if (this.now() - this.refreshedAt < 5e3) return;
22218
+ await this.refresh();
22219
+ }
22220
+ async refresh() {
22221
+ const source = this.source;
22222
+ if (source === null) return;
22223
+ if (this.inFlight !== null) return this.inFlight;
22224
+ const run = (async () => {
22225
+ try {
22226
+ const tags = await source.list();
22227
+ this.names = new Map(tags.map((tag) => [tag.id, tag.name]));
22228
+ this.refreshedAt = this.now();
22229
+ } catch (err) {
22230
+ this.logger.warn("tag names not refreshed — keeping the last answer", { meta: { error: require_scoped_settings.errMsg(err) } });
22231
+ } finally {
22232
+ this.inFlight = null;
21095
22233
  }
21096
- });
21097
- });
21098
- }
21099
- /**
21100
- * Move a location's zone membership from one key to another, for
21101
- * `renameLocation`. Same shape as the icon and description movers.
21102
- */
21103
- function renameLocationZone(membership, fromKey, toKey) {
21104
- const moved = membership[fromKey];
21105
- if (moved === void 0) return null;
21106
- if (fromKey === toKey) return null;
21107
- const { [fromKey]: _dropped, ...rest } = membership;
21108
- return toKey in rest ? rest : {
21109
- ...rest,
21110
- [toKey]: moved
21111
- };
21112
- }
21113
- /**
21114
- * Move a location's description from one key to another, for `renameLocation`.
21115
- *
21116
- * Identical rule to {@link renameLocationIcon}, deliberately: a merge keeps the
21117
- * TARGET's description, because renaming "Sala" into "Hall" moves devices
21118
- * into Hall and does not re-describe it. Split from the icon mover only
21119
- * because the value types differ; if one ever changes, the other must.
21120
- */
21121
- function renameLocationDescription(descriptions, fromKey, toKey) {
21122
- const moved = descriptions[fromKey];
21123
- if (moved === void 0) return null;
21124
- if (fromKey === toKey) return null;
21125
- const { [fromKey]: _dropped, ...rest } = descriptions;
21126
- return toKey in rest ? rest : {
21127
- ...rest,
21128
- [toKey]: moved
21129
- };
21130
- }
21131
- /**
21132
- * Move a location's icon from one key to another, for `renameLocation`.
21133
- *
21134
- * Returns `null` when NOTHING changes, so the caller can leave the key out of
21135
- * its `writeAddonStore` patch instead of re-writing an identical map.
21136
- *
21137
- * A rename onto a room that already has an icon is a MERGE, and the surviving
21138
- * room keeps its own: the operator renaming "Sala" into "Hall" is moving
21139
- * devices into Hall, not restyling it. The source key is dropped either way.
21140
- * Pure — builds a new record, mutates nothing.
21141
- */
21142
- function renameLocationIcon(icons, fromKey, toKey) {
21143
- const moved = icons[fromKey];
21144
- if (moved === void 0) return null;
21145
- if (fromKey === toKey) return null;
21146
- const { [fromKey]: _dropped, ...rest } = icons;
21147
- return toKey in rest ? rest : {
21148
- ...rest,
21149
- [toKey]: moved
21150
- };
21151
- }
21152
- /**
21153
- * Remove a label from the curated registry. Match is
21154
- * case-insensitive. Devices that still reference this label keep
21155
- * their `meta.location` value (the registry is a suggestion
21156
- * list, not a foreign key) — pass `cascade: true` to also clear
21157
- * `setLocation` on every device that referenced this exact
21158
- * label. Cascade only matches case-insensitively + trimmed, same
21159
- * as the registry equality check.
21160
- */
21161
- /**
21162
- * Rename a room in ONE server operation: the registry label in place, then
21163
- * every device that carried it.
21164
- *
21165
- * The lock order is the one `removeLocation` documents and must not be
21166
- * "simplified": the registry edit takes the addon-store lock and RELEASES it
21167
- * before the cascade takes the meta lock. Holding both, in that order, is the
21168
- * reverse of `allocateNextDeviceId`'s meta ⊃ addon-store nesting — the pair
21169
- * that deadlocks.
21170
- *
21171
- * Validation happens BEFORE either lock. A rename that throws halfway is the
21172
- * exact failure this function exists to remove, so an empty target must be
21173
- * refused while nothing has been written yet.
21174
- */
21175
- async function renameLocation(pctx, input) {
21176
- const from = input.from.trim();
21177
- const to = input.to.trim();
21178
- if (from.length === 0) throw new Error("[device-manager] renameLocation: `from` must be non-empty");
21179
- if (to.length === 0) throw new Error("[device-manager] renameLocation: `to` must be non-empty");
21180
- const fromKey = from.toLowerCase();
21181
- const toKey = to.toLowerCase();
21182
- await pctx.bindingsDeps.withAddonStoreWriteLock(async () => {
21183
- const store = await pctx.metaStore.readStore();
21184
- const current = store.locations ?? [];
21185
- const registered = current.some((l) => l.trim().toLowerCase() === fromKey);
21186
- const movedIcons = renameLocationIcon(store.locationIcons ?? {}, fromKey, toKey);
21187
- const movedDescriptions = renameLocationDescription(store.locationDescriptions ?? {}, fromKey, toKey);
21188
- const movedZones = renameLocationZone(store.locationZones ?? {}, fromKey, toKey);
21189
- if (!registered && movedIcons === null && movedDescriptions === null && movedZones === null) return;
21190
- const kept = current.filter((l) => {
21191
- const key = l.trim().toLowerCase();
21192
- return key !== fromKey && key !== toKey;
21193
- });
21194
- await pctx.settings.writeAddonStore({
21195
- ...registered ? { locations: [...kept, to] } : {},
21196
- ...movedIcons !== null ? { locationIcons: movedIcons } : {},
21197
- ...movedDescriptions !== null ? { locationDescriptions: movedDescriptions } : {},
21198
- ...movedZones !== null ? { locationZones: movedZones } : {}
21199
- });
21200
- });
21201
- const moved = await pctx.metaStore.withMetaWriteLock(async () => {
21202
- const out = [];
21203
- for (const row of await pctx.metaStore.rows.listAll()) {
21204
- const location = row.meta.location;
21205
- if (typeof location !== "string") continue;
21206
- if (location.trim().toLowerCase() !== fromKey) continue;
21207
- await pctx.metaStore.rows.patch(row.meta.id, { location: to });
21208
- out.push(row.meta.id);
21209
- }
21210
- return out;
21211
- });
21212
- for (const deviceId of moved) pctx.host.ctx.eventBus.emit({
21213
- id: (0, node_crypto.randomUUID)(),
21214
- timestamp: /* @__PURE__ */ new Date(),
21215
- source: {
21216
- type: "device",
21217
- id: deviceId
21218
- },
21219
- category: require_base_addon.EventCategory.DeviceMetaChanged,
21220
- data: {
21221
- deviceId,
21222
- field: "location",
21223
- value: to
21224
- }
21225
- });
21226
- pctx.host.ctx.logger.info("renameLocation: room renamed", { meta: {
21227
- from,
21228
- to,
21229
- moved: moved.length
21230
- } });
21231
- return { moved: moved.length };
21232
- }
21233
- async function removeLocation(pctx, input) {
21234
- const trimmed = input.name.trim();
21235
- if (trimmed.length === 0) return;
21236
- await pctx.bindingsDeps.withAddonStoreWriteLock(async () => {
21237
- const store = await pctx.metaStore.readStore();
21238
- const current = store.locations ?? [];
21239
- const key = require_addon_settings_cap.locationIconKey(trimmed);
21240
- const remaining = current.filter((l) => l.toLowerCase() !== key);
21241
- const droppedLabel = remaining.length !== current.length;
21242
- const icons = store.locationIcons ?? {};
21243
- const droppedIcon = key in icons;
21244
- const descriptions = store.locationDescriptions ?? {};
21245
- const droppedDescription = key in descriptions;
21246
- const membership = store.locationZones ?? {};
21247
- const droppedZone = key in membership;
21248
- if (!droppedLabel && !droppedIcon && !droppedDescription && !droppedZone) return;
21249
- const { [key]: _removedIcon, ...keptIcons } = icons;
21250
- const { [key]: _removedDescription, ...keptDescriptions } = descriptions;
21251
- const { [key]: _removedZone, ...keptMembership } = membership;
21252
- await pctx.settings.writeAddonStore({
21253
- ...droppedLabel ? { locations: remaining } : {},
21254
- ...droppedIcon ? { locationIcons: keptIcons } : {},
21255
- ...droppedDescription ? { locationDescriptions: keptDescriptions } : {},
21256
- ...droppedZone ? { locationZones: keptMembership } : {}
21257
- });
21258
- });
21259
- if (input.cascade !== true) return;
21260
- const cleared = await pctx.metaStore.withMetaWriteLock(async () => {
21261
- const out = [];
21262
- for (const row of await pctx.metaStore.rows.listAll()) {
21263
- const location = row.meta.location;
21264
- if (typeof location !== "string") continue;
21265
- if (location.trim().toLowerCase() !== trimmed.toLowerCase()) continue;
21266
- await pctx.metaStore.rows.patch(row.meta.id, { location: null });
21267
- out.push(row.meta.id);
21268
- }
21269
- return out;
21270
- });
21271
- for (const deviceId of cleared) pctx.host.ctx.eventBus.emit({
21272
- id: (0, node_crypto.randomUUID)(),
21273
- timestamp: /* @__PURE__ */ new Date(),
21274
- source: {
21275
- type: "device",
21276
- id: deviceId
21277
- },
21278
- category: require_base_addon.EventCategory.DeviceMetaChanged,
21279
- data: {
21280
- deviceId,
21281
- field: "location",
21282
- value: null
22234
+ })();
22235
+ this.inFlight = run;
22236
+ return run;
22237
+ }
22238
+ /** Resolve text names to ids through `ensureTag`; a name no tag cap can mint is left out. */
22239
+ async ensureIds(names) {
22240
+ const source = this.source;
22241
+ if (source === null) return [];
22242
+ const ids = [];
22243
+ for (const name of names) {
22244
+ const tag = await source.ensure(name);
22245
+ ids.push(tag.id);
21283
22246
  }
21284
- });
21285
- }
22247
+ await this.refresh();
22248
+ return ids;
22249
+ }
22250
+ };
21286
22251
  //#endregion
21287
22252
  //#region src/builtins/device-manager/device-identifiers-action.ts
21288
22253
  /**
@@ -21732,7 +22697,6 @@ var IdentityLinkReconciler = class {
21732
22697
  };
21733
22698
  //#endregion
21734
22699
  //#region src/builtins/device-manager/identity-links-store.ts
21735
- var import_read_all_rows = require_read_all_rows$1.require_read_all_rows();
21736
22700
  var IdentityLinksStore = class IdentityLinksStore {
21737
22701
  kind;
21738
22702
  links = null;
@@ -21740,7 +22704,7 @@ var IdentityLinksStore = class IdentityLinksStore {
21740
22704
  this.kind = kind;
21741
22705
  }
21742
22706
  static of(records) {
21743
- return new IdentityLinksStore(records.kind(require_device_row_store.deviceManagerRecordKinds["identity-links"]));
22707
+ return new IdentityLinksStore(records.kind(require_record_kinds.deviceManagerRecordKinds["identity-links"]));
21744
22708
  }
21745
22709
  async load() {
21746
22710
  const rows = await (0, import_read_all_rows.readAllRows)(this.kind);
@@ -22276,7 +23240,7 @@ var DeviceTemplateHost = class {
22276
23240
  }
22277
23241
  }
22278
23242
  const entries = [...rows.values()];
22279
- const mirror = new require_prefix_walk.ConditionMirror(templateMirrorSources(entries));
23243
+ const mirror = new require_named_entity_store.ConditionMirror(templateMirrorSources(entries));
22280
23244
  const report = await mirror.refresh({
22281
23245
  fetchSlice: (deviceId, cap) => this.deps.fetchSlice(deviceId, cap),
22282
23246
  fetchStableIds: async () => /* @__PURE__ */ new Map()
@@ -22816,130 +23780,6 @@ var DeviceTemplateActions = class {
22816
23780
  }
22817
23781
  };
22818
23782
  //#endregion
22819
- //#region src/builtins/device-manager/device-meta-types.ts
22820
- /**
22821
- * Decode the raw `ctx.settings.readAddonStore()` record into {@link AddonStore}.
22822
- *
22823
- * A field of the wrong shape reads as ABSENT rather than being trusted through
22824
- * a cast: the store is JSON on disk and a hand-edit or a partial restore must
22825
- * cost the caller its default, never a downstream `TypeError`.
22826
- */
22827
- function decodeAddonStore(raw) {
22828
- const nextDeviceId = raw["nextDeviceId"];
22829
- const locations = raw["locations"];
22830
- const roleDisplayDefaults = raw["roleDisplayDefaults"];
22831
- const locationIcons = decodeLocationIcons(raw["locationIcons"]);
22832
- const locationDescriptions = decodeLocationDescriptions(raw["locationDescriptions"]);
22833
- const siteZones = decodeSiteZones(raw["siteZones"]);
22834
- const locationZones = decodeStringMap(raw["locationZones"]);
22835
- return {
22836
- ...typeof nextDeviceId === "number" && Number.isFinite(nextDeviceId) ? { nextDeviceId } : {},
22837
- ...Array.isArray(locations) ? { locations: locations.filter((l) => typeof l === "string") } : {},
22838
- ...isRoleDisplayDefaults(roleDisplayDefaults) ? { roleDisplayDefaults } : {},
22839
- ...locationIcons !== null ? { locationIcons } : {},
22840
- ...locationDescriptions !== null ? { locationDescriptions } : {},
22841
- ...siteZones !== null ? { siteZones } : {},
22842
- ...locationZones !== null ? { locationZones } : {}
22843
- };
22844
- }
22845
- /**
22846
- * Decode the `locationIcons` map, dropping every entry whose value is not a
22847
- * member of the closed vocabulary.
22848
- *
22849
- * Dropping, not passing through: the icon's whole point is that both surfaces
22850
- * can draw it, and an id from a hand-edit or a newer hub is exactly the value
22851
- * that draws nothing. Absent reads as "no icon chosen", which every renderer
22852
- * already degrades to the fallback pin. Returns `null` when the key itself is
22853
- * absent or of the wrong shape, so the field stays OMITTED rather than being
22854
- * written back as an empty object.
22855
- */
22856
- function decodeLocationIcons(raw) {
22857
- if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return null;
22858
- const out = {};
22859
- for (const [key, value] of Object.entries(raw)) {
22860
- const icon = require_tag.canonicalIconKey(value);
22861
- if (icon === void 0) continue;
22862
- out[key] = icon;
22863
- }
22864
- return out;
22865
- }
22866
- /**
22867
- * Decode the `locationDescriptions` map, dropping every entry that is not a
22868
- * non-blank string.
22869
- *
22870
- * Same posture as the icons: a blank description and a missing one are the
22871
- * same instruction to every reader, and storing the first would send an empty
22872
- * line to a vision model. Over-long text is TRUNCATED rather than dropped —
22873
- * losing the whole description because a hand-edit ran long is a worse answer
22874
- * than losing its tail.
22875
- */
22876
- function decodeLocationDescriptions(raw) {
22877
- if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return null;
22878
- const out = {};
22879
- for (const [key, value] of Object.entries(raw)) {
22880
- if (typeof value !== "string") continue;
22881
- const text = value.trim();
22882
- if (text.length === 0) continue;
22883
- out[key] = text.slice(0, 400);
22884
- }
22885
- return out;
22886
- }
22887
- /**
22888
- * Decode the zone registry, dropping any entry without a usable label.
22889
- *
22890
- * A zone whose label did not survive a hand-edit cannot be shown or renamed —
22891
- * it would be a row the operator can see the effects of and never name. An
22892
- * icon outside the vocabulary is dropped on its own, leaving the zone: losing
22893
- * a glyph is a smaller loss than losing the grouping.
22894
- */
22895
- function decodeSiteZones(raw) {
22896
- if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return null;
22897
- const out = {};
22898
- for (const [key, value] of Object.entries(raw)) {
22899
- if (value === null || typeof value !== "object" || Array.isArray(value)) continue;
22900
- const rec = value;
22901
- const label = typeof rec["label"] === "string" ? rec["label"].trim() : "";
22902
- if (label.length === 0) continue;
22903
- const icon = require_tag.canonicalIconKey(rec["icon"]);
22904
- out[key] = icon === void 0 ? { label } : {
22905
- label,
22906
- icon
22907
- };
22908
- }
22909
- return out;
22910
- }
22911
- /** Decode a plain `string → string` map, dropping anything else. */
22912
- function decodeStringMap(raw) {
22913
- if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return null;
22914
- const out = {};
22915
- for (const [key, value] of Object.entries(raw)) {
22916
- if (typeof value !== "string" || value.trim().length === 0) continue;
22917
- out[key] = value;
22918
- }
22919
- return out;
22920
- }
22921
- function isRoleDisplayDefaults(value) {
22922
- return value !== null && typeof value === "object" && !Array.isArray(value);
22923
- }
22924
- //#endregion
22925
- //#region src/builtins/device-manager/write-lock.ts
22926
- function createWriteLock() {
22927
- let chain = Promise.resolve();
22928
- return async (fn) => {
22929
- const previous = chain;
22930
- let release = () => {};
22931
- chain = new Promise((resolve) => {
22932
- release = resolve;
22933
- });
22934
- try {
22935
- await previous.catch(() => {});
22936
- return await fn();
22937
- } finally {
22938
- release();
22939
- }
22940
- };
22941
- }
22942
- //#endregion
22943
23783
  //#region src/builtins/device-manager/device-meta-store.ts
22944
23784
  var DeviceMetaStore = class {
22945
23785
  settings;
@@ -22952,7 +23792,7 @@ var DeviceMetaStore = class {
22952
23792
  * ownership without awaiting. Kept in sync with every register/remove and
22953
23793
  * warmed from persistence on boot. */
22954
23794
  idToAddonId = /* @__PURE__ */ new Map();
22955
- constructor(settings, registry, rows, withAddonStoreWriteLock = createWriteLock()) {
23795
+ constructor(settings, registry, rows, withAddonStoreWriteLock = require_named_entity_store.createWriteLock()) {
22956
23796
  this.settings = settings;
22957
23797
  this.registry = registry;
22958
23798
  this.rows = rows;
@@ -22987,7 +23827,7 @@ var DeviceMetaStore = class {
22987
23827
  this.inFlightRead = read;
22988
23828
  return read;
22989
23829
  };
22990
- withMetaWriteLock = createWriteLock();
23830
+ withMetaWriteLock = require_named_entity_store.createWriteLock();
22991
23831
  /** The whole persisted row for one device, or `null`. */
22992
23832
  getRow = async (deviceId) => this.rows.get(deviceId);
22993
23833
  /**
@@ -23069,7 +23909,7 @@ var DeviceTombstoneStore = class DeviceTombstoneStore {
23069
23909
  }
23070
23910
  static of(records, logger) {
23071
23911
  return new DeviceTombstoneStore({
23072
- kind: records.kind(require_device_row_store.deviceManagerRecordKinds.tombstones),
23912
+ kind: records.kind(require_record_kinds.deviceManagerRecordKinds.tombstones),
23073
23913
  logger
23074
23914
  });
23075
23915
  }
@@ -23232,7 +24072,7 @@ var DiscoveryProposalStore = class DiscoveryProposalStore {
23232
24072
  this.now = now;
23233
24073
  }
23234
24074
  static of(records, now) {
23235
- return new DiscoveryProposalStore(records.kind(require_device_row_store.deviceManagerRecordKinds["discovery-proposals"]), now);
24075
+ return new DiscoveryProposalStore(records.kind(require_record_kinds.deviceManagerRecordKinds["discovery-proposals"]), now);
23236
24076
  }
23237
24077
  /** Record what a provider classified. Returns how many proposals are NEW. */
23238
24078
  async observe(addonId, candidates) {
@@ -23682,7 +24522,7 @@ function errorMessage$3(err) {
23682
24522
  * moved yet, so it is a {@link MigrationRefusedError}: the migration refuses
23683
24523
  * and restores both cameras' switches.
23684
24524
  */
23685
- var RuntimeStateDrainError = class extends require_device_row_store.MigrationRefusedError {
24525
+ var RuntimeStateDrainError = class extends require_record_kinds.MigrationRefusedError {
23686
24526
  deviceId;
23687
24527
  constructor(deviceId, reason, options) {
23688
24528
  super(`migration refused: the runtime state of device ${deviceId} could not be drained before the swap (${reason}) — nothing moved; retry the migration`, options);
@@ -26656,16 +27496,20 @@ var REMOVAL_RETRY_DELAYS_MS = [
26656
27496
  12e4,
26657
27497
  6e5
26658
27498
  ];
26659
- async function attempt(steps) {
27499
+ async function attempt(steps, concurrent) {
26660
27500
  const counts = {};
26661
27501
  const failed = [];
26662
27502
  const errors = {};
26663
- for (const step of steps) try {
26664
- counts[step.store] = await step.run();
26665
- } catch (err) {
26666
- failed.push(step);
26667
- errors[step.store] = require_scoped_settings.errMsg(err);
26668
- }
27503
+ const runOne = async (step) => {
27504
+ try {
27505
+ counts[step.store] = await step.run();
27506
+ } catch (err) {
27507
+ failed.push(step);
27508
+ errors[step.store] = require_scoped_settings.errMsg(err);
27509
+ }
27510
+ };
27511
+ if (concurrent) await Promise.all(steps.map(runOne));
27512
+ else for (const step of steps) await runOne(step);
26669
27513
  return {
26670
27514
  counts,
26671
27515
  failed,
@@ -26674,6 +27518,7 @@ async function attempt(steps) {
26674
27518
  }
26675
27519
  function createRemovalCleanup(opts) {
26676
27520
  const label = opts.label ?? "device removal cleanup";
27521
+ const concurrent = opts.concurrent ?? false;
26677
27522
  const delays = opts.retryDelaysMs ?? REMOVAL_RETRY_DELAYS_MS;
26678
27523
  const setTimer = opts.setTimer ?? ((fn, ms) => setTimeout(fn, ms));
26679
27524
  const clearTimer = opts.clearTimer ?? ((handle) => clearTimeout(handle));
@@ -26700,7 +27545,7 @@ function createRemovalCleanup(opts) {
26700
27545
  pending.add(handle);
26701
27546
  };
26702
27547
  const retry = async (deviceId, steps, retryIndex) => {
26703
- const result = await attempt(steps);
27548
+ const result = await attempt(steps, concurrent);
26704
27549
  opts.logger.info(`${label} retried`, {
26705
27550
  tags: { deviceId },
26706
27551
  meta: {
@@ -26713,7 +27558,7 @@ function createRemovalCleanup(opts) {
26713
27558
  };
26714
27559
  return {
26715
27560
  async run(deviceId, steps) {
26716
- const result = await attempt(steps);
27561
+ const result = await attempt(steps, concurrent);
26717
27562
  const failedStores = result.failed.map((s) => s.store);
26718
27563
  const meta = {
26719
27564
  counts: result.counts,
@@ -27046,7 +27891,7 @@ var DeviceManagerAddon = class extends require_base_addon.BaseAddon {
27046
27891
  * bindings purge reach the store through `BindingsDeps` — and two locks over
27047
27892
  * one key range is the same defect one level up. Handed to both.
27048
27893
  */
27049
- addonStoreWriteLock = createWriteLock();
27894
+ addonStoreWriteLock = require_named_entity_store.createWriteLock();
27050
27895
  /** Stored activations of RETIRED wrappers, said once per process (task 17 review M1). */
27051
27896
  staleWrapperActivationsImpl = null;
27052
27897
  get staleWrapperActivations() {
@@ -27125,6 +27970,7 @@ var DeviceManagerAddon = class extends require_base_addon.BaseAddon {
27125
27970
  return /* @__PURE__ */ new Map();
27126
27971
  }
27127
27972
  },
27973
+ roomNameOf: (value) => pctx.rooms.nameOf(value),
27128
27974
  logger: this.ctx.logger
27129
27975
  }, input);
27130
27976
  }
@@ -27177,12 +28023,30 @@ var DeviceManagerAddon = class extends require_base_addon.BaseAddon {
27177
28023
  const settingsStoreApi = this.ctx.api?.settingsStore;
27178
28024
  if (!settingsStoreApi) throw new Error("[device-manager] settings-store API not available — refusing to serve a fleet it cannot persist");
27179
28025
  const identityIndex = new DeviceIdentityIndex();
27180
- const deviceRows = new require_device_row_store.DeviceRowStore(require_device_row_store.deviceRowBackendOf(settingsStoreApi), this.ctx.logger.child("rows"), void 0, identityIndex);
28026
+ const deviceRows = new require_record_kinds.DeviceRowStore(require_record_kinds.deviceRowBackendOf(settingsStoreApi), this.ctx.logger.child("rows"), void 0, identityIndex);
27181
28027
  await deviceRows.declare();
27182
28028
  this.deviceRows = deviceRows;
27183
28029
  const records = this.ctx.records;
27184
28030
  if (records === void 0) throw new Error("[device-manager] ctx.records is required on the hub");
27185
- await records.declare(require_device_row_store.deviceManagerRecordKinds);
28031
+ await records.declare(require_record_kinds.deviceManagerRecordKinds);
28032
+ await this.runMigrations(require_base_addon.defineAddonMigrations(ROOMS_AND_TAGS_MIGRATIONS, deviceManagerMigrationPorts({
28033
+ readStoredKey: (key) => this.readStoredGlobalKey(key),
28034
+ rows: deviceRows,
28035
+ rooms: records.kind(require_record_kinds.deviceManagerRecordKinds.rooms),
28036
+ zones: records.kind(require_record_kinds.deviceManagerRecordKinds.zones),
28037
+ report: (message, meta) => this.ctx.logger.info(message, { meta })
28038
+ })));
28039
+ const rooms = RoomStore.of(records);
28040
+ await rooms.load();
28041
+ const tagApi = this.ctx.api?.tags;
28042
+ const tagNames = new TagNames(tagApi === void 0 ? null : {
28043
+ list: () => tagApi.listTags.query({}),
28044
+ ensure: (name) => tagApi.ensureTag.mutate({ name })
28045
+ }, this.ctx.logger.child("tag-names"));
28046
+ deviceRows.setDerivedNames({
28047
+ room: (id) => rooms.nameOf(id),
28048
+ tag: (id) => tagNames.nameOf(id)
28049
+ });
27186
28050
  const tombstones = DeviceTombstoneStore.of(records, this.ctx.logger.child("tombstones"));
27187
28051
  const identityLinksStore = IdentityLinksStore.of(records);
27188
28052
  await identityLinksStore.load();
@@ -27287,6 +28151,10 @@ var DeviceManagerAddon = class extends require_base_addon.BaseAddon {
27287
28151
  const templates = this.makeTemplateActions();
27288
28152
  const pctx = {
27289
28153
  host: this.providerHost,
28154
+ rooms,
28155
+ freshTagNames: () => tagNames.fresh(),
28156
+ tagNameOf: (id) => tagNames.nameOf(id),
28157
+ ensureTagIds: (names) => tagNames.ensureIds(names),
27290
28158
  metaStore,
27291
28159
  settings,
27292
28160
  registry,
@@ -27332,11 +28200,29 @@ var DeviceManagerAddon = class extends require_base_addon.BaseAddon {
27332
28200
  } catch (err) {
27333
28201
  this.ctx.logger.warn("linked-devices manual backfill failed — auto links are NOT materialised", { meta: { error: require_scoped_settings.errMsg(err) } });
27334
28202
  }
28203
+ try {
28204
+ await this.runMigrations(require_base_addon.defineAddonMigrations(ORPHAN_CHILDREN_MIGRATIONS, {
28205
+ listRows: async () => (await deviceRows.listAll()).map((row) => ({
28206
+ id: row.meta.id,
28207
+ parentDeviceId: row.meta.parentDeviceId
28208
+ })),
28209
+ rowLimit: require_record_kinds.DEVICE_ROWS_FLEET_LIMIT,
28210
+ removeDevice: (deviceId) => removeDevice(pctx, { deviceId }),
28211
+ summary: (counts) => this.ctx.logger.info("device-manager: orphan children found", { meta: counts }),
28212
+ info: (message, deviceId, parentDeviceId) => this.ctx.logger.info(message, {
28213
+ tags: { deviceId },
28214
+ meta: { parentDeviceId }
28215
+ })
28216
+ }));
28217
+ } catch (err) {
28218
+ this.ctx.logger.warn("orphan-children migration failed — rows stay as they are", { meta: { error: require_scoped_settings.errMsg(err) } });
28219
+ }
27335
28220
  const provider = {
27336
28221
  resolveDeviceOwnerSync: (deviceId) => resolveDeviceOwnerSync(pctx, deviceId),
27337
28222
  resolveNativeCapOwnerSync: (capName, deviceId) => resolveNativeCapOwnerSync(pctx, capName, deviceId),
27338
28223
  allocateDeviceId: (input) => allocateDeviceId(pctx, input),
27339
28224
  migrateDevice: (input) => migrateDevice(pctx, input),
28225
+ repairMigrationSecrets: (input) => repairMigrationSecrets(pctx, input),
27340
28226
  registerDevice: (input) => registerDevice(pctx, input),
27341
28227
  removeDevice: (input) => removeDevice(pctx, input),
27342
28228
  listDeletedSince: ({ sinceMs }) => tombstones.listSince(sinceMs),
@@ -27382,6 +28268,10 @@ var DeviceManagerAddon = class extends require_base_addon.BaseAddon {
27382
28268
  setMetadata: (input) => setMetadata(pctx, input),
27383
28269
  setDisabled: (input) => setDisabled(pctx, input),
27384
28270
  loadRuntimeState: (input) => loadRuntimeState(pctx, input),
28271
+ ensureRoom: (input) => ensureRoom(pctx, input),
28272
+ listRooms: () => listRooms(pctx),
28273
+ updateRoom: (input) => updateRoom(pctx, input),
28274
+ deleteRoom: (input) => deleteRoom(pctx, input),
27385
28275
  listLocations: () => listLocations(pctx),
27386
28276
  addLocation: (input) => addLocation(pctx, input),
27387
28277
  removeLocation: (input) => removeLocation(pctx, input),
@@ -27601,7 +28491,8 @@ var DeviceManagerAddon = class extends require_base_addon.BaseAddon {
27601
28491
  get removalHooksCleanup() {
27602
28492
  if (this.removalHooksCleanupImpl === null) this.removalHooksCleanupImpl = createRemovalCleanup({
27603
28493
  logger: this.ctx.logger,
27604
- label: "device removal hooks"
28494
+ label: "device removal hooks",
28495
+ concurrent: true
27605
28496
  });
27606
28497
  return this.removalHooksCleanupImpl;
27607
28498
  }