@camstack/system 1.2.107 → 1.2.108

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.
@@ -4,6 +4,7 @@ Object.defineProperties(exports, {
4
4
  });
5
5
  require("../../chunk-Cek0wNdY.js");
6
6
  const require_dist = require("../../dist-Ctfhlrtl.js");
7
+ const require_retired_settings_keys = require("../../retired-settings-keys-pNmoHPTg.js");
7
8
  let node_crypto = require("node:crypto");
8
9
  let _camstack_types_node = require("@camstack/types/node");
9
10
  //#region src/builtins/device-manager/adoption-job-engine.ts
@@ -294,6 +295,442 @@ var AdoptionJobEngine = class {
294
295
  }
295
296
  };
296
297
  //#endregion
298
+ //#region src/builtins/device-manager/device-aggregation-merge.ts
299
+ /**
300
+ * Pure aggregator-merge + field-tagging helpers for the device-manager
301
+ * device-details aggregator. Extracted verbatim from
302
+ * `device-manager.addon.ts`. These functions are stateless: they take
303
+ * contributions in and return new wire-shape objects, attaching writer
304
+ * provenance to editable fields. No addon-instance dependency.
305
+ *
306
+ * `mergeAggregates` is re-exported from the addon module to preserve the
307
+ * existing public export surface the test-suite imports.
308
+ */
309
+ /**
310
+ * Walk the sections/fields of a contribution and inject `writerCapName` +
311
+ * `writerAddonId` + `source` on each editable field. Readonly fields and
312
+ * structural fields (separator/info/button) pass through untouched. The
313
+ * aggregator is the single place that knows provenance — provider schemas
314
+ * stay clean, UI-bound metadata is attached once at the boundary.
315
+ */
316
+ function tagContribution(contribution, capName, addonId, kind) {
317
+ const source = kind === "settings" ? "settings" : "live";
318
+ return {
319
+ ...contribution.tabs ? { tabs: [...contribution.tabs] } : {},
320
+ sections: contribution.sections.map((section) => ({
321
+ ...section,
322
+ fields: section.fields.map((field) => tagField(field, capName, addonId, source, kind))
323
+ }))
324
+ };
325
+ }
326
+ function isFieldRecord(value) {
327
+ return value !== null && typeof value === "object" && !Array.isArray(value);
328
+ }
329
+ /**
330
+ * Convert a strict `ConfigUISchemaWithValues` (readonly arrays, typed
331
+ * field union) into the cap wire shape `ContributionShape` (mutable
332
+ * arrays, opaque field records). Required because the cap method z.infer
333
+ * uses mutable arrays — readonly arrays are not assignable to mutable
334
+ * even when structurally identical, so a structural copy bridges the gap
335
+ * without disabling the type checker.
336
+ */
337
+ function toWireShape(input) {
338
+ const out = { sections: input.sections.map((s) => ({
339
+ id: s.id,
340
+ title: s.title,
341
+ ...s.description !== void 0 ? { description: s.description } : {},
342
+ ...s.style !== void 0 ? { style: s.style } : {},
343
+ ...s.defaultCollapsed !== void 0 ? { defaultCollapsed: s.defaultCollapsed } : {},
344
+ ...s.columns !== void 0 ? { columns: s.columns } : {},
345
+ ...s.tab !== void 0 ? { tab: s.tab } : {},
346
+ ...s.location !== void 0 ? { location: s.location } : {},
347
+ ...s.order !== void 0 ? { order: s.order } : {},
348
+ fields: [...s.fields]
349
+ })) };
350
+ if (input.tabs) out.tabs = [...input.tabs];
351
+ return out;
352
+ }
353
+ function tagField(field, capName, addonId, source, kind) {
354
+ if (!isFieldRecord(field)) return field;
355
+ const f = field;
356
+ const structuralTypes = new Set([
357
+ "separator",
358
+ "info",
359
+ "button"
360
+ ]);
361
+ if (typeof f.type === "string" && structuralTypes.has(f.type)) return field;
362
+ const tagged = {
363
+ ...f,
364
+ source
365
+ };
366
+ if (kind === "live" || f.readonlyField === true) tagged.readonlyField = true;
367
+ else {
368
+ tagged.writerCapName = capName;
369
+ tagged.writerAddonId = addonId;
370
+ }
371
+ if (f.type === "group") {
372
+ const children = Array.isArray(f.fields) ? f.fields : [];
373
+ if (children.length > 0) tagged.fields = children.map((child) => tagField(child, capName, addonId, source, kind));
374
+ } else if (f.type === "sub-tabs") {
375
+ const rawTabs = Array.isArray(f.tabs) ? f.tabs : [];
376
+ if (rawTabs.length > 0) tagged.tabs = rawTabs.map((tab) => {
377
+ if (!isFieldRecord(tab)) return tab;
378
+ const tabChildren = Array.isArray(tab.fields) ? tab.fields : [];
379
+ return {
380
+ ...tab,
381
+ fields: tabChildren.map((child) => tagField(child, capName, addonId, source, kind))
382
+ };
383
+ });
384
+ }
385
+ return tagged;
386
+ }
387
+ function mergeAggregates(parts) {
388
+ const tabDecls = /* @__PURE__ */ new Map();
389
+ const sections = [];
390
+ const seenSectionIds = /* @__PURE__ */ new Set();
391
+ for (const part of parts) {
392
+ if (part.tabs) {
393
+ for (const t of part.tabs) if (!tabDecls.has(t.id)) tabDecls.set(t.id, t);
394
+ }
395
+ for (const s of part.sections) {
396
+ if (s.id !== void 0) {
397
+ if (seenSectionIds.has(s.id)) continue;
398
+ seenSectionIds.add(s.id);
399
+ }
400
+ sections.push(s);
401
+ }
402
+ }
403
+ for (const s of sections) {
404
+ const tabId = s.tab ?? "general";
405
+ if (tabDecls.has(tabId)) continue;
406
+ const known = require_dist.WELL_KNOWN_TAB_MAP[tabId];
407
+ if (known) tabDecls.set(tabId, {
408
+ id: known.id,
409
+ label: known.label,
410
+ icon: known.icon,
411
+ order: known.order
412
+ });
413
+ else tabDecls.set(tabId, {
414
+ id: tabId,
415
+ label: tabId,
416
+ icon: "wrench",
417
+ order: 100
418
+ });
419
+ }
420
+ sections.sort((a, b) => {
421
+ const tabA = a.tab ?? "general";
422
+ const tabB = b.tab ?? "general";
423
+ if (tabA !== tabB) {
424
+ const orderA = tabDecls.get(tabA)?.order ?? 100;
425
+ const orderB = tabDecls.get(tabB)?.order ?? 100;
426
+ if (orderA !== orderB) return orderA - orderB;
427
+ return tabA.localeCompare(tabB);
428
+ }
429
+ return (a.order ?? 0) - (b.order ?? 0);
430
+ });
431
+ const sortedTabs = [...tabDecls.values()].toSorted((a, b) => (a.order ?? 100) - (b.order ?? 100));
432
+ const out = { sections };
433
+ if (sortedTabs.length > 0) out.tabs = sortedTabs;
434
+ return out;
435
+ }
436
+ //#endregion
437
+ //#region src/builtins/device-manager/device-bindings-store.ts
438
+ /**
439
+ * Wire the push-fed cross-process native-cap cache (`remoteNativeCaps`).
440
+ * Workers emit `DeviceBindingsChanged` on `ctx.registerNativeCap` / device
441
+ * removal; we mirror those into `remoteNativeCaps` so `getBindings` returns the
442
+ * full cluster view. Events from the local node are ignored: hub-local natives
443
+ * live in `capabilityRegistry` and are folded in directly by getBindings.
444
+ *
445
+ * Push events are accurate in the steady state but can be lost during the
446
+ * Moleculer transport handshake window (hub restart, crash-respawn,
447
+ * restartAddon). The reliable replacement for lost events is the D3 re-handshake
448
+ * (`listClusterNativeCaps()`), which `resolveNativeCapOwnerSync` /
449
+ * `getBindings` step 4 fall through to on a push miss. The `$node.disconnected`
450
+ * handler purges a gone node's entries; the worker re-handshakes (and re-emits
451
+ * `native-registered`) on its next boot.
452
+ */
453
+ function wireRemoteNativeCapSync(ctx, remoteNativeCaps) {
454
+ const localNodeId = ctx.kernel.localNodeId ?? "hub";
455
+ ctx.eventBus.subscribe({ category: require_dist.EventCategory.DeviceBindingsChanged }, (event) => {
456
+ const { deviceId, capName, reason, addonId, nodeId } = event.data;
457
+ if (nodeId === localNodeId) return;
458
+ if (reason === "native-registered") {
459
+ let perDevice = remoteNativeCaps.get(deviceId);
460
+ if (!perDevice) {
461
+ perDevice = /* @__PURE__ */ new Map();
462
+ remoteNativeCaps.set(deviceId, perDevice);
463
+ }
464
+ perDevice.set(capName, {
465
+ addonId,
466
+ nodeId
467
+ });
468
+ } else if (reason === "native-unregistered") {
469
+ const perDevice = remoteNativeCaps.get(deviceId);
470
+ if (!perDevice) return;
471
+ perDevice.delete(capName);
472
+ if (perDevice.size === 0) remoteNativeCaps.delete(deviceId);
473
+ }
474
+ });
475
+ const cluster = ctx.kernel.cluster;
476
+ if (cluster) cluster.broker.localBus.on("$node.disconnected", (payload) => {
477
+ const gone = payload.node.id;
478
+ const emptyDevices = [];
479
+ for (const [deviceId, perDevice] of remoteNativeCaps) {
480
+ const toDelete = [];
481
+ for (const [capName, entry] of perDevice) if (entry.nodeId === gone) toDelete.push(capName);
482
+ for (const capName of toDelete) perDevice.delete(capName);
483
+ if (perDevice.size === 0) emptyDevices.push(deviceId);
484
+ }
485
+ for (const deviceId of emptyDevices) remoteNativeCaps.delete(deviceId);
486
+ });
487
+ }
488
+ async function readBindingsStore(deps) {
489
+ return { deviceBindings: (await deps.ctx.settings.readAddonStore()).deviceBindings ?? {} };
490
+ }
491
+ async function writeBindingsStore(deps, next) {
492
+ await deps.ctx.settings.writeAddonStore({ deviceBindings: next.deviceBindings });
493
+ }
494
+ function resolveWrapperNodeId(_wrapperAddonId) {
495
+ return "hub";
496
+ }
497
+ /**
498
+ * Reduce a provider node id to the routable form `DeviceProxy` can pin.
499
+ *
500
+ * Every addon runs in its own `addon-runner` with the composite node id
501
+ * `${parentNodeId}/${runnerId}` (see `addon-runner.ts`) — e.g.
502
+ * `hub/provider-reolink` or `dev-agent-0/provider-reolink`. That composite is
503
+ * an IDENTITY, not a routable target: the `CapRouteResolver` reaches a child
504
+ * only THROUGH its parent (the hub resolves a hub-local-uds child by
505
+ * cap+device; an agent forwards to its own child). `DeviceProxy` pins
506
+ * `entry.providerNodeId` on every cap call, so a binding entry must expose the
507
+ * parent node id — otherwise the explicit pin classifies as `remote-moleculer`
508
+ * to an unknown node → `no-provider`, which surfaces as
509
+ * "this camera doesn't expose …" for client-proxy-driven widget caps
510
+ * (motion-zones, privacy-mask). Wrappers already report the parent via
511
+ * `resolveWrapperNodeId`; this aligns natives with the same contract.
512
+ *
513
+ * A flat node id (a genuine standalone node with no `/`) is returned
514
+ * unchanged.
515
+ */
516
+ function toRoutableProviderNodeId(nodeId) {
517
+ const slash = nodeId.indexOf("/");
518
+ return slash === -1 ? nodeId : nodeId.slice(0, slash);
519
+ }
520
+ /**
521
+ * Resolve a remote native cap entry for a given `(capName, deviceId)` by
522
+ * consulting the handshake-fed `HubNodeRegistry` via
523
+ * `ctx.kernel.listClusterNativeCaps()`. Called when the push-based
524
+ * `remoteNativeCaps` cache misses — covers the Moleculer transport
525
+ * handshake window where `DeviceBindingsChanged` events were lost but the
526
+ * D3 re-handshake (post device restore) has already populated the registry.
527
+ *
528
+ * Returns `null` when the entry is genuinely not present in the cluster
529
+ * view (cap not registered on any worker for that device).
530
+ */
531
+ function resolveRemoteNativeCapFromRegistry(deps, capName, deviceId) {
532
+ const clusterCaps = deps.ctx.kernel.listClusterNativeCapsForDevice?.(deviceId) ?? deps.ctx.kernel.listClusterNativeCaps?.();
533
+ if (!clusterCaps) return null;
534
+ for (const entry of clusterCaps) if (entry.capName === capName && entry.deviceId === deviceId && entry.addonId) return {
535
+ addonId: entry.addonId,
536
+ nodeId: entry.nodeId
537
+ };
538
+ return null;
539
+ }
540
+ /**
541
+ * Resolve the device's declared TYPE (`'camera'`, `'event-emitter'`, …), or
542
+ * `undefined` when it cannot be established.
543
+ *
544
+ * The PERSISTED row is the authority: `ctx.kernel.deviceRegistry` is hub-only
545
+ * and has been observed empty in the very process that answers `getBindings`
546
+ * correctly (see the note on `getAllBindings`). The registry is consulted only
547
+ * as a secondary source, for a device constructed but not yet persisted.
548
+ *
549
+ * `undefined` is a first-class answer and callers must treat it as "no
550
+ * filtering" — an absent row must never be the reason a device loses bindings.
551
+ */
552
+ function resolveDeviceType(deps, row, deviceId) {
553
+ const persisted = row?.meta.type;
554
+ if (typeof persisted === "string" && persisted.length > 0) return persisted;
555
+ const live = deps.ctx.kernel?.deviceRegistry?.getById(deviceId)?.type;
556
+ return typeof live === "string" && live.length > 0 ? live : void 0;
557
+ }
558
+ /**
559
+ * Is this device still part of the fleet?
560
+ *
561
+ * The device-manager's own stores are the authority in-process — no RPC. Two
562
+ * sources, in the same order `resolveDeviceType` uses them: the live registry
563
+ * first (a device constructed but not yet persisted is present), then the
564
+ * PERSISTED meta, which is the index `getBindings` already reads and is present
565
+ * wherever this provider runs.
566
+ *
567
+ * `'absent'` is only ever returned against a NON-EMPTY ledger. An empty one
568
+ * means device restore has not run, not that the fleet was deleted (D49) — the
569
+ * same reason `getAllBindings` warns instead of reporting zero devices. That is
570
+ * the only reason this is async: the `COUNT(*)` runs solely on the miss path,
571
+ * where the alternative is to call a device gone because the store is empty.
572
+ */
573
+ async function resolveDevicePresence(deps, row, deviceId) {
574
+ if (deps.ctx.kernel?.deviceRegistry?.getById(deviceId)) return "present";
575
+ if (row !== null) return "present";
576
+ return await deps.rows.count() > 0 ? "absent" : "unknown";
577
+ }
578
+ /**
579
+ * Does a capability apply to a device of type `deviceType`?
580
+ *
581
+ * The cap's `deviceTypes` is the ONLY declaration consulted (D4: behavioural
582
+ * cap metadata lives in the `*.cap.ts`, never in a manifest). Two deliberate
583
+ * fail-open cases:
584
+ *
585
+ * - a cap that declares no `deviceTypes` (or an empty list) applies to every
586
+ * device — the pre-existing, back-compatible semantics;
587
+ * - an UNKNOWN `deviceType` never filters, so a missing/failed meta lookup
588
+ * changes nothing (D49: a read that fails must not destroy work).
589
+ */
590
+ function capAppliesToDeviceType(def, deviceType) {
591
+ if (deviceType === void 0) return true;
592
+ const declared = def?.deviceTypes;
593
+ if (!declared || declared.length === 0) return true;
594
+ return declared.some((t) => t === deviceType);
595
+ }
596
+ async function getBindings(deps, input) {
597
+ const storeKey = String(input.deviceId);
598
+ const perDevice = (await readBindingsStore(deps)).deviceBindings[storeKey] ?? {};
599
+ const row = await deps.rows.get(input.deviceId);
600
+ const deviceType = resolveDeviceType(deps, row, input.deviceId);
601
+ const presence = await resolveDevicePresence(deps, row, input.deviceId);
602
+ const entries = [];
603
+ const seenCaps = /* @__PURE__ */ new Set();
604
+ const resolveRemote = (capName) => deps.remoteNativeCaps.get(input.deviceId)?.get(capName) ?? resolveRemoteNativeCapFromRegistry(deps, capName, input.deviceId);
605
+ for (const [capName, { wrapperAddonId }] of Object.entries(perDevice)) {
606
+ const hubLocalNative = deps.capabilityRegistry?.getNativeAddonId(capName, input.deviceId) ?? null;
607
+ const remoteNative = resolveRemote(capName);
608
+ const nativeAddonId = hubLocalNative ?? remoteNative?.addonId ?? "";
609
+ const nativeNodeId = hubLocalNative ? deps.ctx.kernel.localNodeId ?? "hub" : remoteNative?.nodeId ?? deps.ctx.kernel.localNodeId ?? "hub";
610
+ if (wrapperAddonId === null && !nativeAddonId) {
611
+ seenCaps.add(capName);
612
+ continue;
613
+ }
614
+ entries.push({
615
+ capName,
616
+ kind: wrapperAddonId ? "wrapped" : "native",
617
+ providerAddonId: wrapperAddonId ?? nativeAddonId,
618
+ providerNodeId: wrapperAddonId ? resolveWrapperNodeId(wrapperAddonId) : toRoutableProviderNodeId(nativeNodeId),
619
+ nativeAddonId
620
+ });
621
+ seenCaps.add(capName);
622
+ }
623
+ if (presence === "absent") deps.ctx.logger.debug("bindings requested for absent device — returning none", { tags: { deviceId: input.deviceId } });
624
+ else if (deps.capabilityRegistry) {
625
+ const skippedForType = [];
626
+ for (const capName of deps.capabilityRegistry.getCapsWithDefaultWrapper()) {
627
+ if (seenCaps.has(capName)) continue;
628
+ if (!capAppliesToDeviceType(deps.capabilityRegistry.getDefinition(capName), deviceType)) {
629
+ skippedForType.push(capName);
630
+ continue;
631
+ }
632
+ const defaultWrapperAddonId = deps.capabilityRegistry.getDefaultWrapperForCap(capName);
633
+ if (!defaultWrapperAddonId) continue;
634
+ const hubLocalNative = deps.capabilityRegistry.getNativeAddonId(capName, input.deviceId) ?? null;
635
+ const remoteNative = resolveRemote(capName);
636
+ const nativeAddonId = hubLocalNative ?? remoteNative?.addonId ?? "";
637
+ entries.push({
638
+ capName,
639
+ kind: "wrapped",
640
+ providerAddonId: defaultWrapperAddonId,
641
+ providerNodeId: resolveWrapperNodeId(defaultWrapperAddonId),
642
+ nativeAddonId
643
+ });
644
+ seenCaps.add(capName);
645
+ }
646
+ if (skippedForType.length > 0) deps.ctx.logger.debug("getBindings: default wrappers skipped — deviceTypes mismatch", {
647
+ tags: { deviceId: input.deviceId },
648
+ meta: {
649
+ deviceType,
650
+ skipped: skippedForType
651
+ }
652
+ });
653
+ }
654
+ if (deps.capabilityRegistry) for (const capName of deps.capabilityRegistry.getNativeCapsForDevice(input.deviceId)) {
655
+ if (seenCaps.has(capName)) continue;
656
+ const nativeAddonId = deps.capabilityRegistry.getNativeAddonId(capName, input.deviceId) ?? "";
657
+ entries.push({
658
+ capName,
659
+ kind: "native",
660
+ providerAddonId: nativeAddonId,
661
+ providerNodeId: deps.ctx.kernel.localNodeId ?? "hub",
662
+ nativeAddonId
663
+ });
664
+ seenCaps.add(capName);
665
+ }
666
+ const pushFed = deps.remoteNativeCaps.get(input.deviceId);
667
+ if (pushFed) for (const [capName, info] of pushFed) {
668
+ if (seenCaps.has(capName)) continue;
669
+ entries.push({
670
+ capName,
671
+ kind: "native",
672
+ providerAddonId: info.addonId,
673
+ providerNodeId: toRoutableProviderNodeId(info.nodeId),
674
+ nativeAddonId: info.addonId
675
+ });
676
+ seenCaps.add(capName);
677
+ }
678
+ const clusterCaps = deps.ctx.kernel.listClusterNativeCapsForDevice?.(input.deviceId) ?? deps.ctx.kernel.listClusterNativeCaps?.();
679
+ if (clusterCaps) for (const entry of clusterCaps) {
680
+ if (entry.deviceId !== input.deviceId) continue;
681
+ if (seenCaps.has(entry.capName)) continue;
682
+ if (!entry.addonId) continue;
683
+ const localNodeId = deps.ctx.kernel.localNodeId ?? "hub";
684
+ if (entry.nodeId === localNodeId) continue;
685
+ entries.push({
686
+ capName: entry.capName,
687
+ kind: "native",
688
+ providerAddonId: entry.addonId,
689
+ providerNodeId: toRoutableProviderNodeId(entry.nodeId),
690
+ nativeAddonId: entry.addonId
691
+ });
692
+ seenCaps.add(entry.capName);
693
+ }
694
+ return {
695
+ deviceId: input.deviceId,
696
+ entries
697
+ };
698
+ }
699
+ /**
700
+ * Whole-fleet binding dump. Iterates every device known to the
701
+ * deviceRegistry and reuses the per-device `getBindings` resolver
702
+ * for each — same routing rules, single round-trip. Used by
703
+ * `SystemManager.init()` for warm-boot.
704
+ *
705
+ * Bindings change rarely (wrapper toggle, device add/remove) so
706
+ * clients invalidate via the existing
707
+ * `capability.binding-changed` event rather than re-fetching this
708
+ * payload periodically.
709
+ */
710
+ async function getAllBindings(deps) {
711
+ const ids = /* @__PURE__ */ new Set();
712
+ for (const row of await deps.rows.listAll()) ids.add(row.meta.id);
713
+ const registered = deps.ctx.kernel?.deviceRegistry?.getAll() ?? [];
714
+ for (const device of registered) ids.add(device.id);
715
+ if (ids.size === 0) {
716
+ deps.ctx.logger.warn("getAllBindings found no devices — warm boot will see nothing", { meta: { hasRegistry: deps.ctx.kernel?.deviceRegistry !== void 0 } });
717
+ return [];
718
+ }
719
+ const out = [];
720
+ for (const deviceId of [...ids].sort((a, b) => a - b)) out.push(await getBindings(deps, { deviceId }));
721
+ return out;
722
+ }
723
+ /**
724
+ * Resolve a numeric deviceId to a stableId via persisted meta.
725
+ * Used only by the device-identity section of the device-details
726
+ * aggregator (see `buildBaseDeviceSection`) to surface the stableId as
727
+ * a readonly display field. All runtime/registry lookups are keyed by
728
+ * numeric deviceId; this helper is display-only.
729
+ */
730
+ async function lookupPersistedStableId(deps, deviceId) {
731
+ return (await deps.rows.get(deviceId))?.meta.stableId;
732
+ }
733
+ //#endregion
297
734
  //#region src/builtins/device-manager/day-night-config-schema.ts
298
735
  var MODE_LABELS = {
299
736
  auto: "Auto",
@@ -683,145 +1120,6 @@ function parseDerivedFormSettingsPatch(builderId, patch) {
683
1120
  return reducer.parsePatch(patch);
684
1121
  }
685
1122
  //#endregion
686
- //#region src/builtins/device-manager/device-aggregation-merge.ts
687
- /**
688
- * Pure aggregator-merge + field-tagging helpers for the device-manager
689
- * device-details aggregator. Extracted verbatim from
690
- * `device-manager.addon.ts`. These functions are stateless: they take
691
- * contributions in and return new wire-shape objects, attaching writer
692
- * provenance to editable fields. No addon-instance dependency.
693
- *
694
- * `mergeAggregates` is re-exported from the addon module to preserve the
695
- * existing public export surface the test-suite imports.
696
- */
697
- /**
698
- * Walk the sections/fields of a contribution and inject `writerCapName` +
699
- * `writerAddonId` + `source` on each editable field. Readonly fields and
700
- * structural fields (separator/info/button) pass through untouched. The
701
- * aggregator is the single place that knows provenance — provider schemas
702
- * stay clean, UI-bound metadata is attached once at the boundary.
703
- */
704
- function tagContribution(contribution, capName, addonId, kind) {
705
- const source = kind === "settings" ? "settings" : "live";
706
- return {
707
- ...contribution.tabs ? { tabs: [...contribution.tabs] } : {},
708
- sections: contribution.sections.map((section) => ({
709
- ...section,
710
- fields: section.fields.map((field) => tagField(field, capName, addonId, source, kind))
711
- }))
712
- };
713
- }
714
- function isFieldRecord(value) {
715
- return value !== null && typeof value === "object" && !Array.isArray(value);
716
- }
717
- /**
718
- * Convert a strict `ConfigUISchemaWithValues` (readonly arrays, typed
719
- * field union) into the cap wire shape `ContributionShape` (mutable
720
- * arrays, opaque field records). Required because the cap method z.infer
721
- * uses mutable arrays — readonly arrays are not assignable to mutable
722
- * even when structurally identical, so a structural copy bridges the gap
723
- * without disabling the type checker.
724
- */
725
- function toWireShape(input) {
726
- const out = { sections: input.sections.map((s) => ({
727
- id: s.id,
728
- title: s.title,
729
- ...s.description !== void 0 ? { description: s.description } : {},
730
- ...s.style !== void 0 ? { style: s.style } : {},
731
- ...s.defaultCollapsed !== void 0 ? { defaultCollapsed: s.defaultCollapsed } : {},
732
- ...s.columns !== void 0 ? { columns: s.columns } : {},
733
- ...s.tab !== void 0 ? { tab: s.tab } : {},
734
- ...s.location !== void 0 ? { location: s.location } : {},
735
- ...s.order !== void 0 ? { order: s.order } : {},
736
- fields: [...s.fields]
737
- })) };
738
- if (input.tabs) out.tabs = [...input.tabs];
739
- return out;
740
- }
741
- function tagField(field, capName, addonId, source, kind) {
742
- if (!isFieldRecord(field)) return field;
743
- const f = field;
744
- const structuralTypes = new Set([
745
- "separator",
746
- "info",
747
- "button"
748
- ]);
749
- if (typeof f.type === "string" && structuralTypes.has(f.type)) return field;
750
- const tagged = {
751
- ...f,
752
- source
753
- };
754
- if (kind === "live" || f.readonlyField === true) tagged.readonlyField = true;
755
- else {
756
- tagged.writerCapName = capName;
757
- tagged.writerAddonId = addonId;
758
- }
759
- if (f.type === "group") {
760
- const children = Array.isArray(f.fields) ? f.fields : [];
761
- if (children.length > 0) tagged.fields = children.map((child) => tagField(child, capName, addonId, source, kind));
762
- } else if (f.type === "sub-tabs") {
763
- const rawTabs = Array.isArray(f.tabs) ? f.tabs : [];
764
- if (rawTabs.length > 0) tagged.tabs = rawTabs.map((tab) => {
765
- if (!isFieldRecord(tab)) return tab;
766
- const tabChildren = Array.isArray(tab.fields) ? tab.fields : [];
767
- return {
768
- ...tab,
769
- fields: tabChildren.map((child) => tagField(child, capName, addonId, source, kind))
770
- };
771
- });
772
- }
773
- return tagged;
774
- }
775
- function mergeAggregates(parts) {
776
- const tabDecls = /* @__PURE__ */ new Map();
777
- const sections = [];
778
- const seenSectionIds = /* @__PURE__ */ new Set();
779
- for (const part of parts) {
780
- if (part.tabs) {
781
- for (const t of part.tabs) if (!tabDecls.has(t.id)) tabDecls.set(t.id, t);
782
- }
783
- for (const s of part.sections) {
784
- if (s.id !== void 0) {
785
- if (seenSectionIds.has(s.id)) continue;
786
- seenSectionIds.add(s.id);
787
- }
788
- sections.push(s);
789
- }
790
- }
791
- for (const s of sections) {
792
- const tabId = s.tab ?? "general";
793
- if (tabDecls.has(tabId)) continue;
794
- const known = require_dist.WELL_KNOWN_TAB_MAP[tabId];
795
- if (known) tabDecls.set(tabId, {
796
- id: known.id,
797
- label: known.label,
798
- icon: known.icon,
799
- order: known.order
800
- });
801
- else tabDecls.set(tabId, {
802
- id: tabId,
803
- label: tabId,
804
- icon: "wrench",
805
- order: 100
806
- });
807
- }
808
- sections.sort((a, b) => {
809
- const tabA = a.tab ?? "general";
810
- const tabB = b.tab ?? "general";
811
- if (tabA !== tabB) {
812
- const orderA = tabDecls.get(tabA)?.order ?? 100;
813
- const orderB = tabDecls.get(tabB)?.order ?? 100;
814
- if (orderA !== orderB) return orderA - orderB;
815
- return tabA.localeCompare(tabB);
816
- }
817
- return (a.order ?? 0) - (b.order ?? 0);
818
- });
819
- const sortedTabs = [...tabDecls.values()].toSorted((a, b) => (a.order ?? 100) - (b.order ?? 100));
820
- const out = { sections };
821
- if (sortedTabs.length > 0) out.tabs = sortedTabs;
822
- return out;
823
- }
824
- //#endregion
825
1123
  //#region src/builtins/device-manager/device-projection.ts
826
1124
  /**
827
1125
  * Return true when `err` is a transient Moleculer error that is worth
@@ -953,22 +1251,15 @@ function resolveDeviceById(registry, deviceId) {
953
1251
  //#region src/builtins/device-manager/device-queries.ts
954
1252
  async function listPersistedByAddon(pctx, input) {
955
1253
  const { addonId } = input;
956
- const { index, meta } = await pctx.metaStore.readAll();
957
- const stableIds = index[addonId] ?? [];
958
- const byStableId = /* @__PURE__ */ new Map();
959
- for (const m of Object.values(meta)) if (m.addonId === addonId) byStableId.set(m.stableId, m);
960
- return stableIds.map((stableId) => {
961
- const m = byStableId.get(stableId);
962
- return {
963
- id: m.id,
964
- stableId,
965
- type: m.type,
966
- name: m.name,
967
- location: m.location ?? null,
968
- disabled: m.disabled ?? false,
969
- parentDeviceId: m.parentDeviceId
970
- };
971
- });
1254
+ return (await pctx.metaStore.rows.listByAddon(addonId)).map(({ meta: m }) => ({
1255
+ id: m.id,
1256
+ stableId: m.stableId,
1257
+ type: m.type,
1258
+ name: m.name,
1259
+ location: m.location ?? null,
1260
+ disabled: m.disabled ?? false,
1261
+ parentDeviceId: m.parentDeviceId
1262
+ }));
972
1263
  }
973
1264
  async function listAll(pctx, input) {
974
1265
  const ownerFilter = Reflect.get(input, "addonId");
@@ -978,7 +1269,9 @@ async function listAll(pctx, input) {
978
1269
  const camerasOnly = input.isCamera === true;
979
1270
  const results = [];
980
1271
  const seen = /* @__PURE__ */ new Set();
981
- const { meta, metadata: metadataMap, index } = await pctx.metaStore.readAll();
1272
+ const fleet = addonId ? await pctx.metaStore.rows.listByAddon(addonId) : await pctx.metaStore.rows.listAll();
1273
+ const rowById = /* @__PURE__ */ new Map();
1274
+ for (const row of fleet) rowById.set(row.meta.id, row);
982
1275
  if (pctx.registry) {
983
1276
  const liveEntries = addonId ? pctx.registry.getAllForAddon(addonId).map((device) => ({
984
1277
  addonId,
@@ -986,7 +1279,8 @@ async function listAll(pctx, input) {
986
1279
  })) : pctx.registry.getAllWithAddonId();
987
1280
  for (const { addonId: aid, device } of liveEntries) {
988
1281
  const key = String(device.id);
989
- const info = toDeviceInfo(aid, device, metadataMap[key] ?? null, meta[key] ?? null);
1282
+ const row = rowById.get(device.id);
1283
+ const info = toDeviceInfo(aid, device, row?.metadata ?? null, row?.meta ?? null);
990
1284
  seen.add(key);
991
1285
  if (camerasOnly && !info.isCamera) continue;
992
1286
  results.push(slim ? {
@@ -996,38 +1290,36 @@ async function listAll(pctx, input) {
996
1290
  } : info);
997
1291
  }
998
1292
  }
999
- const metaByAddonStable = /* @__PURE__ */ new Map();
1000
- for (const m of Object.values(meta)) metaByAddonStable.set(`${m.addonId}${m.stableId}`, m);
1001
- const targetAddons = addonId ? [addonId] : Object.keys(index);
1002
- for (const aid of targetAddons) for (const stableId of index[aid] ?? []) {
1003
- const m = metaByAddonStable.get(`${aid}${stableId}`);
1004
- const key = String(m.id);
1005
- if (seen.has(key)) continue;
1293
+ for (const row of fleet) {
1294
+ const m = row.meta;
1295
+ const aid = m.addonId;
1296
+ const stableId = m.stableId;
1297
+ if (seen.has(String(m.id))) continue;
1006
1298
  const persistedType = m.type;
1007
1299
  if (camerasOnly && persistedType !== require_dist.DeviceType.Camera) continue;
1008
1300
  const persistedConfig = slim ? {} : await pctx.settings.readDeviceStore(m.id);
1009
- const metadata = slim ? null : metadataMap[key] ?? null;
1301
+ const metadata = slim ? null : row.metadata;
1010
1302
  results.push({
1011
1303
  id: m.id,
1012
1304
  stableId,
1013
1305
  addonId: aid,
1014
1306
  type: persistedType,
1015
- name: m?.name ?? stableId,
1016
- location: m?.location ?? null,
1017
- disabled: m?.disabled ?? false,
1018
- parentDeviceId: m?.parentDeviceId ?? null,
1019
- role: toDeviceRole(m?.role),
1307
+ name: m.name,
1308
+ location: m.location ?? null,
1309
+ disabled: m.disabled ?? false,
1310
+ parentDeviceId: m.parentDeviceId ?? null,
1311
+ role: toDeviceRole(m.role),
1020
1312
  online: pctx.host.resolveDeviceOnline(m.id, pctx.registry !== null),
1021
1313
  probed: pctx.host.resolveDeviceProbed(m.id),
1022
- features: persistedFeatures(m?.features),
1314
+ features: persistedFeatures(m.features),
1023
1315
  isCamera: persistedType === require_dist.DeviceType.Camera,
1024
1316
  config: persistedConfig ?? {},
1025
1317
  metadata,
1026
- ...m?.integrationId !== void 0 ? { integrationId: m.integrationId } : {},
1027
- ...m?.linkDeviceId !== void 0 ? { linkDeviceId: m.linkDeviceId } : {},
1028
- ...m?.primaryChildEntityId !== void 0 ? { primaryChildEntityId: m.primaryChildEntityId } : {},
1029
- ...m?.childLayout !== void 0 ? { childLayout: m.childLayout } : {},
1030
- ...m?.display !== void 0 ? { display: m.display } : {},
1318
+ ...m.integrationId !== void 0 ? { integrationId: m.integrationId } : {},
1319
+ ...m.linkDeviceId !== void 0 ? { linkDeviceId: m.linkDeviceId } : {},
1320
+ ...m.primaryChildEntityId !== void 0 ? { primaryChildEntityId: m.primaryChildEntityId } : {},
1321
+ ...m.childLayout !== void 0 ? { childLayout: m.childLayout } : {},
1322
+ ...m.display !== void 0 ? { display: m.display } : {},
1031
1323
  ...(() => {
1032
1324
  if (slim) return {};
1033
1325
  const si = buildSourceInfoFromConfig(persistedConfig ?? {}, stableId, aid);
@@ -1042,19 +1334,15 @@ async function getDevice(pctx, input) {
1042
1334
  if (pctx.registry) {
1043
1335
  const found = resolveDeviceById(pctx.registry, deviceId);
1044
1336
  if (found) {
1045
- const key = String(found.device.id);
1046
- const [map, metaMap] = await Promise.all([pctx.metaStore.readMetadataMap(), pctx.metaStore.readMeta()]);
1047
- const metadata = map[key] ?? null;
1048
- const metaRow = metaMap[key] ?? null;
1049
- return toDeviceInfo(found.addonId, found.device, metadata, metaRow);
1337
+ const row = await pctx.metaStore.getRow(found.device.id);
1338
+ return toDeviceInfo(found.addonId, found.device, row?.metadata ?? null, row?.meta ?? null);
1050
1339
  }
1051
1340
  }
1052
- const persisted = await pctx.metaStore.resolvePersistedById(deviceId);
1053
- if (!persisted) return null;
1054
- const { addonId: aid, stableId, meta: m } = persisted;
1341
+ const row = await pctx.metaStore.getRow(deviceId);
1342
+ if (row === null) return null;
1343
+ const { meta: m, metadata } = row;
1344
+ const { addonId: aid, stableId } = m;
1055
1345
  const persistedConfig = await pctx.settings.readDeviceStore(m.id);
1056
- const key = String(deviceId);
1057
- const metadata = (await pctx.metaStore.readMetadataMap())[key] ?? null;
1058
1346
  const sourceInfoGetDevice = buildSourceInfoFromConfig(persistedConfig ?? {}, stableId, aid);
1059
1347
  return {
1060
1348
  id: deviceId,
@@ -1093,26 +1381,25 @@ async function getChildren(pctx, input) {
1093
1381
  }
1094
1382
  const results = [];
1095
1383
  const seen = /* @__PURE__ */ new Set();
1096
- const { index, meta, metadata: metadataMap } = await pctx.metaStore.readAll();
1384
+ const childRows = await pctx.metaStore.rows.listByParent(parentDeviceId);
1385
+ const rowById = /* @__PURE__ */ new Map();
1386
+ for (const row of childRows) rowById.set(row.meta.id, row);
1097
1387
  if (pctx.registry) {
1098
1388
  const liveChildren = pctx.registry.getChildren(parentDeviceId);
1099
1389
  for (const device of liveChildren) {
1100
1390
  const key = String(device.id);
1101
- const metadata = metadataMap[key] ?? null;
1102
- const metaRow = meta[key] ?? null;
1103
- results.push(toDeviceInfo(ownerAddonId, device, metadata, metaRow));
1391
+ const row = rowById.get(device.id);
1392
+ results.push(toDeviceInfo(ownerAddonId, device, row?.metadata ?? null, row?.meta ?? null));
1104
1393
  seen.add(key);
1105
1394
  }
1106
1395
  }
1107
- const ownerMetaByStableId = /* @__PURE__ */ new Map();
1108
- for (const m of Object.values(meta)) if (m.addonId === ownerAddonId) ownerMetaByStableId.set(m.stableId, m);
1109
- const persistedChildren = (index[ownerAddonId] ?? []).filter((sid) => ownerMetaByStableId.get(sid)?.parentDeviceId === parentDeviceId);
1110
- for (const childStableId of persistedChildren) {
1111
- const m = ownerMetaByStableId.get(childStableId);
1396
+ for (const row of childRows) {
1397
+ const m = row.meta;
1398
+ const childStableId = m.stableId;
1112
1399
  const key = String(m.id);
1113
1400
  if (seen.has(key)) continue;
1114
1401
  const persistedConfig = await pctx.settings.readDeviceStore(m.id);
1115
- const metadata = metadataMap[key] ?? null;
1402
+ const metadata = row.metadata;
1116
1403
  const sourceInfoChild = buildSourceInfoFromConfig(persistedConfig ?? {}, childStableId, ownerAddonId);
1117
1404
  results.push({
1118
1405
  id: m.id,
@@ -1264,16 +1551,10 @@ async function remove(pctx, input) {
1264
1551
  */
1265
1552
  async function removeByIntegration(pctx, input) {
1266
1553
  const { integrationId } = input;
1267
- const meta = await pctx.metaStore.readMeta();
1268
- const parentKeys = Object.keys(meta).filter((key) => {
1269
- const m = meta[key];
1270
- return m !== void 0 && m.integrationId === integrationId && m.parentDeviceId === null;
1271
- });
1554
+ const parents = (await pctx.metaStore.rows.listByIntegration(integrationId)).filter((row) => row.meta.parentDeviceId === null);
1272
1555
  let removed = 0;
1273
- for (const _key of parentKeys) {
1274
- const m = meta[_key];
1275
- if (!m) continue;
1276
- await pctx.provider.remove({ deviceId: m.id });
1556
+ for (const parent of parents) {
1557
+ await pctx.provider.remove({ deviceId: parent.meta.id });
1277
1558
  removed++;
1278
1559
  }
1279
1560
  return { removed };
@@ -1697,316 +1978,16 @@ function splitDeviceStoreKeys(patch) {
1697
1978
  }
1698
1979
  if (Object.keys(slice).length > 0) storeGroups.push({
1699
1980
  section,
1700
- patch: slice
1701
- });
1702
- }
1703
- const driverPatch = {};
1704
- for (const [key, value] of Object.entries(patch)) if (!claimed.has(key)) driverPatch[key] = value;
1705
- return {
1706
- storeGroups,
1707
- driverPatch
1708
- };
1709
- }
1710
- //#endregion
1711
- //#region src/builtins/device-manager/device-bindings-store.ts
1712
- /**
1713
- * Wire the push-fed cross-process native-cap cache (`remoteNativeCaps`).
1714
- * Workers emit `DeviceBindingsChanged` on `ctx.registerNativeCap` / device
1715
- * removal; we mirror those into `remoteNativeCaps` so `getBindings` returns the
1716
- * full cluster view. Events from the local node are ignored: hub-local natives
1717
- * live in `capabilityRegistry` and are folded in directly by getBindings.
1718
- *
1719
- * Push events are accurate in the steady state but can be lost during the
1720
- * Moleculer transport handshake window (hub restart, crash-respawn,
1721
- * restartAddon). The reliable replacement for lost events is the D3 re-handshake
1722
- * (`listClusterNativeCaps()`), which `resolveNativeCapOwnerSync` /
1723
- * `getBindings` step 4 fall through to on a push miss. The `$node.disconnected`
1724
- * handler purges a gone node's entries; the worker re-handshakes (and re-emits
1725
- * `native-registered`) on its next boot.
1726
- */
1727
- function wireRemoteNativeCapSync(ctx, remoteNativeCaps) {
1728
- const localNodeId = ctx.kernel.localNodeId ?? "hub";
1729
- ctx.eventBus.subscribe({ category: require_dist.EventCategory.DeviceBindingsChanged }, (event) => {
1730
- const { deviceId, capName, reason, addonId, nodeId } = event.data;
1731
- if (nodeId === localNodeId) return;
1732
- if (reason === "native-registered") {
1733
- let perDevice = remoteNativeCaps.get(deviceId);
1734
- if (!perDevice) {
1735
- perDevice = /* @__PURE__ */ new Map();
1736
- remoteNativeCaps.set(deviceId, perDevice);
1737
- }
1738
- perDevice.set(capName, {
1739
- addonId,
1740
- nodeId
1741
- });
1742
- } else if (reason === "native-unregistered") {
1743
- const perDevice = remoteNativeCaps.get(deviceId);
1744
- if (!perDevice) return;
1745
- perDevice.delete(capName);
1746
- if (perDevice.size === 0) remoteNativeCaps.delete(deviceId);
1747
- }
1748
- });
1749
- const cluster = ctx.kernel.cluster;
1750
- if (cluster) cluster.broker.localBus.on("$node.disconnected", (payload) => {
1751
- const gone = payload.node.id;
1752
- const emptyDevices = [];
1753
- for (const [deviceId, perDevice] of remoteNativeCaps) {
1754
- const toDelete = [];
1755
- for (const [capName, entry] of perDevice) if (entry.nodeId === gone) toDelete.push(capName);
1756
- for (const capName of toDelete) perDevice.delete(capName);
1757
- if (perDevice.size === 0) emptyDevices.push(deviceId);
1758
- }
1759
- for (const deviceId of emptyDevices) remoteNativeCaps.delete(deviceId);
1760
- });
1761
- }
1762
- async function readBindingsStore(deps) {
1763
- return { deviceBindings: (await deps.ctx.settings.readAddonStore()).deviceBindings ?? {} };
1764
- }
1765
- async function writeBindingsStore(deps, next) {
1766
- await deps.ctx.settings.writeAddonStore({ deviceBindings: next.deviceBindings });
1767
- }
1768
- function resolveWrapperNodeId(_wrapperAddonId) {
1769
- return "hub";
1770
- }
1771
- /**
1772
- * Reduce a provider node id to the routable form `DeviceProxy` can pin.
1773
- *
1774
- * Every addon runs in its own `addon-runner` with the composite node id
1775
- * `${parentNodeId}/${runnerId}` (see `addon-runner.ts`) — e.g.
1776
- * `hub/provider-reolink` or `dev-agent-0/provider-reolink`. That composite is
1777
- * an IDENTITY, not a routable target: the `CapRouteResolver` reaches a child
1778
- * only THROUGH its parent (the hub resolves a hub-local-uds child by
1779
- * cap+device; an agent forwards to its own child). `DeviceProxy` pins
1780
- * `entry.providerNodeId` on every cap call, so a binding entry must expose the
1781
- * parent node id — otherwise the explicit pin classifies as `remote-moleculer`
1782
- * to an unknown node → `no-provider`, which surfaces as
1783
- * "this camera doesn't expose …" for client-proxy-driven widget caps
1784
- * (motion-zones, privacy-mask). Wrappers already report the parent via
1785
- * `resolveWrapperNodeId`; this aligns natives with the same contract.
1786
- *
1787
- * A flat node id (a genuine standalone node with no `/`) is returned
1788
- * unchanged.
1789
- */
1790
- function toRoutableProviderNodeId(nodeId) {
1791
- const slash = nodeId.indexOf("/");
1792
- return slash === -1 ? nodeId : nodeId.slice(0, slash);
1793
- }
1794
- /**
1795
- * Resolve a remote native cap entry for a given `(capName, deviceId)` by
1796
- * consulting the handshake-fed `HubNodeRegistry` via
1797
- * `ctx.kernel.listClusterNativeCaps()`. Called when the push-based
1798
- * `remoteNativeCaps` cache misses — covers the Moleculer transport
1799
- * handshake window where `DeviceBindingsChanged` events were lost but the
1800
- * D3 re-handshake (post device restore) has already populated the registry.
1801
- *
1802
- * Returns `null` when the entry is genuinely not present in the cluster
1803
- * view (cap not registered on any worker for that device).
1804
- */
1805
- function resolveRemoteNativeCapFromRegistry(deps, capName, deviceId) {
1806
- const clusterCaps = deps.ctx.kernel.listClusterNativeCapsForDevice?.(deviceId) ?? deps.ctx.kernel.listClusterNativeCaps?.();
1807
- if (!clusterCaps) return null;
1808
- for (const entry of clusterCaps) if (entry.capName === capName && entry.deviceId === deviceId && entry.addonId) return {
1809
- addonId: entry.addonId,
1810
- nodeId: entry.nodeId
1811
- };
1812
- return null;
1813
- }
1814
- /**
1815
- * Resolve the device's declared TYPE (`'camera'`, `'event-emitter'`, …), or
1816
- * `undefined` when it cannot be established.
1817
- *
1818
- * The PERSISTED meta is the authority: `ctx.kernel.deviceRegistry` is hub-only
1819
- * and has been observed empty in the very process that answers `getBindings`
1820
- * correctly (see the note on `getAllBindings`). The registry is consulted only
1821
- * as a secondary source, for a device constructed but not yet persisted.
1822
- *
1823
- * `undefined` is a first-class answer and callers must treat it as "no
1824
- * filtering" — an absent row must never be the reason a device loses bindings.
1825
- */
1826
- function resolveDeviceType(deps, rawStore, deviceId) {
1827
- const persisted = rawStore.deviceMeta?.[String(deviceId)]?.type;
1828
- if (typeof persisted === "string" && persisted.length > 0) return persisted;
1829
- const live = deps.ctx.kernel?.deviceRegistry?.getById(deviceId)?.type;
1830
- return typeof live === "string" && live.length > 0 ? live : void 0;
1831
- }
1832
- /**
1833
- * Is this device still part of the fleet?
1834
- *
1835
- * The device-manager's own stores are the authority in-process — no RPC. Two
1836
- * sources, in the same order `resolveDeviceType` uses them: the live registry
1837
- * first (a device constructed but not yet persisted is present), then the
1838
- * PERSISTED meta, which is the index `getBindings` already reads and is present
1839
- * wherever this provider runs.
1840
- *
1841
- * `'absent'` is only ever returned against a NON-EMPTY meta store. An empty one
1842
- * means device restore has not run, not that the fleet was deleted (D49) — the
1843
- * same reason `getAllBindings` warns instead of reporting zero devices.
1844
- */
1845
- function resolveDevicePresence(deps, rawStore, deviceId) {
1846
- if (deps.ctx.kernel?.deviceRegistry?.getById(deviceId)) return "present";
1847
- const meta = rawStore.deviceMeta;
1848
- if (meta && Object.keys(meta).length > 0) return meta[String(deviceId)] === void 0 ? "absent" : "present";
1849
- return "unknown";
1850
- }
1851
- /**
1852
- * Does a capability apply to a device of type `deviceType`?
1853
- *
1854
- * The cap's `deviceTypes` is the ONLY declaration consulted (D4: behavioural
1855
- * cap metadata lives in the `*.cap.ts`, never in a manifest). Two deliberate
1856
- * fail-open cases:
1857
- *
1858
- * - a cap that declares no `deviceTypes` (or an empty list) applies to every
1859
- * device — the pre-existing, back-compatible semantics;
1860
- * - an UNKNOWN `deviceType` never filters, so a missing/failed meta lookup
1861
- * changes nothing (D49: a read that fails must not destroy work).
1862
- */
1863
- function capAppliesToDeviceType(def, deviceType) {
1864
- if (deviceType === void 0) return true;
1865
- const declared = def?.deviceTypes;
1866
- if (!declared || declared.length === 0) return true;
1867
- return declared.some((t) => t === deviceType);
1868
- }
1869
- async function getBindings(deps, input) {
1870
- const storeKey = String(input.deviceId);
1871
- const rawStore = await deps.ctx.settings.readAddonStore();
1872
- const perDevice = (rawStore.deviceBindings ?? {})[storeKey] ?? {};
1873
- const deviceType = resolveDeviceType(deps, rawStore, input.deviceId);
1874
- const presence = resolveDevicePresence(deps, rawStore, input.deviceId);
1875
- const entries = [];
1876
- const seenCaps = /* @__PURE__ */ new Set();
1877
- const resolveRemote = (capName) => deps.remoteNativeCaps.get(input.deviceId)?.get(capName) ?? resolveRemoteNativeCapFromRegistry(deps, capName, input.deviceId);
1878
- for (const [capName, { wrapperAddonId }] of Object.entries(perDevice)) {
1879
- const hubLocalNative = deps.capabilityRegistry?.getNativeAddonId(capName, input.deviceId) ?? null;
1880
- const remoteNative = resolveRemote(capName);
1881
- const nativeAddonId = hubLocalNative ?? remoteNative?.addonId ?? "";
1882
- const nativeNodeId = hubLocalNative ? deps.ctx.kernel.localNodeId ?? "hub" : remoteNative?.nodeId ?? deps.ctx.kernel.localNodeId ?? "hub";
1883
- if (wrapperAddonId === null && !nativeAddonId) {
1884
- seenCaps.add(capName);
1885
- continue;
1886
- }
1887
- entries.push({
1888
- capName,
1889
- kind: wrapperAddonId ? "wrapped" : "native",
1890
- providerAddonId: wrapperAddonId ?? nativeAddonId,
1891
- providerNodeId: wrapperAddonId ? resolveWrapperNodeId(wrapperAddonId) : toRoutableProviderNodeId(nativeNodeId),
1892
- nativeAddonId
1893
- });
1894
- seenCaps.add(capName);
1895
- }
1896
- if (presence === "absent") deps.ctx.logger.debug("bindings requested for absent device — returning none", { tags: { deviceId: input.deviceId } });
1897
- else if (deps.capabilityRegistry) {
1898
- const skippedForType = [];
1899
- for (const capName of deps.capabilityRegistry.getCapsWithDefaultWrapper()) {
1900
- if (seenCaps.has(capName)) continue;
1901
- if (!capAppliesToDeviceType(deps.capabilityRegistry.getDefinition(capName), deviceType)) {
1902
- skippedForType.push(capName);
1903
- continue;
1904
- }
1905
- const defaultWrapperAddonId = deps.capabilityRegistry.getDefaultWrapperForCap(capName);
1906
- if (!defaultWrapperAddonId) continue;
1907
- const hubLocalNative = deps.capabilityRegistry.getNativeAddonId(capName, input.deviceId) ?? null;
1908
- const remoteNative = resolveRemote(capName);
1909
- const nativeAddonId = hubLocalNative ?? remoteNative?.addonId ?? "";
1910
- entries.push({
1911
- capName,
1912
- kind: "wrapped",
1913
- providerAddonId: defaultWrapperAddonId,
1914
- providerNodeId: resolveWrapperNodeId(defaultWrapperAddonId),
1915
- nativeAddonId
1916
- });
1917
- seenCaps.add(capName);
1918
- }
1919
- if (skippedForType.length > 0) deps.ctx.logger.debug("getBindings: default wrappers skipped — deviceTypes mismatch", {
1920
- tags: { deviceId: input.deviceId },
1921
- meta: {
1922
- deviceType,
1923
- skipped: skippedForType
1924
- }
1925
- });
1926
- }
1927
- if (deps.capabilityRegistry) for (const capName of deps.capabilityRegistry.getNativeCapsForDevice(input.deviceId)) {
1928
- if (seenCaps.has(capName)) continue;
1929
- const nativeAddonId = deps.capabilityRegistry.getNativeAddonId(capName, input.deviceId) ?? "";
1930
- entries.push({
1931
- capName,
1932
- kind: "native",
1933
- providerAddonId: nativeAddonId,
1934
- providerNodeId: deps.ctx.kernel.localNodeId ?? "hub",
1935
- nativeAddonId
1936
- });
1937
- seenCaps.add(capName);
1938
- }
1939
- const pushFed = deps.remoteNativeCaps.get(input.deviceId);
1940
- if (pushFed) for (const [capName, info] of pushFed) {
1941
- if (seenCaps.has(capName)) continue;
1942
- entries.push({
1943
- capName,
1944
- kind: "native",
1945
- providerAddonId: info.addonId,
1946
- providerNodeId: toRoutableProviderNodeId(info.nodeId),
1947
- nativeAddonId: info.addonId
1948
- });
1949
- seenCaps.add(capName);
1950
- }
1951
- const clusterCaps = deps.ctx.kernel.listClusterNativeCapsForDevice?.(input.deviceId) ?? deps.ctx.kernel.listClusterNativeCaps?.();
1952
- if (clusterCaps) for (const entry of clusterCaps) {
1953
- if (entry.deviceId !== input.deviceId) continue;
1954
- if (seenCaps.has(entry.capName)) continue;
1955
- if (!entry.addonId) continue;
1956
- const localNodeId = deps.ctx.kernel.localNodeId ?? "hub";
1957
- if (entry.nodeId === localNodeId) continue;
1958
- entries.push({
1959
- capName: entry.capName,
1960
- kind: "native",
1961
- providerAddonId: entry.addonId,
1962
- providerNodeId: toRoutableProviderNodeId(entry.nodeId),
1963
- nativeAddonId: entry.addonId
1981
+ patch: slice
1964
1982
  });
1965
- seenCaps.add(entry.capName);
1966
1983
  }
1984
+ const driverPatch = {};
1985
+ for (const [key, value] of Object.entries(patch)) if (!claimed.has(key)) driverPatch[key] = value;
1967
1986
  return {
1968
- deviceId: input.deviceId,
1969
- entries
1987
+ storeGroups,
1988
+ driverPatch
1970
1989
  };
1971
1990
  }
1972
- /**
1973
- * Whole-fleet binding dump. Iterates every device known to the
1974
- * deviceRegistry and reuses the per-device `getBindings` resolver
1975
- * for each — same routing rules, single round-trip. Used by
1976
- * `SystemManager.init()` for warm-boot.
1977
- *
1978
- * Bindings change rarely (wrapper toggle, device add/remove) so
1979
- * clients invalidate via the existing
1980
- * `capability.binding-changed` event rather than re-fetching this
1981
- * payload periodically.
1982
- */
1983
- async function getAllBindings(deps) {
1984
- const store = await deps.ctx.settings.readAddonStore();
1985
- const ids = /* @__PURE__ */ new Set();
1986
- for (const key of Object.keys(store.deviceMeta ?? {})) {
1987
- const id = Number(key);
1988
- if (Number.isInteger(id)) ids.add(id);
1989
- }
1990
- const registered = deps.ctx.kernel?.deviceRegistry?.getAll() ?? [];
1991
- for (const device of registered) ids.add(device.id);
1992
- if (ids.size === 0) {
1993
- deps.ctx.logger.warn("getAllBindings found no devices — warm boot will see nothing", { meta: { hasRegistry: deps.ctx.kernel?.deviceRegistry !== void 0 } });
1994
- return [];
1995
- }
1996
- const out = [];
1997
- for (const deviceId of [...ids].sort((a, b) => a - b)) out.push(await getBindings(deps, { deviceId }));
1998
- return out;
1999
- }
2000
- /**
2001
- * Resolve a numeric deviceId to a stableId via persisted meta.
2002
- * Used only by the device-identity section of the device-details
2003
- * aggregator (see `buildBaseDeviceSection`) to surface the stableId as
2004
- * a readonly display field. All runtime/registry lookups are keyed by
2005
- * numeric deviceId; this helper is display-only.
2006
- */
2007
- async function lookupPersistedStableId(deps, deviceId) {
2008
- return ((await deps.ctx.settings.readAddonStore()).deviceMeta ?? {})[String(deviceId)]?.stableId;
2009
- }
2010
1991
  //#endregion
2011
1992
  //#region src/builtins/device-manager/device-aggregation.ts
2012
1993
  /**
@@ -2795,7 +2776,7 @@ async function getWireableFields(deps, input) {
2795
2776
  if (wireable) caps.push(wireable);
2796
2777
  }
2797
2778
  if (input.includeSynthesizable === true) {
2798
- const deviceType = ((await deps.ctx.settings.readAddonStore()).deviceMeta ?? {})[String(deviceId)]?.type;
2779
+ const deviceType = (await deps.bindingsDeps.rows.get(deviceId))?.meta.type;
2799
2780
  if (deviceType !== void 0) for (const def of require_dist.ALL_CAPABILITY_DEFINITIONS) {
2800
2781
  if (seen.has(def.name)) continue;
2801
2782
  if (def.scope !== "device" || def.kind === "wrapper") continue;
@@ -2949,20 +2930,10 @@ var DeviceEventPropagator = class {
2949
2930
  * because `ProviderContext.stampIntegrationId` delegates HERE — passing the
2950
2931
  * context would be a capture cycle.
2951
2932
  */
2952
- async function stampIntegrationId(metaStore, settings, ctx, deviceId, integrationId) {
2933
+ async function stampIntegrationId(metaStore, ctx, deviceId, integrationId) {
2953
2934
  await metaStore.withMetaWriteLock(async () => {
2954
- const persisted = await metaStore.resolvePersistedById(deviceId);
2955
- if (!persisted) throw new Error(`[device-manager] stampIntegrationId: unknown device id=${deviceId}`);
2956
- const { meta: m } = persisted;
2957
- const key = String(deviceId);
2958
- const allMeta = await metaStore.readMeta();
2959
- await settings.writeAddonStore({ deviceMeta: {
2960
- ...allMeta,
2961
- [key]: {
2962
- ...m,
2963
- integrationId
2964
- }
2965
- } });
2935
+ if (!await metaStore.resolvePersistedById(deviceId)) throw new Error(`[device-manager] stampIntegrationId: unknown device id=${deviceId}`);
2936
+ await metaStore.rows.patch(deviceId, { integrationId });
2966
2937
  });
2967
2938
  ctx.eventBus.emit({
2968
2939
  id: (0, node_crypto.randomUUID)(),
@@ -2982,70 +2953,54 @@ async function stampIntegrationId(metaStore, settings, ctx, deviceId, integratio
2982
2953
  async function allocateDeviceId(pctx, input) {
2983
2954
  const { addonId, stableId } = input;
2984
2955
  return await pctx.metaStore.withMetaWriteLock(async () => {
2985
- const meta = await pctx.metaStore.readMeta();
2986
- const existing = Object.values(meta).find((m) => m.addonId === addonId && m.stableId === stableId);
2987
- if (existing) return { id: existing.id };
2956
+ const existing = await pctx.metaStore.rows.findByStableId(addonId, stableId);
2957
+ if (existing) return { id: existing.meta.id };
2988
2958
  const id = await pctx.metaStore.allocateNextDeviceId();
2989
- await pctx.settings.writeAddonStore({ deviceMeta: {
2990
- ...meta,
2991
- [String(id)]: {
2992
- addonId,
2993
- stableId,
2994
- type: "generic",
2995
- name: stableId,
2996
- location: null,
2997
- disabled: false,
2998
- parentDeviceId: null,
2999
- id
3000
- }
3001
- } });
2959
+ await pctx.metaStore.rows.upsert({
2960
+ addonId,
2961
+ stableId,
2962
+ type: "generic",
2963
+ name: stableId,
2964
+ location: null,
2965
+ disabled: false,
2966
+ parentDeviceId: null,
2967
+ id
2968
+ }, {
2969
+ registered: false,
2970
+ metadata: null
2971
+ });
3002
2972
  return { id };
3003
2973
  });
3004
2974
  }
3005
2975
  async function registerDevice(pctx, input) {
3006
2976
  const { addonId, stableId, id, type, name, parentDeviceId, features, config } = input;
3007
- const key = String(id);
3008
2977
  const featuresArr = Array.isArray(features) ? [...features] : [];
3009
2978
  const { isFirstRegistration, exportFingerprint, fingerprintChanged } = await pctx.metaStore.withMetaWriteLock(async () => {
3010
- const index = await pctx.metaStore.readIndex();
3011
- const existing = index[addonId] ?? [];
3012
- const wasInIndex = existing.includes(stableId);
3013
- if (!wasInIndex) await pctx.settings.writeAddonStore({ deviceIndex: {
3014
- ...index,
3015
- [addonId]: [...existing, stableId]
3016
- } });
3017
- const meta = await pctx.metaStore.readMeta();
3018
- const existingMeta = meta[key];
2979
+ const existingRow = await pctx.metaStore.rows.get(id);
2980
+ const existingMeta = existingRow?.meta;
2981
+ const wasRegistered = existingRow?.registered ?? false;
3019
2982
  const wasUserNamed = existingMeta?.userNamed ?? (existingMeta !== void 0 && existingMeta.name !== stableId);
3020
2983
  const resolvedName = wasUserNamed && existingMeta !== void 0 ? existingMeta.name : name;
3021
- const isFirst = !existingMeta || !wasInIndex;
2984
+ const isFirst = !existingMeta || !wasRegistered;
3022
2985
  const fingerprint = (0, _camstack_types_node.canonicalDeviceFingerprint)({
3023
2986
  deviceId: id,
3024
2987
  deviceType: type,
3025
2988
  features: featuresArr
3026
2989
  });
3027
- await pctx.settings.writeAddonStore({ deviceMeta: {
3028
- ...meta,
3029
- [key]: {
3030
- addonId,
3031
- stableId,
3032
- type,
3033
- name: resolvedName,
3034
- userNamed: wasUserNamed,
3035
- location: existingMeta?.location ?? null,
3036
- disabled: existingMeta?.disabled ?? false,
3037
- ...existingMeta?.integrationId !== void 0 ? { integrationId: existingMeta.integrationId } : {},
3038
- ...existingMeta?.linkDeviceId !== void 0 ? { linkDeviceId: existingMeta.linkDeviceId } : {},
3039
- ...existingMeta?.primaryChildEntityId !== void 0 ? { primaryChildEntityId: existingMeta.primaryChildEntityId } : {},
3040
- ...existingMeta?.childLayout !== void 0 ? { childLayout: existingMeta.childLayout } : {},
3041
- ...existingMeta?.role !== void 0 ? { role: existingMeta.role } : {},
3042
- ...existingMeta?.display !== void 0 ? { display: existingMeta.display } : {},
3043
- parentDeviceId,
3044
- id,
3045
- features: featuresArr,
3046
- exportFingerprint: fingerprint
3047
- }
3048
- } });
2990
+ await pctx.metaStore.rows.upsertRegistration({
2991
+ deviceId: id,
2992
+ addonId,
2993
+ stableId,
2994
+ type,
2995
+ name: resolvedName,
2996
+ userNamed: wasUserNamed,
2997
+ location: existingMeta?.location ?? null,
2998
+ disabled: existingMeta?.disabled ?? false,
2999
+ parentDeviceId: parentDeviceId ?? null,
3000
+ registered: true,
3001
+ features: featuresArr,
3002
+ exportFingerprint: fingerprint
3003
+ });
3049
3004
  return {
3050
3005
  isFirstRegistration: isFirst,
3051
3006
  exportFingerprint: fingerprint,
@@ -3105,26 +3060,9 @@ async function removeDevice(pctx, input) {
3105
3060
  const persisted = await pctx.metaStore.resolvePersistedById(deviceId);
3106
3061
  if (!persisted) return;
3107
3062
  const { addonId, stableId, meta: persistedMeta } = persisted;
3108
- const key = String(deviceId);
3109
3063
  const deviceName = persistedMeta.name;
3110
3064
  await pctx.metaStore.withMetaWriteLock(async () => {
3111
- const index = await pctx.metaStore.readIndex();
3112
- const remaining = (index[addonId] ?? []).filter((sid) => sid !== stableId);
3113
- const updatedIndex = remaining.length > 0 ? {
3114
- ...index,
3115
- [addonId]: remaining
3116
- } : (() => {
3117
- const { [addonId]: _removed, ...rest } = index;
3118
- return rest;
3119
- })();
3120
- await pctx.settings.writeAddonStore({ deviceIndex: updatedIndex });
3121
- const { [key]: _removedMeta, ...restMeta } = await pctx.metaStore.readMeta();
3122
- await pctx.settings.writeAddonStore({ deviceMeta: restMeta });
3123
- const map = await pctx.metaStore.readMetadataMap();
3124
- if (key in map) {
3125
- const { [key]: _removedMetadata, ...restMap } = map;
3126
- await pctx.settings.writeAddonStore({ deviceMetadata: restMap });
3127
- }
3065
+ await pctx.metaStore.rows.remove(deviceId);
3128
3066
  });
3129
3067
  await pctx.settings.clearDeviceStore(deviceId);
3130
3068
  await pctx.settings.clearDeviceRuntimeState(deviceId);
@@ -3180,11 +3118,10 @@ async function loadConfig(pctx, input) {
3180
3118
  */
3181
3119
  async function loadMeta(pctx, input) {
3182
3120
  const { deviceId } = input;
3183
- const persisted = await pctx.metaStore.resolvePersistedById(deviceId);
3184
- if (!persisted) return null;
3185
- const { addonId, stableId, meta: m } = persisted;
3186
- const key = String(deviceId);
3187
- const metadata = (await pctx.metaStore.readMetadataMap())[key] ?? null;
3121
+ const row = await pctx.metaStore.getRow(deviceId);
3122
+ if (row === null) return null;
3123
+ const { meta: m, metadata } = row;
3124
+ const { addonId, stableId } = m;
3188
3125
  return {
3189
3126
  id: m.id,
3190
3127
  stableId,
@@ -3214,32 +3151,26 @@ async function setName(pctx, input) {
3214
3151
  const persisted = await pctx.metaStore.resolvePersistedById(deviceId);
3215
3152
  if (!persisted) throw new Error(`[device-manager] setName: unknown device id=${deviceId}`);
3216
3153
  const { meta: m } = persisted;
3217
- const key = String(deviceId);
3218
3154
  const oldName = m.name;
3219
- const allMeta = await pctx.metaStore.readMeta();
3220
- const nextMeta = {
3221
- ...allMeta,
3222
- [key]: {
3223
- ...m,
3224
- name,
3225
- userNamed: true
3155
+ await pctx.metaStore.rows.patch(deviceId, {
3156
+ name,
3157
+ userNamed: true
3158
+ });
3159
+ if (oldName.length > 0 && oldName !== name) {
3160
+ const candidates = /* @__PURE__ */ new Map();
3161
+ for (const row of await pctx.metaStore.rows.listByParent(deviceId)) candidates.set(row.meta.id, row.meta);
3162
+ for (const row of await pctx.metaStore.rows.listAll()) if (row.meta.linkDeviceId === deviceId) candidates.set(row.meta.id, row.meta);
3163
+ candidates.delete(deviceId);
3164
+ for (const childMeta of candidates.values()) {
3165
+ if (childMeta.name !== oldName && !childMeta.name.startsWith(`${oldName} `)) continue;
3166
+ const childName = childMeta.name === oldName ? name : `${name}${childMeta.name.slice(oldName.length)}`;
3167
+ await pctx.metaStore.rows.patch(childMeta.id, { name: childName });
3168
+ cascaded.push({
3169
+ id: childMeta.id,
3170
+ name: childName
3171
+ });
3226
3172
  }
3227
- };
3228
- if (oldName.length > 0 && oldName !== name) for (const [childKey, childMeta] of Object.entries(allMeta)) {
3229
- if (childKey === key) continue;
3230
- if (!(childMeta.parentDeviceId === deviceId || childMeta.linkDeviceId === deviceId)) continue;
3231
- if (childMeta.name !== oldName && !childMeta.name.startsWith(`${oldName} `)) continue;
3232
- const childName = childMeta.name === oldName ? name : `${name}${childMeta.name.slice(oldName.length)}`;
3233
- nextMeta[childKey] = {
3234
- ...childMeta,
3235
- name: childName
3236
- };
3237
- cascaded.push({
3238
- id: Number(childKey),
3239
- name: childName
3240
- });
3241
3173
  }
3242
- await pctx.settings.writeAddonStore({ deviceMeta: nextMeta });
3243
3174
  });
3244
3175
  pctx.host.ctx.eventBus.emit({
3245
3176
  id: (0, node_crypto.randomUUID)(),
@@ -3279,18 +3210,8 @@ async function setName(pctx, input) {
3279
3210
  async function setLocation(pctx, input) {
3280
3211
  const { deviceId, location } = input;
3281
3212
  await pctx.metaStore.withMetaWriteLock(async () => {
3282
- const persisted = await pctx.metaStore.resolvePersistedById(deviceId);
3283
- if (!persisted) throw new Error(`[device-manager] setLocation: unknown device id=${deviceId}`);
3284
- const { meta: m } = persisted;
3285
- const key = String(deviceId);
3286
- const allMeta = await pctx.metaStore.readMeta();
3287
- await pctx.settings.writeAddonStore({ deviceMeta: {
3288
- ...allMeta,
3289
- [key]: {
3290
- ...m,
3291
- location
3292
- }
3293
- } });
3213
+ if (!await pctx.metaStore.resolvePersistedById(deviceId)) throw new Error(`[device-manager] setLocation: unknown device id=${deviceId}`);
3214
+ await pctx.metaStore.rows.patch(deviceId, { location });
3294
3215
  });
3295
3216
  pctx.host.ctx.eventBus.emit({
3296
3217
  id: (0, node_crypto.randomUUID)(),
@@ -3317,18 +3238,8 @@ async function setLocation(pctx, input) {
3317
3238
  async function setType(pctx, input) {
3318
3239
  const { deviceId, type } = input;
3319
3240
  await pctx.metaStore.withMetaWriteLock(async () => {
3320
- const persisted = await pctx.metaStore.resolvePersistedById(deviceId);
3321
- if (!persisted) throw new Error(`[device-manager] setType: unknown device id=${deviceId}`);
3322
- const { meta: m } = persisted;
3323
- const key = String(deviceId);
3324
- const allMeta = await pctx.metaStore.readMeta();
3325
- await pctx.settings.writeAddonStore({ deviceMeta: {
3326
- ...allMeta,
3327
- [key]: {
3328
- ...m,
3329
- type
3330
- }
3331
- } });
3241
+ if (!await pctx.metaStore.resolvePersistedById(deviceId)) throw new Error(`[device-manager] setType: unknown device id=${deviceId}`);
3242
+ await pctx.metaStore.rows.patch(deviceId, { type });
3332
3243
  });
3333
3244
  pctx.host.ctx.eventBus.emit({
3334
3245
  id: (0, node_crypto.randomUUID)(),
@@ -3363,18 +3274,8 @@ async function setIntegrationId(pctx, input) {
3363
3274
  async function setLinkDeviceId(pctx, input) {
3364
3275
  const { deviceId, linkDeviceId } = input;
3365
3276
  await pctx.metaStore.withMetaWriteLock(async () => {
3366
- const persisted = await pctx.metaStore.resolvePersistedById(deviceId);
3367
- if (!persisted) throw new Error(`[device-manager] setLinkDeviceId: unknown device id=${deviceId}`);
3368
- const { meta: m } = persisted;
3369
- const key = String(deviceId);
3370
- const allMeta = await pctx.metaStore.readMeta();
3371
- await pctx.settings.writeAddonStore({ deviceMeta: {
3372
- ...allMeta,
3373
- [key]: {
3374
- ...m,
3375
- linkDeviceId
3376
- }
3377
- } });
3277
+ if (!await pctx.metaStore.resolvePersistedById(deviceId)) throw new Error(`[device-manager] setLinkDeviceId: unknown device id=${deviceId}`);
3278
+ await pctx.metaStore.rows.patch(deviceId, { linkDeviceId });
3378
3279
  });
3379
3280
  pctx.host.ctx.eventBus.emit({
3380
3281
  id: (0, node_crypto.randomUUID)(),
@@ -3401,18 +3302,8 @@ async function setLinkDeviceId(pctx, input) {
3401
3302
  async function setPrimaryChildEntityId(pctx, input) {
3402
3303
  const { deviceId, primaryChildEntityId } = input;
3403
3304
  await pctx.metaStore.withMetaWriteLock(async () => {
3404
- const persisted = await pctx.metaStore.resolvePersistedById(deviceId);
3405
- if (!persisted) throw new Error(`[device-manager] setPrimaryChildEntityId: unknown device id=${deviceId}`);
3406
- const { meta: m } = persisted;
3407
- const key = String(deviceId);
3408
- const allMeta = await pctx.metaStore.readMeta();
3409
- await pctx.settings.writeAddonStore({ deviceMeta: {
3410
- ...allMeta,
3411
- [key]: {
3412
- ...m,
3413
- primaryChildEntityId
3414
- }
3415
- } });
3305
+ if (!await pctx.metaStore.resolvePersistedById(deviceId)) throw new Error(`[device-manager] setPrimaryChildEntityId: unknown device id=${deviceId}`);
3306
+ await pctx.metaStore.rows.patch(deviceId, { primaryChildEntityId });
3416
3307
  });
3417
3308
  pctx.host.ctx.eventBus.emit({
3418
3309
  id: (0, node_crypto.randomUUID)(),
@@ -3438,18 +3329,8 @@ async function setPrimaryChildEntityId(pctx, input) {
3438
3329
  async function setChildLayout(pctx, input) {
3439
3330
  const { deviceId, childLayout } = input;
3440
3331
  await pctx.metaStore.withMetaWriteLock(async () => {
3441
- const persisted = await pctx.metaStore.resolvePersistedById(deviceId);
3442
- if (!persisted) throw new Error(`[device-manager] setChildLayout: unknown device id=${deviceId}`);
3443
- const { meta: m } = persisted;
3444
- const key = String(deviceId);
3445
- const allMeta = await pctx.metaStore.readMeta();
3446
- await pctx.settings.writeAddonStore({ deviceMeta: {
3447
- ...allMeta,
3448
- [key]: {
3449
- ...m,
3450
- childLayout
3451
- }
3452
- } });
3332
+ if (!await pctx.metaStore.resolvePersistedById(deviceId)) throw new Error(`[device-manager] setChildLayout: unknown device id=${deviceId}`);
3333
+ await pctx.metaStore.rows.patch(deviceId, { childLayout });
3453
3334
  });
3454
3335
  pctx.host.ctx.eventBus.emit({
3455
3336
  id: (0, node_crypto.randomUUID)(),
@@ -3475,18 +3356,8 @@ async function setChildLayout(pctx, input) {
3475
3356
  async function setRole(pctx, input) {
3476
3357
  const { deviceId, role } = input;
3477
3358
  await pctx.metaStore.withMetaWriteLock(async () => {
3478
- const persisted = await pctx.metaStore.resolvePersistedById(deviceId);
3479
- if (!persisted) throw new Error(`[device-manager] setRole: unknown device id=${deviceId}`);
3480
- const { meta: m } = persisted;
3481
- const key = String(deviceId);
3482
- const allMeta = await pctx.metaStore.readMeta();
3483
- await pctx.settings.writeAddonStore({ deviceMeta: {
3484
- ...allMeta,
3485
- [key]: {
3486
- ...m,
3487
- role
3488
- }
3489
- } });
3359
+ if (!await pctx.metaStore.resolvePersistedById(deviceId)) throw new Error(`[device-manager] setRole: unknown device id=${deviceId}`);
3360
+ await pctx.metaStore.rows.patch(deviceId, { role });
3490
3361
  });
3491
3362
  pctx.host.ctx.eventBus.emit({
3492
3363
  id: (0, node_crypto.randomUUID)(),
@@ -3531,19 +3402,8 @@ async function setDisplay(pctx, input) {
3531
3402
  const { deviceId, display } = input;
3532
3403
  const normalized = display === null ? null : normalizeDisplayOverride(display);
3533
3404
  await pctx.metaStore.withMetaWriteLock(async () => {
3534
- const persisted = await pctx.metaStore.resolvePersistedById(deviceId);
3535
- if (!persisted) throw new Error(`[device-manager] setDisplay: unknown device id=${deviceId}`);
3536
- const { meta: m } = persisted;
3537
- const key = String(deviceId);
3538
- const allMeta = await pctx.metaStore.readMeta();
3539
- const nextRow = normalized === null ? (({ display: _drop, ...rest }) => rest)(m) : {
3540
- ...m,
3541
- display: normalized
3542
- };
3543
- await pctx.settings.writeAddonStore({ deviceMeta: {
3544
- ...allMeta,
3545
- [key]: nextRow
3546
- } });
3405
+ if (!await pctx.metaStore.resolvePersistedById(deviceId)) throw new Error(`[device-manager] setDisplay: unknown device id=${deviceId}`);
3406
+ await pctx.metaStore.rows.patch(deviceId, { display: normalized });
3547
3407
  });
3548
3408
  pctx.host.ctx.eventBus.emit({
3549
3409
  id: (0, node_crypto.randomUUID)(),
@@ -3571,7 +3431,7 @@ async function getRoleDisplayDefaults(pctx, _input) {
3571
3431
  * Replace the per-role display defaults whole-record (full replace). Override
3572
3432
  * units are normalized (`normalizeUnit`) at write so the render path always
3573
3433
  * looks up canonical spellings. Single-writer top-level key — no lock, no RMW,
3574
- * no interaction with the `deviceMeta` write lock. Not per-device, so no event
3434
+ * no interaction with the device write lock. Not per-device, so no event
3575
3435
  * is emitted; the UI invalidates its own query on mutate.
3576
3436
  */
3577
3437
  async function setRoleDisplayDefaults(pctx, input) {
@@ -3584,7 +3444,7 @@ async function setRoleDisplayDefaults(pctx, input) {
3584
3444
  /**
3585
3445
  * Batched meta pre-seed. Applies every provided field to the
3586
3446
  * device's meta row in ONE read-modify-write under a single
3587
- * `withMetaWriteLock` acquisition (one `deviceMeta` blob write),
3447
+ * `withMetaWriteLock` acquisition (one row write),
3588
3448
  * then emits one `DeviceMetaChanged` event per field that was
3589
3449
  * supplied — preserving the exact semantics of the individual
3590
3450
  * setters (`setName` / `setLocation` / `setType` /
@@ -3600,24 +3460,15 @@ async function setRoleDisplayDefaults(pctx, input) {
3600
3460
  async function applyInitialMeta(pctx, input) {
3601
3461
  const { deviceId, name, location, type, integrationId, linkDeviceId, role } = input;
3602
3462
  await pctx.metaStore.withMetaWriteLock(async () => {
3603
- const persisted = await pctx.metaStore.resolvePersistedById(deviceId);
3604
- if (!persisted) throw new Error(`[device-manager] applyInitialMeta: unknown device id=${deviceId}`);
3605
- const { meta: m } = persisted;
3606
- const key = String(deviceId);
3607
- const allMeta = await pctx.metaStore.readMeta();
3608
- const merged = {
3609
- ...m,
3463
+ if (!await pctx.metaStore.resolvePersistedById(deviceId)) throw new Error(`[device-manager] applyInitialMeta: unknown device id=${deviceId}`);
3464
+ await pctx.metaStore.rows.patch(deviceId, {
3610
3465
  ...name !== void 0 ? { name } : {},
3611
3466
  ...location !== void 0 ? { location } : {},
3612
3467
  ...type !== void 0 ? { type } : {},
3613
3468
  ...integrationId !== void 0 ? { integrationId } : {},
3614
3469
  ...linkDeviceId !== void 0 ? { linkDeviceId } : {},
3615
3470
  ...role !== void 0 ? { role } : {}
3616
- };
3617
- await pctx.settings.writeAddonStore({ deviceMeta: {
3618
- ...allMeta,
3619
- [key]: merged
3620
- } });
3471
+ });
3621
3472
  });
3622
3473
  const emitMetaChanged = (field, value) => {
3623
3474
  pctx.host.ctx.eventBus.emit({
@@ -3653,10 +3504,9 @@ async function applyInitialMeta(pctx, input) {
3653
3504
  async function setMetadata(pctx, input) {
3654
3505
  const { deviceId, patch } = input;
3655
3506
  const result = await pctx.metaStore.withMetaWriteLock(async () => {
3656
- if (!await pctx.metaStore.resolvePersistedById(deviceId)) throw new Error(`[device-manager] setMetadata: unknown device id=${deviceId}`);
3657
- const key = String(deviceId);
3658
- const map = await pctx.metaStore.readMetadataMap();
3659
- const next = { ...map[key] ?? {} };
3507
+ const row = await pctx.metaStore.rows.get(deviceId);
3508
+ if (row === null) throw new Error(`[device-manager] setMetadata: unknown device id=${deviceId}`);
3509
+ const next = { ...row.metadata ?? {} };
3660
3510
  let changed = false;
3661
3511
  for (const [k, v] of Object.entries(patch)) if (v === null) {
3662
3512
  if (k in next) {
@@ -3669,10 +3519,7 @@ async function setMetadata(pctx, input) {
3669
3519
  }
3670
3520
  if (!changed) return { changed: false };
3671
3521
  const hasFields = Object.keys(next).length > 0;
3672
- const updatedMap = { ...map };
3673
- if (hasFields) updatedMap[key] = next;
3674
- else delete updatedMap[key];
3675
- await pctx.settings.writeAddonStore({ deviceMetadata: updatedMap });
3522
+ await pctx.metaStore.rows.patch(deviceId, { metadata: hasFields ? next : null });
3676
3523
  return {
3677
3524
  changed: true,
3678
3525
  finalMeta: hasFields ? next : null
@@ -3718,15 +3565,7 @@ async function setDisabled(pctx, input) {
3718
3565
  const persisted = await pctx.metaStore.resolvePersistedById(deviceId);
3719
3566
  if (!persisted) throw new Error(`[device-manager] setDisabled: unknown device id=${deviceId}`);
3720
3567
  const { meta: m } = persisted;
3721
- const key = String(deviceId);
3722
- const allMeta = await pctx.metaStore.readMeta();
3723
- await pctx.settings.writeAddonStore({ deviceMeta: {
3724
- ...allMeta,
3725
- [key]: {
3726
- ...m,
3727
- disabled
3728
- }
3729
- } });
3568
+ await pctx.metaStore.rows.patch(deviceId, { disabled });
3730
3569
  return {
3731
3570
  changed: (m.disabled ?? false) !== disabled,
3732
3571
  integrationId: m.integrationId ?? ""
@@ -3776,9 +3615,7 @@ async function loadRuntimeState(pctx, input) {
3776
3615
  * location autocomplete.
3777
3616
  */
3778
3617
  async function listLocations(pctx) {
3779
- const store = await pctx.settings.readAddonStore();
3780
- const meta = store.deviceMeta ?? {};
3781
- const locations = store.locations ?? [];
3618
+ const locations = (await pctx.metaStore.readStore()).locations ?? [];
3782
3619
  const seen = /* @__PURE__ */ new Map();
3783
3620
  const consider = (raw) => {
3784
3621
  if (typeof raw !== "string") return;
@@ -3788,7 +3625,7 @@ async function listLocations(pctx) {
3788
3625
  if (!seen.has(key)) seen.set(key, trimmed);
3789
3626
  };
3790
3627
  for (const label of locations) consider(label);
3791
- for (const m of Object.values(meta)) consider(m.location);
3628
+ for (const row of await pctx.metaStore.rows.listAll()) consider(row.meta.location);
3792
3629
  return [...seen.values()].toSorted((a, b) => a.localeCompare(b, void 0, { sensitivity: "base" }));
3793
3630
  }
3794
3631
  /**
@@ -3800,7 +3637,7 @@ async function listLocations(pctx) {
3800
3637
  async function addLocation(pctx, input) {
3801
3638
  const trimmed = input.name.trim();
3802
3639
  if (trimmed.length === 0) throw new Error("[device-manager] addLocation: name must be non-empty");
3803
- const current = (await pctx.settings.readAddonStore()).locations ?? [];
3640
+ const current = (await pctx.metaStore.readStore()).locations ?? [];
3804
3641
  if (current.some((l) => l.toLowerCase() === trimmed.toLowerCase())) return;
3805
3642
  await pctx.settings.writeAddonStore({ locations: [...current, trimmed] });
3806
3643
  }
@@ -3816,25 +3653,21 @@ async function addLocation(pctx, input) {
3816
3653
  async function removeLocation(pctx, input) {
3817
3654
  const trimmed = input.name.trim();
3818
3655
  if (trimmed.length === 0) return;
3819
- const store = await pctx.settings.readAddonStore();
3820
- const current = store.locations ?? [];
3656
+ const current = (await pctx.metaStore.readStore()).locations ?? [];
3821
3657
  const remaining = current.filter((l) => l.toLowerCase() !== trimmed.toLowerCase());
3822
3658
  if (remaining.length !== current.length) await pctx.settings.writeAddonStore({ locations: remaining });
3823
3659
  if (input.cascade !== true) return;
3824
- const meta = store.deviceMeta ?? {};
3825
- const updates = { ...meta };
3826
- const cleared = [];
3827
- for (const [key, m] of Object.entries(meta)) {
3828
- if (typeof m.location !== "string") continue;
3829
- if (m.location.trim().toLowerCase() !== trimmed.toLowerCase()) continue;
3830
- updates[key] = {
3831
- ...m,
3832
- location: null
3833
- };
3834
- cleared.push(m.id);
3835
- }
3836
- if (cleared.length === 0) return;
3837
- await pctx.settings.writeAddonStore({ deviceMeta: updates });
3660
+ const cleared = await pctx.metaStore.withMetaWriteLock(async () => {
3661
+ const out = [];
3662
+ for (const row of await pctx.metaStore.rows.listAll()) {
3663
+ const location = row.meta.location;
3664
+ if (typeof location !== "string") continue;
3665
+ if (location.trim().toLowerCase() !== trimmed.toLowerCase()) continue;
3666
+ await pctx.metaStore.rows.patch(row.meta.id, { location: null });
3667
+ out.push(row.meta.id);
3668
+ }
3669
+ return out;
3670
+ });
3838
3671
  for (const deviceId of cleared) pctx.host.ctx.eventBus.emit({
3839
3672
  id: (0, node_crypto.randomUUID)(),
3840
3673
  timestamp: /* @__PURE__ */ new Date(),
@@ -3851,42 +3684,58 @@ async function removeLocation(pctx, input) {
3851
3684
  });
3852
3685
  }
3853
3686
  //#endregion
3687
+ //#region src/builtins/device-manager/device-meta-types.ts
3688
+ /**
3689
+ * Decode the raw `ctx.settings.readAddonStore()` record into {@link AddonStore}.
3690
+ *
3691
+ * A field of the wrong shape reads as ABSENT rather than being trusted through
3692
+ * a cast: the store is JSON on disk and a hand-edit or a partial restore must
3693
+ * cost the caller its default, never a downstream `TypeError`.
3694
+ */
3695
+ function decodeAddonStore(raw) {
3696
+ const nextDeviceId = raw["nextDeviceId"];
3697
+ const locations = raw["locations"];
3698
+ const roleDisplayDefaults = raw["roleDisplayDefaults"];
3699
+ return {
3700
+ ...typeof nextDeviceId === "number" && Number.isFinite(nextDeviceId) ? { nextDeviceId } : {},
3701
+ ...Array.isArray(locations) ? { locations: locations.filter((l) => typeof l === "string") } : {},
3702
+ ...isRoleDisplayDefaults(roleDisplayDefaults) ? { roleDisplayDefaults } : {}
3703
+ };
3704
+ }
3705
+ function isRoleDisplayDefaults(value) {
3706
+ return value !== null && typeof value === "object" && !Array.isArray(value);
3707
+ }
3708
+ //#endregion
3854
3709
  //#region src/builtins/device-manager/device-meta-store.ts
3855
3710
  var DeviceMetaStore = class {
3856
3711
  settings;
3857
3712
  registry;
3713
+ rows;
3858
3714
  /** Synchronous ownership cache, keyed by NUMERIC deviceId → owning addonId.
3859
- * The persisted meta store is authoritative but reads are async; hub-side
3715
+ * The persisted row store is authoritative but reads are async; hub-side
3860
3716
  * callers (e.g. `CapabilityRegistry.getNativeProvider` fallback) need
3861
3717
  * ownership without awaiting. Kept in sync with every register/remove and
3862
3718
  * warmed from persistence on boot. */
3863
3719
  idToAddonId = /* @__PURE__ */ new Map();
3864
- /** Serialises every read-modify-write of the deviceMeta / deviceIndex blob
3865
- * through one promise chain (see `withMetaWriteLock`). Per-instance state
3866
- * identical to the former `onInitialize` closure variable. */
3720
+ /** Serialises every read-modify-write of a device row through one promise
3721
+ * chain (see `withMetaWriteLock`). Per-instance state. */
3867
3722
  metaWriteChain = Promise.resolve();
3868
- constructor(settings, registry) {
3723
+ constructor(settings, registry, rows) {
3869
3724
  this.settings = settings;
3870
3725
  this.registry = registry;
3726
+ this.rows = rows;
3871
3727
  }
3872
3728
  /** The read currently in flight, or null. Never a settled value — see
3873
3729
  * {@link readStore}. */
3874
3730
  inFlightRead = null;
3875
3731
  /**
3876
- * The whole persisted addon store.
3732
+ * The addon's own settings row set — `nextDeviceId`, `roleDisplayDefaults`,
3733
+ * `locations`. NOT the fleet: no device has lived here since the flatten.
3877
3734
  *
3878
3735
  * **Concurrent callers join the read already in flight.** This is not a
3879
3736
  * cache and nothing survives settlement: a caller that awaited the running
3880
3737
  * promise could not have observed anything older than its result, so the
3881
- * only thing that changes is cost. What that cost was, measured on the
3882
- * 2026-08-19 boot: `readAddonStore` lands in `SqliteSettingsBackend
3883
- * .getAllAddon`, which reads and `JSON.parse`s this addon's rows —
3884
- * 625 KB on the live hub (`deviceMeta` 467 KB + `deviceMetadata` 87 KB +
3885
- * `deviceIndex` 70 KB) — synchronously, on the hub's event loop. A V8
3886
- * profile of that boot had hub-main's JS thread 99.9% busy with 64% of it
3887
- * inside `getAllAddon`, ~89% of that entered here, and every runner's first
3888
- * store read queued behind it (the notification centre's six parallel reads
3889
- * all resolved together at t+44.7 s).
3738
+ * only thing that changes is cost.
3890
3739
  *
3891
3740
  * A rejection is NOT latched: the slot is cleared before the promise
3892
3741
  * settles either way, so a failed read costs the joiners that one failure
@@ -3897,7 +3746,7 @@ var DeviceMetaStore = class {
3897
3746
  if (existing !== null) return existing;
3898
3747
  const read = (async () => {
3899
3748
  try {
3900
- return await this.settings.readAddonStore();
3749
+ return decodeAddonStore(await this.settings.readAddonStore());
3901
3750
  } finally {
3902
3751
  this.inFlightRead = null;
3903
3752
  }
@@ -3905,41 +3754,6 @@ var DeviceMetaStore = class {
3905
3754
  this.inFlightRead = read;
3906
3755
  return read;
3907
3756
  };
3908
- /**
3909
- * The three fleet projections from ONE read.
3910
- *
3911
- * `listAll` asked for `deviceMeta`, then `deviceMetadata`, then
3912
- * `deviceIndex` — three SEQUENTIAL awaits, which {@link readStore}'s
3913
- * in-flight join cannot collapse because each starts after the previous one
3914
- * settled. Three full 625 KB parses per call, on a call made once per device
3915
- * lifecycle event during a 974-device boot: 23% of hub-main's CPU.
3916
- *
3917
- * It is also ONE snapshot. Three separate reads could straddle a write and
3918
- * hand back an index that names a device the meta map no longer has.
3919
- */
3920
- readAll = async () => {
3921
- const store = await this.readStore();
3922
- return {
3923
- index: store.deviceIndex ?? {},
3924
- meta: store.deviceMeta ?? {},
3925
- metadata: store.deviceMetadata ?? {}
3926
- };
3927
- };
3928
- readIndex = async () => {
3929
- return (await this.readStore()).deviceIndex ?? {};
3930
- };
3931
- readMeta = async () => {
3932
- return (await this.readStore()).deviceMeta ?? {};
3933
- };
3934
- /** Hardware-identity metadata map. Lives in a sibling key on the
3935
- * device-manager addon store so its writers (`setMetadata`) never
3936
- * collide with the lifecycle writers on `deviceMeta`
3937
- * (`registerDevice` / `setName` / `setLocation` / `setDisabled`).
3938
- * Single-writer per row eliminates the "writer X clobbers writer
3939
- * Y's field" bug class — `setMetadata` is the only producer. */
3940
- readMetadataMap = async () => {
3941
- return (await this.readStore()).deviceMetadata ?? {};
3942
- };
3943
3757
  withMetaWriteLock = async (fn) => {
3944
3758
  const previous = this.metaWriteChain;
3945
3759
  let release = () => {};
@@ -3954,31 +3768,36 @@ var DeviceMetaStore = class {
3954
3768
  release();
3955
3769
  }
3956
3770
  };
3771
+ /** The whole persisted row for one device, or `null`. */
3772
+ getRow = async (deviceId) => this.rows.get(deviceId);
3957
3773
  /**
3958
3774
  * Resolve a numeric deviceId to the owning `(addonId, stableId)` pair.
3959
- * Scans persisted meta — live IDevice lookup (hub registry) is handled
3775
+ * Reads the device's own row — live IDevice lookup (hub registry) is handled
3960
3776
  * separately per call site so callers can decide whether to route to
3961
3777
  * an in-process driver or to the cross-process `device-ops` bridge.
3962
3778
  * Returns null when no device with that id is known to the hub.
3963
3779
  */
3964
3780
  resolvePersistedById = async (deviceId) => {
3965
- const m = (await this.readMeta())[String(deviceId)];
3966
- if (!m) return null;
3781
+ const row = await this.rows.get(deviceId);
3782
+ if (row === null) return null;
3967
3783
  return {
3968
- addonId: m.addonId,
3969
- stableId: m.stableId,
3970
- meta: m
3784
+ addonId: row.meta.addonId,
3785
+ stableId: row.meta.stableId,
3786
+ meta: row.meta
3971
3787
  };
3972
3788
  };
3789
+ /** The device's hardware-identity metadata blob, or `null`. */
3790
+ readMetadata = async (deviceId) => {
3791
+ return (await this.rows.get(deviceId))?.metadata ?? null;
3792
+ };
3973
3793
  /** Direct children of a device: the union of the live registry's children
3974
- * and the persisted-meta scan (`parentDeviceId === parentId`), deduplicated
3794
+ * and the persisted rows whose `parentDeviceId` is `parentId`, deduplicated
3975
3795
  * and excluding self. Shared by the `remove` cascade and the `resetToSource`
3976
3796
  * resync purge (#19). */
3977
3797
  directChildIds = async (parentId) => {
3978
3798
  const ids = /* @__PURE__ */ new Set();
3979
3799
  if (this.registry) for (const c of this.registry.getChildren(parentId)) ids.add(c.id);
3980
- const meta = await this.readMeta();
3981
- for (const m of Object.values(meta)) if (m.parentDeviceId === parentId) ids.add(m.id);
3800
+ for (const row of await this.rows.listByParent(parentId)) ids.add(row.meta.id);
3982
3801
  ids.delete(parentId);
3983
3802
  return [...ids];
3984
3803
  };
@@ -3989,6 +3808,525 @@ var DeviceMetaStore = class {
3989
3808
  };
3990
3809
  };
3991
3810
  //#endregion
3811
+ //#region src/builtins/device-manager/device-row-store.ts
3812
+ /**
3813
+ * @durable class=registry owner=device-manager
3814
+ * write="one row per device, written by `allocateDeviceId` (identity placeholder),
3815
+ * `registerDevice` (full reconcile) and every meta setter (single-column patch);
3816
+ * `setMetadata` patches the `metadata` column of the same row"
3817
+ * retention="none — a row goes only when the operator removes the device
3818
+ * (`removeDevice`), or when an integration is deleted and cascades. Bounded by the
3819
+ * fleet an operator configures (974 rows on the reference hub)."
3820
+ */
3821
+ var DEVICE_ROWS_COLLECTION = "device-manager:devices";
3822
+ /**
3823
+ * Fleet reads pass this explicitly.
3824
+ *
3825
+ * `settings-store.query` applies a DEFAULT row cap of 2 000 when the caller
3826
+ * names no `limit` (`query-bounds.ts`), and truncation there is silent to the
3827
+ * caller — it warns in the engine's log and returns a short list that looks
3828
+ * complete. The reference hub is already at 974 devices; half the default cap
3829
+ * is not a margin worth betting the fleet listing on. 20 000 is the engine's
3830
+ * hard ceiling, so this asks for everything the engine will ever serve in one
3831
+ * call and any future need to page is a loud failure rather than a quiet one.
3832
+ */
3833
+ var DEVICE_ROWS_FLEET_LIMIT = 2e4;
3834
+ var DEVICE_ROWS_COLUMNS = [
3835
+ {
3836
+ name: "id",
3837
+ type: "TEXT",
3838
+ primaryKey: true,
3839
+ notNull: true
3840
+ },
3841
+ {
3842
+ name: "deviceId",
3843
+ type: "INTEGER",
3844
+ notNull: true
3845
+ },
3846
+ {
3847
+ name: "addonId",
3848
+ type: "TEXT",
3849
+ notNull: true
3850
+ },
3851
+ {
3852
+ name: "stableId",
3853
+ type: "TEXT",
3854
+ notNull: true
3855
+ },
3856
+ {
3857
+ name: "type",
3858
+ type: "TEXT",
3859
+ notNull: true
3860
+ },
3861
+ {
3862
+ name: "name",
3863
+ type: "TEXT",
3864
+ notNull: true
3865
+ },
3866
+ {
3867
+ name: "userNamed",
3868
+ type: "BOOLEAN"
3869
+ },
3870
+ {
3871
+ name: "location",
3872
+ type: "TEXT"
3873
+ },
3874
+ {
3875
+ name: "disabled",
3876
+ type: "BOOLEAN",
3877
+ notNull: true,
3878
+ defaultValue: false
3879
+ },
3880
+ {
3881
+ name: "parentDeviceId",
3882
+ type: "INTEGER"
3883
+ },
3884
+ {
3885
+ name: "registered",
3886
+ type: "BOOLEAN",
3887
+ notNull: true,
3888
+ defaultValue: false
3889
+ },
3890
+ {
3891
+ name: "features",
3892
+ type: "JSON"
3893
+ },
3894
+ {
3895
+ name: "exportFingerprint",
3896
+ type: "TEXT"
3897
+ },
3898
+ {
3899
+ name: "integrationId",
3900
+ type: "TEXT"
3901
+ },
3902
+ {
3903
+ name: "linkDeviceId",
3904
+ type: "INTEGER"
3905
+ },
3906
+ {
3907
+ name: "primaryChildEntityId",
3908
+ type: "TEXT"
3909
+ },
3910
+ {
3911
+ name: "childLayout",
3912
+ type: "JSON"
3913
+ },
3914
+ {
3915
+ name: "role",
3916
+ type: "TEXT"
3917
+ },
3918
+ {
3919
+ name: "display",
3920
+ type: "JSON"
3921
+ },
3922
+ {
3923
+ name: "metadata",
3924
+ type: "JSON"
3925
+ }
3926
+ ];
3927
+ var DEVICE_ROWS_INDEXES = [
3928
+ {
3929
+ name: "idx_dm_devices_addon_stable",
3930
+ columns: ["addonId", "stableId"]
3931
+ },
3932
+ {
3933
+ name: "idx_dm_devices_parent",
3934
+ columns: ["parentDeviceId"]
3935
+ },
3936
+ {
3937
+ name: "idx_dm_devices_integration",
3938
+ columns: ["integrationId"]
3939
+ }
3940
+ ];
3941
+ /** Adapt `ctx.api.settingsStore` (tRPC namespace) to {@link DeviceRowBackend}. */
3942
+ function deviceRowBackendOf(client) {
3943
+ return {
3944
+ declareCollection: async (input) => {
3945
+ await client.declareCollection.mutate(input);
3946
+ },
3947
+ get: (input) => client.get.query(input),
3948
+ set: async (input) => {
3949
+ await client.set.mutate(input);
3950
+ },
3951
+ query: (input) => client.query.query(input),
3952
+ updateWhere: (input) => client.updateWhere.mutate(input),
3953
+ delete: async (input) => {
3954
+ await client.delete.mutate(input);
3955
+ },
3956
+ count: (input) => client.count.query(input)
3957
+ };
3958
+ }
3959
+ function isPlainObject(value) {
3960
+ return value !== null && typeof value === "object" && !Array.isArray(value);
3961
+ }
3962
+ function readString(value) {
3963
+ return typeof value === "string" ? value : void 0;
3964
+ }
3965
+ function readNumber(value) {
3966
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
3967
+ }
3968
+ function readBoolean(value) {
3969
+ if (typeof value === "boolean") return value;
3970
+ if (value === 1) return true;
3971
+ if (value === 0) return false;
3972
+ }
3973
+ function readStringArray(value) {
3974
+ if (!Array.isArray(value)) return void 0;
3975
+ const out = [];
3976
+ for (const entry of value) if (typeof entry === "string") out.push(entry);
3977
+ return out;
3978
+ }
3979
+ /**
3980
+ * Decode one stored row.
3981
+ *
3982
+ * Returns `null` for a row missing an identity field the rest of the system
3983
+ * treats as an invariant (`deviceId` / `addonId` / `stableId` / `type` /
3984
+ * `name`). A row like that cannot be projected into a `DeviceInfo` and taking
3985
+ * the whole fleet read down for it would be worse — the caller logs the skip.
3986
+ */
3987
+ function decodeDeviceRow(data) {
3988
+ const deviceId = readNumber(data["deviceId"]);
3989
+ const addonId = readString(data["addonId"]);
3990
+ const stableId = readString(data["stableId"]);
3991
+ const type = readString(data["type"]);
3992
+ const name = readString(data["name"]);
3993
+ if (deviceId === void 0 || addonId === void 0 || stableId === void 0 || type === void 0 || name === void 0) return null;
3994
+ const location = readString(data["location"]);
3995
+ const parentDeviceId = readNumber(data["parentDeviceId"]);
3996
+ const userNamed = readBoolean(data["userNamed"]);
3997
+ const features = readStringArray(data["features"]);
3998
+ const exportFingerprint = readString(data["exportFingerprint"]);
3999
+ const integrationId = readString(data["integrationId"]);
4000
+ const linkDeviceId = readNumber(data["linkDeviceId"]);
4001
+ const primaryChildEntityId = readString(data["primaryChildEntityId"]);
4002
+ const role = readString(data["role"]);
4003
+ const rawChildLayout = data["childLayout"];
4004
+ const rawDisplay = data["display"];
4005
+ const rawMetadata = data["metadata"];
4006
+ return {
4007
+ meta: {
4008
+ id: deviceId,
4009
+ addonId,
4010
+ stableId,
4011
+ type,
4012
+ name,
4013
+ location: location ?? null,
4014
+ disabled: readBoolean(data["disabled"]) ?? false,
4015
+ parentDeviceId: parentDeviceId ?? null,
4016
+ ...userNamed !== void 0 ? { userNamed } : {},
4017
+ ...features !== void 0 ? { features } : {},
4018
+ ...exportFingerprint !== void 0 ? { exportFingerprint } : {},
4019
+ ...integrationId !== void 0 ? { integrationId } : {},
4020
+ ...linkDeviceId !== void 0 ? { linkDeviceId } : {},
4021
+ ...primaryChildEntityId !== void 0 ? { primaryChildEntityId } : {},
4022
+ ...isChildLayout(rawChildLayout) ? { childLayout: rawChildLayout } : {},
4023
+ ...role !== void 0 ? { role } : {},
4024
+ ...isPlainObject(rawDisplay) ? { display: toDisplayOverride(rawDisplay) } : {}
4025
+ },
4026
+ metadata: isPlainObject(rawMetadata) ? rawMetadata : null,
4027
+ registered: readBoolean(data["registered"]) ?? false
4028
+ };
4029
+ }
4030
+ /**
4031
+ * `ChildLayout` is a JSON column: what comes back is whatever was written.
4032
+ * The projection hands it to the UI untouched, so the only thing worth
4033
+ * checking is that it is still the array shape the writer put in.
4034
+ */
4035
+ function isChildLayout(value) {
4036
+ return Array.isArray(value);
4037
+ }
4038
+ /**
4039
+ * `DeviceDisplayOverride` is likewise stored verbatim in a JSON column. It is
4040
+ * an all-optional record, so any object round-trips; the write path
4041
+ * (`normalizeDisplayOverride`) is what gives it shape.
4042
+ */
4043
+ function toDisplayOverride(value) {
4044
+ return value;
4045
+ }
4046
+ /** Full-row value for an upsert: identity + every field of the meta record. */
4047
+ function encodeDeviceRow(meta, extra = {}) {
4048
+ const row = {
4049
+ id: String(meta.id),
4050
+ deviceId: meta.id,
4051
+ addonId: meta.addonId,
4052
+ stableId: meta.stableId,
4053
+ type: meta.type,
4054
+ name: meta.name,
4055
+ userNamed: meta.userNamed ?? null,
4056
+ location: meta.location,
4057
+ disabled: meta.disabled,
4058
+ parentDeviceId: meta.parentDeviceId,
4059
+ registered: extra.registered ?? false,
4060
+ features: meta.features === void 0 ? null : [...meta.features],
4061
+ exportFingerprint: meta.exportFingerprint ?? null,
4062
+ integrationId: meta.integrationId ?? null,
4063
+ linkDeviceId: meta.linkDeviceId ?? null,
4064
+ primaryChildEntityId: meta.primaryChildEntityId ?? null,
4065
+ childLayout: meta.childLayout ?? null,
4066
+ role: meta.role ?? null,
4067
+ display: meta.display ?? null
4068
+ };
4069
+ if (extra.metadata !== void 0) row["metadata"] = extra.metadata;
4070
+ return row;
4071
+ }
4072
+ /** Column map for a partial write — only the keys the caller actually named. */
4073
+ function encodeDeviceRowPatch(patch) {
4074
+ const row = {};
4075
+ for (const [key, value] of Object.entries(patch)) {
4076
+ if (value === void 0) continue;
4077
+ row[key] = value;
4078
+ }
4079
+ return row;
4080
+ }
4081
+ /**
4082
+ * Row access for the device fleet. Every method is a single statement against
4083
+ * `device-manager:devices` — there is no in-memory copy of the fleet here and
4084
+ * no cache: a per-device question is a primary-key lookup, a fleet question is
4085
+ * one indexed scan.
4086
+ */
4087
+ var DeviceRowStore = class {
4088
+ backend;
4089
+ logger;
4090
+ declared = null;
4091
+ constructor(backend, logger) {
4092
+ this.backend = backend;
4093
+ this.logger = logger;
4094
+ }
4095
+ /**
4096
+ * Lazy, idempotent `declareCollection`, memoised on the PROMISE so N
4097
+ * concurrent first-callers issue one declaration rather than N. A rejection
4098
+ * is not latched — the slot is cleared so the next caller retries instead of
4099
+ * inheriting a dead collection forever.
4100
+ */
4101
+ async declare() {
4102
+ const existing = this.declared;
4103
+ if (existing !== null) return existing;
4104
+ const run = (async () => {
4105
+ try {
4106
+ await this.backend.declareCollection({
4107
+ collection: DEVICE_ROWS_COLLECTION,
4108
+ columns: DEVICE_ROWS_COLUMNS,
4109
+ indexes: DEVICE_ROWS_INDEXES
4110
+ });
4111
+ } catch (err) {
4112
+ this.declared = null;
4113
+ throw err;
4114
+ }
4115
+ })();
4116
+ this.declared = run;
4117
+ return run;
4118
+ }
4119
+ /** One device, by numeric id. `null` when the fleet does not know it. */
4120
+ async get(deviceId) {
4121
+ await this.declare();
4122
+ const raw = await this.backend.get({
4123
+ collection: DEVICE_ROWS_COLLECTION,
4124
+ key: String(deviceId)
4125
+ });
4126
+ if (!isPlainObject(raw)) return null;
4127
+ const decoded = decodeDeviceRow(raw);
4128
+ if (decoded === null) {
4129
+ this.logger.warn("device row skipped — identity fields missing", { tags: { deviceId } });
4130
+ return null;
4131
+ }
4132
+ return decoded;
4133
+ }
4134
+ /** Every device, ordered by numeric id. */
4135
+ async listAll() {
4136
+ return this.list({
4137
+ orderBy: {
4138
+ field: "deviceId",
4139
+ direction: "asc"
4140
+ },
4141
+ limit: DEVICE_ROWS_FLEET_LIMIT
4142
+ });
4143
+ }
4144
+ /**
4145
+ * The device an addon knows as `stableId`, or `null`.
4146
+ *
4147
+ * `(addonId, stableId)` is the addon-facing identity — unique by
4148
+ * construction, since `allocateDeviceId` is the only thing that mints a row
4149
+ * and it returns the existing id for a pair it already knows. A second row
4150
+ * for the pair would be a corruption, so this takes the LOWEST id and says
4151
+ * so rather than picking arbitrarily.
4152
+ */
4153
+ async findByStableId(addonId, stableId) {
4154
+ const rows = await this.list({
4155
+ where: {
4156
+ addonId,
4157
+ stableId
4158
+ },
4159
+ orderBy: {
4160
+ field: "deviceId",
4161
+ direction: "asc"
4162
+ },
4163
+ limit: 2
4164
+ });
4165
+ const first = rows[0];
4166
+ if (first === void 0) return null;
4167
+ if (rows.length > 1) this.logger.warn("duplicate device rows for one (addonId, stableId) — using the lowest id", {
4168
+ tags: { deviceId: first.meta.id },
4169
+ meta: {
4170
+ addonId,
4171
+ stableId,
4172
+ ids: rows.map((r) => r.meta.id)
4173
+ }
4174
+ });
4175
+ return first;
4176
+ }
4177
+ /** Every device owned by one addon, ordered by numeric id. */
4178
+ async listByAddon(addonId) {
4179
+ return this.list({
4180
+ where: { addonId },
4181
+ orderBy: {
4182
+ field: "deviceId",
4183
+ direction: "asc"
4184
+ },
4185
+ limit: DEVICE_ROWS_FLEET_LIMIT
4186
+ });
4187
+ }
4188
+ /** Every device an integration owns, ordered by numeric id. */
4189
+ async listByIntegration(integrationId) {
4190
+ return this.list({
4191
+ where: { integrationId },
4192
+ orderBy: {
4193
+ field: "deviceId",
4194
+ direction: "asc"
4195
+ },
4196
+ limit: DEVICE_ROWS_FLEET_LIMIT
4197
+ });
4198
+ }
4199
+ /** Direct children of one device, ordered by numeric id. */
4200
+ async listByParent(parentDeviceId) {
4201
+ return this.list({
4202
+ where: { parentDeviceId },
4203
+ orderBy: {
4204
+ field: "deviceId",
4205
+ direction: "asc"
4206
+ },
4207
+ limit: DEVICE_ROWS_FLEET_LIMIT
4208
+ });
4209
+ }
4210
+ /** How many devices the fleet holds. Used to tell "empty store" from "gone device". */
4211
+ async count() {
4212
+ await this.declare();
4213
+ return this.backend.count({ collection: DEVICE_ROWS_COLLECTION });
4214
+ }
4215
+ async list(filter) {
4216
+ await this.declare();
4217
+ const records = await this.backend.query({
4218
+ collection: DEVICE_ROWS_COLLECTION,
4219
+ filter
4220
+ });
4221
+ const out = [];
4222
+ for (const record of records) {
4223
+ const decoded = decodeDeviceRow(record.data);
4224
+ if (decoded === null) {
4225
+ this.logger.warn("device row skipped — identity fields missing", { meta: { rowId: record.id } });
4226
+ continue;
4227
+ }
4228
+ out.push(decoded);
4229
+ }
4230
+ return out;
4231
+ }
4232
+ /** Insert or replace the whole identity row. */
4233
+ async upsert(meta, extra = {}) {
4234
+ await this.declare();
4235
+ await this.backend.set({
4236
+ collection: DEVICE_ROWS_COLLECTION,
4237
+ key: String(meta.id),
4238
+ value: encodeDeviceRow(meta, extra)
4239
+ });
4240
+ }
4241
+ /**
4242
+ * Write the named columns of an EXISTING row and nothing else.
4243
+ *
4244
+ * An UPDATE, deliberately not an upsert: a partial upsert would try to INSERT
4245
+ * a row carrying only the patched columns, and SQLite rejects that on the
4246
+ * `NOT NULL` identity columns before the primary-key conflict can turn it
4247
+ * into an update. Every caller resolves the row under the write lock and
4248
+ * throws when it is gone, so matching zero rows means a device was removed
4249
+ * between the resolve and the write — the patch is lost, and a lost write
4250
+ * that says nothing reads as a write that happened.
4251
+ */
4252
+ async patch(deviceId, patch) {
4253
+ const columns = encodeDeviceRowPatch(patch);
4254
+ if (Object.keys(columns).length === 0) return;
4255
+ await this.declare();
4256
+ const { updated } = await this.backend.updateWhere({
4257
+ collection: DEVICE_ROWS_COLLECTION,
4258
+ filter: { where: { id: String(deviceId) } },
4259
+ data: columns
4260
+ });
4261
+ if (updated === 0) this.logger.warn("device row patch matched no row — the device was removed under it", {
4262
+ tags: { deviceId },
4263
+ meta: { columns: Object.keys(columns) }
4264
+ });
4265
+ }
4266
+ /**
4267
+ * Insert-or-update the registration columns. See {@link DeviceRegistrationRow}
4268
+ * for why this is a separate, fully-specified statement rather than a patch.
4269
+ */
4270
+ async upsertRegistration(row) {
4271
+ await this.declare();
4272
+ await this.backend.set({
4273
+ collection: DEVICE_ROWS_COLLECTION,
4274
+ key: String(row.deviceId),
4275
+ value: {
4276
+ deviceId: row.deviceId,
4277
+ addonId: row.addonId,
4278
+ stableId: row.stableId,
4279
+ type: row.type,
4280
+ name: row.name,
4281
+ userNamed: row.userNamed,
4282
+ location: row.location,
4283
+ disabled: row.disabled,
4284
+ parentDeviceId: row.parentDeviceId,
4285
+ registered: row.registered,
4286
+ features: [...row.features],
4287
+ exportFingerprint: row.exportFingerprint
4288
+ }
4289
+ });
4290
+ }
4291
+ /** Drop the device's row. Idempotent. */
4292
+ async remove(deviceId) {
4293
+ await this.declare();
4294
+ await this.backend.delete({
4295
+ collection: DEVICE_ROWS_COLLECTION,
4296
+ key: String(deviceId)
4297
+ });
4298
+ }
4299
+ /**
4300
+ * The retirement door for the three blobs this collection replaced.
4301
+ *
4302
+ * The purge is gated on THIS collection being non-empty, and the count has to
4303
+ * be taken after `declare()` — which is why the owning addon runs it and the
4304
+ * settings engine cannot: at the engine's own boot no addon has declared
4305
+ * anything, so every successor would read as unreadable, forever.
4306
+ */
4307
+ retiredRowStore() {
4308
+ return {
4309
+ hasRow: async (spec) => {
4310
+ const raw = await this.backend.get({
4311
+ collection: spec.collection,
4312
+ key: spec.row
4313
+ });
4314
+ return raw !== void 0 && raw !== null;
4315
+ },
4316
+ deleteRow: async (spec) => {
4317
+ await this.backend.delete({
4318
+ collection: spec.collection,
4319
+ key: spec.row
4320
+ });
4321
+ },
4322
+ countRows: async (collection) => {
4323
+ await this.declare();
4324
+ return this.backend.count({ collection });
4325
+ }
4326
+ };
4327
+ }
4328
+ };
4329
+ //#endregion
3992
4330
  //#region src/builtins/device-manager/runtime-state-persist-gate.ts
3993
4331
  /**
3994
4332
  * The subset of `blob` that is allowed on disk: slices whose capability
@@ -4553,12 +4891,21 @@ var DeviceManagerAddon = class extends require_dist.BaseAddon {
4553
4891
  }
4554
4892
  }))).filter((id) => id !== null);
4555
4893
  }
4894
+ /**
4895
+ * Row access for `device-manager:devices`. Built once in `onInitialize`
4896
+ * (which is also where the collection is declared) — every consumer reaches
4897
+ * it through {@link bindingsDeps} or the `ProviderContext`.
4898
+ */
4899
+ deviceRows = null;
4556
4900
  /** Build the dependency context the extracted binding resolvers consume. */
4557
4901
  get bindingsDeps() {
4902
+ const rows = this.deviceRows;
4903
+ if (rows === null) throw new Error("[device-manager] device row store not initialized");
4558
4904
  return {
4559
4905
  ctx: this.ctx,
4560
4906
  capabilityRegistry: this.capabilityRegistry,
4561
- remoteNativeCaps: this.remoteNativeCaps
4907
+ remoteNativeCaps: this.remoteNativeCaps,
4908
+ rows
4562
4909
  };
4563
4910
  }
4564
4911
  async getBindings(input) {
@@ -4614,17 +4961,23 @@ var DeviceManagerAddon = class extends require_dist.BaseAddon {
4614
4961
  if (!ops) throw new Error(`[device-manager] device-ops native provider not found for '${deviceId}'`);
4615
4962
  return ops;
4616
4963
  };
4617
- const metaStore = new DeviceMetaStore(settings, registry);
4964
+ const settingsStoreApi = this.ctx.api?.settingsStore;
4965
+ if (!settingsStoreApi) throw new Error("[device-manager] settings-store API not available — refusing to serve a fleet it cannot persist");
4966
+ const deviceRows = new DeviceRowStore(deviceRowBackendOf(settingsStoreApi), this.ctx.logger.child("rows"));
4967
+ await deviceRows.declare();
4968
+ this.deviceRows = deviceRows;
4969
+ try {
4970
+ await require_retired_settings_keys.purgeRetiredSettingsRows(deviceRows.retiredRowStore(), this.ctx.logger.child("RetiredRows"));
4971
+ } catch (err) {
4972
+ this.ctx.logger.warn("retired-row purge failed", { meta: { error: require_dist.errMsg(err) } });
4973
+ }
4974
+ const metaStore = new DeviceMetaStore(settings, registry, deviceRows);
4618
4975
  this.stateMirrorImpl = new DeviceStateMirror(this.ctx);
4619
4976
  const stateMirror = this.stateMirrorImpl;
4620
- const readMeta = metaStore.readMeta;
4621
4977
  const resolvePersistedById = metaStore.resolvePersistedById;
4622
4978
  const idToAddonId = metaStore.idToAddonId;
4623
- {
4624
- const meta = await readMeta();
4625
- for (const m of Object.values(meta)) idToAddonId.set(m.id, m.addonId);
4626
- }
4627
- const stampIntegrationId$1 = (deviceId, integrationId) => stampIntegrationId(metaStore, settings, this.ctx, deviceId, integrationId);
4979
+ for (const row of await deviceRows.listAll()) idToAddonId.set(row.meta.id, row.meta.addonId);
4980
+ const stampIntegrationId$1 = (deviceId, integrationId) => stampIntegrationId(metaStore, this.ctx, deviceId, integrationId);
4628
4981
  const pctx = {
4629
4982
  host: this.providerHost,
4630
4983
  metaStore,