@camstack/addon-provider-reolink 1.2.230 → 1.2.231

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/dist/addon.mjs CHANGED
@@ -106669,7 +106669,7 @@ var ZodIssueCode = {
106669
106669
  var ZodFirstPartyTypeKind;
106670
106670
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
106671
106671
  //#endregion
106672
- //#region ../types/dist/sleep-BX_MqzUe.mjs
106672
+ //#region ../types/dist/sleep-CmjWurK5.mjs
106673
106673
  /**
106674
106674
  * The audio chunk plane's byte format, and the ONE expansion from a coded
106675
106675
  * window to float samples (D455).
@@ -107353,137 +107353,100 @@ async function runAddonMigrations(host, migrations, logger, options = {}) {
107353
107353
  blockOwner
107354
107354
  };
107355
107355
  }
107356
- /**
107357
- * Build a {@link DurableState} over a single store key. Transport-agnostic:
107358
- * `read`/`write` are the addon-store or device-store accessors. The whole
107359
- * validated value round-trips on every read/write — the schema is the
107360
- * single source of truth for what is persisted, so no hand-listed field
107361
- * set can drop a key on save.
107362
- */
107363
- function createDurableState(deps) {
107364
- const get = async () => {
107365
- const raw = (await deps.read())[deps.key];
107366
- if (raw === void 0) return deps.fallback;
107367
- const parsed = deps.schema.safeParse(raw);
107368
- if (!parsed.success) {
107369
- deps.onParseError?.(deps.key, parsed.error);
107370
- return deps.fallback;
107371
- }
107372
- return parsed.data;
107373
- };
107374
- const set = async (next) => {
107375
- const validated = deps.schema.parse(next);
107376
- await deps.write({ [deps.key]: validated });
107377
- };
107378
- const update = async (fn) => {
107379
- await set(fn(await get()));
107380
- };
107356
+ /** The record calls the one-switch migration makes, over the migration API. */
107357
+ function switchRecordsOverMigrationApi(api) {
107358
+ return { kind: (definition) => {
107359
+ const handle = api.records.kind(definition);
107360
+ return {
107361
+ get: (id) => handle.get({ id }),
107362
+ put: (input, opts) => handle.put({
107363
+ ...input,
107364
+ ...opts?.ifRev === void 0 ? {} : { ifRev: opts.ifRev }
107365
+ }),
107366
+ patch: (id, partial) => handle.patch({
107367
+ id,
107368
+ partial
107369
+ })
107370
+ };
107371
+ } };
107372
+ }
107373
+ function integrationRowsApiOver(api) {
107381
107374
  return {
107382
- get,
107383
- set,
107384
- update
107375
+ list: async () => (await api.integrations.list({})).integrations,
107376
+ readLegacyIntegrationRows: (input) => api.legacyRows.read(input),
107377
+ clearLegacyIntegrationRows: (input) => api.legacyRows.clear(input)
107385
107378
  };
107386
107379
  }
107380
+ var PREFIX = "records/";
107381
+ /** The base of every records failure. `detail` is the human part of the message. */
107382
+ var RecordsError = class extends Error {
107383
+ code;
107384
+ detail;
107385
+ constructor(code, detail) {
107386
+ super(`${PREFIX}${code}: ${detail}`);
107387
+ this.name = "RecordsError";
107388
+ this.code = code;
107389
+ this.detail = detail;
107390
+ }
107391
+ };
107392
+ /** A write guarded by `ifRev` found another revision (or an existing row for `ifRev: 0`). */
107393
+ var RevConflictError = class extends RecordsError {
107394
+ constructor(detail) {
107395
+ super("rev-conflict", detail);
107396
+ this.name = "RevConflictError";
107397
+ }
107398
+ };
107399
+ /** The keychain could not store or serve a value: explicit, never an empty string. */
107400
+ var RecordSecretUnavailableError = class extends RecordsError {
107401
+ constructor(detail) {
107402
+ super("secret-unavailable", detail);
107403
+ this.name = "RecordSecretUnavailableError";
107404
+ }
107405
+ };
107406
+ var InvalidRecordError = class extends RecordsError {
107407
+ constructor(detail) {
107408
+ super("invalid-record", detail);
107409
+ this.name = "InvalidRecordError";
107410
+ }
107411
+ };
107412
+ /** A kind declaration the engine refuses (non-additive change, bad shape, wrong file). */
107413
+ var DeclarationRefusedError = class extends RecordsError {
107414
+ constructor(detail) {
107415
+ super("declaration-refused", detail);
107416
+ this.name = "DeclarationRefusedError";
107417
+ }
107418
+ };
107387
107419
  /**
107388
- * Per-node scoping for the shared addon-settings blob.
107389
- *
107390
- * An addon's settings store is hub-central (the `addon-settings` cap is
107391
- * hub-routed — the hub instance answers for every node), so fields whose
107392
- * value is a NODE fact (decoder backend, engine pick, probed hardware
107393
- * capabilities) persist under the node-scoped key `<key>@<nodeId>` inside
107394
- * the single shared blob. The SCHEMA field key stays bare: the write path
107395
- * ({@link scopePatch}) maps the bare field onto the target node's scoped
107396
- * key; the read/hydrate path ({@link projectStore}) maps THIS node's value
107397
- * back, so UI forms and `resolveConfig` only ever see the bare key.
107398
- *
107399
- * Fields opt in via the `perNode: true` schema marker on `ConfigFieldBase`
107400
- * (`interfaces/config-ui.ts`); `BaseAddon` derives the key set from the
107401
- * schema and routes reads/writes through these helpers.
107402
- *
107403
- * ## No bare-key fallback — deliberate
107404
- *
107405
- * {@link readNodeValue} reads the node-scoped key ONLY. A node with no
107406
- * scoped key resolves to `undefined` so the field's schema `default` wins —
107407
- * NEVER `store[base]` and never another node's value. A bare legacy key in
107408
- * the store is invisible to every node, hub included, so one node's
107409
- * selection can never leak onto another. (This generalizes the
107410
- * `decoder-backend-keys.ts` semantics — the no-fallback variant — over an
107411
- * arbitrary set of per-node field keys.)
107412
- *
107413
- * Pure functions only — no I/O, no imports beyond the language. This is a
107414
- * LEAF module: import it via its deep path, never from the root barrel.
107415
- */
107416
- /**
107417
- * Normalize a raw kernel node id to the bare node id used for scoping.
107418
- * `localNodeId` can carry a `<node>/<addon>` suffix on forked child
107419
- * processes; per-node settings are per-NODE, so strip the addon segment.
107420
- * `undefined` / `null` / empty falls back to `'hub'`.
107421
- */
107422
- function normalizeNodeId(raw) {
107423
- if (raw === void 0 || raw === null || raw === "") return "hub";
107424
- const slashIdx = raw.indexOf("/");
107425
- if (slashIdx < 0) return raw;
107426
- const bare = raw.slice(0, slashIdx);
107427
- return bare === "" ? "hub" : bare;
107428
- }
107429
- /** The node-scoped store key for a per-node field: `<base>@<nodeId>`. */
107430
- function nodeScopedKey(base, nodeId) {
107431
- return `${base}@${normalizeNodeId(nodeId)}`;
107432
- }
107433
- /**
107434
- * Read a node's value for a per-node field from the raw shared store:
107435
- * the node-scoped key when present, otherwise `undefined`.
107436
- * Deliberately NO bare-key fallback (see module doc) — the caller lets the
107437
- * schema `default` win on `undefined`.
107420
+ * A link that may stay empty (absent): for a link the addon fills itself, or one an instance does not
107421
+ * always need. The meta rides on the optional wrapper, where {@link linksOfKind} reads it.
107438
107422
  */
107439
- function readNodeValue(store, base, nodeId) {
107440
- return store[nodeScopedKey(base, nodeId)];
107423
+ function optionalLinkField(target) {
107424
+ return string().optional().meta({ link: target });
107441
107425
  }
107442
- /**
107443
- * Re-map a UI/settings patch so every bare perNode field persists under the
107444
- * TARGET node's scoped key; all other keys pass through unchanged. Used on
107445
- * the write path so a save for one node never clobbers another node's value
107446
- * (and the bare key is never written). Returns a new object — the input
107447
- * patch is not mutated.
107448
- */
107449
- function scopePatch(patch, perNodeKeys, nodeId) {
107450
- const out = {};
107451
- for (const [key, value] of Object.entries(patch)) out[perNodeKeys.has(key) ? nodeScopedKey(key, nodeId) : key] = value;
107452
- return out;
107426
+ function linkTargetOf(meta) {
107427
+ if (typeof meta !== "object" || meta === null) return void 0;
107428
+ const link = Reflect.get(meta, "link");
107429
+ const parsed = LinkTargetSchema.safeParse(link);
107430
+ return parsed.success ? parsed.data : void 0;
107453
107431
  }
107454
- /**
107455
- * Project the raw shared store onto the bare schema keys for ONE node so a
107456
- * UI schema (whose field keys are bare) hydrates from that node's own
107457
- * values:
107458
- *
107459
- * - EVERY `@`-scoped key (any node's) is dropped from the pass-through.
107460
- * - Every bare perNode key is dropped from the pass-through (a stray bare
107461
- * legacy key must never hydrate any node — no bare fallback).
107462
- * - THIS node's effective value ({@link readNodeValue}) is then laid onto
107463
- * each bare perNode key; when the node has no scoped key the bare key is
107464
- * left ABSENT so the field's schema `default` wins.
107465
- *
107466
- * Returns a new object — the input store is not mutated.
107467
- */
107468
- function projectStore(store, perNodeKeys, nodeId) {
107469
- const out = {};
107470
- for (const [key, value] of Object.entries(store)) {
107471
- if (key.includes("@")) continue;
107472
- if (perNodeKeys.has(key)) continue;
107473
- out[key] = value;
107474
- }
107475
- for (const base of perNodeKeys) {
107476
- const value = readNodeValue(store, base, nodeId);
107477
- if (value !== void 0) out[base] = value;
107432
+ var LinkTargetSchema = object({
107433
+ cap: string().min(1),
107434
+ kind: string().min(1).optional()
107435
+ });
107436
+ /** The links a kind declares, read from the meta of its body fields. */
107437
+ function linksOfKind(kind) {
107438
+ const schema = kind.schema;
107439
+ if (!(schema instanceof ZodObject)) return [];
107440
+ const links = [];
107441
+ for (const [field, fieldSchema] of Object.entries(schema.shape)) {
107442
+ const to = linkTargetOf(globalRegistry.get(fieldSchema));
107443
+ if (to !== void 0) links.push({
107444
+ field,
107445
+ to
107446
+ });
107478
107447
  }
107479
- return out;
107448
+ return links;
107480
107449
  }
107481
- /** Every scope, in the order the guard and the docs list them. */
107482
- var SCOPED_SETTINGS_SCOPES = [
107483
- "cluster",
107484
- "device-defaults",
107485
- "node"
107486
- ];
107487
107450
  /**
107488
107451
  * The address of one keychain value: `secret://<owner>/<scope>/<fieldPath>`.
107489
107452
  *
@@ -107618,6 +107581,652 @@ function parseSecretRef(ref) {
107618
107581
  fieldPath
107619
107582
  };
107620
107583
  }
107584
+ /** Limits and names of `ctx.records` (D881). One authority; the engine and the facade read it. */
107585
+ /** The files a kind may live in. `history` is device-history's (D850), never records. */
107586
+ var RECORD_DATABASES = ["settings", "events"];
107587
+ /** The classes of a kind: the `@durable` vocabulary, one authority (replaces the annotation). */
107588
+ var RECORD_CLASSES = [
107589
+ "config",
107590
+ "ledger",
107591
+ "audit",
107592
+ "mirror",
107593
+ "ephemeral"
107594
+ ];
107595
+ var RECORD_DEFAULT_MAX_DATA_BYTES = 64 * 1024;
107596
+ var RECORD_MAX_DATA_BYTES = 1024 * 1024;
107597
+ var RECORD_BATCH_MAX = 1e3;
107598
+ var RECORD_QUERY_MAX = 1e3;
107599
+ /** A kind in the `settings` file may not bound itself above this (D447: high volume is `events`). */
107600
+ var RECORD_SETTINGS_MAX_ROWS = 5e4;
107601
+ /** The `Column`-free proof prefix: a ref collection for a kind's secret fields. */
107602
+ var RECORD_SECRET_COLLECTION_PREFIX = "records:";
107603
+ /**
107604
+ * Secret fields of a record, addressed the way a Zod schema declares them
107605
+ * (`collectZodSecretPaths`): dotted keys, `[]` for "each element of this array"
107606
+ * (`auth.accessToken`, `headers[].value`).
107607
+ *
107608
+ * `{}` after a key means "each value of this map" (`applianceSecrets{}`): the map's own key
107609
+ * names the value (`applianceSecrets{fridge}`), so no id key is declared and a body that drops a
107610
+ * key releases exactly that key's secret.
107611
+ *
107612
+ * Array elements are matched by a DECLARED id key (`secretArrayKeys`:
107613
+ * `{ headers: 'name' }`), never by index, so reordering a list keeps every
107614
+ * keychain ref (the same rule as `arrayItemFieldPath`). The concrete path of a
107615
+ * leaf names its element: `headers[X-Api].value`.
107616
+ *
107617
+ * Pure and browser-safe. Nothing here mutates: every transform returns a new value.
107618
+ */
107619
+ /** The array prefixes (declared form, e.g. `headers` or `a.headers`) of a path. */
107620
+ function parseSecretPath(path) {
107621
+ if (path.length === 0) throw new InvalidRecordError("an empty secret path");
107622
+ return path.split(".").map((raw) => {
107623
+ const each = raw.endsWith("[]");
107624
+ const map = raw.endsWith("{}");
107625
+ const key = each || map ? raw.slice(0, -2) : raw;
107626
+ if (key.length === 0) throw new InvalidRecordError(`secret path "${path}" has an empty segment`);
107627
+ return {
107628
+ key,
107629
+ each,
107630
+ map
107631
+ };
107632
+ });
107633
+ }
107634
+ /** The declared array prefixes of `path` that need an id key (`headers`, `a.rows`). */
107635
+ function secretArrayPrefixes(path) {
107636
+ const segments = parseSecretPath(path);
107637
+ const prefixes = [];
107638
+ const walked = [];
107639
+ for (const segment of segments) {
107640
+ walked.push(segment.key);
107641
+ if (segment.each) prefixes.push(walked.join("."));
107642
+ }
107643
+ return prefixes;
107644
+ }
107645
+ function isRecord$6(value) {
107646
+ return typeof value === "object" && value !== null && !Array.isArray(value);
107647
+ }
107648
+ function elementId(element, idKey, declared, prefix) {
107649
+ const id = isRecord$6(element) ? element[idKey] : void 0;
107650
+ if (typeof id !== "string" || id.length === 0) throw new InvalidRecordError(`"${declared}": every element of "${prefix}" needs a non-empty string "${idKey}" to carry a secret`);
107651
+ return id;
107652
+ }
107653
+ /**
107654
+ * Visit every secret leaf PRESENT in `data` (an absent branch has nothing to
107655
+ * visit). `replace` returns the new leaf value, or {@link REMOVE_LEAF}; the
107656
+ * result is a new body, `data` is untouched.
107657
+ */
107658
+ var REMOVE_LEAF = Symbol("remove-leaf");
107659
+ function mapAt(node, segments, index, walkedKeys, concretePrefix, declared, arrayKeys, visit) {
107660
+ if (!isRecord$6(node)) return node;
107661
+ const segment = segments[index];
107662
+ if (segment === void 0) return node;
107663
+ if (!Object.prototype.hasOwnProperty.call(node, segment.key)) return node;
107664
+ const child = node[segment.key];
107665
+ const keys = [...walkedKeys, segment.key];
107666
+ const last = index === segments.length - 1;
107667
+ if (segment.each) {
107668
+ if (!Array.isArray(child)) return node;
107669
+ const prefix = keys.join(".");
107670
+ const idKey = arrayKeys[prefix];
107671
+ if (idKey === void 0) throw new InvalidRecordError(`"${declared}": no id key declared for the array "${prefix}"`);
107672
+ const mapped = child.map((element) => {
107673
+ const id = elementId(element, idKey, declared, prefix);
107674
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}[${encodeURIComponent(id)}]`;
107675
+ return last ? element : mapAt(element, segments, index + 1, keys, concrete, declared, arrayKeys, visit);
107676
+ });
107677
+ return {
107678
+ ...node,
107679
+ [segment.key]: mapped
107680
+ };
107681
+ }
107682
+ if (segment.map) {
107683
+ if (!isRecord$6(child)) return node;
107684
+ const kept = Object.entries(child).map(([mapKey, value]) => {
107685
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}{${encodeURIComponent(mapKey)}}`;
107686
+ if (!last) return [mapKey, mapAt(value, segments, index + 1, keys, concrete, declared, arrayKeys, visit)];
107687
+ return [mapKey, visit({
107688
+ declared,
107689
+ concrete,
107690
+ value
107691
+ })];
107692
+ }).filter(([, value]) => value !== REMOVE_LEAF);
107693
+ return {
107694
+ ...node,
107695
+ [segment.key]: Object.fromEntries(kept)
107696
+ };
107697
+ }
107698
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}`;
107699
+ if (last) {
107700
+ const replacement = visit({
107701
+ declared,
107702
+ concrete,
107703
+ value: child
107704
+ });
107705
+ if (replacement === REMOVE_LEAF) return Object.fromEntries(Object.entries(node).filter(([key]) => key !== segment.key));
107706
+ return {
107707
+ ...node,
107708
+ [segment.key]: replacement
107709
+ };
107710
+ }
107711
+ return {
107712
+ ...node,
107713
+ [segment.key]: mapAt(child, segments, index + 1, keys, concrete, declared, arrayKeys, visit)
107714
+ };
107715
+ }
107716
+ /** Replace/remove every present secret leaf; returns a NEW body. */
107717
+ function mapSecretLeaves(data, paths, arrayKeys, visit) {
107718
+ let current = data;
107719
+ for (const declared of paths) current = mapAt(current, parseSecretPath(declared), 0, [], "", declared, arrayKeys, visit);
107720
+ return current;
107721
+ }
107722
+ /** Every present secret leaf, read-only. */
107723
+ function collectSecretLeaves(data, paths, arrayKeys) {
107724
+ const found = [];
107725
+ mapSecretLeaves(data, paths, arrayKeys, (leaf) => {
107726
+ found.push(leaf);
107727
+ return leaf.value;
107728
+ });
107729
+ return found;
107730
+ }
107731
+ /**
107732
+ * The keychain collection name a kind's secrets live under. Prefixed so a
107733
+ * record's refs never collide with the refs a legacy collection of the same name
107734
+ * already holds during an adoption.
107735
+ */
107736
+ function recordSecretCollection(kind) {
107737
+ return `${RECORD_SECRET_COLLECTION_PREFIX}${kind}`;
107738
+ }
107739
+ /** The ONE ref a row's secret field may carry: the engine and the facade both build it here. */
107740
+ function recordSecretRef(owner, kind, rowId, concretePath) {
107741
+ return buildSecretRef({
107742
+ owner,
107743
+ scope: {
107744
+ kind: "row",
107745
+ collection: recordSecretCollection(kind),
107746
+ rowId
107747
+ },
107748
+ fieldPath: concretePath
107749
+ });
107750
+ }
107751
+ /**
107752
+ * A stored secret, as an admin read shows it: a VIEW naming the row's own
107753
+ * keychain ref (`set: true`), never the value and no longer the bare redaction
107754
+ * token. The form hands it to the secret field, which reveals the value by ref
107755
+ * through the audited `keychain-admin.reveal`; sent back untouched it keeps the
107756
+ * stored secret (the records door reads a view as KEEP).
107757
+ *
107758
+ * ONE implementation for the entries service and for every addon that serves
107759
+ * its own instances (`RecordIntegrationInstances`).
107760
+ */
107761
+ function isRecord$5(value) {
107762
+ return typeof value === "object" && value !== null && !Array.isArray(value);
107763
+ }
107764
+ function secretViewsOf(owner, kind, id, decl, data) {
107765
+ if (decl.secretPaths.length === 0) return data;
107766
+ const shown = mapSecretLeaves(data, decl.secretPaths, decl.secretArrayKeys, (leaf) => {
107767
+ if (leaf.value !== "__camstack_redacted__") return leaf.value;
107768
+ return {
107769
+ $secret: recordSecretRef(owner, kind, id, leaf.concrete),
107770
+ v: 1,
107771
+ set: true
107772
+ };
107773
+ });
107774
+ return isRecord$5(shown) ? shown : data;
107775
+ }
107776
+ /** The most instances one addon lists (an integrations page, not a table). */
107777
+ var INSTANCES_LIST_MAX = 1e3;
107778
+ /**
107779
+ * The ONE reader of an instance's switch (D996): an absent field means on, so a row written
107780
+ * before the field existed needs no migration. Every consumer of an instance body asks this.
107781
+ */
107782
+ function isInstanceEnabled(body) {
107783
+ return body.enabled !== false;
107784
+ }
107785
+ /** The body key of the switch; only {@link RecordIntegrationInstances.setInstanceEnabled} writes it. */
107786
+ var SWITCH_KEY = "enabled";
107787
+ /** The keys of the kind's secret fields that sit at the top level of the body. */
107788
+ function topLevelSecretKeys(paths) {
107789
+ return new Set(paths.filter((p) => !p.includes(".") && !p.includes("[") && !p.includes("{")));
107790
+ }
107791
+ /** The keys of the kind's top-level MAPS whose values are secrets (`applianceSecrets{}`). */
107792
+ function secretMapKeys(paths) {
107793
+ return new Set(paths.filter((p) => p.endsWith("{}") && !p.slice(0, -2).match(/[.[{]/)).map((p) => p.slice(0, -2)));
107794
+ }
107795
+ /**
107796
+ * A patch value for a map of secrets: an entry that is omitted, `''`, the redaction token or the
107797
+ * view the form was given KEEPS its stored secret (it is left out of the merge); `{ $secretClear }`
107798
+ * or `null` removes the entry; any other string replaces it. Null when nothing is left to merge.
107799
+ */
107800
+ function secretMapPatch(value) {
107801
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
107802
+ const out = {};
107803
+ for (const [key, entry] of Object.entries(value)) if (entry === null || isSecretClear(entry)) out[key] = null;
107804
+ else if (typeof entry === "string" && entry !== "" && entry !== "__camstack_redacted__" && !isSecretFieldView(entry)) out[key] = entry;
107805
+ return Object.keys(out).length > 0 ? out : null;
107806
+ }
107807
+ var RecordIntegrationInstances = class {
107808
+ records;
107809
+ kind;
107810
+ hooks;
107811
+ handle;
107812
+ secretKeys;
107813
+ secretMaps;
107814
+ nameField;
107815
+ switchListeners = /* @__PURE__ */ new Set();
107816
+ constructor(records, kind, hooks) {
107817
+ this.records = records;
107818
+ this.kind = kind;
107819
+ this.hooks = hooks;
107820
+ this.handle = records.kind(kind);
107821
+ this.secretKeys = topLevelSecretKeys(kind.declaration.secretPaths);
107822
+ this.secretMaps = secretMapKeys(kind.declaration.secretPaths);
107823
+ this.nameField = kind.declaration.entry?.nameField ?? "name";
107824
+ }
107825
+ /**
107826
+ * One instance read for the addon's own runtime; null when absent. When the keychain is
107827
+ * locked the row is served WITHOUT its secrets and says so (`secrets: 'unavailable'`), so the
107828
+ * caller can keep what it had instead of reconfiguring with an empty secret (D49).
107829
+ */
107830
+ async readResolved(id) {
107831
+ try {
107832
+ const record = await this.handle.getResolved(id);
107833
+ return record === null ? null : {
107834
+ id,
107835
+ body: record.data,
107836
+ enabled: isInstanceEnabled(record.data),
107837
+ secrets: "resolved"
107838
+ };
107839
+ } catch (err) {
107840
+ if (!(err instanceof RecordSecretUnavailableError)) throw err;
107841
+ const stored = await this.handle.get(id);
107842
+ if (stored === null) return null;
107843
+ return {
107844
+ id,
107845
+ body: Object.fromEntries(Object.entries(stored.data).filter(([key]) => !this.secretKeys.has(key))),
107846
+ enabled: isInstanceEnabled(stored.data),
107847
+ secrets: "unavailable"
107848
+ };
107849
+ }
107850
+ }
107851
+ /** The body of {@link readResolved} alone; a locked keychain yields the row without secrets. */
107852
+ async getResolved(id) {
107853
+ return (await this.readResolved(id))?.body ?? null;
107854
+ }
107855
+ /** Every instance, secrets resolved where the keychain allows; an absent one is skipped. */
107856
+ async listResolved() {
107857
+ const page = await this.handle.query({ limit: INSTANCES_LIST_MAX });
107858
+ const out = [];
107859
+ for (const record of page.records) {
107860
+ const read = await this.readResolved(record.id);
107861
+ if (read !== null) out.push(read);
107862
+ }
107863
+ return out;
107864
+ }
107865
+ viewOf(record) {
107866
+ const shown = secretViewsOf(this.records.owner, this.kind.name, record.id, this.kind.declaration, record.data);
107867
+ const rawName = record.data[this.nameField];
107868
+ const kind = this.hooks.kindOf?.(record.data);
107869
+ const health = this.hooks.health?.(record.data, record.id);
107870
+ return {
107871
+ id: record.id,
107872
+ name: typeof rawName === "string" ? rawName : record.id,
107873
+ configured: this.hooks.configured(record.data),
107874
+ enabled: isInstanceEnabled(record.data),
107875
+ formValues: shown,
107876
+ ...kind !== void 0 ? { kind } : {},
107877
+ ...health?.status !== void 0 ? { status: health.status } : {},
107878
+ ...health?.lastCheckedAt !== void 0 ? { lastCheckedAt: health.lastCheckedAt } : {}
107879
+ };
107880
+ }
107881
+ describe = async () => {
107882
+ const declared = linksOfKind(this.kind);
107883
+ const links = this.hooks.description.links !== void 0 || declared.length === 0 ? {} : { links: declared.map((link) => ({
107884
+ kind: this.kind.name,
107885
+ field: link.field,
107886
+ to: link.to
107887
+ })) };
107888
+ return {
107889
+ ...this.hooks.description,
107890
+ ...links,
107891
+ ...this.hooks.mintId === void 0 ? {} : { mintsId: true }
107892
+ };
107893
+ };
107894
+ instanceFormSchema = async ({ id }) => this.hooks.formSchema(id);
107895
+ listInstances = async () => {
107896
+ return (await this.handle.query({ limit: INSTANCES_LIST_MAX })).records.map((record) => this.viewOf(record));
107897
+ };
107898
+ getInstance = async ({ id }) => {
107899
+ const record = await this.handle.get(id);
107900
+ return record === null ? null : this.viewOf(record);
107901
+ };
107902
+ /** Insert ONE row (`ifRev: 0`: an existing id is refused, never overwritten). */
107903
+ createInstance = async ({ id, name, kind, values }) => {
107904
+ const minted = id ?? this.hooks.mintId?.({
107905
+ name,
107906
+ ...kind !== void 0 ? { kind } : {}
107907
+ });
107908
+ if (minted === void 0) throw new Error("createInstance needs an id: this provider does not mint one");
107909
+ await this.handle.put({
107910
+ id: minted,
107911
+ data: this.hooks.initialBody(name, kind)
107912
+ }, { ifRev: 0 });
107913
+ const patch = this.patchOf(values ?? {});
107914
+ if (Object.keys(patch).length > 0) await this.handle.patch(minted, patch);
107915
+ await this.hooks.onChanged?.(minted, "created");
107916
+ return { id: minted };
107917
+ };
107918
+ updateInstance = async ({ id, name, values }) => {
107919
+ const patch = this.patchOf(values);
107920
+ if (name !== void 0) patch[this.nameField] = name;
107921
+ await this.handle.patch(id, patch);
107922
+ await this.hooks.onChanged?.(id, "updated");
107923
+ return { ok: true };
107924
+ };
107925
+ /** The record patch a form `values` object means: secrets kept, cleared or replaced. */
107926
+ patchOf(values) {
107927
+ const patch = {};
107928
+ for (const [key, value] of Object.entries(values)) {
107929
+ if (value === void 0) continue;
107930
+ if (key === "enabled") continue;
107931
+ if (this.secretMaps.has(key)) {
107932
+ const entries = secretMapPatch(value);
107933
+ if (entries !== null) patch[key] = entries;
107934
+ } else if (!this.secretKeys.has(key)) patch[key] = value;
107935
+ else if (isSecretClear(value)) patch[key] = null;
107936
+ else if (typeof value === "string" && value !== "" && value !== "__camstack_redacted__" && !isSecretFieldView(value)) patch[key] = value;
107937
+ }
107938
+ return patch;
107939
+ }
107940
+ /**
107941
+ * Listen to the switch of ANY instance of this helper (in the process that serves it). The
107942
+ * durable replacement of the `integration.enabled` / `integration.disabled` events (D8): the
107943
+ * addon reconciles from the record, whichever way it flipped.
107944
+ */
107945
+ onSwitched(listener) {
107946
+ this.switchListeners.add(listener);
107947
+ }
107948
+ /**
107949
+ * The ONE writer of the switch (D996, D1014): the record body's `enabled`, for every role. A
107950
+ * configured thing is an instance, so an id with no record yet (a default integration that was
107951
+ * never configured) gets its record from `initialBody` before the switch is written.
107952
+ */
107953
+ setInstanceEnabled = async ({ id, enabled }) => {
107954
+ if (await this.handle.get(id) === null) await this.handle.put({
107955
+ id,
107956
+ data: this.hooks.initialBody(id)
107957
+ }, { ifRev: 0 });
107958
+ await this.handle.patch(id, { [SWITCH_KEY]: enabled });
107959
+ await this.hooks.onChanged?.(id, "enabled");
107960
+ for (const listener of this.switchListeners) await listener(id, enabled);
107961
+ return { ok: true };
107962
+ };
107963
+ /** The row and its keychain refs go together (the records door). */
107964
+ deleteInstance = async ({ id }) => {
107965
+ await this.handle.delete(id);
107966
+ await this.hooks.onChanged?.(id, "deleted");
107967
+ return { ok: true };
107968
+ };
107969
+ testInstance = async (input) => {
107970
+ if (this.hooks.test === void 0) return {
107971
+ success: false,
107972
+ status: "unsupported",
107973
+ error: "This integration declares no connection test"
107974
+ };
107975
+ return this.hooks.test(input);
107976
+ };
107977
+ /** The flat provider object to hand to `registerProvider`. */
107978
+ toProvider() {
107979
+ return {
107980
+ describe: this.describe,
107981
+ instanceFormSchema: this.instanceFormSchema,
107982
+ listInstances: this.listInstances,
107983
+ getInstance: this.getInstance,
107984
+ createInstance: this.createInstance,
107985
+ updateInstance: this.updateInstance,
107986
+ setInstanceEnabled: this.setInstanceEnabled,
107987
+ deleteInstance: this.deleteInstance,
107988
+ testInstance: this.testInstance
107989
+ };
107990
+ }
107991
+ };
107992
+ /**
107993
+ * The one-switch migration (epic #440, step 3). An integration's on/off state used to live in the
107994
+ * registry's `enabled` column for a device addon; it now lives only in the instance record's
107995
+ * body (`enabled`, D1007 superseded). This moves a registry `enabled = false` into the body, once.
107996
+ *
107997
+ * For every registry row of the addon that is OFF:
107998
+ * - no record under its id: the record is created from `initialBody(name)` with `enabled: false`
107999
+ * (a default integration that never had settings, Reolink's among them);
108000
+ * - a record whose body states no `enabled`: `enabled: false` is written into it;
108001
+ * - a record that already states `enabled` (either way) is the newer truth and is left alone.
108002
+ * A row that is ON writes nothing: an absent field reads as on. A rerun finds every off row with
108003
+ * a stated switch and does nothing, so nothing switched off comes back on and nothing switched on
108004
+ * goes off. The registry column itself is neither read afterwards nor written; its drop is step 5.
108005
+ *
108006
+ * It runs in the addon process, BEFORE the addon registers its `integration-instances` provider,
108007
+ * which is also why `integrations.list` still answers the stored column at that point.
108008
+ */
108009
+ function registrySwitchToBodyId(addonId, date) {
108010
+ return `${addonId}/${date}-registry-switch-to-body`;
108011
+ }
108012
+ async function moveRegistrySwitchToBody(ports, spec) {
108013
+ const rows = await ports.listIntegrations(spec.addonId);
108014
+ let created = 0;
108015
+ let switched = 0;
108016
+ let kept = 0;
108017
+ for (const row of rows) {
108018
+ if (row.enabled) continue;
108019
+ const body = await ports.readBody(row.id);
108020
+ if (body === null) {
108021
+ if (await ports.createRecord(row.id, {
108022
+ ...spec.initialBody(row.name),
108023
+ ["enabled"]: false
108024
+ }) === "created") created += 1;
108025
+ else kept += 1;
108026
+ continue;
108027
+ }
108028
+ if ("enabled" in body) {
108029
+ kept += 1;
108030
+ continue;
108031
+ }
108032
+ await ports.switchOff(row.id);
108033
+ switched += 1;
108034
+ }
108035
+ const summary = {
108036
+ integrations: rows.length,
108037
+ off: rows.filter((r) => !r.enabled).length,
108038
+ created,
108039
+ switched,
108040
+ kept
108041
+ };
108042
+ return created === 0 && switched === 0 ? {
108043
+ outcome: "already-done",
108044
+ summary
108045
+ } : {
108046
+ outcome: "done",
108047
+ summary
108048
+ };
108049
+ }
108050
+ /** A migration entry: an addon states its kind and how a new body starts, nothing else. */
108051
+ function registrySwitchToBodyMigration(spec) {
108052
+ return {
108053
+ meta: {
108054
+ id: registrySwitchToBodyId(spec.addonId, spec.date),
108055
+ owner: spec.addonId,
108056
+ level: "addon-state",
108057
+ seq: spec.seq,
108058
+ dependsOn: [],
108059
+ store: "settings",
108060
+ scope: "cluster",
108061
+ onFailure: "block-owner",
108062
+ bodyKind: "procedure",
108063
+ description: "Move the registry enabled flag of every switched-off integration into its instance record body, creating the record when there is none",
108064
+ fixtureMark: "enabled"
108065
+ },
108066
+ procedure: (ports) => moveRegistrySwitchToBody(ports, {
108067
+ addonId: spec.addonId,
108068
+ initialBody: spec.initialBody
108069
+ })
108070
+ };
108071
+ }
108072
+ /** The hub and records sides of {@link registrySwitchToBodyMigration}. */
108073
+ function registrySwitchPortsOver(deps) {
108074
+ const handle = deps.records.kind({
108075
+ name: deps.kind.name,
108076
+ declaration: deps.kind.declaration,
108077
+ schema: record(string(), unknown())
108078
+ });
108079
+ return {
108080
+ listIntegrations: async (addonId) => (await deps.api.list()).filter((i) => i.addonId === addonId).map((i) => ({
108081
+ id: i.id,
108082
+ name: i.name,
108083
+ enabled: i.enabled !== false
108084
+ })),
108085
+ readBody: async (id) => (await handle.get(id))?.data ?? null,
108086
+ createRecord: async (id, body) => {
108087
+ if (await handle.get(id) !== null) return "exists";
108088
+ await handle.put({
108089
+ id,
108090
+ data: body
108091
+ }, { ifRev: 0 });
108092
+ return "created";
108093
+ },
108094
+ switchOff: async (id) => {
108095
+ await handle.patch(id, { [SWITCH_KEY]: false });
108096
+ }
108097
+ };
108098
+ }
108099
+ /**
108100
+ * Build a {@link DurableState} over a single store key. Transport-agnostic:
108101
+ * `read`/`write` are the addon-store or device-store accessors. The whole
108102
+ * validated value round-trips on every read/write — the schema is the
108103
+ * single source of truth for what is persisted, so no hand-listed field
108104
+ * set can drop a key on save.
108105
+ */
108106
+ function createDurableState(deps) {
108107
+ const get = async () => {
108108
+ const raw = (await deps.read())[deps.key];
108109
+ if (raw === void 0) return deps.fallback;
108110
+ const parsed = deps.schema.safeParse(raw);
108111
+ if (!parsed.success) {
108112
+ deps.onParseError?.(deps.key, parsed.error);
108113
+ return deps.fallback;
108114
+ }
108115
+ return parsed.data;
108116
+ };
108117
+ const set = async (next) => {
108118
+ const validated = deps.schema.parse(next);
108119
+ await deps.write({ [deps.key]: validated });
108120
+ };
108121
+ const update = async (fn) => {
108122
+ await set(fn(await get()));
108123
+ };
108124
+ return {
108125
+ get,
108126
+ set,
108127
+ update
108128
+ };
108129
+ }
108130
+ /**
108131
+ * Per-node scoping for the shared addon-settings blob.
108132
+ *
108133
+ * An addon's settings store is hub-central (the `addon-settings` cap is
108134
+ * hub-routed — the hub instance answers for every node), so fields whose
108135
+ * value is a NODE fact (decoder backend, engine pick, probed hardware
108136
+ * capabilities) persist under the node-scoped key `<key>@<nodeId>` inside
108137
+ * the single shared blob. The SCHEMA field key stays bare: the write path
108138
+ * ({@link scopePatch}) maps the bare field onto the target node's scoped
108139
+ * key; the read/hydrate path ({@link projectStore}) maps THIS node's value
108140
+ * back, so UI forms and `resolveConfig` only ever see the bare key.
108141
+ *
108142
+ * Fields opt in via the `perNode: true` schema marker on `ConfigFieldBase`
108143
+ * (`interfaces/config-ui.ts`); `BaseAddon` derives the key set from the
108144
+ * schema and routes reads/writes through these helpers.
108145
+ *
108146
+ * ## No bare-key fallback — deliberate
108147
+ *
108148
+ * {@link readNodeValue} reads the node-scoped key ONLY. A node with no
108149
+ * scoped key resolves to `undefined` so the field's schema `default` wins —
108150
+ * NEVER `store[base]` and never another node's value. A bare legacy key in
108151
+ * the store is invisible to every node, hub included, so one node's
108152
+ * selection can never leak onto another. (This generalizes the
108153
+ * `decoder-backend-keys.ts` semantics — the no-fallback variant — over an
108154
+ * arbitrary set of per-node field keys.)
108155
+ *
108156
+ * Pure functions only — no I/O, no imports beyond the language. This is a
108157
+ * LEAF module: import it via its deep path, never from the root barrel.
108158
+ */
108159
+ /**
108160
+ * Normalize a raw kernel node id to the bare node id used for scoping.
108161
+ * `localNodeId` can carry a `<node>/<addon>` suffix on forked child
108162
+ * processes; per-node settings are per-NODE, so strip the addon segment.
108163
+ * `undefined` / `null` / empty falls back to `'hub'`.
108164
+ */
108165
+ function normalizeNodeId(raw) {
108166
+ if (raw === void 0 || raw === null || raw === "") return "hub";
108167
+ const slashIdx = raw.indexOf("/");
108168
+ if (slashIdx < 0) return raw;
108169
+ const bare = raw.slice(0, slashIdx);
108170
+ return bare === "" ? "hub" : bare;
108171
+ }
108172
+ /** The node-scoped store key for a per-node field: `<base>@<nodeId>`. */
108173
+ function nodeScopedKey(base, nodeId) {
108174
+ return `${base}@${normalizeNodeId(nodeId)}`;
108175
+ }
108176
+ /**
108177
+ * Read a node's value for a per-node field from the raw shared store:
108178
+ * the node-scoped key when present, otherwise `undefined`.
108179
+ * Deliberately NO bare-key fallback (see module doc) — the caller lets the
108180
+ * schema `default` win on `undefined`.
108181
+ */
108182
+ function readNodeValue(store, base, nodeId) {
108183
+ return store[nodeScopedKey(base, nodeId)];
108184
+ }
108185
+ /**
108186
+ * Re-map a UI/settings patch so every bare perNode field persists under the
108187
+ * TARGET node's scoped key; all other keys pass through unchanged. Used on
108188
+ * the write path so a save for one node never clobbers another node's value
108189
+ * (and the bare key is never written). Returns a new object — the input
108190
+ * patch is not mutated.
108191
+ */
108192
+ function scopePatch(patch, perNodeKeys, nodeId) {
108193
+ const out = {};
108194
+ for (const [key, value] of Object.entries(patch)) out[perNodeKeys.has(key) ? nodeScopedKey(key, nodeId) : key] = value;
108195
+ return out;
108196
+ }
108197
+ /**
108198
+ * Project the raw shared store onto the bare schema keys for ONE node so a
108199
+ * UI schema (whose field keys are bare) hydrates from that node's own
108200
+ * values:
108201
+ *
108202
+ * - EVERY `@`-scoped key (any node's) is dropped from the pass-through.
108203
+ * - Every bare perNode key is dropped from the pass-through (a stray bare
108204
+ * legacy key must never hydrate any node — no bare fallback).
108205
+ * - THIS node's effective value ({@link readNodeValue}) is then laid onto
108206
+ * each bare perNode key; when the node has no scoped key the bare key is
108207
+ * left ABSENT so the field's schema `default` wins.
108208
+ *
108209
+ * Returns a new object — the input store is not mutated.
108210
+ */
108211
+ function projectStore(store, perNodeKeys, nodeId) {
108212
+ const out = {};
108213
+ for (const [key, value] of Object.entries(store)) {
108214
+ if (key.includes("@")) continue;
108215
+ if (perNodeKeys.has(key)) continue;
108216
+ out[key] = value;
108217
+ }
108218
+ for (const base of perNodeKeys) {
108219
+ const value = readNodeValue(store, base, nodeId);
108220
+ if (value !== void 0) out[base] = value;
108221
+ }
108222
+ return out;
108223
+ }
108224
+ /** Every scope, in the order the guard and the docs list them. */
108225
+ var SCOPED_SETTINGS_SCOPES = [
108226
+ "cluster",
108227
+ "device-defaults",
108228
+ "node"
108229
+ ];
107621
108230
  /** A write to a secret path could not be stored in the keychain, so it was refused. */
107622
108231
  var KeychainWriteRefusedError = class extends Error {
107623
108232
  fieldPath;
@@ -107628,7 +108237,7 @@ var KeychainWriteRefusedError = class extends Error {
107628
108237
  }
107629
108238
  };
107630
108239
  var KEEP = { kind: "keep" };
107631
- function isRecord$6(value) {
108240
+ function isRecord$4(value) {
107632
108241
  return typeof value === "object" && value !== null && !Array.isArray(value);
107633
108242
  }
107634
108243
  function defaultMintId() {
@@ -107641,7 +108250,7 @@ function collectSecretMarkerRefs(value, out = []) {
107641
108250
  return out;
107642
108251
  }
107643
108252
  if (Array.isArray(value)) for (const item of value) collectSecretMarkerRefs(item, out);
107644
- else if (isRecord$6(value)) for (const child of Object.values(value)) collectSecretMarkerRefs(child, out);
108253
+ else if (isRecord$4(value)) for (const child of Object.values(value)) collectSecretMarkerRefs(child, out);
107645
108254
  return out;
107646
108255
  }
107647
108256
  async function storedValueEquals(secrets, marker, candidate) {
@@ -107696,7 +108305,7 @@ function rowId(row, idKey) {
107696
108305
  return null;
107697
108306
  }
107698
108307
  async function writeArray(ctx, node, incoming, stored, fieldPath) {
107699
- const storedRows = Array.isArray(stored) ? stored.filter(isRecord$6) : [];
108308
+ const storedRows = Array.isArray(stored) ? stored.filter(isRecord$4) : [];
107700
108309
  if (!Array.isArray(incoming)) {
107701
108310
  ctx.deletes.push(...collectSecretMarkerRefs(storedRows));
107702
108311
  return {
@@ -107712,7 +108321,7 @@ async function writeArray(ctx, node, incoming, stored, fieldPath) {
107712
108321
  const kept = /* @__PURE__ */ new Set();
107713
108322
  const rows = [];
107714
108323
  for (const row of incoming) {
107715
- if (!isRecord$6(row)) {
108324
+ if (!isRecord$4(row)) {
107716
108325
  rows.push(row);
107717
108326
  continue;
107718
108327
  }
@@ -107737,7 +108346,7 @@ async function writeNode(ctx, node, incoming, stored, fieldPath) {
107737
108346
  case "leaf": return writeLeaf(ctx, incoming, stored, fieldPath);
107738
108347
  case "array": return writeArray(ctx, node, incoming, stored, fieldPath);
107739
108348
  case "object": {
107740
- if (!isRecord$6(incoming)) {
108349
+ if (!isRecord$4(incoming)) {
107741
108350
  if (incoming === void 0) return KEEP;
107742
108351
  ctx.deletes.push(...collectSecretMarkerRefs(stored));
107743
108352
  return {
@@ -107745,7 +108354,7 @@ async function writeNode(ctx, node, incoming, stored, fieldPath) {
107745
108354
  value: incoming
107746
108355
  };
107747
108356
  }
107748
- const storedObj = isRecord$6(stored) ? stored : {};
108357
+ const storedObj = isRecord$4(stored) ? stored : {};
107749
108358
  return {
107750
108359
  kind: "value",
107751
108360
  value: await writeMembers(ctx, node.children, incoming, storedObj, (m) => `${fieldPath}.${m}`)
@@ -107868,7 +108477,7 @@ async function resolveSecretMarkers(value, secrets, options = {}) {
107868
108477
  value: items
107869
108478
  };
107870
108479
  }
107871
- if (isRecord$6(v)) {
108480
+ if (isRecord$4(v)) {
107872
108481
  const out = {};
107873
108482
  for (const [k, child] of Object.entries(v)) {
107874
108483
  const s = substitute(child);
@@ -107900,7 +108509,7 @@ var SecretOverwriteRefusedError = class extends Error {
107900
108509
  this.name = "SecretOverwriteRefusedError";
107901
108510
  }
107902
108511
  };
107903
- function isRecord$5(value) {
108512
+ function isRecord$3(value) {
107904
108513
  return typeof value === "object" && value !== null && !Array.isArray(value);
107905
108514
  }
107906
108515
  function resolvedValue(pass, marker) {
@@ -107929,7 +108538,7 @@ function inArray(pass, incoming, stored) {
107929
108538
  return incoming.map((item, index) => {
107930
108539
  const twin = stored[index];
107931
108540
  if (isSecretMarker(twin)) return typeof item === "string" && item === resolvedValue(pass, twin) ? twin : item;
107932
- if (isRecord$5(item) && isRecord$5(twin)) return inArrayRow(pass, item, twin);
108541
+ if (isRecord$3(item) && isRecord$3(twin)) return inArrayRow(pass, item, twin);
107933
108542
  if (Array.isArray(item) && Array.isArray(twin)) return inArray(pass, item, twin);
107934
108543
  return item;
107935
108544
  });
@@ -107940,7 +108549,7 @@ function inArrayRow(pass, incoming, stored) {
107940
108549
  const twin = stored[key];
107941
108550
  if (isSecretMarker(twin)) {
107942
108551
  if (typeof value === "string" && value === resolvedValue(pass, twin)) out[key] = twin;
107943
- } else if (isRecord$5(value) && isRecord$5(twin)) out[key] = inArrayRow(pass, value, twin);
108552
+ } else if (isRecord$3(value) && isRecord$3(twin)) out[key] = inArrayRow(pass, value, twin);
107944
108553
  else if (Array.isArray(value) && Array.isArray(twin)) out[key] = inArray(pass, value, twin);
107945
108554
  }
107946
108555
  return out;
@@ -107948,7 +108557,7 @@ function inArrayRow(pass, incoming, stored) {
107948
108557
  async function walk(pass, incoming, stored) {
107949
108558
  if (isSecretMarker(stored)) return atMarker(pass, incoming, stored);
107950
108559
  if (Array.isArray(incoming) && Array.isArray(stored)) return inArray(pass, incoming, stored);
107951
- if (!isRecord$5(incoming) || !isRecord$5(stored)) return incoming;
108560
+ if (!isRecord$3(incoming) || !isRecord$3(stored)) return incoming;
107952
108561
  const out = { ...incoming };
107953
108562
  for (const [key, value] of Object.entries(incoming)) out[key] = await walk(pass, value, stored[key]);
107954
108563
  return out;
@@ -107979,7 +108588,7 @@ async function restoreUnchangedSecrets(input) {
107979
108588
  function isJsonEqual(a, b) {
107980
108589
  if (Object.is(a, b)) return true;
107981
108590
  if (Array.isArray(a)) return Array.isArray(b) && a.length === b.length && a.every((v, i) => isJsonEqual(v, b[i]));
107982
- if (isRecord$5(a) && isRecord$5(b)) {
108591
+ if (isRecord$3(a) && isRecord$3(b)) {
107983
108592
  const keys = Object.keys(a);
107984
108593
  if (keys.length !== Object.keys(b).length) return false;
107985
108594
  return keys.every((k) => Object.prototype.hasOwnProperty.call(b, k) && isJsonEqual(a[k], b[k]));
@@ -108003,7 +108612,7 @@ function markerKeysOf(blob, owner) {
108003
108612
  }
108004
108613
  function nodeFromStored(value, owner) {
108005
108614
  if (isSecretMarker(value)) return isSecretRefOwnedBy(value.$secret, owner) ? { kind: "leaf" } : null;
108006
- if (!isRecord$5(value)) return null;
108615
+ if (!isRecord$3(value)) return null;
108007
108616
  const children = /* @__PURE__ */ new Map();
108008
108617
  for (const [key, child] of Object.entries(value)) {
108009
108618
  const node = nodeFromStored(child, owner);
@@ -108500,13 +109109,48 @@ var BaseAddon = class {
108500
109109
  if (api === void 0) throw new Error(`${this.ctx.id}: the migration API is not available on this context`);
108501
109110
  return this.runBound(sets.flatMap((set) => set.bind(api)), options);
108502
109111
  }
108503
- async runBound(migrations, options) {
109112
+ /**
109113
+ * A device addon states its instance kind once, before its migrations run, and the one-switch
109114
+ * migration (registry `enabled` to the instance body, epic #440 step 3) joins whatever
109115
+ * catalogue the addon runs, in the SAME declaration (the engine replaces an owner's catalogue
109116
+ * on every declare).
109117
+ */
109118
+ declareRegistrySwitch(spec) {
109119
+ this.registrySwitchSpec = spec;
109120
+ }
109121
+ registrySwitchSpec = null;
109122
+ registrySwitchBound() {
109123
+ const spec = this.registrySwitchSpec;
109124
+ if (spec === null) return [];
109125
+ const api = this.ctx.migrationApi;
109126
+ if (api === void 0) {
109127
+ this.ctx.logger.warn("the registry switch migration is skipped: the migration API is not available on this context");
109128
+ return [];
109129
+ }
109130
+ return migrationSet([registrySwitchToBodyMigration({
109131
+ addonId: this.ctx.id,
109132
+ date: "2026-11-06",
109133
+ seq: 1e3,
109134
+ initialBody: spec.initialBody
109135
+ })], (a) => registrySwitchPortsOver({
109136
+ api: integrationRowsApiOver(a),
109137
+ records: switchRecordsOverMigrationApi(a),
109138
+ kind: spec.kind
109139
+ })).bind(api);
109140
+ }
109141
+ async runBound(declared, options) {
109142
+ const added = this.registrySwitchBound();
109143
+ const migrations = [...declared, ...added];
109144
+ const phased = options?.only === void 0 || added.length === 0 ? options : {
109145
+ ...options,
109146
+ only: [...options.only, ...added.map((m) => m.meta.id)]
109147
+ };
108504
109148
  const api = this.ctx.api.migrations;
108505
109149
  const report = await runAddonMigrations({
108506
109150
  declareOwner: (input) => api.declareOwner.mutate(input),
108507
109151
  startMigration: (input) => api.startMigration.mutate(input),
108508
109152
  finishMigration: (input) => api.finishMigration.mutate(input)
108509
- }, migrations, this.ctx.logger, options);
109153
+ }, migrations, this.ctx.logger, phased);
108510
109154
  if (report.blockOwner.length > 0) throw new AddonMigrationsBlockedError(report.blockOwner);
108511
109155
  return report;
108512
109156
  }
@@ -109579,237 +110223,6 @@ function normalizeAddonInitResult(result) {
109579
110223
  if (Array.isArray(result)) return { providers: result };
109580
110224
  return result;
109581
110225
  }
109582
- var PREFIX = "records/";
109583
- /** The base of every records failure. `detail` is the human part of the message. */
109584
- var RecordsError = class extends Error {
109585
- code;
109586
- detail;
109587
- constructor(code, detail) {
109588
- super(`${PREFIX}${code}: ${detail}`);
109589
- this.name = "RecordsError";
109590
- this.code = code;
109591
- this.detail = detail;
109592
- }
109593
- };
109594
- /** A write guarded by `ifRev` found another revision (or an existing row for `ifRev: 0`). */
109595
- var RevConflictError = class extends RecordsError {
109596
- constructor(detail) {
109597
- super("rev-conflict", detail);
109598
- this.name = "RevConflictError";
109599
- }
109600
- };
109601
- /** The keychain could not store or serve a value: explicit, never an empty string. */
109602
- var RecordSecretUnavailableError = class extends RecordsError {
109603
- constructor(detail) {
109604
- super("secret-unavailable", detail);
109605
- this.name = "RecordSecretUnavailableError";
109606
- }
109607
- };
109608
- var InvalidRecordError = class extends RecordsError {
109609
- constructor(detail) {
109610
- super("invalid-record", detail);
109611
- this.name = "InvalidRecordError";
109612
- }
109613
- };
109614
- /** A kind declaration the engine refuses (non-additive change, bad shape, wrong file). */
109615
- var DeclarationRefusedError = class extends RecordsError {
109616
- constructor(detail) {
109617
- super("declaration-refused", detail);
109618
- this.name = "DeclarationRefusedError";
109619
- }
109620
- };
109621
- /** Limits and names of `ctx.records` (D881). One authority; the engine and the facade read it. */
109622
- /** The files a kind may live in. `history` is device-history's (D850), never records. */
109623
- var RECORD_DATABASES = ["settings", "events"];
109624
- /** The classes of a kind: the `@durable` vocabulary, one authority (replaces the annotation). */
109625
- var RECORD_CLASSES = [
109626
- "config",
109627
- "ledger",
109628
- "audit",
109629
- "mirror",
109630
- "ephemeral"
109631
- ];
109632
- var RECORD_DEFAULT_MAX_DATA_BYTES = 64 * 1024;
109633
- var RECORD_MAX_DATA_BYTES = 1024 * 1024;
109634
- var RECORD_BATCH_MAX = 1e3;
109635
- var RECORD_QUERY_MAX = 1e3;
109636
- /** A kind in the `settings` file may not bound itself above this (D447: high volume is `events`). */
109637
- var RECORD_SETTINGS_MAX_ROWS = 5e4;
109638
- /** The `Column`-free proof prefix: a ref collection for a kind's secret fields. */
109639
- var RECORD_SECRET_COLLECTION_PREFIX = "records:";
109640
- /**
109641
- * Secret fields of a record, addressed the way a Zod schema declares them
109642
- * (`collectZodSecretPaths`): dotted keys, `[]` for "each element of this array"
109643
- * (`auth.accessToken`, `headers[].value`).
109644
- *
109645
- * `{}` after a key means "each value of this map" (`applianceSecrets{}`): the map's own key
109646
- * names the value (`applianceSecrets{fridge}`), so no id key is declared and a body that drops a
109647
- * key releases exactly that key's secret.
109648
- *
109649
- * Array elements are matched by a DECLARED id key (`secretArrayKeys`:
109650
- * `{ headers: 'name' }`), never by index, so reordering a list keeps every
109651
- * keychain ref (the same rule as `arrayItemFieldPath`). The concrete path of a
109652
- * leaf names its element: `headers[X-Api].value`.
109653
- *
109654
- * Pure and browser-safe. Nothing here mutates: every transform returns a new value.
109655
- */
109656
- /** The array prefixes (declared form, e.g. `headers` or `a.headers`) of a path. */
109657
- function parseSecretPath(path) {
109658
- if (path.length === 0) throw new InvalidRecordError("an empty secret path");
109659
- return path.split(".").map((raw) => {
109660
- const each = raw.endsWith("[]");
109661
- const map = raw.endsWith("{}");
109662
- const key = each || map ? raw.slice(0, -2) : raw;
109663
- if (key.length === 0) throw new InvalidRecordError(`secret path "${path}" has an empty segment`);
109664
- return {
109665
- key,
109666
- each,
109667
- map
109668
- };
109669
- });
109670
- }
109671
- /** The declared array prefixes of `path` that need an id key (`headers`, `a.rows`). */
109672
- function secretArrayPrefixes(path) {
109673
- const segments = parseSecretPath(path);
109674
- const prefixes = [];
109675
- const walked = [];
109676
- for (const segment of segments) {
109677
- walked.push(segment.key);
109678
- if (segment.each) prefixes.push(walked.join("."));
109679
- }
109680
- return prefixes;
109681
- }
109682
- function isRecord$4(value) {
109683
- return typeof value === "object" && value !== null && !Array.isArray(value);
109684
- }
109685
- function elementId(element, idKey, declared, prefix) {
109686
- const id = isRecord$4(element) ? element[idKey] : void 0;
109687
- if (typeof id !== "string" || id.length === 0) throw new InvalidRecordError(`"${declared}": every element of "${prefix}" needs a non-empty string "${idKey}" to carry a secret`);
109688
- return id;
109689
- }
109690
- /**
109691
- * Visit every secret leaf PRESENT in `data` (an absent branch has nothing to
109692
- * visit). `replace` returns the new leaf value, or {@link REMOVE_LEAF}; the
109693
- * result is a new body, `data` is untouched.
109694
- */
109695
- var REMOVE_LEAF = Symbol("remove-leaf");
109696
- function mapAt(node, segments, index, walkedKeys, concretePrefix, declared, arrayKeys, visit) {
109697
- if (!isRecord$4(node)) return node;
109698
- const segment = segments[index];
109699
- if (segment === void 0) return node;
109700
- if (!Object.prototype.hasOwnProperty.call(node, segment.key)) return node;
109701
- const child = node[segment.key];
109702
- const keys = [...walkedKeys, segment.key];
109703
- const last = index === segments.length - 1;
109704
- if (segment.each) {
109705
- if (!Array.isArray(child)) return node;
109706
- const prefix = keys.join(".");
109707
- const idKey = arrayKeys[prefix];
109708
- if (idKey === void 0) throw new InvalidRecordError(`"${declared}": no id key declared for the array "${prefix}"`);
109709
- const mapped = child.map((element) => {
109710
- const id = elementId(element, idKey, declared, prefix);
109711
- const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}[${encodeURIComponent(id)}]`;
109712
- return last ? element : mapAt(element, segments, index + 1, keys, concrete, declared, arrayKeys, visit);
109713
- });
109714
- return {
109715
- ...node,
109716
- [segment.key]: mapped
109717
- };
109718
- }
109719
- if (segment.map) {
109720
- if (!isRecord$4(child)) return node;
109721
- const kept = Object.entries(child).map(([mapKey, value]) => {
109722
- const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}{${encodeURIComponent(mapKey)}}`;
109723
- if (!last) return [mapKey, mapAt(value, segments, index + 1, keys, concrete, declared, arrayKeys, visit)];
109724
- return [mapKey, visit({
109725
- declared,
109726
- concrete,
109727
- value
109728
- })];
109729
- }).filter(([, value]) => value !== REMOVE_LEAF);
109730
- return {
109731
- ...node,
109732
- [segment.key]: Object.fromEntries(kept)
109733
- };
109734
- }
109735
- const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}`;
109736
- if (last) {
109737
- const replacement = visit({
109738
- declared,
109739
- concrete,
109740
- value: child
109741
- });
109742
- if (replacement === REMOVE_LEAF) return Object.fromEntries(Object.entries(node).filter(([key]) => key !== segment.key));
109743
- return {
109744
- ...node,
109745
- [segment.key]: replacement
109746
- };
109747
- }
109748
- return {
109749
- ...node,
109750
- [segment.key]: mapAt(child, segments, index + 1, keys, concrete, declared, arrayKeys, visit)
109751
- };
109752
- }
109753
- /** Replace/remove every present secret leaf; returns a NEW body. */
109754
- function mapSecretLeaves(data, paths, arrayKeys, visit) {
109755
- let current = data;
109756
- for (const declared of paths) current = mapAt(current, parseSecretPath(declared), 0, [], "", declared, arrayKeys, visit);
109757
- return current;
109758
- }
109759
- /** Every present secret leaf, read-only. */
109760
- function collectSecretLeaves(data, paths, arrayKeys) {
109761
- const found = [];
109762
- mapSecretLeaves(data, paths, arrayKeys, (leaf) => {
109763
- found.push(leaf);
109764
- return leaf.value;
109765
- });
109766
- return found;
109767
- }
109768
- /**
109769
- * The keychain collection name a kind's secrets live under. Prefixed so a
109770
- * record's refs never collide with the refs a legacy collection of the same name
109771
- * already holds during an adoption.
109772
- */
109773
- function recordSecretCollection(kind) {
109774
- return `${RECORD_SECRET_COLLECTION_PREFIX}${kind}`;
109775
- }
109776
- /** The ONE ref a row's secret field may carry: the engine and the facade both build it here. */
109777
- function recordSecretRef(owner, kind, rowId, concretePath) {
109778
- return buildSecretRef({
109779
- owner,
109780
- scope: {
109781
- kind: "row",
109782
- collection: recordSecretCollection(kind),
109783
- rowId
109784
- },
109785
- fieldPath: concretePath
109786
- });
109787
- }
109788
- /**
109789
- * A stored secret, as an admin read shows it: a VIEW naming the row's own
109790
- * keychain ref (`set: true`), never the value and no longer the bare redaction
109791
- * token. The form hands it to the secret field, which reveals the value by ref
109792
- * through the audited `keychain-admin.reveal`; sent back untouched it keeps the
109793
- * stored secret (the records door reads a view as KEEP).
109794
- *
109795
- * ONE implementation for the entries service and for every addon that serves
109796
- * its own instances (`RecordIntegrationInstances`).
109797
- */
109798
- function isRecord$3(value) {
109799
- return typeof value === "object" && value !== null && !Array.isArray(value);
109800
- }
109801
- function secretViewsOf(owner, kind, id, decl, data) {
109802
- if (decl.secretPaths.length === 0) return data;
109803
- const shown = mapSecretLeaves(data, decl.secretPaths, decl.secretArrayKeys, (leaf) => {
109804
- if (leaf.value !== "__camstack_redacted__") return leaf.value;
109805
- return {
109806
- $secret: recordSecretRef(owner, kind, id, leaf.concrete),
109807
- v: 1,
109808
- set: true
109809
- };
109810
- });
109811
- return isRecord$3(shown) ? shown : data;
109812
- }
109813
110226
  /**
109814
110227
  * The share-view scope kinds a share-link token can carry. The hub mints
109815
110228
  * and validates them (`ShareViewGrantSchema` builds its
@@ -110063,6 +110476,7 @@ function defineRecordKinds(specs) {
110063
110476
  function entryBody(shape) {
110064
110477
  return object({
110065
110478
  name: string().min(1),
110479
+ enabled: boolean().optional(),
110066
110480
  ...shape
110067
110481
  });
110068
110482
  }
@@ -112015,6 +112429,10 @@ Object.freeze({
112015
112429
  "all",
112016
112430
  "one"
112017
112431
  ]
112432
+ },
112433
+ {
112434
+ "path": "positionUpdatedAt",
112435
+ "valueType": "number"
112018
112436
  }
112019
112437
  ],
112020
112438
  "meter": [{
@@ -112269,22 +112687,6 @@ Object.freeze({
112269
112687
  "path": "pumpRunning",
112270
112688
  "valueType": "boolean"
112271
112689
  },
112272
- {
112273
- "path": "lastDrink",
112274
- "valueType": "number"
112275
- },
112276
- {
112277
- "path": "currentHourDrink",
112278
- "valueType": "number"
112279
- },
112280
- {
112281
- "path": "last24hDrink",
112282
- "valueType": "number"
112283
- },
112284
- {
112285
- "path": "todayDrink",
112286
- "valueType": "number"
112287
- },
112288
112690
  {
112289
112691
  "path": "error",
112290
112692
  "valueType": "string"
@@ -112850,6 +113252,60 @@ Object.freeze({
112850
113252
  }
112851
113253
  ]
112852
113254
  });
113255
+ Object.freeze({
113256
+ "actions": { "run": 363e4 },
113257
+ "audio-analyzer": { "classify": 3e4 },
113258
+ "custom-model-registry": { "importModelBundle": 18e5 },
113259
+ "database-snapshot": { "writeSnapshot": 18e5 },
113260
+ "device-manager": {
113261
+ "migrateDevice": 72e4,
113262
+ "runDiscoverySweep": 12e4
113263
+ },
113264
+ "device-provider": { "reloadDevice": 18e4 },
113265
+ "llm": {
113266
+ "generate": 6e5,
113267
+ "generateVision": 6e5,
113268
+ "testProfile": 6e5
113269
+ },
113270
+ "llm-runtime": {
113271
+ "complete": 6e5,
113272
+ "completeApple": 6e5,
113273
+ "ensureStarted": 6e5,
113274
+ "installModel": 36e5
113275
+ },
113276
+ "local-network": { "scanNetwork": 9e4 },
113277
+ "model-convert": { "convert": 6e5 },
113278
+ "pipeline-analytics": {
113279
+ "addRetrainFrameFromRecording": 6e4,
113280
+ "offerRetrainArchive": 12e4,
113281
+ "proposeRetrainAnnotationsWithLlm": 18e4,
113282
+ "resolveRetrainTrainingCorpus": 6e4,
113283
+ "writeRetrainArchive": 36e5
113284
+ },
113285
+ "server-management": { "applyServerUpdate": 96e4 },
113286
+ "terminal-session": { "pullOutput": 15e3 },
113287
+ "training": {
113288
+ "canaryResult": 12e4,
113289
+ "cancelJob": 12e4,
113290
+ "planJob": 6e4,
113291
+ "registerResult": 18e5,
113292
+ "rollbackCanary": 12e4,
113293
+ "startJob": 12e4,
113294
+ "startJobBatch": 12e4
113295
+ },
113296
+ "training-provider": {
113297
+ "cancelJob": 6e4,
113298
+ "cleanupJob": 3e5,
113299
+ "getJob": 6e4,
113300
+ "listJobEvents": 6e4,
113301
+ "listJobs": 12e4,
113302
+ "offerArtifact": 3e5,
113303
+ "readResult": 3e5,
113304
+ "submitJob": 18e5,
113305
+ "uploadDataset": 72e5,
113306
+ "validateCredentials": 3e4
113307
+ }
113308
+ });
112853
113309
  object({
112854
113310
  code: string().regex(/^[a-z][a-z0-9-]*(\.[a-z0-9-]+)+$/),
112855
113311
  params: record(string(), union([string(), number()])).optional()
@@ -112893,7 +113349,7 @@ function sleep(ms) {
112893
113349
  return new Promise((resolve) => setTimeout(resolve, Math.max(0, ms)));
112894
113350
  }
112895
113351
  //#endregion
112896
- //#region ../types/dist/composition-pOHbTzRB.mjs
113352
+ //#region ../types/dist/composition-BmBHuDTQ.mjs
112897
113353
  /**
112898
113354
  * The ffmpeg build every CamStack node downloads, per platform and arch.
112899
113355
  *
@@ -113197,7 +113653,7 @@ var table = {
113197
113653
  },
113198
113654
  dwell: {
113199
113655
  minArgs: 3,
113200
- maxArgs: 3,
113656
+ maxArgs: 4,
113201
113657
  apply: () => {
113202
113658
  throw new ExpressionEvalError("dwell: stateful evaluation context is required");
113203
113659
  }
@@ -114054,6 +114510,17 @@ var NodeColorIdSchema = _enum([
114054
114510
  "node-g",
114055
114511
  "node-h"
114056
114512
  ]);
114513
+ //#endregion
114514
+ //#region ../types/dist/index.mjs
114515
+ /**
114516
+ * The `smtp-inbound` broker kind (D999): a mailbox a device can send mail to.
114517
+ *
114518
+ * The `broker` cap carries these as `Record<string, unknown>` on the wire; the
114519
+ * provider and its consumers parse them with the schemas below at BOTH ends, so
114520
+ * the shape is declared once.
114521
+ */
114522
+ /** The broker kind tag. */
114523
+ var SMTP_INBOUND_KIND = "smtp-inbound";
114057
114524
  /** The id the first mailbox is minted under (adopt-id), so a consumer can find it again. */
114058
114525
  var SMTP_INBOUND_DEFAULT_ID = "smtp-inbound-default";
114059
114526
  var SMTP_INBOUND_DEFAULT_PORT = 2525;
@@ -114250,212 +114717,6 @@ var IntegrationInstanceRefSchema = object({
114250
114717
  ]),
114251
114718
  candidateStableId: string().optional()
114252
114719
  });
114253
- /**
114254
- * `RecordIntegrationInstances` - the `integration-instances` provider over ONE
114255
- * entry kind, so an addon that holds a connection serves it in ~30 lines.
114256
- *
114257
- * Every instance is one record of the addon's own kind, keyed by the
114258
- * `integrations` registry id. The records door does the secret work: a field the
114259
- * kind marks `.meta({ secret: true })` is a keychain marker bound to the row, so
114260
- * deleting the row deletes the secret, and one row's value is never another's.
114261
- *
114262
- * Patch rules for a secret (`updateInstance`): omitted, `''`, the redaction
114263
- * token or the view the form was given KEEP the stored secret;
114264
- * `{ $secretClear: true }` clears it; any other string replaces it.
114265
- */
114266
- /** The most instances one addon lists (an integrations page, not a table). */
114267
- var INSTANCES_LIST_MAX = 1e3;
114268
- /** The keys of the kind's secret fields that sit at the top level of the body. */
114269
- function topLevelSecretKeys(paths) {
114270
- return new Set(paths.filter((p) => !p.includes(".") && !p.includes("[") && !p.includes("{")));
114271
- }
114272
- /** The keys of the kind's top-level MAPS whose values are secrets (`applianceSecrets{}`). */
114273
- function secretMapKeys(paths) {
114274
- return new Set(paths.filter((p) => p.endsWith("{}") && !p.slice(0, -2).match(/[.[{]/)).map((p) => p.slice(0, -2)));
114275
- }
114276
- /**
114277
- * A patch value for a map of secrets: an entry that is omitted, `''`, the redaction token or the
114278
- * view the form was given KEEPS its stored secret (it is left out of the merge); `{ $secretClear }`
114279
- * or `null` removes the entry; any other string replaces it. Null when nothing is left to merge.
114280
- */
114281
- function secretMapPatch(value) {
114282
- if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
114283
- const out = {};
114284
- for (const [key, entry] of Object.entries(value)) if (entry === null || isSecretClear(entry)) out[key] = null;
114285
- else if (typeof entry === "string" && entry !== "" && entry !== "__camstack_redacted__" && !isSecretFieldView(entry)) out[key] = entry;
114286
- return Object.keys(out).length > 0 ? out : null;
114287
- }
114288
- /** Does the kind's body schema carry an `enabled` field? */
114289
- function declaresEnabled(kind) {
114290
- const json = toJSONSchema(kind.schema, {
114291
- unrepresentable: "any",
114292
- io: "input"
114293
- });
114294
- const properties = Reflect.get(json, "properties");
114295
- return typeof properties === "object" && properties !== null && "enabled" in properties;
114296
- }
114297
- var RecordIntegrationInstances = class {
114298
- records;
114299
- kind;
114300
- hooks;
114301
- handle;
114302
- secretKeys;
114303
- secretMaps;
114304
- nameField;
114305
- /** The `integrations` registry owns the on/off switch (`role: devices`); the body has none. */
114306
- registryOwnsEnabled;
114307
- constructor(records, kind, hooks) {
114308
- this.records = records;
114309
- this.kind = kind;
114310
- this.hooks = hooks;
114311
- this.handle = records.kind(kind);
114312
- this.secretKeys = topLevelSecretKeys(kind.declaration.secretPaths);
114313
- this.secretMaps = secretMapKeys(kind.declaration.secretPaths);
114314
- this.nameField = kind.declaration.entry?.nameField ?? "name";
114315
- this.registryOwnsEnabled = hooks.description.role === "devices";
114316
- if (this.registryOwnsEnabled && declaresEnabled(kind)) throw new Error(`kind "${kind.name}": the integrations registry owns the on/off switch of a role "devices" addon, so the body must not declare "enabled"`);
114317
- }
114318
- /**
114319
- * One instance read for the addon's own runtime; null when absent. When the keychain is
114320
- * locked the row is served WITHOUT its secrets and says so (`secrets: 'unavailable'`), so the
114321
- * caller can keep what it had instead of reconfiguring with an empty secret (D49).
114322
- */
114323
- async readResolved(id) {
114324
- try {
114325
- const record = await this.handle.getResolved(id);
114326
- return record === null ? null : {
114327
- id,
114328
- body: record.data,
114329
- enabled: record.data.enabled !== false,
114330
- secrets: "resolved"
114331
- };
114332
- } catch (err) {
114333
- if (!(err instanceof RecordSecretUnavailableError)) throw err;
114334
- const stored = await this.handle.get(id);
114335
- if (stored === null) return null;
114336
- return {
114337
- id,
114338
- body: Object.fromEntries(Object.entries(stored.data).filter(([key]) => !this.secretKeys.has(key))),
114339
- enabled: stored.data.enabled !== false,
114340
- secrets: "unavailable"
114341
- };
114342
- }
114343
- }
114344
- /** The body of {@link readResolved} alone; a locked keychain yields the row without secrets. */
114345
- async getResolved(id) {
114346
- return (await this.readResolved(id))?.body ?? null;
114347
- }
114348
- /** Every instance, secrets resolved where the keychain allows; an absent one is skipped. */
114349
- async listResolved() {
114350
- const page = await this.handle.query({ limit: INSTANCES_LIST_MAX });
114351
- const out = [];
114352
- for (const record of page.records) {
114353
- const read = await this.readResolved(record.id);
114354
- if (read !== null) out.push(read);
114355
- }
114356
- return out;
114357
- }
114358
- viewOf(record) {
114359
- const shown = secretViewsOf(this.records.owner, this.kind.name, record.id, this.kind.declaration, record.data);
114360
- const rawName = record.data[this.nameField];
114361
- const kind = this.hooks.kindOf?.(record.data);
114362
- const health = this.hooks.health?.(record.data, record.id);
114363
- return {
114364
- id: record.id,
114365
- name: typeof rawName === "string" ? rawName : record.id,
114366
- configured: this.hooks.configured(record.data),
114367
- ...this.registryOwnsEnabled ? {} : { enabled: record.data.enabled !== false },
114368
- formValues: shown,
114369
- ...kind !== void 0 ? { kind } : {},
114370
- ...health?.status !== void 0 ? { status: health.status } : {},
114371
- ...health?.lastCheckedAt !== void 0 ? { lastCheckedAt: health.lastCheckedAt } : {}
114372
- };
114373
- }
114374
- describe = async () => this.hooks.mintId === void 0 ? this.hooks.description : {
114375
- ...this.hooks.description,
114376
- mintsId: true
114377
- };
114378
- instanceFormSchema = async ({ id }) => this.hooks.formSchema(id);
114379
- listInstances = async () => {
114380
- return (await this.handle.query({ limit: INSTANCES_LIST_MAX })).records.map((record) => this.viewOf(record));
114381
- };
114382
- getInstance = async ({ id }) => {
114383
- const record = await this.handle.get(id);
114384
- return record === null ? null : this.viewOf(record);
114385
- };
114386
- /** Insert ONE row (`ifRev: 0`: an existing id is refused, never overwritten). */
114387
- createInstance = async ({ id, name, kind, values }) => {
114388
- const minted = id ?? this.hooks.mintId?.({
114389
- name,
114390
- ...kind !== void 0 ? { kind } : {}
114391
- });
114392
- if (minted === void 0) throw new Error("createInstance needs an id: this provider does not mint one");
114393
- await this.handle.put({
114394
- id: minted,
114395
- data: this.hooks.initialBody(name, kind)
114396
- }, { ifRev: 0 });
114397
- const patch = this.patchOf(values ?? {});
114398
- if (Object.keys(patch).length > 0) await this.handle.patch(minted, patch);
114399
- await this.hooks.onChanged?.(minted, "created");
114400
- return { id: minted };
114401
- };
114402
- updateInstance = async ({ id, name, values }) => {
114403
- const patch = this.patchOf(values);
114404
- if (name !== void 0) patch[this.nameField] = name;
114405
- await this.handle.patch(id, patch);
114406
- await this.hooks.onChanged?.(id, "updated");
114407
- return { ok: true };
114408
- };
114409
- /** The record patch a form `values` object means: secrets kept, cleared or replaced. */
114410
- patchOf(values) {
114411
- const patch = {};
114412
- for (const [key, value] of Object.entries(values)) {
114413
- if (value === void 0) continue;
114414
- if (this.secretMaps.has(key)) {
114415
- const entries = secretMapPatch(value);
114416
- if (entries !== null) patch[key] = entries;
114417
- } else if (!this.secretKeys.has(key)) patch[key] = value;
114418
- else if (isSecretClear(value)) patch[key] = null;
114419
- else if (typeof value === "string" && value !== "" && value !== "__camstack_redacted__" && !isSecretFieldView(value)) patch[key] = value;
114420
- }
114421
- return patch;
114422
- }
114423
- /** The switch lives in the record body; the addon is told so it applies it (D996). */
114424
- setInstanceEnabled = async ({ id, enabled }) => {
114425
- if (this.registryOwnsEnabled) throw new Error(`instance "${id}": the integrations registry owns the on/off switch of this addon; set it with integrations.update`);
114426
- await this.handle.patch(id, { enabled });
114427
- await this.hooks.onChanged?.(id, "enabled");
114428
- return { ok: true };
114429
- };
114430
- /** The row and its keychain refs go together (the records door). */
114431
- deleteInstance = async ({ id }) => {
114432
- await this.handle.delete(id);
114433
- await this.hooks.onChanged?.(id, "deleted");
114434
- return { ok: true };
114435
- };
114436
- testInstance = async (input) => {
114437
- if (this.hooks.test === void 0) return {
114438
- success: false,
114439
- status: "unsupported",
114440
- error: "This integration declares no connection test"
114441
- };
114442
- return this.hooks.test(input);
114443
- };
114444
- /** The flat provider object to hand to `registerProvider`. */
114445
- toProvider() {
114446
- return {
114447
- describe: this.describe,
114448
- instanceFormSchema: this.instanceFormSchema,
114449
- listInstances: this.listInstances,
114450
- getInstance: this.getInstance,
114451
- createInstance: this.createInstance,
114452
- updateInstance: this.updateInstance,
114453
- setInstanceEnabled: this.setInstanceEnabled,
114454
- deleteInstance: this.deleteInstance,
114455
- testInstance: this.testInstance
114456
- };
114457
- }
114458
- };
114459
114720
  var EncodeProfileSchema = object({
114460
114721
  video: object({
114461
114722
  codec: _enum([
@@ -121520,31 +121781,21 @@ var APPLIANCE_CAP_VOCABULARY = {
121520
121781
  "pet-fountain": {
121521
121782
  scope: "device",
121522
121783
  noun: t("Pet fountain", "Fontana per animali"),
121523
- actions: [
121524
- {
121525
- id: "petFountain.pumpOn",
121526
- method: "setPump",
121527
- label: t("Pump on", "Pompa accesa"),
121528
- phrase: t("Start the pump of {device}", "Avvia la pompa di {device}"),
121529
- icon: "play",
121530
- args: { on: true }
121531
- },
121532
- {
121533
- id: "petFountain.pumpOff",
121534
- method: "setPump",
121535
- label: t("Pump off", "Pompa spenta"),
121536
- phrase: t("Stop the pump of {device}", "Ferma la pompa di {device}"),
121537
- icon: "square",
121538
- args: { on: false }
121539
- },
121540
- {
121541
- id: "petFountain.resetDailyConsumption",
121542
- method: "resetDailyConsumption",
121543
- label: t("Clear daily consumption", "Azzera il consumo giornaliero"),
121544
- phrase: t("Clear the daily water consumption of {device}", "Azzera il consumo giornaliero di acqua di {device}"),
121545
- icon: "rotate-ccw"
121546
- }
121547
- ],
121784
+ actions: [{
121785
+ id: "petFountain.pumpOn",
121786
+ method: "setPump",
121787
+ label: t("Pump on", "Pompa accesa"),
121788
+ phrase: t("Start the pump of {device}", "Avvia la pompa di {device}"),
121789
+ icon: "play",
121790
+ args: { on: true }
121791
+ }, {
121792
+ id: "petFountain.pumpOff",
121793
+ method: "setPump",
121794
+ label: t("Pump off", "Pompa spenta"),
121795
+ phrase: t("Stop the pump of {device}", "Ferma la pompa di {device}"),
121796
+ icon: "square",
121797
+ args: { on: false }
121798
+ }],
121548
121799
  state: [{
121549
121800
  kind: "boolean",
121550
121801
  field: "empty",
@@ -145498,8 +145749,15 @@ var ActionInputSchema = object({
145498
145749
  var ActionRunOriginSchema = object({
145499
145750
  /** The automation block whose step started it. */
145500
145751
  blockId: string().min(1).optional() });
145501
- /** `started` = the caller did not ask to wait. */
145502
- var ActionRunOutcomeSchema = union([AutomationRunOutcomeSchema, literal("started")]);
145752
+ /**
145753
+ * `started` = the caller did not ask to wait. `timed-out` = the run reached the
145754
+ * ceiling (`ACTION_RUN_MAX_MS`) and was stopped; it is never a `ran`.
145755
+ */
145756
+ var ActionRunOutcomeSchema = union([
145757
+ AutomationRunOutcomeSchema,
145758
+ literal("started"),
145759
+ literal("timed-out")
145760
+ ]);
145503
145761
  var ActionRunResultSchema = object({
145504
145762
  runId: string().min(1),
145505
145763
  outcome: ActionRunOutcomeSchema,
@@ -146021,6 +146279,8 @@ method(object({}), array(ActionEntrySchema), { auth: "admin" }), method(object({
146021
146279
  kind: "mutation",
146022
146280
  auth: "admin"
146023
146281
  });
146282
+ /** `timeoutMs` of `actions.run`: a waited call outlives any legal run. */
146283
+ var ACTION_RUN_TIMEOUT_MS = 363e4;
146024
146284
  /**
146025
146285
  * actions — the ONE surface for runnable actions, for the UI and for
146026
146286
  * automations. Provided by the core-blocks builtin on the hub.
@@ -146039,6 +146299,12 @@ method(object({}), array(ActionEntrySchema), { auth: "admin" }), method(object({
146039
146299
  * An admin, and an in-process caller (an automation block), may run any action.
146040
146300
  * Every refusal is typed (`[not-linked] …`) and logged.
146041
146301
  *
146302
+ * **A run lasts at most `ACTION_RUN_MAX_MS` (60 min).** The provider stops a
146303
+ * run that reaches it and answers `timed-out` (never `ran`); an action whose
146304
+ * `wait` steps alone add up to more is refused at create/update
146305
+ * (`[invalid-steps]`). `run` declares a `timeoutMs` above that ceiling, so a
146306
+ * waited call (an automation step) is never cut by the 60 s transport default.
146307
+ *
146042
146308
  * A second `run` of an action that is already running is REFUSED — traced and
146043
146309
  * logged — never queued.
146044
146310
  */
@@ -146065,7 +146331,8 @@ method(object({}), array(ActionEntrySchema), { auth: "admin" }), method(object({
146065
146331
  role: "viewer",
146066
146332
  auth: "protected",
146067
146333
  kind: "mutation",
146068
- caller: "required"
146334
+ caller: "required",
146335
+ timeoutMs: ACTION_RUN_TIMEOUT_MS
146069
146336
  }), method(ActionIdInput, _void(), {
146070
146337
  kind: "mutation",
146071
146338
  auth: "admin"
@@ -151092,6 +151359,9 @@ var MediaPlayerStatusSchema = object({
151092
151359
  /** Repeat mode. Null when no repeat surface.
151093
151360
  * Pair with `DeviceFeature.MediaPlayerRepeat`. */
151094
151361
  repeat: MediaPlayerRepeatSchema.nullable(),
151362
+ /** Ms epoch when `position` was read from the device. Null when the driver
151363
+ * does not say; a UI that advances the position while playing counts from it. */
151364
+ positionUpdatedAt: number().nullable().default(null),
151095
151365
  /** Ms epoch when the slice was last updated. */
151096
151366
  lastChangedAt: number()
151097
151367
  });
@@ -151727,7 +151997,9 @@ var ThresholdTransformDraftSchema = object({
151727
151997
  comparison: _enum(["gte", "lte"]),
151728
151998
  threshold: number(),
151729
151999
  startDwellMs: number().nonnegative(),
151730
- stopDwellMs: number().nonnegative()
152000
+ stopDwellMs: number().nonnegative(),
152001
+ /** Samples a start needs; absent = the compiler's default for the source (2 for running power, else 1). */
152002
+ minSamples: number().int().min(1).optional()
151731
152003
  });
151732
152004
  var CustomizeTransformDraftSchema = discriminatedUnion("kind", [
151733
152005
  IdentityTransformDraftSchema,
@@ -157657,6 +157929,7 @@ var IntegrationWithStateSchema = object({
157657
157929
  id: string(),
157658
157930
  addonId: string(),
157659
157931
  name: string(),
157932
+ /** A projection of the instance body's switch (`setInstanceEnabled` is the only writer). */
157660
157933
  enabled: boolean(),
157661
157934
  info: record(string(), unknown()).readonly(),
157662
157935
  /** The discovery candidate this integration was set up from (D984). */
@@ -157669,6 +157942,7 @@ var IntegrationLiteSchema = object({
157669
157942
  id: string(),
157670
157943
  addonId: string(),
157671
157944
  name: string(),
157945
+ /** A projection of the instance body's switch (`setInstanceEnabled` is the only writer). */
157672
157946
  enabled: boolean(),
157673
157947
  info: record(string(), unknown()).readonly(),
157674
157948
  /** The discovery candidate this integration was set up from (D984). */
@@ -157768,7 +158042,6 @@ var TestConnectionResultSchema = object({
157768
158042
  var CreateIntegrationInputSchema = object({
157769
158043
  addonId: string(),
157770
158044
  name: string(),
157771
- enabled: boolean().optional(),
157772
158045
  info: record(string(), unknown()).optional(),
157773
158046
  /** `stableId` of the discovery candidate the form was seeded from (D984). */
157774
158047
  originStableId: string().optional(),
@@ -157777,6 +158050,11 @@ var CreateIntegrationInputSchema = object({
157777
158050
  var UpdateIntegrationInputSchema = object({
157778
158051
  id: string(),
157779
158052
  name: string().optional(),
158053
+ /**
158054
+ * Accepted for a FIXED builtin only (`info.fixed`: alarm panel, camera grid, core blocks,
158055
+ * terminal), which keeps no instance record: the registry flag is its one store. Any other
158056
+ * integration is switched through `integration-instances.setInstanceEnabled`.
158057
+ */
157780
158058
  enabled: boolean().optional(),
157781
158059
  info: record(string(), unknown()).optional()
157782
158060
  });
@@ -157824,7 +158102,7 @@ var IntegrationInstanceIdSchema = string().min(1);
157824
158102
  var IntegrationInstanceModeSchema = _enum(["single", "multiple"]);
157825
158103
  /**
157826
158104
  * What the addon's instances ARE for the Integrations page (planning#416). `devices`: each
157827
- * instance is an integration that brings devices (the registry owns its on/off switch);
158105
+ * instance is an integration that brings devices (its record body owns the on/off switch);
157828
158106
  * `services`: a connection configured from the addon's own function page, never listed on
157829
158107
  * Integrations.
157830
158108
  * It is the same vocabulary as the manifest's `integrationRole`, which stays as an override.
@@ -157867,18 +158145,38 @@ var IntegrationInstanceKindSchema = object({
157867
158145
  /** Relative hub path to disconnect that account. */
157868
158146
  disconnectPath: string().min(1).optional()
157869
158147
  });
158148
+ /**
158149
+ * How devices of an instance are found. `none`: the operator adds them by hand; `lan`: the addon
158150
+ * scans the network before any instance exists (the wizard offers the candidates); `account`: the
158151
+ * devices appear after the instance signs in. `scopedToInstance`: a discovery run belongs to ONE
158152
+ * instance and its candidates are claimed by it.
158153
+ */
158154
+ var IntegrationInstanceDiscoverySchema = object({
158155
+ mode: _enum([
158156
+ "none",
158157
+ "lan",
158158
+ "account"
158159
+ ]),
158160
+ scopedToInstance: boolean()
158161
+ });
158162
+ /**
158163
+ * One link a kind of this provider declares (D1013 rule 5): the body `field` of an instance of
158164
+ * `kind` holds the id of an instance of the function cap `to.cap` (of kind `to.kind`, when set).
158165
+ * The hub indexes these so the target's delete is refused while a link names it.
158166
+ */
158167
+ var IntegrationInstanceLinkSchema = object({
158168
+ kind: string().min(1),
158169
+ field: string().min(1),
158170
+ to: object({
158171
+ cap: string().min(1),
158172
+ kind: string().min(1).optional()
158173
+ })
158174
+ });
157870
158175
  var IntegrationInstanceDescriptionSchema = object({
157871
158176
  /** What the instances are for the Integrations page; see {@link IntegrationInstanceRoleSchema}. */
157872
158177
  role: IntegrationInstanceRoleSchema,
157873
158178
  /** How the devices of an instance are found; absent means `{ mode: 'none' }`. */
157874
- discovery: object({
157875
- mode: _enum([
157876
- "none",
157877
- "lan",
157878
- "account"
157879
- ]),
157880
- scopedToInstance: boolean()
157881
- }).optional(),
158179
+ discovery: IntegrationInstanceDiscoverySchema.optional(),
157882
158180
  /** `single`: at most one instance can exist (Loki). `multiple`: an account each. */
157883
158181
  instanceMode: IntegrationInstanceModeSchema,
157884
158182
  /** What the instance is, for the UI (`destination`, `relay`, `account`). */
@@ -157899,7 +158197,9 @@ var IntegrationInstanceDescriptionSchema = object({
157899
158197
  * `createInstance` without an `id` works: the provider mints it. Absent means the caller must
157900
158198
  * send an id (the UI then mints an opaque one).
157901
158199
  */
157902
- mintsId: boolean().optional()
158200
+ mintsId: boolean().optional(),
158201
+ /** The links to other instances the provider's kinds declare; absent means none. */
158202
+ links: array(IntegrationInstanceLinkSchema).optional()
157903
158203
  });
157904
158204
  var IntegrationInstanceStatusSchema = object({
157905
158205
  state: _enum([
@@ -157919,8 +158219,8 @@ var IntegrationInstanceSchema = object({
157919
158219
  configured: boolean(),
157920
158220
  /**
157921
158221
  * The instance's own on/off switch (D996), derived from the record body (`enabled !== false`,
157922
- * so a row written before the field existed is on). Absent when the `integrations` registry
157923
- * owns the switch (`describe().role` is `devices`): read it from the registry row.
158222
+ * so a row written before the field existed is on). The same for every role, `devices` included:
158223
+ * the body is the one store, `setInstanceEnabled` the one writer (epic #440, step 3).
157924
158224
  */
157925
158225
  enabled: boolean().optional(),
157926
158226
  /** The kind of this instance (one of `describe().kinds[].id`), when the provider has kinds. */
@@ -157970,7 +158270,8 @@ var integrationInstancesCapability = {
157970
158270
  auth: "admin"
157971
158271
  }),
157972
158272
  /**
157973
- * Switch ONE instance on or off. A row control, not a form field: `updateInstance.values` is the
158273
+ * Switch ONE instance on or off, for every role; a missing record is created from the addon's
158274
+ * initial body. A row control, not a form field: `updateInstance.values` is the
157974
158275
  * form patch (D62, D996). An off instance keeps its record and secrets and does no work.
157975
158276
  */
157976
158277
  setInstanceEnabled: method(object({
@@ -161054,6 +161355,8 @@ var MigrationIntegrationSchema = object({
161054
161355
  addonId: string(),
161055
161356
  name: string(),
161056
161357
  info: Rows,
161358
+ /** The registry's stored switch: read by the one-switch migration, nothing else. */
161359
+ enabled: boolean().optional(),
161057
161360
  originStableId: string().optional()
161058
161361
  });
161059
161362
  var MigrationDeviceSchema = object({
@@ -171249,14 +171552,6 @@ var PetFountainStatusSchema = object({
171249
171552
  empty: boolean().nullable(),
171250
171553
  /** True while the pump is running. Null while unknown. */
171251
171554
  pumpRunning: boolean().nullable(),
171252
- /** Water drunk in the last drink, in litres. */
171253
- lastDrink: number().min(0).nullable().meta(readingMeta("volume")),
171254
- /** Water drunk in the current hour, in litres. */
171255
- currentHourDrink: number().min(0).nullable().meta(readingMeta("volume")),
171256
- /** Water drunk over the last 24 hours (rolling), in litres. */
171257
- last24hDrink: number().min(0).nullable().meta(readingMeta("volume")),
171258
- /** Water drunk since local midnight, in litres. Null when the fountain has no such sensor. */
171259
- todayDrink: number().min(0).nullable().meta(readingMeta("volume")),
171260
171555
  /** Decoded fault message. Null means healthy; a non-null string is an active fault. */
171261
171556
  error: string().nullable(),
171262
171557
  /** Ms epoch when the slice was last refreshed. */
@@ -171269,21 +171564,15 @@ var petFountainCapability = {
171269
171564
  deviceNative: true,
171270
171565
  mode: "singleton",
171271
171566
  deviceTypes: [DeviceType.PetFountain],
171272
- methods: {
171273
- /** Start or stop the pump. */
171274
- setPump: method(object({
171275
- deviceId: DeviceIdSchema$1,
171276
- on: boolean()
171277
- }), _void(), {
171278
- kind: "mutation",
171279
- auth: "protected"
171280
- }),
171281
- /** Clear the rolling daily consumption counters on the device. */
171282
- resetDailyConsumption: method(object({ deviceId: DeviceIdSchema$1 }), _void(), {
171283
- kind: "mutation",
171284
- auth: "protected"
171285
- })
171286
- },
171567
+ methods: {
171568
+ /** Start or stop the pump. */
171569
+ setPump: method(object({
171570
+ deviceId: DeviceIdSchema$1,
171571
+ on: boolean()
171572
+ }), _void(), {
171573
+ kind: "mutation",
171574
+ auth: "protected"
171575
+ }) },
171287
171576
  status: {
171288
171577
  schema: PetFountainStatusSchema,
171289
171578
  kind: "push"
@@ -171307,14 +171596,6 @@ var petFountainCapability = {
171307
171596
  waterVolume: {
171308
171597
  kind: "gauge",
171309
171598
  unit: "L"
171310
- },
171311
- todayDrink: {
171312
- kind: "gauge",
171313
- unit: "L"
171314
- },
171315
- last24hDrink: {
171316
- kind: "gauge",
171317
- unit: "L"
171318
171599
  }
171319
171600
  } }
171320
171601
  };
@@ -191030,13 +191311,6 @@ Object.freeze({
191030
191311
  access: "view",
191031
191312
  role: "viewer"
191032
191313
  },
191033
- "petFountain.resetDailyConsumption": {
191034
- capName: "pet-fountain",
191035
- capScope: "device",
191036
- addonId: null,
191037
- access: "delete",
191038
- role: "viewer"
191039
- },
191040
191314
  "petFountain.setPump": {
191041
191315
  capName: "pet-fountain",
191042
191316
  capScope: "device",
@@ -197585,11 +197859,6 @@ Object.freeze({
197585
197859
  form: "single",
197586
197860
  optional: false
197587
197861
  }],
197588
- "petFountain.resetDailyConsumption": [{
197589
- name: "deviceId",
197590
- form: "single",
197591
- optional: false
197592
- }],
197593
197862
  "petFountain.setPump": [{
197594
197863
  name: "deviceId",
197595
197864
  form: "single",
@@ -200384,7 +200653,6 @@ object({
200384
200653
  delay: number().nonnegative().optional(),
200385
200654
  commands: record(string(), unknown())
200386
200655
  });
200387
- entryBody({ brokerId: string() });
200388
200656
  //#endregion
200389
200657
  //#region src/clips/clip-prefetch.ts
200390
200658
  /** The longest a device may stay quiet after refusals, whatever its interval. */
@@ -212887,6 +213155,10 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
212887
213155
  const host = this.config.get("host");
212888
213156
  return typeof host === "string" && host.length > 0 ? host : null;
212889
213157
  }
213158
+ /** The integration this camera belongs to, or `null` when it names none. */
213159
+ get integrationId() {
213160
+ return this.hubIntegrationId();
213161
+ }
212890
213162
  /** The integration (one NVR / Home Hub, D985) this camera was adopted from, or `null`. */
212891
213163
  hubIntegrationId() {
212892
213164
  const id = this.config.get("integrationId");
@@ -220861,6 +221133,20 @@ var SMTP_BROKER_ADDON_ID = "smtp-nodemailer";
220861
221133
  /** Who this addon is, among the subscribers of a mailbox. */
220862
221134
  var REOLINK_SUBSCRIBER_ID = "provider-reolink";
220863
221135
  var MAILBOX_NAME = "Camera mailbox";
221136
+ /** What an integration's `mailboxId` points at: an `smtp-inbound` instance of the `broker` cap (D1013). */
221137
+ var SMTP_MAILBOX_LINK = {
221138
+ cap: "broker",
221139
+ kind: SMTP_INBOUND_KIND
221140
+ };
221141
+ /** The body field of an integration record that names its camera mailbox; empty or absent when none. */
221142
+ var MAILBOX_LINK_FIELD = "mailboxId";
221143
+ /**
221144
+ * The link field of the integration record. The bridge fills it (an integration whose standalone
221145
+ * cameras mail the mailbox links to it), so the hub refuses to delete a mailbox that is in use.
221146
+ */
221147
+ function mailboxLinkField() {
221148
+ return optionalLinkField(SMTP_MAILBOX_LINK);
221149
+ }
220864
221150
  var RECIPIENT_PREFIX = "cam-";
220865
221151
  /**
220866
221152
  * The real port: the mailboxes are `integration-instances` of the SMTP addon (the kind of its
@@ -221014,20 +221300,54 @@ var EmailPushBridge = class {
221014
221300
  const recipients = this.recipients();
221015
221301
  if (recipients.length === 0) {
221016
221302
  if (this.brokerId !== null && this.subscriptionId !== null) await this.deps.port.unsubscribe(this.brokerId, this.subscriptionId);
221303
+ if (this.brokerId !== null) await this.syncLinks(this.brokerId, /* @__PURE__ */ new Set());
221017
221304
  this.subscriptionId = null;
221018
221305
  this.declared = null;
221019
221306
  return;
221020
221307
  }
221021
- const key = recipients.join(",");
221308
+ const owners = this.linkOwners();
221309
+ const key = `${recipients.join(",")}|${[...owners].sort().join(",")}`;
221022
221310
  if (!force && this.declared === key && this.subscriptionId !== null) return;
221023
221311
  const brokerId = await this.ensureMailbox();
221024
221312
  await this.seedBaseline(brokerId);
221025
221313
  const { subscriptionId } = await this.deps.port.subscribe(brokerId, recipients);
221026
221314
  this.brokerId = brokerId;
221027
221315
  this.subscriptionId = subscriptionId;
221028
- this.declared = key;
221316
+ this.declared = await this.syncLinks(brokerId, owners) ? key : null;
221029
221317
  await this.reconcile();
221030
221318
  }
221319
+ /** The integrations whose standalone cameras mail the mailbox: they link to it. */
221320
+ linkOwners() {
221321
+ const owners = /* @__PURE__ */ new Set();
221322
+ for (const cam of this.deps.listCameras()) if (cam.isEmailPushEligible && cam.integrationId !== null) owners.add(cam.integrationId);
221323
+ return owners;
221324
+ }
221325
+ /**
221326
+ * Make the `mailboxId` links say who uses the mailbox: `owners` link to it, no other
221327
+ * integration does. Idempotent, so an install whose mailbox already exists is filled from it
221328
+ * (the mailbox is re-adopted by `ensureMailbox`) with nothing stored beforehand. False when the
221329
+ * links could not be written: the caller retries at the next sync.
221330
+ */
221331
+ async syncLinks(brokerId, owners) {
221332
+ try {
221333
+ const rows = await this.deps.links.list();
221334
+ for (const row of rows) {
221335
+ const wanted = owners.has(row.id) ? brokerId : "";
221336
+ if (row.mailboxId !== wanted) await this.deps.links.set(row.id, wanted);
221337
+ }
221338
+ for (const owner of owners) if (!rows.some((row) => row.id === owner)) this.deps.logger.warn("email-push: an integration with email-push cameras has no record to link the mailbox from", { meta: {
221339
+ integrationId: owner,
221340
+ brokerId
221341
+ } });
221342
+ return true;
221343
+ } catch (err) {
221344
+ this.deps.logger.warn("email-push: the camera mailbox links could not be written", { meta: {
221345
+ brokerId,
221346
+ error: errMsg(err)
221347
+ } });
221348
+ return false;
221349
+ }
221350
+ }
221031
221351
  /**
221032
221352
  * What the mailbox retains from BEFORE this subscription is old news (a restart of this addon
221033
221353
  * must not re-fire a quarter hour of alarms). Nothing for our recipients is accepted before the
@@ -221176,6 +221496,126 @@ var EmailPushBridge = class {
221176
221496
  function pickMailbox(list) {
221177
221497
  return list.find((b) => b.id === "smtp-inbound-default")?.id ?? list[0]?.id ?? null;
221178
221498
  }
221499
+ var reolinkConnectionsEntryKind = defineEntryKind("connections", {
221500
+ title: "Reolink integrations",
221501
+ schema: entryBody({
221502
+ host: string().nullish(),
221503
+ port: number().int().min(1).max(65535).nullish(),
221504
+ rtspPort: number().int().min(1).max(65535).nullish(),
221505
+ username: string().nullish(),
221506
+ password: string().optional().meta({ secret: true }),
221507
+ transport: _enum(["tcp", "udp"]).nullish(),
221508
+ uid: string().nullish(),
221509
+ debugGeneral: boolean().nullish(),
221510
+ debugSocketLogs: array(ReolinkSocketDebugFlagSchema).nullish(),
221511
+ mailboxId: mailboxLinkField()
221512
+ }),
221513
+ writeTrigger: "an operator adds, edits or removes a Reolink integration, or a Hub device is migrated into one"
221514
+ });
221515
+ /** Every kind this addon declares, keyed by its name. */
221516
+ var reolinkRecordKinds = { connections: reolinkConnectionsEntryKind };
221517
+ /** The record body as the connection form's flat values: no name, no unset keys. */
221518
+ function hubSettingsOf(body) {
221519
+ const out = {};
221520
+ for (const [key, value] of Object.entries(body)) {
221521
+ if (key === "name" || value === null || value === void 0) continue;
221522
+ out[key] = value;
221523
+ }
221524
+ return out;
221525
+ }
221526
+ /**
221527
+ * What a resolved record says about its hub. A keychain that is locked yields a record WITHOUT
221528
+ * its password: that is `password-locked`, never an empty password (D49).
221529
+ */
221530
+ function hubConnectionOf(resolved) {
221531
+ const read = readHubConnection(hubSettingsOf(resolved.body));
221532
+ return read.kind === "no-password" && resolved.secrets === "unavailable" ? { kind: "password-locked" } : read;
221533
+ }
221534
+ /**
221535
+ * What each enabled integration's RECORD says about its hub: the one reader of the connection.
221536
+ * A record that is absent reads as `no-host` (no session), exactly as an empty settings blob did.
221537
+ */
221538
+ async function readHubConnections(instances, integrations) {
221539
+ const out = [];
221540
+ for (const integration of integrations) {
221541
+ const resolved = await instances.readResolved(integration.id);
221542
+ out.push({
221543
+ id: integration.id,
221544
+ name: integration.name,
221545
+ read: resolved === null ? { kind: "no-host" } : hubConnectionOf(resolved)
221546
+ });
221547
+ }
221548
+ return out;
221549
+ }
221550
+ function buildReolinkInstances(records, deps) {
221551
+ return new RecordIntegrationInstances(records, reolinkConnectionsEntryKind, {
221552
+ description: {
221553
+ role: "devices",
221554
+ discovery: {
221555
+ mode: "lan",
221556
+ scopedToInstance: false
221557
+ },
221558
+ instanceMode: "multiple",
221559
+ kind: "connection",
221560
+ canTest: false
221561
+ },
221562
+ formSchema: () => buildHubInstanceSchema(),
221563
+ initialBody: (name) => ({ name }),
221564
+ configured: (body) => (body.host ?? "").length === 0 || (body.password ?? "").length > 0,
221565
+ onChanged: () => deps.onChanged()
221566
+ });
221567
+ }
221568
+ /**
221569
+ * The provider handed to the hub: the default integration (no connection) shows no hub form, an
221570
+ * NVR / Home Hub one does, and a create wizard (no id yet) sets up a hub.
221571
+ */
221572
+ function reolinkInstancesProvider(instances, deps) {
221573
+ return {
221574
+ ...instances.toProvider(),
221575
+ instanceFormSchema: async ({ id }) => {
221576
+ if (id === null) return buildHubInstanceSchema();
221577
+ const [evidence, body] = await Promise.all([deps.registryEvidenceOf(id), instances.getResolved(id)]);
221578
+ return evidence !== null && isHubIntegration({
221579
+ originStableId: evidence.originStableId,
221580
+ info: evidence.info,
221581
+ settings: body === null ? {} : hubSettingsOf(body)
221582
+ }) || body === null ? buildHubInstanceSchema() : { sections: [] };
221583
+ }
221584
+ };
221585
+ }
221586
+ /**
221587
+ * Whether an integration IS one NVR / Home Hub (its devices come from the hub, so there is no
221588
+ * manual add by IP). An integration the registry cannot name is not a hub for this question.
221589
+ */
221590
+ async function integrationIsHub(instances, deps, id) {
221591
+ const [evidence, body] = await Promise.all([deps.registryEvidenceOf(id), instances.getResolved(id)]);
221592
+ if (evidence === null) return false;
221593
+ return isHubIntegration({
221594
+ originStableId: evidence.originStableId,
221595
+ info: evidence.info,
221596
+ settings: body === null ? {} : hubSettingsOf(body)
221597
+ });
221598
+ }
221599
+ //#endregion
221600
+ //#region src/mailbox-link-store.ts
221601
+ var INTEGRATIONS_MAX = 1e3;
221602
+ function mailboxLinkStoreOver(records) {
221603
+ const handle = records.kind(reolinkConnectionsEntryKind);
221604
+ return {
221605
+ list: async () => {
221606
+ return (await handle.query({ limit: INTEGRATIONS_MAX })).records.map((row) => {
221607
+ const linked = row.data[MAILBOX_LINK_FIELD];
221608
+ return {
221609
+ id: row.id,
221610
+ mailboxId: typeof linked === "string" ? linked : ""
221611
+ };
221612
+ });
221613
+ },
221614
+ set: async (integrationId, mailboxId) => {
221615
+ await handle.patch(integrationId, { [MAILBOX_LINK_FIELD]: mailboxId === "" ? null : mailboxId });
221616
+ }
221617
+ };
221618
+ }
221179
221619
  //#endregion
221180
221620
  //#region src/email-push-removal-hook.ts
221181
221621
  /**
@@ -221602,105 +222042,6 @@ async function moveEmailPushToMailbox(ports) {
221602
222042
  summary: { moved: true }
221603
222043
  };
221604
222044
  }
221605
- var reolinkConnectionsEntryKind = defineEntryKind("connections", {
221606
- title: "Reolink integrations",
221607
- schema: entryBody({
221608
- host: string().nullish(),
221609
- port: number().int().min(1).max(65535).nullish(),
221610
- rtspPort: number().int().min(1).max(65535).nullish(),
221611
- username: string().nullish(),
221612
- password: string().optional().meta({ secret: true }),
221613
- transport: _enum(["tcp", "udp"]).nullish(),
221614
- uid: string().nullish(),
221615
- debugGeneral: boolean().nullish(),
221616
- debugSocketLogs: array(ReolinkSocketDebugFlagSchema).nullish()
221617
- }),
221618
- writeTrigger: "an operator adds, edits or removes a Reolink integration, or a Hub device is migrated into one"
221619
- });
221620
- /** Every kind this addon declares, keyed by its name. */
221621
- var reolinkRecordKinds = { connections: reolinkConnectionsEntryKind };
221622
- /** The record body as the connection form's flat values: no name, no unset keys. */
221623
- function hubSettingsOf(body) {
221624
- const out = {};
221625
- for (const [key, value] of Object.entries(body)) {
221626
- if (key === "name" || value === null || value === void 0) continue;
221627
- out[key] = value;
221628
- }
221629
- return out;
221630
- }
221631
- /**
221632
- * What a resolved record says about its hub. A keychain that is locked yields a record WITHOUT
221633
- * its password: that is `password-locked`, never an empty password (D49).
221634
- */
221635
- function hubConnectionOf(resolved) {
221636
- const read = readHubConnection(hubSettingsOf(resolved.body));
221637
- return read.kind === "no-password" && resolved.secrets === "unavailable" ? { kind: "password-locked" } : read;
221638
- }
221639
- /**
221640
- * What each enabled integration's RECORD says about its hub: the one reader of the connection.
221641
- * A record that is absent reads as `no-host` (no session), exactly as an empty settings blob did.
221642
- */
221643
- async function readHubConnections(instances, integrations) {
221644
- const out = [];
221645
- for (const integration of integrations) {
221646
- const resolved = await instances.readResolved(integration.id);
221647
- out.push({
221648
- id: integration.id,
221649
- name: integration.name,
221650
- read: resolved === null ? { kind: "no-host" } : hubConnectionOf(resolved)
221651
- });
221652
- }
221653
- return out;
221654
- }
221655
- function buildReolinkInstances(records, deps) {
221656
- return new RecordIntegrationInstances(records, reolinkConnectionsEntryKind, {
221657
- description: {
221658
- role: "devices",
221659
- discovery: {
221660
- mode: "lan",
221661
- scopedToInstance: false
221662
- },
221663
- instanceMode: "multiple",
221664
- kind: "connection",
221665
- canTest: false
221666
- },
221667
- formSchema: () => buildHubInstanceSchema(),
221668
- initialBody: (name) => ({ name }),
221669
- configured: (body) => (body.host ?? "").length === 0 || (body.password ?? "").length > 0,
221670
- onChanged: () => deps.onChanged()
221671
- });
221672
- }
221673
- /**
221674
- * The provider handed to the hub: the default integration (no connection) shows no hub form, an
221675
- * NVR / Home Hub one does, and a create wizard (no id yet) sets up a hub.
221676
- */
221677
- function reolinkInstancesProvider(instances, deps) {
221678
- return {
221679
- ...instances.toProvider(),
221680
- instanceFormSchema: async ({ id }) => {
221681
- if (id === null) return buildHubInstanceSchema();
221682
- const [evidence, body] = await Promise.all([deps.registryEvidenceOf(id), instances.getResolved(id)]);
221683
- return evidence !== null && isHubIntegration({
221684
- originStableId: evidence.originStableId,
221685
- info: evidence.info,
221686
- settings: body === null ? {} : hubSettingsOf(body)
221687
- }) || body === null ? buildHubInstanceSchema() : { sections: [] };
221688
- }
221689
- };
221690
- }
221691
- /**
221692
- * Whether an integration IS one NVR / Home Hub (its devices come from the hub, so there is no
221693
- * manual add by IP). An integration the registry cannot name is not a hub for this question.
221694
- */
221695
- async function integrationIsHub(instances, deps, id) {
221696
- const [evidence, body] = await Promise.all([deps.registryEvidenceOf(id), instances.getResolved(id)]);
221697
- if (evidence === null) return false;
221698
- return isHubIntegration({
221699
- originStableId: evidence.originStableId,
221700
- info: evidence.info,
221701
- settings: body === null ? {} : hubSettingsOf(body)
221702
- });
221703
- }
221704
222045
  //#endregion
221705
222046
  //#region src/migrations/integration-rows-to-record.ts
221706
222047
  /**
@@ -222577,10 +222918,16 @@ var ReolinkProviderAddon = class extends BaseDeviceProvider {
222577
222918
  await this.mailboxPendingState.set(null);
222578
222919
  await this.mailboxPendingPasswordState.set("");
222579
222920
  }
222921
+ requireRecords() {
222922
+ const records = this.ctx.records;
222923
+ if (records === void 0) throw new Error("provider-reolink: ctx.records is required (hub-only addon)");
222924
+ return records;
222925
+ }
222580
222926
  /** The camera mailbox bridge, built once. */
222581
222927
  ensureEmailBridge() {
222582
222928
  this.emailBridge ??= new EmailPushBridge({
222583
222929
  port: createBrokerPort(this.ctx.api),
222930
+ links: mailboxLinkStoreOver(this.requireRecords()),
222584
222931
  listCameras: () => this.listReolinkCameras(),
222585
222932
  logger: this.ctx.logger.child("email-push"),
222586
222933
  pending: {
@@ -222746,8 +223093,9 @@ var ReolinkProviderAddon = class extends BaseDeviceProvider {
222746
223093
  if (typeof addonId === "string" && addonId !== this.ctx.id) return;
222747
223094
  this.reconcileIntegrations();
222748
223095
  };
222749
- this.ctx.eventBus.subscribe({ category: EventCategory.IntegrationEnabled }, handler);
222750
- this.ctx.eventBus.subscribe({ category: EventCategory.IntegrationDisabled }, handler);
223096
+ this.instances?.onSwitched(() => {
223097
+ this.reconcileIntegrations();
223098
+ });
222751
223099
  this.ctx.eventBus.subscribe({ category: EventCategory.IntegrationDeleted }, handler);
222752
223100
  }
222753
223101
  /** The hub box follows its integration's socket. */
@@ -222991,6 +223339,10 @@ var ReolinkProviderAddon = class extends BaseDeviceProvider {
222991
223339
  });
222992
223340
  this.instances = instances;
222993
223341
  this.hubIntegrationProbe = (id) => integrationIsHub(instances, { registryEvidenceOf }, id);
223342
+ this.declareRegistrySwitch({
223343
+ kind: reolinkConnectionsEntryKind,
223344
+ initialBody: (name) => ({ name })
223345
+ });
222994
223346
  await this.runMigrations([...defineAddonMigrations(REOLINK_MIGRATIONS, this.migrationPorts()), ...defineAddonMigrations(REOLINK_INTEGRATION_MIGRATIONS, integrationPorts)]);
222995
223347
  this.wireEmailBridge();
222996
223348
  const wireSleepPushResolvers = (event, via) => {