@camstack/server 1.2.917 → 1.2.919

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 (93) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/package.json +13 -11
  3. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.js +1 -1
  4. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.mjs +1 -1
  5. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js +1 -1
  6. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs +1 -1
  7. package/system/dist/builtins/alerts/alerts.addon.js +1 -1
  8. package/system/dist/builtins/alerts/alerts.addon.mjs +1 -1
  9. package/system/dist/builtins/autotrack/index.js +1 -1
  10. package/system/dist/builtins/autotrack/index.mjs +1 -1
  11. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.js +2 -2
  12. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.mjs +2 -2
  13. package/system/dist/builtins/calendars/calendars.addon.js +1 -1
  14. package/system/dist/builtins/calendars/calendars.addon.mjs +1 -1
  15. package/system/dist/builtins/camera-grid/index.js +1 -1
  16. package/system/dist/builtins/camera-grid/index.mjs +1 -1
  17. package/system/dist/builtins/composer/composer.addon.js +4 -4
  18. package/system/dist/builtins/composer/composer.addon.mjs +4 -4
  19. package/system/dist/builtins/console-logging/index.js +1 -1
  20. package/system/dist/builtins/console-logging/index.mjs +1 -1
  21. package/system/dist/builtins/core-blocks/core-blocks.addon.js +4 -4
  22. package/system/dist/builtins/core-blocks/core-blocks.addon.mjs +4 -4
  23. package/system/dist/builtins/device-history/device-history.addon.js +2 -2
  24. package/system/dist/builtins/device-history/device-history.addon.mjs +2 -2
  25. package/system/dist/builtins/device-manager/device-manager.addon.js +19 -1132
  26. package/system/dist/builtins/device-manager/device-manager.addon.mjs +11 -1123
  27. package/system/dist/builtins/hub-forwarder/index.js +1 -1
  28. package/system/dist/builtins/hub-forwarder/index.mjs +1 -1
  29. package/system/dist/builtins/keychain/index.js +4 -4
  30. package/system/dist/builtins/keychain/index.mjs +4 -4
  31. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.js +1 -1
  32. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.mjs +1 -1
  33. package/system/dist/builtins/local-auth/local-auth.addon.js +2 -2
  34. package/system/dist/builtins/local-auth/local-auth.addon.mjs +2 -2
  35. package/system/dist/builtins/local-network/local-network.addon.js +3 -3
  36. package/system/dist/builtins/local-network/local-network.addon.mjs +3 -3
  37. package/system/dist/builtins/loki-logging/index.js +1 -1
  38. package/system/dist/builtins/loki-logging/index.mjs +1 -1
  39. package/system/dist/builtins/native-metrics/native-metrics.addon.js +1 -1
  40. package/system/dist/builtins/native-metrics/native-metrics.addon.mjs +1 -1
  41. package/system/dist/builtins/platform-probe/index.js +1 -1
  42. package/system/dist/builtins/platform-probe/index.mjs +1 -1
  43. package/system/dist/builtins/record-entries/index.js +1 -1
  44. package/system/dist/builtins/record-entries/index.mjs +1 -1
  45. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.js +1 -1
  46. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.mjs +1 -1
  47. package/system/dist/builtins/snapshot/index.js +1 -1
  48. package/system/dist/builtins/snapshot/index.mjs +1 -1
  49. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.js +1 -1
  50. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.mjs +1 -1
  51. package/system/dist/builtins/sqlite-storage/index.js +1 -1
  52. package/system/dist/builtins/sqlite-storage/index.mjs +1 -1
  53. package/system/dist/builtins/sqlite-storage/migrations/migration-edits.d.ts +31 -5
  54. package/system/dist/builtins/sqlite-storage/migrations/migration-pass.d.ts +5 -5
  55. package/system/dist/builtins/sqlite-storage/migrations/migration-types.d.ts +15 -1
  56. package/system/dist/builtins/sqlite-storage/records/records-engine.d.ts +7 -0
  57. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.js +4 -4
  58. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs +4 -4
  59. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.js +1 -1
  60. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.mjs +1 -1
  61. package/system/dist/builtins/system-config/system-config.addon.js +3 -3
  62. package/system/dist/builtins/system-config/system-config.addon.mjs +284 -284
  63. package/system/dist/builtins/winston-logging/index.js +1 -1
  64. package/system/dist/builtins/winston-logging/index.mjs +1 -1
  65. package/system/dist/{capture-engine-UNTcSBiF.js → capture-engine-DLFzxSof.js} +1 -1
  66. package/system/dist/{capture-engine-DgO-N5FL.mjs → capture-engine-lx-ggDqQ.mjs} +1 -1
  67. package/system/dist/{composition-sources-AfSwY0mW.mjs → composition-sources-BKA_EEb6.mjs} +1 -1
  68. package/system/dist/{composition-sources-Df52Wv0k.js → composition-sources-BVQ2x2kp.js} +1 -1
  69. package/system/dist/{constants-Z-nqQ-0f.mjs → constants-BpaM7LV9.mjs} +1 -1
  70. package/system/dist/{constants-D5nE68R-.js → constants-TrK4tkaV.js} +1 -1
  71. package/system/dist/{device-ca-Cn9FRko2.js → device-ca-BCURI4VN.js} +1 -1
  72. package/system/dist/{device-ca-BqqBJ5Ft.mjs → device-ca-CR1WOAty.mjs} +1 -1
  73. package/system/dist/device-row-store-DIYmeeJf.mjs +1113 -0
  74. package/system/dist/device-row-store-ML0g2MYJ.js +1143 -0
  75. package/system/dist/{dist-CftbsT6r.mjs → dist-B9QP5wIl.mjs} +702 -3
  76. package/system/dist/{dist-DxBWhuSc.js → dist-UXAYr3HM.js} +713 -2
  77. package/system/dist/file-host-worker.js +2 -2
  78. package/system/dist/file-host-worker.mjs +2 -2
  79. package/system/dist/{hub-identity-D_lD6udf.mjs → hub-identity-3gYSQdRz.mjs} +1 -1
  80. package/system/dist/{hub-identity-Db7fve3f.js → hub-identity-CGsNqBks.js} +1 -1
  81. package/system/dist/{hub-mdns-ciao-DX6jDD_d.mjs → hub-mdns-ciao-BvjAcyuD.mjs} +2 -2
  82. package/system/dist/{hub-mdns-ciao-CK1mWOyO.js → hub-mdns-ciao-CDHA875K.js} +2 -2
  83. package/system/dist/index.js +8 -8
  84. package/system/dist/index.mjs +8 -8
  85. package/system/dist/{legacy-integration-rows-door-CsYIwKtO.mjs → legacy-integration-rows-door-D3V2leAn.mjs} +1 -1
  86. package/system/dist/{legacy-integration-rows-door-COSfBe0d.js → legacy-integration-rows-door-DhQRTSPJ.js} +1 -1
  87. package/system/dist/{rename-composition-block-CaZBnU9O.js → rename-composition-block-BeC7EAMk.js} +1 -1
  88. package/system/dist/{rename-composition-block-CcCjR2ZX.mjs → rename-composition-block-Cz7yCW3Q.mjs} +1 -1
  89. package/system/dist/{restore-archive-D-0Jq9fY.js → restore-archive-Dj81PTwm.js} +1 -1
  90. package/system/dist/{restore-archive-BRPFibpR.mjs → restore-archive-oOjfUbB5.mjs} +82 -82
  91. package/system/dist/{wal-maintenance-BdNZFRV8.mjs → wal-maintenance-BhbA2ep5.mjs} +0 -0
  92. package/system/dist/{wal-maintenance-lUBLKZVQ.js → wal-maintenance-PtLQ5hgH.js} +0 -0
  93. package/system/package.json +1 -1
@@ -0,0 +1,1113 @@
1
+ import { El as defineRecordKinds, Xs as canonicalStoredDeviceType, jt as IdentityLinkBodySchema, nt as DeviceIdentifierKeySchema, ot as DeviceTombstoneSchema, rt as DeviceIdentifiersSchema, st as DiscoveryProposalBodySchema } from "./dist-B9QP5wIl.mjs";
2
+ //#region src/builtins/device-manager/migration-refused.ts
3
+ /**
4
+ * A migration step that REFUSED with nothing moved.
5
+ *
6
+ * `migrateDevice` distinguishes two kinds of failure after the disable phase,
7
+ * and they must never be confused (D663 task 5b ruling I-1):
8
+ *
9
+ * - **refused, nothing moved** — a precheck of `swapIds` (a row missing, the
10
+ * temp id taken), the mirror drain that runs before the rows move, or a
11
+ * claim found in the mirror after that drain (it landed while the migration
12
+ * was starting). Both cameras are switched back to exactly what they were,
13
+ * because nothing about either device changed.
14
+ * - **failed while moving** — any other throw from `swapIds` (rows partially
15
+ * moved), or from `swapHardwareState` (rows swapped, state not). The two
16
+ * devices may wear each other's identity; switching them back on would run
17
+ * pipelines against crossed identities, so they stay off and the operator is
18
+ * told to intervene.
19
+ *
20
+ * Only a step that KNOWS it wrote nothing may throw this. An unknown error is
21
+ * read as "may have moved" — the safe reading.
22
+ */
23
+ var MigrationRefusedError = class extends Error {
24
+ constructor(message, options) {
25
+ super(message, options);
26
+ this.name = "MigrationRefusedError";
27
+ }
28
+ };
29
+ var _deviceManagerRecordKinds = defineRecordKinds({
30
+ tombstones: {
31
+ schema: DeviceTombstoneSchema.omit({ deviceId: true }),
32
+ class: "ledger",
33
+ writeTrigger: "`removeDevice` records one row per deleted device after the device row is gone; re-record keeps the earlier `deletedAt`",
34
+ device: "none",
35
+ at: "required",
36
+ indexes: [{
37
+ name: "deleted_at",
38
+ fields: ["deletedAt"]
39
+ }],
40
+ retention: {
41
+ owner: "device-manager",
42
+ reason: "90 days (`DEVICE_TOMBSTONE_RETENTION_MS`), pruned whenever a tombstone is written or the list is read"
43
+ }
44
+ },
45
+ "discovery-proposals": {
46
+ schema: DiscoveryProposalBodySchema,
47
+ class: "config",
48
+ writeTrigger: "the passive listener and the 30-minute sweep of `local-network` re-see a device (`lastSeenAt` and `at` move); `dismissDiscoveryProposal` sets `dismissed`",
49
+ device: "none",
50
+ at: "required",
51
+ indexes: [{
52
+ name: "last_seen_at",
53
+ fields: ["lastSeenAt"]
54
+ }],
55
+ retention: {
56
+ ttlMs: 2160 * 60 * 60 * 1e3,
57
+ from: "at"
58
+ }
59
+ },
60
+ "identity-links": {
61
+ schema: IdentityLinkBodySchema,
62
+ class: "config",
63
+ writeTrigger: "the identity-link reconciler sees a candidate appear, upgrade or lose its evidence; the operator confirms, dismisses or unlinks (D1063)",
64
+ device: "none",
65
+ at: "none",
66
+ indexes: [{
67
+ name: "a_device",
68
+ fields: ["a.deviceId"]
69
+ }, {
70
+ name: "b_device",
71
+ fields: ["b.deviceId"]
72
+ }],
73
+ retention: { none: "a link lives as long as both its devices; a dismissal is sticky (operator intent)" }
74
+ }
75
+ });
76
+ var deviceManagerRecordKinds = _deviceManagerRecordKinds;
77
+ _deviceManagerRecordKinds.tombstones;
78
+ //#endregion
79
+ //#region src/builtins/device-manager/fleet-read-census.ts
80
+ /** How many stack frames identify a call site. One frame is a method; three are
81
+ * a cause — `listFleet < listAll < onDeviceRegistered` is the answer, `listAll`
82
+ * alone is not. Same choice, for the same reason, as `read-census.ts`. */
83
+ var CENSUS_STACK_FRAMES = 3;
84
+ function siteFromStack(stack) {
85
+ if (stack === void 0) return "unknown";
86
+ const frames = stack.split("\n").slice(1).map((line) => line.trim().replace(/^at\s+/, "")).filter((line) => line.length > 0).slice(0, CENSUS_STACK_FRAMES).map((line) => {
87
+ const open = line.indexOf(" (");
88
+ return (open > 0 ? line.slice(0, open) : line).replace(/^async\s+/, "");
89
+ });
90
+ return frames.length === 0 ? "unknown" : frames.join(" < ");
91
+ }
92
+ var FleetReadCensus = class FleetReadCensus {
93
+ /**
94
+ * Longest window the census may be armed for.
95
+ *
96
+ * Ten minutes covers a boot several times over and bounds what an operator
97
+ * pays if they set the variable and forget it. A diagnostic that can be left
98
+ * on becomes a tax nobody remembers enabling.
99
+ */
100
+ static MAX_WINDOW_MS = 10 * 6e4;
101
+ windowMs;
102
+ closesAt;
103
+ counts = /* @__PURE__ */ new Map();
104
+ reported = false;
105
+ constructor(rawEnv, nowMs) {
106
+ const parsed = rawEnv === void 0 ? NaN : Number(rawEnv);
107
+ const valid = Number.isFinite(parsed) && parsed > 0;
108
+ this.windowMs = valid ? Math.min(parsed, FleetReadCensus.MAX_WINDOW_MS) : 0;
109
+ this.closesAt = valid ? nowMs + this.windowMs : 0;
110
+ }
111
+ get armed() {
112
+ return this.windowMs > 0;
113
+ }
114
+ /** Test seam: pretend the window closed. Production reads the clock. */
115
+ closeAt(nowMs) {
116
+ if (nowMs >= this.closesAt) this.forceClosed = true;
117
+ }
118
+ forceClosed = false;
119
+ isOpen(nowMs) {
120
+ if (!this.armed || this.forceClosed) return false;
121
+ return nowMs < this.closesAt;
122
+ }
123
+ /**
124
+ * Capture the caller, or `null` when the window is shut.
125
+ *
126
+ * Called at the START of a read. A read that began inside the window belongs
127
+ * to it even if it lands after the close — otherwise the slow reads at the
128
+ * edge would be attributed to nobody, and the slow ones are the interesting
129
+ * ones.
130
+ *
131
+ * `callerAddonId`, when given, is formatted as the site VERBATIM instead of
132
+ * walking the local stack. A call that arrived over the cap channel — a
133
+ * forked addon's `ctx.api.deviceManager.listAll.query()`, routed through
134
+ * `LocalChildRegistry` → `onUnownedCall` → `CapRouteResolver` — carries its
135
+ * origin as DATA (the registered `childId` the parent captured off the UDS
136
+ * connection), and no amount of stack depth would ever recover it: every
137
+ * frame between the socket read and this call is the SAME generic
138
+ * dispatcher code (`onUnownedCall`, `dispatch`, `invoke`) regardless of
139
+ * which addon called — the 2026-08-25 boot census measured this directly,
140
+ * five thousand calls landing on `listAll` with nothing nameable above it.
141
+ *
142
+ * `isOpen` is checked FIRST, before the id is even looked at — a caller
143
+ * threading a (cheap, already-known) `callerAddonId` through on every
144
+ * request, armed or not, must not pay for the template string when
145
+ * disarmed. This is also why formatting lives HERE rather than at the call
146
+ * site: `DeviceRowStore` passes the raw id through unconditionally, and
147
+ * only this method — which already knows whether armed — decides whether
148
+ * to spend anything on it.
149
+ */
150
+ siteOf(callerAddonId, nowMs = Date.now()) {
151
+ if (!this.isOpen(nowMs)) return null;
152
+ if (callerAddonId !== void 0) return `addon:${callerAddonId}`;
153
+ const holder = {};
154
+ Error.captureStackTrace(holder, this.siteOf);
155
+ return siteFromStack(holder.stack);
156
+ }
157
+ /** Count one read at an already-captured site. A `null` site is not counted. */
158
+ record(site, rowCount) {
159
+ if (site === null) return;
160
+ const existing = this.counts.get(site);
161
+ if (existing === void 0) {
162
+ this.counts.set(site, {
163
+ site,
164
+ calls: 1,
165
+ rows: rowCount
166
+ });
167
+ return;
168
+ }
169
+ existing.calls += 1;
170
+ existing.rows += rowCount;
171
+ }
172
+ /** Attributed sites, busiest first. */
173
+ rows() {
174
+ return [...this.counts.values()].map((c) => ({
175
+ site: c.site,
176
+ calls: c.calls,
177
+ rows: c.rows
178
+ })).sort((a, b) => b.calls - a.calls);
179
+ }
180
+ /**
181
+ * Emit the report ONCE.
182
+ *
183
+ * `perMin` is included because the raw count is unreadable without the window
184
+ * it was taken over — "4 149" means nothing until you know it was 66 seconds.
185
+ */
186
+ report(logger, elapsedMs) {
187
+ if (this.reported || !this.armed) return;
188
+ this.reported = true;
189
+ const rows = this.rows();
190
+ const totalCalls = rows.reduce((acc, r) => acc + r.calls, 0);
191
+ logger.info("fleet read census", { meta: {
192
+ elapsedMs,
193
+ sites: rows.length,
194
+ totalCalls,
195
+ rows: rows.map((r) => ({
196
+ site: r.site,
197
+ calls: r.calls,
198
+ rows: r.rows,
199
+ perMin: elapsedMs === 0 ? 0 : Math.round(r.calls * 6e4 / elapsedMs)
200
+ }))
201
+ } });
202
+ }
203
+ };
204
+ //#endregion
205
+ //#region src/builtins/device-manager/device-row-store.ts
206
+ /**
207
+ * `device-manager:devices` — ONE ROW PER DEVICE.
208
+ *
209
+ * ## What this replaces
210
+ *
211
+ * The device-manager used to keep its whole fleet in three JSON blobs on the
212
+ * addon-settings row set (`deviceMeta`, `deviceMetadata`, `deviceIndex`).
213
+ * Measured on the live hub 2026-08-19: 467 KB + 87 KB + 70 KB = 625 KB of the
214
+ * table's 627 KB, and EVERY read of any of them read and `JSON.parse`d all
215
+ * three, synchronously, on hub-main's event loop — `ctx.settings.readAddonStore`
216
+ * lands in `SqliteSettingsBackend.getAllAddon`, which is prefix-scoped to the
217
+ * addon but not to the key. A V8 profile of that boot had hub-main's JS thread
218
+ * 99.9% busy for 76 s with 64% of it inside `getAllAddon`, ~89% of that entered
219
+ * through the meta store, and every runner's first store read queued behind it.
220
+ *
221
+ * Writing was worse than reading. `ConfigManager.createSettingsView`'s
222
+ * `writeAddonStore` is `setAllAddon(addonId, { ...existing, ...patch })`, and
223
+ * `setAllAddon` DELETEs and re-INSERTs every row of the addon — so renaming one
224
+ * camera rewrote 625 KB.
225
+ *
226
+ * A row per device makes the per-device question a primary-key lookup and the
227
+ * per-device write a single-row upsert touching only the columns named.
228
+ *
229
+ * ## Why `deviceIndex` has no column and no collection
230
+ *
231
+ * `deviceIndex` was `Record<addonId, stableId[]>` — pure derivation: `addonId`
232
+ * and `stableId` are fields of every row, so "this addon's devices" is
233
+ * `where: { addonId }`. It carried exactly one bit that is NOT derivable:
234
+ * membership meant "`registerDevice` has run at least once", which is how
235
+ * `registerDevice` tells a FIRST registration (emit `DeviceRegistered`) from a
236
+ * meta refresh. `allocateDeviceId` writes a row without registering, so row
237
+ * existence alone cannot answer it. That bit is the {@link registered} column,
238
+ * and nothing else of `deviceIndex` survives.
239
+ *
240
+ * ## Why metadata is a column and not a second collection
241
+ *
242
+ * `deviceMetadata` lived in its own blob for ONE reason: a blob write is
243
+ * whole-value, so a lifecycle writer (`registerDevice` / `setName` / …) that
244
+ * had to preserve a `metadata` field would eventually clobber a concurrent
245
+ * `setMetadata`. Single-writer-per-blob was the fix. Column writes have no such
246
+ * problem — `set` names its columns and leaves the rest of the row untouched —
247
+ * so the split has no reason to exist and metadata rides on the device's own
248
+ * row.
249
+ *
250
+ * ## Adding a column later
251
+ *
252
+ * `declareCollection` is additive ONLY when SQLite can `ALTER TABLE … ADD
253
+ * COLUMN` it. A new `NOT NULL` column without a `defaultValue` cannot be added
254
+ * to a populated table, so the backend counts it as non-additive and REBUILDS
255
+ * the collection — dropping every row. Any column added here after ship must
256
+ * either be nullable or carry a `defaultValue`.
257
+ */
258
+ /**
259
+ * @durable class=ledger owner=device-manager
260
+ * write="one row per device, written by `allocateDeviceId` (identity placeholder),
261
+ * `registerDevice` (full reconcile) and every meta setter (single-column patch);
262
+ * `setMetadata` patches the `metadata` column of the same row"
263
+ * retention="none — a row goes only when the operator removes the device
264
+ * (`removeDevice`), or when an integration is deleted and cascades. Bounded by the
265
+ * fleet an operator configures (974 rows on the reference hub)."
266
+ *
267
+ * ### Why `ledger` and not `config`
268
+ *
269
+ * This shipped as `class=registry`, a sixth class that does not exist —
270
+ * `DURABLE_CLASSES` is `ledger | mirror | ephemeral | config | audit`, so
271
+ * `check-durable-state-declared.ts` has failed since. `config` is the tempting
272
+ * answer, because a device's `name` and `location` ARE operator intent. It is
273
+ * the wrong one, and wrong in the dangerous direction: `config`'s rule is
274
+ * *"already durable everywhere"*, and that is exactly the premise that made the
275
+ * dead `devices` table look harmless right up to D183.
276
+ *
277
+ * Nothing else holds a device's NUMERIC id. `allocateDeviceId` mints it here
278
+ * and every other store in the system keys on it — `addon-device-settings`,
279
+ * `device-runtime-state`, every `pipeline-analytics:*` row, every recorder path.
280
+ * That is `ledger`'s definition verbatim ("a fact only this component ever
281
+ * held"), and `ledger`'s rule — *must not be pruned against a fallible read* —
282
+ * is precisely the rule this collection needs (D49): a `getBindings` or an
283
+ * integration listing that answers empty because it FAILED must never be
284
+ * allowed to retire a device row.
285
+ */
286
+ var DEVICE_ROWS_COLLECTION = "device-manager:devices";
287
+ /**
288
+ * Fleet reads pass this explicitly.
289
+ *
290
+ * `settings-store.query` applies a DEFAULT row cap of 2 000 when the caller
291
+ * names no `limit` (`query-bounds.ts`), and truncation there is silent to the
292
+ * caller — it warns in the engine's log and returns a short list that looks
293
+ * complete. The reference hub is already at 974 devices; half the default cap
294
+ * is not a margin worth betting the fleet listing on. 20 000 is the engine's
295
+ * hard ceiling, so this asks for everything the engine will ever serve in one
296
+ * call and any future need to page is a loud failure rather than a quiet one.
297
+ */
298
+ var DEVICE_ROWS_FLEET_LIMIT = 2e4;
299
+ var DEVICE_ROWS_COLUMNS = [
300
+ {
301
+ name: "id",
302
+ type: "TEXT",
303
+ primaryKey: true,
304
+ notNull: true
305
+ },
306
+ {
307
+ name: "deviceId",
308
+ type: "INTEGER",
309
+ notNull: true
310
+ },
311
+ {
312
+ name: "addonId",
313
+ type: "TEXT",
314
+ notNull: true
315
+ },
316
+ {
317
+ name: "stableId",
318
+ type: "TEXT",
319
+ notNull: true
320
+ },
321
+ {
322
+ name: "type",
323
+ type: "TEXT",
324
+ notNull: true
325
+ },
326
+ {
327
+ name: "name",
328
+ type: "TEXT",
329
+ notNull: true
330
+ },
331
+ {
332
+ name: "alias",
333
+ type: "TEXT"
334
+ },
335
+ {
336
+ name: "userNamed",
337
+ type: "BOOLEAN"
338
+ },
339
+ {
340
+ name: "location",
341
+ type: "TEXT"
342
+ },
343
+ {
344
+ name: "tags",
345
+ type: "JSON"
346
+ },
347
+ {
348
+ name: "disabled",
349
+ type: "BOOLEAN",
350
+ notNull: true,
351
+ defaultValue: false
352
+ },
353
+ {
354
+ name: "parentDeviceId",
355
+ type: "INTEGER"
356
+ },
357
+ {
358
+ name: "registered",
359
+ type: "BOOLEAN",
360
+ notNull: true,
361
+ defaultValue: false
362
+ },
363
+ {
364
+ name: "features",
365
+ type: "JSON"
366
+ },
367
+ {
368
+ name: "exportFingerprint",
369
+ type: "TEXT"
370
+ },
371
+ {
372
+ name: "integrationId",
373
+ type: "TEXT"
374
+ },
375
+ {
376
+ name: "linkDeviceId",
377
+ type: "INTEGER"
378
+ },
379
+ {
380
+ name: "primaryChildEntityId",
381
+ type: "TEXT"
382
+ },
383
+ {
384
+ name: "childLayout",
385
+ type: "JSON"
386
+ },
387
+ {
388
+ name: "primaryChildPreference",
389
+ type: "JSON"
390
+ },
391
+ {
392
+ name: "role",
393
+ type: "TEXT"
394
+ },
395
+ {
396
+ name: "display",
397
+ type: "JSON"
398
+ },
399
+ {
400
+ name: "metadata",
401
+ type: "JSON"
402
+ },
403
+ {
404
+ name: "identifiers",
405
+ type: "JSON"
406
+ },
407
+ {
408
+ name: "attachedIdentifiers",
409
+ type: "JSON"
410
+ },
411
+ {
412
+ name: "attachedRetained",
413
+ type: "JSON"
414
+ }
415
+ ];
416
+ /**
417
+ * The columns a SLIM fleet read selects: every declared column except the
418
+ * primary key (always returned) and `metadata`.
419
+ *
420
+ * ## Why this is a DENYLIST and must stay one
421
+ *
422
+ * `decodeDeviceRow` returns `null` when `deviceId`, `addonId`, `stableId`,
423
+ * `type` or `name` is missing, and `list()` then SKIPS the row with a warn. A
424
+ * hand-written allowlist that forgot one of the five would not make the fleet
425
+ * slower — it would make devices vanish from every listing, quietly, and the
426
+ * only trace would be a log line nobody is reading at the time. Deriving the
427
+ * list by subtraction means a column added tomorrow is carried by default and
428
+ * the only way to lose one is to name it here.
429
+ *
430
+ * `metadata` is the one slim provably discards: `device-queries.ts#listAll`
431
+ * sets `metadata: null` on every slim row. It is also the largest JSON column
432
+ * on the row, which is why this is worth doing at all.
433
+ *
434
+ * ## What is NOT here, and will not be
435
+ *
436
+ * There is no `where: { type: 'camera' }` companion to this. `isCameraDevice`
437
+ * is a method-presence check (`getStreamSources`), not the persisted `type`, so
438
+ * a doorbell with a camera answers YES while its row says `doorbell`. Filtering
439
+ * the rows by type would strip exactly those devices of their row — and
440
+ * `toDeviceInfo` reads `name` / `location` / `disabled` from the ROW precisely
441
+ * because the live device's copies are stale by construction. The fleet would
442
+ * keep working and start reporting pre-rename names on doorbells. The
443
+ * `isCamera` filter stays in JS.
444
+ */
445
+ var DEVICE_ROWS_SLIM_COLUMNS = DEVICE_ROWS_COLUMNS.map((c) => c.name).filter((name) => name !== "id" && name !== "metadata");
446
+ var DEVICE_ROWS_INDEXES = [
447
+ {
448
+ name: "idx_dm_devices_addon_stable",
449
+ columns: ["addonId", "stableId"]
450
+ },
451
+ {
452
+ name: "idx_dm_devices_parent",
453
+ columns: ["parentDeviceId"]
454
+ },
455
+ {
456
+ name: "idx_dm_devices_integration",
457
+ columns: ["integrationId"]
458
+ },
459
+ {
460
+ name: "idx_dm_devices_alias",
461
+ columns: ["alias"]
462
+ }
463
+ ];
464
+ /** Adapt `ctx.api.settingsStore` (tRPC namespace) to {@link DeviceRowBackend}. */
465
+ function deviceRowBackendOf(client) {
466
+ return {
467
+ declareCollection: async (input) => {
468
+ await client.declareCollection.mutate(input);
469
+ },
470
+ get: (input) => client.get.query(input),
471
+ set: async (input) => {
472
+ await client.set.mutate(input);
473
+ },
474
+ query: (input) => client.query.query(input),
475
+ updateWhere: (input) => client.updateWhere.mutate(input),
476
+ delete: async (input) => {
477
+ await client.delete.mutate(input);
478
+ },
479
+ count: (input) => client.count.query(input)
480
+ };
481
+ }
482
+ function isPlainObject(value) {
483
+ return value !== null && typeof value === "object" && !Array.isArray(value);
484
+ }
485
+ function readString(value) {
486
+ return typeof value === "string" ? value : void 0;
487
+ }
488
+ function readNumber(value) {
489
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
490
+ }
491
+ function readBoolean(value) {
492
+ if (typeof value === "boolean") return value;
493
+ if (value === 1) return true;
494
+ if (value === 0) return false;
495
+ }
496
+ function readStringArray(value) {
497
+ if (!Array.isArray(value)) return void 0;
498
+ const out = [];
499
+ for (const entry of value) if (typeof entry === "string") out.push(entry);
500
+ return out;
501
+ }
502
+ /**
503
+ * Decode one stored row.
504
+ *
505
+ * Returns `null` for a row missing an identity field the rest of the system
506
+ * treats as an invariant (`deviceId` / `addonId` / `stableId` / `type` /
507
+ * `name`). A row like that cannot be projected into a `DeviceInfo` and taking
508
+ * the whole fleet read down for it would be worse — the caller logs the skip.
509
+ */
510
+ function decodeDeviceRow(data) {
511
+ const deviceId = readNumber(data["deviceId"]);
512
+ const addonId = readString(data["addonId"]);
513
+ const stableId = readString(data["stableId"]);
514
+ const storedType = readString(data["type"]);
515
+ const type = storedType === void 0 ? void 0 : canonicalStoredDeviceType(storedType);
516
+ const name = readString(data["name"]);
517
+ if (deviceId === void 0 || addonId === void 0 || stableId === void 0 || type === void 0 || name === void 0) return null;
518
+ const location = readString(data["location"]);
519
+ const tags = readStringArray(data["tags"]);
520
+ const parentDeviceId = readNumber(data["parentDeviceId"]);
521
+ const userNamed = readBoolean(data["userNamed"]);
522
+ const features = readStringArray(data["features"]);
523
+ const exportFingerprint = readString(data["exportFingerprint"]);
524
+ const integrationId = readString(data["integrationId"]);
525
+ const linkDeviceId = readNumber(data["linkDeviceId"]);
526
+ const primaryChildEntityId = readString(data["primaryChildEntityId"]);
527
+ const role = readString(data["role"]);
528
+ const alias = readString(data["alias"]);
529
+ const rawChildLayout = data["childLayout"];
530
+ const primaryChildPreference = readStringArray(data["primaryChildPreference"]);
531
+ const rawDisplay = data["display"];
532
+ const rawMetadata = data["metadata"];
533
+ const identifiers = DeviceIdentifiersSchema.safeParse(data["identifiers"]);
534
+ const attachedIdentifiers = DeviceIdentifiersSchema.safeParse(data["attachedIdentifiers"]);
535
+ const attachedRetained = DeviceIdentifierKeySchema.array().min(1).safeParse(data["attachedRetained"]);
536
+ return {
537
+ meta: {
538
+ id: deviceId,
539
+ addonId,
540
+ stableId,
541
+ type,
542
+ name,
543
+ location: location ?? null,
544
+ ...tags !== void 0 && tags.length > 0 ? { tags: [...tags] } : {},
545
+ disabled: readBoolean(data["disabled"]) ?? false,
546
+ parentDeviceId: parentDeviceId ?? null,
547
+ ...alias !== void 0 ? { alias } : {},
548
+ ...userNamed !== void 0 ? { userNamed } : {},
549
+ ...features !== void 0 ? { features } : {},
550
+ ...exportFingerprint !== void 0 ? { exportFingerprint } : {},
551
+ ...integrationId !== void 0 ? { integrationId } : {},
552
+ ...linkDeviceId !== void 0 ? { linkDeviceId } : {},
553
+ ...primaryChildEntityId !== void 0 ? { primaryChildEntityId } : {},
554
+ ...isChildLayout(rawChildLayout) ? { childLayout: rawChildLayout } : {},
555
+ ...primaryChildPreference !== void 0 ? { primaryChildPreference } : {},
556
+ ...role !== void 0 ? { role } : {},
557
+ ...isPlainObject(rawDisplay) ? { display: toDisplayOverride(rawDisplay) } : {},
558
+ ...identifiers.success ? { identifiers: identifiers.data } : {},
559
+ ...attachedIdentifiers.success ? { attachedIdentifiers: attachedIdentifiers.data } : {},
560
+ ...attachedRetained.success ? { attachedRetained: attachedRetained.data } : {}
561
+ },
562
+ metadata: isPlainObject(rawMetadata) ? rawMetadata : null,
563
+ registered: readBoolean(data["registered"]) ?? false
564
+ };
565
+ }
566
+ /**
567
+ * `ChildLayout` is a JSON column: what comes back is whatever was written.
568
+ * The projection hands it to the UI untouched, so the only thing worth
569
+ * checking is that it is still the array shape the writer put in.
570
+ */
571
+ function isChildLayout(value) {
572
+ return Array.isArray(value);
573
+ }
574
+ /**
575
+ * `DeviceDisplayOverride` is likewise stored verbatim in a JSON column. It is
576
+ * an all-optional record, so any object round-trips; the write path
577
+ * (`normalizeDisplayOverride`) is what gives it shape.
578
+ */
579
+ function toDisplayOverride(value) {
580
+ return value;
581
+ }
582
+ /** Full-row value for an upsert: identity + every field of the meta record. */
583
+ function encodeDeviceRow(meta, extra = {}) {
584
+ const row = {
585
+ id: String(meta.id),
586
+ deviceId: meta.id,
587
+ addonId: meta.addonId,
588
+ stableId: meta.stableId,
589
+ type: meta.type,
590
+ name: meta.name,
591
+ alias: meta.alias ?? null,
592
+ userNamed: meta.userNamed ?? null,
593
+ location: meta.location,
594
+ tags: meta.tags === void 0 || meta.tags.length === 0 ? null : [...meta.tags],
595
+ disabled: meta.disabled,
596
+ parentDeviceId: meta.parentDeviceId,
597
+ registered: extra.registered ?? false,
598
+ features: meta.features === void 0 ? null : [...meta.features],
599
+ exportFingerprint: meta.exportFingerprint ?? null,
600
+ integrationId: meta.integrationId ?? null,
601
+ linkDeviceId: meta.linkDeviceId ?? null,
602
+ primaryChildEntityId: meta.primaryChildEntityId ?? null,
603
+ childLayout: meta.childLayout ?? null,
604
+ primaryChildPreference: meta.primaryChildPreference === void 0 ? null : [...meta.primaryChildPreference],
605
+ role: meta.role ?? null,
606
+ display: meta.display ?? null,
607
+ identifiers: meta.identifiers ?? null,
608
+ attachedIdentifiers: meta.attachedIdentifiers ?? null,
609
+ attachedRetained: meta.attachedRetained === void 0 ? null : [...meta.attachedRetained]
610
+ };
611
+ if (extra.metadata !== void 0) row["metadata"] = extra.metadata;
612
+ return row;
613
+ }
614
+ /** Column map for a partial write — only the keys the caller actually named. */
615
+ function encodeDeviceRowPatch(patch) {
616
+ const row = {};
617
+ for (const [key, value] of Object.entries(patch)) {
618
+ if (value === void 0) continue;
619
+ row[key] = value;
620
+ }
621
+ return row;
622
+ }
623
+ /**
624
+ * Row access for the device fleet. Every method is a single statement against
625
+ * `device-manager:devices` — there is no in-memory copy of the fleet here and
626
+ * no cache: a per-device question is a primary-key lookup, a fleet question is
627
+ * one indexed scan.
628
+ */
629
+ var DeviceRowStore = class {
630
+ backend;
631
+ logger;
632
+ observer;
633
+ declared = null;
634
+ /** Call-site attribution for fleet reads. Armed only by
635
+ * `CAMSTACK_FLEET_READ_CENSUS_MS`; see `fleet-read-census.ts`. */
636
+ census;
637
+ /**
638
+ * Is the fleet-read census armed right now? Exposed so a caller ABOVE this
639
+ * store (`device-queries.ts`) can skip extracting a caller identity off its
640
+ * input entirely when nobody is measuring — "the boolean field read first"
641
+ * pattern this repo already uses elsewhere to keep a diagnostic seam at
642
+ * zero cost while disarmed.
643
+ */
644
+ get censusArmed() {
645
+ return this.census.armed;
646
+ }
647
+ constructor(backend, logger, census, observer) {
648
+ this.backend = backend;
649
+ this.logger = logger;
650
+ this.observer = observer;
651
+ this.census = census ?? new FleetReadCensus(process.env["CAMSTACK_FLEET_READ_CENSUS_MS"], Date.now());
652
+ if (this.census.armed) {
653
+ const startedAt = Date.now();
654
+ setTimeout(() => this.census.report(this.logger, Date.now() - startedAt), this.census.windowMs).unref?.();
655
+ }
656
+ }
657
+ /**
658
+ * Lazy, idempotent `declareCollection`, memoised on the PROMISE so N
659
+ * concurrent first-callers issue one declaration rather than N. A rejection
660
+ * is not latched — the slot is cleared so the next caller retries instead of
661
+ * inheriting a dead collection forever.
662
+ */
663
+ async declare() {
664
+ const existing = this.declared;
665
+ if (existing !== null) return existing;
666
+ const run = (async () => {
667
+ try {
668
+ await this.backend.declareCollection({
669
+ collection: DEVICE_ROWS_COLLECTION,
670
+ columns: DEVICE_ROWS_COLUMNS,
671
+ indexes: DEVICE_ROWS_INDEXES
672
+ });
673
+ } catch (err) {
674
+ this.declared = null;
675
+ throw err;
676
+ }
677
+ })();
678
+ this.declared = run;
679
+ return run;
680
+ }
681
+ /** One device, by numeric id. `null` when the fleet does not know it. */
682
+ async get(deviceId) {
683
+ await this.declare();
684
+ const raw = await this.backend.get({
685
+ collection: DEVICE_ROWS_COLLECTION,
686
+ key: String(deviceId)
687
+ });
688
+ if (!isPlainObject(raw)) return null;
689
+ const decoded = decodeDeviceRow(raw);
690
+ if (decoded === null) {
691
+ this.logger.warn("device row skipped — identity fields missing", { tags: { deviceId } });
692
+ return null;
693
+ }
694
+ return decoded;
695
+ }
696
+ /**
697
+ * Every device, ordered by numeric id.
698
+ *
699
+ * `callerAddonId`, when known, is the addon that ORIGINATED this call —
700
+ * captured off the cap-channel envelope (`CapCallInput.callerAddonId`, set
701
+ * by `LocalChildRegistry` from the registered `childId`), never guessed.
702
+ * Passed straight to the census; a stack walk can never name it (see
703
+ * `fleet-read-census.ts#siteOf`).
704
+ */
705
+ async listAll(callerAddonId) {
706
+ return this.list({
707
+ orderBy: {
708
+ field: "deviceId",
709
+ direction: "asc"
710
+ },
711
+ limit: DEVICE_ROWS_FLEET_LIMIT
712
+ }, void 0, callerAddonId);
713
+ }
714
+ /**
715
+ * The fleet, read as narrowly as the question allows.
716
+ *
717
+ * `listAll` is a full-table `SELECT … ORDER BY "deviceId"` — ~1 017 rows a
718
+ * call on the live hub, 14–54 calls a minute — and its callers then filtered
719
+ * the result in JS. The two filters that CAN be pushed down are here:
720
+ *
721
+ * - `deviceIds` becomes a `whereIn`. The viewer's linked-devices panel asks
722
+ * about ~8 named ids; it was answered by reading the whole ledger. An
723
+ * EMPTY set reads nothing at all rather than degrading to "everything" —
724
+ * a request for no devices is a request, not an omission.
725
+ * - `slim` becomes a column projection, {@link DEVICE_ROWS_SLIM_COLUMNS}.
726
+ *
727
+ * `isCamera` is deliberately NOT one of them — see that constant's note and
728
+ * `device-row-store-filtered.spec.ts`.
729
+ *
730
+ * `callerAddonId` — see {@link listAll}'s doc; same meaning here.
731
+ */
732
+ async listFleet(opts, callerAddonId) {
733
+ if (opts.deviceIds !== void 0 && opts.deviceIds.length === 0) return [];
734
+ return this.list({
735
+ ...opts.deviceIds !== void 0 ? { whereIn: { deviceId: [...new Set(opts.deviceIds)] } } : {},
736
+ orderBy: {
737
+ field: "deviceId",
738
+ direction: "asc"
739
+ },
740
+ limit: DEVICE_ROWS_FLEET_LIMIT
741
+ }, opts.slim === true ? DEVICE_ROWS_SLIM_COLUMNS : void 0, callerAddonId);
742
+ }
743
+ /**
744
+ * Many devices, by numeric id, in ONE query.
745
+ *
746
+ * `get(id)` called once per id in a loop is the primary-key lookup this
747
+ * store exists to make cheap, repeated until it isn't — measured on the
748
+ * live hub 2026-08-25: `get device-manager:devices` at 1 656 calls/min
749
+ * steady-state and 17 687 during boot, exactly one row per call. This
750
+ * collapses that into the same `whereIn` {@link listFleet} already does for
751
+ * a fleet read, keyed by id.
752
+ *
753
+ * A requested id the fleet does not know is simply ABSENT from the map —
754
+ * never a fabricated row, matching {@link get}'s `null`. An empty `ids`
755
+ * reads nothing at all, same as `listFleet({ deviceIds: [] })`.
756
+ */
757
+ async getMany(ids) {
758
+ const rows = await this.listFleet({ deviceIds: ids });
759
+ return new Map(rows.map((row) => [row.meta.id, row]));
760
+ }
761
+ /**
762
+ * The device an addon knows as `stableId`, or `null`.
763
+ *
764
+ * `(addonId, stableId)` is the addon-facing identity — unique by
765
+ * construction, since `allocateDeviceId` is the only thing that mints a row
766
+ * and it returns the existing id for a pair it already knows. A second row
767
+ * for the pair would be a corruption, so this takes the LOWEST id and says
768
+ * so rather than picking arbitrarily.
769
+ */
770
+ async findByStableId(addonId, stableId) {
771
+ const rows = await this.list({
772
+ where: {
773
+ addonId,
774
+ stableId
775
+ },
776
+ orderBy: {
777
+ field: "deviceId",
778
+ direction: "asc"
779
+ },
780
+ limit: 2
781
+ });
782
+ const first = rows[0];
783
+ if (first === void 0) return null;
784
+ if (rows.length > 1) this.logger.warn("duplicate device rows for one (addonId, stableId) — using the lowest id", {
785
+ tags: { deviceId: first.meta.id },
786
+ meta: {
787
+ addonId,
788
+ stableId,
789
+ ids: rows.map((r) => r.meta.id)
790
+ }
791
+ });
792
+ return first;
793
+ }
794
+ /**
795
+ * The device that owns a template alias, or `null`. Aliases are unique, so a
796
+ * second row for one alias would be a corruption: the LOWEST id is answered and
797
+ * the duplicate is said on the record.
798
+ */
799
+ async findByAlias(alias) {
800
+ const rows = await this.list({
801
+ where: { alias },
802
+ orderBy: {
803
+ field: "deviceId",
804
+ direction: "asc"
805
+ },
806
+ limit: 2
807
+ });
808
+ const first = rows[0];
809
+ if (first === void 0) return null;
810
+ if (rows.length > 1) this.logger.warn("duplicate device rows for one alias — using the lowest id", {
811
+ tags: { deviceId: first.meta.id },
812
+ meta: {
813
+ alias,
814
+ ids: rows.map((r) => r.meta.id)
815
+ }
816
+ });
817
+ return first;
818
+ }
819
+ /** Every device owned by one addon, ordered by numeric id. */
820
+ async listByAddon(addonId) {
821
+ return this.list({
822
+ where: { addonId },
823
+ orderBy: {
824
+ field: "deviceId",
825
+ direction: "asc"
826
+ },
827
+ limit: DEVICE_ROWS_FLEET_LIMIT
828
+ });
829
+ }
830
+ /** Every device an integration owns, ordered by numeric id. */
831
+ async listByIntegration(integrationId) {
832
+ return this.list({
833
+ where: { integrationId },
834
+ orderBy: {
835
+ field: "deviceId",
836
+ direction: "asc"
837
+ },
838
+ limit: DEVICE_ROWS_FLEET_LIMIT
839
+ });
840
+ }
841
+ /** Direct children of one device, ordered by numeric id. */
842
+ async listByParent(parentDeviceId) {
843
+ return this.list({
844
+ where: { parentDeviceId },
845
+ orderBy: {
846
+ field: "deviceId",
847
+ direction: "asc"
848
+ },
849
+ limit: DEVICE_ROWS_FLEET_LIMIT
850
+ });
851
+ }
852
+ /**
853
+ * Direct children of MANY devices, in ONE query.
854
+ *
855
+ * `listByParent` called once per parent is the same shape `get` was before
856
+ * {@link getMany}: an indexed lookup this store makes cheap, repeated until
857
+ * it isn't. Measured on the live hub 2026-08-27, 120-second boot window:
858
+ * `DeviceRowStore.list < DeviceRowStore.listByParent < getChildren` at
859
+ * **1 024 calls** — one per device — for 919 rows in total. The BFS in
860
+ * `device-meta-actions.ts#collectDescendants` walked a container tree the
861
+ * same way, one query per node.
862
+ *
863
+ * `whereIn` on the indexed `parentDeviceId` column collapses a level of that
864
+ * walk into a single statement. Contract, verbatim from {@link getMany}: an
865
+ * EMPTY `parentDeviceIds` reads nothing at all rather than degrading to
866
+ * "everything", and a parent with no children — or one the fleet does not
867
+ * know — is simply ABSENT from the map, never an invented empty row.
868
+ */
869
+ async listByParentMany(parentDeviceIds) {
870
+ const out = /* @__PURE__ */ new Map();
871
+ const unique = [...new Set(parentDeviceIds)];
872
+ if (unique.length === 0) return out;
873
+ const rows = await this.list({
874
+ whereIn: { parentDeviceId: unique },
875
+ orderBy: {
876
+ field: "deviceId",
877
+ direction: "asc"
878
+ },
879
+ limit: DEVICE_ROWS_FLEET_LIMIT
880
+ });
881
+ const byParent = /* @__PURE__ */ new Map();
882
+ for (const row of rows) {
883
+ const parent = row.meta.parentDeviceId;
884
+ if (parent === null || parent === void 0) continue;
885
+ const bucket = byParent.get(parent);
886
+ if (bucket === void 0) byParent.set(parent, [row]);
887
+ else bucket.push(row);
888
+ }
889
+ for (const [parent, bucket] of byParent) out.set(parent, bucket);
890
+ return out;
891
+ }
892
+ /** How many devices the fleet holds. Used to tell "empty store" from "gone device". */
893
+ async count() {
894
+ await this.declare();
895
+ return this.backend.count({ collection: DEVICE_ROWS_COLLECTION });
896
+ }
897
+ async list(filter, columns, callerAddonId) {
898
+ const site = this.census.siteOf(callerAddonId);
899
+ await this.declare();
900
+ const records = await this.backend.query({
901
+ collection: DEVICE_ROWS_COLLECTION,
902
+ filter,
903
+ ...columns === void 0 ? {} : { columns }
904
+ });
905
+ this.census.record(site, records.length);
906
+ const out = [];
907
+ for (const record of records) {
908
+ const decoded = decodeDeviceRow(record.data);
909
+ if (decoded === null) {
910
+ this.logger.warn("device row skipped — identity fields missing", { meta: { rowId: record.id } });
911
+ continue;
912
+ }
913
+ out.push(decoded);
914
+ }
915
+ return out;
916
+ }
917
+ /** Insert or replace the whole identity row. */
918
+ async upsert(meta, extra = {}) {
919
+ await this.declare();
920
+ await this.backend.set({
921
+ collection: DEVICE_ROWS_COLLECTION,
922
+ key: String(meta.id),
923
+ value: encodeDeviceRow(meta, extra)
924
+ });
925
+ this.observer?.rowWritten(meta);
926
+ }
927
+ /**
928
+ * Write the named columns of an EXISTING row and nothing else.
929
+ *
930
+ * An UPDATE, deliberately not an upsert: a partial upsert would try to INSERT
931
+ * a row carrying only the patched columns, and SQLite rejects that on the
932
+ * `NOT NULL` identity columns before the primary-key conflict can turn it
933
+ * into an update. Every caller resolves the row under the write lock and
934
+ * throws when it is gone, so matching zero rows means a device was removed
935
+ * between the resolve and the write — the patch is lost, and a lost write
936
+ * that says nothing reads as a write that happened.
937
+ */
938
+ async patch(deviceId, patch) {
939
+ const columns = encodeDeviceRowPatch(patch);
940
+ if (Object.keys(columns).length === 0) return;
941
+ await this.declare();
942
+ const { updated } = await this.backend.updateWhere({
943
+ collection: DEVICE_ROWS_COLLECTION,
944
+ filter: { where: { id: String(deviceId) } },
945
+ data: columns
946
+ });
947
+ if (updated === 0) {
948
+ this.logger.warn("device row patch matched no row — the device was removed under it", {
949
+ tags: { deviceId },
950
+ meta: { columns: Object.keys(columns) }
951
+ });
952
+ return;
953
+ }
954
+ this.observer?.rowPatched(deviceId, patch);
955
+ }
956
+ /**
957
+ * Insert-or-update the registration columns. See {@link DeviceRegistrationRow}
958
+ * for why this is a separate, fully-specified statement rather than a patch.
959
+ */
960
+ async upsertRegistration(row) {
961
+ await this.declare();
962
+ await this.backend.set({
963
+ collection: DEVICE_ROWS_COLLECTION,
964
+ key: String(row.deviceId),
965
+ value: {
966
+ deviceId: row.deviceId,
967
+ addonId: row.addonId,
968
+ stableId: row.stableId,
969
+ type: row.type,
970
+ name: row.name,
971
+ userNamed: row.userNamed,
972
+ location: row.location,
973
+ disabled: row.disabled,
974
+ parentDeviceId: row.parentDeviceId,
975
+ registered: row.registered,
976
+ features: [...row.features],
977
+ exportFingerprint: row.exportFingerprint
978
+ }
979
+ });
980
+ this.observer?.registrationWritten(row);
981
+ }
982
+ /** Drop the device's row. Idempotent. */
983
+ /**
984
+ * Exchange the ids of two devices, carrying their children with them.
985
+ *
986
+ * ## Why this exists as a primitive
987
+ *
988
+ * Replacing a camera means the new hardware has to become the device the rest
989
+ * of the system already knows. Everything general about a camera is keyed on
990
+ * the NUMERIC id and on nothing else — the recording path on disk is
991
+ * `<deviceId>/profile/…`, the hour ledger, the media store and zone ownership
992
+ * carry `deviceId` and not one `stableId` between them, and all four
993
+ * ecosystem exports (Home Assistant, Alexa, HomeKit, Google) key on it too.
994
+ * Moving that work is the expensive, lossy operation. Moving the NUMBER is
995
+ * two rows.
996
+ *
997
+ * ## Children are re-pointed, not renumbered
998
+ *
999
+ * A child keeps its own id and follows its parent: every row whose
1000
+ * `parentDeviceId` was `a` now names `b`, and the reverse. Renumbering the
1001
+ * children as well would move THEIR general work for no reason — the
1002
+ * accessory's own recordings and rules are keyed on the child id, which is
1003
+ * not the id being inherited.
1004
+ *
1005
+ * ## There are no transactions here, so the ORDER is the safety
1006
+ *
1007
+ * The backing store is a collection API (`set` / `delete` / `updateWhere`);
1008
+ * there is no rollback to lean on. So the sequence is chosen to make every
1009
+ * crash point LOUD rather than plausible: `a` first moves to a freshly
1010
+ * allocated id, which the monotonic counter guarantees was never used and
1011
+ * will never be reused. A crash before the end therefore leaves a device
1012
+ * missing from its number and a stray at an unfamiliar one — visible in the
1013
+ * device list at a glance. What it can never leave is two rows on one number,
1014
+ * or a row that looks correct while its children point elsewhere.
1015
+ *
1016
+ * The caller holds {@link DeviceMetaStore.withMetaWriteLock}. This method does
1017
+ * not take it: taking it here would deadlock the migration that has to disable
1018
+ * functions on both devices in the same critical section.
1019
+ */
1020
+ async swapIds(a, b, tempId) {
1021
+ const { rowA, rowB, childrenOfA, childrenOfB } = await this.planSwap(a, b, tempId).catch((err) => {
1022
+ if (err instanceof MigrationRefusedError) throw err;
1023
+ throw new MigrationRefusedError(`[device-manager] swapIds: precheck failed before any row moved — ${err instanceof Error ? err.message : String(err)}`, { cause: err });
1024
+ });
1025
+ await this.moveRow(rowA, tempId);
1026
+ await this.moveRow(rowB, a);
1027
+ await this.moveRow({
1028
+ ...rowA,
1029
+ meta: {
1030
+ ...rowA.meta,
1031
+ id: tempId
1032
+ }
1033
+ }, b);
1034
+ for (const childId of childrenOfA) await this.patch(childId, { parentDeviceId: b });
1035
+ for (const childId of childrenOfB) await this.patch(childId, { parentDeviceId: a });
1036
+ this.logger.info("device ids swapped", {
1037
+ tags: { deviceId: a },
1038
+ meta: {
1039
+ a,
1040
+ b,
1041
+ childrenOfA,
1042
+ childrenOfB
1043
+ }
1044
+ });
1045
+ }
1046
+ /** The read-only half of {@link swapIds}: every refusal, every read, no write. */
1047
+ async planSwap(a, b, tempId) {
1048
+ if (a === b) throw new MigrationRefusedError(`[device-manager] swapIds: ${a} and ${b} are the same device`);
1049
+ await this.declare();
1050
+ const rowA = await this.get(a);
1051
+ const rowB = await this.get(b);
1052
+ if (rowA === null) throw new MigrationRefusedError(`[device-manager] swapIds: device ${a} does not exist`);
1053
+ if (rowB === null) throw new MigrationRefusedError(`[device-manager] swapIds: device ${b} does not exist`);
1054
+ if (await this.get(tempId) !== null) throw new MigrationRefusedError(`[device-manager] swapIds: temp id ${tempId} is taken`);
1055
+ return {
1056
+ rowA,
1057
+ rowB,
1058
+ childrenOfA: (await this.listByParent(a)).map((r) => r.meta.id),
1059
+ childrenOfB: (await this.listByParent(b)).map((r) => r.meta.id)
1060
+ };
1061
+ }
1062
+ /** Rewrite a row under a new id and drop the old key. Not exported: the only
1063
+ * legitimate reason to move a row is {@link swapIds}. */
1064
+ async moveRow(row, toId) {
1065
+ await this.upsert({
1066
+ ...row.meta,
1067
+ id: toId
1068
+ }, {
1069
+ registered: row.registered,
1070
+ metadata: row.metadata
1071
+ });
1072
+ await this.remove(row.meta.id);
1073
+ }
1074
+ async remove(deviceId) {
1075
+ await this.declare();
1076
+ await this.backend.delete({
1077
+ collection: DEVICE_ROWS_COLLECTION,
1078
+ key: String(deviceId)
1079
+ });
1080
+ this.observer?.rowRemoved(deviceId);
1081
+ }
1082
+ /**
1083
+ * The retirement door for the three blobs this collection replaced.
1084
+ *
1085
+ * The purge is gated on THIS collection being non-empty, and the count has to
1086
+ * be taken after `declare()` — which is why the owning addon runs it and the
1087
+ * settings engine cannot: at the engine's own boot no addon has declared
1088
+ * anything, so every successor would read as unreadable, forever.
1089
+ */
1090
+ retiredRowStore() {
1091
+ return {
1092
+ hasRow: async (spec) => {
1093
+ const raw = await this.backend.get({
1094
+ collection: spec.collection,
1095
+ key: spec.row
1096
+ });
1097
+ return raw !== void 0 && raw !== null;
1098
+ },
1099
+ deleteRow: async (spec) => {
1100
+ await this.backend.delete({
1101
+ collection: spec.collection,
1102
+ key: spec.row
1103
+ });
1104
+ },
1105
+ countRows: async (collection) => {
1106
+ await this.declare();
1107
+ return this.backend.count({ collection });
1108
+ }
1109
+ };
1110
+ }
1111
+ };
1112
+ //#endregion
1113
+ export { MigrationRefusedError as a, deviceManagerRecordKinds as i, DeviceRowStore as n, deviceRowBackendOf as r, DEVICE_ROWS_COLLECTION as t };