@camstack/server 1.2.928 → 1.2.930
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -0
- package/package.json +10 -10
- package/system/dist/addon-id-CVg1_r5E.mjs +39 -0
- package/system/dist/addon-id-Di0lNJ89.js +50 -0
- package/system/dist/addon-pages.cap-Df9FQwN1.js +49 -0
- package/system/dist/addon-pages.cap-DksUlE8j.mjs +44 -0
- package/system/dist/addon-settings.cap-3-TIIMq_.mjs +592 -0
- package/system/dist/addon-settings.cap-DAiE0Nb0.js +651 -0
- package/system/dist/addon-utils.mjs +1 -1
- package/system/dist/addon-widgets.cap-C4jxflbF.js +200 -0
- package/system/dist/addon-widgets.cap-D9m48X78.mjs +183 -0
- package/system/dist/base-addon-DD5dIfcZ.js +4624 -0
- package/system/dist/base-addon-Md14i7pe.mjs +4505 -0
- package/system/dist/base-device-2sL1DMm1.js +1103 -0
- package/system/dist/base-device-IuM1AwXZ.mjs +1098 -0
- package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.js +8 -6
- package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.mjs +6 -4
- package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js +8 -6
- package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs +7 -5
- package/system/dist/builtins/alerts/alerts.addon.js +113 -56
- package/system/dist/builtins/alerts/alerts.addon.mjs +60 -3
- package/system/dist/builtins/autotrack/index.js +21 -17
- package/system/dist/builtins/autotrack/index.mjs +5 -1
- package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.js +14 -11
- package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.mjs +8 -5
- package/system/dist/builtins/calendars/calendars.addon.js +8 -6
- package/system/dist/builtins/calendars/calendars.addon.mjs +3 -1
- package/system/dist/builtins/camera-grid/index.js +615 -58
- package/system/dist/builtins/camera-grid/index.mjs +558 -1
- package/system/dist/builtins/composer/composer.addon.js +788 -209
- package/system/dist/builtins/composer/composer.addon.mjs +583 -4
- package/system/dist/builtins/console-logging/index.js +4 -3
- package/system/dist/builtins/console-logging/index.mjs +2 -1
- package/system/dist/builtins/core-blocks/actions-service.d.ts +18 -1
- package/system/dist/builtins/core-blocks/core-blocks.addon.js +8670 -386
- package/system/dist/builtins/core-blocks/core-blocks.addon.mjs +8294 -11
- package/system/dist/builtins/core-blocks/tcp-connect.d.ts +3 -0
- package/system/dist/builtins/core-notifier/core-notifier.addon.js +250 -21
- package/system/dist/builtins/core-notifier/core-notifier.addon.mjs +230 -1
- package/system/dist/builtins/device-history/device-history.addon.js +110 -31
- package/system/dist/builtins/device-history/device-history.addon.mjs +81 -2
- package/system/dist/builtins/device-manager/device-manager.addon.js +12806 -227
- package/system/dist/builtins/device-manager/device-manager.addon.mjs +12583 -5
- package/system/dist/builtins/hub-forwarder/index.js +4 -3
- package/system/dist/builtins/hub-forwarder/index.mjs +2 -1
- package/system/dist/builtins/keychain/index.js +31 -28
- package/system/dist/builtins/keychain/index.mjs +7 -4
- package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.js +15 -12
- package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.mjs +4 -1
- package/system/dist/builtins/local-auth/local-auth.addon.js +140 -39
- package/system/dist/builtins/local-auth/local-auth.addon.mjs +106 -6
- package/system/dist/builtins/local-network/local-network.addon.js +43 -39
- package/system/dist/builtins/local-network/local-network.addon.mjs +7 -3
- package/system/dist/builtins/loki-logging/index.js +23 -17
- package/system/dist/builtins/loki-logging/index.mjs +7 -1
- package/system/dist/builtins/native-metrics/native-metrics.addon.js +156 -15
- package/system/dist/builtins/native-metrics/native-metrics.addon.mjs +151 -10
- package/system/dist/builtins/platform-probe/index.js +25 -23
- package/system/dist/builtins/platform-probe/index.mjs +12 -10
- package/system/dist/builtins/record-entries/index.js +9 -7
- package/system/dist/builtins/record-entries/index.mjs +3 -1
- package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.js +4 -4
- package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.mjs +1 -1
- package/system/dist/builtins/snapshot/index.js +97 -44
- package/system/dist/builtins/snapshot/index.mjs +54 -1
- package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.js +5 -4
- package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.mjs +21 -20
- package/system/dist/builtins/sqlite-storage/index.js +1 -1
- package/system/dist/builtins/sqlite-storage/index.mjs +1 -1
- package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.js +87 -61
- package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs +29 -3
- package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.js +81 -72
- package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.mjs +10 -1
- package/system/dist/builtins/system-config/system-config.addon.js +17 -14
- package/system/dist/builtins/system-config/system-config.addon.mjs +118 -115
- package/system/dist/builtins/winston-logging/index.js +7 -5
- package/system/dist/builtins/winston-logging/index.mjs +3 -1
- package/system/dist/calendars.cap-CaFlShS9.js +155 -0
- package/system/dist/calendars.cap-_C4eD4fi.mjs +138 -0
- package/system/dist/camstack-error-DJ-TUAi1.js +23 -0
- package/system/dist/camstack-error-viZYfcj9.mjs +18 -0
- package/system/dist/cap-call-context-Bd76CbOW.js +95 -0
- package/system/dist/cap-call-context-DNwdgGSQ.mjs +78 -0
- package/system/dist/capability-definition-C2rJdVeX.mjs +177 -0
- package/system/dist/capability-definition-HCmTem8c.js +242 -0
- package/system/dist/{capture-engine-BcuwOSXv.js → capture-engine-DZ0LIUqA.js} +5 -4
- package/system/dist/{capture-engine-Bz7eXFjT.mjs → capture-engine-DiwbjoWp.mjs} +2 -1
- package/system/dist/command-origin-claim-Cief660O.js +35 -0
- package/system/dist/command-origin-claim-D1Wy7Qld.mjs +24 -0
- package/system/dist/composition-sources-BEUWn2s_.mjs +391 -0
- package/system/dist/composition-sources-acfR4hDq.js +408 -0
- package/system/dist/{constants-D2etJ02O.js → constants-Ba3FTIHl.js} +1 -1
- package/system/dist/constants-C860Y6U4.js +26 -0
- package/system/dist/{constants-BcUTQd1M.mjs → constants-DB4piTD5.mjs} +1 -1
- package/system/dist/constants-DCLpoF4L.mjs +21 -0
- package/system/dist/coral-accelerators-7o8hqvcN.js +564 -0
- package/system/dist/coral-accelerators-BKcXP59c.mjs +521 -0
- package/system/dist/core-blocks.cap-BMeMCBrx.js +18733 -0
- package/system/dist/core-blocks.cap-BRPsLAij.mjs +18008 -0
- package/system/dist/{custom-action-registry-N7flBDwT.mjs → custom-action-registry-B9zFBNVa.mjs} +37 -37
- package/system/dist/custom-actions-BFUSalC9.mjs +25 -0
- package/system/dist/custom-actions-D92NRi2c.js +36 -0
- package/system/dist/database-snapshot.cap-DF38e-0P.js +162 -0
- package/system/dist/database-snapshot.cap-dhrc9xnY.mjs +133 -0
- package/system/dist/declared-device-BWphj9WE.js +303 -0
- package/system/dist/declared-device-CKERA1Hi.mjs +286 -0
- package/system/dist/{device-ca-ExMN3xW3.mjs → device-ca-BLM6fccc.mjs} +2 -1
- package/system/dist/{device-ca-CU8zh9Pi.js → device-ca-C5kJE6mL.js} +7 -6
- package/system/dist/device-certificate-Cddm4Idn.mjs +91 -0
- package/system/dist/device-certificate-CguVACQO.js +162 -0
- package/system/dist/device-identifiers-BQg9EQi1.js +600 -0
- package/system/dist/device-identifiers-iSuQCKmK.mjs +529 -0
- package/system/dist/device-kind-BJ2pfsjw.mjs +78 -0
- package/system/dist/device-kind-CsSiv_YF.js +101 -0
- package/system/dist/device-manager.cap-2abwVLCM.js +2874 -0
- package/system/dist/device-manager.cap-CFZSPfUh.mjs +2749 -0
- package/system/dist/device-provider.cap-3Uvk6f5-.mjs +331 -0
- package/system/dist/device-provider.cap-D7TV2kVH.js +366 -0
- package/system/dist/{device-row-store-CeW_GWh9.mjs → device-row-store-YF3jtmkk.mjs} +4 -1
- package/system/dist/{device-row-store-BMIR-n3m.js → device-row-store-doTfMOqn.js} +12 -9
- package/system/dist/device-transitions.cap-B5w5PYU_.js +860 -0
- package/system/dist/device-transitions.cap-DojcwEuX.mjs +819 -0
- package/system/dist/device-type-CbQsnFdC.js +477 -0
- package/system/dist/device-type-DgEvK3ch.mjs +454 -0
- package/system/dist/entry-kind-D9MuVJCK.mjs +44 -0
- package/system/dist/entry-kind-cq90c--V.js +55 -0
- package/system/dist/error.cap-CSM_SRfR.mjs +3423 -0
- package/system/dist/error.cap-DBhgPeWK.js +3848 -0
- package/system/dist/file-host-worker.js +1 -1
- package/system/dist/file-host-worker.mjs +1 -1
- package/system/dist/history-catalog-BKRarIL_.js +831 -0
- package/system/dist/history-catalog-BwTeQ4Mr.mjs +802 -0
- package/system/dist/{hub-identity-Csxx2Q8k.js → hub-identity-BMdR3Mw9.js} +2 -2
- package/system/dist/{hub-identity-CYC1820R.mjs → hub-identity-DjMN9Ac2.mjs} +10 -10
- package/system/dist/{hub-mdns-ciao-By5577HM.js → hub-mdns-ciao--0v1TKME.js} +5 -5
- package/system/dist/{hub-mdns-ciao-CCDxM5qz.mjs → hub-mdns-ciao-DBrtHOcc.mjs} +2 -2
- package/system/dist/index.js +763 -151
- package/system/dist/index.mjs +832 -220
- package/system/dist/integration-instances.cap-Cl9O-k4h.mjs +538 -0
- package/system/dist/integration-instances.cap-dJIxg2_s.js +549 -0
- package/system/dist/keychain-admin.cap-Db_oFX4H.js +425 -0
- package/system/dist/keychain-admin.cap-GtM7gVGG.mjs +396 -0
- package/system/dist/l10n-Bu6aUvSY.mjs +10 -0
- package/system/dist/l10n-CGMvp7NF.js +15 -0
- package/system/dist/labels-DX5S8deC.js +81 -0
- package/system/dist/labels-DsBcU7md.mjs +64 -0
- package/system/dist/{legacy-integration-rows-door-CVwOo5aq.js → legacy-integration-rows-door-B1nzxxr5.js} +2 -2
- package/system/dist/{legacy-integration-rows-door-D9tQOUzh.mjs → legacy-integration-rows-door-nTvo_6jQ.mjs} +1 -1
- package/system/dist/log-destination.cap-CxZzAVaR.mjs +143 -0
- package/system/dist/log-destination.cap-DELPJkZ0.js +148 -0
- package/system/dist/low-power-sleep.cap-7lfVU41N.js +103 -0
- package/system/dist/low-power-sleep.cap-tGPmaZ_V.mjs +92 -0
- package/system/dist/mask-shape-Ci8Co9w0.mjs +57 -0
- package/system/dist/mask-shape-CmPA2fst.js +92 -0
- package/system/dist/metrics-provider.cap-BNmcHDkQ.mjs +405 -0
- package/system/dist/metrics-provider.cap-BcmQUt6l.js +410 -0
- package/system/dist/migration-BMjgkyG2.js +380 -0
- package/system/dist/migration-DRJAtdy7.mjs +321 -0
- package/system/dist/network-access.cap-B5TWLDCC.js +1099 -0
- package/system/dist/network-access.cap-BJnGbE6n.mjs +1004 -0
- package/system/dist/notification-rules.cap-BDh0LDhV.js +3428 -0
- package/system/dist/notification-rules.cap-DUmiMBQB.mjs +3357 -0
- package/system/dist/notification-targets-CRH-9Dy5.js +509 -0
- package/system/dist/notification-targets-DaNE-pIt.mjs +486 -0
- package/system/dist/ops-log-CB4pIdqi.mjs +64 -0
- package/system/dist/ops-log-pxt9176Z.js +81 -0
- package/system/dist/pinned-binary-BOhOSNff.js +28 -0
- package/system/dist/pinned-binary-CrIRAi4G.mjs +23 -0
- package/system/dist/platform-probe.cap-1WrMhWHx.js +250 -0
- package/system/dist/platform-probe.cap-BFeqFLtQ.mjs +233 -0
- package/system/dist/prefix-walk-BkMxoXpL.js +843 -0
- package/system/dist/prefix-walk-ifwg_ukx.mjs +790 -0
- package/system/dist/ptz-autotrack.cap-BW7w0zHD.js +229 -0
- package/system/dist/ptz-autotrack.cap-DT2GypXw.mjs +224 -0
- package/system/dist/quantity-D3g5SxsZ.mjs +114 -0
- package/system/dist/quantity-lY1KiTSZ.js +143 -0
- package/system/dist/raw-secret-migration-DxuBFtvi.js +50 -0
- package/system/dist/raw-secret-migration-iv88mLoc.mjs +39 -0
- package/system/dist/record-entries.cap-sMUhTvTU.mjs +75 -0
- package/system/dist/record-entries.cap-ti1C046R.js +80 -0
- package/system/dist/record-kind-DoBfYHCs.js +203 -0
- package/system/dist/record-kind-ub6NXqfh.mjs +162 -0
- package/system/dist/recording-archive.cap-7OrIn9e5.mjs +1299 -0
- package/system/dist/recording-archive.cap-D7bo-QSM.js +1328 -0
- package/system/dist/records.cap-ClcWV64i.js +329 -0
- package/system/dist/records.cap-CwLT2ByG.mjs +294 -0
- package/system/dist/relocate-CdVQAk-w.js +804 -0
- package/system/dist/relocate-CoZZTui1.mjs +661 -0
- package/system/dist/rename-composition-block-BJsL58Ih.js +34798 -0
- package/system/dist/rename-composition-block-OAtErZgq.mjs +33631 -0
- package/system/dist/{restore-archive-BJfyu0sG.mjs → restore-archive-CjAyKpgX.mjs} +96 -94
- package/system/dist/{restore-archive-CIFvqOze.js → restore-archive-CkTkv3Ss.js} +6 -4
- package/system/dist/scoped-settings-CylSSq_8.js +955 -0
- package/system/dist/scoped-settings-DVWUIP7Z.mjs +650 -0
- package/system/dist/server-name-BIhLuHvX.mjs +35 -0
- package/system/dist/server-name-OALNvpqC.js +52 -0
- package/system/dist/settings-store.cap-Ci4F2zul.mjs +569 -0
- package/system/dist/settings-store.cap-wlJhCspr.js +640 -0
- package/system/dist/snapshot.cap-3suPdBHV.js +250 -0
- package/system/dist/snapshot.cap-Bs8Oyaqh.mjs +245 -0
- package/system/dist/source-info-DGB7SdB_.mjs +190 -0
- package/system/dist/source-info-DtWf4k2j.js +225 -0
- package/system/dist/storage-admin.cap-BSv1NjKJ.mjs +883 -0
- package/system/dist/storage-admin.cap-he0OqvVM.js +906 -0
- package/system/dist/storage-location-CBT8GCD6.mjs +163 -0
- package/system/dist/storage-location-CTweDMZf.js +198 -0
- package/system/dist/storage-location-mode-B21UVRRX.mjs +167 -0
- package/system/dist/storage-location-mode-CS4sMzo-.js +232 -0
- package/system/dist/storage-migration.cap-CyyATY_p.js +330 -0
- package/system/dist/storage-migration.cap-D7QqGobp.mjs +313 -0
- package/system/dist/storage-occupancy.cap-2rmnS58Z.js +622 -0
- package/system/dist/storage-occupancy.cap-CqBztTl9.mjs +611 -0
- package/system/dist/storage-provider.cap-Bw0CfxVc.js +213 -0
- package/system/dist/storage-provider.cap-CMeck2w4.mjs +202 -0
- package/system/dist/stream-catalog.cap-Bp7SkgIf.mjs +6560 -0
- package/system/dist/stream-catalog.cap-D3uwePiA.js +6763 -0
- package/system/dist/streaming-shared-B8cXatuU.mjs +431 -0
- package/system/dist/streaming-shared-DQwFZOSi.js +526 -0
- package/system/dist/system-reasons-Be_k1W8g.js +25 -0
- package/system/dist/system-reasons-CYj4qwyS.mjs +20 -0
- package/system/dist/tag-BxLazvVb.js +2138 -0
- package/system/dist/tag-uZBAq6ox.mjs +2073 -0
- package/system/dist/user-management.cap-B9QDu8NE.js +825 -0
- package/system/dist/user-management.cap-DBIi77sB.mjs +766 -0
- package/system/dist/vector-store.cap-DnyfrYDn.js +330 -0
- package/system/dist/vector-store.cap-h2GHWQ1t.mjs +319 -0
- package/system/dist/{wal-maintenance-CTrCPzds.mjs → wal-maintenance-BG01rOn9.mjs} +0 -0
- package/system/dist/{wal-maintenance-dq7T3quB.js → wal-maintenance-DyrebYKF.js} +0 -0
- package/system/dist/zod-secret-DS7mj1bk.js +78 -0
- package/system/dist/zod-secret-zY4nM61M.mjs +73 -0
- package/system/package.json +1 -1
- package/system/dist/composition-sources-BI614LJx.mjs +0 -141
- package/system/dist/composition-sources-v_kkb8A9.js +0 -152
- package/system/dist/coral-accelerators-BSVsBVzt.js +0 -250
- package/system/dist/coral-accelerators-BW3OcrLD.mjs +0 -231
- package/system/dist/dist-BCHMSqzc.mjs +0 -143467
- package/system/dist/dist-BZfvhfS1.js +0 -146970
- package/system/dist/prefix-walk-DAOBSyH1.mjs +0 -88
- package/system/dist/prefix-walk-Dv6MLZlM.js +0 -99
- package/system/dist/rename-composition-block-C9HuBrKS.js +0 -112
- package/system/dist/rename-composition-block-DtaYmYAR.mjs +0 -101
|
@@ -0,0 +1,4505 @@
|
|
|
1
|
+
import { B as SECRET_CLEAR, H as isSecretClear, K as makeSecretMarker, N as RecordSecretUnavailableError, S as globalSecretScope, U as isSecretFieldView, V as classifySecretWrite, W as isSecretMarker, X as isKeychainStoredField, Z as errMsg, a as mapSecretLeaves, o as recordSecretRef, q as toSecretFieldView, t as SCOPED_SETTINGS_SCOPES, w as parseSecretRef, y as arrayItemFieldPath } from "./scoped-settings-DVWUIP7Z.mjs";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
//#region ../types/dist/esm/addon/migrations-blocked-error.mjs
|
|
4
|
+
/**
|
|
5
|
+
* An addon whose own migrations did not apply refuses to initialise (D987). The error is typed
|
|
6
|
+
* so a runner hosting several addons can tell "this addon is blocked" from a crash and keep its
|
|
7
|
+
* co-located siblings running. Recognised by NAME and shape, never `instanceof`: a forked addon
|
|
8
|
+
* bundles its own copy of this module, so the class the runner sees is not the one that threw.
|
|
9
|
+
*/
|
|
10
|
+
var MIGRATIONS_BLOCKED_ERROR_NAME = "AddonMigrationsBlockedError";
|
|
11
|
+
var AddonMigrationsBlockedError = class extends Error {
|
|
12
|
+
/** The ledger ids that did not apply and block the owner. */
|
|
13
|
+
migrationIds;
|
|
14
|
+
constructor(migrationIds) {
|
|
15
|
+
super(`migration(s) ${migrationIds.join(", ")} did not apply and block this addon — fix or retry them (migrations.retry), then restart it`);
|
|
16
|
+
this.name = MIGRATIONS_BLOCKED_ERROR_NAME;
|
|
17
|
+
this.migrationIds = migrationIds;
|
|
18
|
+
}
|
|
19
|
+
};
|
|
20
|
+
//#endregion
|
|
21
|
+
//#region ../types/dist/esm/enums/event-category.mjs
|
|
22
|
+
var EventCategory = /* @__PURE__ */ function(EventCategory) {
|
|
23
|
+
EventCategory["SystemBoot"] = "system.boot";
|
|
24
|
+
EventCategory["SystemAddonsReady"] = "system.addons-ready";
|
|
25
|
+
EventCategory["SystemRestarting"] = "system.restarting";
|
|
26
|
+
/**
|
|
27
|
+
* Fired exactly once after the hub finishes booting following a
|
|
28
|
+
* restart that was triggered by `RestartCoordinator` (today: framework
|
|
29
|
+
* live-update). Payload is the marker that was on disk at boot
|
|
30
|
+
* (`PendingRestartMarkerPayload`); admin UI listens for it to display a
|
|
31
|
+
* success toast describing what changed.
|
|
32
|
+
*
|
|
33
|
+
* Spec: docs/superpowers/specs/2026-05-14-framework-live-update-design.md
|
|
34
|
+
*/
|
|
35
|
+
EventCategory["SystemRestartCompleted"] = "system.restart-completed";
|
|
36
|
+
/**
|
|
37
|
+
* The hub reissued its own TLS certificate at boot (`ensureTlsCert`).
|
|
38
|
+
* Emitted only when the material on disk actually changed, so an
|
|
39
|
+
* operator who trusted the old certificate by hand is told rather than
|
|
40
|
+
* discovering it as a browser error. Payload `TlsCertChangedPayload`.
|
|
41
|
+
*
|
|
42
|
+
* Rule: docs/decisions/adr-0227-*.md
|
|
43
|
+
*/
|
|
44
|
+
EventCategory["SystemTlsCertChanged"] = "system.tls-cert-changed";
|
|
45
|
+
/**
|
|
46
|
+
* A newer addon or server-root package version was found by the
|
|
47
|
+
* authoritative registry check. Emitted once when any observed
|
|
48
|
+
* `latestVersion` changes (or a package/node first appears behind);
|
|
49
|
+
* the payload carries the full currently-available list. Repeated
|
|
50
|
+
* polling of the same latests is silent.
|
|
51
|
+
*/
|
|
52
|
+
EventCategory["UpdateAvailable"] = "update.available";
|
|
53
|
+
/**
|
|
54
|
+
* Readiness transition for a capability provider. Every producer emits
|
|
55
|
+
* this event on `onInitialize` completion, `onDestroy`, and
|
|
56
|
+
* `$node.reconnect`; every consumer that needs to gate on a cross-process
|
|
57
|
+
* cap subscribes via the kernel's readiness module (`awaitReady` /
|
|
58
|
+
* `onReadyState`) instead of polling. Payload is
|
|
59
|
+
* `SystemReadyStatePayload` — see event-bus.ts.
|
|
60
|
+
*/
|
|
61
|
+
EventCategory["SystemReadyState"] = "system.ready-state";
|
|
62
|
+
EventCategory["AddonStarted"] = "addon.started";
|
|
63
|
+
EventCategory["AddonStopped"] = "addon.stopped";
|
|
64
|
+
EventCategory["AddonRestarted"] = "addon.restarted";
|
|
65
|
+
EventCategory["AddonUpdated"] = "addon.updated";
|
|
66
|
+
EventCategory["AddonInstalled"] = "addon.installed";
|
|
67
|
+
EventCategory["AddonUninstalled"] = "addon.uninstalled";
|
|
68
|
+
EventCategory["AddonCrashed"] = "addon.crashed";
|
|
69
|
+
/**
|
|
70
|
+
* A RUNNER the D6 crash circuit-breaker gave up on — terminal.
|
|
71
|
+
*
|
|
72
|
+
* `AddonCrashed` is the routine, self-healing fact ("it crashed; it is being
|
|
73
|
+
* respawned"); this is the one that never resolves itself. Emitted exactly
|
|
74
|
+
* once per trip, by `process-service.ts`, carrying the node, the runner, the
|
|
75
|
+
* addons it hosted and the crash count that tripped the breaker.
|
|
76
|
+
*
|
|
77
|
+
* It exists because a runner marked terminally `failed` used to be SILENT:
|
|
78
|
+
* on 2026-08-18 the `recorder` runner died of three unhandled ffmpeg spawn
|
|
79
|
+
* errors, the breaker stopped respawning it (correctly), `/health` kept
|
|
80
|
+
* returning 200, and fleet-wide recording was gone for 3h15 before the
|
|
81
|
+
* operator's phone told him. The Notification Center's system-event intake
|
|
82
|
+
* consumes this category and maps it to the `addon-crash-loop` kind.
|
|
83
|
+
*/
|
|
84
|
+
EventCategory["AddonRunnerFailed"] = "addon.runner-failed";
|
|
85
|
+
/**
|
|
86
|
+
* A runner whose addon refused to start with a typed reason (D877) - parked
|
|
87
|
+
* in `refused`, never counted by the crash breaker, retried on operator
|
|
88
|
+
* action. One event per refusal.
|
|
89
|
+
*/
|
|
90
|
+
EventCategory["AddonRunnerRefused"] = "addon.runner-refused";
|
|
91
|
+
/**
|
|
92
|
+
* A runner settled on a state (D877): `running` (READY), `crashed`, `failed` or
|
|
93
|
+
* `refused`. In-process telemetry for the boot check (re-evaluate while any
|
|
94
|
+
* runner is still pending) and the alert centre (close a recovered runner).
|
|
95
|
+
*/
|
|
96
|
+
EventCategory["ProcessStateChanged"] = "process.state-changed";
|
|
97
|
+
/**
|
|
98
|
+
* The node's one-shot runner boot check (D877): planned runners against the
|
|
99
|
+
* process service, `degraded` when any is failed, refused or missing. The
|
|
100
|
+
* alert centre turns it into one critical alert.
|
|
101
|
+
*/
|
|
102
|
+
EventCategory["SystemRunnerCheck"] = "system.runner-check";
|
|
103
|
+
/**
|
|
104
|
+
* An alert EPISODE opened or closed, emitted by the alert centre for alerts
|
|
105
|
+
* of severity `critical` or `error` (`AlertEpisodePayload`). The alert
|
|
106
|
+
* centre sends no notification of its own: Notification Center turns this
|
|
107
|
+
* into the `alert-critical` / `alert-error` / `alert-critical-resolved`
|
|
108
|
+
* system-event kinds, and reconciles from the alerts store because a bus
|
|
109
|
+
* event may be dropped (D8, D11).
|
|
110
|
+
*/
|
|
111
|
+
EventCategory["AlertEpisode"] = "alert.episode";
|
|
112
|
+
EventCategory["AddonError"] = "addon.error";
|
|
113
|
+
EventCategory["AddonPageReady"] = "addon.page-ready";
|
|
114
|
+
EventCategory["AddonWidgetReady"] = "addon.widget-ready";
|
|
115
|
+
/**
|
|
116
|
+
* Addon failed to load (import or initialize). Emitted by the kernel's
|
|
117
|
+
* AddonHealthMonitor only AFTER the boot grace period ends — failures
|
|
118
|
+
* during the first 5 minutes are silently retried without alerting
|
|
119
|
+
* (slow-starting addons must have time to come up). Post-grace, this
|
|
120
|
+
* event is emitted exactly once per failure-streak; AlertCenter
|
|
121
|
+
* consumes it to create a persistent operator-visible alert.
|
|
122
|
+
*
|
|
123
|
+
* Payload: `{ packageName, addonId?, error: { message, stack }, retryCount, nextRetryAt }`.
|
|
124
|
+
*/
|
|
125
|
+
EventCategory["AddonLoadFailed"] = "addon.load-failed";
|
|
126
|
+
/**
|
|
127
|
+
* A keychain value was stored or removed (D787). Carries the ref, its
|
|
128
|
+
* owner and the new version — NEVER the value. A process holding the ref
|
|
129
|
+
* drops its cached copy and the owning `BaseAddon` re-resolves its config.
|
|
130
|
+
* Telemetry (D8): a process that misses it still revalidates by version.
|
|
131
|
+
*/
|
|
132
|
+
EventCategory["KeychainChanged"] = "keychain.changed";
|
|
133
|
+
/**
|
|
134
|
+
* Addon recovered from a previous failure. Emitted when an addon
|
|
135
|
+
* transitions from `failed` back to `healthy` (typically via the
|
|
136
|
+
* monitor's auto-retry loop, or after manual `addons.retryLoad`).
|
|
137
|
+
* AlertCenter dismisses the corresponding `AddonLoadFailed` alert
|
|
138
|
+
* on this event.
|
|
139
|
+
*/
|
|
140
|
+
EventCategory["AddonLoadRecovered"] = "addon.load-recovered";
|
|
141
|
+
/**
|
|
142
|
+
* An addon is RUNNING although its installed package is below what the
|
|
143
|
+
* running server requires (`camstack.requires.addons` of the server, or the
|
|
144
|
+
* addon's own `requires.server`). Raised once per streak by the unsupported-
|
|
145
|
+
* addon tracker, on the hub and on agents; AlertCenter turns it into one
|
|
146
|
+
* operator alert per node and package. The addon is never held back for it.
|
|
147
|
+
*
|
|
148
|
+
* Payload: `{ packageName, addonId, nodeId, installedVersion, requiredMinimum, serverVersion, unmet }`.
|
|
149
|
+
*/
|
|
150
|
+
EventCategory["AddonUnsupportedVersion"] = "addon.unsupported-version";
|
|
151
|
+
/**
|
|
152
|
+
* The package of an {@link AddonUnsupportedVersion} alert reached a supported
|
|
153
|
+
* version, or is no longer installed on the node. AlertCenter dismisses the matching alert.
|
|
154
|
+
*
|
|
155
|
+
* Payload: `{ packageName, addonId, nodeId }`.
|
|
156
|
+
*/
|
|
157
|
+
EventCategory["AddonUnsupportedResolved"] = "addon.unsupported-resolved";
|
|
158
|
+
/**
|
|
159
|
+
* Monitor scheduled the next retry for a failed addon. Transient —
|
|
160
|
+
* surfaced to the UI for live-updating the "next retry in Ns"
|
|
161
|
+
* countdown on the Addons page row, NOT persisted as an alert.
|
|
162
|
+
*/
|
|
163
|
+
EventCategory["AddonRetryScheduled"] = "addon.retry-scheduled";
|
|
164
|
+
/**
|
|
165
|
+
* A liveness invariant of this node is false — it has no devices, every
|
|
166
|
+
* camera is offline, or a camera that was recording has stopped producing
|
|
167
|
+
* segments. Emitted by the `liveness-monitor` builtin, once per fault (the
|
|
168
|
+
* `findingId` is stable across ticks), only after its boot grace period.
|
|
169
|
+
* AlertCenter raises a persistent operator-visible alert.
|
|
170
|
+
*
|
|
171
|
+
* It exists because on 2026-08-03 the hub ran four hours with zero devices
|
|
172
|
+
* and zero recordings while every surface stayed quiet.
|
|
173
|
+
*
|
|
174
|
+
* Payload: `{ findingId, severity, title, message, deviceId? }`.
|
|
175
|
+
*/
|
|
176
|
+
EventCategory["SystemLivenessFailed"] = "system.liveness-failed";
|
|
177
|
+
/**
|
|
178
|
+
* A previously reported liveness fault is true again. AlertCenter dismisses
|
|
179
|
+
* the matching `SystemLivenessFailed` alert.
|
|
180
|
+
*
|
|
181
|
+
* Payload: `{ findingId }`.
|
|
182
|
+
*/
|
|
183
|
+
EventCategory["SystemLivenessRecovered"] = "system.liveness-recovered";
|
|
184
|
+
/**
|
|
185
|
+
* Monitor is attempting to reload a failed addon NOW. UI uses this
|
|
186
|
+
* to show a spinner during the retry attempt. Same transient nature
|
|
187
|
+
* as AddonRetryScheduled.
|
|
188
|
+
*/
|
|
189
|
+
EventCategory["AddonRetryAttempting"] = "addon.retry-attempting";
|
|
190
|
+
EventCategory["DeviceRegistered"] = "device.registered";
|
|
191
|
+
EventCategory["DeviceUnregistered"] = "device.unregistered";
|
|
192
|
+
EventCategory["DeviceEnabled"] = "device.enabled";
|
|
193
|
+
EventCategory["DeviceDisabled"] = "device.disabled";
|
|
194
|
+
EventCategory["DeviceSettingsUpdated"] = "device.settings-updated";
|
|
195
|
+
/**
|
|
196
|
+
* Emitted when the set of native capability providers bound to a device
|
|
197
|
+
* changes — e.g. an addon registers a new native cap via
|
|
198
|
+
* `DeviceContext.registerNativeCap`, or all native bindings for a device
|
|
199
|
+
* are cleared on removal. Hub consumers re-resolve device-proxy routes
|
|
200
|
+
* when this fires.
|
|
201
|
+
*/
|
|
202
|
+
EventCategory["DeviceBindingsChanged"] = "device.bindings-changed";
|
|
203
|
+
/**
|
|
204
|
+
* Emitted when the operator-organisational meta surface changes
|
|
205
|
+
* (`name` / `location` / `disabled`). Payload: `{deviceId, field,
|
|
206
|
+
* value}`. Live consumers (UI device list, alert center) react
|
|
207
|
+
* without polling. Distinct from `DeviceSettingsUpdated` which
|
|
208
|
+
* fires on hardware-config changes (host/port/credentials/etc).
|
|
209
|
+
*/
|
|
210
|
+
EventCategory["DeviceMetaChanged"] = "device.meta-changed";
|
|
211
|
+
/**
|
|
212
|
+
* Emitted by `BaseDevice.updateSourceInfo()` after a successful patch
|
|
213
|
+
* to the device's upstream-system identity / rendering envelope. The
|
|
214
|
+
* full new SourceInfo travels in the payload so cross-process listeners
|
|
215
|
+
* (UI, export adapters) don't need to re-read the meta blob.
|
|
216
|
+
*
|
|
217
|
+
* Payload: `{deviceId, sourceInfo}`.
|
|
218
|
+
*
|
|
219
|
+
* Distinct from `DeviceMetaChanged` which covers the operator-edited
|
|
220
|
+
* surface (`name` / `location` / `disabled`). The two share the
|
|
221
|
+
* persistence layer (both ride on `device-manager.setMetadata` for
|
|
222
|
+
* SourceInfo, or `setName`/`setLocation`/`setDisabled` for the meta
|
|
223
|
+
* fields) but consumers care about different subsets.
|
|
224
|
+
*/
|
|
225
|
+
EventCategory["DeviceSourceInfoChanged"] = "device.source-info-changed";
|
|
226
|
+
/**
|
|
227
|
+
* Emitted by DeviceStreamWiringService after a successful
|
|
228
|
+
* `stream-broker.registerDeviceStreams` call. Payload includes
|
|
229
|
+
* deviceId — consumers look up the full registered device info via
|
|
230
|
+
* `brokerManager.getRegisteredDevice(deviceId)`.
|
|
231
|
+
*
|
|
232
|
+
* Replaces the legacy `StreamRouterService.onDeviceRegistered` callback.
|
|
233
|
+
*/
|
|
234
|
+
EventCategory["DeviceStreamsRegistered"] = "device.streams-registered";
|
|
235
|
+
/**
|
|
236
|
+
* Device-level "fully provisioned" signal — the EXPORT trigger. Emitted once
|
|
237
|
+
* a device's persisted export-relevant shape (its `DeviceFeature` set) is
|
|
238
|
+
* established or changes, carrying `{deviceId, fingerprint, generation}`.
|
|
239
|
+
* Export adapters (Alexa / HAP) react to THIS instead of the chatty per-cap
|
|
240
|
+
* `DeviceBindingsChanged`, turning a boot's incomplete→complete trickle into
|
|
241
|
+
* one clean delta. `fingerprint` is `canonicalDeviceFingerprint(shape)`.
|
|
242
|
+
*
|
|
243
|
+
* Spec: docs/superpowers/specs/2026-06-01-alexa-hap-export-reconciler-design.md
|
|
244
|
+
*/
|
|
245
|
+
EventCategory["DeviceProvisioned"] = "device.provisioned";
|
|
246
|
+
/**
|
|
247
|
+
* Fires once when a device's initial feature-probe completes successfully
|
|
248
|
+
* (lastProbedAt 0→>0); exported shape is now stable. Telemetry (may be
|
|
249
|
+
* dropped) — consumers MUST also gate on the device record's `probed` flag.
|
|
250
|
+
*/
|
|
251
|
+
EventCategory["DeviceReady"] = "device.ready";
|
|
252
|
+
/**
|
|
253
|
+
* An identity link (D1063) became `linked` — auto on strong evidence or
|
|
254
|
+
* confirmed by the operator — or a confirmed link's evidence came back. Telemetry: the `identity-links` record is the
|
|
255
|
+
* truth, and core-blocks reconciles its contributions from it as well.
|
|
256
|
+
* Payload: `IdentityLinkEventPayload`.
|
|
257
|
+
*/
|
|
258
|
+
EventCategory["IdentityLinkCreated"] = "identity-link.created";
|
|
259
|
+
/**
|
|
260
|
+
* A `linked` identity link stopped acting: its evidence is gone (an auto link
|
|
261
|
+
* is deleted; an operator-confirmed one stays `linked`, flagged
|
|
262
|
+
* `evidenceGone`, and no longer acts), a side was removed, or the operator
|
|
263
|
+
* unlinked it. Payload: `IdentityLinkEventPayload` with `reason`.
|
|
264
|
+
*/
|
|
265
|
+
EventCategory["IdentityLinkLost"] = "identity-link.lost";
|
|
266
|
+
EventCategory["IntegrationEnabled"] = "integration.enabled";
|
|
267
|
+
EventCategory["IntegrationDisabled"] = "integration.disabled";
|
|
268
|
+
EventCategory["IntegrationDeleted"] = "integration.deleted";
|
|
269
|
+
/** Emitted when a broker connection's status flips (connected /
|
|
270
|
+
* disconnected / error). Carries `{ brokerId, status, error? }`. */
|
|
271
|
+
EventCategory["BrokerStatusChanged"] = "broker.status-changed";
|
|
272
|
+
/** Emitted for every subscription-matched message routed by a
|
|
273
|
+
* broker provider. Carries `{ brokerId, subscriptionId, key, payload }`.
|
|
274
|
+
* Consumers filter by `brokerId` + `subscriptionId` in the handler. */
|
|
275
|
+
EventCategory["BrokerMessage"] = "broker.message";
|
|
276
|
+
EventCategory["ProviderStarted"] = "provider.started";
|
|
277
|
+
EventCategory["ProviderStopped"] = "provider.stopped";
|
|
278
|
+
EventCategory["ProcessCrashed"] = "process.crashed";
|
|
279
|
+
EventCategory["ProcessRestartScheduled"] = "process.restart_scheduled";
|
|
280
|
+
EventCategory["ProcessRestarted"] = "process.restarted";
|
|
281
|
+
/**
|
|
282
|
+
* The SET of storage locations changed — one was created, edited, enabled,
|
|
283
|
+
* disabled or deleted through the location instances or the forced-delete action.
|
|
284
|
+
*
|
|
285
|
+
* Telemetry, not a transaction (D8/D11): every consumer that re-resolves on
|
|
286
|
+
* it must also converge on its own periodic path, because a dropped event
|
|
287
|
+
* must not leave a node writing to yesterday's disk set forever. It exists
|
|
288
|
+
* because there was NO signal at all — an operator who added a second
|
|
289
|
+
* recordings disk in the admin UI got nothing, and the recorder kept its
|
|
290
|
+
* resolved locations until something else happened to re-resolve them
|
|
291
|
+
* (D387). Payload `StorageLocationsChangedPayload`.
|
|
292
|
+
*/
|
|
293
|
+
EventCategory["StorageLocationsChanged"] = "storage.locations-changed";
|
|
294
|
+
EventCategory["RecordingStarted"] = "recording.started";
|
|
295
|
+
EventCategory["RecordingStopped"] = "recording.stopped";
|
|
296
|
+
EventCategory["RecordingError"] = "recording.error";
|
|
297
|
+
EventCategory["RecordingHealthDegraded"] = "recording.health.degraded";
|
|
298
|
+
/** Recording enabled but no segment finalized for the NC stall window. */
|
|
299
|
+
EventCategory["RecordingHealthStalled"] = "recording.health.stalled";
|
|
300
|
+
/** Recovery from {@link RecordingHealthStalled}. */
|
|
301
|
+
EventCategory["RecordingHealthOk"] = "recording.health.ok";
|
|
302
|
+
EventCategory["RecordingStorageCritical"] = "recording.storage.critical";
|
|
303
|
+
/** Free space on a storage location crossed the warn bar. */
|
|
304
|
+
EventCategory["StorageLocationLow"] = "storage.location.low";
|
|
305
|
+
/** Free space at/under the critical bar, or capacity probe failed (`null`). */
|
|
306
|
+
EventCategory["StorageLocationCritical"] = "storage.location.critical";
|
|
307
|
+
/** Recovery from low/critical on a storage location. */
|
|
308
|
+
EventCategory["StorageLocationOk"] = "storage.location.ok";
|
|
309
|
+
/**
|
|
310
|
+
* A `drain` location's regular progress ping (#538) — location id + name,
|
|
311
|
+
* bytes remaining, the observed cede rate and the estimated empty date, or
|
|
312
|
+
* `null` fields when the occupancy read that sweep failed (D393: never
|
|
313
|
+
* folded to 0). Cadence is the named constant
|
|
314
|
+
* `DRAIN_PROGRESS_EVENT_INTERVAL_MS` (15 min) plus once on drain start — no
|
|
315
|
+
* operator knob. Telemetry (D8): a lost tick is a stale progress bar the
|
|
316
|
+
* next sweep corrects.
|
|
317
|
+
*/
|
|
318
|
+
EventCategory["StorageDrainProgress"] = "storage.drain.progress";
|
|
319
|
+
/** Fires once when a draining location reaches zero evictable bytes. */
|
|
320
|
+
EventCategory["StorageDrainComplete"] = "storage.drain.complete";
|
|
321
|
+
EventCategory["RecordingSegmentWritten"] = "recording.segment.written";
|
|
322
|
+
EventCategory["RecordingPolicyFallback"] = "recording.policy.fallback";
|
|
323
|
+
EventCategory["RecordingRetentionCompleted"] = "recording.retention.completed";
|
|
324
|
+
/** Export render progress (0–100). Telemetry (D8): a lost tick is a stale
|
|
325
|
+
* progress bar the client reconciles via `recordingExport.getExport`. */
|
|
326
|
+
EventCategory["RecordingExportProgress"] = "recording.export.progress";
|
|
327
|
+
EventCategory["RecordingExportCompleted"] = "recording.export.completed";
|
|
328
|
+
EventCategory["RecordingExportFailed"] = "recording.export.failed";
|
|
329
|
+
EventCategory["DetectionEvent"] = "detection.event";
|
|
330
|
+
EventCategory["SessionTrackNew"] = "session.track.new";
|
|
331
|
+
EventCategory["SessionTrackExpired"] = "session.track.expired";
|
|
332
|
+
EventCategory["BenchmarkProgress"] = "benchmark.progress";
|
|
333
|
+
EventCategory["PlatformProbePhase"] = "platform-probe.phase";
|
|
334
|
+
EventCategory["PipelineProgress"] = "pipeline.progress";
|
|
335
|
+
/** Per-frame execution trace emitted by the pipeline executor for live observability. */
|
|
336
|
+
EventCategory["PipelineTrace"] = "pipeline.trace";
|
|
337
|
+
/**
|
|
338
|
+
* Raw inference output emitted by `addon-pipeline-runner` after running the
|
|
339
|
+
* detection pipeline on a frame. Carries the `FrameResult` (with
|
|
340
|
+
* `detections[]`, `width`/`height`, timing debug) — never the frame
|
|
341
|
+
* buffer itself. Hub-side consumers (analysis pipeline, class filters,
|
|
342
|
+
* notifications) subscribe to this and re-emit `detection.result` after
|
|
343
|
+
* post-processing.
|
|
344
|
+
*/
|
|
345
|
+
EventCategory["PipelineInferenceResult"] = "pipeline.inference-result";
|
|
346
|
+
/**
|
|
347
|
+
* Camera lifecycle event emitted by `addon-pipeline-orchestrator` when it
|
|
348
|
+
* assigns or unassigns a camera to/from an agent. Carries no frame data;
|
|
349
|
+
* pure observability for UI dashboards and metrics consumers.
|
|
350
|
+
*/
|
|
351
|
+
EventCategory["PipelineCameraAssigned"] = "pipeline.camera-assigned";
|
|
352
|
+
EventCategory["PipelineCameraUnassigned"] = "pipeline.camera-unassigned";
|
|
353
|
+
/**
|
|
354
|
+
* A node the orchestrator would otherwise place cameras on has NO usable
|
|
355
|
+
* inference device: the operator enabled one or more accelerators there and
|
|
356
|
+
* the live probe reports every one of them unavailable. Emitted once per
|
|
357
|
+
* TRANSITION into that state (never per dispatch), and the node is dropped
|
|
358
|
+
* from the placement candidate set for as long as it holds.
|
|
359
|
+
*
|
|
360
|
+
* This exists because the state was previously invisible: agent-a
|
|
361
|
+
* absorbed 283k inference errors in a day while still being handed cameras,
|
|
362
|
+
* and nothing in the system said so.
|
|
363
|
+
*
|
|
364
|
+
* A node with no accelerators configured at all is NOT this — its devices
|
|
365
|
+
* are `disabled`, not `unavailable`, and the runner's default CPU pool
|
|
366
|
+
* serves it exactly as before.
|
|
367
|
+
*/
|
|
368
|
+
EventCategory["PipelineNodeInferenceUnavailable"] = "pipeline.node-inference-unavailable";
|
|
369
|
+
/**
|
|
370
|
+
* A camera has an OPEN detection session and has produced no detection at
|
|
371
|
+
* all for longer than the blind threshold — the camera is being decoded and
|
|
372
|
+
* inferred and is returning nothing. Emitted once per transition into blind,
|
|
373
|
+
* per camera.
|
|
374
|
+
*
|
|
375
|
+
* The failure it reports: a 1h43 detection blackout on the entrance camera
|
|
376
|
+
* that nobody noticed, because "a camera that detects nothing" and "a quiet
|
|
377
|
+
* camera" produce byte-identical silence.
|
|
378
|
+
*/
|
|
379
|
+
EventCategory["PipelineDetectionBlind"] = "pipeline.detection-blind";
|
|
380
|
+
/**
|
|
381
|
+
* A camera's motion source has fired constantly with no subject for an hour
|
|
382
|
+
* (motion duty or session count over the bar, zero detections) — it is not
|
|
383
|
+
* blind, its motion zones or sensitivity want tuning (D907). Paired with
|
|
384
|
+
* {@link PipelineMotionCalm}.
|
|
385
|
+
*/
|
|
386
|
+
EventCategory["PipelineMotionNoisy"] = "pipeline.motion-noisy";
|
|
387
|
+
/** The recovery edge of {@link PipelineMotionNoisy}: the motion fell back, or a detection arrived. */
|
|
388
|
+
EventCategory["PipelineMotionCalm"] = "pipeline.motion-calm";
|
|
389
|
+
/**
|
|
390
|
+
* A camera's package LLM confirm has failed closed three times in a row
|
|
391
|
+
* (D931, 2026-10-26). One edge per camera until
|
|
392
|
+
* {@link PipelinePackageLlmAnswered}.
|
|
393
|
+
*/
|
|
394
|
+
EventCategory["PipelinePackageLlmSilent"] = "pipeline.package-llm-silent";
|
|
395
|
+
/** The recovery edge of {@link PipelinePackageLlmSilent}: a confirm returned yes or no. */
|
|
396
|
+
EventCategory["PipelinePackageLlmAnswered"] = "pipeline.package-llm-answered";
|
|
397
|
+
/**
|
|
398
|
+
* Per-camera pipeline config was mutated by the orchestrator
|
|
399
|
+
* (a settings change via `setAgentInferenceDevices` /
|
|
400
|
+
* `setCameraStepToggle` / `setCameraStepSettings`). Orchestrator
|
|
401
|
+
* subscribes to its own emission to hot-reload the assigned runner
|
|
402
|
+
* via `attachCamera` so the next frame executes against the new
|
|
403
|
+
* engine/steps without waiting for a rebalance or the next
|
|
404
|
+
* `DeviceStreamsRegistered` cycle.
|
|
405
|
+
*/
|
|
406
|
+
EventCategory["PipelineCameraUpdated"] = "pipeline.camera-updated";
|
|
407
|
+
/**
|
|
408
|
+
* The cluster camera-source OWNER changed (`clusterRoles.ingestNode`).
|
|
409
|
+
* Emitted by addon-pipeline-orchestrator whenever it (re)derives node
|
|
410
|
+
* capabilities — at boot, on agent online/offline, and on an ingest-node
|
|
411
|
+
* flip. Carries the resolved `ownerNodeId`. The stream-broker consumes it to
|
|
412
|
+
* keep its ingest-owner-gate decision current WITHOUT a per-`ensureBroker`
|
|
413
|
+
* cross-process `getIngestOwner` query (push the authority's decision instead
|
|
414
|
+
* of polling it on the hot path). Idempotent state — re-emitted on every
|
|
415
|
+
* topology change, so a dropped event self-heals on the next one (plus the
|
|
416
|
+
* broker's long backstop reconcile query).
|
|
417
|
+
*/
|
|
418
|
+
EventCategory["PipelineIngestOwnerChanged"] = "pipeline.ingest-owner-changed";
|
|
419
|
+
/**
|
|
420
|
+
* Periodic snapshot of per-node pipeline-runner load
|
|
421
|
+
* (`RunnerLocalLoad`). Emitted ~1Hz by every runner so UI dashboards
|
|
422
|
+
* subscribe instead of polling `pipelineRunner.getLocalLoad`.
|
|
423
|
+
* `nodeId` carried in the payload + on `event.source.nodeId`.
|
|
424
|
+
*/
|
|
425
|
+
EventCategory["PipelineRunnerLoadSnapshot"] = "pipeline.runner-load-snapshot";
|
|
426
|
+
/**
|
|
427
|
+
* Periodic snapshot of per-camera pipeline metrics (`CameraMetrics`
|
|
428
|
+
* + `deviceId` + `nodeId`). Emitted ~1Hz by every runner for each
|
|
429
|
+
* attached camera. UI subscribes to drive overlay phase / fps /
|
|
430
|
+
* inference time without polling `getCameraMetrics`.
|
|
431
|
+
*/
|
|
432
|
+
EventCategory["PipelineCameraMetricsSnapshot"] = "pipeline.camera-metrics-snapshot";
|
|
433
|
+
/**
|
|
434
|
+
* Periodic snapshot of stream-broker per-broker statistics (input
|
|
435
|
+
* fps, decoded fps, bitrate, codec). Emitted ~1Hz by every
|
|
436
|
+
* stream-broker process for each active broker so the UI can drive
|
|
437
|
+
* the Stream / Cluster dashboards without polling
|
|
438
|
+
* `streamBroker.listAllProfileSlots` and friends.
|
|
439
|
+
*/
|
|
440
|
+
EventCategory["StreamBrokerMetricsSnapshot"] = "stream-broker.metrics-snapshot";
|
|
441
|
+
/**
|
|
442
|
+
* Cap event fired by `stream-broker` when a profile slot enters
|
|
443
|
+
* "demanded" state — a cam stream has been assigned and at least one
|
|
444
|
+
* consumer (RTSP restream, decoded subscriber, WebRTC session, …) is
|
|
445
|
+
* present. Camera-provider addons (Reolink Baichuan push, …)
|
|
446
|
+
* subscribe to this category to start their underlying transport
|
|
447
|
+
* lazily. Payload: `{ deviceId, camStreamId, profile }`.
|
|
448
|
+
*/
|
|
449
|
+
EventCategory["StreamBrokerOnCamStreamDemand"] = "stream-broker.onCamStreamDemand";
|
|
450
|
+
/**
|
|
451
|
+
* Cap event fired by `stream-broker` when the last consumer leaves a
|
|
452
|
+
* previously-demanded cam stream. Providers tear down their
|
|
453
|
+
* underlying transport on receipt. Payload: `{ deviceId, camStreamId }`.
|
|
454
|
+
*/
|
|
455
|
+
EventCategory["StreamBrokerOnCamStreamIdle"] = "stream-broker.onCamStreamIdle";
|
|
456
|
+
/**
|
|
457
|
+
* Cap event fired by `stream-broker` when a broker fails to dial a
|
|
458
|
+
* managed-loopback source (today: `pull-rfc4571`) and the publisher
|
|
459
|
+
* needs to refresh the cached URL. The lib's TCP server idle-tears-down
|
|
460
|
+
* on its own schedule, so a re-publish with a fresh `host:port` is the
|
|
461
|
+
* only way to keep the broker dialable. Camera providers (Reolink
|
|
462
|
+
* Baichuan native, …) subscribe and respond by re-running their publish
|
|
463
|
+
* pipeline.
|
|
464
|
+
* Payload: `{ deviceId, camStreamId, brokerId }`.
|
|
465
|
+
*/
|
|
466
|
+
EventCategory["StreamBrokerOnRequestStreamSourceRefresh"] = "stream-broker.onRequestStreamSourceRefresh";
|
|
467
|
+
/**
|
|
468
|
+
* A broker RE-DIALED its source (every dial after the first). A consumer that
|
|
469
|
+
* reads the broker over a transport that does not announce the cut — the
|
|
470
|
+
* recorder's ffmpeg writer — learns here instead of through its idle clock.
|
|
471
|
+
* Telemetry: a dropped event only means the idle clock recovers it later.
|
|
472
|
+
* Payload: `{ deviceId, camStreamId, brokerId, reason }`.
|
|
473
|
+
*/
|
|
474
|
+
EventCategory["StreamBrokerOnSourceRestart"] = "stream-broker.onSourceRestart";
|
|
475
|
+
/**
|
|
476
|
+
* A camera provider changed a device's stream parameters (codec /
|
|
477
|
+
* resolution / bitrate / a stream added or removed). A LOW-LATENCY NUDGE
|
|
478
|
+
* for the stream-broker's catalog reconcile: it carries NO authoritative
|
|
479
|
+
* data — the broker re-PULLS that device's `stream-catalog` cap on receipt
|
|
480
|
+
* (the 30s reconcile poll is the backstop if this nudge is dropped). Emitted
|
|
481
|
+
* by providers from `stream-params.setProfile`. Payload: `{ deviceId }`.
|
|
482
|
+
*/
|
|
483
|
+
EventCategory["StreamParamsChanged"] = "stream-params.changed";
|
|
484
|
+
/**
|
|
485
|
+
* Generic per-device runtime-state change. Fired by `device-manager`
|
|
486
|
+
* whenever a persisted slice in any cap's `runtimeState` shape
|
|
487
|
+
* mutates. Payload: `{deviceId, capName, slice}`. Subscribers are
|
|
488
|
+
* the `deviceState` cap router (cross-process listeners) and the
|
|
489
|
+
* deviceProxy reactive bindings (`device.state.<capName>.value`).
|
|
490
|
+
* Cap-specific events (`battery.onStatusChanged`, …) still fire
|
|
491
|
+
* — they're authoritative for callers that want a typed payload
|
|
492
|
+
* without filtering on `capName`.
|
|
493
|
+
*/
|
|
494
|
+
EventCategory["DeviceStateChanged"] = "device.state-changed";
|
|
495
|
+
/**
|
|
496
|
+
* A device COMMAND (a vocabulary action, D920/D983) settled in the hub's
|
|
497
|
+
* transition audit (D1022): confirmed, already in place, unconfirmed or
|
|
498
|
+
* failed. Never a device's own change. Payload: `DeviceCommandSettledEvent`
|
|
499
|
+
* (`{deviceId, action, outcome, actor, at}`, no arguments). It feeds
|
|
500
|
+
* the Notification Center `device-command` kind. Telemetry (D8): losing one
|
|
501
|
+
* costs a notification, never state; the audit row is the record.
|
|
502
|
+
*/
|
|
503
|
+
EventCategory["DeviceCommandSettled"] = "device.command-settled";
|
|
504
|
+
/**
|
|
505
|
+
* The NATIVE shadow of a cap a composition has claimed fields of moved
|
|
506
|
+
* (D663). Payload: `{ deviceId, capName, native }` — what the provider
|
|
507
|
+
* wrote, BEFORE the owned fields are overlaid. Owner-only (D224): it is for
|
|
508
|
+
* the composer's native self-reads, and the public event routers refuse it
|
|
509
|
+
* (`isOwnerOnlyEventCategory`) so no consumer surface ever shows a second
|
|
510
|
+
* truth beside the merged `DeviceStateChanged.slice`. Emitted only under a
|
|
511
|
+
* `replace` claim, one per native write of that cap.
|
|
512
|
+
*/
|
|
513
|
+
EventCategory["DeviceNativeShadowChanged"] = "device.native-shadow-changed";
|
|
514
|
+
/**
|
|
515
|
+
* Frame occupancy for a camera CHANGED — a tracked object was gained or
|
|
516
|
+
* lost. Carries `{ deviceId, totalObjects, byClass, zones }`.
|
|
517
|
+
*
|
|
518
|
+
* Emitted only on a change, so a steady scene is silent. It exists so a
|
|
519
|
+
* client can stop polling `zoneAnalytics.getCurrentSnapshot`: that was the
|
|
520
|
+
* one live badge with no push signal at all, and it cost a request every
|
|
521
|
+
* four seconds per visible camera.
|
|
522
|
+
*
|
|
523
|
+
* Like every event it is telemetry and may be dropped ([D8]) — a consumer
|
|
524
|
+
* keeps a slow reconcile rather than trusting it alone.
|
|
525
|
+
*/
|
|
526
|
+
EventCategory["ZoneAnalyticsOccupancyChanged"] = "zone-analytics.occupancy-changed";
|
|
527
|
+
/**
|
|
528
|
+
* Cap event fired by every device that registers the `battery`
|
|
529
|
+
* capability. Mirrors the cap definition's `onStatusChanged`. Carries
|
|
530
|
+
* `{ deviceId, status: BatteryStatus }`. Subscribers (alert center,
|
|
531
|
+
* snapshot wrapper, UI) react to charge/sleep transitions without
|
|
532
|
+
* polling `batteryCapability.getStatus`.
|
|
533
|
+
*/
|
|
534
|
+
EventCategory["BatteryOnStatusChanged"] = "battery.onStatusChanged";
|
|
535
|
+
/**
|
|
536
|
+
* Cap event fired by every device that registers the `network-link`
|
|
537
|
+
* capability. Mirrors the cap definition's `onStatusChanged`. Carries
|
|
538
|
+
* `{ deviceId, status: NetworkLinkStatus }` — a link switch or a signal
|
|
539
|
+
* reading that moved.
|
|
540
|
+
*/
|
|
541
|
+
EventCategory["NetworkLinkOnStatusChanged"] = "network-link.onStatusChanged";
|
|
542
|
+
/**
|
|
543
|
+
* Emitted by the battery cap provider WHEN `wakeUp` enters the
|
|
544
|
+
* "wake in progress" window — between the Baichuan wake-up issue and
|
|
545
|
+
* the camera's first dialed-back RTP packet. The stream-broker
|
|
546
|
+
* manager subscribes to flip the per-broker placeholder reason to
|
|
547
|
+
* `'waking'` so viewers see a labelled "WAKING UP" tile instead of
|
|
548
|
+
* the generic `'reconnecting'` frame. Carries `{ deviceId }`. The
|
|
549
|
+
* complementary "wake complete" signal is the existing
|
|
550
|
+
* `BatteryOnStatusChanged { sleeping: false }` event.
|
|
551
|
+
*/
|
|
552
|
+
EventCategory["BatteryOnWakeStarted"] = "battery.onWakeStarted";
|
|
553
|
+
/**
|
|
554
|
+
* Cap event fired by every device that registers the `doorbell`
|
|
555
|
+
* capability. Mirrors `doorbellCapability.events.onPressed`. Carries
|
|
556
|
+
* `{ deviceId, timestamp }`. Operators consuming the UI subscribe
|
|
557
|
+
* here to render transient ring toasts and a "Recent presses" row
|
|
558
|
+
* on the device detail page.
|
|
559
|
+
*/
|
|
560
|
+
EventCategory["DoorbellOnPressed"] = "doorbell.onPressed";
|
|
561
|
+
/** Mirrors `runningStateCapability.events.onStarted`. */
|
|
562
|
+
EventCategory["RunningStarted"] = "running.started";
|
|
563
|
+
/** Mirrors `runningStateCapability.events.onFinished`. */
|
|
564
|
+
EventCategory["RunningFinished"] = "running.finished";
|
|
565
|
+
/** Mirrors `workloadCapability.events.onStarted` — a workload reached running (#585). */
|
|
566
|
+
EventCategory["WorkloadStarted"] = "workload.started";
|
|
567
|
+
/** Mirrors `workloadCapability.events.onStopped` — a running workload stopped cleanly. */
|
|
568
|
+
EventCategory["WorkloadStopped"] = "workload.stopped";
|
|
569
|
+
/** Mirrors `workloadCapability.events.onCrashed` — a workload stopped without a request. */
|
|
570
|
+
EventCategory["WorkloadCrashed"] = "workload.crashed";
|
|
571
|
+
/** Mirrors `workloadCapability.events.onRecovered` — a crashed workload runs again. */
|
|
572
|
+
EventCategory["WorkloadRecovered"] = "workload.recovered";
|
|
573
|
+
/** Mirrors `deviceRunsCapability.events.onRunOpened` - a durable run record opened. */
|
|
574
|
+
EventCategory["DeviceRunOpened"] = "device-run.opened";
|
|
575
|
+
/** Mirrors `deviceRunsCapability.events.onRunClosed` - a durable run record closed. */
|
|
576
|
+
EventCategory["DeviceRunClosed"] = "device-run.closed";
|
|
577
|
+
/**
|
|
578
|
+
* Cap event fired by every device that registers the `event-emitter`
|
|
579
|
+
* capability. Mirrors `eventEmitterCapability.events.onEvent`. Carries
|
|
580
|
+
* `{ deviceId, eventType, data, timestamp, seq }` — the device's EXACT
|
|
581
|
+
* declared event verbatim (NO normalization). Subscribers (UI event
|
|
582
|
+
* stream, advanced-notifier rules) react to fired events without
|
|
583
|
+
* holding a cap reference.
|
|
584
|
+
*/
|
|
585
|
+
EventCategory["EventEmitted"] = "event-emitter.event";
|
|
586
|
+
/**
|
|
587
|
+
* Periodic snapshot of the per-node detection-pipeline engine
|
|
588
|
+
* registry (loaded engines, models resident, in-use cameras, idle
|
|
589
|
+
* TTL). Emitted ~0.2Hz (every 5 s) by every detection-pipeline
|
|
590
|
+
* process. The Engines tab subscribes to drive its inventory view
|
|
591
|
+
* without polling `pipelineExecutor.listLoadedEngines`.
|
|
592
|
+
*/
|
|
593
|
+
EventCategory["PipelineEngineMetricsSnapshot"] = "pipeline.engine-metrics-snapshot";
|
|
594
|
+
/**
|
|
595
|
+
* Per-node detection-engine runtime-provisioning transition. Emitted by
|
|
596
|
+
* the detection-pipeline provider on every state change of its lazy
|
|
597
|
+
* engine-provisioning machine (idle → installing → verifying → ready,
|
|
598
|
+
* or → failed with a `nextRetryAt`). Payload is the
|
|
599
|
+
* `EngineProvisioningState` snapshot; `event.source.nodeId` carries the
|
|
600
|
+
* node. The Pipeline page subscribes to drive a live "installing
|
|
601
|
+
* OpenVINO… / ready" indicator per node without polling
|
|
602
|
+
* `pipelineExecutor.getEngineProvisioning`. Telemetry-grade (D8): the UI
|
|
603
|
+
* also reads the cap snapshot on mount / reconnect. Phase 2.
|
|
604
|
+
*/
|
|
605
|
+
EventCategory["PipelineEngineProvisioning"] = "pipeline.engine-provisioning";
|
|
606
|
+
/**
|
|
607
|
+
* Cluster topology snapshot. Carries the same payload returned by
|
|
608
|
+
* `nodes.topology` (every reachable node + addons + processes).
|
|
609
|
+
* Emitted by the hub on any agent / addon lifecycle change
|
|
610
|
+
* (debounced) plus a periodic safety net. Replaces UI polling on
|
|
611
|
+
* `nodes.topology` — admin-ui dashboards subscribe to drive the
|
|
612
|
+
* cluster view directly from the event payload.
|
|
613
|
+
*/
|
|
614
|
+
EventCategory["ClusterTopologySnapshot"] = "cluster.topology-snapshot";
|
|
615
|
+
/**
|
|
616
|
+
* Periodic per-node system metrics snapshot (CPU / memory / GPU /
|
|
617
|
+
* disk / network). Emitted ~0.2 Hz by the metrics-provider addon
|
|
618
|
+
* for each node. Drives the dashboard SystemStatus / ProcessResources
|
|
619
|
+
* widgets without polling `metricsProvider.getCurrent`.
|
|
620
|
+
*/
|
|
621
|
+
EventCategory["MetricsNodeResourcesSnapshot"] = "metrics.node-resources-snapshot";
|
|
622
|
+
/**
|
|
623
|
+
* Periodic per-node process-tree snapshot (camstack-related pids
|
|
624
|
+
* with root / managed / system classification). Emitted ~0.2 Hz by
|
|
625
|
+
* the metrics-provider addon. Drives the Cluster → Processes tab
|
|
626
|
+
* without polling `metricsProvider.listNodeProcesses`.
|
|
627
|
+
*/
|
|
628
|
+
EventCategory["MetricsNodeProcessesSnapshot"] = "metrics.node-processes-snapshot";
|
|
629
|
+
/**
|
|
630
|
+
* Capability binding change event emitted by `addon-pipeline-orchestrator`
|
|
631
|
+
* when a user changes which addon implements a cap on a node. Subscribed
|
|
632
|
+
* by every kernel process to update its local `preferredProviderRegistry`
|
|
633
|
+
* so future capability lookups respect the new binding.
|
|
634
|
+
*/
|
|
635
|
+
/**
|
|
636
|
+
* A capability binding was changed for a node — addon X now provides
|
|
637
|
+
* capability `cap` on node `nodeId`. Lives under the generic
|
|
638
|
+
* `capability.*` namespace because capability bindings are a kernel-
|
|
639
|
+
* level concept used by many addons, not strictly pipeline-scoped.
|
|
640
|
+
*/
|
|
641
|
+
EventCategory["CapabilityBindingChanged"] = "capability.binding-changed";
|
|
642
|
+
EventCategory["ModelDownloadProgress"] = "model.download.progress";
|
|
643
|
+
EventCategory["AgentRegistered"] = "agent.registered";
|
|
644
|
+
EventCategory["AgentUnregistered"] = "agent.unregistered";
|
|
645
|
+
EventCategory["AgentOnline"] = "agent.online";
|
|
646
|
+
EventCategory["AgentOffline"] = "agent.offline";
|
|
647
|
+
/** Forked worker process (e.g. hub/pipeline) connected to the broker. */
|
|
648
|
+
EventCategory["WorkerOnline"] = "worker.online";
|
|
649
|
+
/** Forked worker process disconnected from the broker. */
|
|
650
|
+
EventCategory["WorkerOffline"] = "worker.offline";
|
|
651
|
+
EventCategory["AgentTaskDispatched"] = "agent.task.dispatched";
|
|
652
|
+
EventCategory["AgentTaskAssigned"] = "agent.task.assigned";
|
|
653
|
+
EventCategory["AgentTrpcConnected"] = "agent.trpc.connected";
|
|
654
|
+
EventCategory["AgentWsConnected"] = "agent.ws.connected";
|
|
655
|
+
EventCategory["AgentWsDisconnected"] = "agent.ws.disconnected";
|
|
656
|
+
EventCategory["AgentBackupActivated"] = "agent.backup.activated";
|
|
657
|
+
EventCategory["OrchestrationSettingsUpdated"] = "orchestration.settings-updated";
|
|
658
|
+
EventCategory["MotionAnalysis"] = "detection.motion-analysis";
|
|
659
|
+
/** All raw motion zones from CCL before minArea filter — for UI debug overlay. */
|
|
660
|
+
EventCategory["MotionZonesRaw"] = "detection.motion-zones-raw";
|
|
661
|
+
/**
|
|
662
|
+
* Per-camera motion phase transition (`watching ↔ active`) emitted
|
|
663
|
+
* by the runner. Mirrors the `motion.onMotionChanged` cap event
|
|
664
|
+
* surface — payload `MotionOnMotionChangedPayload` carries
|
|
665
|
+
* `{deviceId, detected, timestamp, source, regions?}`. Subscribers
|
|
666
|
+
* include addons that need to react to motion state without
|
|
667
|
+
* polling the runtime-state mirror.
|
|
668
|
+
*/
|
|
669
|
+
EventCategory["MotionOnMotionChanged"] = "motion.on-motion-changed";
|
|
670
|
+
EventCategory["DetectionResult"] = "detection.result";
|
|
671
|
+
EventCategory["DetectionRaw"] = "detection.raw";
|
|
672
|
+
EventCategory["DetectionCameraNative"] = "detection.camera-native";
|
|
673
|
+
/**
|
|
674
|
+
* Canonical per-chunk live audio pipeline output. Payload is
|
|
675
|
+
* `PipelineAudioInferenceResultPayload` carrying a full `AudioResult`
|
|
676
|
+
* (level + detections + debug). Lives on the pipeline.* namespace
|
|
677
|
+
* alongside `pipeline.inference-result` (video) for symmetry.
|
|
678
|
+
*/
|
|
679
|
+
EventCategory["PipelineAudioInferenceResult"] = "pipeline.audio-inference-result";
|
|
680
|
+
EventCategory["DetectionPhaseTransition"] = "detection.phase-transition";
|
|
681
|
+
/**
|
|
682
|
+
* A camera provider's RAW onboard motion push (D673): the `MotionOnMotionChanged`
|
|
683
|
+
* data shape without `triggeredBy`, built by `providerMotionEvent`. Its one
|
|
684
|
+
* consumer is the orchestrator's camera-sensors bridge, which re-emits the
|
|
685
|
+
* camera's EFFECTIVE onboard motion as `MotionOnMotionChanged` (a pass-through
|
|
686
|
+
* for a camera with no attached sensor). Providers must not emit
|
|
687
|
+
* `MotionOnMotionChanged` themselves; `scripts/check-onboard-motion-emitters.ts`
|
|
688
|
+
* keeps it so (camera-grid is a named, deferred exception).
|
|
689
|
+
*/
|
|
690
|
+
EventCategory["ProviderMotion"] = "provider.motion";
|
|
691
|
+
EventCategory["ProviderDetection"] = "provider.detection";
|
|
692
|
+
EventCategory["EnrichmentEmbeddingStored"] = "enrichment.embedding.stored";
|
|
693
|
+
EventCategory["EnrichmentSceneStateChanged"] = "enrichment.scene.state-changed";
|
|
694
|
+
EventCategory["EnrichmentActivitySummary"] = "enrichment.activity.summary";
|
|
695
|
+
/**
|
|
696
|
+
* Unified track-lifecycle event: ONE category carrying `phase:
|
|
697
|
+
* 'start' | 'update' | 'end'` with a rich, typed
|
|
698
|
+
* `PipelineAnalyticsTrackLifecyclePayload`. Supersedes the thin
|
|
699
|
+
* `PipelineAnalyticsTrackStarted` / `PipelineAnalyticsTrackEnded`
|
|
700
|
+
* pair — a consumer subscribes once and branches on `phase`.
|
|
701
|
+
*/
|
|
702
|
+
EventCategory["PipelineAnalyticsTrackLifecycle"] = "pipeline-analytics.track-lifecycle";
|
|
703
|
+
/**
|
|
704
|
+
* @deprecated Superseded by {@link PipelineAnalyticsTrackLifecycle}
|
|
705
|
+
* (`phase:'start'`). Kept as a soft alias — no known subscribers.
|
|
706
|
+
*/
|
|
707
|
+
EventCategory["PipelineAnalyticsTrackStarted"] = "pipeline-analytics.track-started";
|
|
708
|
+
/**
|
|
709
|
+
* @deprecated Superseded by {@link PipelineAnalyticsTrackLifecycle}
|
|
710
|
+
* (`phase:'end'`). Kept as a soft alias — no known subscribers.
|
|
711
|
+
*/
|
|
712
|
+
EventCategory["PipelineAnalyticsTrackEnded"] = "pipeline-analytics.track-ended";
|
|
713
|
+
EventCategory["PipelineAnalyticsDetectionEvent"] = "pipeline-analytics.detection-event";
|
|
714
|
+
EventCategory["PipelineAnalyticsFrameTracked"] = "pipeline-analytics.frame-tracked";
|
|
715
|
+
/**
|
|
716
|
+
* Fired by `addon-post-analysis` when a parked (stationary) object appears
|
|
717
|
+
* (a track was promoted to a stationary-registry entry) or departs (the
|
|
718
|
+
* object moved / was removed). Telemetry (D8): lossy, drives a UI refresh of
|
|
719
|
+
* the dedicated "Stationary" section — never the live event feed. Payload:
|
|
720
|
+
* `{ deviceId, entryId, className, phase:'appeared'|'departed', timestamp, observedAt, zones }`.
|
|
721
|
+
*/
|
|
722
|
+
EventCategory["PipelineAnalyticsStationaryChanged"] = "pipeline-analytics.stationary-changed";
|
|
723
|
+
/**
|
|
724
|
+
* Fired by `addon-post-analysis` when a package-drop is confirmed inside
|
|
725
|
+
* a package zone — a newly-appeared stationary object of a package class
|
|
726
|
+
* that cleared the class / zone / dwell / size gates. Payload:
|
|
727
|
+
* `PipelineAnalyticsPackageDeliveredPayload` carrying `{ deviceId,
|
|
728
|
+
* entryId, className, zoneIds, keyFrameMediaId?, bbox, timestamp }`.
|
|
729
|
+
* Telemetry (D8): the durable record is the `package-events` store row;
|
|
730
|
+
* this bus topic drives notifier rules + live UI. See
|
|
731
|
+
* docs/superpowers/specs/2026-07-17-package-zones-design.md §5.1.
|
|
732
|
+
*/
|
|
733
|
+
EventCategory["PipelineAnalyticsPackageDelivered"] = "pipeline-analytics.package-delivered";
|
|
734
|
+
/**
|
|
735
|
+
* Fired by `addon-post-analysis` when a previously-delivered package
|
|
736
|
+
* leaves its zone (the stationary entry departed — moved or swept).
|
|
737
|
+
* Payload: `PipelineAnalyticsPackagePickedUpPayload` carrying
|
|
738
|
+
* `{ deviceId, entryId, deliveredEventId, className, timestamp }`.
|
|
739
|
+
* Telemetry (D8). See package-zones-design §5.2.
|
|
740
|
+
*/
|
|
741
|
+
EventCategory["PipelineAnalyticsPackagePickedUp"] = "pipeline-analytics.package-picked-up";
|
|
742
|
+
/**
|
|
743
|
+
* Fired by `addon-post-analysis` whenever a gallery face row changes:
|
|
744
|
+
* `kind:'buffered'` a new detected face was persisted, `'assigned'` /
|
|
745
|
+
* `'unassigned'` its identity link changed, `'deleted'` the row was
|
|
746
|
+
* removed. Telemetry semantics (D8): a lost event only delays a refresh,
|
|
747
|
+
* never a correctness issue. Payload `PipelineAnalyticsFaceGalleryChangedPayload`.
|
|
748
|
+
*/
|
|
749
|
+
EventCategory["PipelineAnalyticsFaceGalleryChanged"] = "pipeline-analytics.face-gallery-changed";
|
|
750
|
+
/**
|
|
751
|
+
* Fired by `addon-post-analysis` whenever a gallery plate row changes:
|
|
752
|
+
* `kind:'buffered'` a new read was persisted (`PlateRecognizer.onTrackEnd`),
|
|
753
|
+
* `'assigned'` / `'unassigned'` its vehicle link changed
|
|
754
|
+
* (`PlateGalleryProvider`), `'deleted'` the row was removed. Telemetry
|
|
755
|
+
* semantics (D8): a lost event only delays a refresh, never a correctness
|
|
756
|
+
* issue. Payload `PipelineAnalyticsPlateGalleryChangedPayload`.
|
|
757
|
+
*/
|
|
758
|
+
EventCategory["PipelineAnalyticsPlateGalleryChanged"] = "pipeline-analytics.plate-gallery-changed";
|
|
759
|
+
EventCategory["CameraStreamsProfileSlotsChanged"] = "camera-streams.onProfileSlotsChanged";
|
|
760
|
+
/**
|
|
761
|
+
* Stream-broker health watchdog. Per-broker (deviceId/profile) emission.
|
|
762
|
+
* `stream.offline` fires after STREAM_STALE_TIMEOUT_MS without an encoded
|
|
763
|
+
* packet on an active broker. `stream.online` fires on first packet
|
|
764
|
+
* after a stale gap (or on initial first packet). Payload includes
|
|
765
|
+
* the assigned camStreamId as `profileKey`.
|
|
766
|
+
*/
|
|
767
|
+
EventCategory["StreamOnline"] = "stream.online";
|
|
768
|
+
EventCategory["StreamOffline"] = "stream.offline";
|
|
769
|
+
EventCategory["NetworkTunnelStarted"] = "network.tunnel.started";
|
|
770
|
+
EventCategory["NetworkTunnelStopped"] = "network.tunnel.stopped";
|
|
771
|
+
/** Fired by the `local-network` cap when the host's interface set
|
|
772
|
+
* changes (new IP from DHCP, VPN connect, docker bridge added). */
|
|
773
|
+
EventCategory["LocalNetworkChanged"] = "network.local.changed";
|
|
774
|
+
/**
|
|
775
|
+
* Fired by a `mesh-network` provider (Tailscale, …) when its
|
|
776
|
+
* mesh-reachable host changes (join / leave / MagicDNS or 100.x IP
|
|
777
|
+
* change). Lets `local-network` fold the mesh endpoint into its
|
|
778
|
+
* connection-endpoint list without a cross-package import. Payload
|
|
779
|
+
* carries the preferred host (`host: ''` = no longer reachable),
|
|
780
|
+
* the hub port, and the scheme. Telemetry-grade (D8): consumers
|
|
781
|
+
* pull-reconcile from the provider's `getStatus` on reconnect. */
|
|
782
|
+
EventCategory["MeshNetworkChanged"] = "network.mesh.changed";
|
|
783
|
+
EventCategory["BackupCompleted"] = "backup.completed";
|
|
784
|
+
/**
|
|
785
|
+
* A whole backup RUN finished — every destination attempted, win or lose.
|
|
786
|
+
*
|
|
787
|
+
* `backup.completed` fires once per DESTINATION, which is the right grain for
|
|
788
|
+
* a progress UI and the wrong one for a notification: an operator with three
|
|
789
|
+
* destinations would be told three times. And a run where two of three
|
|
790
|
+
* destinations succeeded is not a clean success — a single "backup
|
|
791
|
+
* completed" that hid the failed one would be a lie, so the count of each is
|
|
792
|
+
* carried here and the message says both.
|
|
793
|
+
*
|
|
794
|
+
* Emitted by the backup orchestrator only after the destination loop, so a
|
|
795
|
+
* run that dies during the BUILD phase produces no completion at all.
|
|
796
|
+
*/
|
|
797
|
+
EventCategory["BackupRunCompleted"] = "backup.run-completed";
|
|
798
|
+
EventCategory["BackupRestored"] = "backup.restored";
|
|
799
|
+
EventCategory["NotificationDispatched"] = "notification.dispatched";
|
|
800
|
+
EventCategory["NotificationFailed"] = "notification.failed";
|
|
801
|
+
/**
|
|
802
|
+
* A notification rule that cannot work (D905): its stored row does not load,
|
|
803
|
+
* or it still names a device / delivery target the prune CONFIRMED deleted.
|
|
804
|
+
* One edge per rule per distinct set of reasons; never on an unanswered read.
|
|
805
|
+
*/
|
|
806
|
+
EventCategory["NotificationRuleBroken"] = "notification.rule-broken";
|
|
807
|
+
/** The clear of {@link NotificationRuleBroken}: the rule loads and names nothing deleted. */
|
|
808
|
+
EventCategory["NotificationRuleRepaired"] = "notification.rule-repaired";
|
|
809
|
+
/** A migration failed or was blocked; the Alert Center re-reads the ledger. */
|
|
810
|
+
EventCategory["MigrationFailed"] = "migration.failed";
|
|
811
|
+
/** A migration applied or a failure cleared; the Alert Center re-reads the ledger. */
|
|
812
|
+
EventCategory["MigrationApplied"] = "migration.applied";
|
|
813
|
+
EventCategory["DeviceUpdated"] = "device.updated";
|
|
814
|
+
/**
|
|
815
|
+
* Transport-level connectivity. Emitted by the device driver when
|
|
816
|
+
* the underlying control socket actually connects / disconnects
|
|
817
|
+
* (Baichuan TCP, ONVIF probe response, RTSP DESCRIBE, …) — NOT for
|
|
818
|
+
* power-state transitions on a battery camera. For battery wake /
|
|
819
|
+
* doze cycles see `DeviceAwake` / `DeviceSleeping`.
|
|
820
|
+
*/
|
|
821
|
+
EventCategory["DeviceOnline"] = "device.online";
|
|
822
|
+
/**
|
|
823
|
+
* Stream-broker watchdog — emitted when no encoded packet has been
|
|
824
|
+
* received for STREAM_STALE_TIMEOUT_MS on an active broker (rtsp or
|
|
825
|
+
* push). Paired with DeviceOnline which fires on first packet after
|
|
826
|
+
* a stale gap. Payload: DeviceStreamHealthPayload.
|
|
827
|
+
*/
|
|
828
|
+
EventCategory["DeviceOffline"] = "device.offline";
|
|
829
|
+
/**
|
|
830
|
+
* Battery cam woke up — physical power-state transition reported
|
|
831
|
+
* by the device firmware. Distinct from `DeviceOnline` so a UI panel
|
|
832
|
+
* watching power state doesn't flap on every UDP socket reconnect.
|
|
833
|
+
*/
|
|
834
|
+
EventCategory["DeviceAwake"] = "device.awake";
|
|
835
|
+
/**
|
|
836
|
+
* Battery cam went to sleep. See `DeviceAwake`.
|
|
837
|
+
*/
|
|
838
|
+
EventCategory["DeviceSleeping"] = "device.sleeping";
|
|
839
|
+
EventCategory["RetentionCleanup"] = "retention.cleanup";
|
|
840
|
+
/**
|
|
841
|
+
* Legacy bulk-update progress snapshot (payload `BulkUpdateState`). No longer
|
|
842
|
+
* emitted — F3 removed the coordinator that produced it; "Update all" now runs
|
|
843
|
+
* as one lifecycle engine job (`AddonsJobProgress`/`AddonsJobLog`). Retained
|
|
844
|
+
* (with `BulkUpdateState`) only to avoid regenerating the event maps; removed
|
|
845
|
+
* in F4 once live bulk progress is re-implemented over the engine events.
|
|
846
|
+
*/
|
|
847
|
+
EventCategory["AddonsBulkUpdateProgress"] = "addons.bulk-update-progress";
|
|
848
|
+
EventCategory["AddonsJobProgress"] = "addons.job-progress";
|
|
849
|
+
EventCategory["AddonsJobLog"] = "addons.job-log";
|
|
850
|
+
/**
|
|
851
|
+
* A container's child visibility toggled (hidden/shown). Emitted by the
|
|
852
|
+
* `accessories` cap when a child device is hidden or revealed.
|
|
853
|
+
* Payload: `{ deviceId, childDeviceId, hidden }`.
|
|
854
|
+
*/
|
|
855
|
+
EventCategory["AccessoriesChildVisibilityChanged"] = "accessories.onChildVisibilityChanged";
|
|
856
|
+
/**
|
|
857
|
+
* A container's child set changed (children added/removed/reordered).
|
|
858
|
+
* Payload: `{ deviceId, childDeviceIds, hiddenChildIds }`.
|
|
859
|
+
*/
|
|
860
|
+
EventCategory["AccessoriesChanged"] = "accessories.onAccessoriesChanged";
|
|
861
|
+
/**
|
|
862
|
+
* An action run started or ended. Emitted by the `actions` surface.
|
|
863
|
+
* Payload: `ActionRunChanged` (`{ actionId, runId, isRunning, outcome?, lastRunAt, lastError }`).
|
|
864
|
+
*/
|
|
865
|
+
EventCategory["ActionsRunChanged"] = "actions.onRunChanged";
|
|
866
|
+
/**
|
|
867
|
+
* Progress update from a running model conversion job.
|
|
868
|
+
* Payload: `{ kind: 'model-convert', phase, sessionId?, pct?, detail? }`.
|
|
869
|
+
* Emitted by `addon-model-studio` on the converting node.
|
|
870
|
+
*/
|
|
871
|
+
EventCategory["ModelConvertProgress"] = "model-convert.progress";
|
|
872
|
+
return EventCategory;
|
|
873
|
+
}({});
|
|
874
|
+
//#endregion
|
|
875
|
+
//#region ../types/dist/esm/addon/instance-switches.mjs
|
|
876
|
+
var SWITCHES = /* @__PURE__ */ new Map();
|
|
877
|
+
/** The ids the registry is known to hold a row for (hydrated, or told by the hub). */
|
|
878
|
+
var ROWS = /* @__PURE__ */ new Set();
|
|
879
|
+
/** The owner addon of an id, learned from its rows and from the helper that serves it. */
|
|
880
|
+
var OWNER_OF = /* @__PURE__ */ new Map();
|
|
881
|
+
/** The addons whose registry read answered at least once. */
|
|
882
|
+
var ANSWERED = /* @__PURE__ */ new Set();
|
|
883
|
+
/** The addons whose boot has begun reading the registry: only they can be held back. */
|
|
884
|
+
var HYDRATING = /* @__PURE__ */ new Set();
|
|
885
|
+
/**
|
|
886
|
+
* The addons that serve an instance kind and have not been answered by the registry yet. Scoped
|
|
887
|
+
* per owner: one addon's failed read never turns off another addon's instances, and an addon that
|
|
888
|
+
* serves no instance kind never enters it.
|
|
889
|
+
*/
|
|
890
|
+
var PENDING = /* @__PURE__ */ new Set();
|
|
891
|
+
/**
|
|
892
|
+
* An addon's boot is about to read the registry for its rows. From now on, until the registry
|
|
893
|
+
* answers, its served instance kinds (already built or built later in its boot) fail closed. A
|
|
894
|
+
* helper used with no addon boot around it (a spec, a tool) is never held back.
|
|
895
|
+
*/
|
|
896
|
+
function beginHydration(ownerId) {
|
|
897
|
+
if (ANSWERED.has(ownerId)) return;
|
|
898
|
+
HYDRATING.add(ownerId);
|
|
899
|
+
if (KINDS.has(ownerId)) PENDING.add(ownerId);
|
|
900
|
+
}
|
|
901
|
+
/** The helper of `ownerId` serves `id`: its fail-closed window is that owner's, not the process's. */
|
|
902
|
+
function claimInstance(ownerId, id) {
|
|
903
|
+
OWNER_OF.set(id, ownerId);
|
|
904
|
+
}
|
|
905
|
+
/** Whether `ownerId` still waits for the registry to answer (it serves a kind and has no rows yet). */
|
|
906
|
+
function isHydrationPending(ownerId) {
|
|
907
|
+
return PENDING.has(ownerId);
|
|
908
|
+
}
|
|
909
|
+
/**
|
|
910
|
+
* The switch of `id` as this process knows it. An id nobody stated reads off while ITS owner waits
|
|
911
|
+
* for the registry, on afterwards (a fresh instance). An id with no known owner reads off while any
|
|
912
|
+
* owner waits.
|
|
913
|
+
*/
|
|
914
|
+
function isInstanceOn(id) {
|
|
915
|
+
const stated = SWITCHES.get(id);
|
|
916
|
+
if (stated !== void 0) return stated;
|
|
917
|
+
const owner = OWNER_OF.get(id);
|
|
918
|
+
return owner === void 0 ? PENDING.size === 0 : !PENDING.has(owner);
|
|
919
|
+
}
|
|
920
|
+
/** Record a state this process holds for `id` (a local mirror; the registry may not have a row yet). */
|
|
921
|
+
function recordInstanceSwitch(id, enabled) {
|
|
922
|
+
SWITCHES.set(id, enabled);
|
|
923
|
+
}
|
|
924
|
+
/** Record what the hub told: the registry holds a row of `id` in this state. */
|
|
925
|
+
function recordRegistrySwitch(id, enabled) {
|
|
926
|
+
SWITCHES.set(id, enabled);
|
|
927
|
+
ROWS.add(id);
|
|
928
|
+
}
|
|
929
|
+
/** Whether the registry is known to hold a row for `id`. */
|
|
930
|
+
function hasRegistryRow(id) {
|
|
931
|
+
return ROWS.has(id);
|
|
932
|
+
}
|
|
933
|
+
/** The state this process holds for `id`, or undefined when it holds none. */
|
|
934
|
+
function statedInstanceSwitch(id) {
|
|
935
|
+
return SWITCHES.get(id);
|
|
936
|
+
}
|
|
937
|
+
/** Forget `id` (the instance was deleted). */
|
|
938
|
+
function forgetInstanceSwitch(id) {
|
|
939
|
+
SWITCHES.delete(id);
|
|
940
|
+
ROWS.delete(id);
|
|
941
|
+
OWNER_OF.delete(id);
|
|
942
|
+
}
|
|
943
|
+
/** Seed the store from the registry rows of `ownerId`; the registry answered, so the owner is known. */
|
|
944
|
+
function hydrateInstanceSwitches(ownerId, rows) {
|
|
945
|
+
ANSWERED.add(ownerId);
|
|
946
|
+
for (const row of rows) {
|
|
947
|
+
recordRegistrySwitch(row.id, row.enabled);
|
|
948
|
+
OWNER_OF.set(row.id, ownerId);
|
|
949
|
+
}
|
|
950
|
+
}
|
|
951
|
+
/** The addon's boot has built every instance kind and read the registry: unknown ids now read on. */
|
|
952
|
+
function settleHydration(ownerId) {
|
|
953
|
+
PENDING.delete(ownerId);
|
|
954
|
+
}
|
|
955
|
+
var KINDS = /* @__PURE__ */ new Map();
|
|
956
|
+
/**
|
|
957
|
+
* A helper announces the kind it serves, by owner addon. The one-time body-to-registry move
|
|
958
|
+
* (D1066) walks exactly these kinds, so an addon needs no list of its own: a record kind IS an
|
|
959
|
+
* instance kind precisely when a helper wraps it.
|
|
960
|
+
*/
|
|
961
|
+
function registerServedInstanceKind(ownerId, served) {
|
|
962
|
+
const owned = KINDS.get(ownerId) ?? /* @__PURE__ */ new Map();
|
|
963
|
+
owned.set(served.kind.name, served);
|
|
964
|
+
KINDS.set(ownerId, owned);
|
|
965
|
+
if (HYDRATING.has(ownerId) && !ANSWERED.has(ownerId)) PENDING.add(ownerId);
|
|
966
|
+
}
|
|
967
|
+
/** The instance kinds announced for `ownerId` so far. */
|
|
968
|
+
function servedInstanceKindsOf(ownerId) {
|
|
969
|
+
return [...KINDS.get(ownerId)?.values() ?? []];
|
|
970
|
+
}
|
|
971
|
+
/** Lookup map for well-known tabs by ID. */
|
|
972
|
+
var WELL_KNOWN_TAB_MAP = /* @__PURE__ */ Object.fromEntries(/* @__PURE__ */ [
|
|
973
|
+
{
|
|
974
|
+
id: "overview",
|
|
975
|
+
label: "Overview",
|
|
976
|
+
icon: "layout-dashboard",
|
|
977
|
+
order: -10
|
|
978
|
+
},
|
|
979
|
+
{
|
|
980
|
+
id: "general",
|
|
981
|
+
label: "General",
|
|
982
|
+
icon: "settings",
|
|
983
|
+
order: 0
|
|
984
|
+
},
|
|
985
|
+
{
|
|
986
|
+
id: "image",
|
|
987
|
+
label: "Image",
|
|
988
|
+
icon: "image",
|
|
989
|
+
order: 5
|
|
990
|
+
},
|
|
991
|
+
{
|
|
992
|
+
id: "light",
|
|
993
|
+
label: "Light",
|
|
994
|
+
icon: "lightbulb",
|
|
995
|
+
order: 7
|
|
996
|
+
},
|
|
997
|
+
{
|
|
998
|
+
id: "motion",
|
|
999
|
+
label: "Motion",
|
|
1000
|
+
icon: "activity",
|
|
1001
|
+
order: 10
|
|
1002
|
+
},
|
|
1003
|
+
{
|
|
1004
|
+
id: "audio",
|
|
1005
|
+
label: "Audio",
|
|
1006
|
+
icon: "mic",
|
|
1007
|
+
order: 12
|
|
1008
|
+
},
|
|
1009
|
+
{
|
|
1010
|
+
id: "alarms",
|
|
1011
|
+
label: "Alarms",
|
|
1012
|
+
icon: "bell-ring",
|
|
1013
|
+
order: 13
|
|
1014
|
+
},
|
|
1015
|
+
{
|
|
1016
|
+
id: "snapshot",
|
|
1017
|
+
label: "Snapshot",
|
|
1018
|
+
icon: "camera",
|
|
1019
|
+
order: 15
|
|
1020
|
+
},
|
|
1021
|
+
{
|
|
1022
|
+
id: "osd",
|
|
1023
|
+
label: "OSD",
|
|
1024
|
+
icon: "type",
|
|
1025
|
+
order: 18
|
|
1026
|
+
},
|
|
1027
|
+
{
|
|
1028
|
+
id: "stream-broker",
|
|
1029
|
+
label: "Stream Broker",
|
|
1030
|
+
icon: "radio",
|
|
1031
|
+
order: 20
|
|
1032
|
+
},
|
|
1033
|
+
{
|
|
1034
|
+
id: "streaming",
|
|
1035
|
+
label: "Streaming",
|
|
1036
|
+
icon: "video",
|
|
1037
|
+
order: 35
|
|
1038
|
+
},
|
|
1039
|
+
{
|
|
1040
|
+
id: "ptz",
|
|
1041
|
+
label: "PTZ",
|
|
1042
|
+
icon: "move",
|
|
1043
|
+
order: 40
|
|
1044
|
+
},
|
|
1045
|
+
{
|
|
1046
|
+
id: "navigation",
|
|
1047
|
+
label: "Navigation",
|
|
1048
|
+
icon: "compass",
|
|
1049
|
+
order: 41
|
|
1050
|
+
},
|
|
1051
|
+
{
|
|
1052
|
+
id: "consumables",
|
|
1053
|
+
label: "Consumables",
|
|
1054
|
+
icon: "recycle",
|
|
1055
|
+
order: 44
|
|
1056
|
+
},
|
|
1057
|
+
{
|
|
1058
|
+
id: "pipeline",
|
|
1059
|
+
label: "Detection Pipeline",
|
|
1060
|
+
icon: "cpu",
|
|
1061
|
+
order: 39
|
|
1062
|
+
},
|
|
1063
|
+
{
|
|
1064
|
+
id: "detection-pipeline",
|
|
1065
|
+
label: "Detection pipeline",
|
|
1066
|
+
icon: "cpu",
|
|
1067
|
+
order: 39
|
|
1068
|
+
},
|
|
1069
|
+
{
|
|
1070
|
+
id: "zones",
|
|
1071
|
+
label: "Detection",
|
|
1072
|
+
icon: "shapes",
|
|
1073
|
+
order: 38
|
|
1074
|
+
},
|
|
1075
|
+
{
|
|
1076
|
+
id: "analytics",
|
|
1077
|
+
label: "Analytics",
|
|
1078
|
+
icon: "activity",
|
|
1079
|
+
order: 37
|
|
1080
|
+
},
|
|
1081
|
+
{
|
|
1082
|
+
id: "live-stats",
|
|
1083
|
+
label: "Live Stats",
|
|
1084
|
+
icon: "activity",
|
|
1085
|
+
order: 39
|
|
1086
|
+
},
|
|
1087
|
+
{
|
|
1088
|
+
id: "recording",
|
|
1089
|
+
label: "Recording",
|
|
1090
|
+
icon: "circle-dot",
|
|
1091
|
+
order: 40
|
|
1092
|
+
},
|
|
1093
|
+
{
|
|
1094
|
+
id: "engine",
|
|
1095
|
+
label: "Inference Engine",
|
|
1096
|
+
icon: "zap",
|
|
1097
|
+
order: 41
|
|
1098
|
+
},
|
|
1099
|
+
{
|
|
1100
|
+
id: "scheduler",
|
|
1101
|
+
label: "Scheduler",
|
|
1102
|
+
icon: "list-checks",
|
|
1103
|
+
order: 42
|
|
1104
|
+
},
|
|
1105
|
+
{
|
|
1106
|
+
id: "decoder",
|
|
1107
|
+
label: "Decoder",
|
|
1108
|
+
icon: "film",
|
|
1109
|
+
order: 43
|
|
1110
|
+
},
|
|
1111
|
+
{
|
|
1112
|
+
id: "notifications",
|
|
1113
|
+
label: "Notifications",
|
|
1114
|
+
icon: "bell",
|
|
1115
|
+
order: 50
|
|
1116
|
+
},
|
|
1117
|
+
{
|
|
1118
|
+
id: "network",
|
|
1119
|
+
label: "Network",
|
|
1120
|
+
icon: "globe",
|
|
1121
|
+
order: 60
|
|
1122
|
+
},
|
|
1123
|
+
{
|
|
1124
|
+
id: "storage",
|
|
1125
|
+
label: "Storage",
|
|
1126
|
+
icon: "hard-drive",
|
|
1127
|
+
order: 70
|
|
1128
|
+
},
|
|
1129
|
+
{
|
|
1130
|
+
id: "advanced",
|
|
1131
|
+
label: "Advanced",
|
|
1132
|
+
icon: "wrench",
|
|
1133
|
+
order: 100
|
|
1134
|
+
}
|
|
1135
|
+
].map((t) => [t.id, t]));
|
|
1136
|
+
/**
|
|
1137
|
+
* Field types that never carry a value (separator, info, button). Used by
|
|
1138
|
+
* `hydrateSchema` to skip the `value` injection for structural-only fields.
|
|
1139
|
+
*/
|
|
1140
|
+
function isValuelessField(field) {
|
|
1141
|
+
return field.type === "separator" || field.type === "info" || field.type === "qr-code" || field.type === "button" || field.type === "object-array" || field.type === "widget" || field.type === "addon-action-button" || field.type === "device-action-button" || field.type === "account-sign-in" || field.type === "secret-presence";
|
|
1142
|
+
}
|
|
1143
|
+
/**
|
|
1144
|
+
* Base collector: flatten a hydrated `ConfigUISchemaWithValues` into
|
|
1145
|
+
* `key → { value, default }`, recursing through `group` and `sub-tabs`
|
|
1146
|
+
* layout fields. Keeping `value` and `default` SEPARATE (rather than
|
|
1147
|
+
* pre-resolving) lets callers both read the effective value AND detect
|
|
1148
|
+
* overrides (`value` differs from `default`). Structural over `unknown`;
|
|
1149
|
+
* malformed input yields an empty map, never throws.
|
|
1150
|
+
*/
|
|
1151
|
+
function collectHydratedFieldEntries(schema) {
|
|
1152
|
+
const out = /* @__PURE__ */ new Map();
|
|
1153
|
+
if (typeof schema !== "object" || schema === null) return out;
|
|
1154
|
+
const sections = schema.sections;
|
|
1155
|
+
if (!Array.isArray(sections)) return out;
|
|
1156
|
+
for (const section of sections) if (typeof section === "object" && section !== null) collectFieldEntriesInto(section.fields, out);
|
|
1157
|
+
return out;
|
|
1158
|
+
}
|
|
1159
|
+
/** Recursive field walker for {@link collectHydratedFieldEntries}. */
|
|
1160
|
+
function collectFieldEntriesInto(fields, into) {
|
|
1161
|
+
if (!Array.isArray(fields)) return;
|
|
1162
|
+
for (const field of fields) {
|
|
1163
|
+
if (typeof field !== "object" || field === null) continue;
|
|
1164
|
+
const type = field.type;
|
|
1165
|
+
if (type === "group") {
|
|
1166
|
+
collectFieldEntriesInto(field.fields, into);
|
|
1167
|
+
continue;
|
|
1168
|
+
}
|
|
1169
|
+
if (type === "sub-tabs") {
|
|
1170
|
+
const tabs = field.tabs;
|
|
1171
|
+
if (Array.isArray(tabs)) {
|
|
1172
|
+
for (const tab of tabs) if (typeof tab === "object" && tab !== null) collectFieldEntriesInto(tab.fields, into);
|
|
1173
|
+
}
|
|
1174
|
+
continue;
|
|
1175
|
+
}
|
|
1176
|
+
const key = field.key;
|
|
1177
|
+
if (typeof key !== "string" || key.length === 0) continue;
|
|
1178
|
+
if (!("value" in field)) continue;
|
|
1179
|
+
into.set(key, {
|
|
1180
|
+
value: field.value,
|
|
1181
|
+
default: field.default
|
|
1182
|
+
});
|
|
1183
|
+
}
|
|
1184
|
+
}
|
|
1185
|
+
/**
|
|
1186
|
+
* Flatten a hydrated settings payload into `key → EFFECTIVE value`
|
|
1187
|
+
* (`value ?? default`). The read-side inverse of `hydrateSchema` for the
|
|
1188
|
+
* common "just give me the resolved values" case. Built on
|
|
1189
|
+
* {@link collectHydratedFieldEntries}.
|
|
1190
|
+
*/
|
|
1191
|
+
function collectHydratedFieldValues(schema) {
|
|
1192
|
+
const out = /* @__PURE__ */ new Map();
|
|
1193
|
+
for (const [key, entry] of collectHydratedFieldEntries(schema)) out.set(key, entry.value ?? entry.default);
|
|
1194
|
+
return out;
|
|
1195
|
+
}
|
|
1196
|
+
function hydrateSchema(schema, values, options = {}) {
|
|
1197
|
+
return {
|
|
1198
|
+
...schema.tabs ? { tabs: [...schema.tabs] } : {},
|
|
1199
|
+
sections: schema.sections.map((section) => ({
|
|
1200
|
+
...section,
|
|
1201
|
+
fields: section.fields.map((field) => hydrateField(field, values, options))
|
|
1202
|
+
}))
|
|
1203
|
+
};
|
|
1204
|
+
}
|
|
1205
|
+
function hydrateField(field, values, options) {
|
|
1206
|
+
if (isValuelessField(field)) return field;
|
|
1207
|
+
if (field.type === "group") {
|
|
1208
|
+
const hydratedChildren = field.fields.map((child) => hydrateField(child, values, options));
|
|
1209
|
+
return {
|
|
1210
|
+
...field,
|
|
1211
|
+
fields: hydratedChildren
|
|
1212
|
+
};
|
|
1213
|
+
}
|
|
1214
|
+
if (field.type === "sub-tabs") {
|
|
1215
|
+
const hydratedTabs = field.tabs.map((tab) => ({
|
|
1216
|
+
...tab,
|
|
1217
|
+
fields: tab.fields.map((child) => hydrateField(child, values, options))
|
|
1218
|
+
}));
|
|
1219
|
+
return {
|
|
1220
|
+
...field,
|
|
1221
|
+
tabs: hydratedTabs
|
|
1222
|
+
};
|
|
1223
|
+
}
|
|
1224
|
+
const key = field.key;
|
|
1225
|
+
const storedValue = Object.prototype.hasOwnProperty.call(values, key) ? values[key] : void 0;
|
|
1226
|
+
const defaultValue = field.default;
|
|
1227
|
+
const asView = (v) => isSecretMarker(v) || options.inlineSecretsAsViews === true && v !== void 0;
|
|
1228
|
+
if (isKeychainStoredField(field) && asView(storedValue)) return {
|
|
1229
|
+
...field,
|
|
1230
|
+
value: toSecretFieldView(storedValue)
|
|
1231
|
+
};
|
|
1232
|
+
if (isKeychainStoredField(field) && options.inlineSecretsAsViews === true) return {
|
|
1233
|
+
...field,
|
|
1234
|
+
value: null
|
|
1235
|
+
};
|
|
1236
|
+
if (field.type === "editable-array" && Array.isArray(storedValue)) {
|
|
1237
|
+
const secretItemKeys = field.itemFields.filter((item) => "key" in item && isKeychainStoredField(item)).map((item) => "key" in item ? item.key : "");
|
|
1238
|
+
if (secretItemKeys.length > 0) {
|
|
1239
|
+
const rows = storedValue.map((row) => {
|
|
1240
|
+
if (row === null || typeof row !== "object" || Array.isArray(row)) return row;
|
|
1241
|
+
const out = { ...row };
|
|
1242
|
+
for (const k of secretItemKeys) {
|
|
1243
|
+
const v = Reflect.get(row, k);
|
|
1244
|
+
if (asView(v)) out[k] = toSecretFieldView(v);
|
|
1245
|
+
}
|
|
1246
|
+
return out;
|
|
1247
|
+
});
|
|
1248
|
+
return {
|
|
1249
|
+
...field,
|
|
1250
|
+
value: rows
|
|
1251
|
+
};
|
|
1252
|
+
}
|
|
1253
|
+
}
|
|
1254
|
+
if (field.multiple) {
|
|
1255
|
+
const stored = Array.isArray(storedValue) ? storedValue : storedValue !== void 0 && storedValue !== null ? [storedValue] : [];
|
|
1256
|
+
const itemFallback = field.multiple.itemDefault !== void 0 ? field.multiple.itemDefault : defaultValue !== void 0 ? defaultValue : typeOf(field) === "string" ? "" : null;
|
|
1257
|
+
const minCount = Math.max(field.multiple.min, stored.length);
|
|
1258
|
+
const items = [];
|
|
1259
|
+
for (let i = 0; i < minCount; i++) items.push(i < stored.length ? stored[i] : itemFallback);
|
|
1260
|
+
return {
|
|
1261
|
+
...field,
|
|
1262
|
+
value: items
|
|
1263
|
+
};
|
|
1264
|
+
}
|
|
1265
|
+
const rawValue = storedValue !== void 0 ? storedValue : defaultValue !== void 0 ? defaultValue : null;
|
|
1266
|
+
const value = field.type === "textarea" && field.isJson && rawValue !== null && typeof rawValue === "object" ? JSON.stringify(rawValue, null, 2) : rawValue;
|
|
1267
|
+
if (field.type === "tags" && typeof field.suggestionsFrom === "string") {
|
|
1268
|
+
const from = values[field.suggestionsFrom];
|
|
1269
|
+
const extra = Array.isArray(from) ? from.filter((s) => typeof s === "string" && s.length > 0) : [];
|
|
1270
|
+
const merged = [...new Set([...field.suggestions ?? [], ...extra])];
|
|
1271
|
+
return {
|
|
1272
|
+
...field,
|
|
1273
|
+
suggestions: merged,
|
|
1274
|
+
value
|
|
1275
|
+
};
|
|
1276
|
+
}
|
|
1277
|
+
if ((field.type === "select" || field.type === "multiselect") && typeof field.optionsFrom === "string") {
|
|
1278
|
+
const from = values[field.optionsFrom];
|
|
1279
|
+
const byValue = /* @__PURE__ */ new Map();
|
|
1280
|
+
for (const opt of field.options) byValue.set(opt.value, opt);
|
|
1281
|
+
if (Array.isArray(from)) for (const entry of from) {
|
|
1282
|
+
if (typeof entry === "string" && entry.length > 0) {
|
|
1283
|
+
if (!byValue.has(entry)) byValue.set(entry, {
|
|
1284
|
+
value: entry,
|
|
1285
|
+
label: entry
|
|
1286
|
+
});
|
|
1287
|
+
continue;
|
|
1288
|
+
}
|
|
1289
|
+
if (entry === null || typeof entry !== "object") continue;
|
|
1290
|
+
const v = Reflect.get(entry, "value");
|
|
1291
|
+
const lbl = Reflect.get(entry, "label");
|
|
1292
|
+
if (typeof v !== "string" || v.length === 0) continue;
|
|
1293
|
+
if (!byValue.has(v)) byValue.set(v, {
|
|
1294
|
+
value: v,
|
|
1295
|
+
label: typeof lbl === "string" && lbl.length > 0 ? lbl : v
|
|
1296
|
+
});
|
|
1297
|
+
}
|
|
1298
|
+
return {
|
|
1299
|
+
...field,
|
|
1300
|
+
options: [...byValue.values()],
|
|
1301
|
+
value
|
|
1302
|
+
};
|
|
1303
|
+
}
|
|
1304
|
+
return {
|
|
1305
|
+
...field,
|
|
1306
|
+
value
|
|
1307
|
+
};
|
|
1308
|
+
}
|
|
1309
|
+
/**
|
|
1310
|
+
* Rough "value family" classifier used by `hydrateField`'s multiple
|
|
1311
|
+
* fallback to pick a sensible zero-value when no `itemDefault` / no
|
|
1312
|
+
* field `default` / no stored value is available.
|
|
1313
|
+
*/
|
|
1314
|
+
function typeOf(field) {
|
|
1315
|
+
switch (field.type) {
|
|
1316
|
+
case "text":
|
|
1317
|
+
case "textarea":
|
|
1318
|
+
case "password":
|
|
1319
|
+
case "color":
|
|
1320
|
+
case "probe":
|
|
1321
|
+
case "timezone":
|
|
1322
|
+
case "datetime": return "string";
|
|
1323
|
+
case "number":
|
|
1324
|
+
case "slider": return "number";
|
|
1325
|
+
case "boolean": return "boolean";
|
|
1326
|
+
default: return "other";
|
|
1327
|
+
}
|
|
1328
|
+
}
|
|
1329
|
+
//#endregion
|
|
1330
|
+
//#region ../types/dist/esm/interfaces/event-bus.mjs
|
|
1331
|
+
/**
|
|
1332
|
+
* Narrow a SystemEvent to a typed event by checking its category.
|
|
1333
|
+
* Returns `true` (and narrows the type) if the category matches.
|
|
1334
|
+
*
|
|
1335
|
+
* @example
|
|
1336
|
+
* ```typescript
|
|
1337
|
+
* eventBus.subscribe({ category: 'addon.started' }, (event) => {
|
|
1338
|
+
* if (isEvent(event, 'addon.started')) {
|
|
1339
|
+
* event.data.addonId // ✓ typed as string
|
|
1340
|
+
* }
|
|
1341
|
+
* })
|
|
1342
|
+
* ```
|
|
1343
|
+
*/
|
|
1344
|
+
function isEvent(event, category) {
|
|
1345
|
+
return event.category === category;
|
|
1346
|
+
}
|
|
1347
|
+
/**
|
|
1348
|
+
* Create a typed event with less boilerplate.
|
|
1349
|
+
*
|
|
1350
|
+
* @example
|
|
1351
|
+
* ```typescript
|
|
1352
|
+
* eventBus.emit(createEvent('addon.started', { type: 'addon', id: 'pipeline' }, {
|
|
1353
|
+
* addonId: 'pipeline',
|
|
1354
|
+
* packageVersion: '0.1.8',
|
|
1355
|
+
* }))
|
|
1356
|
+
* ```
|
|
1357
|
+
*/
|
|
1358
|
+
function createEvent(category, source, data) {
|
|
1359
|
+
return {
|
|
1360
|
+
id: typeof crypto !== "undefined" && crypto.randomUUID ? crypto.randomUUID() : Math.random().toString(36).slice(2),
|
|
1361
|
+
timestamp: /* @__PURE__ */ new Date(),
|
|
1362
|
+
source,
|
|
1363
|
+
category,
|
|
1364
|
+
data
|
|
1365
|
+
};
|
|
1366
|
+
}
|
|
1367
|
+
/**
|
|
1368
|
+
* Emit a `system.ready-state` event for a capability. Caller supplies a
|
|
1369
|
+
* per-process `generation` string — stable across a single process
|
|
1370
|
+
* lifetime, changes on restart — which consumer-side registries use to
|
|
1371
|
+
* derive a monotonic `epoch` without requiring the emitter to
|
|
1372
|
+
* coordinate.
|
|
1373
|
+
*/
|
|
1374
|
+
function emitReadiness(bus, params) {
|
|
1375
|
+
const ts = params.ts ?? Date.now();
|
|
1376
|
+
bus.emit(createEvent("system.ready-state", {
|
|
1377
|
+
type: "capability",
|
|
1378
|
+
id: params.capName,
|
|
1379
|
+
nodeId: params.sourceNodeId
|
|
1380
|
+
}, {
|
|
1381
|
+
capName: params.capName,
|
|
1382
|
+
scope: params.scope,
|
|
1383
|
+
state: params.state,
|
|
1384
|
+
generation: params.generation,
|
|
1385
|
+
sourceNodeId: params.sourceNodeId,
|
|
1386
|
+
ts
|
|
1387
|
+
}));
|
|
1388
|
+
}
|
|
1389
|
+
//#endregion
|
|
1390
|
+
//#region ../types/dist/esm/migrations/addon-migration.mjs
|
|
1391
|
+
/** Why a catalogue entry is not a runnable body of its declared kind. */
|
|
1392
|
+
var AddonMigrationDefinitionError = class extends Error {
|
|
1393
|
+
id;
|
|
1394
|
+
constructor(id, message) {
|
|
1395
|
+
super(`${id}: ${message}`);
|
|
1396
|
+
this.id = id;
|
|
1397
|
+
this.name = "AddonMigrationDefinitionError";
|
|
1398
|
+
}
|
|
1399
|
+
};
|
|
1400
|
+
/**
|
|
1401
|
+
* Bind a catalogue to the addon's ports. Throws {@link AddonMigrationDefinitionError} when
|
|
1402
|
+
* an entry's `bodyKind` does not match the body it carries, or is `sql` (a hub-only
|
|
1403
|
+
* body). A throwing body never escapes `execute`: it is reported as a failed result.
|
|
1404
|
+
*/
|
|
1405
|
+
function defineAddonMigrations(catalogue, ports) {
|
|
1406
|
+
return catalogue.map((entry) => {
|
|
1407
|
+
const { meta } = entry;
|
|
1408
|
+
if ("plan" in entry) {
|
|
1409
|
+
if (meta.bodyKind !== "plan") throw new AddonMigrationDefinitionError(meta.id, `carries a plan body but declares "${meta.bodyKind}"`);
|
|
1410
|
+
return {
|
|
1411
|
+
meta,
|
|
1412
|
+
execute: () => guarded(async () => ({
|
|
1413
|
+
kind: "plan",
|
|
1414
|
+
plan: await entry.plan(ports)
|
|
1415
|
+
}))
|
|
1416
|
+
};
|
|
1417
|
+
}
|
|
1418
|
+
if (meta.bodyKind !== "procedure") throw new AddonMigrationDefinitionError(meta.id, `carries a procedure body but declares "${meta.bodyKind}"`);
|
|
1419
|
+
return {
|
|
1420
|
+
meta,
|
|
1421
|
+
execute: () => guarded(async () => ({
|
|
1422
|
+
kind: "procedure",
|
|
1423
|
+
result: await entry.procedure(ports)
|
|
1424
|
+
}))
|
|
1425
|
+
};
|
|
1426
|
+
});
|
|
1427
|
+
}
|
|
1428
|
+
async function guarded(work) {
|
|
1429
|
+
try {
|
|
1430
|
+
return await work();
|
|
1431
|
+
} catch (err) {
|
|
1432
|
+
return {
|
|
1433
|
+
kind: "failed",
|
|
1434
|
+
error: errMsg(err)
|
|
1435
|
+
};
|
|
1436
|
+
}
|
|
1437
|
+
}
|
|
1438
|
+
var NOT_RUN = {
|
|
1439
|
+
declared: false,
|
|
1440
|
+
snapshot: null,
|
|
1441
|
+
applied: [],
|
|
1442
|
+
failed: [],
|
|
1443
|
+
blocked: [],
|
|
1444
|
+
skipped: [],
|
|
1445
|
+
blockOwner: []
|
|
1446
|
+
};
|
|
1447
|
+
/**
|
|
1448
|
+
* Offer `migrations` to the engine and run what it says to run, in its order. Never
|
|
1449
|
+
* throws: an unreachable or refusing engine is logged and reported `declared: false`,
|
|
1450
|
+
* because the hub (and this addon's boot) must not hang on a migration.
|
|
1451
|
+
*/
|
|
1452
|
+
async function runAddonMigrations(host, migrations, logger, options = {}) {
|
|
1453
|
+
const first = migrations[0];
|
|
1454
|
+
if (first === void 0) return NOT_RUN;
|
|
1455
|
+
const owner = first.meta.owner;
|
|
1456
|
+
const log = logger.withTags({ migrationOwner: owner });
|
|
1457
|
+
const byId = new Map(migrations.map((m) => [m.meta.id, m]));
|
|
1458
|
+
let declaration;
|
|
1459
|
+
try {
|
|
1460
|
+
declaration = await host.declareOwner({
|
|
1461
|
+
owner,
|
|
1462
|
+
metas: migrations.map((m) => m.meta),
|
|
1463
|
+
...options.retired === void 0 ? {} : { retired: [...options.retired] }
|
|
1464
|
+
});
|
|
1465
|
+
} catch (err) {
|
|
1466
|
+
log.error("the migration engine refused or could not take this addon catalogue — none ran", { meta: { error: errMsg(err) } });
|
|
1467
|
+
return {
|
|
1468
|
+
...NOT_RUN,
|
|
1469
|
+
blockOwner: migrations.filter((m) => m.meta.onFailure === "block-owner").map((m) => m.meta.id)
|
|
1470
|
+
};
|
|
1471
|
+
}
|
|
1472
|
+
const applied = [];
|
|
1473
|
+
const failed = [];
|
|
1474
|
+
const blocked = [];
|
|
1475
|
+
const skipped = [];
|
|
1476
|
+
const settle = (id, status) => {
|
|
1477
|
+
if (status === "applied") applied.push(id);
|
|
1478
|
+
else if (status === "failed") failed.push(id);
|
|
1479
|
+
else if (status === "blocked") blocked.push(id);
|
|
1480
|
+
else skipped.push(id);
|
|
1481
|
+
};
|
|
1482
|
+
const selected = options.only === void 0 ? null : new Set(options.only);
|
|
1483
|
+
const deferred = /* @__PURE__ */ new Set();
|
|
1484
|
+
const deferredBy = (reason) => {
|
|
1485
|
+
if (selected === null || reason === null) return null;
|
|
1486
|
+
const dep = /^dependency-(?:pending|blocked):(.+)$/.exec(reason)?.[1];
|
|
1487
|
+
if (dep === void 0 || !byId.has(dep)) return null;
|
|
1488
|
+
return !selected.has(dep) || deferred.has(dep) ? dep : null;
|
|
1489
|
+
};
|
|
1490
|
+
for (const step of declaration.steps) {
|
|
1491
|
+
if (selected !== null && !selected.has(step.id)) continue;
|
|
1492
|
+
const bound = byId.get(step.id);
|
|
1493
|
+
if (bound === void 0 || step.action === "skip") {
|
|
1494
|
+
skipped.push(step.id);
|
|
1495
|
+
continue;
|
|
1496
|
+
}
|
|
1497
|
+
const tags = { migrationId: step.id };
|
|
1498
|
+
try {
|
|
1499
|
+
const gate = await host.startMigration({ id: step.id });
|
|
1500
|
+
if (!gate.proceed) {
|
|
1501
|
+
const waitsFor = deferredBy(gate.reason);
|
|
1502
|
+
if (waitsFor !== null) {
|
|
1503
|
+
log.info("migration deferred: its predecessor runs in another phase of this owner", {
|
|
1504
|
+
tags,
|
|
1505
|
+
meta: {
|
|
1506
|
+
waitsFor,
|
|
1507
|
+
reason: gate.reason
|
|
1508
|
+
}
|
|
1509
|
+
});
|
|
1510
|
+
deferred.add(step.id);
|
|
1511
|
+
skipped.push(step.id);
|
|
1512
|
+
continue;
|
|
1513
|
+
}
|
|
1514
|
+
log.warn("migration not run", {
|
|
1515
|
+
tags,
|
|
1516
|
+
meta: {
|
|
1517
|
+
state: gate.state,
|
|
1518
|
+
reason: gate.reason
|
|
1519
|
+
}
|
|
1520
|
+
});
|
|
1521
|
+
settle(step.id, gate.state === "pending" ? "blocked" : gate.state);
|
|
1522
|
+
continue;
|
|
1523
|
+
}
|
|
1524
|
+
const result = await bound.execute();
|
|
1525
|
+
const outcome = await host.finishMigration({
|
|
1526
|
+
id: step.id,
|
|
1527
|
+
result
|
|
1528
|
+
});
|
|
1529
|
+
if (outcome.status === "applied") log.info("migration applied", {
|
|
1530
|
+
tags,
|
|
1531
|
+
meta: { rowsChanged: outcome.rowsChanged }
|
|
1532
|
+
});
|
|
1533
|
+
else log.error("migration failed", {
|
|
1534
|
+
tags,
|
|
1535
|
+
meta: { error: outcome.error }
|
|
1536
|
+
});
|
|
1537
|
+
settle(step.id, outcome.status);
|
|
1538
|
+
} catch (err) {
|
|
1539
|
+
log.error("migration could not be completed with the engine", {
|
|
1540
|
+
tags,
|
|
1541
|
+
meta: { error: errMsg(err) }
|
|
1542
|
+
});
|
|
1543
|
+
failed.push(step.id);
|
|
1544
|
+
}
|
|
1545
|
+
}
|
|
1546
|
+
const blockOwner = [...failed, ...blocked].filter((id) => byId.get(id)?.meta.onFailure === "block-owner");
|
|
1547
|
+
return {
|
|
1548
|
+
declared: true,
|
|
1549
|
+
snapshot: declaration.snapshot,
|
|
1550
|
+
applied,
|
|
1551
|
+
failed,
|
|
1552
|
+
blocked,
|
|
1553
|
+
skipped,
|
|
1554
|
+
blockOwner
|
|
1555
|
+
};
|
|
1556
|
+
}
|
|
1557
|
+
//#endregion
|
|
1558
|
+
//#region ../types/dist/esm/migrations/api/migration-api-ports.mjs
|
|
1559
|
+
/** The record calls the one-switch migration makes, over the migration API. */
|
|
1560
|
+
function switchRecordsOverMigrationApi(api) {
|
|
1561
|
+
return { kind: (definition) => {
|
|
1562
|
+
const handle = api.records.kind(definition);
|
|
1563
|
+
return {
|
|
1564
|
+
get: (id) => handle.get({ id }),
|
|
1565
|
+
put: (input, opts) => handle.put({
|
|
1566
|
+
...input,
|
|
1567
|
+
...opts?.ifRev === void 0 ? {} : { ifRev: opts.ifRev }
|
|
1568
|
+
}),
|
|
1569
|
+
patch: (id, partial) => handle.patch({
|
|
1570
|
+
id,
|
|
1571
|
+
partial
|
|
1572
|
+
})
|
|
1573
|
+
};
|
|
1574
|
+
} };
|
|
1575
|
+
}
|
|
1576
|
+
/** The record calls the body-to-registry switch migration makes, over the migration API. */
|
|
1577
|
+
function bodySwitchRecordsOverMigrationApi(api) {
|
|
1578
|
+
return { kind: (definition) => {
|
|
1579
|
+
const handle = api.records.kind(definition);
|
|
1580
|
+
return {
|
|
1581
|
+
query: async () => {
|
|
1582
|
+
const rows = [];
|
|
1583
|
+
let cursor;
|
|
1584
|
+
do {
|
|
1585
|
+
const page = await handle.query({
|
|
1586
|
+
limit: 500,
|
|
1587
|
+
...cursor === void 0 ? {} : { cursor }
|
|
1588
|
+
});
|
|
1589
|
+
rows.push(...page.records);
|
|
1590
|
+
cursor = page.nextCursor ?? void 0;
|
|
1591
|
+
} while (cursor !== void 0);
|
|
1592
|
+
return { records: rows };
|
|
1593
|
+
},
|
|
1594
|
+
get: (id) => handle.get({ id }),
|
|
1595
|
+
put: (input, opts) => handle.put({
|
|
1596
|
+
...input,
|
|
1597
|
+
...opts?.ifRev === void 0 ? {} : { ifRev: opts.ifRev }
|
|
1598
|
+
})
|
|
1599
|
+
};
|
|
1600
|
+
} };
|
|
1601
|
+
}
|
|
1602
|
+
function integrationRowsApiOver(api) {
|
|
1603
|
+
return {
|
|
1604
|
+
list: async () => (await api.integrations.list({})).integrations,
|
|
1605
|
+
readLegacyIntegrationRows: (input) => api.legacyRows.read(input),
|
|
1606
|
+
clearLegacyIntegrationRows: (input) => api.legacyRows.clear(input)
|
|
1607
|
+
};
|
|
1608
|
+
}
|
|
1609
|
+
//#endregion
|
|
1610
|
+
//#region ../types/dist/esm/addon/instance-link-meta.mjs
|
|
1611
|
+
/**
|
|
1612
|
+
* A link that may stay empty (absent): for a link the addon fills itself, or one an instance does not
|
|
1613
|
+
* always need. The meta rides on the optional wrapper, where {@link linksOfKind} reads it.
|
|
1614
|
+
*/
|
|
1615
|
+
function optionalLinkField(target) {
|
|
1616
|
+
return z.string().optional().meta({ link: target });
|
|
1617
|
+
}
|
|
1618
|
+
function linkTargetOf(meta) {
|
|
1619
|
+
if (typeof meta !== "object" || meta === null) return void 0;
|
|
1620
|
+
const link = Reflect.get(meta, "link");
|
|
1621
|
+
const parsed = LinkTargetSchema.safeParse(link);
|
|
1622
|
+
return parsed.success ? parsed.data : void 0;
|
|
1623
|
+
}
|
|
1624
|
+
var LinkTargetSchema = /* @__PURE__ */ z.object({
|
|
1625
|
+
cap: /* @__PURE__ */ z.string().min(1),
|
|
1626
|
+
kind: /* @__PURE__ */ z.string().min(1).optional()
|
|
1627
|
+
});
|
|
1628
|
+
/** The links a kind declares, read from the meta of its body fields. */
|
|
1629
|
+
function linksOfKind(kind) {
|
|
1630
|
+
const schema = kind.schema;
|
|
1631
|
+
if (!(schema instanceof z.ZodObject)) return [];
|
|
1632
|
+
const links = [];
|
|
1633
|
+
for (const [field, fieldSchema] of Object.entries(schema.shape)) {
|
|
1634
|
+
const to = linkTargetOf(z.globalRegistry.get(fieldSchema));
|
|
1635
|
+
if (to !== void 0) links.push({
|
|
1636
|
+
field,
|
|
1637
|
+
to
|
|
1638
|
+
});
|
|
1639
|
+
}
|
|
1640
|
+
return links;
|
|
1641
|
+
}
|
|
1642
|
+
//#endregion
|
|
1643
|
+
//#region ../types/dist/esm/records/secret-views.mjs
|
|
1644
|
+
/**
|
|
1645
|
+
* A stored secret, as an admin read shows it: a VIEW naming the row's own
|
|
1646
|
+
* keychain ref (`set: true`), never the value and no longer the bare redaction
|
|
1647
|
+
* token. The form hands it to the secret field, which reveals the value by ref
|
|
1648
|
+
* through the audited `keychain-admin.reveal`; sent back untouched it keeps the
|
|
1649
|
+
* stored secret (the records door reads a view as KEEP).
|
|
1650
|
+
*
|
|
1651
|
+
* ONE implementation for the entries service and for every addon that serves
|
|
1652
|
+
* its own instances (`RecordIntegrationInstances`).
|
|
1653
|
+
*/
|
|
1654
|
+
function isRecord$2(value) {
|
|
1655
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1656
|
+
}
|
|
1657
|
+
function secretViewsOf(owner, kind, id, decl, data) {
|
|
1658
|
+
if (decl.secretPaths.length === 0) return data;
|
|
1659
|
+
const shown = mapSecretLeaves(data, decl.secretPaths, decl.secretArrayKeys, (leaf) => {
|
|
1660
|
+
if (leaf.value !== "__camstack_redacted__") return leaf.value;
|
|
1661
|
+
return {
|
|
1662
|
+
$secret: recordSecretRef(owner, kind, id, leaf.concrete),
|
|
1663
|
+
v: 1,
|
|
1664
|
+
set: true
|
|
1665
|
+
};
|
|
1666
|
+
});
|
|
1667
|
+
return isRecord$2(shown) ? shown : data;
|
|
1668
|
+
}
|
|
1669
|
+
//#endregion
|
|
1670
|
+
//#region ../types/dist/esm/addon/record-integration-instances.mjs
|
|
1671
|
+
/** The most instances one addon lists (an integrations page, not a table). */
|
|
1672
|
+
var INSTANCES_LIST_MAX = 1e3;
|
|
1673
|
+
/**
|
|
1674
|
+
* The body key the switch USED to live under (D1007, D1015). Nothing writes or reads it any more;
|
|
1675
|
+
* the migrations that move it between the body and the registry name it.
|
|
1676
|
+
*/
|
|
1677
|
+
var SWITCH_KEY = "enabled";
|
|
1678
|
+
/**
|
|
1679
|
+
* The "Add device" mode an instance gets when its provider states none, from how the provider's
|
|
1680
|
+
* devices are found: `lan` scans, `account` adopts the account's children, anything else is manual.
|
|
1681
|
+
* The one place this default lives.
|
|
1682
|
+
*/
|
|
1683
|
+
function defaultAddDeviceMode(description) {
|
|
1684
|
+
switch (description.discovery?.mode) {
|
|
1685
|
+
case "lan": return "scan";
|
|
1686
|
+
case "account": return "children";
|
|
1687
|
+
default: return "none";
|
|
1688
|
+
}
|
|
1689
|
+
}
|
|
1690
|
+
/** The keys of the kind's secret fields that sit at the top level of the body. */
|
|
1691
|
+
function topLevelSecretKeys(paths) {
|
|
1692
|
+
return new Set(paths.filter((p) => !p.includes(".") && !p.includes("[") && !p.includes("{")));
|
|
1693
|
+
}
|
|
1694
|
+
/** The keys of the kind's top-level MAPS whose values are secrets (`applianceSecrets{}`). */
|
|
1695
|
+
function secretMapKeys(paths) {
|
|
1696
|
+
return new Set(paths.filter((p) => p.endsWith("{}") && !p.slice(0, -2).match(/[.[{]/)).map((p) => p.slice(0, -2)));
|
|
1697
|
+
}
|
|
1698
|
+
/**
|
|
1699
|
+
* A patch value for a map of secrets: an entry that is omitted, `''`, the redaction token or the
|
|
1700
|
+
* view the form was given KEEPS its stored secret (it is left out of the merge); `{ $secretClear }`
|
|
1701
|
+
* or `null` removes the entry; any other string replaces it. Null when nothing is left to merge.
|
|
1702
|
+
*/
|
|
1703
|
+
function secretMapPatch(value) {
|
|
1704
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
|
|
1705
|
+
const out = {};
|
|
1706
|
+
for (const [key, entry] of Object.entries(value)) if (entry === null || isSecretClear(entry)) out[key] = null;
|
|
1707
|
+
else if (typeof entry === "string" && entry !== "" && entry !== "__camstack_redacted__" && !isSecretFieldView(entry)) out[key] = entry;
|
|
1708
|
+
return Object.keys(out).length > 0 ? out : null;
|
|
1709
|
+
}
|
|
1710
|
+
var RecordIntegrationInstances = class {
|
|
1711
|
+
records;
|
|
1712
|
+
kind;
|
|
1713
|
+
hooks;
|
|
1714
|
+
handle;
|
|
1715
|
+
secretKeys;
|
|
1716
|
+
secretMaps;
|
|
1717
|
+
nameField;
|
|
1718
|
+
/** The state each instance had when the addon last read it or was told it: {@link reapply} announces only a change. */
|
|
1719
|
+
knownSwitches = /* @__PURE__ */ new Map();
|
|
1720
|
+
/** What the addon reads for `id`: the switch as this process holds it, remembered as known. */
|
|
1721
|
+
knownSwitchOf(id) {
|
|
1722
|
+
claimInstance(this.records.owner, id);
|
|
1723
|
+
const enabled = isInstanceOn(id);
|
|
1724
|
+
this.knownSwitches.set(id, enabled);
|
|
1725
|
+
return enabled;
|
|
1726
|
+
}
|
|
1727
|
+
/** What a view of `id` shows; the addon did not read it, so nothing is remembered as known. */
|
|
1728
|
+
viewSwitchOf(id) {
|
|
1729
|
+
claimInstance(this.records.owner, id);
|
|
1730
|
+
return isInstanceOn(id);
|
|
1731
|
+
}
|
|
1732
|
+
switchListeners = /* @__PURE__ */ new Set();
|
|
1733
|
+
constructor(records, kind, hooks) {
|
|
1734
|
+
this.records = records;
|
|
1735
|
+
this.kind = kind;
|
|
1736
|
+
this.hooks = hooks;
|
|
1737
|
+
this.handle = records.kind(kind);
|
|
1738
|
+
this.secretKeys = topLevelSecretKeys(kind.declaration.secretPaths);
|
|
1739
|
+
this.secretMaps = secretMapKeys(kind.declaration.secretPaths);
|
|
1740
|
+
this.nameField = kind.declaration.entry?.nameField ?? "name";
|
|
1741
|
+
registerServedInstanceKind(records.owner, {
|
|
1742
|
+
kind,
|
|
1743
|
+
reapply: () => this.reapply(),
|
|
1744
|
+
unrowed: () => this.unrowed()
|
|
1745
|
+
});
|
|
1746
|
+
if (hooks.kindOf === void 0 && hooks.description.kinds.length !== 1) throw new Error(`record kind '${kind.name}': describe().kinds has ${hooks.description.kinds.length} entries, so kindOf is required to say which one an instance is`);
|
|
1747
|
+
}
|
|
1748
|
+
/**
|
|
1749
|
+
* One instance read for the addon's own runtime; null when absent. When the keychain is
|
|
1750
|
+
* locked the row is served WITHOUT its secrets and says so (`secrets: 'unavailable'`), so the
|
|
1751
|
+
* caller can keep what it had instead of reconfiguring with an empty secret (D49).
|
|
1752
|
+
*/
|
|
1753
|
+
async readResolved(id) {
|
|
1754
|
+
try {
|
|
1755
|
+
const record = await this.handle.getResolved(id);
|
|
1756
|
+
return record === null ? null : {
|
|
1757
|
+
id,
|
|
1758
|
+
body: record.data,
|
|
1759
|
+
enabled: this.knownSwitchOf(id),
|
|
1760
|
+
secrets: "resolved"
|
|
1761
|
+
};
|
|
1762
|
+
} catch (err) {
|
|
1763
|
+
if (!(err instanceof RecordSecretUnavailableError)) throw err;
|
|
1764
|
+
const stored = await this.handle.get(id);
|
|
1765
|
+
if (stored === null) return null;
|
|
1766
|
+
return {
|
|
1767
|
+
id,
|
|
1768
|
+
body: Object.fromEntries(Object.entries(stored.data).filter(([key]) => !this.secretKeys.has(key))),
|
|
1769
|
+
enabled: this.knownSwitchOf(id),
|
|
1770
|
+
secrets: "unavailable"
|
|
1771
|
+
};
|
|
1772
|
+
}
|
|
1773
|
+
}
|
|
1774
|
+
/** The body of {@link readResolved} alone; a locked keychain yields the row without secrets. */
|
|
1775
|
+
async getResolved(id) {
|
|
1776
|
+
return (await this.readResolved(id))?.body ?? null;
|
|
1777
|
+
}
|
|
1778
|
+
/** Every instance, secrets resolved where the keychain allows; an absent one is skipped. */
|
|
1779
|
+
async listResolved() {
|
|
1780
|
+
const page = await this.handle.query({ limit: INSTANCES_LIST_MAX });
|
|
1781
|
+
const out = [];
|
|
1782
|
+
for (const record of page.records) {
|
|
1783
|
+
const read = await this.readResolved(record.id);
|
|
1784
|
+
if (read !== null) out.push(read);
|
|
1785
|
+
}
|
|
1786
|
+
return out;
|
|
1787
|
+
}
|
|
1788
|
+
/** The kind an instance body is of: the provider's `kindOf`, else its one declared kind. */
|
|
1789
|
+
kindOfBody(body) {
|
|
1790
|
+
if (this.hooks.kindOf !== void 0) {
|
|
1791
|
+
const id = this.hooks.kindOf(body);
|
|
1792
|
+
if (!this.hooks.description.kinds.some((declared) => declared.id === id)) throw new Error(`record kind '${this.kind.name}': kindOf returned '${id}', which describe().kinds does not declare`);
|
|
1793
|
+
return id;
|
|
1794
|
+
}
|
|
1795
|
+
const only = this.hooks.description.kinds[0];
|
|
1796
|
+
if (only === void 0) throw new Error(`record kind '${this.kind.name}' declares no kinds`);
|
|
1797
|
+
return only.id;
|
|
1798
|
+
}
|
|
1799
|
+
viewOf(record) {
|
|
1800
|
+
const shown = secretViewsOf(this.records.owner, this.kind.name, record.id, this.kind.declaration, record.data);
|
|
1801
|
+
const rawName = record.data[this.nameField];
|
|
1802
|
+
const kind = this.kindOfBody(record.data);
|
|
1803
|
+
const health = this.hooks.health?.(record.data, record.id);
|
|
1804
|
+
return {
|
|
1805
|
+
id: record.id,
|
|
1806
|
+
name: typeof rawName === "string" ? rawName : record.id,
|
|
1807
|
+
configured: this.hooks.configured(record.data),
|
|
1808
|
+
enabled: this.viewSwitchOf(record.id),
|
|
1809
|
+
formValues: shown,
|
|
1810
|
+
kind,
|
|
1811
|
+
addDevice: this.hooks.addDevice?.(record.data) ?? defaultAddDeviceMode(this.hooks.description),
|
|
1812
|
+
...health?.status !== void 0 ? { status: health.status } : {},
|
|
1813
|
+
...health?.lastCheckedAt !== void 0 ? { lastCheckedAt: health.lastCheckedAt } : {}
|
|
1814
|
+
};
|
|
1815
|
+
}
|
|
1816
|
+
describe = async () => {
|
|
1817
|
+
const declared = linksOfKind(this.kind);
|
|
1818
|
+
const links = this.hooks.description.links !== void 0 || declared.length === 0 ? {} : { links: declared.map((link) => ({
|
|
1819
|
+
kind: this.kind.name,
|
|
1820
|
+
field: link.field,
|
|
1821
|
+
to: link.to
|
|
1822
|
+
})) };
|
|
1823
|
+
const wired = this.hooks.test !== void 0;
|
|
1824
|
+
const stated = this.hooks.description;
|
|
1825
|
+
return {
|
|
1826
|
+
...stated,
|
|
1827
|
+
...stated.canTest && !wired ? { canTest: false } : {},
|
|
1828
|
+
...stated.kinds === void 0 ? {} : { kinds: stated.kinds.map((kind) => kind.canTest === true && !wired ? {
|
|
1829
|
+
...kind,
|
|
1830
|
+
canTest: false
|
|
1831
|
+
} : kind) },
|
|
1832
|
+
...links,
|
|
1833
|
+
...this.hooks.mintId === void 0 ? {} : { mintsId: true }
|
|
1834
|
+
};
|
|
1835
|
+
};
|
|
1836
|
+
instanceFormSchema = async ({ id }) => this.hooks.formSchema(id);
|
|
1837
|
+
listInstances = async () => {
|
|
1838
|
+
return (await this.handle.query({ limit: INSTANCES_LIST_MAX })).records.map((record) => this.viewOf(record));
|
|
1839
|
+
};
|
|
1840
|
+
getInstance = async ({ id }) => {
|
|
1841
|
+
const record = await this.handle.get(id);
|
|
1842
|
+
return record === null ? null : this.viewOf(record);
|
|
1843
|
+
};
|
|
1844
|
+
/** Insert ONE row (`ifRev: 0`: an existing id is refused, never overwritten). */
|
|
1845
|
+
createInstance = async ({ id, name, kind, values }) => {
|
|
1846
|
+
const minted = id ?? this.hooks.mintId?.({
|
|
1847
|
+
name,
|
|
1848
|
+
...kind !== void 0 ? { kind } : {}
|
|
1849
|
+
});
|
|
1850
|
+
if (minted === void 0) throw new Error("createInstance needs an id: this provider does not mint one");
|
|
1851
|
+
const initial = this.hooks.initialBody(name, kind);
|
|
1852
|
+
const patch = this.patchOf(values ?? {});
|
|
1853
|
+
if (Object.keys(patch).length > 0) Object.assign(patch, await this.hooks.validateWrite?.({
|
|
1854
|
+
kind,
|
|
1855
|
+
body: {
|
|
1856
|
+
...initial,
|
|
1857
|
+
...patch
|
|
1858
|
+
}
|
|
1859
|
+
}));
|
|
1860
|
+
await this.handle.put({
|
|
1861
|
+
id: minted,
|
|
1862
|
+
data: initial
|
|
1863
|
+
}, { ifRev: 0 });
|
|
1864
|
+
claimInstance(this.records.owner, minted);
|
|
1865
|
+
recordRegistrySwitch(minted, true);
|
|
1866
|
+
if (Object.keys(patch).length > 0) await this.handle.patch(minted, patch);
|
|
1867
|
+
await this.hooks.onChanged?.(minted, "created");
|
|
1868
|
+
return { id: minted };
|
|
1869
|
+
};
|
|
1870
|
+
updateInstance = async ({ id, name, values }) => {
|
|
1871
|
+
const patch = this.patchOf(values);
|
|
1872
|
+
if (this.hooks.validateWrite !== void 0 && Object.keys(patch).length > 0) {
|
|
1873
|
+
const stored = await this.handle.get(id);
|
|
1874
|
+
if (stored !== null) Object.assign(patch, await this.hooks.validateWrite({
|
|
1875
|
+
kind: void 0,
|
|
1876
|
+
body: {
|
|
1877
|
+
...stored.data,
|
|
1878
|
+
...patch
|
|
1879
|
+
}
|
|
1880
|
+
}));
|
|
1881
|
+
}
|
|
1882
|
+
if (name !== void 0) patch[this.nameField] = name;
|
|
1883
|
+
await this.handle.patch(id, patch);
|
|
1884
|
+
await this.hooks.onChanged?.(id, "updated");
|
|
1885
|
+
return { ok: true };
|
|
1886
|
+
};
|
|
1887
|
+
/** The record patch a form `values` object means: secrets kept, cleared or replaced. */
|
|
1888
|
+
patchOf(values) {
|
|
1889
|
+
const patch = {};
|
|
1890
|
+
for (const [key, value] of Object.entries(values)) {
|
|
1891
|
+
if (value === void 0) continue;
|
|
1892
|
+
if (key === "enabled") continue;
|
|
1893
|
+
if (this.secretMaps.has(key)) {
|
|
1894
|
+
const entries = secretMapPatch(value);
|
|
1895
|
+
if (entries !== null) patch[key] = entries;
|
|
1896
|
+
} else if (!this.secretKeys.has(key)) patch[key] = value;
|
|
1897
|
+
else if (isSecretClear(value)) patch[key] = null;
|
|
1898
|
+
else if (typeof value === "string" && value !== "" && value !== "__camstack_redacted__" && !isSecretFieldView(value)) patch[key] = value;
|
|
1899
|
+
}
|
|
1900
|
+
return patch;
|
|
1901
|
+
}
|
|
1902
|
+
/**
|
|
1903
|
+
* Listen to the switch of ANY instance of this helper (in the process that serves it). The
|
|
1904
|
+
* durable replacement of the `integration.enabled` / `integration.disabled` events (D8): the
|
|
1905
|
+
* addon reconciles from the record, whichever way it flipped.
|
|
1906
|
+
*/
|
|
1907
|
+
onSwitched(listener) {
|
|
1908
|
+
this.switchListeners.add(listener);
|
|
1909
|
+
}
|
|
1910
|
+
/**
|
|
1911
|
+
* The hub's notification that the registry row of `id` moved (D1066). The registry holds the
|
|
1912
|
+
* switch; this keeps NO copy of it in the record. It remembers the state for this process's
|
|
1913
|
+
* readers ({@link isInstanceOn}), lets the addon re-apply, and fires the listeners.
|
|
1914
|
+
*/
|
|
1915
|
+
setInstanceEnabled = async ({ id, enabled }) => {
|
|
1916
|
+
claimInstance(this.records.owner, id);
|
|
1917
|
+
recordRegistrySwitch(id, enabled);
|
|
1918
|
+
this.knownSwitches.set(id, enabled);
|
|
1919
|
+
await this.hooks.onChanged?.(id, "enabled");
|
|
1920
|
+
for (const listener of this.switchListeners) await listener(id, enabled);
|
|
1921
|
+
return { ok: true };
|
|
1922
|
+
};
|
|
1923
|
+
/**
|
|
1924
|
+
* After the registry answered for a kind built before it could: announce the state of every
|
|
1925
|
+
* instance of this kind, on and off, so an addon that started on the fail-closed default (off)
|
|
1926
|
+
* starts what is on and stops what is off.
|
|
1927
|
+
*/
|
|
1928
|
+
async reapply() {
|
|
1929
|
+
const page = await this.handle.query({ limit: INSTANCES_LIST_MAX });
|
|
1930
|
+
for (const record of page.records) {
|
|
1931
|
+
claimInstance(this.records.owner, record.id);
|
|
1932
|
+
const enabled = isInstanceOn(record.id);
|
|
1933
|
+
if (this.knownSwitches.get(record.id) === enabled) continue;
|
|
1934
|
+
this.knownSwitches.set(record.id, enabled);
|
|
1935
|
+
await this.hooks.onChanged?.(record.id, "enabled");
|
|
1936
|
+
for (const listener of this.switchListeners) await listener(record.id, enabled);
|
|
1937
|
+
}
|
|
1938
|
+
}
|
|
1939
|
+
/**
|
|
1940
|
+
* The records of this kind the registry holds no row for: created outside the hub door (a
|
|
1941
|
+
* seed, a migration, a store write). Each carries the state this process holds for it, on when
|
|
1942
|
+
* it holds none, because on was its effective state before the registry owned the switch.
|
|
1943
|
+
*/
|
|
1944
|
+
async unrowed() {
|
|
1945
|
+
return (await this.handle.query({ limit: INSTANCES_LIST_MAX })).records.filter((record) => !hasRegistryRow(record.id)).map((record) => {
|
|
1946
|
+
const name = record.data[this.nameField];
|
|
1947
|
+
return {
|
|
1948
|
+
id: record.id,
|
|
1949
|
+
name: typeof name === "string" ? name : record.id,
|
|
1950
|
+
enabled: statedInstanceSwitch(record.id) ?? true
|
|
1951
|
+
};
|
|
1952
|
+
});
|
|
1953
|
+
}
|
|
1954
|
+
/** The row and its keychain refs go together (the records door). */
|
|
1955
|
+
deleteInstance = async ({ id }) => {
|
|
1956
|
+
await this.handle.delete(id);
|
|
1957
|
+
forgetInstanceSwitch(id);
|
|
1958
|
+
await this.hooks.onChanged?.(id, "deleted");
|
|
1959
|
+
return { ok: true };
|
|
1960
|
+
};
|
|
1961
|
+
testInstance = async (input) => {
|
|
1962
|
+
if (this.hooks.test === void 0) return {
|
|
1963
|
+
success: false,
|
|
1964
|
+
status: "unsupported",
|
|
1965
|
+
error: "This integration declares no connection test"
|
|
1966
|
+
};
|
|
1967
|
+
return this.hooks.test(input);
|
|
1968
|
+
};
|
|
1969
|
+
/** The flat provider object to hand to `registerProvider`. */
|
|
1970
|
+
toProvider() {
|
|
1971
|
+
return {
|
|
1972
|
+
describe: this.describe,
|
|
1973
|
+
instanceFormSchema: this.instanceFormSchema,
|
|
1974
|
+
listInstances: this.listInstances,
|
|
1975
|
+
getInstance: this.getInstance,
|
|
1976
|
+
createInstance: this.createInstance,
|
|
1977
|
+
updateInstance: this.updateInstance,
|
|
1978
|
+
setInstanceEnabled: this.setInstanceEnabled,
|
|
1979
|
+
deleteInstance: this.deleteInstance,
|
|
1980
|
+
testInstance: this.testInstance
|
|
1981
|
+
};
|
|
1982
|
+
}
|
|
1983
|
+
};
|
|
1984
|
+
//#endregion
|
|
1985
|
+
//#region ../types/dist/esm/migrations/registry-switch-to-body.mjs
|
|
1986
|
+
/**
|
|
1987
|
+
* The one-switch migration (epic #440, step 3). An integration's on/off state used to live in the
|
|
1988
|
+
* registry's `enabled` column for a device addon; it now lives only in the instance record's
|
|
1989
|
+
* body (`enabled`, D1007 superseded). This moves a registry `enabled = false` into the body, once.
|
|
1990
|
+
*
|
|
1991
|
+
* For every registry row of the addon that is OFF:
|
|
1992
|
+
* - no record under its id: the record is created from `initialBody(name)` with `enabled: false`
|
|
1993
|
+
* (a default integration that never had settings, Reolink's among them);
|
|
1994
|
+
* - a record whose body states no `enabled`: `enabled: false` is written into it;
|
|
1995
|
+
* - a record that already states `enabled` (either way) is the newer truth and is left alone.
|
|
1996
|
+
* A row that is ON writes nothing: an absent field reads as on. A rerun finds every off row with
|
|
1997
|
+
* a stated switch and does nothing, so nothing switched off comes back on and nothing switched on
|
|
1998
|
+
* goes off. The registry column itself is neither read afterwards nor written; its drop is step 5.
|
|
1999
|
+
*
|
|
2000
|
+
* It runs in the addon process, BEFORE the addon registers its `integration-instances` provider,
|
|
2001
|
+
* which is also why `integrations.list` still answers the stored column at that point.
|
|
2002
|
+
*/
|
|
2003
|
+
function registrySwitchToBodyId(addonId, date) {
|
|
2004
|
+
return `${addonId}/${date}-registry-switch-to-body`;
|
|
2005
|
+
}
|
|
2006
|
+
async function moveRegistrySwitchToBody(ports, spec) {
|
|
2007
|
+
const rows = await ports.listIntegrations(spec.addonId);
|
|
2008
|
+
let created = 0;
|
|
2009
|
+
let switched = 0;
|
|
2010
|
+
let kept = 0;
|
|
2011
|
+
for (const row of rows) {
|
|
2012
|
+
if (row.enabled) continue;
|
|
2013
|
+
const body = await ports.readBody(row.id);
|
|
2014
|
+
if (body === null) {
|
|
2015
|
+
if (await ports.createRecord(row.id, {
|
|
2016
|
+
...spec.initialBody(row.name),
|
|
2017
|
+
["enabled"]: false
|
|
2018
|
+
}) === "created") created += 1;
|
|
2019
|
+
else kept += 1;
|
|
2020
|
+
continue;
|
|
2021
|
+
}
|
|
2022
|
+
if ("enabled" in body) {
|
|
2023
|
+
kept += 1;
|
|
2024
|
+
continue;
|
|
2025
|
+
}
|
|
2026
|
+
await ports.switchOff(row.id);
|
|
2027
|
+
switched += 1;
|
|
2028
|
+
}
|
|
2029
|
+
const summary = {
|
|
2030
|
+
integrations: rows.length,
|
|
2031
|
+
off: rows.filter((r) => !r.enabled).length,
|
|
2032
|
+
created,
|
|
2033
|
+
switched,
|
|
2034
|
+
kept
|
|
2035
|
+
};
|
|
2036
|
+
return created === 0 && switched === 0 ? {
|
|
2037
|
+
outcome: "already-done",
|
|
2038
|
+
summary
|
|
2039
|
+
} : {
|
|
2040
|
+
outcome: "done",
|
|
2041
|
+
summary
|
|
2042
|
+
};
|
|
2043
|
+
}
|
|
2044
|
+
/** A migration entry: an addon states its kind and how a new body starts, nothing else. */
|
|
2045
|
+
function registrySwitchToBodyMigration(spec) {
|
|
2046
|
+
return {
|
|
2047
|
+
meta: {
|
|
2048
|
+
id: registrySwitchToBodyId(spec.addonId, spec.date),
|
|
2049
|
+
owner: spec.addonId,
|
|
2050
|
+
level: "addon-state",
|
|
2051
|
+
seq: spec.seq,
|
|
2052
|
+
dependsOn: [],
|
|
2053
|
+
store: "settings",
|
|
2054
|
+
scope: "cluster",
|
|
2055
|
+
onFailure: "block-owner",
|
|
2056
|
+
bodyKind: "procedure",
|
|
2057
|
+
description: "Move the registry enabled flag of every switched-off integration into its instance record body, creating the record when there is none",
|
|
2058
|
+
fixtureMark: "enabled"
|
|
2059
|
+
},
|
|
2060
|
+
procedure: (ports) => moveRegistrySwitchToBody(ports, {
|
|
2061
|
+
addonId: spec.addonId,
|
|
2062
|
+
initialBody: spec.initialBody
|
|
2063
|
+
})
|
|
2064
|
+
};
|
|
2065
|
+
}
|
|
2066
|
+
/** The hub and records sides of {@link registrySwitchToBodyMigration}. */
|
|
2067
|
+
function registrySwitchPortsOver(deps) {
|
|
2068
|
+
const handle = deps.records.kind({
|
|
2069
|
+
name: deps.kind.name,
|
|
2070
|
+
declaration: deps.kind.declaration,
|
|
2071
|
+
schema: z.record(z.string(), z.unknown())
|
|
2072
|
+
});
|
|
2073
|
+
return {
|
|
2074
|
+
listIntegrations: async (addonId) => (await deps.api.list()).filter((i) => i.addonId === addonId).map((i) => ({
|
|
2075
|
+
id: i.id,
|
|
2076
|
+
name: i.name,
|
|
2077
|
+
enabled: i.enabled !== false
|
|
2078
|
+
})),
|
|
2079
|
+
readBody: async (id) => (await handle.get(id))?.data ?? null,
|
|
2080
|
+
createRecord: async (id, body) => {
|
|
2081
|
+
if (await handle.get(id) !== null) return "exists";
|
|
2082
|
+
await handle.put({
|
|
2083
|
+
id,
|
|
2084
|
+
data: body
|
|
2085
|
+
}, { ifRev: 0 });
|
|
2086
|
+
return "created";
|
|
2087
|
+
},
|
|
2088
|
+
switchOff: async (id) => {
|
|
2089
|
+
await handle.patch(id, { [SWITCH_KEY]: false });
|
|
2090
|
+
}
|
|
2091
|
+
};
|
|
2092
|
+
}
|
|
2093
|
+
//#endregion
|
|
2094
|
+
//#region ../types/dist/esm/migrations/body-switch-to-registry.mjs
|
|
2095
|
+
/**
|
|
2096
|
+
* The switch comes back to the registry (D1066), the reverse of {@link registrySwitchToBodyMigration}.
|
|
2097
|
+
* An instance's on/off state lived in its record body (`enabled`, D1007 superseded by D1015); the hub
|
|
2098
|
+
* registry row, keyed by (addon, integration id) like a device, is now the only stored switch.
|
|
2099
|
+
*
|
|
2100
|
+
* For every record of the addon's kind:
|
|
2101
|
+
* - the state is the body's `enabled` (absent means on). When the registry row of that id disagrees,
|
|
2102
|
+
* the BODY wins: it was the only live copy while the body held the switch, and the registry
|
|
2103
|
+
* column of a migrated row was never read;
|
|
2104
|
+
* - a record with no registry row gets one (a services instance, under its addon-minted id);
|
|
2105
|
+
* - the key is then removed from the body, so no second copy remains.
|
|
2106
|
+
* A rerun finds no body that states `enabled` and writes nothing. The registry write goes first, so
|
|
2107
|
+
* a crash between the two steps repeats the pair (idempotent) and never loses a switched-off state.
|
|
2108
|
+
*
|
|
2109
|
+
* It runs in the addon process, after {@link registrySwitchToBodyMigration}, BEFORE the addon
|
|
2110
|
+
* registers its provider.
|
|
2111
|
+
*/
|
|
2112
|
+
function bodySwitchToRegistryId(addonId, date, kindName) {
|
|
2113
|
+
return `${addonId}/${date}-body-switch-to-registry-${kindName}`;
|
|
2114
|
+
}
|
|
2115
|
+
async function moveBodySwitchToRegistry(ports, spec) {
|
|
2116
|
+
const records = await ports.listRecords();
|
|
2117
|
+
const adopted = records.length === 0 ? {
|
|
2118
|
+
created: 0,
|
|
2119
|
+
updated: 0,
|
|
2120
|
+
conflicts: []
|
|
2121
|
+
} : await ports.adoptRows(spec.addonId, records.map((r) => ({
|
|
2122
|
+
id: r.id,
|
|
2123
|
+
name: r.name,
|
|
2124
|
+
enabled: r.enabled,
|
|
2125
|
+
stated: r.stated
|
|
2126
|
+
})));
|
|
2127
|
+
const foreign = new Map(adopted.conflicts.map((c) => [c.id, c.ownerAddonId]));
|
|
2128
|
+
for (const [id, owner] of foreign) await ports.warn(`body switch kept: the registry row "${id}" belongs to addon "${owner}", not "${spec.addonId}"`);
|
|
2129
|
+
const stated = records.filter((r) => r.stated && !foreign.has(r.id));
|
|
2130
|
+
for (const row of stated) await ports.stripSwitch(row.id);
|
|
2131
|
+
const summary = {
|
|
2132
|
+
records: records.length,
|
|
2133
|
+
stripped: stated.length,
|
|
2134
|
+
rowsCreated: adopted.created,
|
|
2135
|
+
rowsCorrected: adopted.updated,
|
|
2136
|
+
conflicts: adopted.conflicts.length
|
|
2137
|
+
};
|
|
2138
|
+
return stated.length === 0 && adopted.created === 0 && adopted.updated === 0 ? {
|
|
2139
|
+
outcome: "already-done",
|
|
2140
|
+
summary
|
|
2141
|
+
} : {
|
|
2142
|
+
outcome: "done",
|
|
2143
|
+
summary
|
|
2144
|
+
};
|
|
2145
|
+
}
|
|
2146
|
+
/** A migration entry: an addon states its kind, nothing else. */
|
|
2147
|
+
function bodySwitchToRegistryMigration(spec) {
|
|
2148
|
+
return {
|
|
2149
|
+
meta: {
|
|
2150
|
+
id: bodySwitchToRegistryId(spec.addonId, spec.date, spec.kindName),
|
|
2151
|
+
owner: spec.addonId,
|
|
2152
|
+
level: "addon-state",
|
|
2153
|
+
seq: spec.seq,
|
|
2154
|
+
dependsOn: spec.followsDate === void 0 ? [] : [registrySwitchToBodyId(spec.addonId, spec.followsDate)],
|
|
2155
|
+
store: "settings",
|
|
2156
|
+
scope: "cluster",
|
|
2157
|
+
onFailure: "block-owner",
|
|
2158
|
+
bodyKind: "procedure",
|
|
2159
|
+
description: "Move the switch of every instance record back to its registry row (creating the row of a services instance) and remove it from the body",
|
|
2160
|
+
fixtureMark: "enabled"
|
|
2161
|
+
},
|
|
2162
|
+
procedure: (ports) => moveBodySwitchToRegistry(ports, { addonId: spec.addonId })
|
|
2163
|
+
};
|
|
2164
|
+
}
|
|
2165
|
+
function bodySwitchPortsOver(deps) {
|
|
2166
|
+
const handle = deps.records.kind({
|
|
2167
|
+
name: deps.kind.name,
|
|
2168
|
+
declaration: deps.kind.declaration,
|
|
2169
|
+
schema: z.record(z.string(), z.unknown())
|
|
2170
|
+
});
|
|
2171
|
+
return {
|
|
2172
|
+
listRecords: async () => {
|
|
2173
|
+
return (await handle.query({ limit: 1e3 })).records.map((r) => {
|
|
2174
|
+
const name = r.data[deps.nameField];
|
|
2175
|
+
return {
|
|
2176
|
+
id: r.id,
|
|
2177
|
+
name: typeof name === "string" ? name : r.id,
|
|
2178
|
+
enabled: r.data[SWITCH_KEY] !== false,
|
|
2179
|
+
stated: SWITCH_KEY in r.data
|
|
2180
|
+
};
|
|
2181
|
+
});
|
|
2182
|
+
},
|
|
2183
|
+
adoptRows: deps.adopt,
|
|
2184
|
+
warn: deps.warn,
|
|
2185
|
+
stripSwitch: async (id) => {
|
|
2186
|
+
const row = await handle.get(id);
|
|
2187
|
+
if (row === null || !("enabled" in row.data)) return;
|
|
2188
|
+
const { [SWITCH_KEY]: _dropped, ...rest } = row.data;
|
|
2189
|
+
await handle.put({
|
|
2190
|
+
id,
|
|
2191
|
+
data: rest
|
|
2192
|
+
}, { ifRev: row.rev });
|
|
2193
|
+
}
|
|
2194
|
+
};
|
|
2195
|
+
}
|
|
2196
|
+
//#endregion
|
|
2197
|
+
//#region ../types/dist/esm/addon/durable-state.mjs
|
|
2198
|
+
/**
|
|
2199
|
+
* Build a {@link DurableState} over a single store key. Transport-agnostic:
|
|
2200
|
+
* `read`/`write` are the addon-store or device-store accessors. The whole
|
|
2201
|
+
* validated value round-trips on every read/write — the schema is the
|
|
2202
|
+
* single source of truth for what is persisted, so no hand-listed field
|
|
2203
|
+
* set can drop a key on save.
|
|
2204
|
+
*/
|
|
2205
|
+
function createDurableState(deps) {
|
|
2206
|
+
const get = async () => {
|
|
2207
|
+
const raw = (await deps.read())[deps.key];
|
|
2208
|
+
if (raw === void 0) return deps.fallback;
|
|
2209
|
+
const parsed = deps.schema.safeParse(raw);
|
|
2210
|
+
if (!parsed.success) {
|
|
2211
|
+
deps.onParseError?.(deps.key, parsed.error);
|
|
2212
|
+
return deps.fallback;
|
|
2213
|
+
}
|
|
2214
|
+
return parsed.data;
|
|
2215
|
+
};
|
|
2216
|
+
const set = async (next) => {
|
|
2217
|
+
const validated = deps.schema.parse(next);
|
|
2218
|
+
await deps.write({ [deps.key]: validated });
|
|
2219
|
+
};
|
|
2220
|
+
const update = async (fn) => {
|
|
2221
|
+
await set(fn(await get()));
|
|
2222
|
+
};
|
|
2223
|
+
return {
|
|
2224
|
+
get,
|
|
2225
|
+
set,
|
|
2226
|
+
update
|
|
2227
|
+
};
|
|
2228
|
+
}
|
|
2229
|
+
//#endregion
|
|
2230
|
+
//#region ../types/dist/esm/addon/instance-switches-unread-error.mjs
|
|
2231
|
+
/**
|
|
2232
|
+
* The registry could not be read for the switches of an addon that serves instance kinds, so its
|
|
2233
|
+
* instances read off (D1066). A forked runner treats it as a failed boot: the supervisor respawns
|
|
2234
|
+
* it, bounded and marked terminally failed (D6), rather than leave instances off silently.
|
|
2235
|
+
*/
|
|
2236
|
+
var INSTANCE_SWITCHES_UNREAD_ERROR_NAME = "InstanceSwitchesUnreadError";
|
|
2237
|
+
var InstanceSwitchesUnreadError = class extends Error {
|
|
2238
|
+
ownerId;
|
|
2239
|
+
constructor(ownerId) {
|
|
2240
|
+
super(`'${ownerId}': the registry did not answer for the instance switches; its instances stay off`);
|
|
2241
|
+
this.ownerId = ownerId;
|
|
2242
|
+
this.name = INSTANCE_SWITCHES_UNREAD_ERROR_NAME;
|
|
2243
|
+
}
|
|
2244
|
+
};
|
|
2245
|
+
//#endregion
|
|
2246
|
+
//#region ../types/dist/esm/addon/per-node-store.mjs
|
|
2247
|
+
/**
|
|
2248
|
+
* Per-node scoping for the shared addon-settings blob.
|
|
2249
|
+
*
|
|
2250
|
+
* An addon's settings store is hub-central (the `addon-settings` cap is
|
|
2251
|
+
* hub-routed — the hub instance answers for every node), so fields whose
|
|
2252
|
+
* value is a NODE fact (decoder backend, engine pick, probed hardware
|
|
2253
|
+
* capabilities) persist under the node-scoped key `<key>@<nodeId>` inside
|
|
2254
|
+
* the single shared blob. The SCHEMA field key stays bare: the write path
|
|
2255
|
+
* ({@link scopePatch}) maps the bare field onto the target node's scoped
|
|
2256
|
+
* key; the read/hydrate path ({@link projectStore}) maps THIS node's value
|
|
2257
|
+
* back, so UI forms and `resolveConfig` only ever see the bare key.
|
|
2258
|
+
*
|
|
2259
|
+
* Fields opt in via the `perNode: true` schema marker on `ConfigFieldBase`
|
|
2260
|
+
* (`interfaces/config-ui.ts`); `BaseAddon` derives the key set from the
|
|
2261
|
+
* schema and routes reads/writes through these helpers.
|
|
2262
|
+
*
|
|
2263
|
+
* ## No bare-key fallback — deliberate
|
|
2264
|
+
*
|
|
2265
|
+
* {@link readNodeValue} reads the node-scoped key ONLY. A node with no
|
|
2266
|
+
* scoped key resolves to `undefined` so the field's schema `default` wins —
|
|
2267
|
+
* NEVER `store[base]` and never another node's value. A bare legacy key in
|
|
2268
|
+
* the store is invisible to every node, hub included, so one node's
|
|
2269
|
+
* selection can never leak onto another. (This generalizes the
|
|
2270
|
+
* `decoder-backend-keys.ts` semantics — the no-fallback variant — over an
|
|
2271
|
+
* arbitrary set of per-node field keys.)
|
|
2272
|
+
*
|
|
2273
|
+
* Pure functions only — no I/O, no imports beyond the language. This is a
|
|
2274
|
+
* LEAF module: import it via its deep path, never from the root barrel.
|
|
2275
|
+
*/
|
|
2276
|
+
/**
|
|
2277
|
+
* Normalize a raw kernel node id to the bare node id used for scoping.
|
|
2278
|
+
* `localNodeId` can carry a `<node>/<addon>` suffix on forked child
|
|
2279
|
+
* processes; per-node settings are per-NODE, so strip the addon segment.
|
|
2280
|
+
* `undefined` / `null` / empty falls back to `'hub'`.
|
|
2281
|
+
*/
|
|
2282
|
+
function normalizeNodeId(raw) {
|
|
2283
|
+
if (raw === void 0 || raw === null || raw === "") return "hub";
|
|
2284
|
+
const slashIdx = raw.indexOf("/");
|
|
2285
|
+
if (slashIdx < 0) return raw;
|
|
2286
|
+
const bare = raw.slice(0, slashIdx);
|
|
2287
|
+
return bare === "" ? "hub" : bare;
|
|
2288
|
+
}
|
|
2289
|
+
/** The node-scoped store key for a per-node field: `<base>@<nodeId>`. */
|
|
2290
|
+
function nodeScopedKey(base, nodeId) {
|
|
2291
|
+
return `${base}@${normalizeNodeId(nodeId)}`;
|
|
2292
|
+
}
|
|
2293
|
+
/**
|
|
2294
|
+
* Read a node's value for a per-node field from the raw shared store:
|
|
2295
|
+
* the node-scoped key when present, otherwise `undefined`.
|
|
2296
|
+
* Deliberately NO bare-key fallback (see module doc) — the caller lets the
|
|
2297
|
+
* schema `default` win on `undefined`.
|
|
2298
|
+
*/
|
|
2299
|
+
function readNodeValue(store, base, nodeId) {
|
|
2300
|
+
return store[nodeScopedKey(base, nodeId)];
|
|
2301
|
+
}
|
|
2302
|
+
/**
|
|
2303
|
+
* Re-map a UI/settings patch so every bare perNode field persists under the
|
|
2304
|
+
* TARGET node's scoped key; all other keys pass through unchanged. Used on
|
|
2305
|
+
* the write path so a save for one node never clobbers another node's value
|
|
2306
|
+
* (and the bare key is never written). Returns a new object — the input
|
|
2307
|
+
* patch is not mutated.
|
|
2308
|
+
*/
|
|
2309
|
+
function scopePatch(patch, perNodeKeys, nodeId) {
|
|
2310
|
+
const out = {};
|
|
2311
|
+
for (const [key, value] of Object.entries(patch)) out[perNodeKeys.has(key) ? nodeScopedKey(key, nodeId) : key] = value;
|
|
2312
|
+
return out;
|
|
2313
|
+
}
|
|
2314
|
+
/**
|
|
2315
|
+
* Project the raw shared store onto the bare schema keys for ONE node so a
|
|
2316
|
+
* UI schema (whose field keys are bare) hydrates from that node's own
|
|
2317
|
+
* values:
|
|
2318
|
+
*
|
|
2319
|
+
* - EVERY `@`-scoped key (any node's) is dropped from the pass-through.
|
|
2320
|
+
* - Every bare perNode key is dropped from the pass-through (a stray bare
|
|
2321
|
+
* legacy key must never hydrate any node — no bare fallback).
|
|
2322
|
+
* - THIS node's effective value ({@link readNodeValue}) is then laid onto
|
|
2323
|
+
* each bare perNode key; when the node has no scoped key the bare key is
|
|
2324
|
+
* left ABSENT so the field's schema `default` wins.
|
|
2325
|
+
*
|
|
2326
|
+
* Returns a new object — the input store is not mutated.
|
|
2327
|
+
*/
|
|
2328
|
+
function projectStore(store, perNodeKeys, nodeId) {
|
|
2329
|
+
const out = {};
|
|
2330
|
+
for (const [key, value] of Object.entries(store)) {
|
|
2331
|
+
if (key.includes("@")) continue;
|
|
2332
|
+
if (perNodeKeys.has(key)) continue;
|
|
2333
|
+
out[key] = value;
|
|
2334
|
+
}
|
|
2335
|
+
for (const base of perNodeKeys) {
|
|
2336
|
+
const value = readNodeValue(store, base, nodeId);
|
|
2337
|
+
if (value !== void 0) out[base] = value;
|
|
2338
|
+
}
|
|
2339
|
+
return out;
|
|
2340
|
+
}
|
|
2341
|
+
//#endregion
|
|
2342
|
+
//#region ../types/dist/esm/addon/secret-settings-view.mjs
|
|
2343
|
+
/** A write to a secret path could not be stored in the keychain, so it was refused. */
|
|
2344
|
+
var KeychainWriteRefusedError = class extends Error {
|
|
2345
|
+
fieldPath;
|
|
2346
|
+
constructor(fieldPath, cause) {
|
|
2347
|
+
super(`secret "${fieldPath}" was not saved: the keychain could not store it (${cause instanceof Error ? cause.message : String(cause)}). Nothing was written.`);
|
|
2348
|
+
this.fieldPath = fieldPath;
|
|
2349
|
+
this.name = "KeychainWriteRefusedError";
|
|
2350
|
+
}
|
|
2351
|
+
};
|
|
2352
|
+
var KEEP = { kind: "keep" };
|
|
2353
|
+
function isRecord$1(value) {
|
|
2354
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2355
|
+
}
|
|
2356
|
+
function defaultMintId() {
|
|
2357
|
+
return globalThis.crypto.randomUUID();
|
|
2358
|
+
}
|
|
2359
|
+
/** Every marker ref anywhere under `value`. */
|
|
2360
|
+
function collectSecretMarkerRefs(value, out = []) {
|
|
2361
|
+
if (isSecretMarker(value)) {
|
|
2362
|
+
out.push(value.$secret);
|
|
2363
|
+
return out;
|
|
2364
|
+
}
|
|
2365
|
+
if (Array.isArray(value)) for (const item of value) collectSecretMarkerRefs(item, out);
|
|
2366
|
+
else if (isRecord$1(value)) for (const child of Object.values(value)) collectSecretMarkerRefs(child, out);
|
|
2367
|
+
return out;
|
|
2368
|
+
}
|
|
2369
|
+
async function storedValueEquals(secrets, marker, candidate) {
|
|
2370
|
+
const resolved = (await secrets.resolve([marker.$secret]))[marker.$secret];
|
|
2371
|
+
return resolved?.kind === "value" && resolved.value === candidate;
|
|
2372
|
+
}
|
|
2373
|
+
async function writeLeaf(ctx, incoming, stored, fieldPath) {
|
|
2374
|
+
const intent = classifySecretWrite(incoming);
|
|
2375
|
+
const ref = ctx.secrets.ref(ctx.scope, fieldPath);
|
|
2376
|
+
const storedIsOurs = isSecretMarker(stored) && stored.$secret === ref;
|
|
2377
|
+
if (intent.kind === "keep") return KEEP;
|
|
2378
|
+
if (intent.kind === "set" && !ctx.operatorWrite && typeof stored === "string" && stored === intent.value) return KEEP;
|
|
2379
|
+
if (intent.kind === "clear") {
|
|
2380
|
+
if (storedIsOurs) ctx.deletes.push(ref);
|
|
2381
|
+
return {
|
|
2382
|
+
kind: "value",
|
|
2383
|
+
value: null
|
|
2384
|
+
};
|
|
2385
|
+
}
|
|
2386
|
+
if (storedIsOurs && await storedValueEquals(ctx.secrets, stored, intent.value)) return {
|
|
2387
|
+
kind: "value",
|
|
2388
|
+
value: stored
|
|
2389
|
+
};
|
|
2390
|
+
try {
|
|
2391
|
+
await ctx.secrets.put(ref, intent.value);
|
|
2392
|
+
} catch (err) {
|
|
2393
|
+
throw new KeychainWriteRefusedError(fieldPath, err);
|
|
2394
|
+
}
|
|
2395
|
+
return {
|
|
2396
|
+
kind: "value",
|
|
2397
|
+
value: makeSecretMarker(ref)
|
|
2398
|
+
};
|
|
2399
|
+
}
|
|
2400
|
+
/** Apply a member result onto `out`: KEEP restores the stored member, or removes it. */
|
|
2401
|
+
function applyMember(out, key, result, storedParent) {
|
|
2402
|
+
if (result.kind === "value") {
|
|
2403
|
+
out[key] = result.value;
|
|
2404
|
+
return;
|
|
2405
|
+
}
|
|
2406
|
+
if (Object.prototype.hasOwnProperty.call(storedParent, key)) out[key] = storedParent[key];
|
|
2407
|
+
else delete out[key];
|
|
2408
|
+
}
|
|
2409
|
+
async function writeMembers(ctx, children, incoming, stored, pathOf) {
|
|
2410
|
+
const out = { ...incoming };
|
|
2411
|
+
for (const [member, node] of children) applyMember(out, member, await writeNode(ctx, node, incoming[member], stored[member], pathOf(member)), stored);
|
|
2412
|
+
return out;
|
|
2413
|
+
}
|
|
2414
|
+
function rowId(row, idKey) {
|
|
2415
|
+
const raw = row[idKey];
|
|
2416
|
+
if (typeof raw === "string" && raw.length > 0) return raw;
|
|
2417
|
+
if (typeof raw === "number" && Number.isFinite(raw)) return String(raw);
|
|
2418
|
+
return null;
|
|
2419
|
+
}
|
|
2420
|
+
async function writeArray(ctx, node, incoming, stored, fieldPath) {
|
|
2421
|
+
const storedRows = Array.isArray(stored) ? stored.filter(isRecord$1) : [];
|
|
2422
|
+
if (!Array.isArray(incoming)) {
|
|
2423
|
+
ctx.deletes.push(...collectSecretMarkerRefs(storedRows));
|
|
2424
|
+
return {
|
|
2425
|
+
kind: "value",
|
|
2426
|
+
value: incoming
|
|
2427
|
+
};
|
|
2428
|
+
}
|
|
2429
|
+
const storedById = /* @__PURE__ */ new Map();
|
|
2430
|
+
for (const row of storedRows) {
|
|
2431
|
+
const id = rowId(row, node.idKey);
|
|
2432
|
+
if (id !== null) storedById.set(id, row);
|
|
2433
|
+
}
|
|
2434
|
+
const kept = /* @__PURE__ */ new Set();
|
|
2435
|
+
const rows = [];
|
|
2436
|
+
for (const row of incoming) {
|
|
2437
|
+
if (!isRecord$1(row)) {
|
|
2438
|
+
rows.push(row);
|
|
2439
|
+
continue;
|
|
2440
|
+
}
|
|
2441
|
+
const id = rowId(row, node.idKey) ?? ctx.mintId();
|
|
2442
|
+
kept.add(id);
|
|
2443
|
+
const withId = {
|
|
2444
|
+
...row,
|
|
2445
|
+
[node.idKey]: row[node.idKey] ?? id
|
|
2446
|
+
};
|
|
2447
|
+
if (rowId(withId, node.idKey) === null) withId[node.idKey] = id;
|
|
2448
|
+
const storedRow = storedById.get(id) ?? {};
|
|
2449
|
+
rows.push(await writeMembers(ctx, node.item, withId, storedRow, (member) => arrayItemFieldPath(fieldPath, id, member)));
|
|
2450
|
+
}
|
|
2451
|
+
for (const [id, row] of storedById) if (!kept.has(id)) ctx.deletes.push(...collectSecretMarkerRefs(row));
|
|
2452
|
+
return {
|
|
2453
|
+
kind: "value",
|
|
2454
|
+
value: rows
|
|
2455
|
+
};
|
|
2456
|
+
}
|
|
2457
|
+
async function writeNode(ctx, node, incoming, stored, fieldPath) {
|
|
2458
|
+
switch (node.kind) {
|
|
2459
|
+
case "leaf": return writeLeaf(ctx, incoming, stored, fieldPath);
|
|
2460
|
+
case "array": return writeArray(ctx, node, incoming, stored, fieldPath);
|
|
2461
|
+
case "object": {
|
|
2462
|
+
if (!isRecord$1(incoming)) {
|
|
2463
|
+
if (incoming === void 0) return KEEP;
|
|
2464
|
+
ctx.deletes.push(...collectSecretMarkerRefs(stored));
|
|
2465
|
+
return {
|
|
2466
|
+
kind: "value",
|
|
2467
|
+
value: incoming
|
|
2468
|
+
};
|
|
2469
|
+
}
|
|
2470
|
+
const storedObj = isRecord$1(stored) ? stored : {};
|
|
2471
|
+
return {
|
|
2472
|
+
kind: "value",
|
|
2473
|
+
value: await writeMembers(ctx, node.children, incoming, storedObj, (m) => `${fieldPath}.${m}`)
|
|
2474
|
+
};
|
|
2475
|
+
}
|
|
2476
|
+
}
|
|
2477
|
+
}
|
|
2478
|
+
/** Split a perNode-scoped key (`key@nodeId`). */
|
|
2479
|
+
function splitNodeKey(key) {
|
|
2480
|
+
const at = key.indexOf("@");
|
|
2481
|
+
return at <= 0 ? {
|
|
2482
|
+
base: key,
|
|
2483
|
+
nodeId: null
|
|
2484
|
+
} : {
|
|
2485
|
+
base: key.slice(0, at),
|
|
2486
|
+
nodeId: key.slice(at + 1)
|
|
2487
|
+
};
|
|
2488
|
+
}
|
|
2489
|
+
/** Rewrite a settings patch so no secret value reaches the blob. See the file doc. */
|
|
2490
|
+
async function transformSecretWrite(input) {
|
|
2491
|
+
const deletes = [];
|
|
2492
|
+
const base = {
|
|
2493
|
+
secrets: input.secrets,
|
|
2494
|
+
mintId: input.mintId ?? defaultMintId,
|
|
2495
|
+
deletes,
|
|
2496
|
+
operatorWrite: input.operatorWrite === true
|
|
2497
|
+
};
|
|
2498
|
+
const out = {};
|
|
2499
|
+
for (const [key, incoming] of Object.entries(input.patch)) {
|
|
2500
|
+
const { base: baseKey, nodeId } = splitNodeKey(key);
|
|
2501
|
+
const node = input.tree.get(baseKey);
|
|
2502
|
+
if (node === void 0) {
|
|
2503
|
+
out[key] = incoming;
|
|
2504
|
+
continue;
|
|
2505
|
+
}
|
|
2506
|
+
const scope = nodeId !== null && nodeId.length > 0 ? {
|
|
2507
|
+
kind: "node",
|
|
2508
|
+
nodeId
|
|
2509
|
+
} : input.scope ?? globalSecretScope();
|
|
2510
|
+
const result = await writeNode({
|
|
2511
|
+
...base,
|
|
2512
|
+
scope
|
|
2513
|
+
}, node, incoming, input.stored[key], baseKey);
|
|
2514
|
+
if (result.kind === "value") out[key] = result.value;
|
|
2515
|
+
}
|
|
2516
|
+
return {
|
|
2517
|
+
patch: out,
|
|
2518
|
+
afterWrite: async () => {
|
|
2519
|
+
if (deletes.length === 0) return { orphaned: [] };
|
|
2520
|
+
try {
|
|
2521
|
+
await input.secrets.delete([...new Set(deletes)]);
|
|
2522
|
+
return { orphaned: [] };
|
|
2523
|
+
} catch {
|
|
2524
|
+
return { orphaned: [...new Set(deletes)] };
|
|
2525
|
+
}
|
|
2526
|
+
}
|
|
2527
|
+
};
|
|
2528
|
+
}
|
|
2529
|
+
/** Is `ref` one of `owner`'s refs? */
|
|
2530
|
+
function isSecretRefOwnedBy(ref, owner) {
|
|
2531
|
+
return parseSecretRef(ref)?.owner === owner;
|
|
2532
|
+
}
|
|
2533
|
+
/**
|
|
2534
|
+
* Replace every marker in `value` with its keychain value. Returns the SAME
|
|
2535
|
+
* reference when there is no marker (no allocation, no keychain call).
|
|
2536
|
+
*/
|
|
2537
|
+
async function resolveSecretMarkers(value, secrets, options = {}) {
|
|
2538
|
+
const keepMarker = options.unresolved === "keep-marker";
|
|
2539
|
+
const owner = options.ownedBy;
|
|
2540
|
+
const inScope = (ref) => owner === void 0 || isSecretRefOwnedBy(ref, owner);
|
|
2541
|
+
const refs = collectSecretMarkerRefs(value).filter(inScope);
|
|
2542
|
+
if (refs.length === 0) return {
|
|
2543
|
+
value,
|
|
2544
|
+
unresolved: []
|
|
2545
|
+
};
|
|
2546
|
+
const answers = await secrets.resolve(refs);
|
|
2547
|
+
const unresolved = [];
|
|
2548
|
+
for (const ref of new Set(refs)) {
|
|
2549
|
+
const answer = answers[ref];
|
|
2550
|
+
if (answer === void 0) unresolved.push({
|
|
2551
|
+
ref,
|
|
2552
|
+
reason: "not-initialized"
|
|
2553
|
+
});
|
|
2554
|
+
else if (answer.kind === "unavailable") unresolved.push({
|
|
2555
|
+
ref,
|
|
2556
|
+
reason: answer.reason
|
|
2557
|
+
});
|
|
2558
|
+
else if (answer.kind === "missing" || answer.kind === "forbidden") unresolved.push({
|
|
2559
|
+
ref,
|
|
2560
|
+
reason: answer.kind
|
|
2561
|
+
});
|
|
2562
|
+
}
|
|
2563
|
+
const substitute = (v) => {
|
|
2564
|
+
if (isSecretMarker(v)) {
|
|
2565
|
+
if (!inScope(v.$secret)) return {
|
|
2566
|
+
keep: true,
|
|
2567
|
+
value: v
|
|
2568
|
+
};
|
|
2569
|
+
const answer = answers[v.$secret];
|
|
2570
|
+
if (answer?.kind === "value") return {
|
|
2571
|
+
keep: true,
|
|
2572
|
+
value: answer.value
|
|
2573
|
+
};
|
|
2574
|
+
return keepMarker ? {
|
|
2575
|
+
keep: true,
|
|
2576
|
+
value: v
|
|
2577
|
+
} : {
|
|
2578
|
+
keep: false,
|
|
2579
|
+
value: void 0
|
|
2580
|
+
};
|
|
2581
|
+
}
|
|
2582
|
+
if (Array.isArray(v)) {
|
|
2583
|
+
const items = [];
|
|
2584
|
+
for (const item of v) {
|
|
2585
|
+
const s = substitute(item);
|
|
2586
|
+
if (s.keep) items.push(s.value);
|
|
2587
|
+
}
|
|
2588
|
+
return {
|
|
2589
|
+
keep: true,
|
|
2590
|
+
value: items
|
|
2591
|
+
};
|
|
2592
|
+
}
|
|
2593
|
+
if (isRecord$1(v)) {
|
|
2594
|
+
const out = {};
|
|
2595
|
+
for (const [k, child] of Object.entries(v)) {
|
|
2596
|
+
const s = substitute(child);
|
|
2597
|
+
if (s.keep) out[k] = s.value;
|
|
2598
|
+
}
|
|
2599
|
+
return {
|
|
2600
|
+
keep: true,
|
|
2601
|
+
value: out
|
|
2602
|
+
};
|
|
2603
|
+
}
|
|
2604
|
+
return {
|
|
2605
|
+
keep: true,
|
|
2606
|
+
value: v
|
|
2607
|
+
};
|
|
2608
|
+
};
|
|
2609
|
+
return {
|
|
2610
|
+
value: substitute(value).value,
|
|
2611
|
+
unresolved
|
|
2612
|
+
};
|
|
2613
|
+
}
|
|
2614
|
+
//#endregion
|
|
2615
|
+
//#region ../types/dist/esm/addon/secret-paths.mjs
|
|
2616
|
+
var LEAF = { kind: "leaf" };
|
|
2617
|
+
var DEFAULT_ITEM_ID_KEY = "id";
|
|
2618
|
+
function collectFields(fields, out) {
|
|
2619
|
+
for (const field of fields) {
|
|
2620
|
+
if (field.type === "group") {
|
|
2621
|
+
collectFields(field.fields, out);
|
|
2622
|
+
continue;
|
|
2623
|
+
}
|
|
2624
|
+
if (field.type === "sub-tabs") {
|
|
2625
|
+
for (const tab of field.tabs) collectFields(tab.fields, out);
|
|
2626
|
+
continue;
|
|
2627
|
+
}
|
|
2628
|
+
if (field.type === "editable-array") {
|
|
2629
|
+
const item = /* @__PURE__ */ new Map();
|
|
2630
|
+
for (const itemField of field.itemFields) if ("key" in itemField && isKeychainStoredField(itemField)) item.set(itemField.key, LEAF);
|
|
2631
|
+
if (item.size > 0) out.set(field.key, {
|
|
2632
|
+
kind: "array",
|
|
2633
|
+
idKey: field.itemIdKey ?? DEFAULT_ITEM_ID_KEY,
|
|
2634
|
+
item
|
|
2635
|
+
});
|
|
2636
|
+
continue;
|
|
2637
|
+
}
|
|
2638
|
+
if (!("key" in field) || typeof field.key !== "string") continue;
|
|
2639
|
+
if (isKeychainStoredField(field)) out.set(field.key, LEAF);
|
|
2640
|
+
}
|
|
2641
|
+
}
|
|
2642
|
+
/** The secret tree a settings schema declares. */
|
|
2643
|
+
function secretTreeFromSchema(schema) {
|
|
2644
|
+
const out = /* @__PURE__ */ new Map();
|
|
2645
|
+
if (schema === null) return out;
|
|
2646
|
+
for (const section of schema.sections) collectFields(section.fields, out);
|
|
2647
|
+
return out;
|
|
2648
|
+
}
|
|
2649
|
+
/** Parse `a.b[id].c` into segments; throws on a malformed path (a declaration bug). */
|
|
2650
|
+
function parseSecretStatePath(path) {
|
|
2651
|
+
const segments = [];
|
|
2652
|
+
for (const raw of path.split(".")) {
|
|
2653
|
+
const m = /^([^[\]]+)(?:\[([^[\]]+)\])?$/.exec(raw);
|
|
2654
|
+
if (m === null || m[1] === void 0) throw new Error(`secretStatePaths: malformed path "${path}"`);
|
|
2655
|
+
segments.push(m[2] !== void 0 ? {
|
|
2656
|
+
key: m[1],
|
|
2657
|
+
idKey: m[2]
|
|
2658
|
+
} : { key: m[1] });
|
|
2659
|
+
}
|
|
2660
|
+
if (segments.length === 0) throw new Error(`secretStatePaths: empty path`);
|
|
2661
|
+
if (segments[segments.length - 1]?.idKey !== void 0) throw new Error(`secretStatePaths: "${path}" ends on an array — name the member that is secret`);
|
|
2662
|
+
return segments;
|
|
2663
|
+
}
|
|
2664
|
+
function insert(into, segments) {
|
|
2665
|
+
const [head, ...rest] = segments;
|
|
2666
|
+
if (head === void 0) return;
|
|
2667
|
+
if (rest.length === 0) {
|
|
2668
|
+
into.set(head.key, LEAF);
|
|
2669
|
+
return;
|
|
2670
|
+
}
|
|
2671
|
+
const existing = into.get(head.key);
|
|
2672
|
+
if (head.idKey !== void 0) {
|
|
2673
|
+
const item = new Map(existing?.kind === "array" ? existing.item : []);
|
|
2674
|
+
insert(item, rest);
|
|
2675
|
+
into.set(head.key, {
|
|
2676
|
+
kind: "array",
|
|
2677
|
+
idKey: head.idKey,
|
|
2678
|
+
item
|
|
2679
|
+
});
|
|
2680
|
+
return;
|
|
2681
|
+
}
|
|
2682
|
+
const children = new Map(existing?.kind === "object" ? existing.children : []);
|
|
2683
|
+
insert(children, rest);
|
|
2684
|
+
into.set(head.key, {
|
|
2685
|
+
kind: "object",
|
|
2686
|
+
children
|
|
2687
|
+
});
|
|
2688
|
+
}
|
|
2689
|
+
/** Add hidden-state paths (`secretStatePaths`) to a schema-derived tree. */
|
|
2690
|
+
function mergeSecretStatePaths(tree, paths) {
|
|
2691
|
+
if (paths.length === 0) return tree;
|
|
2692
|
+
const out = new Map(tree);
|
|
2693
|
+
for (const path of paths) insert(out, parseSecretStatePath(path));
|
|
2694
|
+
return out;
|
|
2695
|
+
}
|
|
2696
|
+
/**
|
|
2697
|
+
* The tree of a DECLARED path list — a device's `secretConfigPaths`
|
|
2698
|
+
* (`collectZodSecretPaths`: dotted, `[]` for array items). An array segment
|
|
2699
|
+
* without a named id field is addressed by the item's `id`.
|
|
2700
|
+
*/
|
|
2701
|
+
function secretTreeFromPaths(paths) {
|
|
2702
|
+
const out = /* @__PURE__ */ new Map();
|
|
2703
|
+
for (const path of paths) {
|
|
2704
|
+
if (path.length === 0) continue;
|
|
2705
|
+
insert(out, parseSecretStatePath(path.replace(/\[\]/g, `[${DEFAULT_ITEM_ID_KEY}]`)));
|
|
2706
|
+
}
|
|
2707
|
+
return out;
|
|
2708
|
+
}
|
|
2709
|
+
//#endregion
|
|
2710
|
+
//#region ../types/dist/esm/addon/scoped-settings-handle.mjs
|
|
2711
|
+
/** The one refusal of a key a scope did not declare. */
|
|
2712
|
+
function assertDeclaredKeys(keys, declared) {
|
|
2713
|
+
const undeclared = keys.filter((key) => !declared.has(key));
|
|
2714
|
+
if (undeclared.length > 0) throw new Error(`scoped settings: [${undeclared.join(", ")}] not declared for this scope (declared: [${[...declared].join(", ")}])`);
|
|
2715
|
+
}
|
|
2716
|
+
/** Build the handle over an addon's scoped read, write and unset. */
|
|
2717
|
+
function createScopedSettings(deps) {
|
|
2718
|
+
return {
|
|
2719
|
+
async get() {
|
|
2720
|
+
return deps.schema.parse(await deps.read());
|
|
2721
|
+
},
|
|
2722
|
+
patch: (patch) => deps.write(Object.fromEntries(Object.entries(patch))),
|
|
2723
|
+
unset: (keys) => deps.unset(keys)
|
|
2724
|
+
};
|
|
2725
|
+
}
|
|
2726
|
+
//#endregion
|
|
2727
|
+
//#region ../types/dist/esm/addon/secret-write-back.mjs
|
|
2728
|
+
/** An addon tried to replace a stored secret it could not read. Nothing was written. */
|
|
2729
|
+
var SecretOverwriteRefusedError = class extends Error {
|
|
2730
|
+
ref;
|
|
2731
|
+
reason;
|
|
2732
|
+
constructor(ref, reason) {
|
|
2733
|
+
super(`secret ${ref} was not replaced: its stored value cannot be read right now (${reason}), and an addon may not overwrite a secret it cannot see. Nothing was written.`);
|
|
2734
|
+
this.ref = ref;
|
|
2735
|
+
this.reason = reason;
|
|
2736
|
+
this.name = "SecretOverwriteRefusedError";
|
|
2737
|
+
}
|
|
2738
|
+
};
|
|
2739
|
+
function isRecord(value) {
|
|
2740
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2741
|
+
}
|
|
2742
|
+
function resolvedValue(pass, marker) {
|
|
2743
|
+
const answer = pass.answers[marker.$secret];
|
|
2744
|
+
return answer?.kind === "value" ? answer.value : null;
|
|
2745
|
+
}
|
|
2746
|
+
async function atMarker(pass, incoming, stored) {
|
|
2747
|
+
if (incoming === null) return stored;
|
|
2748
|
+
if (typeof incoming !== "string") return incoming;
|
|
2749
|
+
if (incoming === resolvedValue(pass, stored)) return stored;
|
|
2750
|
+
const intent = classifySecretWrite(incoming);
|
|
2751
|
+
if (intent.kind !== "set") return stored;
|
|
2752
|
+
const ref = stored.$secret;
|
|
2753
|
+
if (!isSecretRefOwnedBy(ref, pass.secrets.owner)) return incoming;
|
|
2754
|
+
const answer = pass.answers[ref];
|
|
2755
|
+
if ((answer === void 0 || answer.kind === "unavailable" || answer.kind === "forbidden") && !pass.operatorWrite) throw new SecretOverwriteRefusedError(ref, answer === void 0 ? "not-initialized" : answer.kind === "unavailable" ? answer.reason : answer.kind);
|
|
2756
|
+
try {
|
|
2757
|
+
await pass.secrets.put(ref, intent.value);
|
|
2758
|
+
} catch (err) {
|
|
2759
|
+
throw new KeychainWriteRefusedError(ref, err);
|
|
2760
|
+
}
|
|
2761
|
+
pass.changedRefs.push(ref);
|
|
2762
|
+
return stored;
|
|
2763
|
+
}
|
|
2764
|
+
function inArray(pass, incoming, stored) {
|
|
2765
|
+
return incoming.map((item, index) => {
|
|
2766
|
+
const twin = stored[index];
|
|
2767
|
+
if (isSecretMarker(twin)) return typeof item === "string" && item === resolvedValue(pass, twin) ? twin : item;
|
|
2768
|
+
if (isRecord(item) && isRecord(twin)) return inArrayRow(pass, item, twin);
|
|
2769
|
+
if (Array.isArray(item) && Array.isArray(twin)) return inArray(pass, item, twin);
|
|
2770
|
+
return item;
|
|
2771
|
+
});
|
|
2772
|
+
}
|
|
2773
|
+
function inArrayRow(pass, incoming, stored) {
|
|
2774
|
+
const out = { ...incoming };
|
|
2775
|
+
for (const [key, value] of Object.entries(incoming)) {
|
|
2776
|
+
const twin = stored[key];
|
|
2777
|
+
if (isSecretMarker(twin)) {
|
|
2778
|
+
if (typeof value === "string" && value === resolvedValue(pass, twin)) out[key] = twin;
|
|
2779
|
+
} else if (isRecord(value) && isRecord(twin)) out[key] = inArrayRow(pass, value, twin);
|
|
2780
|
+
else if (Array.isArray(value) && Array.isArray(twin)) out[key] = inArray(pass, value, twin);
|
|
2781
|
+
}
|
|
2782
|
+
return out;
|
|
2783
|
+
}
|
|
2784
|
+
async function walk(pass, incoming, stored) {
|
|
2785
|
+
if (isSecretMarker(stored)) return atMarker(pass, incoming, stored);
|
|
2786
|
+
if (Array.isArray(incoming) && Array.isArray(stored)) return inArray(pass, incoming, stored);
|
|
2787
|
+
if (!isRecord(incoming) || !isRecord(stored)) return incoming;
|
|
2788
|
+
const out = { ...incoming };
|
|
2789
|
+
for (const [key, value] of Object.entries(incoming)) out[key] = await walk(pass, value, stored[key]);
|
|
2790
|
+
return out;
|
|
2791
|
+
}
|
|
2792
|
+
/** Restore markers a write-back carries as values. See the file doc. */
|
|
2793
|
+
async function restoreUnchangedSecrets(input) {
|
|
2794
|
+
const refs = [];
|
|
2795
|
+
for (const key of Object.keys(input.patch)) collectSecretMarkerRefs(input.stored[key], refs);
|
|
2796
|
+
const owned = refs.filter((ref) => isSecretRefOwnedBy(ref, input.secrets.owner));
|
|
2797
|
+
if (owned.length === 0) return {
|
|
2798
|
+
patch: input.patch,
|
|
2799
|
+
changedRefs: []
|
|
2800
|
+
};
|
|
2801
|
+
const pass = {
|
|
2802
|
+
secrets: input.secrets,
|
|
2803
|
+
answers: await input.secrets.resolve([...new Set(owned)]),
|
|
2804
|
+
operatorWrite: input.operatorWrite,
|
|
2805
|
+
changedRefs: []
|
|
2806
|
+
};
|
|
2807
|
+
const out = {};
|
|
2808
|
+
for (const [key, value] of Object.entries(input.patch)) out[key] = await walk(pass, value, input.stored[key]);
|
|
2809
|
+
return {
|
|
2810
|
+
patch: out,
|
|
2811
|
+
changedRefs: pass.changedRefs
|
|
2812
|
+
};
|
|
2813
|
+
}
|
|
2814
|
+
/** Structural equality over JSON-shaped values (key order does not matter). */
|
|
2815
|
+
function isJsonEqual(a, b) {
|
|
2816
|
+
if (Object.is(a, b)) return true;
|
|
2817
|
+
if (Array.isArray(a)) return Array.isArray(b) && a.length === b.length && a.every((v, i) => isJsonEqual(v, b[i]));
|
|
2818
|
+
if (isRecord(a) && isRecord(b)) {
|
|
2819
|
+
const keys = Object.keys(a);
|
|
2820
|
+
if (keys.length !== Object.keys(b).length) return false;
|
|
2821
|
+
return keys.every((k) => Object.prototype.hasOwnProperty.call(b, k) && isJsonEqual(a[k], b[k]));
|
|
2822
|
+
}
|
|
2823
|
+
return false;
|
|
2824
|
+
}
|
|
2825
|
+
/** The patch without the keys whose value already equals the stored one. */
|
|
2826
|
+
function dropUnchangedKeys(patch, stored) {
|
|
2827
|
+
const out = {};
|
|
2828
|
+
for (const [key, value] of Object.entries(patch)) {
|
|
2829
|
+
if (Object.prototype.hasOwnProperty.call(stored, key) && isJsonEqual(value, stored[key])) continue;
|
|
2830
|
+
out[key] = value;
|
|
2831
|
+
}
|
|
2832
|
+
return out;
|
|
2833
|
+
}
|
|
2834
|
+
/** The top-level keys of a blob that hold at least one of `owner`'s markers. */
|
|
2835
|
+
function markerKeysOf(blob, owner) {
|
|
2836
|
+
const keys = /* @__PURE__ */ new Set();
|
|
2837
|
+
for (const [key, value] of Object.entries(blob)) if (collectSecretMarkerRefs(value).some((ref) => isSecretRefOwnedBy(ref, owner))) keys.add(key);
|
|
2838
|
+
return keys;
|
|
2839
|
+
}
|
|
2840
|
+
function nodeFromStored(value, owner) {
|
|
2841
|
+
if (isSecretMarker(value)) return isSecretRefOwnedBy(value.$secret, owner) ? { kind: "leaf" } : null;
|
|
2842
|
+
if (!isRecord(value)) return null;
|
|
2843
|
+
const children = /* @__PURE__ */ new Map();
|
|
2844
|
+
for (const [key, child] of Object.entries(value)) {
|
|
2845
|
+
const node = nodeFromStored(child, owner);
|
|
2846
|
+
if (node !== null) children.set(key, node);
|
|
2847
|
+
}
|
|
2848
|
+
return children.size > 0 ? {
|
|
2849
|
+
kind: "object",
|
|
2850
|
+
children
|
|
2851
|
+
} : null;
|
|
2852
|
+
}
|
|
2853
|
+
/**
|
|
2854
|
+
* The declared secret tree, widened by every place the STORED blob holds a
|
|
2855
|
+
* marker under one of `keys` — so a marker the schema no longer declares (or
|
|
2856
|
+
* never declared: Wyze before b4906cec6) still gets the save path's
|
|
2857
|
+
* KEEP / SET / CLEAR semantics instead of being overwritten by whatever the
|
|
2858
|
+
* addon writes. Markers inside arrays are not added: a row has no id field to
|
|
2859
|
+
* match by unless the schema declares one. Only `owner`'s markers count: a
|
|
2860
|
+
* builtin that keeps another addon's marker (device-manager) never takes it
|
|
2861
|
+
* over.
|
|
2862
|
+
*/
|
|
2863
|
+
function widenTreeWithStoredMarkers(declared, stored, keys, owner) {
|
|
2864
|
+
const added = /* @__PURE__ */ new Map();
|
|
2865
|
+
for (const key of keys) {
|
|
2866
|
+
const at = key.indexOf("@");
|
|
2867
|
+
const base = at > 0 ? key.slice(0, at) : key;
|
|
2868
|
+
if (declared.has(base) || added.has(base)) continue;
|
|
2869
|
+
const node = nodeFromStored(stored[key], owner);
|
|
2870
|
+
if (node !== null) added.set(base, node);
|
|
2871
|
+
}
|
|
2872
|
+
return added.size === 0 ? declared : new Map([...declared, ...added]);
|
|
2873
|
+
}
|
|
2874
|
+
//#endregion
|
|
2875
|
+
//#region ../types/dist/esm/addon/secret-aware-context.mjs
|
|
2876
|
+
/** The blob as stored now; a failed read REFUSES the write instead of guessing. */
|
|
2877
|
+
async function readStoredAddonBlob(raw) {
|
|
2878
|
+
const threeWay = raw.readAddonStoreResult;
|
|
2879
|
+
if (threeWay === void 0) return raw.readAddonStore();
|
|
2880
|
+
const result = await threeWay.call(raw);
|
|
2881
|
+
if (result.kind === "failed") throw new Error(`settings write refused: the stored blob could not be read (${result.error})`);
|
|
2882
|
+
return result.kind === "missing" ? {} : result.value;
|
|
2883
|
+
}
|
|
2884
|
+
function touchesTree(tree, patch) {
|
|
2885
|
+
if (tree.size === 0) return false;
|
|
2886
|
+
for (const key of Object.keys(patch)) {
|
|
2887
|
+
const at = key.indexOf("@");
|
|
2888
|
+
if (tree.has(at > 0 ? key.slice(0, at) : key)) return true;
|
|
2889
|
+
}
|
|
2890
|
+
return false;
|
|
2891
|
+
}
|
|
2892
|
+
/**
|
|
2893
|
+
* Which top-level keys of each store held markers when last seen. `undefined`
|
|
2894
|
+
* for a store not seen yet: its first write reads it, to be safe.
|
|
2895
|
+
*/
|
|
2896
|
+
var MarkerKeyIndex = class {
|
|
2897
|
+
owner;
|
|
2898
|
+
byStore = /* @__PURE__ */ new Map();
|
|
2899
|
+
constructor(owner) {
|
|
2900
|
+
this.owner = owner;
|
|
2901
|
+
}
|
|
2902
|
+
seen(store, blob) {
|
|
2903
|
+
this.byStore.set(store, markerKeysOf(blob, this.owner));
|
|
2904
|
+
}
|
|
2905
|
+
wrote(store, patch) {
|
|
2906
|
+
const keys = this.byStore.get(store);
|
|
2907
|
+
if (keys === void 0) return;
|
|
2908
|
+
const now = markerKeysOf(patch, this.owner);
|
|
2909
|
+
for (const key of Object.keys(patch)) if (now.has(key)) keys.add(key);
|
|
2910
|
+
else keys.delete(key);
|
|
2911
|
+
}
|
|
2912
|
+
mayHoldMarkers(store, patch) {
|
|
2913
|
+
const keys = this.byStore.get(store);
|
|
2914
|
+
if (keys === void 0) return true;
|
|
2915
|
+
return Object.keys(patch).some((key) => keys.has(key));
|
|
2916
|
+
}
|
|
2917
|
+
};
|
|
2918
|
+
function createHandle(raw, opts) {
|
|
2919
|
+
const chains = /* @__PURE__ */ new Map();
|
|
2920
|
+
const serialize = (key, fn) => {
|
|
2921
|
+
const next = (chains.get(key) ?? Promise.resolve()).then(fn, fn);
|
|
2922
|
+
const tail = next.catch(() => void 0);
|
|
2923
|
+
chains.set(key, tail);
|
|
2924
|
+
tail.then(() => {
|
|
2925
|
+
if (chains.get(key) === tail) chains.delete(key);
|
|
2926
|
+
});
|
|
2927
|
+
return next;
|
|
2928
|
+
};
|
|
2929
|
+
const index = new MarkerKeyIndex(opts.secrets.owner);
|
|
2930
|
+
const resolveRead = async (store, blob) => {
|
|
2931
|
+
index.seen(store, blob);
|
|
2932
|
+
const { value, unresolved } = await resolveSecretMarkers(blob, opts.secrets, {
|
|
2933
|
+
unresolved: "keep-marker",
|
|
2934
|
+
ownedBy: opts.secrets.owner
|
|
2935
|
+
});
|
|
2936
|
+
if (unresolved.length > 0) opts.onUnresolved?.(unresolved);
|
|
2937
|
+
return value;
|
|
2938
|
+
};
|
|
2939
|
+
const write = async (store, declared, scope, patch, readStored, rawWrite) => {
|
|
2940
|
+
if (!touchesTree(declared, patch) && !index.mayHoldMarkers(store, patch)) {
|
|
2941
|
+
await rawWrite(patch);
|
|
2942
|
+
index.wrote(store, patch);
|
|
2943
|
+
return { changed: true };
|
|
2944
|
+
}
|
|
2945
|
+
return serialize(store, async () => {
|
|
2946
|
+
const stored = await readStored();
|
|
2947
|
+
index.seen(store, stored);
|
|
2948
|
+
const operatorWrite = opts.isOperatorWrite?.() === true;
|
|
2949
|
+
const restored = await restoreUnchangedSecrets({
|
|
2950
|
+
patch,
|
|
2951
|
+
stored,
|
|
2952
|
+
secrets: opts.secrets,
|
|
2953
|
+
operatorWrite
|
|
2954
|
+
});
|
|
2955
|
+
const result = await transformSecretWrite({
|
|
2956
|
+
tree: widenTreeWithStoredMarkers(declared, stored, Object.keys(restored.patch), opts.secrets.owner),
|
|
2957
|
+
secrets: opts.secrets,
|
|
2958
|
+
patch: restored.patch,
|
|
2959
|
+
stored,
|
|
2960
|
+
...scope !== void 0 ? { scope } : {},
|
|
2961
|
+
operatorWrite
|
|
2962
|
+
});
|
|
2963
|
+
const effective = dropUnchangedKeys(result.patch, stored);
|
|
2964
|
+
const wroteBlob = Object.keys(effective).length > 0;
|
|
2965
|
+
if (wroteBlob) {
|
|
2966
|
+
await rawWrite(effective);
|
|
2967
|
+
index.wrote(store, effective);
|
|
2968
|
+
}
|
|
2969
|
+
const { orphaned } = await result.afterWrite();
|
|
2970
|
+
if (orphaned.length > 0) opts.onOrphaned(orphaned);
|
|
2971
|
+
return { changed: wroteBlob || restored.changedRefs.length > 0 };
|
|
2972
|
+
});
|
|
2973
|
+
};
|
|
2974
|
+
const writeAddon = (patch) => write("addon", opts.addonTree(), void 0, patch, () => readStoredAddonBlob(raw), (p) => raw.writeAddonStore(p));
|
|
2975
|
+
const readAddonStoreResult = raw.readAddonStoreResult;
|
|
2976
|
+
const readAddonStoreKeyResult = raw.readAddonStoreKeyResult;
|
|
2977
|
+
const overrides = {
|
|
2978
|
+
readAddonStore: async () => resolveRead("addon", await raw.readAddonStore()),
|
|
2979
|
+
...readAddonStoreResult !== void 0 ? { readAddonStoreResult: async () => {
|
|
2980
|
+
const result = await readAddonStoreResult.call(raw);
|
|
2981
|
+
return result.kind === "value" ? {
|
|
2982
|
+
kind: "value",
|
|
2983
|
+
value: await resolveRead("addon", result.value)
|
|
2984
|
+
} : result;
|
|
2985
|
+
} } : {},
|
|
2986
|
+
...readAddonStoreKeyResult !== void 0 ? { readAddonStoreKeyResult: async (key) => {
|
|
2987
|
+
const result = await readAddonStoreKeyResult.call(raw, key);
|
|
2988
|
+
if (result.kind !== "present") return result;
|
|
2989
|
+
const { value, unresolved } = await resolveSecretMarkers({ [key]: result.value }, opts.secrets, {
|
|
2990
|
+
unresolved: "keep-marker",
|
|
2991
|
+
ownedBy: opts.secrets.owner
|
|
2992
|
+
});
|
|
2993
|
+
if (unresolved.length > 0) opts.onUnresolved?.(unresolved);
|
|
2994
|
+
return {
|
|
2995
|
+
kind: "present",
|
|
2996
|
+
value: value[key]
|
|
2997
|
+
};
|
|
2998
|
+
} } : {},
|
|
2999
|
+
readDeviceStore: async (deviceId) => resolveRead(`device:${deviceId}`, await raw.readDeviceStore(deviceId)),
|
|
3000
|
+
readDeviceStoreBatch: async (deviceIds) => {
|
|
3001
|
+
const rows = await raw.readDeviceStoreBatch(deviceIds);
|
|
3002
|
+
const out = /* @__PURE__ */ new Map();
|
|
3003
|
+
for (const [deviceId, blob] of rows) out.set(deviceId, await resolveRead(`device:${deviceId}`, blob));
|
|
3004
|
+
return out;
|
|
3005
|
+
},
|
|
3006
|
+
writeAddonStore: async (patch) => {
|
|
3007
|
+
await writeAddon(patch);
|
|
3008
|
+
},
|
|
3009
|
+
writeDeviceStore: async (deviceId, patch) => {
|
|
3010
|
+
await write(`device:${deviceId}`, opts.deviceTree(), {
|
|
3011
|
+
kind: "device",
|
|
3012
|
+
deviceId
|
|
3013
|
+
}, patch, () => raw.readDeviceStore(deviceId), (p) => raw.writeDeviceStore(deviceId, p));
|
|
3014
|
+
}
|
|
3015
|
+
};
|
|
3016
|
+
return {
|
|
3017
|
+
settings: new Proxy(raw, { get(target, prop, receiver) {
|
|
3018
|
+
if (typeof prop === "string" && Object.prototype.hasOwnProperty.call(overrides, prop)) return Reflect.get(overrides, prop);
|
|
3019
|
+
const value = Reflect.get(target, prop, receiver);
|
|
3020
|
+
return typeof value === "function" ? value.bind(target) : value;
|
|
3021
|
+
} }),
|
|
3022
|
+
raw: {
|
|
3023
|
+
readAddonStore: async () => {
|
|
3024
|
+
const blob = await raw.readAddonStore();
|
|
3025
|
+
index.seen("addon", blob);
|
|
3026
|
+
return blob;
|
|
3027
|
+
},
|
|
3028
|
+
readDeviceStore: async (deviceId) => {
|
|
3029
|
+
const blob = await raw.readDeviceStore(deviceId);
|
|
3030
|
+
index.seen(`device:${deviceId}`, blob);
|
|
3031
|
+
return blob;
|
|
3032
|
+
}
|
|
3033
|
+
},
|
|
3034
|
+
writeAddonStore: writeAddon,
|
|
3035
|
+
removeClearedKeys: (keys) => serialize("addon", async () => {
|
|
3036
|
+
const stored = await readStoredAddonBlob(raw);
|
|
3037
|
+
index.seen("addon", stored);
|
|
3038
|
+
const removable = keys.filter((key) => collectSecretMarkerRefs(stored[key]).length === 0);
|
|
3039
|
+
if (removable.length === 0) return;
|
|
3040
|
+
const patch = Object.fromEntries(removable.map((key) => [key, void 0]));
|
|
3041
|
+
await raw.writeAddonStore(patch);
|
|
3042
|
+
index.wrote("addon", patch);
|
|
3043
|
+
})
|
|
3044
|
+
};
|
|
3045
|
+
}
|
|
3046
|
+
/** The context the addon sees, plus the private raw view and write outcome. */
|
|
3047
|
+
function createSecretAwareContext(context, opts) {
|
|
3048
|
+
const raw = context.settings;
|
|
3049
|
+
if (raw === void 0) return {
|
|
3050
|
+
context,
|
|
3051
|
+
handle: null
|
|
3052
|
+
};
|
|
3053
|
+
const handle = createHandle(raw, opts);
|
|
3054
|
+
return {
|
|
3055
|
+
context: new Proxy(context, { get(target, prop, receiver) {
|
|
3056
|
+
if (prop === "settings") return handle.settings;
|
|
3057
|
+
return Reflect.get(target, prop, receiver);
|
|
3058
|
+
} }),
|
|
3059
|
+
handle
|
|
3060
|
+
};
|
|
3061
|
+
}
|
|
3062
|
+
//#endregion
|
|
3063
|
+
//#region ../types/dist/esm/addon/base-addon.mjs
|
|
3064
|
+
/** First retry of a secret the keychain could not serve; doubles to {@link SECRET_RETRY_MAX_MS}. */
|
|
3065
|
+
var SECRET_RETRY_FIRST_MS = 5e3;
|
|
3066
|
+
var SECRET_RETRY_MAX_MS = 5 * 6e4;
|
|
3067
|
+
/** Coalesces a burst of `keychain.changed` events into one re-resolve. */
|
|
3068
|
+
var SECRET_CHANGE_DEBOUNCE_MS = 250;
|
|
3069
|
+
/**
|
|
3070
|
+
* Pair a catalogue with the function that builds its ports FROM THE MIGRATION API. The one
|
|
3071
|
+
* place a catalogue is bound: a migration reaches nothing a ports binder cannot reach
|
|
3072
|
+
* through `api` (guard `check-migration-ports-surface`).
|
|
3073
|
+
*/
|
|
3074
|
+
function migrationSet(catalogue, bindPorts) {
|
|
3075
|
+
return { bind: (api) => defineAddonMigrations(catalogue, bindPorts(api)) };
|
|
3076
|
+
}
|
|
3077
|
+
/** A mixed array is a mistake: the other kind would be dropped without a word. */
|
|
3078
|
+
function refuseMixed(form, kept, dropped) {
|
|
3079
|
+
if (dropped > 0) throw new Error(`runMigrations(${form}): ${dropped} of ${kept + dropped} entries are of the other kind and would be dropped; pass one kind per call`);
|
|
3080
|
+
}
|
|
3081
|
+
function catalogueOf(list) {
|
|
3082
|
+
const kept = list.filter((entry) => !("execute" in entry));
|
|
3083
|
+
refuseMixed("catalogue, (api) => ports", kept.length, list.length - kept.length);
|
|
3084
|
+
return kept;
|
|
3085
|
+
}
|
|
3086
|
+
function boundOf(list) {
|
|
3087
|
+
const kept = list.filter((entry) => "execute" in entry);
|
|
3088
|
+
refuseMixed("bound migrations", kept.length, list.length - kept.length);
|
|
3089
|
+
return kept;
|
|
3090
|
+
}
|
|
3091
|
+
/**
|
|
3092
|
+
* Base class for CamStack addons. Eliminates settings boilerplate:
|
|
3093
|
+
*
|
|
3094
|
+
* - Typed `config` property with automatic resolution from store + defaults
|
|
3095
|
+
* - the scoped settings API (`clusterSettings` / `nodeSettings` / `deviceDefaults`) auto-implemented
|
|
3096
|
+
* - `getAddonSettings()` / `updateAddonSettings()` auto-implemented
|
|
3097
|
+
* - `getDeviceSettings()` / `updateDeviceSettings()` auto-implemented
|
|
3098
|
+
* - `ctx` accessor for the AddonContext (no manual `this.ctxRef` storage)
|
|
3099
|
+
* - `field()` helper that constrains field keys to TConfig keys
|
|
3100
|
+
* - `schema()` helper that validates the full schema structure
|
|
3101
|
+
*
|
|
3102
|
+
* Subclasses override:
|
|
3103
|
+
* - `onInitialize()` — addon-specific init logic, return ProviderRegistration[]
|
|
3104
|
+
* - `onShutdown()` — cleanup
|
|
3105
|
+
* - `clusterSettingsSchema()` / `nodeSettingsSchema()` / `deviceSettingsSchema()` — UI schemas
|
|
3106
|
+
*
|
|
3107
|
+
* @example
|
|
3108
|
+
* ```ts
|
|
3109
|
+
* interface MyConfig {
|
|
3110
|
+
* maxRetries: number
|
|
3111
|
+
* endpoint: string
|
|
3112
|
+
* }
|
|
3113
|
+
*
|
|
3114
|
+
* export default class MyAddon extends BaseAddon<MyConfig> {
|
|
3115
|
+
* constructor() {
|
|
3116
|
+
* super({ maxRetries: 3, endpoint: 'http://localhost' })
|
|
3117
|
+
* }
|
|
3118
|
+
*
|
|
3119
|
+
* protected clusterSettingsSchema() {
|
|
3120
|
+
* return this.schema({
|
|
3121
|
+
* sections: [{
|
|
3122
|
+
* id: 'main', title: 'Settings',
|
|
3123
|
+
* fields: [
|
|
3124
|
+
* this.field({ type: 'number', key: 'maxRetries', label: 'Max Retries', default: 3 }),
|
|
3125
|
+
* this.field({ type: 'text', key: 'endpoint', label: 'Endpoint' }),
|
|
3126
|
+
* ],
|
|
3127
|
+
* }],
|
|
3128
|
+
* })
|
|
3129
|
+
* }
|
|
3130
|
+
*
|
|
3131
|
+
* protected async onInitialize(): Promise<ProviderRegistration[]> {
|
|
3132
|
+
* const client = new Client(this.config.endpoint, this.config.maxRetries)
|
|
3133
|
+
* return [{ capability: 'my-feature', provider: client }]
|
|
3134
|
+
* }
|
|
3135
|
+
* }
|
|
3136
|
+
* ```
|
|
3137
|
+
*/
|
|
3138
|
+
var BaseAddon = class {
|
|
3139
|
+
_ctx = null;
|
|
3140
|
+
_config;
|
|
3141
|
+
/**
|
|
3142
|
+
* Per-process random id used as the `generation` stamp on every
|
|
3143
|
+
* `system.ready-state` event this addon emits. Constant for the
|
|
3144
|
+
* lifetime of this addon instance (== one process boot); consumer-
|
|
3145
|
+
* side registries derive a monotonic `epoch` by watching for
|
|
3146
|
+
* generation transitions.
|
|
3147
|
+
*/
|
|
3148
|
+
_readinessGeneration = typeof crypto !== "undefined" && crypto.randomUUID ? crypto.randomUUID() : Math.random().toString(36).slice(2, 14);
|
|
3149
|
+
/** Capability names this addon registered at init — used to emit matching `down` events on shutdown. */
|
|
3150
|
+
_registeredCapNames = [];
|
|
3151
|
+
/**
|
|
3152
|
+
* True only after `readAddonStore` actually answered. Constructor
|
|
3153
|
+
* defaults look like stored config when the store is down — a forked
|
|
3154
|
+
* addon that auto-starts from those defaults (cloudflare-tunnel quick
|
|
3155
|
+
* mode, 2026-08-25) is not "the operator chose this".
|
|
3156
|
+
*/
|
|
3157
|
+
settingsStoreReady = false;
|
|
3158
|
+
/** Default config values. Provided via constructor. */
|
|
3159
|
+
defaults;
|
|
3160
|
+
/**
|
|
3161
|
+
* Hidden-state paths that hold secrets (D787) — values the addon writes
|
|
3162
|
+
* itself (`state()`, the scoped writers) that no form field declares.
|
|
3163
|
+
* Stored in the keychain exactly like a `password` field. Syntax:
|
|
3164
|
+
* `'snapshotSigningKey'`, `'identity.pincode'`, `'tokens[userId].accessToken'`
|
|
3165
|
+
* (`key[<id field>]` addresses array items by id, never by index).
|
|
3166
|
+
*/
|
|
3167
|
+
secretStatePaths = [];
|
|
3168
|
+
_addonSecretTree = null;
|
|
3169
|
+
/**
|
|
3170
|
+
* D986 M4: the scoped schemas this addon declared, resolved once per capability
|
|
3171
|
+
* (`loadScopedSchemas`) so the sync readers (`perNodeKeys`, the secret tree, the restart check)
|
|
3172
|
+
* see them. Empty until loaded.
|
|
3173
|
+
*/
|
|
3174
|
+
_scopedByCap = /* @__PURE__ */ new Map();
|
|
3175
|
+
_nodeKeysByCap = /* @__PURE__ */ new Map();
|
|
3176
|
+
_deviceSecretTree = null;
|
|
3177
|
+
/** Refs the last resolved config pointed at — a change to one re-resolves. */
|
|
3178
|
+
_configSecretRefs = /* @__PURE__ */ new Set();
|
|
3179
|
+
_unresolvedSecrets = [];
|
|
3180
|
+
_secretRetryTimer = null;
|
|
3181
|
+
_secretRetryDelayMs = SECRET_RETRY_FIRST_MS;
|
|
3182
|
+
_secretChangeTimer = null;
|
|
3183
|
+
_secretChangeUnsub = null;
|
|
3184
|
+
/** >0 while an OPERATOR's settings write is being applied. */
|
|
3185
|
+
_operatorWriteDepth = 0;
|
|
3186
|
+
/**
|
|
3187
|
+
* The keychain-aware settings handle (D798). Its `raw` view is the ONLY way
|
|
3188
|
+
* to the marker-bearing blobs and stays private to this class: the form
|
|
3189
|
+
* hydrate and config resolution need markers, addon code never does.
|
|
3190
|
+
*/
|
|
3191
|
+
_secretSettings = null;
|
|
3192
|
+
/** Refs an addon-facing read could not resolve — each is logged once per process. */
|
|
3193
|
+
_loggedUnresolvedReads = /* @__PURE__ */ new Set();
|
|
3194
|
+
constructor(defaults) {
|
|
3195
|
+
this.defaults = defaults;
|
|
3196
|
+
this._config = { ...defaults };
|
|
3197
|
+
}
|
|
3198
|
+
/**
|
|
3199
|
+
* Override to opt out of the automatic `system.ready-state` emission.
|
|
3200
|
+
* Returns `true` by default — addons that don't map cleanly to the
|
|
3201
|
+
* readiness protocol (e.g. pure collection providers whose readiness
|
|
3202
|
+
* is already reported per-device by upstream) can override to `false`
|
|
3203
|
+
* and emit manually.
|
|
3204
|
+
*/
|
|
3205
|
+
get autoEmitReadiness() {
|
|
3206
|
+
return true;
|
|
3207
|
+
}
|
|
3208
|
+
/** The AddonContext, available after initialize(). */
|
|
3209
|
+
get ctx() {
|
|
3210
|
+
if (!this._ctx) throw new Error(`${this.constructor.name}: ctx accessed before initialize()`);
|
|
3211
|
+
return this._ctx;
|
|
3212
|
+
}
|
|
3213
|
+
/**
|
|
3214
|
+
* Non-throwing ctx accessor for code paths that can legitimately run
|
|
3215
|
+
* before `initialize()` has resolved — most commonly cap handlers the
|
|
3216
|
+
* hub invokes eagerly at page load (device-details aggregator pings
|
|
3217
|
+
* every addon's `getDeviceSettingsContribution` as soon as the page
|
|
3218
|
+
* mounts). Prefer `ctx` for the normal case; reach for this only in
|
|
3219
|
+
* capability methods that may be queried before the addon is wired up.
|
|
3220
|
+
*/
|
|
3221
|
+
get ctxIfReady() {
|
|
3222
|
+
return this._ctx;
|
|
3223
|
+
}
|
|
3224
|
+
/** Current resolved config (defaults merged with persisted store values). */
|
|
3225
|
+
get config() {
|
|
3226
|
+
return this._config;
|
|
3227
|
+
}
|
|
3228
|
+
async initialize(context) {
|
|
3229
|
+
const secrets = context.secrets;
|
|
3230
|
+
if (secrets !== void 0) {
|
|
3231
|
+
const { context: wrapped, handle } = createSecretAwareContext(context, {
|
|
3232
|
+
secrets,
|
|
3233
|
+
addonTree: () => this.addonSecretTree(),
|
|
3234
|
+
deviceTree: () => this.deviceSecretTree(),
|
|
3235
|
+
onOrphaned: (refs) => context.logger.warn("keychain refs dropped by a settings write could not be deleted", { meta: { refs: [...refs] } }),
|
|
3236
|
+
isOperatorWrite: () => this._operatorWriteDepth > 0,
|
|
3237
|
+
onUnresolved: (unresolved) => this.logUnresolvedRead(unresolved)
|
|
3238
|
+
});
|
|
3239
|
+
this._ctx = wrapped;
|
|
3240
|
+
this._secretSettings = handle;
|
|
3241
|
+
} else {
|
|
3242
|
+
this._ctx = context;
|
|
3243
|
+
this._secretSettings = null;
|
|
3244
|
+
}
|
|
3245
|
+
await this.loadScopedSchemas();
|
|
3246
|
+
await this.resolveConfig();
|
|
3247
|
+
if (secrets !== void 0) this._secretChangeUnsub = secrets.onChange((ref) => {
|
|
3248
|
+
if (this._configSecretRefs.has(ref)) this.scheduleSecretReresolve(SECRET_CHANGE_DEBOUNCE_MS);
|
|
3249
|
+
});
|
|
3250
|
+
await this.hydrateSwitches();
|
|
3251
|
+
const result = await this.onInitialize();
|
|
3252
|
+
await this.moveLateInstanceKinds();
|
|
3253
|
+
await this.adoptUnrowed();
|
|
3254
|
+
if (this.switchesHydrated) {
|
|
3255
|
+
settleHydration(this.ctx.id);
|
|
3256
|
+
for (const served of servedInstanceKindsOf(this.ctx.id)) await served.reapply();
|
|
3257
|
+
}
|
|
3258
|
+
this.emitLifecycle(EventCategory.AddonStarted);
|
|
3259
|
+
const normalized = normalizeAddonInitResult(result);
|
|
3260
|
+
const providers = normalized && "providers" in normalized && normalized.providers ? normalized.providers : [];
|
|
3261
|
+
this._registeredCapNames = providers.map((p) => p.capability.name);
|
|
3262
|
+
await this.loadScopedSchemas();
|
|
3263
|
+
return normalized;
|
|
3264
|
+
}
|
|
3265
|
+
async runMigrations(first, second, third) {
|
|
3266
|
+
if (typeof second === "function") return this.runMigrationSets([migrationSet(catalogueOf(first), second)], third);
|
|
3267
|
+
return this.runBound(boundOf(first), second);
|
|
3268
|
+
}
|
|
3269
|
+
/**
|
|
3270
|
+
* Several catalogues of ONE owner in one declaration (the engine replaces an owner's
|
|
3271
|
+
* catalogue on every declare, so two calls would each judge the other's ids "newer").
|
|
3272
|
+
* Build each entry with `migrationSet(catalogue, (api) => ports)`.
|
|
3273
|
+
*/
|
|
3274
|
+
async runMigrationSets(sets, options) {
|
|
3275
|
+
const api = this.ctx.migrationApi;
|
|
3276
|
+
if (api === void 0) throw new Error(`${this.ctx.id}: the migration API is not available on this context`);
|
|
3277
|
+
return this.runBound(sets.flatMap((set) => set.bind(api)), options);
|
|
3278
|
+
}
|
|
3279
|
+
/**
|
|
3280
|
+
* A device addon states its instance kind once, before its migrations run, and the one-switch
|
|
3281
|
+
* migration (registry `enabled` to the instance body, epic #440 step 3) joins whatever
|
|
3282
|
+
* catalogue the addon runs, in the SAME declaration (the engine replaces an owner's catalogue
|
|
3283
|
+
* on every declare).
|
|
3284
|
+
*/
|
|
3285
|
+
declareRegistrySwitch(spec) {
|
|
3286
|
+
this.registrySwitchSpec = spec;
|
|
3287
|
+
}
|
|
3288
|
+
/**
|
|
3289
|
+
* Ids this addon removed from its catalogue on purpose (`declareRetiredMigrations`): sent with
|
|
3290
|
+
* every declaration so the engine does not read their applied rows as a newer database.
|
|
3291
|
+
*/
|
|
3292
|
+
retiredMigrationIds = [];
|
|
3293
|
+
declareRetiredMigrations(ids) {
|
|
3294
|
+
this.retiredMigrationIds = ids;
|
|
3295
|
+
}
|
|
3296
|
+
registrySwitchSpec = null;
|
|
3297
|
+
/** The instance kinds whose switch move this process already ran (or tried), by record kind name. */
|
|
3298
|
+
switchMoved = /* @__PURE__ */ new Set();
|
|
3299
|
+
lastDeclared = [];
|
|
3300
|
+
registrySwitchBound() {
|
|
3301
|
+
const api = this.ctx.migrationApi;
|
|
3302
|
+
const spec = this.registrySwitchSpec;
|
|
3303
|
+
const kinds = servedInstanceKindsOf(this.ctx.id).filter((k) => !this.switchMoved.has(k.kind.name));
|
|
3304
|
+
if (spec === null && kinds.length === 0) return [];
|
|
3305
|
+
if (api === void 0) {
|
|
3306
|
+
this.ctx.logger.warn("the registry switch migration is skipped: the migration API is not available on this context");
|
|
3307
|
+
return [];
|
|
3308
|
+
}
|
|
3309
|
+
const date = "2026-11-06";
|
|
3310
|
+
const moveIn = spec === null ? [] : migrationSet([registrySwitchToBodyMigration({
|
|
3311
|
+
addonId: this.ctx.id,
|
|
3312
|
+
date,
|
|
3313
|
+
seq: 1e3,
|
|
3314
|
+
initialBody: spec.initialBody
|
|
3315
|
+
})], (a) => registrySwitchPortsOver({
|
|
3316
|
+
api: integrationRowsApiOver(a),
|
|
3317
|
+
records: switchRecordsOverMigrationApi(a),
|
|
3318
|
+
kind: spec.kind
|
|
3319
|
+
})).bind(api);
|
|
3320
|
+
const moveBack = kinds.flatMap(({ kind }, index) => {
|
|
3321
|
+
this.switchMoved.add(kind.name);
|
|
3322
|
+
return migrationSet([bodySwitchToRegistryMigration({
|
|
3323
|
+
addonId: this.ctx.id,
|
|
3324
|
+
date: "2026-11-19",
|
|
3325
|
+
seq: 1001 + index,
|
|
3326
|
+
kindName: kind.name,
|
|
3327
|
+
...spec === null ? {} : { followsDate: date }
|
|
3328
|
+
})], (a) => bodySwitchPortsOver({
|
|
3329
|
+
records: bodySwitchRecordsOverMigrationApi(a),
|
|
3330
|
+
kind,
|
|
3331
|
+
nameField: kind.declaration.entry?.nameField ?? "name",
|
|
3332
|
+
adopt: (addonId, rows) => this.ctx.api.integrations.adoptInstanceRows.mutate({
|
|
3333
|
+
addonId,
|
|
3334
|
+
rows: [...rows]
|
|
3335
|
+
}),
|
|
3336
|
+
warn: async (message) => {
|
|
3337
|
+
await a.log.warn({ message });
|
|
3338
|
+
}
|
|
3339
|
+
})).bind(api);
|
|
3340
|
+
});
|
|
3341
|
+
return [...moveIn, ...moveBack];
|
|
3342
|
+
}
|
|
3343
|
+
/**
|
|
3344
|
+
* A helper built AFTER the addon's migrations ran has a kind that moved nothing yet. Run its
|
|
3345
|
+
* switch move now (the engine replaces an owner's catalogue on every declare, so the whole
|
|
3346
|
+
* declared set goes with it, phased to the late ids), read the registry again, and tell the
|
|
3347
|
+
* addon about every instance that is off so it stops what it started on the default.
|
|
3348
|
+
*/
|
|
3349
|
+
async moveLateInstanceKinds() {
|
|
3350
|
+
const late = servedInstanceKindsOf(this.ctx.id).filter((k) => !this.switchMoved.has(k.kind.name));
|
|
3351
|
+
if (late.length === 0) return;
|
|
3352
|
+
try {
|
|
3353
|
+
const only = late.map((k) => bodySwitchToRegistryId(this.ctx.id, "2026-11-19", k.kind.name));
|
|
3354
|
+
await this.runBound(this.lastDeclared, { only });
|
|
3355
|
+
} catch (err) {
|
|
3356
|
+
if (err instanceof AddonMigrationsBlockedError) throw err;
|
|
3357
|
+
this.ctx.logger.error("the late instance switch move failed", { meta: { error: errMsg(err) } });
|
|
3358
|
+
}
|
|
3359
|
+
}
|
|
3360
|
+
async runBound(declared, options) {
|
|
3361
|
+
this.lastDeclared = declared;
|
|
3362
|
+
const added = this.registrySwitchBound();
|
|
3363
|
+
const migrations = [...declared, ...added];
|
|
3364
|
+
const widened = options?.only === void 0 || added.length === 0 ? options : {
|
|
3365
|
+
...options,
|
|
3366
|
+
only: [...new Set([...options.only, ...added.map((m) => m.meta.id)])]
|
|
3367
|
+
};
|
|
3368
|
+
const phased = this.retiredMigrationIds.length === 0 ? widened ?? {} : {
|
|
3369
|
+
...widened,
|
|
3370
|
+
retired: this.retiredMigrationIds
|
|
3371
|
+
};
|
|
3372
|
+
const api = this.ctx.api.migrations;
|
|
3373
|
+
const report = await runAddonMigrations({
|
|
3374
|
+
declareOwner: (input) => api.declareOwner.mutate(input),
|
|
3375
|
+
startMigration: (input) => api.startMigration.mutate(input),
|
|
3376
|
+
finishMigration: (input) => api.finishMigration.mutate(input)
|
|
3377
|
+
}, migrations, this.ctx.logger, phased);
|
|
3378
|
+
if (report.blockOwner.length > 0) throw new AddonMigrationsBlockedError(report.blockOwner);
|
|
3379
|
+
await this.hydrateSwitches();
|
|
3380
|
+
await this.adoptUnrowed();
|
|
3381
|
+
return report;
|
|
3382
|
+
}
|
|
3383
|
+
/**
|
|
3384
|
+
* Learn the on/off state of this addon's instances from the registry rows (D1066), at boot, after
|
|
3385
|
+
* a migration run, and again through {@link rehydrateSwitches}. It runs on the addon's own boot
|
|
3386
|
+
* path, never inside a method the hub calls into. A registry that cannot answer leaves the
|
|
3387
|
+
* instances of THIS addon reading off (fail closed, per owner) until a read answers.
|
|
3388
|
+
*/
|
|
3389
|
+
switchesHydrated = false;
|
|
3390
|
+
async hydrateSwitches() {
|
|
3391
|
+
beginHydration(this.ctx.id);
|
|
3392
|
+
try {
|
|
3393
|
+
const rows = await this.ctx.api.integrations.listByAddon.query({ addonId: this.ctx.id });
|
|
3394
|
+
hydrateInstanceSwitches(this.ctx.id, rows);
|
|
3395
|
+
this.switchesHydrated = true;
|
|
3396
|
+
return true;
|
|
3397
|
+
} catch (err) {
|
|
3398
|
+
this.ctx.logger.warn("instance switches not read from the registry: instances stay off", { meta: { error: errMsg(err) } });
|
|
3399
|
+
return false;
|
|
3400
|
+
}
|
|
3401
|
+
}
|
|
3402
|
+
/**
|
|
3403
|
+
* Every record of a served kind the registry holds no row for (created outside the hub door:
|
|
3404
|
+
* a seed, a store write) is adopted with the state it effectively had, on unless this process
|
|
3405
|
+
* stated it off, so the hub can switch it. A failure is logged; the next hydration retries.
|
|
3406
|
+
*/
|
|
3407
|
+
async adoptUnrowed() {
|
|
3408
|
+
if (!this.switchesHydrated) return;
|
|
3409
|
+
try {
|
|
3410
|
+
for (const served of servedInstanceKindsOf(this.ctx.id)) {
|
|
3411
|
+
const rows = await served.unrowed();
|
|
3412
|
+
if (rows.length === 0) continue;
|
|
3413
|
+
await this.ctx.api.integrations.adoptInstanceRows.mutate({
|
|
3414
|
+
addonId: this.ctx.id,
|
|
3415
|
+
rows: rows.map((r) => ({
|
|
3416
|
+
id: r.id,
|
|
3417
|
+
name: r.name,
|
|
3418
|
+
enabled: r.enabled,
|
|
3419
|
+
stated: false
|
|
3420
|
+
}))
|
|
3421
|
+
});
|
|
3422
|
+
for (const r of rows) recordRegistrySwitch(r.id, r.enabled);
|
|
3423
|
+
}
|
|
3424
|
+
} catch (err) {
|
|
3425
|
+
this.ctx.logger.warn("records without a registry row were not adopted", { meta: { error: errMsg(err) } });
|
|
3426
|
+
}
|
|
3427
|
+
}
|
|
3428
|
+
/**
|
|
3429
|
+
* Read the switches from the registry again and announce the states now known, so an addon that
|
|
3430
|
+
* started on the fail-closed default (off) starts what is on. Throws
|
|
3431
|
+
* {@link InstanceSwitchesUnreadError} when the registry still does not answer while this addon
|
|
3432
|
+
* serves instance kinds: a forked runner turns that into a failed boot (the supervisor respawns
|
|
3433
|
+
* it, bounded, D6), an agent or the hub reads again on the next hub connect (event-driven, D3).
|
|
3434
|
+
* An addon with no instance kind has nothing waiting and never throws.
|
|
3435
|
+
*/
|
|
3436
|
+
async rehydrateSwitches() {
|
|
3437
|
+
if (this._ctx === null) return;
|
|
3438
|
+
if (await this.hydrateSwitches()) {
|
|
3439
|
+
await this.adoptUnrowed();
|
|
3440
|
+
settleHydration(this.ctx.id);
|
|
3441
|
+
for (const served of servedInstanceKindsOf(this.ctx.id)) await served.reapply();
|
|
3442
|
+
return;
|
|
3443
|
+
}
|
|
3444
|
+
if (isHydrationPending(this.ctx.id)) throw new InstanceSwitchesUnreadError(this.ctx.id);
|
|
3445
|
+
}
|
|
3446
|
+
/**
|
|
3447
|
+
* Called on the hub-reachable event (instead of `onHubReachable` directly): the switches are
|
|
3448
|
+
* read again, then `onHubReachable` runs. A registry that still does not answer is logged and
|
|
3449
|
+
* left for the next connect.
|
|
3450
|
+
*/
|
|
3451
|
+
async hubReachable() {
|
|
3452
|
+
try {
|
|
3453
|
+
await this.rehydrateSwitches();
|
|
3454
|
+
} catch (err) {
|
|
3455
|
+
this.ctx.logger.warn("instance switches still unread at the hub connect", { meta: { error: errMsg(err) } });
|
|
3456
|
+
}
|
|
3457
|
+
await this.onHubReachable();
|
|
3458
|
+
}
|
|
3459
|
+
/**
|
|
3460
|
+
* Called by the isolated-process runner AFTER `broker.start()`.
|
|
3461
|
+
* In-process addons never need this because the hub broker is already
|
|
3462
|
+
* running when `initialize()` fires. For forked children the broker
|
|
3463
|
+
* starts AFTER `initialize()`, so the readiness emit inside initialize()
|
|
3464
|
+
* fires before the broker can broadcast it. This method re-emits the
|
|
3465
|
+
* ready state once the transport is live.
|
|
3466
|
+
*/
|
|
3467
|
+
postBrokerStart() {
|
|
3468
|
+
if (this.autoEmitReadiness && this._registeredCapNames.length > 0) this.emitReadinessForProviders("ready");
|
|
3469
|
+
}
|
|
3470
|
+
/**
|
|
3471
|
+
* Called by the isolated-process runner / agent bootstrap once the broker
|
|
3472
|
+
* has started AND the hub node is connected — the moment `ctx.api.*` calls
|
|
3473
|
+
* to hub-provided capabilities become safe. Wrap any bootstrap work that
|
|
3474
|
+
* must query the hub (device restore, settings fetch, initial sync) in
|
|
3475
|
+
* `onHubConnected()` rather than `onInitialize()` — during `initialize()`
|
|
3476
|
+
* on a worker the broker is not yet connected and remote cap calls either
|
|
3477
|
+
* time out or throw "Service not found".
|
|
3478
|
+
*
|
|
3479
|
+
* Default implementation is a no-op. Override in subclasses that need it.
|
|
3480
|
+
* Never fires on hub-local in-process addons (the hub is its own node).
|
|
3481
|
+
*/
|
|
3482
|
+
async onHubReachable() {}
|
|
3483
|
+
async shutdown() {
|
|
3484
|
+
this._secretChangeUnsub?.();
|
|
3485
|
+
this._secretChangeUnsub = null;
|
|
3486
|
+
if (this._secretRetryTimer !== null) clearTimeout(this._secretRetryTimer);
|
|
3487
|
+
if (this._secretChangeTimer !== null) clearTimeout(this._secretChangeTimer);
|
|
3488
|
+
this._secretRetryTimer = null;
|
|
3489
|
+
this._secretChangeTimer = null;
|
|
3490
|
+
this.emitLifecycle(EventCategory.AddonStopped);
|
|
3491
|
+
if (this.autoEmitReadiness) this.emitReadinessForProviders("down");
|
|
3492
|
+
await this.onShutdown();
|
|
3493
|
+
for (const unsub of this._subscriptions) unsub();
|
|
3494
|
+
this._subscriptions = [];
|
|
3495
|
+
this._ctx = null;
|
|
3496
|
+
}
|
|
3497
|
+
/** Addon-specific cleanup. Override if needed. */
|
|
3498
|
+
async onShutdown() {}
|
|
3499
|
+
/**
|
|
3500
|
+
* Called after config is resolved during a settings write.
|
|
3501
|
+
* Override to react to config changes (e.g. restart a sampler, reconnect a service).
|
|
3502
|
+
* Not called during initialize() — use onInitialize() for initial setup.
|
|
3503
|
+
*/
|
|
3504
|
+
async onConfigChanged() {}
|
|
3505
|
+
/**
|
|
3506
|
+
* Create a ConfigField with `key` constrained to keys of TConfig.
|
|
3507
|
+
* Provides autocomplete and compile-time validation.
|
|
3508
|
+
*/
|
|
3509
|
+
field(field) {
|
|
3510
|
+
return field;
|
|
3511
|
+
}
|
|
3512
|
+
/**
|
|
3513
|
+
* Create a full ConfigUISchema with typed sections.
|
|
3514
|
+
* Fields created via `this.field()` get key validation automatically.
|
|
3515
|
+
*/
|
|
3516
|
+
schema(schema) {
|
|
3517
|
+
return schema;
|
|
3518
|
+
}
|
|
3519
|
+
/**
|
|
3520
|
+
* The capability names whose scoped settings schemas ({@link clusterSettingsSchema},
|
|
3521
|
+
* {@link nodeSettingsSchema}, {@link deviceDefaultsSchema}) this addon declares. Read BEFORE
|
|
3522
|
+
* `onInitialize`, when the providers it registers are not known yet: the first config resolve
|
|
3523
|
+
* must already know which keys are per node. Names the providers register at init are added
|
|
3524
|
+
* once known.
|
|
3525
|
+
*/
|
|
3526
|
+
scopedSettingsCapabilities() {
|
|
3527
|
+
return [];
|
|
3528
|
+
}
|
|
3529
|
+
/** Override to provide device-level settings UI schema. */
|
|
3530
|
+
deviceSettingsSchema() {
|
|
3531
|
+
return null;
|
|
3532
|
+
}
|
|
3533
|
+
/**
|
|
3534
|
+
* D986 scoped settings: the form shape of the CLUSTER-wide settings one capability this addon
|
|
3535
|
+
* provides owns, or `null` when it has none. `cap` is a capability name the addon's manifest
|
|
3536
|
+
* declares. Stored as `addon-settings` rows `<addonId>.<field>`. The keys of this schema, of
|
|
3537
|
+
* {@link nodeSettingsSchema} and of {@link deviceDefaultsSchema} are disjoint, and a key never
|
|
3538
|
+
* contains `@` (guard `check-scoped-settings-declared`). SHAPE only: values are read by scope.
|
|
3539
|
+
*/
|
|
3540
|
+
async clusterSettingsSchema(_cap) {
|
|
3541
|
+
return null;
|
|
3542
|
+
}
|
|
3543
|
+
/**
|
|
3544
|
+
* D986: the form shape of the settings one capability owns PER NODE, or `null`. Stored as
|
|
3545
|
+
* `addon-settings` rows `<addonId>.<field>@<nodeId>` carrying `nodeId` in the row data, so a
|
|
3546
|
+
* forgotten node's rows go in one central delete.
|
|
3547
|
+
*/
|
|
3548
|
+
async nodeSettingsSchema(_cap) {
|
|
3549
|
+
return null;
|
|
3550
|
+
}
|
|
3551
|
+
/**
|
|
3552
|
+
* D986: the form shape of the FLEET DEFAULTS of the per-device settings one capability owns,
|
|
3553
|
+
* or `null`. Stored as `addon-settings` rows `<addonId>.<field>`; a device resolves its value
|
|
3554
|
+
* as device row, then this default, then the schema default (`resolveDeviceSettings`).
|
|
3555
|
+
*/
|
|
3556
|
+
async deviceDefaultsSchema(_cap) {
|
|
3557
|
+
return null;
|
|
3558
|
+
}
|
|
3559
|
+
/**
|
|
3560
|
+
* The host's read of the scoped declarations: the schema one capability declares for `scope`,
|
|
3561
|
+
* or `null`. The hook is protected, the host asks this method.
|
|
3562
|
+
*/
|
|
3563
|
+
async getScopedSettingsSchema(scope, cap) {
|
|
3564
|
+
switch (scope) {
|
|
3565
|
+
case "cluster": return this.clusterSettingsSchema(cap);
|
|
3566
|
+
case "node": return this.nodeSettingsSchema(cap);
|
|
3567
|
+
case "device-defaults": return this.deviceDefaultsSchema(cap);
|
|
3568
|
+
}
|
|
3569
|
+
}
|
|
3570
|
+
/**
|
|
3571
|
+
* Hook: values layered over the stored ones when the FORM of one scope is served
|
|
3572
|
+
* ({@link getScopedSettings}) — a preview that derives dependent options without writing.
|
|
3573
|
+
* Never applied to {@link ScopedSettings.get} or to a write. `null` ⇒ no overlay.
|
|
3574
|
+
*/
|
|
3575
|
+
async scopedSettingsOverlay(_scope, _cap, _nodeId) {
|
|
3576
|
+
return null;
|
|
3577
|
+
}
|
|
3578
|
+
/**
|
|
3579
|
+
* Hook: a write of one scope changed stored values (not called when the store reports no change,
|
|
3580
|
+
* e.g. the write-back of a stored secret). `keys` are the bare field keys of the write, node keys included.
|
|
3581
|
+
*/
|
|
3582
|
+
async onScopedSettingsChanged(_scope, _cap, _keys) {}
|
|
3583
|
+
/** Typed handle over the CLUSTER settings `cap` declares (`clusterSettingsSchema`). */
|
|
3584
|
+
clusterSettings(cap, schema) {
|
|
3585
|
+
return this.scopedHandle("cluster", cap, schema);
|
|
3586
|
+
}
|
|
3587
|
+
/** Typed handle over the fleet defaults of the per-device settings `cap` declares. */
|
|
3588
|
+
deviceDefaults(cap, schema) {
|
|
3589
|
+
return this.scopedHandle("device-defaults", cap, schema);
|
|
3590
|
+
}
|
|
3591
|
+
/**
|
|
3592
|
+
* Typed handle over the settings `cap` owns PER NODE. `nodeId` omitted ⇒ the local node. A node
|
|
3593
|
+
* with no row yields the schema defaults — never a bare-key fallback.
|
|
3594
|
+
*/
|
|
3595
|
+
nodeSettings(cap, schema, nodeId) {
|
|
3596
|
+
return this.scopedHandle("node", cap, schema, nodeId);
|
|
3597
|
+
}
|
|
3598
|
+
/**
|
|
3599
|
+
* {@link state} for a value that is kept per node: stored under `<key>@<nodeId>`, and the
|
|
3600
|
+
* settings store carries `nodeId` in the row data (D986 §1), so a forgotten node's rows go in one
|
|
3601
|
+
* central delete. `nodeId` omitted ⇒ the local node.
|
|
3602
|
+
*/
|
|
3603
|
+
nodeState(key, schema, fallback, nodeId) {
|
|
3604
|
+
this._declaredStateKeys.add(key);
|
|
3605
|
+
return createDurableState({
|
|
3606
|
+
key: nodeScopedKey(key, nodeId ?? this._ctx?.kernel?.localNodeId ?? ""),
|
|
3607
|
+
schema,
|
|
3608
|
+
fallback,
|
|
3609
|
+
read: async () => this.resolveStoredSecrets(await this.readAddonStoreWithRetry()),
|
|
3610
|
+
write: async (patch) => {
|
|
3611
|
+
await this._ctx?.settings?.writeAddonStore(patch);
|
|
3612
|
+
},
|
|
3613
|
+
onParseError: (k, e) => this._ctx?.logger?.warn?.(`durable-state: stored "${k}" failed validation — using fallback`, { meta: {
|
|
3614
|
+
addonId: this._ctx?.id,
|
|
3615
|
+
key: k,
|
|
3616
|
+
error: String(e)
|
|
3617
|
+
} })
|
|
3618
|
+
});
|
|
3619
|
+
}
|
|
3620
|
+
/** The loaded schema `cap` declares for `scope`, or `null`. */
|
|
3621
|
+
async declaredScopedSchema(scope, cap) {
|
|
3622
|
+
await this.loadScopedSchemas(cap);
|
|
3623
|
+
return this.loadedScopedSchemas(cap).find((entry) => entry.scope === scope)?.schema ?? null;
|
|
3624
|
+
}
|
|
3625
|
+
async requireScopedSchema(scope, cap) {
|
|
3626
|
+
const schema = await this.declaredScopedSchema(scope, cap);
|
|
3627
|
+
if (schema === null) throw new Error(`${this.constructor.name}: cap "${cap}" declares no ${scope} settings`);
|
|
3628
|
+
return schema;
|
|
3629
|
+
}
|
|
3630
|
+
scopedKeys(schema) {
|
|
3631
|
+
return new Set(schema.sections.flatMap((section) => collectValueFieldKeys(section.fields)));
|
|
3632
|
+
}
|
|
3633
|
+
/** `store` narrowed to the keys `schema` declares. */
|
|
3634
|
+
narrowToScope(store, schema) {
|
|
3635
|
+
const keys = this.scopedKeys(schema);
|
|
3636
|
+
return Object.fromEntries(Object.entries(store).filter(([key]) => keys.has(key)));
|
|
3637
|
+
}
|
|
3638
|
+
scopedHandle(scope, cap, schema, nodeId) {
|
|
3639
|
+
return createScopedSettings({
|
|
3640
|
+
schema,
|
|
3641
|
+
read: async () => {
|
|
3642
|
+
const declared = await this.requireScopedSchema(scope, cap);
|
|
3643
|
+
const stored = this.narrowToScope(await this.resolveGlobalStore(nodeId, cap), declared);
|
|
3644
|
+
const effective = collectHydratedFieldValues(hydrateSchema(declared, stored));
|
|
3645
|
+
return {
|
|
3646
|
+
...Object.fromEntries([...effective].filter(([, value]) => value !== void 0)),
|
|
3647
|
+
...stored
|
|
3648
|
+
};
|
|
3649
|
+
},
|
|
3650
|
+
write: (patch) => this.writeScoped(scope, cap, patch, nodeId),
|
|
3651
|
+
unset: (keys) => this.unsetScoped(scope, cap, keys, nodeId)
|
|
3652
|
+
});
|
|
3653
|
+
}
|
|
3654
|
+
/** The one write path of the scoped API: declared keys only, then the global patch. */
|
|
3655
|
+
async writeScoped(scope, cap, patch, nodeId) {
|
|
3656
|
+
assertDeclaredKeys(Object.keys(patch), this.scopedKeys(await this.requireScopedSchema(scope, cap)));
|
|
3657
|
+
if (await this.applyGlobalPatch(patch, scope === "node" ? nodeId : void 0, cap)) await this.onScopedSettingsChanged(scope, cap, Object.keys(patch));
|
|
3658
|
+
}
|
|
3659
|
+
/**
|
|
3660
|
+
* Remove declared keys of one scope. A secret goes through {@link clearSecrets} — its keychain
|
|
3661
|
+
* value is released exactly as there — and the emptied row is then removed; every other key is
|
|
3662
|
+
* removed by an `undefined` patch (which a secret transform would read as "keep").
|
|
3663
|
+
*/
|
|
3664
|
+
async unsetScoped(scope, cap, keys, nodeId) {
|
|
3665
|
+
assertDeclaredKeys(keys, this.scopedKeys(await this.requireScopedSchema(scope, cap)));
|
|
3666
|
+
const target = scope === "node" ? nodeId : void 0;
|
|
3667
|
+
const tree = this.addonSecretTree();
|
|
3668
|
+
const secretKeys = keys.filter((key) => tree.has(key));
|
|
3669
|
+
const plainKeys = keys.filter((key) => !tree.has(key));
|
|
3670
|
+
let changed = false;
|
|
3671
|
+
if (plainKeys.length > 0) {
|
|
3672
|
+
const patch = Object.fromEntries(plainKeys.map((key) => [key, void 0]));
|
|
3673
|
+
changed = await this.applyGlobalPatch(patch, target, cap) || changed;
|
|
3674
|
+
}
|
|
3675
|
+
if (secretKeys.length > 0) {
|
|
3676
|
+
await this.clearSecretKeys(secretKeys, target, cap);
|
|
3677
|
+
const node = normalizeNodeId(target ?? this._ctx?.kernel?.localNodeId);
|
|
3678
|
+
const rows = secretKeys.map((key) => scope === "node" ? nodeScopedKey(key, node) : key);
|
|
3679
|
+
if (this._secretSettings !== null) await this._secretSettings.removeClearedKeys(rows);
|
|
3680
|
+
else await this._ctx?.settings?.writeAddonStore(Object.fromEntries(rows.map((row) => [row, void 0])));
|
|
3681
|
+
changed = true;
|
|
3682
|
+
}
|
|
3683
|
+
if (changed) await this.onScopedSettingsChanged(scope, cap, [...keys]);
|
|
3684
|
+
}
|
|
3685
|
+
/**
|
|
3686
|
+
* The hydrated form of one scope of one capability's settings (any
|
|
3687
|
+
* {@link scopedSettingsOverlay} applied), or `null` when the capability declares nothing there.
|
|
3688
|
+
*/
|
|
3689
|
+
async getScopedSettings(scope, cap, nodeId) {
|
|
3690
|
+
const schema = await this.declaredScopedSchema(scope, cap);
|
|
3691
|
+
if (schema === null) return null;
|
|
3692
|
+
const stored = this.narrowToScope(await this.readRawProjectedStore(nodeId, cap), schema);
|
|
3693
|
+
const overlay = await this.scopedSettingsOverlay(scope, cap, nodeId);
|
|
3694
|
+
return hydrateSchema(schema, overlay ? await this.overlayKeepingMarkers(stored, overlay) : stored, { inlineSecretsAsViews: true });
|
|
3695
|
+
}
|
|
3696
|
+
/**
|
|
3697
|
+
* The scoped schemas this addon serves: one entry per loaded (capability, scope), capabilities
|
|
3698
|
+
* in declaration order, scopes in {@link SCOPED_SETTINGS_SCOPES} order. `[]` when it declares
|
|
3699
|
+
* nothing.
|
|
3700
|
+
*/
|
|
3701
|
+
async listScopedSettings() {
|
|
3702
|
+
await this.loadScopedSchemas();
|
|
3703
|
+
return [...this._scopedByCap].flatMap(([cap, entries]) => entries.map((entry) => ({
|
|
3704
|
+
cap,
|
|
3705
|
+
scope: entry.scope,
|
|
3706
|
+
sectionIds: entry.schema.sections.map((section) => section.id)
|
|
3707
|
+
})));
|
|
3708
|
+
}
|
|
3709
|
+
/** The OPERATOR's write of declared keys of one scope (D787 secret semantics). */
|
|
3710
|
+
async updateScopedSettings(scope, cap, patch, nodeId) {
|
|
3711
|
+
this._operatorWriteDepth++;
|
|
3712
|
+
try {
|
|
3713
|
+
await this.writeScoped(scope, cap, patch, nodeId);
|
|
3714
|
+
} finally {
|
|
3715
|
+
this._operatorWriteDepth--;
|
|
3716
|
+
}
|
|
3717
|
+
}
|
|
3718
|
+
/**
|
|
3719
|
+
* The effective values (`stored ?? default`) of one scope, a secret as its `set` view — never
|
|
3720
|
+
* its value. `null` when the capability declares nothing for the scope.
|
|
3721
|
+
*/
|
|
3722
|
+
async readScopedValues(scope, cap, nodeId) {
|
|
3723
|
+
const schema = await this.declaredScopedSchema(scope, cap);
|
|
3724
|
+
if (schema === null) return null;
|
|
3725
|
+
const form = hydrateSchema(schema, this.narrowToScope(await this.readRawProjectedStore(nodeId, cap), schema), { inlineSecretsAsViews: true });
|
|
3726
|
+
return Object.fromEntries([...collectHydratedFieldValues(form)].filter(([, value]) => value !== void 0));
|
|
3727
|
+
}
|
|
3728
|
+
/**
|
|
3729
|
+
* The raw addon store PROJECTED onto the target node's bare per-node keys:
|
|
3730
|
+
* every `perNode: true` field carries THAT node's scoped value on its bare
|
|
3731
|
+
* key (absent scoped key ⇒ key absent, so the schema `default` wins — no
|
|
3732
|
+
* bare fallback), all `@`-scoped and stray bare per-node keys are dropped.
|
|
3733
|
+
* A no-op passthrough when the schema declares no `perNode` field.
|
|
3734
|
+
*
|
|
3735
|
+
* This is the sanctioned way for an addon that needs
|
|
3736
|
+
* the store for custom logic (option narrowing, value snapping) to
|
|
3737
|
+
* read it per-node — never `ctx.settings.readAddonStore()` directly.
|
|
3738
|
+
* `nodeId` omitted ⇒ the local node (node-blind injection from ctx).
|
|
3739
|
+
*
|
|
3740
|
+
* Keychain values come back RESOLVED (D798): a secret reads as its value,
|
|
3741
|
+
* never as a `{ $secret }` marker. One the keychain cannot serve right now
|
|
3742
|
+
* stays a marker — "stored, unavailable" (`isSecretMarker()` is true, and it
|
|
3743
|
+
* is listed in {@link unresolvedSecrets}) — never `''` and never absent, so
|
|
3744
|
+
* it cannot be mistaken for "nothing stored, mint a new one". Writing the
|
|
3745
|
+
* resolved blob back is a no-op for every unchanged secret.
|
|
3746
|
+
*/
|
|
3747
|
+
async resolveGlobalStore(nodeId, cap) {
|
|
3748
|
+
await this.loadScopedSchemas(cap);
|
|
3749
|
+
const raw = await this._ctx?.settings?.readAddonStore() ?? {};
|
|
3750
|
+
return this.projectForNode(raw, nodeId, cap);
|
|
3751
|
+
}
|
|
3752
|
+
projectForNode(store, nodeId, cap) {
|
|
3753
|
+
const keys = this.perNodeKeys(cap);
|
|
3754
|
+
const node = normalizeNodeId(nodeId ?? this._ctx?.kernel?.localNodeId);
|
|
3755
|
+
return keys.size > 0 ? projectStore(store, keys, node) : store;
|
|
3756
|
+
}
|
|
3757
|
+
/** The PROJECTED store with its markers — the form hydrate only (D798). */
|
|
3758
|
+
async readRawProjectedStore(nodeId, cap) {
|
|
3759
|
+
await this.loadScopedSchemas(cap);
|
|
3760
|
+
const raw = await this.rawSettings()?.readAddonStore() ?? {};
|
|
3761
|
+
return this.projectForNode(raw, nodeId, cap);
|
|
3762
|
+
}
|
|
3763
|
+
/**
|
|
3764
|
+
* `{ ...stored, ...overlay }`, except that an overlay member equal to the
|
|
3765
|
+
* RESOLVED stored one keeps the stored (marker-bearing) member — so a form
|
|
3766
|
+
* hydrated from a resolved overlay still shows a secret as "set", never as
|
|
3767
|
+
* its value.
|
|
3768
|
+
*/
|
|
3769
|
+
async overlayKeepingMarkers(stored, overlay) {
|
|
3770
|
+
const secrets = this._ctx?.secrets;
|
|
3771
|
+
const merged = {
|
|
3772
|
+
...stored,
|
|
3773
|
+
...overlay
|
|
3774
|
+
};
|
|
3775
|
+
if (secrets === void 0 || collectSecretMarkerRefs(stored).length === 0) return merged;
|
|
3776
|
+
const { value: resolved } = await resolveSecretMarkers(stored, secrets, {
|
|
3777
|
+
unresolved: "keep-marker",
|
|
3778
|
+
ownedBy: secrets.owner
|
|
3779
|
+
});
|
|
3780
|
+
for (const key of Object.keys(overlay)) {
|
|
3781
|
+
if (collectSecretMarkerRefs(stored[key]).length === 0) continue;
|
|
3782
|
+
if (isJsonEqual(overlay[key], resolved[key])) merged[key] = stored[key];
|
|
3783
|
+
}
|
|
3784
|
+
return merged;
|
|
3785
|
+
}
|
|
3786
|
+
/**
|
|
3787
|
+
* Whether ONE global key of this addon's store was written, read three-way
|
|
3788
|
+
* (D651). For a question a hydrated view cannot answer: a hydrated form
|
|
3789
|
+
* reports `value ?? default`, so "the operator chose the default" and "nobody
|
|
3790
|
+
* chose" look the same, and a failed read looks like both. A `perNode` key is
|
|
3791
|
+
* not supported here: its stored name is scoped.
|
|
3792
|
+
*/
|
|
3793
|
+
async readStoredGlobalKey(key) {
|
|
3794
|
+
const read = this._ctx?.settings?.readAddonStoreResult;
|
|
3795
|
+
if (read === void 0) return {
|
|
3796
|
+
kind: "unreadable",
|
|
3797
|
+
reason: "three-way-read-unavailable"
|
|
3798
|
+
};
|
|
3799
|
+
let result;
|
|
3800
|
+
try {
|
|
3801
|
+
result = await read.call(this._ctx?.settings);
|
|
3802
|
+
} catch (err) {
|
|
3803
|
+
return {
|
|
3804
|
+
kind: "unreadable",
|
|
3805
|
+
reason: "store-read-failed",
|
|
3806
|
+
error: err instanceof Error ? err.message : String(err)
|
|
3807
|
+
};
|
|
3808
|
+
}
|
|
3809
|
+
if (result.kind === "failed") return {
|
|
3810
|
+
kind: "unreadable",
|
|
3811
|
+
reason: "store-read-failed",
|
|
3812
|
+
error: result.error
|
|
3813
|
+
};
|
|
3814
|
+
if (result.kind === "missing" || !Object.prototype.hasOwnProperty.call(result.value, key)) return { kind: "absent" };
|
|
3815
|
+
return {
|
|
3816
|
+
kind: "present",
|
|
3817
|
+
value: result.value[key]
|
|
3818
|
+
};
|
|
3819
|
+
}
|
|
3820
|
+
/**
|
|
3821
|
+
* The OPERATOR's write — a settings form or an admin API call, dispatched by
|
|
3822
|
+
* the kernel. The one in-process write of the addon blob that is not a scoped write; a secret
|
|
3823
|
+
* the operator sends is stored as sent even when it equals a pre-keychain
|
|
3824
|
+
* inline value: the operator re-entering a password is a change, an addon
|
|
3825
|
+
* writing back what it read is not (D787).
|
|
3826
|
+
*/
|
|
3827
|
+
async updateGlobalSettingsAsOperator(patch, nodeId) {
|
|
3828
|
+
this._operatorWriteDepth++;
|
|
3829
|
+
try {
|
|
3830
|
+
await this.applyGlobalPatch(patch, nodeId);
|
|
3831
|
+
} finally {
|
|
3832
|
+
this._operatorWriteDepth--;
|
|
3833
|
+
}
|
|
3834
|
+
}
|
|
3835
|
+
/**
|
|
3836
|
+
* REMOVE stored secrets — their keychain values and their markers (D787).
|
|
3837
|
+
*
|
|
3838
|
+
* Writing `''` to a secret field KEEPS what is stored (an empty string is
|
|
3839
|
+
* what a defaults fallback writes back, and it must never destroy a
|
|
3840
|
+
* credential), so code that means "forget this token" says so here. Without
|
|
3841
|
+
* a keychain (an older kernel) it writes `''`, as such code always did.
|
|
3842
|
+
*/
|
|
3843
|
+
async clearSecrets(keys, nodeId) {
|
|
3844
|
+
await this.clearSecretKeys(keys, nodeId);
|
|
3845
|
+
}
|
|
3846
|
+
async clearSecretKeys(keys, nodeId, cap) {
|
|
3847
|
+
const tree = this.addonSecretTree();
|
|
3848
|
+
const keychain = this._ctx?.secrets !== void 0;
|
|
3849
|
+
const stored = keychain ? await this.readAddonStoreWithRetry() : {};
|
|
3850
|
+
const patch = {};
|
|
3851
|
+
for (const key of keys) {
|
|
3852
|
+
if (tree.get(key)?.kind === "array") {
|
|
3853
|
+
patch[key] = [];
|
|
3854
|
+
continue;
|
|
3855
|
+
}
|
|
3856
|
+
const keychainStored = tree.has(key) || collectSecretMarkerRefs(stored[key]).length > 0;
|
|
3857
|
+
patch[key] = keychain && keychainStored ? SECRET_CLEAR : "";
|
|
3858
|
+
}
|
|
3859
|
+
await this.applyGlobalPatch(patch, nodeId, cap);
|
|
3860
|
+
}
|
|
3861
|
+
/** Resolves `true` when the write changed stored values. */
|
|
3862
|
+
async applyGlobalPatch(barePatch, nodeId, cap) {
|
|
3863
|
+
await this.loadScopedSchemas(cap);
|
|
3864
|
+
const keys = this.perNodeKeys(cap);
|
|
3865
|
+
const localNode = normalizeNodeId(this._ctx?.kernel?.localNodeId);
|
|
3866
|
+
const target = normalizeNodeId(nodeId ?? this._ctx?.kernel?.localNodeId);
|
|
3867
|
+
const scoped = keys.size > 0 ? scopePatch(barePatch, keys, target) : barePatch;
|
|
3868
|
+
const handle = this._secretSettings;
|
|
3869
|
+
if (handle !== null) {
|
|
3870
|
+
const { changed } = await handle.writeAddonStore(scoped);
|
|
3871
|
+
if (!changed) return false;
|
|
3872
|
+
} else await this._ctx?.settings?.writeAddonStore(scoped);
|
|
3873
|
+
if (target !== localNode) return true;
|
|
3874
|
+
await this.resolveConfig();
|
|
3875
|
+
await this.onConfigChanged();
|
|
3876
|
+
this.emitLifecycle(EventCategory.AddonUpdated, { level: "global" });
|
|
3877
|
+
this.maybeAutoRestart(Object.keys(barePatch), this.loadedScopedSchemas().map((entry) => entry.schema));
|
|
3878
|
+
return true;
|
|
3879
|
+
}
|
|
3880
|
+
/**
|
|
3881
|
+
* The set of field keys the global settings schema declares `perNode: true`
|
|
3882
|
+
* — derived once per `cap` argument and memoized (schemas are static
|
|
3883
|
+
* declarations). Empty set ⇒ every per-node code path is bypassed and the
|
|
3884
|
+
* settings API behaves exactly like the legacy node-agnostic one.
|
|
3885
|
+
*/
|
|
3886
|
+
/**
|
|
3887
|
+
* Load the scoped schemas of every capability this addon declares (the override and the
|
|
3888
|
+
* providers registered at init, plus `extraCap`) that is not loaded yet, then drop what was
|
|
3889
|
+
* derived from the previous set. Idempotent.
|
|
3890
|
+
*/
|
|
3891
|
+
async loadScopedSchemas(extraCap) {
|
|
3892
|
+
const caps = new Set([
|
|
3893
|
+
...this.scopedSettingsCapabilities(),
|
|
3894
|
+
...this._registeredCapNames,
|
|
3895
|
+
...extraCap === void 0 ? [] : [extraCap]
|
|
3896
|
+
]);
|
|
3897
|
+
let added = false;
|
|
3898
|
+
for (const cap of caps) {
|
|
3899
|
+
if (this._scopedByCap.has(cap)) continue;
|
|
3900
|
+
const loaded = [];
|
|
3901
|
+
for (const scope of SCOPED_SETTINGS_SCOPES) {
|
|
3902
|
+
const schema = await this.getScopedSettingsSchema(scope, cap);
|
|
3903
|
+
if (schema !== null) loaded.push({
|
|
3904
|
+
scope,
|
|
3905
|
+
schema
|
|
3906
|
+
});
|
|
3907
|
+
}
|
|
3908
|
+
this._scopedByCap.set(cap, loaded);
|
|
3909
|
+
added = true;
|
|
3910
|
+
}
|
|
3911
|
+
if (!added) return;
|
|
3912
|
+
this._nodeKeysByCap = /* @__PURE__ */ new Map();
|
|
3913
|
+
this._addonSecretTree = null;
|
|
3914
|
+
}
|
|
3915
|
+
/** Every loaded scoped schema of `cap`, or of every loaded capability. */
|
|
3916
|
+
loadedScopedSchemas(cap) {
|
|
3917
|
+
if (cap !== void 0) return this._scopedByCap.get(cap) ?? [];
|
|
3918
|
+
return [...this._scopedByCap.values()].flat();
|
|
3919
|
+
}
|
|
3920
|
+
/**
|
|
3921
|
+
* The field keys that are stored per node: every field of a {@link nodeSettingsSchema}. Derived once
|
|
3922
|
+
* per `cap` argument and memoized (schemas are static declarations). Empty set ⇒ every
|
|
3923
|
+
* per-node code path is bypassed and the settings API behaves like the node-agnostic one.
|
|
3924
|
+
* Call {@link loadScopedSchemas} first (the async seams do).
|
|
3925
|
+
*/
|
|
3926
|
+
perNodeKeys(cap) {
|
|
3927
|
+
const cacheKey = cap ?? "";
|
|
3928
|
+
const cached = this._nodeKeysByCap.get(cacheKey);
|
|
3929
|
+
if (cached) return cached;
|
|
3930
|
+
const keys = /* @__PURE__ */ new Set();
|
|
3931
|
+
for (const { scope, schema } of this.loadedScopedSchemas(cap)) {
|
|
3932
|
+
if (scope !== "node") continue;
|
|
3933
|
+
for (const section of schema.sections) for (const key of collectValueFieldKeys(section.fields)) keys.add(key);
|
|
3934
|
+
}
|
|
3935
|
+
this._nodeKeysByCap.set(cacheKey, keys);
|
|
3936
|
+
return keys;
|
|
3937
|
+
}
|
|
3938
|
+
/**
|
|
3939
|
+
* If any field in `patch` is marked `requiresRestart` in `schema`,
|
|
3940
|
+
* schedule an addon restart for the next tick. Deferred via
|
|
3941
|
+
* `setImmediate` so the tRPC mutation that triggered the write has
|
|
3942
|
+
* time to return its response before the addon is torn down and
|
|
3943
|
+
* re-initialised by `AddonRegistryService.restartAddon`.
|
|
3944
|
+
*/
|
|
3945
|
+
maybeAutoRestart(patchKeys, schemas) {
|
|
3946
|
+
const restartKeys = /* @__PURE__ */ new Set();
|
|
3947
|
+
for (const schema of schemas) for (const section of schema.sections) for (const field of section.fields) {
|
|
3948
|
+
if (field.type === "separator" || field.type === "info") continue;
|
|
3949
|
+
if (field.requiresRestart) restartKeys.add(field.key);
|
|
3950
|
+
}
|
|
3951
|
+
if (restartKeys.size === 0) return;
|
|
3952
|
+
if (!patchKeys.some((k) => restartKeys.has(k))) return;
|
|
3953
|
+
const ctx = this._ctx;
|
|
3954
|
+
if (!ctx) return;
|
|
3955
|
+
const addonId = ctx.id;
|
|
3956
|
+
setImmediate(() => {
|
|
3957
|
+
ctx.api.addons.restartAddon.mutate({ addonId }).then(() => {
|
|
3958
|
+
ctx.logger.info("addon auto-restart triggered by restart-required setting change", { meta: { changedFields: patchKeys.filter((k) => restartKeys.has(k)) } });
|
|
3959
|
+
}).catch((err) => {
|
|
3960
|
+
ctx.logger.error("addon auto-restart failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
|
|
3961
|
+
});
|
|
3962
|
+
});
|
|
3963
|
+
}
|
|
3964
|
+
async getDeviceSettings(deviceId) {
|
|
3965
|
+
const schema = this.deviceSettingsSchema();
|
|
3966
|
+
if (!schema) return { sections: [] };
|
|
3967
|
+
return hydrateSchema(schema, await this.rawSettings()?.readDeviceStore(deviceId) ?? {}, { inlineSecretsAsViews: true });
|
|
3968
|
+
}
|
|
3969
|
+
async updateDeviceSettings(deviceId, patch) {
|
|
3970
|
+
await this._ctx?.settings?.writeDeviceStore(deviceId, patch);
|
|
3971
|
+
}
|
|
3972
|
+
_subscriptions = [];
|
|
3973
|
+
/**
|
|
3974
|
+
* Subscribe to an event bus category. The subscription is automatically
|
|
3975
|
+
* unsubscribed on shutdown — no manual cleanup needed.
|
|
3976
|
+
*
|
|
3977
|
+
* @example
|
|
3978
|
+
* ```ts
|
|
3979
|
+
* this.subscribe({ category: EventCategory.DeviceRegistered }, (event) => {
|
|
3980
|
+
* void this.handleDevice(event)
|
|
3981
|
+
* })
|
|
3982
|
+
* ```
|
|
3983
|
+
*/
|
|
3984
|
+
/**
|
|
3985
|
+
* Subscribe to `system.ready-state` events for one or more capabilities.
|
|
3986
|
+
* Abstracts the boilerplate type-narrowing + nodeId extraction that every
|
|
3987
|
+
* resilience subscription duplicates. Cleanup is automatic (registered on
|
|
3988
|
+
* `_subscriptions` like a normal `subscribe` call).
|
|
3989
|
+
*/
|
|
3990
|
+
watchCapability(capNames, handlers) {
|
|
3991
|
+
const nameSet = new Set(Array.isArray(capNames) ? capNames : [capNames]);
|
|
3992
|
+
this.subscribe({ category: "system.ready-state" }, (event) => {
|
|
3993
|
+
const data = event.data;
|
|
3994
|
+
if (typeof data.capName !== "string") return;
|
|
3995
|
+
if (!nameSet.has(data.capName)) return;
|
|
3996
|
+
if (data.scope?.type !== "node") return;
|
|
3997
|
+
const nodeId = data.scope.nodeId;
|
|
3998
|
+
if (typeof nodeId !== "string" || nodeId.length === 0) return;
|
|
3999
|
+
const capName = data.capName;
|
|
4000
|
+
if (data.state === "down") handlers.onDown?.(nodeId, capName);
|
|
4001
|
+
else if (data.state === "ready") handlers.onReady?.(nodeId, capName);
|
|
4002
|
+
});
|
|
4003
|
+
}
|
|
4004
|
+
subscribe(filter, handler) {
|
|
4005
|
+
const unsub = this.ctx.eventBus.subscribe(filter, handler);
|
|
4006
|
+
this._subscriptions.push(unsub);
|
|
4007
|
+
}
|
|
4008
|
+
emitLifecycle(category, data) {
|
|
4009
|
+
try {
|
|
4010
|
+
const ctx = this._ctx;
|
|
4011
|
+
if (!ctx) return;
|
|
4012
|
+
ctx.eventBus.emit({
|
|
4013
|
+
id: `${ctx.id}-${Date.now()}`,
|
|
4014
|
+
timestamp: /* @__PURE__ */ new Date(),
|
|
4015
|
+
source: {
|
|
4016
|
+
type: "addon",
|
|
4017
|
+
id: ctx.id,
|
|
4018
|
+
nodeId: ctx.kernel.localNodeId ?? "hub"
|
|
4019
|
+
},
|
|
4020
|
+
category,
|
|
4021
|
+
data: {
|
|
4022
|
+
addonId: ctx.id,
|
|
4023
|
+
...data
|
|
4024
|
+
}
|
|
4025
|
+
});
|
|
4026
|
+
} catch {}
|
|
4027
|
+
}
|
|
4028
|
+
/**
|
|
4029
|
+
* Emit a `system.ready-state` event for every capability this addon
|
|
4030
|
+
* registered at init. Scope is `{type:'node', nodeId}` — readiness is
|
|
4031
|
+
* tied to the node that hosts the provider. Consumers that care about
|
|
4032
|
+
* per-device readiness can subscribe with `{type:'device', ...}` if
|
|
4033
|
+
* the provider emits at finer granularity (collection addons may
|
|
4034
|
+
* opt-out via `autoEmitReadiness` and emit manually).
|
|
4035
|
+
*/
|
|
4036
|
+
emitReadinessForProviders(state) {
|
|
4037
|
+
const ctx = this._ctx;
|
|
4038
|
+
if (!ctx) return;
|
|
4039
|
+
if (this._registeredCapNames.length === 0) return;
|
|
4040
|
+
const rawNodeId = ctx.kernel?.localNodeId ?? "hub";
|
|
4041
|
+
const nodeId = rawNodeId.includes("/") ? rawNodeId.split("/")[0] : rawNodeId;
|
|
4042
|
+
for (const capName of this._registeredCapNames) try {
|
|
4043
|
+
emitReadiness(ctx.eventBus, {
|
|
4044
|
+
capName,
|
|
4045
|
+
scope: {
|
|
4046
|
+
type: "node",
|
|
4047
|
+
nodeId
|
|
4048
|
+
},
|
|
4049
|
+
state,
|
|
4050
|
+
generation: this._readinessGeneration,
|
|
4051
|
+
sourceNodeId: nodeId
|
|
4052
|
+
});
|
|
4053
|
+
} catch {}
|
|
4054
|
+
}
|
|
4055
|
+
/**
|
|
4056
|
+
* Resolve the shared, node-local models directory: `<nodeDataDir>/models`.
|
|
4057
|
+
*
|
|
4058
|
+
* This is the SINGLE centralized models-dir resolver for every inference addon
|
|
4059
|
+
* (detection-pipeline, audio-analyzer, embedding-encoder, model-studio). It is
|
|
4060
|
+
* anchored at the node's own writable data root (`ctx.nodeDataDir`, i.e.
|
|
4061
|
+
* `CAMSTACK_DATA` ?? the kernel boot dir) — never the hub-singleton `storage`
|
|
4062
|
+
* cap, which returns the hub's `/data/models` to every node and breaks any node
|
|
4063
|
+
* whose real data dir differs (e.g. the macOS electron agent).
|
|
4064
|
+
*
|
|
4065
|
+
* `node:path`/`node:fs` are imported dynamically so the `@camstack/types` root
|
|
4066
|
+
* barrel (re-exported into browser bundles) stays free of node builtins.
|
|
4067
|
+
*/
|
|
4068
|
+
async resolveModelsDir() {
|
|
4069
|
+
const { join } = await import("node:path");
|
|
4070
|
+
const { promises: fsp } = await import("node:fs");
|
|
4071
|
+
const dir = join(this.ctx.nodeDataDir, "models");
|
|
4072
|
+
await fsp.mkdir(dir, { recursive: true });
|
|
4073
|
+
return dir;
|
|
4074
|
+
}
|
|
4075
|
+
/**
|
|
4076
|
+
* Access the runtime capability registry for in-process provider lookups.
|
|
4077
|
+
* Returns null if the registry is not available (e.g. on agents).
|
|
4078
|
+
* Used by addons that consume other capabilities directly (snapshot, stream-broker, enrichment).
|
|
4079
|
+
*/
|
|
4080
|
+
get capabilities() {
|
|
4081
|
+
return this.ctx.capabilities ?? null;
|
|
4082
|
+
}
|
|
4083
|
+
/**
|
|
4084
|
+
* Resolve config by merging defaults with persisted store values.
|
|
4085
|
+
* Called automatically during initialize() and after every updateSettings().
|
|
4086
|
+
*
|
|
4087
|
+
* The merge is shallow: each key in `defaults` is checked against the store.
|
|
4088
|
+
* Only keys present in defaults are read — the store can contain extra keys
|
|
4089
|
+
* (e.g. from older versions) without polluting the typed config.
|
|
4090
|
+
*
|
|
4091
|
+
* Keys the global settings schema declares `perNode: true` resolve from
|
|
4092
|
+
* THIS node's scoped key (`<key>@<localNode>`) via `readNodeValue` — never
|
|
4093
|
+
* from the bare key — so a per-node field resolves to this node's own
|
|
4094
|
+
* selection at boot (absent scoped key ⇒ the constructor default wins).
|
|
4095
|
+
*/
|
|
4096
|
+
async resolveConfig() {
|
|
4097
|
+
const stored = await this.resolveStoredSecrets(await this.readAddonStoreWithRetry());
|
|
4098
|
+
const perNode = this.perNodeKeys();
|
|
4099
|
+
const localNode = normalizeNodeId(this._ctx?.kernel?.localNodeId);
|
|
4100
|
+
const resolved = { ...this.defaults };
|
|
4101
|
+
for (const key of Object.keys(this.defaults)) {
|
|
4102
|
+
const storedValue = perNode.has(key) ? readNodeValue(stored, key, localNode) : stored[key];
|
|
4103
|
+
if (storedValue !== void 0 && storedValue !== null) {
|
|
4104
|
+
const defaultType = typeof this.defaults[key];
|
|
4105
|
+
if (typeof storedValue === defaultType) resolved[key] = storedValue;
|
|
4106
|
+
}
|
|
4107
|
+
}
|
|
4108
|
+
this._config = resolved;
|
|
4109
|
+
}
|
|
4110
|
+
/**
|
|
4111
|
+
* Typed durable handle over ONE key of this addon's store. The whole
|
|
4112
|
+
* Zod-validated value round-trips on every read/write — no hand-listed
|
|
4113
|
+
* fields, so a field can never be silently dropped on persist. Reads use
|
|
4114
|
+
* the same retry budget as config resolution; a corrupt/legacy blob logs
|
|
4115
|
+
* a warning and falls back rather than crashing boot.
|
|
4116
|
+
*/
|
|
4117
|
+
state(key, schema, fallback) {
|
|
4118
|
+
this._declaredStateKeys.add(key);
|
|
4119
|
+
return createDurableState({
|
|
4120
|
+
key,
|
|
4121
|
+
schema,
|
|
4122
|
+
fallback,
|
|
4123
|
+
read: async () => this.resolveStoredSecrets(await this.readAddonStoreWithRetry()),
|
|
4124
|
+
write: async (patch) => {
|
|
4125
|
+
await this._ctx?.settings?.writeAddonStore(patch);
|
|
4126
|
+
},
|
|
4127
|
+
onParseError: (k, e) => this._ctx?.logger?.warn?.(`durable-state: stored "${k}" failed validation — using fallback`, { meta: {
|
|
4128
|
+
addonId: this._ctx?.id,
|
|
4129
|
+
key: k,
|
|
4130
|
+
error: String(e)
|
|
4131
|
+
} })
|
|
4132
|
+
});
|
|
4133
|
+
}
|
|
4134
|
+
/** Durable-state keys this process registered through {@link state}. */
|
|
4135
|
+
_declaredStateKeys = /* @__PURE__ */ new Set();
|
|
4136
|
+
/**
|
|
4137
|
+
* Stale-data audit: every global-settings key this addon still declares —
|
|
4138
|
+
* constructor defaults, settings-schema fields (layout containers included),
|
|
4139
|
+
* durable-state keys and the root of each `secretStatePaths` entry. Answered
|
|
4140
|
+
* here, in the addon's own process, so the hub keeps no copy of it.
|
|
4141
|
+
*/
|
|
4142
|
+
async getDeclaredSettingsKeys() {
|
|
4143
|
+
await this.loadScopedSchemas();
|
|
4144
|
+
return { keys: [...this.declaredKeySet()].toSorted() };
|
|
4145
|
+
}
|
|
4146
|
+
declaredKeySet() {
|
|
4147
|
+
const keys = new Set(Object.keys(this.defaults));
|
|
4148
|
+
for (const { schema: scoped } of this.loadedScopedSchemas()) for (const section of scoped.sections) for (const key of collectFieldKeys(section.fields)) keys.add(key);
|
|
4149
|
+
for (const key of this._declaredStateKeys) keys.add(key);
|
|
4150
|
+
for (const path of this.secretStatePaths) {
|
|
4151
|
+
const root = path.split(/[.[]/, 1)[0];
|
|
4152
|
+
if (root) keys.add(root);
|
|
4153
|
+
}
|
|
4154
|
+
return keys;
|
|
4155
|
+
}
|
|
4156
|
+
/**
|
|
4157
|
+
* Stale-data audit: remove stored global-settings keys the addon no longer
|
|
4158
|
+
* declares, and clear the keychain values their markers held — except a value
|
|
4159
|
+
* a surviving key still points at. A declared or absent key is refused.
|
|
4160
|
+
*/
|
|
4161
|
+
async unsetStoredSettingsKeys(keys) {
|
|
4162
|
+
const settings = this._ctx?.settings;
|
|
4163
|
+
const raw = this.rawSettings();
|
|
4164
|
+
if (!settings || !raw) return {
|
|
4165
|
+
removed: [],
|
|
4166
|
+
refused: keys.map((key) => ({
|
|
4167
|
+
key,
|
|
4168
|
+
reason: "no settings store"
|
|
4169
|
+
})),
|
|
4170
|
+
secretsCleared: 0
|
|
4171
|
+
};
|
|
4172
|
+
let stored;
|
|
4173
|
+
try {
|
|
4174
|
+
stored = await raw.readAddonStore();
|
|
4175
|
+
} catch (error) {
|
|
4176
|
+
const reason = `store unreadable: ${error instanceof Error ? error.message : "unknown"}`;
|
|
4177
|
+
return {
|
|
4178
|
+
removed: [],
|
|
4179
|
+
refused: keys.map((key) => ({
|
|
4180
|
+
key,
|
|
4181
|
+
reason
|
|
4182
|
+
})),
|
|
4183
|
+
secretsCleared: 0
|
|
4184
|
+
};
|
|
4185
|
+
}
|
|
4186
|
+
const declared = this.declaredKeySet();
|
|
4187
|
+
const removed = [];
|
|
4188
|
+
const refused = [];
|
|
4189
|
+
for (const key of keys) {
|
|
4190
|
+
const base = key.split("@", 1)[0] ?? key;
|
|
4191
|
+
if (declared.has(base)) refused.push({
|
|
4192
|
+
key,
|
|
4193
|
+
reason: "still declared by the addon"
|
|
4194
|
+
});
|
|
4195
|
+
else if (!(key in stored)) refused.push({
|
|
4196
|
+
key,
|
|
4197
|
+
reason: "not stored"
|
|
4198
|
+
});
|
|
4199
|
+
else removed.push(key);
|
|
4200
|
+
}
|
|
4201
|
+
if (removed.length === 0) return {
|
|
4202
|
+
removed,
|
|
4203
|
+
refused,
|
|
4204
|
+
secretsCleared: 0
|
|
4205
|
+
};
|
|
4206
|
+
const kept = /* @__PURE__ */ new Set();
|
|
4207
|
+
const held = /* @__PURE__ */ new Set();
|
|
4208
|
+
for (const [key, value] of Object.entries(stored)) {
|
|
4209
|
+
const target = removed.includes(key) ? held : kept;
|
|
4210
|
+
for (const ref of collectSecretMarkerRefs(value)) target.add(ref);
|
|
4211
|
+
}
|
|
4212
|
+
const refsToClear = [...held].filter((ref) => !kept.has(ref));
|
|
4213
|
+
const patch = {};
|
|
4214
|
+
for (const key of removed) patch[key] = void 0;
|
|
4215
|
+
await settings.writeAddonStore(patch);
|
|
4216
|
+
const secretsCleared = refsToClear.length > 0 && this._ctx?.secrets ? await this._ctx.secrets.delete(refsToClear) : 0;
|
|
4217
|
+
await this.resolveConfig();
|
|
4218
|
+
return {
|
|
4219
|
+
removed,
|
|
4220
|
+
refused,
|
|
4221
|
+
secretsCleared
|
|
4222
|
+
};
|
|
4223
|
+
}
|
|
4224
|
+
/** Per-device variant of {@link state}, backed by the per-device store. */
|
|
4225
|
+
deviceState(deviceId, key, schema, fallback) {
|
|
4226
|
+
return createDurableState({
|
|
4227
|
+
key,
|
|
4228
|
+
schema,
|
|
4229
|
+
fallback,
|
|
4230
|
+
read: async () => this.resolveStoredSecrets(await this.rawSettings()?.readDeviceStore(deviceId) ?? {}, false),
|
|
4231
|
+
write: async (patch) => {
|
|
4232
|
+
await this._ctx?.settings?.writeDeviceStore(deviceId, patch);
|
|
4233
|
+
},
|
|
4234
|
+
onParseError: (k, e) => this._ctx?.logger?.warn?.(`durable-state: stored device ${deviceId} "${k}" failed validation — using fallback`, { meta: {
|
|
4235
|
+
addonId: this._ctx?.id,
|
|
4236
|
+
deviceId,
|
|
4237
|
+
key: k,
|
|
4238
|
+
error: String(e)
|
|
4239
|
+
} })
|
|
4240
|
+
});
|
|
4241
|
+
}
|
|
4242
|
+
/** The addon store's secret tree: schema fields by TYPE, plus `secretStatePaths`. */
|
|
4243
|
+
addonSecretTree() {
|
|
4244
|
+
if (this._addonSecretTree === null) {
|
|
4245
|
+
const tree = /* @__PURE__ */ new Map();
|
|
4246
|
+
for (const { schema } of this.loadedScopedSchemas()) for (const [key, node] of secretTreeFromSchema(schema)) tree.set(key, node);
|
|
4247
|
+
this._addonSecretTree = mergeSecretStatePaths(tree, this.secretStatePaths);
|
|
4248
|
+
}
|
|
4249
|
+
return this._addonSecretTree;
|
|
4250
|
+
}
|
|
4251
|
+
deviceSecretTree() {
|
|
4252
|
+
this._deviceSecretTree ??= mergeSecretStatePaths(secretTreeFromSchema(this.deviceSettingsSchema()), this.secretStatePaths);
|
|
4253
|
+
return this._deviceSecretTree;
|
|
4254
|
+
}
|
|
4255
|
+
/**
|
|
4256
|
+
* Secrets of this addon's stored config that could not be resolved on the
|
|
4257
|
+
* last read, with why. Non-empty means the addon is running WITHOUT them —
|
|
4258
|
+
* an addon whose function needs one should report itself degraded rather
|
|
4259
|
+
* than start on an empty credential.
|
|
4260
|
+
*/
|
|
4261
|
+
get unresolvedSecrets() {
|
|
4262
|
+
return this._unresolvedSecrets;
|
|
4263
|
+
}
|
|
4264
|
+
/**
|
|
4265
|
+
* Substitute every keychain marker in a stored blob with its value. With no
|
|
4266
|
+
* keychain (no `ctx.secrets`) or no marker, the blob comes back unchanged.
|
|
4267
|
+
* An unresolvable value is LEFT OUT (never `''`), logged by ref — never by
|
|
4268
|
+
* value — and, when the cause can pass, retried with backoff. Nothing is
|
|
4269
|
+
* ever written back from here.
|
|
4270
|
+
*/
|
|
4271
|
+
async resolveStoredSecrets(blob, trackForConfig = true) {
|
|
4272
|
+
const secrets = this._ctx?.secrets;
|
|
4273
|
+
if (secrets === void 0) return blob;
|
|
4274
|
+
const refs = collectSecretMarkerRefs(blob);
|
|
4275
|
+
if (trackForConfig) this._configSecretRefs = new Set(refs);
|
|
4276
|
+
if (refs.length === 0) {
|
|
4277
|
+
if (trackForConfig) this._unresolvedSecrets = [];
|
|
4278
|
+
return blob;
|
|
4279
|
+
}
|
|
4280
|
+
const { value, unresolved } = await resolveSecretMarkers(blob, secrets);
|
|
4281
|
+
if (trackForConfig) {
|
|
4282
|
+
this._unresolvedSecrets = unresolved;
|
|
4283
|
+
if (unresolved.length > 0) {
|
|
4284
|
+
this._ctx?.logger?.error?.("secret unavailable — running without it, will retry", { meta: { secrets: unresolved.map((u) => ({
|
|
4285
|
+
ref: u.ref,
|
|
4286
|
+
reason: u.reason
|
|
4287
|
+
})) } });
|
|
4288
|
+
if (unresolved.some((u) => u.reason !== "missing" && u.reason !== "forbidden")) {
|
|
4289
|
+
this.scheduleSecretReresolve(this._secretRetryDelayMs);
|
|
4290
|
+
this._secretRetryDelayMs = Math.min(this._secretRetryDelayMs * 2, SECRET_RETRY_MAX_MS);
|
|
4291
|
+
}
|
|
4292
|
+
} else this._secretRetryDelayMs = SECRET_RETRY_FIRST_MS;
|
|
4293
|
+
}
|
|
4294
|
+
return value;
|
|
4295
|
+
}
|
|
4296
|
+
/**
|
|
4297
|
+
* The marker-bearing settings reads (D798) — private on purpose. Without a
|
|
4298
|
+
* keychain the context's own view is already raw.
|
|
4299
|
+
*/
|
|
4300
|
+
rawSettings() {
|
|
4301
|
+
return this._secretSettings?.raw ?? this._ctx?.settings;
|
|
4302
|
+
}
|
|
4303
|
+
/** An addon-facing read met markers it could not resolve: say so once per ref. */
|
|
4304
|
+
logUnresolvedRead(unresolved) {
|
|
4305
|
+
const fresh = unresolved.filter((u) => !this._loggedUnresolvedReads.has(u.ref));
|
|
4306
|
+
if (fresh.length === 0) return;
|
|
4307
|
+
for (const u of fresh) this._loggedUnresolvedReads.add(u.ref);
|
|
4308
|
+
this._ctx?.logger?.warn?.("settings read: a stored secret is unavailable — it reads as its marker, not as a value", { meta: { secrets: fresh.map((u) => ({
|
|
4309
|
+
ref: u.ref,
|
|
4310
|
+
reason: u.reason
|
|
4311
|
+
})) } });
|
|
4312
|
+
}
|
|
4313
|
+
/** Re-resolve the config (a keychain-only change, or a retry) and apply it. */
|
|
4314
|
+
scheduleSecretReresolve(delayMs) {
|
|
4315
|
+
const timerOf = delayMs === SECRET_CHANGE_DEBOUNCE_MS ? "_secretChangeTimer" : "_secretRetryTimer";
|
|
4316
|
+
if (this[timerOf] !== null) return;
|
|
4317
|
+
const timer = setTimeout(() => {
|
|
4318
|
+
this[timerOf] = null;
|
|
4319
|
+
if (this._ctx === null) return;
|
|
4320
|
+
this.resolveConfig().then(() => this.onConfigChanged()).catch((err) => {
|
|
4321
|
+
this._ctx?.logger?.error?.("re-resolving secrets failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
|
|
4322
|
+
});
|
|
4323
|
+
}, delayMs);
|
|
4324
|
+
timer.unref?.();
|
|
4325
|
+
this[timerOf] = timer;
|
|
4326
|
+
}
|
|
4327
|
+
/**
|
|
4328
|
+
* Wrap `ctx.settings.readAddonStore()` with a retry budget so a transient
|
|
4329
|
+
* settings-store outage doesn't propagate up into `initialize()` and leave the
|
|
4330
|
+
* addon permanently broken.
|
|
4331
|
+
*
|
|
4332
|
+
* Two kinds of outage, two budgets:
|
|
4333
|
+
* - the store's own restart fingerprints (`SqliteSettingsBackend not
|
|
4334
|
+
* initialized`, `provider not available`): a short budget, then the addon
|
|
4335
|
+
* falls back to `{}` (defaults) - its first successful patch rehydrates;
|
|
4336
|
+
* - a TRANSPORT failure (the hub is restarting while this runner boots:
|
|
4337
|
+
* `discovery deadline exceeded`, `parent could not route`, a refused or
|
|
4338
|
+
* timed-out connection). Since D870 a runner's settings read THROWS instead
|
|
4339
|
+
* of answering `{}`, so without a budget a hub restart ends in a respawn
|
|
4340
|
+
* loop. A long, bounded budget; only after it the error propagates - the
|
|
4341
|
+
* addon never runs on defaults for a store it could not ask.
|
|
4342
|
+
* Anything else propagates immediately so real bugs surface.
|
|
4343
|
+
*/
|
|
4344
|
+
async readAddonStoreWithRetry() {
|
|
4345
|
+
const settings = this.rawSettings();
|
|
4346
|
+
if (!settings) return {};
|
|
4347
|
+
let lastErr;
|
|
4348
|
+
for (let attempt = 0;; attempt++) try {
|
|
4349
|
+
const stored = await settings.readAddonStore() ?? {};
|
|
4350
|
+
this.settingsStoreReady = true;
|
|
4351
|
+
return stored;
|
|
4352
|
+
} catch (err) {
|
|
4353
|
+
lastErr = err;
|
|
4354
|
+
const kind = classifyStoreError(err);
|
|
4355
|
+
if (kind === "permanent") throw err;
|
|
4356
|
+
const delay = (kind === "transport" ? TRANSPORT_RETRY_DELAYS_MS : RESTART_RETRY_DELAYS_MS)[attempt];
|
|
4357
|
+
if (delay === void 0) {
|
|
4358
|
+
if (kind === "transport") throw err;
|
|
4359
|
+
break;
|
|
4360
|
+
}
|
|
4361
|
+
await new Promise((r) => setTimeout(r, delay));
|
|
4362
|
+
}
|
|
4363
|
+
this.settingsStoreReady = false;
|
|
4364
|
+
this._ctx?.logger?.warn?.("readAddonStore: settings-store unavailable after retries — using defaults", { meta: { error: lastErr instanceof Error ? lastErr.message : String(lastErr) } });
|
|
4365
|
+
return {};
|
|
4366
|
+
}
|
|
4367
|
+
};
|
|
4368
|
+
/** The settings store's own restart fingerprints. */
|
|
4369
|
+
var RESTART_RETRY_DELAYS_MS = [
|
|
4370
|
+
150,
|
|
4371
|
+
350,
|
|
4372
|
+
600,
|
|
4373
|
+
900
|
|
4374
|
+
];
|
|
4375
|
+
/** A hub restarting under a booting runner: ~100 s in total. */
|
|
4376
|
+
var TRANSPORT_RETRY_DELAYS_MS = [
|
|
4377
|
+
150,
|
|
4378
|
+
350,
|
|
4379
|
+
600,
|
|
4380
|
+
900,
|
|
4381
|
+
2e3,
|
|
4382
|
+
5e3,
|
|
4383
|
+
1e4,
|
|
4384
|
+
2e4,
|
|
4385
|
+
3e4,
|
|
4386
|
+
3e4
|
|
4387
|
+
];
|
|
4388
|
+
var RESTART_FINGERPRINTS = ["SqliteSettingsBackend not initialized", "provider not available"];
|
|
4389
|
+
/** Node / socket error codes of a connection that did not happen or broke. */
|
|
4390
|
+
var TRANSPORT_CODES = /* @__PURE__ */ new Set([
|
|
4391
|
+
"ECONNREFUSED",
|
|
4392
|
+
"ECONNRESET",
|
|
4393
|
+
"ETIMEDOUT",
|
|
4394
|
+
"EPIPE",
|
|
4395
|
+
"EHOSTUNREACH",
|
|
4396
|
+
"ENETUNREACH"
|
|
4397
|
+
]);
|
|
4398
|
+
/** tRPC error codes that mean "the other side is not answering now", not "your call is wrong". */
|
|
4399
|
+
var UNAVAILABLE_TRPC_CODES = /* @__PURE__ */ new Set([
|
|
4400
|
+
"TIMEOUT",
|
|
4401
|
+
"SERVICE_UNAVAILABLE",
|
|
4402
|
+
"BAD_GATEWAY",
|
|
4403
|
+
"GATEWAY_TIMEOUT"
|
|
4404
|
+
]);
|
|
4405
|
+
/** The exact phrases OUR transport raises when it cannot reach the hub. */
|
|
4406
|
+
var TRANSPORT_PHRASES = [
|
|
4407
|
+
"discovery deadline exceeded",
|
|
4408
|
+
"parent could not route child unowned cap call",
|
|
4409
|
+
"UDS request timed out after",
|
|
4410
|
+
"channel closed"
|
|
4411
|
+
];
|
|
4412
|
+
/** Moleculer error `type`s of a call that could not be served right now. */
|
|
4413
|
+
var MOLECULER_TRANSIENT_TYPES = /* @__PURE__ */ new Set([
|
|
4414
|
+
"REQUEST_TIMEOUT",
|
|
4415
|
+
"SERVICE_NOT_FOUND",
|
|
4416
|
+
"SERVICE_NOT_AVAILABLE",
|
|
4417
|
+
"REQUEST_REJECTED",
|
|
4418
|
+
"BROKER_DISCONNECTED"
|
|
4419
|
+
]);
|
|
4420
|
+
function stringProp(value, key) {
|
|
4421
|
+
if (typeof value !== "object" || value === null) return void 0;
|
|
4422
|
+
const found = Reflect.get(value, key);
|
|
4423
|
+
return typeof found === "string" ? found : void 0;
|
|
4424
|
+
}
|
|
4425
|
+
/** The code an error carries: its own, its cause's, or a tRPC `data.code`. */
|
|
4426
|
+
function errorCode(err) {
|
|
4427
|
+
const out = {};
|
|
4428
|
+
const cause = typeof err === "object" && err !== null ? Reflect.get(err, "cause") : void 0;
|
|
4429
|
+
const data = typeof err === "object" && err !== null ? Reflect.get(err, "data") : void 0;
|
|
4430
|
+
const node = stringProp(err, "code") ?? stringProp(cause, "code");
|
|
4431
|
+
if (node !== void 0) out.node = node;
|
|
4432
|
+
const trpc = stringProp(data, "code");
|
|
4433
|
+
if (trpc !== void 0) out.trpc = trpc;
|
|
4434
|
+
return out;
|
|
4435
|
+
}
|
|
4436
|
+
/**
|
|
4437
|
+
* Is a settings read failure worth retrying, and with which budget? Only
|
|
4438
|
+
* EXPLICIT signals count: a socket error code, a tRPC "unavailable" code, or
|
|
4439
|
+
* one of the exact phrases our own transport raises. A message that merely
|
|
4440
|
+
* contains "timed out" or "unreachable" is not evidence of anything, and
|
|
4441
|
+
* `settings store not wired` is a wiring bug that retrying cannot fix.
|
|
4442
|
+
*/
|
|
4443
|
+
function classifyStoreError(err) {
|
|
4444
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
4445
|
+
if (RESTART_FINGERPRINTS.some((f) => message.includes(f))) return "restart";
|
|
4446
|
+
const code = errorCode(err);
|
|
4447
|
+
if (code.node !== void 0 && TRANSPORT_CODES.has(code.node)) return "transport";
|
|
4448
|
+
if (code.trpc !== void 0 && UNAVAILABLE_TRPC_CODES.has(code.trpc)) return "transport";
|
|
4449
|
+
if (typeof err === "object" && err !== null) {
|
|
4450
|
+
if (Reflect.get(err, "retryable") === true) return "transport";
|
|
4451
|
+
const type = stringProp(err, "type");
|
|
4452
|
+
if (type !== void 0 && MOLECULER_TRANSIENT_TYPES.has(type)) return "transport";
|
|
4453
|
+
}
|
|
4454
|
+
if (TRANSPORT_PHRASES.some((f) => message.includes(f))) return "transport";
|
|
4455
|
+
return "permanent";
|
|
4456
|
+
}
|
|
4457
|
+
/** The keys of the value-holding fields, recursing into layout containers. */
|
|
4458
|
+
function collectValueFieldKeys(fields) {
|
|
4459
|
+
const collected = [];
|
|
4460
|
+
for (const field of fields) {
|
|
4461
|
+
if (field.type === "group") {
|
|
4462
|
+
collected.push(...collectValueFieldKeys(field.fields));
|
|
4463
|
+
continue;
|
|
4464
|
+
}
|
|
4465
|
+
if (field.type === "sub-tabs") {
|
|
4466
|
+
for (const tab of field.tabs) collected.push(...collectValueFieldKeys(tab.fields));
|
|
4467
|
+
continue;
|
|
4468
|
+
}
|
|
4469
|
+
if (field.type === "separator" || field.type === "info") continue;
|
|
4470
|
+
if ("key" in field && typeof field.key === "string") collected.push(field.key);
|
|
4471
|
+
}
|
|
4472
|
+
return collected;
|
|
4473
|
+
}
|
|
4474
|
+
function collectFieldKeys(fields) {
|
|
4475
|
+
const collected = [];
|
|
4476
|
+
for (const field of fields) {
|
|
4477
|
+
if (field.type === "group") {
|
|
4478
|
+
collected.push(...collectFieldKeys(field.fields));
|
|
4479
|
+
continue;
|
|
4480
|
+
}
|
|
4481
|
+
if (field.type === "sub-tabs") {
|
|
4482
|
+
for (const tab of field.tabs) collected.push(...collectFieldKeys(tab.fields));
|
|
4483
|
+
continue;
|
|
4484
|
+
}
|
|
4485
|
+
if ("key" in field && typeof field.key === "string") collected.push(field.key);
|
|
4486
|
+
}
|
|
4487
|
+
return collected;
|
|
4488
|
+
}
|
|
4489
|
+
/**
|
|
4490
|
+
* Normalize an `ICamstackAddon.initialize()` return value into the
|
|
4491
|
+
* `AddonInitResult` envelope. Arrays are wrapped into `{ providers }`;
|
|
4492
|
+
* envelopes pass through; void stays void.
|
|
4493
|
+
*
|
|
4494
|
+
* Exported so the kernel boot path and the backend addon registry can
|
|
4495
|
+
* share the same normalizer instead of duplicating the shim. Addons that
|
|
4496
|
+
* extend `BaseAddon` already emit the envelope, so this helper is only a
|
|
4497
|
+
* safety net for direct `ICamstackAddon` implementations (mostly tests).
|
|
4498
|
+
*/
|
|
4499
|
+
function normalizeAddonInitResult(result) {
|
|
4500
|
+
if (result == null) return;
|
|
4501
|
+
if (Array.isArray(result)) return { providers: result };
|
|
4502
|
+
return result;
|
|
4503
|
+
}
|
|
4504
|
+
//#endregion
|
|
4505
|
+
export { hydrateSchema as _, isSecretRefOwnedBy as a, EventCategory as b, normalizeNodeId as c, optionalLinkField as d, defineAddonMigrations as f, WELL_KNOWN_TAB_MAP as g, isEvent as h, collectSecretMarkerRefs as i, RecordIntegrationInstances as l, emitReadiness as m, secretTreeFromPaths as n, resolveSecretMarkers as o, createEvent as p, secretTreeFromSchema as r, transformSecretWrite as s, BaseAddon as t, secretViewsOf as u, isInstanceOn as v, recordInstanceSwitch as y };
|