@camstack/addon-provider-enpal 0.1.11 → 0.1.12

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
@@ -5980,7 +5980,7 @@ var ZodIssueCode = {
5980
5980
  var ZodFirstPartyTypeKind;
5981
5981
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
5982
5982
  //#endregion
5983
- //#region ../types/dist/sleep-BX_MqzUe.mjs
5983
+ //#region ../types/dist/sleep-CmjWurK5.mjs
5984
5984
  /**
5985
5985
  * The audio chunk plane's byte format, and the ONE expansion from a coded
5986
5986
  * window to float samples (D455).
@@ -6664,137 +6664,153 @@ async function runAddonMigrations(host, migrations, logger, options = {}) {
6664
6664
  blockOwner
6665
6665
  };
6666
6666
  }
6667
- /**
6668
- * Build a {@link DurableState} over a single store key. Transport-agnostic:
6669
- * `read`/`write` are the addon-store or device-store accessors. The whole
6670
- * validated value round-trips on every read/write — the schema is the
6671
- * single source of truth for what is persisted, so no hand-listed field
6672
- * set can drop a key on save.
6673
- */
6674
- function createDurableState(deps) {
6675
- const get = async () => {
6676
- const raw = (await deps.read())[deps.key];
6677
- if (raw === void 0) return deps.fallback;
6678
- const parsed = deps.schema.safeParse(raw);
6679
- if (!parsed.success) {
6680
- deps.onParseError?.(deps.key, parsed.error);
6681
- return deps.fallback;
6682
- }
6683
- return parsed.data;
6684
- };
6685
- const set = async (next) => {
6686
- const validated = deps.schema.parse(next);
6687
- await deps.write({ [deps.key]: validated });
6688
- };
6689
- const update = async (fn) => {
6690
- await set(fn(await get()));
6691
- };
6667
+ function secretsOverMigrationApi(api) {
6692
6668
  return {
6693
- get,
6694
- set,
6695
- update
6669
+ resolve: async (refs) => {
6670
+ const { values } = await api.secrets.resolve({ refs: [...refs] });
6671
+ const out = {};
6672
+ for (const ref of refs) {
6673
+ const value = values[ref];
6674
+ out[ref] = value === null || value === void 0 ? { kind: "missing" } : {
6675
+ kind: "value",
6676
+ value,
6677
+ version: 0
6678
+ };
6679
+ }
6680
+ return out;
6681
+ },
6682
+ delete: async (refs) => (await api.secrets.delete({ refs: [...refs] })).deleted
6696
6683
  };
6697
6684
  }
6698
- /**
6699
- * Per-node scoping for the shared addon-settings blob.
6700
- *
6701
- * An addon's settings store is hub-central (the `addon-settings` cap is
6702
- * hub-routed — the hub instance answers for every node), so fields whose
6703
- * value is a NODE fact (decoder backend, engine pick, probed hardware
6704
- * capabilities) persist under the node-scoped key `<key>@<nodeId>` inside
6705
- * the single shared blob. The SCHEMA field key stays bare: the write path
6706
- * ({@link scopePatch}) maps the bare field onto the target node's scoped
6707
- * key; the read/hydrate path ({@link projectStore}) maps THIS node's value
6708
- * back, so UI forms and `resolveConfig` only ever see the bare key.
6709
- *
6710
- * Fields opt in via the `perNode: true` schema marker on `ConfigFieldBase`
6711
- * (`interfaces/config-ui.ts`); `BaseAddon` derives the key set from the
6712
- * schema and routes reads/writes through these helpers.
6713
- *
6714
- * ## No bare-key fallback — deliberate
6715
- *
6716
- * {@link readNodeValue} reads the node-scoped key ONLY. A node with no
6717
- * scoped key resolves to `undefined` so the field's schema `default` wins —
6718
- * NEVER `store[base]` and never another node's value. A bare legacy key in
6719
- * the store is invisible to every node, hub included, so one node's
6720
- * selection can never leak onto another. (This generalizes the
6721
- * `decoder-backend-keys.ts` semantics — the no-fallback variant — over an
6722
- * arbitrary set of per-node field keys.)
6723
- *
6724
- * Pure functions only — no I/O, no imports beyond the language. This is a
6725
- * LEAF module: import it via its deep path, never from the root barrel.
6726
- */
6727
- /**
6728
- * Normalize a raw kernel node id to the bare node id used for scoping.
6729
- * `localNodeId` can carry a `<node>/<addon>` suffix on forked child
6730
- * processes; per-node settings are per-NODE, so strip the addon segment.
6731
- * `undefined` / `null` / empty falls back to `'hub'`.
6732
- */
6733
- function normalizeNodeId(raw) {
6734
- if (raw === void 0 || raw === null || raw === "") return "hub";
6735
- const slashIdx = raw.indexOf("/");
6736
- if (slashIdx < 0) return raw;
6737
- const bare = raw.slice(0, slashIdx);
6738
- return bare === "" ? "hub" : bare;
6685
+ /** The record calls the one-switch migration makes, over the migration API. */
6686
+ function switchRecordsOverMigrationApi(api) {
6687
+ return { kind: (definition) => {
6688
+ const handle = api.records.kind(definition);
6689
+ return {
6690
+ get: (id) => handle.get({ id }),
6691
+ put: (input, opts) => handle.put({
6692
+ ...input,
6693
+ ...opts?.ifRev === void 0 ? {} : { ifRev: opts.ifRev }
6694
+ }),
6695
+ patch: (id, partial) => handle.patch({
6696
+ id,
6697
+ partial
6698
+ })
6699
+ };
6700
+ } };
6739
6701
  }
6740
- /** The node-scoped store key for a per-node field: `<base>@<nodeId>`. */
6741
- function nodeScopedKey(base, nodeId) {
6742
- return `${base}@${normalizeNodeId(nodeId)}`;
6702
+ /** `ctx.records` as the migration API offers it: bind a kind, read and write by id. */
6703
+ function recordsOverMigrationApi(api) {
6704
+ return { kind: (definition) => {
6705
+ const handle = api.records.kind(definition);
6706
+ return {
6707
+ get: (id) => handle.get({ id }),
6708
+ getResolved: (id) => handle.getResolved({ id }),
6709
+ put: (input, opts) => handle.put({
6710
+ ...input,
6711
+ ...opts?.ifRev === void 0 ? {} : { ifRev: opts.ifRev }
6712
+ }),
6713
+ delete: (id) => handle.delete({ id })
6714
+ };
6715
+ } };
6743
6716
  }
6744
- /**
6745
- * Read a node's value for a per-node field from the raw shared store:
6746
- * the node-scoped key when present, otherwise `undefined`.
6747
- * Deliberately NO bare-key fallback (see module doc) — the caller lets the
6748
- * schema `default` win on `undefined`.
6749
- */
6750
- function readNodeValue(store, base, nodeId) {
6751
- return store[nodeScopedKey(base, nodeId)];
6717
+ function integrationRowsApiOver(api) {
6718
+ return {
6719
+ list: async () => (await api.integrations.list({})).integrations,
6720
+ readLegacyIntegrationRows: (input) => api.legacyRows.read(input),
6721
+ clearLegacyIntegrationRows: (input) => api.legacyRows.clear(input)
6722
+ };
6752
6723
  }
6753
6724
  /**
6754
- * Re-map a UI/settings patch so every bare perNode field persists under the
6755
- * TARGET node's scoped key; all other keys pass through unchanged. Used on
6756
- * the write path so a save for one node never clobbers another node's value
6757
- * (and the bare key is never written). Returns a new object — the input
6758
- * patch is not mutated.
6725
+ * One serial lane per migration API: a log line is delivered after the line before it, so the
6726
+ * order the steps wrote them in is the order the hub reads them in. A delivery that fails
6727
+ * is reported once through the same door; if that fails too nothing is left to tell, and the
6728
+ * line is dropped rather than thrown into a migration step or left as an unhandled rejection.
6759
6729
  */
6760
- function scopePatch(patch, perNodeKeys, nodeId) {
6761
- const out = {};
6762
- for (const [key, value] of Object.entries(patch)) out[perNodeKeys.has(key) ? nodeScopedKey(key, nodeId) : key] = value;
6763
- return out;
6730
+ var lanes = /* @__PURE__ */ new WeakMap();
6731
+ function deliver(api, send) {
6732
+ const next = (lanes.get(api) ?? Promise.resolve()).then(send).then(() => void 0).catch(async (error) => {
6733
+ const reason = error instanceof Error ? error.message : String(error);
6734
+ await api.log.warn({ message: `a migration log line could not be delivered: ${reason}` }).catch(() => void 0);
6735
+ });
6736
+ lanes.set(api, next);
6737
+ return next;
6764
6738
  }
6765
- /**
6766
- * Project the raw shared store onto the bare schema keys for ONE node so a
6767
- * UI schema (whose field keys are bare) hydrates from that node's own
6768
- * values:
6769
- *
6770
- * - EVERY `@`-scoped key (any node's) is dropped from the pass-through.
6771
- * - Every bare perNode key is dropped from the pass-through (a stray bare
6772
- * legacy key must never hydrate any node — no bare fallback).
6773
- * - THIS node's effective value ({@link readNodeValue}) is then laid onto
6774
- * each bare perNode key; when the node has no scoped key the bare key is
6775
- * left ABSENT so the field's schema `default` wins.
6776
- *
6777
- * Returns a new object — the input store is not mutated.
6778
- */
6779
- function projectStore(store, perNodeKeys, nodeId) {
6780
- const out = {};
6781
- for (const [key, value] of Object.entries(store)) {
6782
- if (key.includes("@")) continue;
6783
- if (perNodeKeys.has(key)) continue;
6784
- out[key] = value;
6739
+ function warnOver(api) {
6740
+ return (message) => deliver(api, () => api.log.warn({ message }));
6741
+ }
6742
+ /** What the rows-to-records move needs, over the migration API. */
6743
+ function rowsDepsOver(api) {
6744
+ return {
6745
+ api: integrationRowsApiOver(api),
6746
+ records: recordsOverMigrationApi(api),
6747
+ secrets: secretsOverMigrationApi(api),
6748
+ warn: warnOver(api)
6749
+ };
6750
+ }
6751
+ var PREFIX = "records/";
6752
+ /** The base of every records failure. `detail` is the human part of the message. */
6753
+ var RecordsError = class extends Error {
6754
+ code;
6755
+ detail;
6756
+ constructor(code, detail) {
6757
+ super(`${PREFIX}${code}: ${detail}`);
6758
+ this.name = "RecordsError";
6759
+ this.code = code;
6760
+ this.detail = detail;
6785
6761
  }
6786
- for (const base of perNodeKeys) {
6787
- const value = readNodeValue(store, base, nodeId);
6788
- if (value !== void 0) out[base] = value;
6762
+ };
6763
+ /** A write guarded by `ifRev` found another revision (or an existing row for `ifRev: 0`). */
6764
+ var RevConflictError = class extends RecordsError {
6765
+ constructor(detail) {
6766
+ super("rev-conflict", detail);
6767
+ this.name = "RevConflictError";
6789
6768
  }
6790
- return out;
6769
+ };
6770
+ /** The keychain could not store or serve a value: explicit, never an empty string. */
6771
+ var RecordSecretUnavailableError = class extends RecordsError {
6772
+ constructor(detail) {
6773
+ super("secret-unavailable", detail);
6774
+ this.name = "RecordSecretUnavailableError";
6775
+ }
6776
+ };
6777
+ var InvalidRecordError = class extends RecordsError {
6778
+ constructor(detail) {
6779
+ super("invalid-record", detail);
6780
+ this.name = "InvalidRecordError";
6781
+ }
6782
+ };
6783
+ /** A kind declaration the engine refuses (non-additive change, bad shape, wrong file). */
6784
+ var DeclarationRefusedError = class extends RecordsError {
6785
+ constructor(detail) {
6786
+ super("declaration-refused", detail);
6787
+ this.name = "DeclarationRefusedError";
6788
+ }
6789
+ };
6790
+ function linkTargetOf(meta) {
6791
+ if (typeof meta !== "object" || meta === null) return void 0;
6792
+ const link = Reflect.get(meta, "link");
6793
+ const parsed = LinkTargetSchema.safeParse(link);
6794
+ return parsed.success ? parsed.data : void 0;
6795
+ }
6796
+ var LinkTargetSchema = object({
6797
+ cap: string().min(1),
6798
+ kind: string().min(1).optional()
6799
+ });
6800
+ /** The links a kind declares, read from the meta of its body fields. */
6801
+ function linksOfKind(kind) {
6802
+ const schema = kind.schema;
6803
+ if (!(schema instanceof ZodObject)) return [];
6804
+ const links = [];
6805
+ for (const [field, fieldSchema] of Object.entries(schema.shape)) {
6806
+ const to = linkTargetOf(globalRegistry.get(fieldSchema));
6807
+ if (to !== void 0) links.push({
6808
+ field,
6809
+ to
6810
+ });
6811
+ }
6812
+ return links;
6791
6813
  }
6792
- /** Every scope, in the order the guard and the docs list them. */
6793
- var SCOPED_SETTINGS_SCOPES = [
6794
- "cluster",
6795
- "device-defaults",
6796
- "node"
6797
- ];
6798
6814
  /**
6799
6815
  * The address of one keychain value: `secret://<owner>/<scope>/<fieldPath>`.
6800
6816
  *
@@ -6929,6 +6945,652 @@ function parseSecretRef(ref) {
6929
6945
  fieldPath
6930
6946
  };
6931
6947
  }
6948
+ /** Limits and names of `ctx.records` (D881). One authority; the engine and the facade read it. */
6949
+ /** The files a kind may live in. `history` is device-history's (D850), never records. */
6950
+ var RECORD_DATABASES = ["settings", "events"];
6951
+ /** The classes of a kind: the `@durable` vocabulary, one authority (replaces the annotation). */
6952
+ var RECORD_CLASSES = [
6953
+ "config",
6954
+ "ledger",
6955
+ "audit",
6956
+ "mirror",
6957
+ "ephemeral"
6958
+ ];
6959
+ var RECORD_DEFAULT_MAX_DATA_BYTES = 64 * 1024;
6960
+ var RECORD_MAX_DATA_BYTES = 1024 * 1024;
6961
+ var RECORD_BATCH_MAX = 1e3;
6962
+ var RECORD_QUERY_MAX = 1e3;
6963
+ /** A kind in the `settings` file may not bound itself above this (D447: high volume is `events`). */
6964
+ var RECORD_SETTINGS_MAX_ROWS = 5e4;
6965
+ /** The `Column`-free proof prefix: a ref collection for a kind's secret fields. */
6966
+ var RECORD_SECRET_COLLECTION_PREFIX = "records:";
6967
+ /**
6968
+ * Secret fields of a record, addressed the way a Zod schema declares them
6969
+ * (`collectZodSecretPaths`): dotted keys, `[]` for "each element of this array"
6970
+ * (`auth.accessToken`, `headers[].value`).
6971
+ *
6972
+ * `{}` after a key means "each value of this map" (`applianceSecrets{}`): the map's own key
6973
+ * names the value (`applianceSecrets{fridge}`), so no id key is declared and a body that drops a
6974
+ * key releases exactly that key's secret.
6975
+ *
6976
+ * Array elements are matched by a DECLARED id key (`secretArrayKeys`:
6977
+ * `{ headers: 'name' }`), never by index, so reordering a list keeps every
6978
+ * keychain ref (the same rule as `arrayItemFieldPath`). The concrete path of a
6979
+ * leaf names its element: `headers[X-Api].value`.
6980
+ *
6981
+ * Pure and browser-safe. Nothing here mutates: every transform returns a new value.
6982
+ */
6983
+ /** The array prefixes (declared form, e.g. `headers` or `a.headers`) of a path. */
6984
+ function parseSecretPath(path) {
6985
+ if (path.length === 0) throw new InvalidRecordError("an empty secret path");
6986
+ return path.split(".").map((raw) => {
6987
+ const each = raw.endsWith("[]");
6988
+ const map = raw.endsWith("{}");
6989
+ const key = each || map ? raw.slice(0, -2) : raw;
6990
+ if (key.length === 0) throw new InvalidRecordError(`secret path "${path}" has an empty segment`);
6991
+ return {
6992
+ key,
6993
+ each,
6994
+ map
6995
+ };
6996
+ });
6997
+ }
6998
+ /** The declared array prefixes of `path` that need an id key (`headers`, `a.rows`). */
6999
+ function secretArrayPrefixes(path) {
7000
+ const segments = parseSecretPath(path);
7001
+ const prefixes = [];
7002
+ const walked = [];
7003
+ for (const segment of segments) {
7004
+ walked.push(segment.key);
7005
+ if (segment.each) prefixes.push(walked.join("."));
7006
+ }
7007
+ return prefixes;
7008
+ }
7009
+ function isRecord$6(value) {
7010
+ return typeof value === "object" && value !== null && !Array.isArray(value);
7011
+ }
7012
+ function elementId(element, idKey, declared, prefix) {
7013
+ const id = isRecord$6(element) ? element[idKey] : void 0;
7014
+ 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`);
7015
+ return id;
7016
+ }
7017
+ /**
7018
+ * Visit every secret leaf PRESENT in `data` (an absent branch has nothing to
7019
+ * visit). `replace` returns the new leaf value, or {@link REMOVE_LEAF}; the
7020
+ * result is a new body, `data` is untouched.
7021
+ */
7022
+ var REMOVE_LEAF = Symbol("remove-leaf");
7023
+ function mapAt(node, segments, index, walkedKeys, concretePrefix, declared, arrayKeys, visit) {
7024
+ if (!isRecord$6(node)) return node;
7025
+ const segment = segments[index];
7026
+ if (segment === void 0) return node;
7027
+ if (!Object.prototype.hasOwnProperty.call(node, segment.key)) return node;
7028
+ const child = node[segment.key];
7029
+ const keys = [...walkedKeys, segment.key];
7030
+ const last = index === segments.length - 1;
7031
+ if (segment.each) {
7032
+ if (!Array.isArray(child)) return node;
7033
+ const prefix = keys.join(".");
7034
+ const idKey = arrayKeys[prefix];
7035
+ if (idKey === void 0) throw new InvalidRecordError(`"${declared}": no id key declared for the array "${prefix}"`);
7036
+ const mapped = child.map((element) => {
7037
+ const id = elementId(element, idKey, declared, prefix);
7038
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}[${encodeURIComponent(id)}]`;
7039
+ return last ? element : mapAt(element, segments, index + 1, keys, concrete, declared, arrayKeys, visit);
7040
+ });
7041
+ return {
7042
+ ...node,
7043
+ [segment.key]: mapped
7044
+ };
7045
+ }
7046
+ if (segment.map) {
7047
+ if (!isRecord$6(child)) return node;
7048
+ const kept = Object.entries(child).map(([mapKey, value]) => {
7049
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}{${encodeURIComponent(mapKey)}}`;
7050
+ if (!last) return [mapKey, mapAt(value, segments, index + 1, keys, concrete, declared, arrayKeys, visit)];
7051
+ return [mapKey, visit({
7052
+ declared,
7053
+ concrete,
7054
+ value
7055
+ })];
7056
+ }).filter(([, value]) => value !== REMOVE_LEAF);
7057
+ return {
7058
+ ...node,
7059
+ [segment.key]: Object.fromEntries(kept)
7060
+ };
7061
+ }
7062
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}`;
7063
+ if (last) {
7064
+ const replacement = visit({
7065
+ declared,
7066
+ concrete,
7067
+ value: child
7068
+ });
7069
+ if (replacement === REMOVE_LEAF) return Object.fromEntries(Object.entries(node).filter(([key]) => key !== segment.key));
7070
+ return {
7071
+ ...node,
7072
+ [segment.key]: replacement
7073
+ };
7074
+ }
7075
+ return {
7076
+ ...node,
7077
+ [segment.key]: mapAt(child, segments, index + 1, keys, concrete, declared, arrayKeys, visit)
7078
+ };
7079
+ }
7080
+ /** Replace/remove every present secret leaf; returns a NEW body. */
7081
+ function mapSecretLeaves(data, paths, arrayKeys, visit) {
7082
+ let current = data;
7083
+ for (const declared of paths) current = mapAt(current, parseSecretPath(declared), 0, [], "", declared, arrayKeys, visit);
7084
+ return current;
7085
+ }
7086
+ /** Every present secret leaf, read-only. */
7087
+ function collectSecretLeaves(data, paths, arrayKeys) {
7088
+ const found = [];
7089
+ mapSecretLeaves(data, paths, arrayKeys, (leaf) => {
7090
+ found.push(leaf);
7091
+ return leaf.value;
7092
+ });
7093
+ return found;
7094
+ }
7095
+ /**
7096
+ * The keychain collection name a kind's secrets live under. Prefixed so a
7097
+ * record's refs never collide with the refs a legacy collection of the same name
7098
+ * already holds during an adoption.
7099
+ */
7100
+ function recordSecretCollection(kind) {
7101
+ return `${RECORD_SECRET_COLLECTION_PREFIX}${kind}`;
7102
+ }
7103
+ /** The ONE ref a row's secret field may carry: the engine and the facade both build it here. */
7104
+ function recordSecretRef(owner, kind, rowId, concretePath) {
7105
+ return buildSecretRef({
7106
+ owner,
7107
+ scope: {
7108
+ kind: "row",
7109
+ collection: recordSecretCollection(kind),
7110
+ rowId
7111
+ },
7112
+ fieldPath: concretePath
7113
+ });
7114
+ }
7115
+ /**
7116
+ * A stored secret, as an admin read shows it: a VIEW naming the row's own
7117
+ * keychain ref (`set: true`), never the value and no longer the bare redaction
7118
+ * token. The form hands it to the secret field, which reveals the value by ref
7119
+ * through the audited `keychain-admin.reveal`; sent back untouched it keeps the
7120
+ * stored secret (the records door reads a view as KEEP).
7121
+ *
7122
+ * ONE implementation for the entries service and for every addon that serves
7123
+ * its own instances (`RecordIntegrationInstances`).
7124
+ */
7125
+ function isRecord$5(value) {
7126
+ return typeof value === "object" && value !== null && !Array.isArray(value);
7127
+ }
7128
+ function secretViewsOf(owner, kind, id, decl, data) {
7129
+ if (decl.secretPaths.length === 0) return data;
7130
+ const shown = mapSecretLeaves(data, decl.secretPaths, decl.secretArrayKeys, (leaf) => {
7131
+ if (leaf.value !== "__camstack_redacted__") return leaf.value;
7132
+ return {
7133
+ $secret: recordSecretRef(owner, kind, id, leaf.concrete),
7134
+ v: 1,
7135
+ set: true
7136
+ };
7137
+ });
7138
+ return isRecord$5(shown) ? shown : data;
7139
+ }
7140
+ /** The most instances one addon lists (an integrations page, not a table). */
7141
+ var INSTANCES_LIST_MAX = 1e3;
7142
+ /**
7143
+ * The ONE reader of an instance's switch (D996): an absent field means on, so a row written
7144
+ * before the field existed needs no migration. Every consumer of an instance body asks this.
7145
+ */
7146
+ function isInstanceEnabled(body) {
7147
+ return body.enabled !== false;
7148
+ }
7149
+ /** The body key of the switch; only {@link RecordIntegrationInstances.setInstanceEnabled} writes it. */
7150
+ var SWITCH_KEY = "enabled";
7151
+ /** The keys of the kind's secret fields that sit at the top level of the body. */
7152
+ function topLevelSecretKeys(paths) {
7153
+ return new Set(paths.filter((p) => !p.includes(".") && !p.includes("[") && !p.includes("{")));
7154
+ }
7155
+ /** The keys of the kind's top-level MAPS whose values are secrets (`applianceSecrets{}`). */
7156
+ function secretMapKeys(paths) {
7157
+ return new Set(paths.filter((p) => p.endsWith("{}") && !p.slice(0, -2).match(/[.[{]/)).map((p) => p.slice(0, -2)));
7158
+ }
7159
+ /**
7160
+ * A patch value for a map of secrets: an entry that is omitted, `''`, the redaction token or the
7161
+ * view the form was given KEEPS its stored secret (it is left out of the merge); `{ $secretClear }`
7162
+ * or `null` removes the entry; any other string replaces it. Null when nothing is left to merge.
7163
+ */
7164
+ function secretMapPatch(value) {
7165
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
7166
+ const out = {};
7167
+ for (const [key, entry] of Object.entries(value)) if (entry === null || isSecretClear(entry)) out[key] = null;
7168
+ else if (typeof entry === "string" && entry !== "" && entry !== "__camstack_redacted__" && !isSecretFieldView(entry)) out[key] = entry;
7169
+ return Object.keys(out).length > 0 ? out : null;
7170
+ }
7171
+ var RecordIntegrationInstances = class {
7172
+ records;
7173
+ kind;
7174
+ hooks;
7175
+ handle;
7176
+ secretKeys;
7177
+ secretMaps;
7178
+ nameField;
7179
+ switchListeners = /* @__PURE__ */ new Set();
7180
+ constructor(records, kind, hooks) {
7181
+ this.records = records;
7182
+ this.kind = kind;
7183
+ this.hooks = hooks;
7184
+ this.handle = records.kind(kind);
7185
+ this.secretKeys = topLevelSecretKeys(kind.declaration.secretPaths);
7186
+ this.secretMaps = secretMapKeys(kind.declaration.secretPaths);
7187
+ this.nameField = kind.declaration.entry?.nameField ?? "name";
7188
+ }
7189
+ /**
7190
+ * One instance read for the addon's own runtime; null when absent. When the keychain is
7191
+ * locked the row is served WITHOUT its secrets and says so (`secrets: 'unavailable'`), so the
7192
+ * caller can keep what it had instead of reconfiguring with an empty secret (D49).
7193
+ */
7194
+ async readResolved(id) {
7195
+ try {
7196
+ const record = await this.handle.getResolved(id);
7197
+ return record === null ? null : {
7198
+ id,
7199
+ body: record.data,
7200
+ enabled: isInstanceEnabled(record.data),
7201
+ secrets: "resolved"
7202
+ };
7203
+ } catch (err) {
7204
+ if (!(err instanceof RecordSecretUnavailableError)) throw err;
7205
+ const stored = await this.handle.get(id);
7206
+ if (stored === null) return null;
7207
+ return {
7208
+ id,
7209
+ body: Object.fromEntries(Object.entries(stored.data).filter(([key]) => !this.secretKeys.has(key))),
7210
+ enabled: isInstanceEnabled(stored.data),
7211
+ secrets: "unavailable"
7212
+ };
7213
+ }
7214
+ }
7215
+ /** The body of {@link readResolved} alone; a locked keychain yields the row without secrets. */
7216
+ async getResolved(id) {
7217
+ return (await this.readResolved(id))?.body ?? null;
7218
+ }
7219
+ /** Every instance, secrets resolved where the keychain allows; an absent one is skipped. */
7220
+ async listResolved() {
7221
+ const page = await this.handle.query({ limit: INSTANCES_LIST_MAX });
7222
+ const out = [];
7223
+ for (const record of page.records) {
7224
+ const read = await this.readResolved(record.id);
7225
+ if (read !== null) out.push(read);
7226
+ }
7227
+ return out;
7228
+ }
7229
+ viewOf(record) {
7230
+ const shown = secretViewsOf(this.records.owner, this.kind.name, record.id, this.kind.declaration, record.data);
7231
+ const rawName = record.data[this.nameField];
7232
+ const kind = this.hooks.kindOf?.(record.data);
7233
+ const health = this.hooks.health?.(record.data, record.id);
7234
+ return {
7235
+ id: record.id,
7236
+ name: typeof rawName === "string" ? rawName : record.id,
7237
+ configured: this.hooks.configured(record.data),
7238
+ enabled: isInstanceEnabled(record.data),
7239
+ formValues: shown,
7240
+ ...kind !== void 0 ? { kind } : {},
7241
+ ...health?.status !== void 0 ? { status: health.status } : {},
7242
+ ...health?.lastCheckedAt !== void 0 ? { lastCheckedAt: health.lastCheckedAt } : {}
7243
+ };
7244
+ }
7245
+ describe = async () => {
7246
+ const declared = linksOfKind(this.kind);
7247
+ const links = this.hooks.description.links !== void 0 || declared.length === 0 ? {} : { links: declared.map((link) => ({
7248
+ kind: this.kind.name,
7249
+ field: link.field,
7250
+ to: link.to
7251
+ })) };
7252
+ return {
7253
+ ...this.hooks.description,
7254
+ ...links,
7255
+ ...this.hooks.mintId === void 0 ? {} : { mintsId: true }
7256
+ };
7257
+ };
7258
+ instanceFormSchema = async ({ id }) => this.hooks.formSchema(id);
7259
+ listInstances = async () => {
7260
+ return (await this.handle.query({ limit: INSTANCES_LIST_MAX })).records.map((record) => this.viewOf(record));
7261
+ };
7262
+ getInstance = async ({ id }) => {
7263
+ const record = await this.handle.get(id);
7264
+ return record === null ? null : this.viewOf(record);
7265
+ };
7266
+ /** Insert ONE row (`ifRev: 0`: an existing id is refused, never overwritten). */
7267
+ createInstance = async ({ id, name, kind, values }) => {
7268
+ const minted = id ?? this.hooks.mintId?.({
7269
+ name,
7270
+ ...kind !== void 0 ? { kind } : {}
7271
+ });
7272
+ if (minted === void 0) throw new Error("createInstance needs an id: this provider does not mint one");
7273
+ await this.handle.put({
7274
+ id: minted,
7275
+ data: this.hooks.initialBody(name, kind)
7276
+ }, { ifRev: 0 });
7277
+ const patch = this.patchOf(values ?? {});
7278
+ if (Object.keys(patch).length > 0) await this.handle.patch(minted, patch);
7279
+ await this.hooks.onChanged?.(minted, "created");
7280
+ return { id: minted };
7281
+ };
7282
+ updateInstance = async ({ id, name, values }) => {
7283
+ const patch = this.patchOf(values);
7284
+ if (name !== void 0) patch[this.nameField] = name;
7285
+ await this.handle.patch(id, patch);
7286
+ await this.hooks.onChanged?.(id, "updated");
7287
+ return { ok: true };
7288
+ };
7289
+ /** The record patch a form `values` object means: secrets kept, cleared or replaced. */
7290
+ patchOf(values) {
7291
+ const patch = {};
7292
+ for (const [key, value] of Object.entries(values)) {
7293
+ if (value === void 0) continue;
7294
+ if (key === "enabled") continue;
7295
+ if (this.secretMaps.has(key)) {
7296
+ const entries = secretMapPatch(value);
7297
+ if (entries !== null) patch[key] = entries;
7298
+ } else if (!this.secretKeys.has(key)) patch[key] = value;
7299
+ else if (isSecretClear(value)) patch[key] = null;
7300
+ else if (typeof value === "string" && value !== "" && value !== "__camstack_redacted__" && !isSecretFieldView(value)) patch[key] = value;
7301
+ }
7302
+ return patch;
7303
+ }
7304
+ /**
7305
+ * Listen to the switch of ANY instance of this helper (in the process that serves it). The
7306
+ * durable replacement of the `integration.enabled` / `integration.disabled` events (D8): the
7307
+ * addon reconciles from the record, whichever way it flipped.
7308
+ */
7309
+ onSwitched(listener) {
7310
+ this.switchListeners.add(listener);
7311
+ }
7312
+ /**
7313
+ * The ONE writer of the switch (D996, D1014): the record body's `enabled`, for every role. A
7314
+ * configured thing is an instance, so an id with no record yet (a default integration that was
7315
+ * never configured) gets its record from `initialBody` before the switch is written.
7316
+ */
7317
+ setInstanceEnabled = async ({ id, enabled }) => {
7318
+ if (await this.handle.get(id) === null) await this.handle.put({
7319
+ id,
7320
+ data: this.hooks.initialBody(id)
7321
+ }, { ifRev: 0 });
7322
+ await this.handle.patch(id, { [SWITCH_KEY]: enabled });
7323
+ await this.hooks.onChanged?.(id, "enabled");
7324
+ for (const listener of this.switchListeners) await listener(id, enabled);
7325
+ return { ok: true };
7326
+ };
7327
+ /** The row and its keychain refs go together (the records door). */
7328
+ deleteInstance = async ({ id }) => {
7329
+ await this.handle.delete(id);
7330
+ await this.hooks.onChanged?.(id, "deleted");
7331
+ return { ok: true };
7332
+ };
7333
+ testInstance = async (input) => {
7334
+ if (this.hooks.test === void 0) return {
7335
+ success: false,
7336
+ status: "unsupported",
7337
+ error: "This integration declares no connection test"
7338
+ };
7339
+ return this.hooks.test(input);
7340
+ };
7341
+ /** The flat provider object to hand to `registerProvider`. */
7342
+ toProvider() {
7343
+ return {
7344
+ describe: this.describe,
7345
+ instanceFormSchema: this.instanceFormSchema,
7346
+ listInstances: this.listInstances,
7347
+ getInstance: this.getInstance,
7348
+ createInstance: this.createInstance,
7349
+ updateInstance: this.updateInstance,
7350
+ setInstanceEnabled: this.setInstanceEnabled,
7351
+ deleteInstance: this.deleteInstance,
7352
+ testInstance: this.testInstance
7353
+ };
7354
+ }
7355
+ };
7356
+ /**
7357
+ * The one-switch migration (epic #440, step 3). An integration's on/off state used to live in the
7358
+ * registry's `enabled` column for a device addon; it now lives only in the instance record's
7359
+ * body (`enabled`, D1007 superseded). This moves a registry `enabled = false` into the body, once.
7360
+ *
7361
+ * For every registry row of the addon that is OFF:
7362
+ * - no record under its id: the record is created from `initialBody(name)` with `enabled: false`
7363
+ * (a default integration that never had settings, Reolink's among them);
7364
+ * - a record whose body states no `enabled`: `enabled: false` is written into it;
7365
+ * - a record that already states `enabled` (either way) is the newer truth and is left alone.
7366
+ * A row that is ON writes nothing: an absent field reads as on. A rerun finds every off row with
7367
+ * a stated switch and does nothing, so nothing switched off comes back on and nothing switched on
7368
+ * goes off. The registry column itself is neither read afterwards nor written; its drop is step 5.
7369
+ *
7370
+ * It runs in the addon process, BEFORE the addon registers its `integration-instances` provider,
7371
+ * which is also why `integrations.list` still answers the stored column at that point.
7372
+ */
7373
+ function registrySwitchToBodyId(addonId, date) {
7374
+ return `${addonId}/${date}-registry-switch-to-body`;
7375
+ }
7376
+ async function moveRegistrySwitchToBody(ports, spec) {
7377
+ const rows = await ports.listIntegrations(spec.addonId);
7378
+ let created = 0;
7379
+ let switched = 0;
7380
+ let kept = 0;
7381
+ for (const row of rows) {
7382
+ if (row.enabled) continue;
7383
+ const body = await ports.readBody(row.id);
7384
+ if (body === null) {
7385
+ if (await ports.createRecord(row.id, {
7386
+ ...spec.initialBody(row.name),
7387
+ ["enabled"]: false
7388
+ }) === "created") created += 1;
7389
+ else kept += 1;
7390
+ continue;
7391
+ }
7392
+ if ("enabled" in body) {
7393
+ kept += 1;
7394
+ continue;
7395
+ }
7396
+ await ports.switchOff(row.id);
7397
+ switched += 1;
7398
+ }
7399
+ const summary = {
7400
+ integrations: rows.length,
7401
+ off: rows.filter((r) => !r.enabled).length,
7402
+ created,
7403
+ switched,
7404
+ kept
7405
+ };
7406
+ return created === 0 && switched === 0 ? {
7407
+ outcome: "already-done",
7408
+ summary
7409
+ } : {
7410
+ outcome: "done",
7411
+ summary
7412
+ };
7413
+ }
7414
+ /** A migration entry: an addon states its kind and how a new body starts, nothing else. */
7415
+ function registrySwitchToBodyMigration(spec) {
7416
+ return {
7417
+ meta: {
7418
+ id: registrySwitchToBodyId(spec.addonId, spec.date),
7419
+ owner: spec.addonId,
7420
+ level: "addon-state",
7421
+ seq: spec.seq,
7422
+ dependsOn: [],
7423
+ store: "settings",
7424
+ scope: "cluster",
7425
+ onFailure: "block-owner",
7426
+ bodyKind: "procedure",
7427
+ description: "Move the registry enabled flag of every switched-off integration into its instance record body, creating the record when there is none",
7428
+ fixtureMark: "enabled"
7429
+ },
7430
+ procedure: (ports) => moveRegistrySwitchToBody(ports, {
7431
+ addonId: spec.addonId,
7432
+ initialBody: spec.initialBody
7433
+ })
7434
+ };
7435
+ }
7436
+ /** The hub and records sides of {@link registrySwitchToBodyMigration}. */
7437
+ function registrySwitchPortsOver(deps) {
7438
+ const handle = deps.records.kind({
7439
+ name: deps.kind.name,
7440
+ declaration: deps.kind.declaration,
7441
+ schema: record(string(), unknown())
7442
+ });
7443
+ return {
7444
+ listIntegrations: async (addonId) => (await deps.api.list()).filter((i) => i.addonId === addonId).map((i) => ({
7445
+ id: i.id,
7446
+ name: i.name,
7447
+ enabled: i.enabled !== false
7448
+ })),
7449
+ readBody: async (id) => (await handle.get(id))?.data ?? null,
7450
+ createRecord: async (id, body) => {
7451
+ if (await handle.get(id) !== null) return "exists";
7452
+ await handle.put({
7453
+ id,
7454
+ data: body
7455
+ }, { ifRev: 0 });
7456
+ return "created";
7457
+ },
7458
+ switchOff: async (id) => {
7459
+ await handle.patch(id, { [SWITCH_KEY]: false });
7460
+ }
7461
+ };
7462
+ }
7463
+ /**
7464
+ * Build a {@link DurableState} over a single store key. Transport-agnostic:
7465
+ * `read`/`write` are the addon-store or device-store accessors. The whole
7466
+ * validated value round-trips on every read/write — the schema is the
7467
+ * single source of truth for what is persisted, so no hand-listed field
7468
+ * set can drop a key on save.
7469
+ */
7470
+ function createDurableState(deps) {
7471
+ const get = async () => {
7472
+ const raw = (await deps.read())[deps.key];
7473
+ if (raw === void 0) return deps.fallback;
7474
+ const parsed = deps.schema.safeParse(raw);
7475
+ if (!parsed.success) {
7476
+ deps.onParseError?.(deps.key, parsed.error);
7477
+ return deps.fallback;
7478
+ }
7479
+ return parsed.data;
7480
+ };
7481
+ const set = async (next) => {
7482
+ const validated = deps.schema.parse(next);
7483
+ await deps.write({ [deps.key]: validated });
7484
+ };
7485
+ const update = async (fn) => {
7486
+ await set(fn(await get()));
7487
+ };
7488
+ return {
7489
+ get,
7490
+ set,
7491
+ update
7492
+ };
7493
+ }
7494
+ /**
7495
+ * Per-node scoping for the shared addon-settings blob.
7496
+ *
7497
+ * An addon's settings store is hub-central (the `addon-settings` cap is
7498
+ * hub-routed — the hub instance answers for every node), so fields whose
7499
+ * value is a NODE fact (decoder backend, engine pick, probed hardware
7500
+ * capabilities) persist under the node-scoped key `<key>@<nodeId>` inside
7501
+ * the single shared blob. The SCHEMA field key stays bare: the write path
7502
+ * ({@link scopePatch}) maps the bare field onto the target node's scoped
7503
+ * key; the read/hydrate path ({@link projectStore}) maps THIS node's value
7504
+ * back, so UI forms and `resolveConfig` only ever see the bare key.
7505
+ *
7506
+ * Fields opt in via the `perNode: true` schema marker on `ConfigFieldBase`
7507
+ * (`interfaces/config-ui.ts`); `BaseAddon` derives the key set from the
7508
+ * schema and routes reads/writes through these helpers.
7509
+ *
7510
+ * ## No bare-key fallback — deliberate
7511
+ *
7512
+ * {@link readNodeValue} reads the node-scoped key ONLY. A node with no
7513
+ * scoped key resolves to `undefined` so the field's schema `default` wins —
7514
+ * NEVER `store[base]` and never another node's value. A bare legacy key in
7515
+ * the store is invisible to every node, hub included, so one node's
7516
+ * selection can never leak onto another. (This generalizes the
7517
+ * `decoder-backend-keys.ts` semantics — the no-fallback variant — over an
7518
+ * arbitrary set of per-node field keys.)
7519
+ *
7520
+ * Pure functions only — no I/O, no imports beyond the language. This is a
7521
+ * LEAF module: import it via its deep path, never from the root barrel.
7522
+ */
7523
+ /**
7524
+ * Normalize a raw kernel node id to the bare node id used for scoping.
7525
+ * `localNodeId` can carry a `<node>/<addon>` suffix on forked child
7526
+ * processes; per-node settings are per-NODE, so strip the addon segment.
7527
+ * `undefined` / `null` / empty falls back to `'hub'`.
7528
+ */
7529
+ function normalizeNodeId(raw) {
7530
+ if (raw === void 0 || raw === null || raw === "") return "hub";
7531
+ const slashIdx = raw.indexOf("/");
7532
+ if (slashIdx < 0) return raw;
7533
+ const bare = raw.slice(0, slashIdx);
7534
+ return bare === "" ? "hub" : bare;
7535
+ }
7536
+ /** The node-scoped store key for a per-node field: `<base>@<nodeId>`. */
7537
+ function nodeScopedKey(base, nodeId) {
7538
+ return `${base}@${normalizeNodeId(nodeId)}`;
7539
+ }
7540
+ /**
7541
+ * Read a node's value for a per-node field from the raw shared store:
7542
+ * the node-scoped key when present, otherwise `undefined`.
7543
+ * Deliberately NO bare-key fallback (see module doc) — the caller lets the
7544
+ * schema `default` win on `undefined`.
7545
+ */
7546
+ function readNodeValue(store, base, nodeId) {
7547
+ return store[nodeScopedKey(base, nodeId)];
7548
+ }
7549
+ /**
7550
+ * Re-map a UI/settings patch so every bare perNode field persists under the
7551
+ * TARGET node's scoped key; all other keys pass through unchanged. Used on
7552
+ * the write path so a save for one node never clobbers another node's value
7553
+ * (and the bare key is never written). Returns a new object — the input
7554
+ * patch is not mutated.
7555
+ */
7556
+ function scopePatch(patch, perNodeKeys, nodeId) {
7557
+ const out = {};
7558
+ for (const [key, value] of Object.entries(patch)) out[perNodeKeys.has(key) ? nodeScopedKey(key, nodeId) : key] = value;
7559
+ return out;
7560
+ }
7561
+ /**
7562
+ * Project the raw shared store onto the bare schema keys for ONE node so a
7563
+ * UI schema (whose field keys are bare) hydrates from that node's own
7564
+ * values:
7565
+ *
7566
+ * - EVERY `@`-scoped key (any node's) is dropped from the pass-through.
7567
+ * - Every bare perNode key is dropped from the pass-through (a stray bare
7568
+ * legacy key must never hydrate any node — no bare fallback).
7569
+ * - THIS node's effective value ({@link readNodeValue}) is then laid onto
7570
+ * each bare perNode key; when the node has no scoped key the bare key is
7571
+ * left ABSENT so the field's schema `default` wins.
7572
+ *
7573
+ * Returns a new object — the input store is not mutated.
7574
+ */
7575
+ function projectStore(store, perNodeKeys, nodeId) {
7576
+ const out = {};
7577
+ for (const [key, value] of Object.entries(store)) {
7578
+ if (key.includes("@")) continue;
7579
+ if (perNodeKeys.has(key)) continue;
7580
+ out[key] = value;
7581
+ }
7582
+ for (const base of perNodeKeys) {
7583
+ const value = readNodeValue(store, base, nodeId);
7584
+ if (value !== void 0) out[base] = value;
7585
+ }
7586
+ return out;
7587
+ }
7588
+ /** Every scope, in the order the guard and the docs list them. */
7589
+ var SCOPED_SETTINGS_SCOPES = [
7590
+ "cluster",
7591
+ "device-defaults",
7592
+ "node"
7593
+ ];
6932
7594
  /** A write to a secret path could not be stored in the keychain, so it was refused. */
6933
7595
  var KeychainWriteRefusedError = class extends Error {
6934
7596
  fieldPath;
@@ -6939,7 +7601,7 @@ var KeychainWriteRefusedError = class extends Error {
6939
7601
  }
6940
7602
  };
6941
7603
  var KEEP = { kind: "keep" };
6942
- function isRecord$6(value) {
7604
+ function isRecord$4(value) {
6943
7605
  return typeof value === "object" && value !== null && !Array.isArray(value);
6944
7606
  }
6945
7607
  function defaultMintId() {
@@ -6952,7 +7614,7 @@ function collectSecretMarkerRefs(value, out = []) {
6952
7614
  return out;
6953
7615
  }
6954
7616
  if (Array.isArray(value)) for (const item of value) collectSecretMarkerRefs(item, out);
6955
- else if (isRecord$6(value)) for (const child of Object.values(value)) collectSecretMarkerRefs(child, out);
7617
+ else if (isRecord$4(value)) for (const child of Object.values(value)) collectSecretMarkerRefs(child, out);
6956
7618
  return out;
6957
7619
  }
6958
7620
  async function storedValueEquals(secrets, marker, candidate) {
@@ -7007,7 +7669,7 @@ function rowId(row, idKey) {
7007
7669
  return null;
7008
7670
  }
7009
7671
  async function writeArray(ctx, node, incoming, stored, fieldPath) {
7010
- const storedRows = Array.isArray(stored) ? stored.filter(isRecord$6) : [];
7672
+ const storedRows = Array.isArray(stored) ? stored.filter(isRecord$4) : [];
7011
7673
  if (!Array.isArray(incoming)) {
7012
7674
  ctx.deletes.push(...collectSecretMarkerRefs(storedRows));
7013
7675
  return {
@@ -7023,7 +7685,7 @@ async function writeArray(ctx, node, incoming, stored, fieldPath) {
7023
7685
  const kept = /* @__PURE__ */ new Set();
7024
7686
  const rows = [];
7025
7687
  for (const row of incoming) {
7026
- if (!isRecord$6(row)) {
7688
+ if (!isRecord$4(row)) {
7027
7689
  rows.push(row);
7028
7690
  continue;
7029
7691
  }
@@ -7048,7 +7710,7 @@ async function writeNode(ctx, node, incoming, stored, fieldPath) {
7048
7710
  case "leaf": return writeLeaf(ctx, incoming, stored, fieldPath);
7049
7711
  case "array": return writeArray(ctx, node, incoming, stored, fieldPath);
7050
7712
  case "object": {
7051
- if (!isRecord$6(incoming)) {
7713
+ if (!isRecord$4(incoming)) {
7052
7714
  if (incoming === void 0) return KEEP;
7053
7715
  ctx.deletes.push(...collectSecretMarkerRefs(stored));
7054
7716
  return {
@@ -7056,7 +7718,7 @@ async function writeNode(ctx, node, incoming, stored, fieldPath) {
7056
7718
  value: incoming
7057
7719
  };
7058
7720
  }
7059
- const storedObj = isRecord$6(stored) ? stored : {};
7721
+ const storedObj = isRecord$4(stored) ? stored : {};
7060
7722
  return {
7061
7723
  kind: "value",
7062
7724
  value: await writeMembers(ctx, node.children, incoming, storedObj, (m) => `${fieldPath}.${m}`)
@@ -7179,7 +7841,7 @@ async function resolveSecretMarkers(value, secrets, options = {}) {
7179
7841
  value: items
7180
7842
  };
7181
7843
  }
7182
- if (isRecord$6(v)) {
7844
+ if (isRecord$4(v)) {
7183
7845
  const out = {};
7184
7846
  for (const [k, child] of Object.entries(v)) {
7185
7847
  const s = substitute(child);
@@ -7211,7 +7873,7 @@ var SecretOverwriteRefusedError = class extends Error {
7211
7873
  this.name = "SecretOverwriteRefusedError";
7212
7874
  }
7213
7875
  };
7214
- function isRecord$5(value) {
7876
+ function isRecord$3(value) {
7215
7877
  return typeof value === "object" && value !== null && !Array.isArray(value);
7216
7878
  }
7217
7879
  function resolvedValue(pass, marker) {
@@ -7240,7 +7902,7 @@ function inArray(pass, incoming, stored) {
7240
7902
  return incoming.map((item, index) => {
7241
7903
  const twin = stored[index];
7242
7904
  if (isSecretMarker(twin)) return typeof item === "string" && item === resolvedValue(pass, twin) ? twin : item;
7243
- if (isRecord$5(item) && isRecord$5(twin)) return inArrayRow(pass, item, twin);
7905
+ if (isRecord$3(item) && isRecord$3(twin)) return inArrayRow(pass, item, twin);
7244
7906
  if (Array.isArray(item) && Array.isArray(twin)) return inArray(pass, item, twin);
7245
7907
  return item;
7246
7908
  });
@@ -7251,7 +7913,7 @@ function inArrayRow(pass, incoming, stored) {
7251
7913
  const twin = stored[key];
7252
7914
  if (isSecretMarker(twin)) {
7253
7915
  if (typeof value === "string" && value === resolvedValue(pass, twin)) out[key] = twin;
7254
- } else if (isRecord$5(value) && isRecord$5(twin)) out[key] = inArrayRow(pass, value, twin);
7916
+ } else if (isRecord$3(value) && isRecord$3(twin)) out[key] = inArrayRow(pass, value, twin);
7255
7917
  else if (Array.isArray(value) && Array.isArray(twin)) out[key] = inArray(pass, value, twin);
7256
7918
  }
7257
7919
  return out;
@@ -7259,7 +7921,7 @@ function inArrayRow(pass, incoming, stored) {
7259
7921
  async function walk(pass, incoming, stored) {
7260
7922
  if (isSecretMarker(stored)) return atMarker(pass, incoming, stored);
7261
7923
  if (Array.isArray(incoming) && Array.isArray(stored)) return inArray(pass, incoming, stored);
7262
- if (!isRecord$5(incoming) || !isRecord$5(stored)) return incoming;
7924
+ if (!isRecord$3(incoming) || !isRecord$3(stored)) return incoming;
7263
7925
  const out = { ...incoming };
7264
7926
  for (const [key, value] of Object.entries(incoming)) out[key] = await walk(pass, value, stored[key]);
7265
7927
  return out;
@@ -7290,7 +7952,7 @@ async function restoreUnchangedSecrets(input) {
7290
7952
  function isJsonEqual(a, b) {
7291
7953
  if (Object.is(a, b)) return true;
7292
7954
  if (Array.isArray(a)) return Array.isArray(b) && a.length === b.length && a.every((v, i) => isJsonEqual(v, b[i]));
7293
- if (isRecord$5(a) && isRecord$5(b)) {
7955
+ if (isRecord$3(a) && isRecord$3(b)) {
7294
7956
  const keys = Object.keys(a);
7295
7957
  if (keys.length !== Object.keys(b).length) return false;
7296
7958
  return keys.every((k) => Object.prototype.hasOwnProperty.call(b, k) && isJsonEqual(a[k], b[k]));
@@ -7314,7 +7976,7 @@ function markerKeysOf(blob, owner) {
7314
7976
  }
7315
7977
  function nodeFromStored(value, owner) {
7316
7978
  if (isSecretMarker(value)) return isSecretRefOwnedBy(value.$secret, owner) ? { kind: "leaf" } : null;
7317
- if (!isRecord$5(value)) return null;
7979
+ if (!isRecord$3(value)) return null;
7318
7980
  const children = /* @__PURE__ */ new Map();
7319
7981
  for (const [key, child] of Object.entries(value)) {
7320
7982
  const node = nodeFromStored(child, owner);
@@ -7811,13 +8473,48 @@ var BaseAddon = class {
7811
8473
  if (api === void 0) throw new Error(`${this.ctx.id}: the migration API is not available on this context`);
7812
8474
  return this.runBound(sets.flatMap((set) => set.bind(api)), options);
7813
8475
  }
7814
- async runBound(migrations, options) {
8476
+ /**
8477
+ * A device addon states its instance kind once, before its migrations run, and the one-switch
8478
+ * migration (registry `enabled` to the instance body, epic #440 step 3) joins whatever
8479
+ * catalogue the addon runs, in the SAME declaration (the engine replaces an owner's catalogue
8480
+ * on every declare).
8481
+ */
8482
+ declareRegistrySwitch(spec) {
8483
+ this.registrySwitchSpec = spec;
8484
+ }
8485
+ registrySwitchSpec = null;
8486
+ registrySwitchBound() {
8487
+ const spec = this.registrySwitchSpec;
8488
+ if (spec === null) return [];
8489
+ const api = this.ctx.migrationApi;
8490
+ if (api === void 0) {
8491
+ this.ctx.logger.warn("the registry switch migration is skipped: the migration API is not available on this context");
8492
+ return [];
8493
+ }
8494
+ return migrationSet([registrySwitchToBodyMigration({
8495
+ addonId: this.ctx.id,
8496
+ date: "2026-11-06",
8497
+ seq: 1e3,
8498
+ initialBody: spec.initialBody
8499
+ })], (a) => registrySwitchPortsOver({
8500
+ api: integrationRowsApiOver(a),
8501
+ records: switchRecordsOverMigrationApi(a),
8502
+ kind: spec.kind
8503
+ })).bind(api);
8504
+ }
8505
+ async runBound(declared, options) {
8506
+ const added = this.registrySwitchBound();
8507
+ const migrations = [...declared, ...added];
8508
+ const phased = options?.only === void 0 || added.length === 0 ? options : {
8509
+ ...options,
8510
+ only: [...options.only, ...added.map((m) => m.meta.id)]
8511
+ };
7815
8512
  const api = this.ctx.api.migrations;
7816
8513
  const report = await runAddonMigrations({
7817
8514
  declareOwner: (input) => api.declareOwner.mutate(input),
7818
8515
  startMigration: (input) => api.startMigration.mutate(input),
7819
8516
  finishMigration: (input) => api.finishMigration.mutate(input)
7820
- }, migrations, this.ctx.logger, options);
8517
+ }, migrations, this.ctx.logger, phased);
7821
8518
  if (report.blockOwner.length > 0) throw new AddonMigrationsBlockedError(report.blockOwner);
7822
8519
  return report;
7823
8520
  }
@@ -8890,237 +9587,6 @@ function normalizeAddonInitResult(result) {
8890
9587
  if (Array.isArray(result)) return { providers: result };
8891
9588
  return result;
8892
9589
  }
8893
- var PREFIX = "records/";
8894
- /** The base of every records failure. `detail` is the human part of the message. */
8895
- var RecordsError = class extends Error {
8896
- code;
8897
- detail;
8898
- constructor(code, detail) {
8899
- super(`${PREFIX}${code}: ${detail}`);
8900
- this.name = "RecordsError";
8901
- this.code = code;
8902
- this.detail = detail;
8903
- }
8904
- };
8905
- /** A write guarded by `ifRev` found another revision (or an existing row for `ifRev: 0`). */
8906
- var RevConflictError = class extends RecordsError {
8907
- constructor(detail) {
8908
- super("rev-conflict", detail);
8909
- this.name = "RevConflictError";
8910
- }
8911
- };
8912
- /** The keychain could not store or serve a value: explicit, never an empty string. */
8913
- var RecordSecretUnavailableError = class extends RecordsError {
8914
- constructor(detail) {
8915
- super("secret-unavailable", detail);
8916
- this.name = "RecordSecretUnavailableError";
8917
- }
8918
- };
8919
- var InvalidRecordError = class extends RecordsError {
8920
- constructor(detail) {
8921
- super("invalid-record", detail);
8922
- this.name = "InvalidRecordError";
8923
- }
8924
- };
8925
- /** A kind declaration the engine refuses (non-additive change, bad shape, wrong file). */
8926
- var DeclarationRefusedError = class extends RecordsError {
8927
- constructor(detail) {
8928
- super("declaration-refused", detail);
8929
- this.name = "DeclarationRefusedError";
8930
- }
8931
- };
8932
- /** Limits and names of `ctx.records` (D881). One authority; the engine and the facade read it. */
8933
- /** The files a kind may live in. `history` is device-history's (D850), never records. */
8934
- var RECORD_DATABASES = ["settings", "events"];
8935
- /** The classes of a kind: the `@durable` vocabulary, one authority (replaces the annotation). */
8936
- var RECORD_CLASSES = [
8937
- "config",
8938
- "ledger",
8939
- "audit",
8940
- "mirror",
8941
- "ephemeral"
8942
- ];
8943
- var RECORD_DEFAULT_MAX_DATA_BYTES = 64 * 1024;
8944
- var RECORD_MAX_DATA_BYTES = 1024 * 1024;
8945
- var RECORD_BATCH_MAX = 1e3;
8946
- var RECORD_QUERY_MAX = 1e3;
8947
- /** A kind in the `settings` file may not bound itself above this (D447: high volume is `events`). */
8948
- var RECORD_SETTINGS_MAX_ROWS = 5e4;
8949
- /** The `Column`-free proof prefix: a ref collection for a kind's secret fields. */
8950
- var RECORD_SECRET_COLLECTION_PREFIX = "records:";
8951
- /**
8952
- * Secret fields of a record, addressed the way a Zod schema declares them
8953
- * (`collectZodSecretPaths`): dotted keys, `[]` for "each element of this array"
8954
- * (`auth.accessToken`, `headers[].value`).
8955
- *
8956
- * `{}` after a key means "each value of this map" (`applianceSecrets{}`): the map's own key
8957
- * names the value (`applianceSecrets{fridge}`), so no id key is declared and a body that drops a
8958
- * key releases exactly that key's secret.
8959
- *
8960
- * Array elements are matched by a DECLARED id key (`secretArrayKeys`:
8961
- * `{ headers: 'name' }`), never by index, so reordering a list keeps every
8962
- * keychain ref (the same rule as `arrayItemFieldPath`). The concrete path of a
8963
- * leaf names its element: `headers[X-Api].value`.
8964
- *
8965
- * Pure and browser-safe. Nothing here mutates: every transform returns a new value.
8966
- */
8967
- /** The array prefixes (declared form, e.g. `headers` or `a.headers`) of a path. */
8968
- function parseSecretPath(path) {
8969
- if (path.length === 0) throw new InvalidRecordError("an empty secret path");
8970
- return path.split(".").map((raw) => {
8971
- const each = raw.endsWith("[]");
8972
- const map = raw.endsWith("{}");
8973
- const key = each || map ? raw.slice(0, -2) : raw;
8974
- if (key.length === 0) throw new InvalidRecordError(`secret path "${path}" has an empty segment`);
8975
- return {
8976
- key,
8977
- each,
8978
- map
8979
- };
8980
- });
8981
- }
8982
- /** The declared array prefixes of `path` that need an id key (`headers`, `a.rows`). */
8983
- function secretArrayPrefixes(path) {
8984
- const segments = parseSecretPath(path);
8985
- const prefixes = [];
8986
- const walked = [];
8987
- for (const segment of segments) {
8988
- walked.push(segment.key);
8989
- if (segment.each) prefixes.push(walked.join("."));
8990
- }
8991
- return prefixes;
8992
- }
8993
- function isRecord$4(value) {
8994
- return typeof value === "object" && value !== null && !Array.isArray(value);
8995
- }
8996
- function elementId(element, idKey, declared, prefix) {
8997
- const id = isRecord$4(element) ? element[idKey] : void 0;
8998
- 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`);
8999
- return id;
9000
- }
9001
- /**
9002
- * Visit every secret leaf PRESENT in `data` (an absent branch has nothing to
9003
- * visit). `replace` returns the new leaf value, or {@link REMOVE_LEAF}; the
9004
- * result is a new body, `data` is untouched.
9005
- */
9006
- var REMOVE_LEAF = Symbol("remove-leaf");
9007
- function mapAt(node, segments, index, walkedKeys, concretePrefix, declared, arrayKeys, visit) {
9008
- if (!isRecord$4(node)) return node;
9009
- const segment = segments[index];
9010
- if (segment === void 0) return node;
9011
- if (!Object.prototype.hasOwnProperty.call(node, segment.key)) return node;
9012
- const child = node[segment.key];
9013
- const keys = [...walkedKeys, segment.key];
9014
- const last = index === segments.length - 1;
9015
- if (segment.each) {
9016
- if (!Array.isArray(child)) return node;
9017
- const prefix = keys.join(".");
9018
- const idKey = arrayKeys[prefix];
9019
- if (idKey === void 0) throw new InvalidRecordError(`"${declared}": no id key declared for the array "${prefix}"`);
9020
- const mapped = child.map((element) => {
9021
- const id = elementId(element, idKey, declared, prefix);
9022
- const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}[${encodeURIComponent(id)}]`;
9023
- return last ? element : mapAt(element, segments, index + 1, keys, concrete, declared, arrayKeys, visit);
9024
- });
9025
- return {
9026
- ...node,
9027
- [segment.key]: mapped
9028
- };
9029
- }
9030
- if (segment.map) {
9031
- if (!isRecord$4(child)) return node;
9032
- const kept = Object.entries(child).map(([mapKey, value]) => {
9033
- const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}{${encodeURIComponent(mapKey)}}`;
9034
- if (!last) return [mapKey, mapAt(value, segments, index + 1, keys, concrete, declared, arrayKeys, visit)];
9035
- return [mapKey, visit({
9036
- declared,
9037
- concrete,
9038
- value
9039
- })];
9040
- }).filter(([, value]) => value !== REMOVE_LEAF);
9041
- return {
9042
- ...node,
9043
- [segment.key]: Object.fromEntries(kept)
9044
- };
9045
- }
9046
- const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}`;
9047
- if (last) {
9048
- const replacement = visit({
9049
- declared,
9050
- concrete,
9051
- value: child
9052
- });
9053
- if (replacement === REMOVE_LEAF) return Object.fromEntries(Object.entries(node).filter(([key]) => key !== segment.key));
9054
- return {
9055
- ...node,
9056
- [segment.key]: replacement
9057
- };
9058
- }
9059
- return {
9060
- ...node,
9061
- [segment.key]: mapAt(child, segments, index + 1, keys, concrete, declared, arrayKeys, visit)
9062
- };
9063
- }
9064
- /** Replace/remove every present secret leaf; returns a NEW body. */
9065
- function mapSecretLeaves(data, paths, arrayKeys, visit) {
9066
- let current = data;
9067
- for (const declared of paths) current = mapAt(current, parseSecretPath(declared), 0, [], "", declared, arrayKeys, visit);
9068
- return current;
9069
- }
9070
- /** Every present secret leaf, read-only. */
9071
- function collectSecretLeaves(data, paths, arrayKeys) {
9072
- const found = [];
9073
- mapSecretLeaves(data, paths, arrayKeys, (leaf) => {
9074
- found.push(leaf);
9075
- return leaf.value;
9076
- });
9077
- return found;
9078
- }
9079
- /**
9080
- * The keychain collection name a kind's secrets live under. Prefixed so a
9081
- * record's refs never collide with the refs a legacy collection of the same name
9082
- * already holds during an adoption.
9083
- */
9084
- function recordSecretCollection(kind) {
9085
- return `${RECORD_SECRET_COLLECTION_PREFIX}${kind}`;
9086
- }
9087
- /** The ONE ref a row's secret field may carry: the engine and the facade both build it here. */
9088
- function recordSecretRef(owner, kind, rowId, concretePath) {
9089
- return buildSecretRef({
9090
- owner,
9091
- scope: {
9092
- kind: "row",
9093
- collection: recordSecretCollection(kind),
9094
- rowId
9095
- },
9096
- fieldPath: concretePath
9097
- });
9098
- }
9099
- /**
9100
- * A stored secret, as an admin read shows it: a VIEW naming the row's own
9101
- * keychain ref (`set: true`), never the value and no longer the bare redaction
9102
- * token. The form hands it to the secret field, which reveals the value by ref
9103
- * through the audited `keychain-admin.reveal`; sent back untouched it keeps the
9104
- * stored secret (the records door reads a view as KEEP).
9105
- *
9106
- * ONE implementation for the entries service and for every addon that serves
9107
- * its own instances (`RecordIntegrationInstances`).
9108
- */
9109
- function isRecord$3(value) {
9110
- return typeof value === "object" && value !== null && !Array.isArray(value);
9111
- }
9112
- function secretViewsOf(owner, kind, id, decl, data) {
9113
- if (decl.secretPaths.length === 0) return data;
9114
- const shown = mapSecretLeaves(data, decl.secretPaths, decl.secretArrayKeys, (leaf) => {
9115
- if (leaf.value !== "__camstack_redacted__") return leaf.value;
9116
- return {
9117
- $secret: recordSecretRef(owner, kind, id, leaf.concrete),
9118
- v: 1,
9119
- set: true
9120
- };
9121
- });
9122
- return isRecord$3(shown) ? shown : data;
9123
- }
9124
9590
  /**
9125
9591
  * The share-view scope kinds a share-link token can carry. The hub mints
9126
9592
  * and validates them (`ShareViewGrantSchema` builds its
@@ -9374,6 +9840,7 @@ function defineRecordKinds(specs) {
9374
9840
  function entryBody(shape) {
9375
9841
  return object({
9376
9842
  name: string().min(1),
9843
+ enabled: boolean().optional(),
9377
9844
  ...shape
9378
9845
  });
9379
9846
  }
@@ -11217,6 +11684,10 @@ Object.freeze({
11217
11684
  "all",
11218
11685
  "one"
11219
11686
  ]
11687
+ },
11688
+ {
11689
+ "path": "positionUpdatedAt",
11690
+ "valueType": "number"
11220
11691
  }
11221
11692
  ],
11222
11693
  "meter": [{
@@ -11471,22 +11942,6 @@ Object.freeze({
11471
11942
  "path": "pumpRunning",
11472
11943
  "valueType": "boolean"
11473
11944
  },
11474
- {
11475
- "path": "lastDrink",
11476
- "valueType": "number"
11477
- },
11478
- {
11479
- "path": "currentHourDrink",
11480
- "valueType": "number"
11481
- },
11482
- {
11483
- "path": "last24hDrink",
11484
- "valueType": "number"
11485
- },
11486
- {
11487
- "path": "todayDrink",
11488
- "valueType": "number"
11489
- },
11490
11945
  {
11491
11946
  "path": "error",
11492
11947
  "valueType": "string"
@@ -12052,12 +12507,66 @@ Object.freeze({
12052
12507
  }
12053
12508
  ]
12054
12509
  });
12510
+ Object.freeze({
12511
+ "actions": { "run": 363e4 },
12512
+ "audio-analyzer": { "classify": 3e4 },
12513
+ "custom-model-registry": { "importModelBundle": 18e5 },
12514
+ "database-snapshot": { "writeSnapshot": 18e5 },
12515
+ "device-manager": {
12516
+ "migrateDevice": 72e4,
12517
+ "runDiscoverySweep": 12e4
12518
+ },
12519
+ "device-provider": { "reloadDevice": 18e4 },
12520
+ "llm": {
12521
+ "generate": 6e5,
12522
+ "generateVision": 6e5,
12523
+ "testProfile": 6e5
12524
+ },
12525
+ "llm-runtime": {
12526
+ "complete": 6e5,
12527
+ "completeApple": 6e5,
12528
+ "ensureStarted": 6e5,
12529
+ "installModel": 36e5
12530
+ },
12531
+ "local-network": { "scanNetwork": 9e4 },
12532
+ "model-convert": { "convert": 6e5 },
12533
+ "pipeline-analytics": {
12534
+ "addRetrainFrameFromRecording": 6e4,
12535
+ "offerRetrainArchive": 12e4,
12536
+ "proposeRetrainAnnotationsWithLlm": 18e4,
12537
+ "resolveRetrainTrainingCorpus": 6e4,
12538
+ "writeRetrainArchive": 36e5
12539
+ },
12540
+ "server-management": { "applyServerUpdate": 96e4 },
12541
+ "terminal-session": { "pullOutput": 15e3 },
12542
+ "training": {
12543
+ "canaryResult": 12e4,
12544
+ "cancelJob": 12e4,
12545
+ "planJob": 6e4,
12546
+ "registerResult": 18e5,
12547
+ "rollbackCanary": 12e4,
12548
+ "startJob": 12e4,
12549
+ "startJobBatch": 12e4
12550
+ },
12551
+ "training-provider": {
12552
+ "cancelJob": 6e4,
12553
+ "cleanupJob": 3e5,
12554
+ "getJob": 6e4,
12555
+ "listJobEvents": 6e4,
12556
+ "listJobs": 12e4,
12557
+ "offerArtifact": 3e5,
12558
+ "readResult": 3e5,
12559
+ "submitJob": 18e5,
12560
+ "uploadDataset": 72e5,
12561
+ "validateCredentials": 3e4
12562
+ }
12563
+ });
12055
12564
  object({
12056
12565
  code: string().regex(/^[a-z][a-z0-9-]*(\.[a-z0-9-]+)+$/),
12057
12566
  params: record(string(), union([string(), number()])).optional()
12058
12567
  });
12059
12568
  //#endregion
12060
- //#region ../types/dist/composition-pOHbTzRB.mjs
12569
+ //#region ../types/dist/composition-BmBHuDTQ.mjs
12061
12570
  /**
12062
12571
  * The ffmpeg build every CamStack node downloads, per platform and arch.
12063
12572
  *
@@ -12361,7 +12870,7 @@ var table = {
12361
12870
  },
12362
12871
  dwell: {
12363
12872
  minArgs: 3,
12364
- maxArgs: 3,
12873
+ maxArgs: 4,
12365
12874
  apply: () => {
12366
12875
  throw new ExpressionEvalError("dwell: stateful evaluation context is required");
12367
12876
  }
@@ -13404,212 +13913,6 @@ var IntegrationInstanceRefSchema = object({
13404
13913
  ]),
13405
13914
  candidateStableId: string().optional()
13406
13915
  });
13407
- /**
13408
- * `RecordIntegrationInstances` - the `integration-instances` provider over ONE
13409
- * entry kind, so an addon that holds a connection serves it in ~30 lines.
13410
- *
13411
- * Every instance is one record of the addon's own kind, keyed by the
13412
- * `integrations` registry id. The records door does the secret work: a field the
13413
- * kind marks `.meta({ secret: true })` is a keychain marker bound to the row, so
13414
- * deleting the row deletes the secret, and one row's value is never another's.
13415
- *
13416
- * Patch rules for a secret (`updateInstance`): omitted, `''`, the redaction
13417
- * token or the view the form was given KEEP the stored secret;
13418
- * `{ $secretClear: true }` clears it; any other string replaces it.
13419
- */
13420
- /** The most instances one addon lists (an integrations page, not a table). */
13421
- var INSTANCES_LIST_MAX = 1e3;
13422
- /** The keys of the kind's secret fields that sit at the top level of the body. */
13423
- function topLevelSecretKeys(paths) {
13424
- return new Set(paths.filter((p) => !p.includes(".") && !p.includes("[") && !p.includes("{")));
13425
- }
13426
- /** The keys of the kind's top-level MAPS whose values are secrets (`applianceSecrets{}`). */
13427
- function secretMapKeys(paths) {
13428
- return new Set(paths.filter((p) => p.endsWith("{}") && !p.slice(0, -2).match(/[.[{]/)).map((p) => p.slice(0, -2)));
13429
- }
13430
- /**
13431
- * A patch value for a map of secrets: an entry that is omitted, `''`, the redaction token or the
13432
- * view the form was given KEEPS its stored secret (it is left out of the merge); `{ $secretClear }`
13433
- * or `null` removes the entry; any other string replaces it. Null when nothing is left to merge.
13434
- */
13435
- function secretMapPatch(value) {
13436
- if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
13437
- const out = {};
13438
- for (const [key, entry] of Object.entries(value)) if (entry === null || isSecretClear(entry)) out[key] = null;
13439
- else if (typeof entry === "string" && entry !== "" && entry !== "__camstack_redacted__" && !isSecretFieldView(entry)) out[key] = entry;
13440
- return Object.keys(out).length > 0 ? out : null;
13441
- }
13442
- /** Does the kind's body schema carry an `enabled` field? */
13443
- function declaresEnabled(kind) {
13444
- const json = toJSONSchema(kind.schema, {
13445
- unrepresentable: "any",
13446
- io: "input"
13447
- });
13448
- const properties = Reflect.get(json, "properties");
13449
- return typeof properties === "object" && properties !== null && "enabled" in properties;
13450
- }
13451
- var RecordIntegrationInstances = class {
13452
- records;
13453
- kind;
13454
- hooks;
13455
- handle;
13456
- secretKeys;
13457
- secretMaps;
13458
- nameField;
13459
- /** The `integrations` registry owns the on/off switch (`role: devices`); the body has none. */
13460
- registryOwnsEnabled;
13461
- constructor(records, kind, hooks) {
13462
- this.records = records;
13463
- this.kind = kind;
13464
- this.hooks = hooks;
13465
- this.handle = records.kind(kind);
13466
- this.secretKeys = topLevelSecretKeys(kind.declaration.secretPaths);
13467
- this.secretMaps = secretMapKeys(kind.declaration.secretPaths);
13468
- this.nameField = kind.declaration.entry?.nameField ?? "name";
13469
- this.registryOwnsEnabled = hooks.description.role === "devices";
13470
- 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"`);
13471
- }
13472
- /**
13473
- * One instance read for the addon's own runtime; null when absent. When the keychain is
13474
- * locked the row is served WITHOUT its secrets and says so (`secrets: 'unavailable'`), so the
13475
- * caller can keep what it had instead of reconfiguring with an empty secret (D49).
13476
- */
13477
- async readResolved(id) {
13478
- try {
13479
- const record = await this.handle.getResolved(id);
13480
- return record === null ? null : {
13481
- id,
13482
- body: record.data,
13483
- enabled: record.data.enabled !== false,
13484
- secrets: "resolved"
13485
- };
13486
- } catch (err) {
13487
- if (!(err instanceof RecordSecretUnavailableError)) throw err;
13488
- const stored = await this.handle.get(id);
13489
- if (stored === null) return null;
13490
- return {
13491
- id,
13492
- body: Object.fromEntries(Object.entries(stored.data).filter(([key]) => !this.secretKeys.has(key))),
13493
- enabled: stored.data.enabled !== false,
13494
- secrets: "unavailable"
13495
- };
13496
- }
13497
- }
13498
- /** The body of {@link readResolved} alone; a locked keychain yields the row without secrets. */
13499
- async getResolved(id) {
13500
- return (await this.readResolved(id))?.body ?? null;
13501
- }
13502
- /** Every instance, secrets resolved where the keychain allows; an absent one is skipped. */
13503
- async listResolved() {
13504
- const page = await this.handle.query({ limit: INSTANCES_LIST_MAX });
13505
- const out = [];
13506
- for (const record of page.records) {
13507
- const read = await this.readResolved(record.id);
13508
- if (read !== null) out.push(read);
13509
- }
13510
- return out;
13511
- }
13512
- viewOf(record) {
13513
- const shown = secretViewsOf(this.records.owner, this.kind.name, record.id, this.kind.declaration, record.data);
13514
- const rawName = record.data[this.nameField];
13515
- const kind = this.hooks.kindOf?.(record.data);
13516
- const health = this.hooks.health?.(record.data, record.id);
13517
- return {
13518
- id: record.id,
13519
- name: typeof rawName === "string" ? rawName : record.id,
13520
- configured: this.hooks.configured(record.data),
13521
- ...this.registryOwnsEnabled ? {} : { enabled: record.data.enabled !== false },
13522
- formValues: shown,
13523
- ...kind !== void 0 ? { kind } : {},
13524
- ...health?.status !== void 0 ? { status: health.status } : {},
13525
- ...health?.lastCheckedAt !== void 0 ? { lastCheckedAt: health.lastCheckedAt } : {}
13526
- };
13527
- }
13528
- describe = async () => this.hooks.mintId === void 0 ? this.hooks.description : {
13529
- ...this.hooks.description,
13530
- mintsId: true
13531
- };
13532
- instanceFormSchema = async ({ id }) => this.hooks.formSchema(id);
13533
- listInstances = async () => {
13534
- return (await this.handle.query({ limit: INSTANCES_LIST_MAX })).records.map((record) => this.viewOf(record));
13535
- };
13536
- getInstance = async ({ id }) => {
13537
- const record = await this.handle.get(id);
13538
- return record === null ? null : this.viewOf(record);
13539
- };
13540
- /** Insert ONE row (`ifRev: 0`: an existing id is refused, never overwritten). */
13541
- createInstance = async ({ id, name, kind, values }) => {
13542
- const minted = id ?? this.hooks.mintId?.({
13543
- name,
13544
- ...kind !== void 0 ? { kind } : {}
13545
- });
13546
- if (minted === void 0) throw new Error("createInstance needs an id: this provider does not mint one");
13547
- await this.handle.put({
13548
- id: minted,
13549
- data: this.hooks.initialBody(name, kind)
13550
- }, { ifRev: 0 });
13551
- const patch = this.patchOf(values ?? {});
13552
- if (Object.keys(patch).length > 0) await this.handle.patch(minted, patch);
13553
- await this.hooks.onChanged?.(minted, "created");
13554
- return { id: minted };
13555
- };
13556
- updateInstance = async ({ id, name, values }) => {
13557
- const patch = this.patchOf(values);
13558
- if (name !== void 0) patch[this.nameField] = name;
13559
- await this.handle.patch(id, patch);
13560
- await this.hooks.onChanged?.(id, "updated");
13561
- return { ok: true };
13562
- };
13563
- /** The record patch a form `values` object means: secrets kept, cleared or replaced. */
13564
- patchOf(values) {
13565
- const patch = {};
13566
- for (const [key, value] of Object.entries(values)) {
13567
- if (value === void 0) continue;
13568
- if (this.secretMaps.has(key)) {
13569
- const entries = secretMapPatch(value);
13570
- if (entries !== null) patch[key] = entries;
13571
- } else if (!this.secretKeys.has(key)) patch[key] = value;
13572
- else if (isSecretClear(value)) patch[key] = null;
13573
- else if (typeof value === "string" && value !== "" && value !== "__camstack_redacted__" && !isSecretFieldView(value)) patch[key] = value;
13574
- }
13575
- return patch;
13576
- }
13577
- /** The switch lives in the record body; the addon is told so it applies it (D996). */
13578
- setInstanceEnabled = async ({ id, enabled }) => {
13579
- if (this.registryOwnsEnabled) throw new Error(`instance "${id}": the integrations registry owns the on/off switch of this addon; set it with integrations.update`);
13580
- await this.handle.patch(id, { enabled });
13581
- await this.hooks.onChanged?.(id, "enabled");
13582
- return { ok: true };
13583
- };
13584
- /** The row and its keychain refs go together (the records door). */
13585
- deleteInstance = async ({ id }) => {
13586
- await this.handle.delete(id);
13587
- await this.hooks.onChanged?.(id, "deleted");
13588
- return { ok: true };
13589
- };
13590
- testInstance = async (input) => {
13591
- if (this.hooks.test === void 0) return {
13592
- success: false,
13593
- status: "unsupported",
13594
- error: "This integration declares no connection test"
13595
- };
13596
- return this.hooks.test(input);
13597
- };
13598
- /** The flat provider object to hand to `registerProvider`. */
13599
- toProvider() {
13600
- return {
13601
- describe: this.describe,
13602
- instanceFormSchema: this.instanceFormSchema,
13603
- listInstances: this.listInstances,
13604
- getInstance: this.getInstance,
13605
- createInstance: this.createInstance,
13606
- updateInstance: this.updateInstance,
13607
- setInstanceEnabled: this.setInstanceEnabled,
13608
- deleteInstance: this.deleteInstance,
13609
- testInstance: this.testInstance
13610
- };
13611
- }
13612
- };
13613
13916
  var EncodeProfileSchema = object({
13614
13917
  video: object({
13615
13918
  codec: _enum([
@@ -19991,31 +20294,21 @@ var APPLIANCE_CAP_VOCABULARY = {
19991
20294
  "pet-fountain": {
19992
20295
  scope: "device",
19993
20296
  noun: t("Pet fountain", "Fontana per animali"),
19994
- actions: [
19995
- {
19996
- id: "petFountain.pumpOn",
19997
- method: "setPump",
19998
- label: t("Pump on", "Pompa accesa"),
19999
- phrase: t("Start the pump of {device}", "Avvia la pompa di {device}"),
20000
- icon: "play",
20001
- args: { on: true }
20002
- },
20003
- {
20004
- id: "petFountain.pumpOff",
20005
- method: "setPump",
20006
- label: t("Pump off", "Pompa spenta"),
20007
- phrase: t("Stop the pump of {device}", "Ferma la pompa di {device}"),
20008
- icon: "square",
20009
- args: { on: false }
20010
- },
20011
- {
20012
- id: "petFountain.resetDailyConsumption",
20013
- method: "resetDailyConsumption",
20014
- label: t("Clear daily consumption", "Azzera il consumo giornaliero"),
20015
- phrase: t("Clear the daily water consumption of {device}", "Azzera il consumo giornaliero di acqua di {device}"),
20016
- icon: "rotate-ccw"
20017
- }
20018
- ],
20297
+ actions: [{
20298
+ id: "petFountain.pumpOn",
20299
+ method: "setPump",
20300
+ label: t("Pump on", "Pompa accesa"),
20301
+ phrase: t("Start the pump of {device}", "Avvia la pompa di {device}"),
20302
+ icon: "play",
20303
+ args: { on: true }
20304
+ }, {
20305
+ id: "petFountain.pumpOff",
20306
+ method: "setPump",
20307
+ label: t("Pump off", "Pompa spenta"),
20308
+ phrase: t("Stop the pump of {device}", "Ferma la pompa di {device}"),
20309
+ icon: "square",
20310
+ args: { on: false }
20311
+ }],
20019
20312
  state: [{
20020
20313
  kind: "boolean",
20021
20314
  field: "empty",
@@ -44048,8 +44341,15 @@ var ActionInputSchema = object({
44048
44341
  var ActionRunOriginSchema = object({
44049
44342
  /** The automation block whose step started it. */
44050
44343
  blockId: string().min(1).optional() });
44051
- /** `started` = the caller did not ask to wait. */
44052
- var ActionRunOutcomeSchema = union([AutomationRunOutcomeSchema, literal("started")]);
44344
+ /**
44345
+ * `started` = the caller did not ask to wait. `timed-out` = the run reached the
44346
+ * ceiling (`ACTION_RUN_MAX_MS`) and was stopped; it is never a `ran`.
44347
+ */
44348
+ var ActionRunOutcomeSchema = union([
44349
+ AutomationRunOutcomeSchema,
44350
+ literal("started"),
44351
+ literal("timed-out")
44352
+ ]);
44053
44353
  var ActionRunResultSchema = object({
44054
44354
  runId: string().min(1),
44055
44355
  outcome: ActionRunOutcomeSchema,
@@ -44571,6 +44871,8 @@ method(object({}), array(ActionEntrySchema), { auth: "admin" }), method(object({
44571
44871
  kind: "mutation",
44572
44872
  auth: "admin"
44573
44873
  });
44874
+ /** `timeoutMs` of `actions.run`: a waited call outlives any legal run. */
44875
+ var ACTION_RUN_TIMEOUT_MS = 363e4;
44574
44876
  /**
44575
44877
  * actions — the ONE surface for runnable actions, for the UI and for
44576
44878
  * automations. Provided by the core-blocks builtin on the hub.
@@ -44589,6 +44891,12 @@ method(object({}), array(ActionEntrySchema), { auth: "admin" }), method(object({
44589
44891
  * An admin, and an in-process caller (an automation block), may run any action.
44590
44892
  * Every refusal is typed (`[not-linked] …`) and logged.
44591
44893
  *
44894
+ * **A run lasts at most `ACTION_RUN_MAX_MS` (60 min).** The provider stops a
44895
+ * run that reaches it and answers `timed-out` (never `ran`); an action whose
44896
+ * `wait` steps alone add up to more is refused at create/update
44897
+ * (`[invalid-steps]`). `run` declares a `timeoutMs` above that ceiling, so a
44898
+ * waited call (an automation step) is never cut by the 60 s transport default.
44899
+ *
44592
44900
  * A second `run` of an action that is already running is REFUSED — traced and
44593
44901
  * logged — never queued.
44594
44902
  */
@@ -44615,7 +44923,8 @@ method(object({}), array(ActionEntrySchema), { auth: "admin" }), method(object({
44615
44923
  role: "viewer",
44616
44924
  auth: "protected",
44617
44925
  kind: "mutation",
44618
- caller: "required"
44926
+ caller: "required",
44927
+ timeoutMs: ACTION_RUN_TIMEOUT_MS
44619
44928
  }), method(ActionIdInput, _void(), {
44620
44929
  kind: "mutation",
44621
44930
  auth: "admin"
@@ -49642,6 +49951,9 @@ var MediaPlayerStatusSchema = object({
49642
49951
  /** Repeat mode. Null when no repeat surface.
49643
49952
  * Pair with `DeviceFeature.MediaPlayerRepeat`. */
49644
49953
  repeat: MediaPlayerRepeatSchema.nullable(),
49954
+ /** Ms epoch when `position` was read from the device. Null when the driver
49955
+ * does not say; a UI that advances the position while playing counts from it. */
49956
+ positionUpdatedAt: number().nullable().default(null),
49645
49957
  /** Ms epoch when the slice was last updated. */
49646
49958
  lastChangedAt: number()
49647
49959
  });
@@ -50277,7 +50589,9 @@ var ThresholdTransformDraftSchema = object({
50277
50589
  comparison: _enum(["gte", "lte"]),
50278
50590
  threshold: number(),
50279
50591
  startDwellMs: number().nonnegative(),
50280
- stopDwellMs: number().nonnegative()
50592
+ stopDwellMs: number().nonnegative(),
50593
+ /** Samples a start needs; absent = the compiler's default for the source (2 for running power, else 1). */
50594
+ minSamples: number().int().min(1).optional()
50281
50595
  });
50282
50596
  var CustomizeTransformDraftSchema = discriminatedUnion("kind", [
50283
50597
  IdentityTransformDraftSchema,
@@ -56175,6 +56489,7 @@ var IntegrationWithStateSchema = object({
56175
56489
  id: string(),
56176
56490
  addonId: string(),
56177
56491
  name: string(),
56492
+ /** A projection of the instance body's switch (`setInstanceEnabled` is the only writer). */
56178
56493
  enabled: boolean(),
56179
56494
  info: record(string(), unknown()).readonly(),
56180
56495
  /** The discovery candidate this integration was set up from (D984). */
@@ -56187,6 +56502,7 @@ var IntegrationLiteSchema = object({
56187
56502
  id: string(),
56188
56503
  addonId: string(),
56189
56504
  name: string(),
56505
+ /** A projection of the instance body's switch (`setInstanceEnabled` is the only writer). */
56190
56506
  enabled: boolean(),
56191
56507
  info: record(string(), unknown()).readonly(),
56192
56508
  /** The discovery candidate this integration was set up from (D984). */
@@ -56286,7 +56602,6 @@ var TestConnectionResultSchema = object({
56286
56602
  var CreateIntegrationInputSchema = object({
56287
56603
  addonId: string(),
56288
56604
  name: string(),
56289
- enabled: boolean().optional(),
56290
56605
  info: record(string(), unknown()).optional(),
56291
56606
  /** `stableId` of the discovery candidate the form was seeded from (D984). */
56292
56607
  originStableId: string().optional(),
@@ -56295,6 +56610,11 @@ var CreateIntegrationInputSchema = object({
56295
56610
  var UpdateIntegrationInputSchema = object({
56296
56611
  id: string(),
56297
56612
  name: string().optional(),
56613
+ /**
56614
+ * Accepted for a FIXED builtin only (`info.fixed`: alarm panel, camera grid, core blocks,
56615
+ * terminal), which keeps no instance record: the registry flag is its one store. Any other
56616
+ * integration is switched through `integration-instances.setInstanceEnabled`.
56617
+ */
56298
56618
  enabled: boolean().optional(),
56299
56619
  info: record(string(), unknown()).optional()
56300
56620
  });
@@ -56342,7 +56662,7 @@ var IntegrationInstanceIdSchema = string().min(1);
56342
56662
  var IntegrationInstanceModeSchema = _enum(["single", "multiple"]);
56343
56663
  /**
56344
56664
  * What the addon's instances ARE for the Integrations page (planning#416). `devices`: each
56345
- * instance is an integration that brings devices (the registry owns its on/off switch);
56665
+ * instance is an integration that brings devices (its record body owns the on/off switch);
56346
56666
  * `services`: a connection configured from the addon's own function page, never listed on
56347
56667
  * Integrations.
56348
56668
  * It is the same vocabulary as the manifest's `integrationRole`, which stays as an override.
@@ -56385,18 +56705,38 @@ var IntegrationInstanceKindSchema = object({
56385
56705
  /** Relative hub path to disconnect that account. */
56386
56706
  disconnectPath: string().min(1).optional()
56387
56707
  });
56708
+ /**
56709
+ * How devices of an instance are found. `none`: the operator adds them by hand; `lan`: the addon
56710
+ * scans the network before any instance exists (the wizard offers the candidates); `account`: the
56711
+ * devices appear after the instance signs in. `scopedToInstance`: a discovery run belongs to ONE
56712
+ * instance and its candidates are claimed by it.
56713
+ */
56714
+ var IntegrationInstanceDiscoverySchema = object({
56715
+ mode: _enum([
56716
+ "none",
56717
+ "lan",
56718
+ "account"
56719
+ ]),
56720
+ scopedToInstance: boolean()
56721
+ });
56722
+ /**
56723
+ * One link a kind of this provider declares (D1013 rule 5): the body `field` of an instance of
56724
+ * `kind` holds the id of an instance of the function cap `to.cap` (of kind `to.kind`, when set).
56725
+ * The hub indexes these so the target's delete is refused while a link names it.
56726
+ */
56727
+ var IntegrationInstanceLinkSchema = object({
56728
+ kind: string().min(1),
56729
+ field: string().min(1),
56730
+ to: object({
56731
+ cap: string().min(1),
56732
+ kind: string().min(1).optional()
56733
+ })
56734
+ });
56388
56735
  var IntegrationInstanceDescriptionSchema = object({
56389
56736
  /** What the instances are for the Integrations page; see {@link IntegrationInstanceRoleSchema}. */
56390
56737
  role: IntegrationInstanceRoleSchema,
56391
56738
  /** How the devices of an instance are found; absent means `{ mode: 'none' }`. */
56392
- discovery: object({
56393
- mode: _enum([
56394
- "none",
56395
- "lan",
56396
- "account"
56397
- ]),
56398
- scopedToInstance: boolean()
56399
- }).optional(),
56739
+ discovery: IntegrationInstanceDiscoverySchema.optional(),
56400
56740
  /** `single`: at most one instance can exist (Loki). `multiple`: an account each. */
56401
56741
  instanceMode: IntegrationInstanceModeSchema,
56402
56742
  /** What the instance is, for the UI (`destination`, `relay`, `account`). */
@@ -56417,7 +56757,9 @@ var IntegrationInstanceDescriptionSchema = object({
56417
56757
  * `createInstance` without an `id` works: the provider mints it. Absent means the caller must
56418
56758
  * send an id (the UI then mints an opaque one).
56419
56759
  */
56420
- mintsId: boolean().optional()
56760
+ mintsId: boolean().optional(),
56761
+ /** The links to other instances the provider's kinds declare; absent means none. */
56762
+ links: array(IntegrationInstanceLinkSchema).optional()
56421
56763
  });
56422
56764
  var IntegrationInstanceStatusSchema = object({
56423
56765
  state: _enum([
@@ -56437,8 +56779,8 @@ var IntegrationInstanceSchema = object({
56437
56779
  configured: boolean(),
56438
56780
  /**
56439
56781
  * The instance's own on/off switch (D996), derived from the record body (`enabled !== false`,
56440
- * so a row written before the field existed is on). Absent when the `integrations` registry
56441
- * owns the switch (`describe().role` is `devices`): read it from the registry row.
56782
+ * so a row written before the field existed is on). The same for every role, `devices` included:
56783
+ * the body is the one store, `setInstanceEnabled` the one writer (epic #440, step 3).
56442
56784
  */
56443
56785
  enabled: boolean().optional(),
56444
56786
  /** The kind of this instance (one of `describe().kinds[].id`), when the provider has kinds. */
@@ -56488,7 +56830,8 @@ var integrationInstancesCapability = {
56488
56830
  auth: "admin"
56489
56831
  }),
56490
56832
  /**
56491
- * Switch ONE instance on or off. A row control, not a form field: `updateInstance.values` is the
56833
+ * Switch ONE instance on or off, for every role; a missing record is created from the addon's
56834
+ * initial body. A row control, not a form field: `updateInstance.values` is the
56492
56835
  * form patch (D62, D996). An off instance keeps its record and secrets and does no work.
56493
56836
  */
56494
56837
  setInstanceEnabled: method(object({
@@ -59551,6 +59894,8 @@ var MigrationIntegrationSchema = object({
59551
59894
  addonId: string(),
59552
59895
  name: string(),
59553
59896
  info: Rows,
59897
+ /** The registry's stored switch: read by the one-switch migration, nothing else. */
59898
+ enabled: boolean().optional(),
59554
59899
  originStableId: string().optional()
59555
59900
  });
59556
59901
  var MigrationDeviceSchema = object({
@@ -69680,14 +70025,6 @@ var PetFountainStatusSchema = object({
69680
70025
  empty: boolean().nullable(),
69681
70026
  /** True while the pump is running. Null while unknown. */
69682
70027
  pumpRunning: boolean().nullable(),
69683
- /** Water drunk in the last drink, in litres. */
69684
- lastDrink: number().min(0).nullable().meta(readingMeta("volume")),
69685
- /** Water drunk in the current hour, in litres. */
69686
- currentHourDrink: number().min(0).nullable().meta(readingMeta("volume")),
69687
- /** Water drunk over the last 24 hours (rolling), in litres. */
69688
- last24hDrink: number().min(0).nullable().meta(readingMeta("volume")),
69689
- /** Water drunk since local midnight, in litres. Null when the fountain has no such sensor. */
69690
- todayDrink: number().min(0).nullable().meta(readingMeta("volume")),
69691
70028
  /** Decoded fault message. Null means healthy; a non-null string is an active fault. */
69692
70029
  error: string().nullable(),
69693
70030
  /** Ms epoch when the slice was last refreshed. */
@@ -69700,21 +70037,15 @@ var petFountainCapability = {
69700
70037
  deviceNative: true,
69701
70038
  mode: "singleton",
69702
70039
  deviceTypes: [DeviceType.PetFountain],
69703
- methods: {
69704
- /** Start or stop the pump. */
69705
- setPump: method(object({
69706
- deviceId: DeviceIdSchema$1,
69707
- on: boolean()
69708
- }), _void(), {
69709
- kind: "mutation",
69710
- auth: "protected"
69711
- }),
69712
- /** Clear the rolling daily consumption counters on the device. */
69713
- resetDailyConsumption: method(object({ deviceId: DeviceIdSchema$1 }), _void(), {
69714
- kind: "mutation",
69715
- auth: "protected"
69716
- })
69717
- },
70040
+ methods: {
70041
+ /** Start or stop the pump. */
70042
+ setPump: method(object({
70043
+ deviceId: DeviceIdSchema$1,
70044
+ on: boolean()
70045
+ }), _void(), {
70046
+ kind: "mutation",
70047
+ auth: "protected"
70048
+ }) },
69718
70049
  status: {
69719
70050
  schema: PetFountainStatusSchema,
69720
70051
  kind: "push"
@@ -69738,14 +70069,6 @@ var petFountainCapability = {
69738
70069
  waterVolume: {
69739
70070
  kind: "gauge",
69740
70071
  unit: "L"
69741
- },
69742
- todayDrink: {
69743
- kind: "gauge",
69744
- unit: "L"
69745
- },
69746
- last24hDrink: {
69747
- kind: "gauge",
69748
- unit: "L"
69749
70072
  }
69750
70073
  } }
69751
70074
  };
@@ -88286,13 +88609,6 @@ Object.freeze({
88286
88609
  access: "view",
88287
88610
  role: "viewer"
88288
88611
  },
88289
- "petFountain.resetDailyConsumption": {
88290
- capName: "pet-fountain",
88291
- capScope: "device",
88292
- addonId: null,
88293
- access: "delete",
88294
- role: "viewer"
88295
- },
88296
88612
  "petFountain.setPump": {
88297
88613
  capName: "pet-fountain",
88298
88614
  capScope: "device",
@@ -94689,11 +95005,6 @@ Object.freeze({
94689
95005
  form: "single",
94690
95006
  optional: false
94691
95007
  }],
94692
- "petFountain.resetDailyConsumption": [{
94693
- name: "deviceId",
94694
- form: "single",
94695
- optional: false
94696
- }],
94697
95008
  "petFountain.setPump": [{
94698
95009
  name: "deviceId",
94699
95010
  form: "single",
@@ -97562,74 +97873,6 @@ object({
97562
97873
  delay: number().nonnegative().optional(),
97563
97874
  commands: record(string(), unknown())
97564
97875
  });
97565
- entryBody({ brokerId: string() });
97566
- function secretsOverMigrationApi(api) {
97567
- return {
97568
- resolve: async (refs) => {
97569
- const { values } = await api.secrets.resolve({ refs: [...refs] });
97570
- const out = {};
97571
- for (const ref of refs) {
97572
- const value = values[ref];
97573
- out[ref] = value === null || value === void 0 ? { kind: "missing" } : {
97574
- kind: "value",
97575
- value,
97576
- version: 0
97577
- };
97578
- }
97579
- return out;
97580
- },
97581
- delete: async (refs) => (await api.secrets.delete({ refs: [...refs] })).deleted
97582
- };
97583
- }
97584
- /** `ctx.records` as the migration API offers it: bind a kind, read and write by id. */
97585
- function recordsOverMigrationApi(api) {
97586
- return { kind: (definition) => {
97587
- const handle = api.records.kind(definition);
97588
- return {
97589
- get: (id) => handle.get({ id }),
97590
- getResolved: (id) => handle.getResolved({ id }),
97591
- put: (input, opts) => handle.put({
97592
- ...input,
97593
- ...opts?.ifRev === void 0 ? {} : { ifRev: opts.ifRev }
97594
- }),
97595
- delete: (id) => handle.delete({ id })
97596
- };
97597
- } };
97598
- }
97599
- function integrationRowsApiOver(api) {
97600
- return {
97601
- list: async () => (await api.integrations.list({})).integrations,
97602
- readLegacyIntegrationRows: (input) => api.legacyRows.read(input),
97603
- clearLegacyIntegrationRows: (input) => api.legacyRows.clear(input)
97604
- };
97605
- }
97606
- /**
97607
- * One serial lane per migration API: a log line is delivered after the line before it, so the
97608
- * order the steps wrote them in is the order the hub reads them in. A delivery that fails
97609
- * is reported once through the same door; if that fails too nothing is left to tell, and the
97610
- * line is dropped rather than thrown into a migration step or left as an unhandled rejection.
97611
- */
97612
- var lanes = /* @__PURE__ */ new WeakMap();
97613
- function deliver(api, send) {
97614
- const next = (lanes.get(api) ?? Promise.resolve()).then(send).then(() => void 0).catch(async (error) => {
97615
- const reason = error instanceof Error ? error.message : String(error);
97616
- await api.log.warn({ message: `a migration log line could not be delivered: ${reason}` }).catch(() => void 0);
97617
- });
97618
- lanes.set(api, next);
97619
- return next;
97620
- }
97621
- function warnOver(api) {
97622
- return (message) => deliver(api, () => api.log.warn({ message }));
97623
- }
97624
- /** What the rows-to-records move needs, over the migration API. */
97625
- function rowsDepsOver(api) {
97626
- return {
97627
- api: integrationRowsApiOver(api),
97628
- records: recordsOverMigrationApi(api),
97629
- secrets: secretsOverMigrationApi(api),
97630
- warn: warnOver(api)
97631
- };
97632
- }
97633
97876
  //#endregion
97634
97877
  //#region src/config.ts
97635
97878
  /**
@@ -99398,6 +99641,10 @@ var EnpalProviderAddon = class extends BaseDeviceProvider {
99398
99641
  const records = this.ctx.records;
99399
99642
  if (records === void 0) throw new Error("provider-enpal: ctx.records is required (hub-only addon)");
99400
99643
  await records.declare(enpalRecordKinds);
99644
+ this.declareRegistrySwitch({
99645
+ kind: enpalConnectionsEntryKind,
99646
+ initialBody: (name) => ({ name })
99647
+ });
99401
99648
  await this.runMigrations([integrationRowsMigration({
99402
99649
  addonId: this.addonId,
99403
99650
  date: ENPAL_MIGRATIONS_DATE,
@@ -99488,8 +99735,9 @@ var EnpalProviderAddon = class extends BaseDeviceProvider {
99488
99735
  const integrationId = event.data["integrationId"];
99489
99736
  this.reconciler().onLifecycle(kind, typeof integrationId === "string" ? integrationId : null);
99490
99737
  };
99491
- this.ctx.eventBus.subscribe({ category: EventCategory.IntegrationEnabled }, on("enabled"));
99492
- this.ctx.eventBus.subscribe({ category: EventCategory.IntegrationDisabled }, on("disabled"));
99738
+ this.requireInstances().onSwitched((id, enabled) => {
99739
+ this.reconciler().onLifecycle(enabled ? "enabled" : "disabled", id);
99740
+ });
99493
99741
  this.ctx.eventBus.subscribe({ category: EventCategory.IntegrationDeleted }, on("deleted"));
99494
99742
  }
99495
99743
  /** The integrations that own devices here, for the orphan sweep. */