@camstack/addon-export-hap 1.2.191 → 1.2.193

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.
@@ -1,6 +1,6 @@
1
1
  import { createRequire } from "node:module";
2
- import { spawn } from "node:child_process";
3
2
  import { createHash, randomBytes, randomUUID } from "node:crypto";
3
+ import { spawn } from "node:child_process";
4
4
  import * as path from "node:path";
5
5
  import { join } from "node:path";
6
6
  import { createReadStream, createWriteStream, readFileSync } from "node:fs";
@@ -4598,6 +4598,12 @@ var numberProcessor = (schema, ctx, _json, _params) => {
4598
4598
  var booleanProcessor = (_schema, _ctx, json, _params) => {
4599
4599
  json.type = "boolean";
4600
4600
  };
4601
+ var bigintProcessor = (_schema, ctx, _json, _params) => {
4602
+ if (ctx.unrepresentable === "throw") throw new Error("BigInt cannot be represented in JSON Schema");
4603
+ };
4604
+ var symbolProcessor = (_schema, ctx, _json, _params) => {
4605
+ if (ctx.unrepresentable === "throw") throw new Error("Symbols cannot be represented in JSON Schema");
4606
+ };
4601
4607
  var nullProcessor = (_schema, ctx, json, _params) => {
4602
4608
  if (ctx.target === "openapi-3.0") {
4603
4609
  json.type = "string";
@@ -4605,12 +4611,17 @@ var nullProcessor = (_schema, ctx, json, _params) => {
4605
4611
  json.enum = [null];
4606
4612
  } else json.type = "null";
4607
4613
  };
4614
+ var undefinedProcessor = (_schema, ctx, _json, _params) => {
4615
+ if (ctx.unrepresentable === "throw") throw new Error("Undefined cannot be represented in JSON Schema");
4616
+ };
4608
4617
  var voidProcessor = (_schema, ctx, _json, _params) => {
4609
4618
  if (ctx.unrepresentable === "throw") throw new Error("Void cannot be represented in JSON Schema");
4610
4619
  };
4611
4620
  var neverProcessor = (_schema, _ctx, json, _params) => {
4612
4621
  json.not = {};
4613
4622
  };
4623
+ var anyProcessor = (_schema, _ctx, _json, _params) => {};
4624
+ var unknownProcessor = (_schema, _ctx, _json, _params) => {};
4614
4625
  var dateProcessor = (_schema, ctx, _json, _params) => {
4615
4626
  if (ctx.unrepresentable === "throw") throw new Error("Date cannot be represented in JSON Schema");
4616
4627
  };
@@ -4642,12 +4653,53 @@ var literalProcessor = (schema, ctx, json, _params) => {
4642
4653
  json.enum = vals;
4643
4654
  }
4644
4655
  };
4656
+ var nanProcessor = (_schema, ctx, _json, _params) => {
4657
+ if (ctx.unrepresentable === "throw") throw new Error("NaN cannot be represented in JSON Schema");
4658
+ };
4659
+ var templateLiteralProcessor = (schema, _ctx, json, _params) => {
4660
+ const _json = json;
4661
+ const pattern = schema._zod.pattern;
4662
+ if (!pattern) throw new Error("Pattern not found in template literal");
4663
+ _json.type = "string";
4664
+ _json.pattern = pattern.source;
4665
+ };
4666
+ var fileProcessor = (schema, _ctx, json, _params) => {
4667
+ const _json = json;
4668
+ const file = {
4669
+ type: "string",
4670
+ format: "binary",
4671
+ contentEncoding: "binary"
4672
+ };
4673
+ const { minimum, maximum, mime } = schema._zod.bag;
4674
+ if (minimum !== void 0) file.minLength = minimum;
4675
+ if (maximum !== void 0) file.maxLength = maximum;
4676
+ if (mime) if (mime.length === 1) {
4677
+ file.contentMediaType = mime[0];
4678
+ Object.assign(_json, file);
4679
+ } else {
4680
+ Object.assign(_json, file);
4681
+ _json.anyOf = mime.map((m) => ({ contentMediaType: m }));
4682
+ }
4683
+ else Object.assign(_json, file);
4684
+ };
4685
+ var successProcessor = (_schema, _ctx, json, _params) => {
4686
+ json.type = "boolean";
4687
+ };
4645
4688
  var customProcessor = (_schema, ctx, _json, _params) => {
4646
4689
  if (ctx.unrepresentable === "throw") throw new Error("Custom types cannot be represented in JSON Schema");
4647
4690
  };
4691
+ var functionProcessor = (_schema, ctx, _json, _params) => {
4692
+ if (ctx.unrepresentable === "throw") throw new Error("Function types cannot be represented in JSON Schema");
4693
+ };
4648
4694
  var transformProcessor = (_schema, ctx, _json, _params) => {
4649
4695
  if (ctx.unrepresentable === "throw") throw new Error("Transforms cannot be represented in JSON Schema");
4650
4696
  };
4697
+ var mapProcessor = (_schema, ctx, _json, _params) => {
4698
+ if (ctx.unrepresentable === "throw") throw new Error("Map cannot be represented in JSON Schema");
4699
+ };
4700
+ var setProcessor = (_schema, ctx, _json, _params) => {
4701
+ if (ctx.unrepresentable === "throw") throw new Error("Set cannot be represented in JSON Schema");
4702
+ };
4651
4703
  var arrayProcessor = (schema, ctx, _json, params) => {
4652
4704
  const json = _json;
4653
4705
  const def = schema._zod.def;
@@ -4852,6 +4904,12 @@ var readonlyProcessor = (schema, ctx, json, params) => {
4852
4904
  seen.ref = def.innerType;
4853
4905
  json.readOnly = true;
4854
4906
  };
4907
+ var promiseProcessor = (schema, ctx, _json, params) => {
4908
+ const def = schema._zod.def;
4909
+ process$1(def.innerType, ctx, params);
4910
+ const seen = ctx.seen.get(schema);
4911
+ seen.ref = def.innerType;
4912
+ };
4855
4913
  var optionalProcessor = (schema, ctx, _json, params) => {
4856
4914
  const def = schema._zod.def;
4857
4915
  process$1(def.innerType, ctx, params);
@@ -4864,6 +4922,81 @@ var lazyProcessor = (schema, ctx, _json, params) => {
4864
4922
  const seen = ctx.seen.get(schema);
4865
4923
  seen.ref = innerType;
4866
4924
  };
4925
+ var allProcessors = {
4926
+ string: stringProcessor,
4927
+ number: numberProcessor,
4928
+ boolean: booleanProcessor,
4929
+ bigint: bigintProcessor,
4930
+ symbol: symbolProcessor,
4931
+ null: nullProcessor,
4932
+ undefined: undefinedProcessor,
4933
+ void: voidProcessor,
4934
+ never: neverProcessor,
4935
+ any: anyProcessor,
4936
+ unknown: unknownProcessor,
4937
+ date: dateProcessor,
4938
+ enum: enumProcessor,
4939
+ literal: literalProcessor,
4940
+ nan: nanProcessor,
4941
+ template_literal: templateLiteralProcessor,
4942
+ file: fileProcessor,
4943
+ success: successProcessor,
4944
+ custom: customProcessor,
4945
+ function: functionProcessor,
4946
+ transform: transformProcessor,
4947
+ map: mapProcessor,
4948
+ set: setProcessor,
4949
+ array: arrayProcessor,
4950
+ object: objectProcessor,
4951
+ union: unionProcessor,
4952
+ intersection: intersectionProcessor,
4953
+ tuple: tupleProcessor,
4954
+ record: recordProcessor,
4955
+ nullable: nullableProcessor,
4956
+ nonoptional: nonoptionalProcessor,
4957
+ default: defaultProcessor,
4958
+ prefault: prefaultProcessor,
4959
+ catch: catchProcessor,
4960
+ pipe: pipeProcessor,
4961
+ readonly: readonlyProcessor,
4962
+ promise: promiseProcessor,
4963
+ optional: optionalProcessor,
4964
+ lazy: lazyProcessor
4965
+ };
4966
+ function toJSONSchema(input, params) {
4967
+ if ("_idmap" in input) {
4968
+ const registry = input;
4969
+ const ctx = initializeContext({
4970
+ ...params,
4971
+ processors: allProcessors
4972
+ });
4973
+ const defs = {};
4974
+ for (const entry of registry._idmap.entries()) {
4975
+ const [_, schema] = entry;
4976
+ process$1(schema, ctx);
4977
+ }
4978
+ const schemas = {};
4979
+ ctx.external = {
4980
+ registry,
4981
+ uri: params?.uri,
4982
+ defs
4983
+ };
4984
+ for (const entry of registry._idmap.entries()) {
4985
+ const [key, schema] = entry;
4986
+ extractDefs(ctx, schema);
4987
+ schemas[key] = finalize(ctx, schema);
4988
+ }
4989
+ if (Object.keys(defs).length > 0) schemas.__shared = { [ctx.target === "draft-2020-12" ? "$defs" : "definitions"]: defs };
4990
+ return { schemas };
4991
+ }
4992
+ const ctx = initializeContext({
4993
+ ...params,
4994
+ processors: allProcessors
4995
+ });
4996
+ process$1(input, ctx);
4997
+ extractDefs(ctx, input);
4998
+ return finalize(ctx, input);
4999
+ }
4867
5000
  //#endregion
4868
5001
  //#region ../../node_modules/zod/v4/classic/iso.js
4869
5002
  var ZodISODateTime = /*@__PURE__*/ $constructor("ZodISODateTime", (inst, def) => {
@@ -5888,7 +6021,7 @@ var ZodIssueCode = {
5888
6021
  var ZodFirstPartyTypeKind;
5889
6022
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
5890
6023
  //#endregion
5891
- //#region ../types/dist/sleep-BkzQdpzF.mjs
6024
+ //#region ../types/dist/sleep-D1jjWAr8.mjs
5892
6025
  /**
5893
6026
  * The audio chunk plane's byte format, and the ONE expansion from a coded
5894
6027
  * window to float samples (D455).
@@ -6036,9 +6169,16 @@ function isSecretMarker(value) {
6036
6169
  const ref = value["$secret"];
6037
6170
  return typeof ref === "string" && ref.length > 0;
6038
6171
  }
6172
+ /** Anything carrying a `$secret` key — a stored marker or a UI view of one. */
6173
+ function isSecretMarkerLike(value) {
6174
+ return isRecord$7(value) && Object.prototype.hasOwnProperty.call(value, "$secret");
6175
+ }
6039
6176
  function isSecretClear(value) {
6040
6177
  return isRecord$7(value) && value["$secretClear"] === true;
6041
6178
  }
6179
+ function isSecretFieldView(value) {
6180
+ return isRecord$7(value) && value["set"] === true && isSecretMarkerLike(value);
6181
+ }
6042
6182
  /**
6043
6183
  * The UI view of a stored secret field value: a marker becomes "set", inline
6044
6184
  * plaintext becomes "set (inline)", nothing becomes `null`. A value never
@@ -6481,7 +6621,7 @@ var NOT_RUN = {
6481
6621
  * throws: an unreachable or refusing engine is logged and reported `declared: false`,
6482
6622
  * because the hub (and this addon's boot) must not hang on a migration.
6483
6623
  */
6484
- async function runAddonMigrations(host, migrations, logger) {
6624
+ async function runAddonMigrations(host, migrations, logger, options = {}) {
6485
6625
  const first = migrations[0];
6486
6626
  if (first === void 0) return NOT_RUN;
6487
6627
  const owner = first.meta.owner;
@@ -6510,7 +6650,9 @@ async function runAddonMigrations(host, migrations, logger) {
6510
6650
  else if (status === "blocked") blocked.push(id);
6511
6651
  else skipped.push(id);
6512
6652
  };
6653
+ const selected = options.only === void 0 ? null : new Set(options.only);
6513
6654
  for (const step of declaration.steps) {
6655
+ if (selected !== null && !selected.has(step.id)) continue;
6514
6656
  const bound = byId.get(step.id);
6515
6657
  if (bound === void 0 || step.action === "skip") {
6516
6658
  skipped.push(step.id);
@@ -6688,11 +6830,36 @@ function projectStore(store, perNodeKeys, nodeId) {
6688
6830
  }
6689
6831
  return out;
6690
6832
  }
6833
+ /**
6834
+ * The address of one keychain value: `secret://<owner>/<scope>/<fieldPath>`.
6835
+ *
6836
+ * A ref is DETERMINISTIC from where the value lives — the owner addon, the
6837
+ * scope (global, one node, one device, one integration, one row of a business
6838
+ * collection) and the field path inside that scope — so saving the same field
6839
+ * twice updates the same ref, and the ref itself says which settings blob
6840
+ * points at it. It is also the AAD of the value's ciphertext: a ciphertext
6841
+ * copied onto another ref does not decrypt.
6842
+ *
6843
+ * Array items are addressed by ITEM ID, never by index
6844
+ * (`providers[authentik].clientSecret`), so reordering a list keeps every ref.
6845
+ *
6846
+ * Pure and browser-safe: no node builtins, no I/O.
6847
+ */
6848
+ /** The URI scheme of every keychain ref. */
6849
+ var SECRET_REF_SCHEME = "secret://";
6691
6850
  var GLOBAL_SCOPE = { kind: "global" };
6692
6851
  /** The scope every addon-wide (not per-node, not per-device) setting lives in. */
6693
6852
  function globalSecretScope() {
6694
6853
  return GLOBAL_SCOPE;
6695
6854
  }
6855
+ /**
6856
+ * An addon id as a ref owner. A hub in-process builtin's context id is
6857
+ * `addon:<id>`; the owner of its secrets is `<id>`, exactly as for the same
6858
+ * addon running forked.
6859
+ */
6860
+ function normalizeSecretOwner(addonId) {
6861
+ return addonId.startsWith("addon:") ? addonId.slice(6) : addonId;
6862
+ }
6696
6863
  function encodeSegment(value) {
6697
6864
  return encodeURIComponent(value);
6698
6865
  }
@@ -6703,6 +6870,16 @@ function decodeSegment(value) {
6703
6870
  return null;
6704
6871
  }
6705
6872
  }
6873
+ /** The scope as it appears inside a ref (`global`, `node/<id>`, …). */
6874
+ function formatSecretScope(scope) {
6875
+ switch (scope.kind) {
6876
+ case "global": return "global";
6877
+ case "node": return `node/${encodeSegment(scope.nodeId)}`;
6878
+ case "device": return `device/${scope.deviceId}`;
6879
+ case "integration": return `integration/${encodeSegment(scope.integrationId)}`;
6880
+ case "row": return `row/${encodeSegment(scope.collection)}/${encodeSegment(scope.rowId)}`;
6881
+ }
6882
+ }
6706
6883
  /**
6707
6884
  * The field path of a value inside an array item, addressed by the item's id:
6708
6885
  * `arrayItemFieldPath('providers', 'authentik', 'clientSecret')` →
@@ -6711,6 +6888,13 @@ function decodeSegment(value) {
6711
6888
  function arrayItemFieldPath(arrayKey, itemId, fieldKey) {
6712
6889
  return `${arrayKey}[${encodeSegment(itemId)}].${fieldKey}`;
6713
6890
  }
6891
+ /** Build a ref. Throws on an empty owner or field path — both are bugs. */
6892
+ function buildSecretRef(parts) {
6893
+ const owner = normalizeSecretOwner(parts.owner);
6894
+ if (owner.length === 0) throw new Error("buildSecretRef: owner is empty");
6895
+ if (parts.fieldPath.length === 0) throw new Error("buildSecretRef: fieldPath is empty");
6896
+ return `${SECRET_REF_SCHEME}${encodeSegment(owner)}/${formatSecretScope(parts.scope)}/${parts.fieldPath}`;
6897
+ }
6714
6898
  function parseScope(segments) {
6715
6899
  switch (segments[0]) {
6716
6900
  case "global": return {
@@ -6851,7 +7035,7 @@ async function writeMembers(ctx, children, incoming, stored, pathOf) {
6851
7035
  for (const [member, node] of children) applyMember(out, member, await writeNode(ctx, node, incoming[member], stored[member], pathOf(member)), stored);
6852
7036
  return out;
6853
7037
  }
6854
- function rowId(row, idKey) {
7038
+ function rowId$1(row, idKey) {
6855
7039
  const raw = row[idKey];
6856
7040
  if (typeof raw === "string" && raw.length > 0) return raw;
6857
7041
  if (typeof raw === "number" && Number.isFinite(raw)) return String(raw);
@@ -6868,7 +7052,7 @@ async function writeArray(ctx, node, incoming, stored, fieldPath) {
6868
7052
  }
6869
7053
  const storedById = /* @__PURE__ */ new Map();
6870
7054
  for (const row of storedRows) {
6871
- const id = rowId(row, node.idKey);
7055
+ const id = rowId$1(row, node.idKey);
6872
7056
  if (id !== null) storedById.set(id, row);
6873
7057
  }
6874
7058
  const kept = /* @__PURE__ */ new Set();
@@ -6878,13 +7062,13 @@ async function writeArray(ctx, node, incoming, stored, fieldPath) {
6878
7062
  rows.push(row);
6879
7063
  continue;
6880
7064
  }
6881
- const id = rowId(row, node.idKey) ?? ctx.mintId();
7065
+ const id = rowId$1(row, node.idKey) ?? ctx.mintId();
6882
7066
  kept.add(id);
6883
7067
  const withId = {
6884
7068
  ...row,
6885
7069
  [node.idKey]: row[node.idKey] ?? id
6886
7070
  };
6887
- if (rowId(withId, node.idKey) === null) withId[node.idKey] = id;
7071
+ if (rowId$1(withId, node.idKey) === null) withId[node.idKey] = id;
6888
7072
  const storedRow = storedById.get(id) ?? {};
6889
7073
  rows.push(await writeMembers(ctx, node.item, withId, storedRow, (member) => arrayItemFieldPath(fieldPath, id, member)));
6890
7074
  }
@@ -7628,14 +7812,18 @@ var BaseAddon = class {
7628
7812
  * nothing; the boot continues. A migration that FAILED (or was blocked by one)
7629
7813
  * and declares `onFailure: 'block-owner'` makes this throw, so the addon does not
7630
7814
  * serve data whose shape it cannot trust; `tolerate` migrations never do.
7815
+ *
7816
+ * ALWAYS pass the whole catalogue; a phase that must run only some of it passes
7817
+ * `{ only: [ids] }` — never a filtered catalogue (the engine would judge the
7818
+ * omitted applied ids "newer").
7631
7819
  */
7632
- async runMigrations(migrations) {
7820
+ async runMigrations(migrations, options) {
7633
7821
  const api = this.ctx.api.migrations;
7634
7822
  const report = await runAddonMigrations({
7635
7823
  declareOwner: (input) => api.declareOwner.mutate(input),
7636
7824
  startMigration: (input) => api.startMigration.mutate(input),
7637
7825
  finishMigration: (input) => api.finishMigration.mutate(input)
7638
- }, migrations, this.ctx.logger);
7826
+ }, migrations, this.ctx.logger, options);
7639
7827
  if (report.blockOwner.length > 0) throw new AddonMigrationsBlockedError(report.blockOwner);
7640
7828
  return report;
7641
7829
  }
@@ -8619,6 +8807,45 @@ function normalizeAddonInitResult(result) {
8619
8807
  if (Array.isArray(result)) return { providers: result };
8620
8808
  return result;
8621
8809
  }
8810
+ var PREFIX = "records/";
8811
+ /** The base of every records failure. `detail` is the human part of the message. */
8812
+ var RecordsError = class extends Error {
8813
+ code;
8814
+ detail;
8815
+ constructor(code, detail) {
8816
+ super(`${PREFIX}${code}: ${detail}`);
8817
+ this.name = "RecordsError";
8818
+ this.code = code;
8819
+ this.detail = detail;
8820
+ }
8821
+ };
8822
+ /** A write guarded by `ifRev` found another revision (or an existing row for `ifRev: 0`). */
8823
+ var RevConflictError = class extends RecordsError {
8824
+ constructor(detail) {
8825
+ super("rev-conflict", detail);
8826
+ this.name = "RevConflictError";
8827
+ }
8828
+ };
8829
+ /** The keychain could not store or serve a value: explicit, never an empty string. */
8830
+ var RecordSecretUnavailableError = class extends RecordsError {
8831
+ constructor(detail) {
8832
+ super("secret-unavailable", detail);
8833
+ this.name = "RecordSecretUnavailableError";
8834
+ }
8835
+ };
8836
+ var InvalidRecordError = class extends RecordsError {
8837
+ constructor(detail) {
8838
+ super("invalid-record", detail);
8839
+ this.name = "InvalidRecordError";
8840
+ }
8841
+ };
8842
+ /** A kind declaration the engine refuses (non-additive change, bad shape, wrong file). */
8843
+ var DeclarationRefusedError = class extends RecordsError {
8844
+ constructor(detail) {
8845
+ super("declaration-refused", detail);
8846
+ this.name = "DeclarationRefusedError";
8847
+ }
8848
+ };
8622
8849
  /** Limits and names of `ctx.records` (D881). One authority; the engine and the facade read it. */
8623
8850
  /** The files a kind may live in. `history` is device-history's (D850), never records. */
8624
8851
  var RECORD_DATABASES = ["settings", "events"];
@@ -8634,6 +8861,174 @@ var RECORD_DEFAULT_MAX_DATA_BYTES = 64 * 1024;
8634
8861
  var RECORD_MAX_DATA_BYTES = 1024 * 1024;
8635
8862
  var RECORD_BATCH_MAX = 1e3;
8636
8863
  var RECORD_QUERY_MAX = 1e3;
8864
+ /** A kind in the `settings` file may not bound itself above this (D447: high volume is `events`). */
8865
+ var RECORD_SETTINGS_MAX_ROWS = 5e4;
8866
+ /** The `Column`-free proof prefix: a ref collection for a kind's secret fields. */
8867
+ var RECORD_SECRET_COLLECTION_PREFIX = "records:";
8868
+ /**
8869
+ * Secret fields of a record, addressed the way a Zod schema declares them
8870
+ * (`collectZodSecretPaths`): dotted keys, `[]` for "each element of this array"
8871
+ * (`auth.accessToken`, `headers[].value`).
8872
+ *
8873
+ * `{}` after a key means "each value of this map" (`applianceSecrets{}`): the map's own key
8874
+ * names the value (`applianceSecrets{fridge}`), so no id key is declared and a body that drops a
8875
+ * key releases exactly that key's secret.
8876
+ *
8877
+ * Array elements are matched by a DECLARED id key (`secretArrayKeys`:
8878
+ * `{ headers: 'name' }`), never by index, so reordering a list keeps every
8879
+ * keychain ref (the same rule as `arrayItemFieldPath`). The concrete path of a
8880
+ * leaf names its element: `headers[X-Api].value`.
8881
+ *
8882
+ * Pure and browser-safe. Nothing here mutates: every transform returns a new value.
8883
+ */
8884
+ /** The array prefixes (declared form, e.g. `headers` or `a.headers`) of a path. */
8885
+ function parseSecretPath(path) {
8886
+ if (path.length === 0) throw new InvalidRecordError("an empty secret path");
8887
+ return path.split(".").map((raw) => {
8888
+ const each = raw.endsWith("[]");
8889
+ const map = raw.endsWith("{}");
8890
+ const key = each || map ? raw.slice(0, -2) : raw;
8891
+ if (key.length === 0) throw new InvalidRecordError(`secret path "${path}" has an empty segment`);
8892
+ return {
8893
+ key,
8894
+ each,
8895
+ map
8896
+ };
8897
+ });
8898
+ }
8899
+ /** The declared array prefixes of `path` that need an id key (`headers`, `a.rows`). */
8900
+ function secretArrayPrefixes(path) {
8901
+ const segments = parseSecretPath(path);
8902
+ const prefixes = [];
8903
+ const walked = [];
8904
+ for (const segment of segments) {
8905
+ walked.push(segment.key);
8906
+ if (segment.each) prefixes.push(walked.join("."));
8907
+ }
8908
+ return prefixes;
8909
+ }
8910
+ function isRecord$4(value) {
8911
+ return typeof value === "object" && value !== null && !Array.isArray(value);
8912
+ }
8913
+ function elementId(element, idKey, declared, prefix) {
8914
+ const id = isRecord$4(element) ? element[idKey] : void 0;
8915
+ 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`);
8916
+ return id;
8917
+ }
8918
+ /**
8919
+ * Visit every secret leaf PRESENT in `data` (an absent branch has nothing to
8920
+ * visit). `replace` returns the new leaf value, or {@link REMOVE_LEAF}; the
8921
+ * result is a new body, `data` is untouched.
8922
+ */
8923
+ var REMOVE_LEAF = Symbol("remove-leaf");
8924
+ function mapAt(node, segments, index, walkedKeys, concretePrefix, declared, arrayKeys, visit) {
8925
+ if (!isRecord$4(node)) return node;
8926
+ const segment = segments[index];
8927
+ if (segment === void 0) return node;
8928
+ if (!Object.prototype.hasOwnProperty.call(node, segment.key)) return node;
8929
+ const child = node[segment.key];
8930
+ const keys = [...walkedKeys, segment.key];
8931
+ const last = index === segments.length - 1;
8932
+ if (segment.each) {
8933
+ if (!Array.isArray(child)) return node;
8934
+ const prefix = keys.join(".");
8935
+ const idKey = arrayKeys[prefix];
8936
+ if (idKey === void 0) throw new InvalidRecordError(`"${declared}": no id key declared for the array "${prefix}"`);
8937
+ const mapped = child.map((element) => {
8938
+ const id = elementId(element, idKey, declared, prefix);
8939
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}[${encodeURIComponent(id)}]`;
8940
+ return last ? element : mapAt(element, segments, index + 1, keys, concrete, declared, arrayKeys, visit);
8941
+ });
8942
+ return {
8943
+ ...node,
8944
+ [segment.key]: mapped
8945
+ };
8946
+ }
8947
+ if (segment.map) {
8948
+ if (!isRecord$4(child)) return node;
8949
+ const kept = Object.entries(child).map(([mapKey, value]) => {
8950
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}{${encodeURIComponent(mapKey)}}`;
8951
+ if (!last) return [mapKey, mapAt(value, segments, index + 1, keys, concrete, declared, arrayKeys, visit)];
8952
+ return [mapKey, visit({
8953
+ declared,
8954
+ concrete,
8955
+ value
8956
+ })];
8957
+ }).filter(([, value]) => value !== REMOVE_LEAF);
8958
+ return {
8959
+ ...node,
8960
+ [segment.key]: Object.fromEntries(kept)
8961
+ };
8962
+ }
8963
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}`;
8964
+ if (last) {
8965
+ const replacement = visit({
8966
+ declared,
8967
+ concrete,
8968
+ value: child
8969
+ });
8970
+ if (replacement === REMOVE_LEAF) return Object.fromEntries(Object.entries(node).filter(([key]) => key !== segment.key));
8971
+ return {
8972
+ ...node,
8973
+ [segment.key]: replacement
8974
+ };
8975
+ }
8976
+ return {
8977
+ ...node,
8978
+ [segment.key]: mapAt(child, segments, index + 1, keys, concrete, declared, arrayKeys, visit)
8979
+ };
8980
+ }
8981
+ /** Replace/remove every present secret leaf; returns a NEW body. */
8982
+ function mapSecretLeaves(data, paths, arrayKeys, visit) {
8983
+ let current = data;
8984
+ for (const declared of paths) current = mapAt(current, parseSecretPath(declared), 0, [], "", declared, arrayKeys, visit);
8985
+ return current;
8986
+ }
8987
+ /**
8988
+ * The keychain collection name a kind's secrets live under. Prefixed so a
8989
+ * record's refs never collide with the refs a legacy collection of the same name
8990
+ * already holds during an adoption.
8991
+ */
8992
+ function recordSecretCollection(kind) {
8993
+ return `${RECORD_SECRET_COLLECTION_PREFIX}${kind}`;
8994
+ }
8995
+ /** The ONE ref a row's secret field may carry: the engine and the facade both build it here. */
8996
+ function recordSecretRef(owner, kind, rowId, concretePath) {
8997
+ return buildSecretRef({
8998
+ owner,
8999
+ scope: {
9000
+ kind: "row",
9001
+ collection: recordSecretCollection(kind),
9002
+ rowId
9003
+ },
9004
+ fieldPath: concretePath
9005
+ });
9006
+ }
9007
+ /**
9008
+ * A stored secret, as an admin read shows it: a VIEW naming the row's own
9009
+ * keychain ref (`set: true`), never the value and no longer the bare redaction
9010
+ * token. The form hands it to the secret field, which reveals the value by ref
9011
+ * through the audited `keychain-admin.reveal`; sent back untouched it keeps the
9012
+ * stored secret (the records door reads a view as KEEP).
9013
+ *
9014
+ * ONE implementation for the entries service and for every addon that serves
9015
+ * its own instances (`RecordIntegrationInstances`).
9016
+ */
9017
+ function isRecord$3(value) {
9018
+ return typeof value === "object" && value !== null && !Array.isArray(value);
9019
+ }
9020
+ function secretViewsOf(owner, kind, id, decl, data) {
9021
+ if (decl.secretPaths.length === 0) return data;
9022
+ const shown = mapSecretLeaves(data, decl.secretPaths, decl.secretArrayKeys, (leaf) => {
9023
+ if (leaf.value !== "__camstack_redacted__") return leaf.value;
9024
+ return {
9025
+ $secret: recordSecretRef(owner, kind, id, leaf.concrete),
9026
+ v: 1,
9027
+ set: true
9028
+ };
9029
+ });
9030
+ return isRecord$3(shown) ? shown : data;
9031
+ }
8637
9032
  /**
8638
9033
  * The share-view scope kinds a share-link token can carry. The hub mints
8639
9034
  * and validates them (`ShareViewGrantSchema` builds its
@@ -8658,6 +9053,75 @@ var PeerBytesTicketSchema = object({
8658
9053
  */
8659
9054
  declaredBytes: number().int().nonnegative().nullable()
8660
9055
  });
9056
+ function defOf(schema) {
9057
+ const zodBag = Reflect.get(schema, "_zod");
9058
+ if (typeof zodBag !== "object" || zodBag === null) return {};
9059
+ const def = Reflect.get(zodBag, "def");
9060
+ if (typeof def !== "object" || def === null) return {};
9061
+ return def;
9062
+ }
9063
+ function declaredHere(schema) {
9064
+ return globalRegistry.get(schema)?.secret === true;
9065
+ }
9066
+ /** Wrapper kinds whose `innerType` is the field itself. */
9067
+ var WRAPPERS = new Set([
9068
+ "optional",
9069
+ "nullable",
9070
+ "default",
9071
+ "prefault",
9072
+ "catch",
9073
+ "readonly",
9074
+ "nonoptional"
9075
+ ]);
9076
+ /**
9077
+ * The schema layers that make up ONE field: the schema itself and every
9078
+ * wrapper below it (optional / default / nullable / readonly / catch), plus
9079
+ * both sides of a pipe (`z.preprocess` puts the real schema on `out`,
9080
+ * `.transform` on `in`).
9081
+ */
9082
+ function layersOf(schema) {
9083
+ const out = [];
9084
+ const queue = [schema];
9085
+ while (queue.length > 0) {
9086
+ const s = queue.shift();
9087
+ if (!s || out.includes(s)) continue;
9088
+ out.push(s);
9089
+ const def = defOf(s);
9090
+ if (def.type !== void 0 && WRAPPERS.has(def.type) && def.innerType) queue.push(def.innerType);
9091
+ if (def.type === "pipe") {
9092
+ if (def.in) queue.push(def.in);
9093
+ if (def.out) queue.push(def.out);
9094
+ }
9095
+ }
9096
+ return out;
9097
+ }
9098
+ /** True when any layer of this field declares `.meta({ secret: true })`. */
9099
+ function isZodSecret(schema) {
9100
+ return layersOf(schema).some(declaredHere);
9101
+ }
9102
+ /**
9103
+ * Every declared secret path in a config schema: dotted keys, `[]` for "each
9104
+ * element of this array" (`connection.password`, `rows[].token`), `{}` for "each value of this
9105
+ * map" (`applianceSecrets{}`). A declared
9106
+ * object or array is reported as one path and not descended into — everything
9107
+ * under it is secret.
9108
+ */
9109
+ function collectZodSecretPaths(schema, prefix = "") {
9110
+ if (isZodSecret(schema)) return prefix.length > 0 ? [prefix] : [];
9111
+ const paths = [];
9112
+ for (const layer of layersOf(schema)) {
9113
+ const def = defOf(layer);
9114
+ if (def.type === "object" && def.shape) for (const [key, child] of Object.entries(def.shape)) paths.push(...collectZodSecretPaths(child, prefix ? `${prefix}.${key}` : key));
9115
+ else if (def.type === "array" && def.element) paths.push(...collectZodSecretPaths(def.element, `${prefix}[]`));
9116
+ else if (def.type === "record" && def.valueType) paths.push(...collectZodSecretPaths(def.valueType, `${prefix}{}`));
9117
+ else if (def.type === "union" && def.options) for (const option of def.options) paths.push(...collectZodSecretPaths(option, prefix));
9118
+ else if (def.type === "intersection") {
9119
+ if (def.left) paths.push(...collectZodSecretPaths(def.left, prefix));
9120
+ if (def.right) paths.push(...collectZodSecretPaths(def.right, prefix));
9121
+ }
9122
+ }
9123
+ return [...new Set(paths)];
9124
+ }
8661
9125
  /**
8662
9126
  * Record kinds (D881): the declaration an addon makes of one kind of fact, the
8663
9127
  * Zod row schema that describes it, and the helper that turns the two into the
@@ -8724,6 +9188,112 @@ var RecordKindDeclarationSchema = object({
8724
9188
  }).strict();
8725
9189
  /** The kind names: lower-case, dash separated, short enough for an index name. */
8726
9190
  var RecordKindNameSchema = string().regex(/^[a-z][a-z0-9-]{0,47}$/);
9191
+ /** Cross-field rules a declaration must satisfy. Throws {@link DeclarationRefusedError}. */
9192
+ function assertValidDeclaration(name, decl) {
9193
+ const refuse = (why) => {
9194
+ throw new DeclarationRefusedError(`kind "${name}": ${why}`);
9195
+ };
9196
+ if (!RecordKindNameSchema.safeParse(name).success) refuse("the name must be lower-case-dashed");
9197
+ const seen = /* @__PURE__ */ new Set();
9198
+ for (const index of decl.indexes) {
9199
+ if (seen.has(index.name)) refuse(`index name "${index.name}" is declared twice`);
9200
+ seen.add(index.name);
9201
+ }
9202
+ const { retention } = decl;
9203
+ const hasSecrets = decl.secretPaths.length > 0;
9204
+ if ("ttlMs" in retention) {
9205
+ if (retention.from === "at" && decl.at !== "required") refuse("a ttl from \"at\" needs at: \"required\"");
9206
+ if (hasSecrets) refuse("a kind with secret fields cannot use engine TTL (its keychain values would be orphaned)");
9207
+ }
9208
+ if ("maxRows" in retention || "maxRowsPerDevice" in retention) {
9209
+ if (retention.maxRowsPerDevice !== void 0 && decl.device !== "required") refuse("maxRowsPerDevice needs device: \"required\"");
9210
+ if (decl.at !== "required") refuse("a row bound trims the oldest \"at\": it needs at: \"required\"");
9211
+ if (hasSecrets) refuse("a kind with secret fields cannot use an engine row bound");
9212
+ const bound = Math.max(retention.maxRows ?? 0, retention.maxRowsPerDevice ?? 0);
9213
+ if (decl.database === "settings" && bound > 5e4) refuse(`a row bound above ${RECORD_SETTINGS_MAX_ROWS} belongs in database: "events" (a big delete on the settings thread stalls every configuration read)`);
9214
+ }
9215
+ if (decl.deviceRemoval === "delete" && decl.device === "none") refuse("deviceRemoval: \"delete\" needs a device: \"required\" or \"optional\"");
9216
+ for (const path of decl.secretPaths) for (const prefix of secretArrayPrefixes(path)) if (decl.secretArrayKeys[prefix] === void 0) refuse(`secret path "${path}" crosses the array "${prefix}": declare its id key in secretArrayKeys`);
9217
+ }
9218
+ function bodyFieldsOf(schema) {
9219
+ return { ...toJSONSchema(schema, {
9220
+ unrepresentable: "any",
9221
+ io: "input"
9222
+ }) };
9223
+ }
9224
+ function isRecordLike(value) {
9225
+ return typeof value === "object" && value !== null && !Array.isArray(value);
9226
+ }
9227
+ /** Does every branch of the body schema carry `field`? (A discriminated union has several.) */
9228
+ function hasNameField(json, field) {
9229
+ const branches = json["oneOf"] ?? json["anyOf"];
9230
+ if (Array.isArray(branches)) return branches.length > 0 && branches.every((b) => isRecordLike(b) && hasNameField(b, field));
9231
+ const properties = json["properties"];
9232
+ return isRecordLike(properties) && Object.prototype.hasOwnProperty.call(properties, field);
9233
+ }
9234
+ /**
9235
+ * Declare the kinds of a package. The keys are the kind names. The result is
9236
+ * what `ctx.records.declare` sends to the engine and what `ctx.records.kind`
9237
+ * types its handle from.
9238
+ */
9239
+ function defineRecordKinds(specs) {
9240
+ const out = {};
9241
+ for (const [name, spec] of Object.entries(specs)) {
9242
+ const secretPaths = collectZodSecretPaths(spec.schema);
9243
+ const nameField = spec.entry?.nameField ?? "name";
9244
+ const fields = bodyFieldsOf(spec.schema);
9245
+ if (spec.entry !== void 0 && !hasNameField(fields, nameField)) throw new DeclarationRefusedError(`kind "${name}": an entry kind's schema needs a "${nameField}" field`);
9246
+ const parsed = RecordKindDeclarationSchema.parse({
9247
+ database: spec.database,
9248
+ class: spec.class,
9249
+ writeTrigger: spec.writeTrigger,
9250
+ device: spec.device,
9251
+ at: spec.at,
9252
+ indexes: spec.indexes === void 0 ? void 0 : [...spec.indexes],
9253
+ retention: spec.retention,
9254
+ deviceRemoval: spec.deviceRemoval,
9255
+ maxDataBytes: spec.maxDataBytes,
9256
+ secretPaths: [...new Set([...secretPaths, ...spec.retiredSecretPaths ?? []])],
9257
+ secretArrayKeys: spec.secretArrayKeys === void 0 ? void 0 : { ...spec.secretArrayKeys },
9258
+ transactFamily: spec.transactFamily,
9259
+ entry: spec.entry === void 0 ? void 0 : {
9260
+ title: spec.entry.title,
9261
+ nameField,
9262
+ fields
9263
+ }
9264
+ });
9265
+ assertValidDeclaration(name, parsed);
9266
+ out[name] = {
9267
+ name,
9268
+ schema: spec.schema,
9269
+ declaration: parsed
9270
+ };
9271
+ }
9272
+ return out;
9273
+ }
9274
+ /**
9275
+ * Declare one entry kind. An entry is configuration: never trimmed by the
9276
+ * engine, never aged, belonging to no device.
9277
+ */
9278
+ function defineEntryKind(name, spec) {
9279
+ const defined = defineRecordKinds({ [name]: {
9280
+ schema: spec.schema,
9281
+ class: "config",
9282
+ writeTrigger: spec.writeTrigger ?? "an operator adds or edits an entry in the entries UI",
9283
+ retention: { none: "an entry goes only when the operator deletes it" },
9284
+ ...spec.maxDataBytes === void 0 ? {} : { maxDataBytes: spec.maxDataBytes },
9285
+ ...spec.database === void 0 ? {} : { database: spec.database },
9286
+ ...spec.indexes === void 0 ? {} : { indexes: spec.indexes },
9287
+ ...spec.secretArrayKeys === void 0 ? {} : { secretArrayKeys: spec.secretArrayKeys },
9288
+ ...spec.retiredSecretPaths === void 0 ? {} : { retiredSecretPaths: spec.retiredSecretPaths },
9289
+ entry: {
9290
+ title: spec.title,
9291
+ ...spec.nameField === void 0 ? {} : { nameField: spec.nameField }
9292
+ }
9293
+ } })[name];
9294
+ if (defined === void 0) throw new DeclarationRefusedError(`entry kind "${name}" was not built`);
9295
+ return defined;
9296
+ }
8727
9297
  object({
8728
9298
  field: string().min(1),
8729
9299
  on: literal("advance")
@@ -9408,6 +9978,28 @@ function toNodeId(idOrRunnerId) {
9408
9978
  const head = idOrRunnerId.split("/")[0];
9409
9979
  return head === void 0 || head.length === 0 ? idOrRunnerId : head;
9410
9980
  }
9981
+ /**
9982
+ * Identity — preserves literal types for downstream inference.
9983
+ *
9984
+ * The constraint is `Record<string, unknown>` (not `CustomActionsSpec`) so
9985
+ * TypeScript does not widen each entry's literal `kind`/`auth` fields to
9986
+ * the broader unions declared on `CustomActionSpec`'s default generics.
9987
+ * Shape validity is enforced separately by the `customAction(...)` helper
9988
+ * whose return type is already a `CustomActionSpec<...>`.
9989
+ */
9990
+ function defineCustomActions(spec) {
9991
+ return spec;
9992
+ }
9993
+ function customAction(input, output, options) {
9994
+ return {
9995
+ input,
9996
+ output,
9997
+ kind: options?.kind ?? "query",
9998
+ auth: options?.auth ?? "protected",
9999
+ scope: options?.scope ?? { kind: "system" },
10000
+ ...options?.caller ? { caller: "required" } : {}
10001
+ };
10002
+ }
9411
10003
  Object.freeze({ "doorbell": "lastPressedAt" });
9412
10004
  /** Every capability name, so addon code can check a name without the schema graph. */
9413
10005
  var CAP_NAMES = Object.freeze([
@@ -11436,7 +12028,7 @@ object({
11436
12028
  params: record(string(), union([string(), number()])).optional()
11437
12029
  });
11438
12030
  //#endregion
11439
- //#region ../types/dist/composition-CRNwcFYY.mjs
12031
+ //#region ../types/dist/composition-pOHbTzRB.mjs
11440
12032
  var AUDIO_ENCODER_BY_CODEC = {
11441
12033
  opus: "libopus",
11442
12034
  aac: "aac",
@@ -13379,6 +13971,205 @@ var IntegrationInstanceRefSchema = object({
13379
13971
  ]),
13380
13972
  candidateStableId: string().optional()
13381
13973
  });
13974
+ /**
13975
+ * `RecordIntegrationInstances` - the `integration-instances` provider over ONE
13976
+ * entry kind, so an addon that holds a connection serves it in ~30 lines.
13977
+ *
13978
+ * Every instance is one record of the addon's own kind, keyed by the
13979
+ * `integrations` registry id. The records door does the secret work: a field the
13980
+ * kind marks `.meta({ secret: true })` is a keychain marker bound to the row, so
13981
+ * deleting the row deletes the secret, and one row's value is never another's.
13982
+ *
13983
+ * Patch rules for a secret (`updateInstance`): omitted, `''`, the redaction
13984
+ * token or the view the form was given KEEP the stored secret;
13985
+ * `{ $secretClear: true }` clears it; any other string replaces it.
13986
+ */
13987
+ /** The most instances one addon lists (an integrations page, not a table). */
13988
+ var INSTANCES_LIST_MAX = 1e3;
13989
+ /** The keys of the kind's secret fields that sit at the top level of the body. */
13990
+ function topLevelSecretKeys(paths) {
13991
+ return new Set(paths.filter((p) => !p.includes(".") && !p.includes("[") && !p.includes("{")));
13992
+ }
13993
+ /** The keys of the kind's top-level MAPS whose values are secrets (`applianceSecrets{}`). */
13994
+ function secretMapKeys(paths) {
13995
+ return new Set(paths.filter((p) => p.endsWith("{}") && !p.slice(0, -2).match(/[.[{]/)).map((p) => p.slice(0, -2)));
13996
+ }
13997
+ /**
13998
+ * A patch value for a map of secrets: an entry that is omitted, `''`, the redaction token or the
13999
+ * view the form was given KEEPS its stored secret (it is left out of the merge); `{ $secretClear }`
14000
+ * or `null` removes the entry; any other string replaces it. Null when nothing is left to merge.
14001
+ */
14002
+ function secretMapPatch(value) {
14003
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
14004
+ const out = {};
14005
+ for (const [key, entry] of Object.entries(value)) if (entry === null || isSecretClear(entry)) out[key] = null;
14006
+ else if (typeof entry === "string" && entry !== "" && entry !== "__camstack_redacted__" && !isSecretFieldView(entry)) out[key] = entry;
14007
+ return Object.keys(out).length > 0 ? out : null;
14008
+ }
14009
+ /** Does the kind's body schema carry an `enabled` field? */
14010
+ function declaresEnabled(kind) {
14011
+ const json = toJSONSchema(kind.schema, {
14012
+ unrepresentable: "any",
14013
+ io: "input"
14014
+ });
14015
+ const properties = Reflect.get(json, "properties");
14016
+ return typeof properties === "object" && properties !== null && "enabled" in properties;
14017
+ }
14018
+ var RecordIntegrationInstances = class {
14019
+ records;
14020
+ kind;
14021
+ hooks;
14022
+ handle;
14023
+ secretKeys;
14024
+ secretMaps;
14025
+ nameField;
14026
+ /** The `integrations` registry owns the on/off switch (`role: devices`); the body has none. */
14027
+ registryOwnsEnabled;
14028
+ constructor(records, kind, hooks) {
14029
+ this.records = records;
14030
+ this.kind = kind;
14031
+ this.hooks = hooks;
14032
+ this.handle = records.kind(kind);
14033
+ this.secretKeys = topLevelSecretKeys(kind.declaration.secretPaths);
14034
+ this.secretMaps = secretMapKeys(kind.declaration.secretPaths);
14035
+ this.nameField = kind.declaration.entry?.nameField ?? "name";
14036
+ this.registryOwnsEnabled = hooks.description.role === "devices";
14037
+ 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"`);
14038
+ }
14039
+ /**
14040
+ * One instance read for the addon's own runtime; null when absent. When the keychain is
14041
+ * locked the row is served WITHOUT its secrets and says so (`secrets: 'unavailable'`), so the
14042
+ * caller can keep what it had instead of reconfiguring with an empty secret (D49).
14043
+ */
14044
+ async readResolved(id) {
14045
+ try {
14046
+ const record = await this.handle.getResolved(id);
14047
+ return record === null ? null : {
14048
+ id,
14049
+ body: record.data,
14050
+ enabled: record.data.enabled !== false,
14051
+ secrets: "resolved"
14052
+ };
14053
+ } catch (err) {
14054
+ if (!(err instanceof RecordSecretUnavailableError)) throw err;
14055
+ const stored = await this.handle.get(id);
14056
+ if (stored === null) return null;
14057
+ return {
14058
+ id,
14059
+ body: Object.fromEntries(Object.entries(stored.data).filter(([key]) => !this.secretKeys.has(key))),
14060
+ enabled: stored.data.enabled !== false,
14061
+ secrets: "unavailable"
14062
+ };
14063
+ }
14064
+ }
14065
+ /** The body of {@link readResolved} alone; a locked keychain yields the row without secrets. */
14066
+ async getResolved(id) {
14067
+ return (await this.readResolved(id))?.body ?? null;
14068
+ }
14069
+ /** Every instance, secrets resolved where the keychain allows; an absent one is skipped. */
14070
+ async listResolved() {
14071
+ const page = await this.handle.query({ limit: INSTANCES_LIST_MAX });
14072
+ const out = [];
14073
+ for (const record of page.records) {
14074
+ const read = await this.readResolved(record.id);
14075
+ if (read !== null) out.push(read);
14076
+ }
14077
+ return out;
14078
+ }
14079
+ viewOf(record) {
14080
+ const shown = secretViewsOf(this.records.owner, this.kind.name, record.id, this.kind.declaration, record.data);
14081
+ const rawName = record.data[this.nameField];
14082
+ const kind = this.hooks.kindOf?.(record.data);
14083
+ const health = this.hooks.health?.(record.data, record.id);
14084
+ return {
14085
+ id: record.id,
14086
+ name: typeof rawName === "string" ? rawName : record.id,
14087
+ configured: this.hooks.configured(record.data),
14088
+ ...this.registryOwnsEnabled ? {} : { enabled: record.data.enabled !== false },
14089
+ formValues: shown,
14090
+ ...kind !== void 0 ? { kind } : {},
14091
+ ...health?.status !== void 0 ? { status: health.status } : {},
14092
+ ...health?.lastCheckedAt !== void 0 ? { lastCheckedAt: health.lastCheckedAt } : {}
14093
+ };
14094
+ }
14095
+ describe = async () => this.hooks.mintId === void 0 ? this.hooks.description : {
14096
+ ...this.hooks.description,
14097
+ mintsId: true
14098
+ };
14099
+ instanceFormSchema = async ({ id }) => this.hooks.formSchema(id);
14100
+ listInstances = async () => {
14101
+ return (await this.handle.query({ limit: INSTANCES_LIST_MAX })).records.map((record) => this.viewOf(record));
14102
+ };
14103
+ getInstance = async ({ id }) => {
14104
+ const record = await this.handle.get(id);
14105
+ return record === null ? null : this.viewOf(record);
14106
+ };
14107
+ /** Insert ONE row (`ifRev: 0`: an existing id is refused, never overwritten). */
14108
+ createInstance = async ({ id, name, kind }) => {
14109
+ const minted = id ?? this.hooks.mintId?.({
14110
+ name,
14111
+ ...kind !== void 0 ? { kind } : {}
14112
+ });
14113
+ if (minted === void 0) throw new Error("createInstance needs an id: this provider does not mint one");
14114
+ await this.handle.put({
14115
+ id: minted,
14116
+ data: this.hooks.initialBody(name, kind)
14117
+ }, { ifRev: 0 });
14118
+ await this.hooks.onChanged?.(minted, "created");
14119
+ return { id: minted };
14120
+ };
14121
+ updateInstance = async ({ id, name, values }) => {
14122
+ const patch = {};
14123
+ for (const [key, value] of Object.entries(values)) {
14124
+ if (value === void 0) continue;
14125
+ if (this.secretMaps.has(key)) {
14126
+ const entries = secretMapPatch(value);
14127
+ if (entries !== null) patch[key] = entries;
14128
+ } else if (!this.secretKeys.has(key)) patch[key] = value;
14129
+ else if (isSecretClear(value)) patch[key] = null;
14130
+ else if (typeof value === "string" && value !== "" && value !== "__camstack_redacted__" && !isSecretFieldView(value)) patch[key] = value;
14131
+ }
14132
+ if (name !== void 0) patch[this.nameField] = name;
14133
+ await this.handle.patch(id, patch);
14134
+ await this.hooks.onChanged?.(id, "updated");
14135
+ return { ok: true };
14136
+ };
14137
+ /** The switch lives in the record body; the addon is told so it applies it (D996). */
14138
+ setInstanceEnabled = async ({ id, enabled }) => {
14139
+ if (this.registryOwnsEnabled) throw new Error(`instance "${id}": the integrations registry owns the on/off switch of this addon; set it with integrations.update`);
14140
+ await this.handle.patch(id, { enabled });
14141
+ await this.hooks.onChanged?.(id, "enabled");
14142
+ return { ok: true };
14143
+ };
14144
+ /** The row and its keychain refs go together (the records door). */
14145
+ deleteInstance = async ({ id }) => {
14146
+ await this.handle.delete(id);
14147
+ await this.hooks.onChanged?.(id, "deleted");
14148
+ return { ok: true };
14149
+ };
14150
+ testInstance = async (input) => {
14151
+ if (this.hooks.test === void 0) return {
14152
+ success: false,
14153
+ status: "unsupported",
14154
+ error: "This integration declares no connection test"
14155
+ };
14156
+ return this.hooks.test(input);
14157
+ };
14158
+ /** The flat provider object to hand to `registerProvider`. */
14159
+ toProvider() {
14160
+ return {
14161
+ describe: this.describe,
14162
+ instanceFormSchema: this.instanceFormSchema,
14163
+ listInstances: this.listInstances,
14164
+ getInstance: this.getInstance,
14165
+ createInstance: this.createInstance,
14166
+ updateInstance: this.updateInstance,
14167
+ setInstanceEnabled: this.setInstanceEnabled,
14168
+ deleteInstance: this.deleteInstance,
14169
+ testInstance: this.testInstance
14170
+ };
14171
+ }
14172
+ };
13382
14173
  var EncodeProfileSchema = object({
13383
14174
  video: object({
13384
14175
  codec: _enum([
@@ -14494,7 +15285,13 @@ var MigrationLedgerEntrySchema = object({
14494
15285
  * joined by the engine from the catalogues it knows this boot. Absent when no
14495
15286
  * catalogue lists the id (a newer database).
14496
15287
  */
14497
- meta: MigrationMetaSchema.optional()
15288
+ meta: MigrationMetaSchema.optional(),
15289
+ /**
15290
+ * Set when this is an applied row of an addon owner whose catalogue the answering
15291
+ * process has not loaded (the owner has not declared yet): the row is applied, the
15292
+ * process just cannot judge it. Never `skipped-newer` — that needs the owner loaded.
15293
+ */
15294
+ ownerNotLoaded: boolean().optional()
14498
15295
  });
14499
15296
  /** A catalogued migration that is not applied, with where it stands. */
14500
15297
  var MigrationPendingEntrySchema = object({
@@ -49242,6 +50039,9 @@ var RunningProposalEvidenceSchema = object({
49242
50039
  runsFound: number().int().nonnegative(),
49243
50040
  pausesFound: number().int().nonnegative(),
49244
50041
  longestPauseMs: number().nonnegative(),
50042
+ /** Episodes shorter than ~90 s (an anti-crease pulse, a display waking): never a run, never a pause. */
50043
+ pulsesFound: number().int().nonnegative(),
50044
+ longestPulseMs: number().nonnegative(),
49245
50045
  idleFloorW: number(),
49246
50046
  noiseCeilingW: number(),
49247
50047
  plateauW: number(),
@@ -50468,13 +51268,6 @@ var ExportInstanceUnknownError = class extends Error {
50468
51268
  function statusInstanceOf(input) {
50469
51269
  return "instanceId" in input ? input.instanceId : void 0;
50470
51270
  }
50471
- /**
50472
- * A single-instance provider's check: an absent id or its own passes, any other throws
50473
- * `ExportInstanceUnknownError`.
50474
- */
50475
- function assertOwnExportInstance(addon, own, instanceId) {
50476
- if (instanceId !== void 0 && instanceId !== own) throw new ExportInstanceUnknownError(addon, instanceId);
50477
- }
50478
51271
  var LinkStateSchema = _enum([
50479
51272
  "unlinked",
50480
51273
  "linked",
@@ -54326,6 +55119,12 @@ method(_void(), array(IntegrationWithStateSchema)), method(object({ id: string()
54326
55119
  }), object({ success: boolean() }), {
54327
55120
  kind: "mutation",
54328
55121
  auth: "admin"
55122
+ }), method(object({ id: string() }), object({
55123
+ rows: number().int().nonnegative(),
55124
+ secrets: number().int().nonnegative()
55125
+ }), {
55126
+ kind: "mutation",
55127
+ auth: "admin"
54329
55128
  }), method(_void(), array(AvailableIntegrationTypeSchema), { auth: "admin" }), method(object({
54330
55129
  addonId: string(),
54331
55130
  settings: record(string(), unknown())
@@ -54377,6 +55176,21 @@ var IntegrationInstanceKindSchema = object({
54377
55176
  disconnectPath: string().min(1).optional()
54378
55177
  });
54379
55178
  var IntegrationInstanceDescriptionSchema = object({
55179
+ /** What the instances are for the Integrations page; see {@link IntegrationInstanceRoleSchema}. */
55180
+ role: _enum([
55181
+ "devices",
55182
+ "services",
55183
+ "both"
55184
+ ]),
55185
+ /** How the devices of an instance are found; absent means `{ mode: 'none' }`. */
55186
+ discovery: object({
55187
+ mode: _enum([
55188
+ "none",
55189
+ "lan",
55190
+ "account"
55191
+ ]),
55192
+ scopedToInstance: boolean()
55193
+ }).optional(),
54380
55194
  /** `single`: at most one instance can exist (Loki). `multiple`: an account each. */
54381
55195
  instanceMode: IntegrationInstanceModeSchema,
54382
55196
  /** What the instance is, for the UI (`destination`, `relay`, `account`). */
@@ -54416,10 +55230,11 @@ var IntegrationInstanceSchema = object({
54416
55230
  /** The addon's own rule (an URL is present, a client id is present...). */
54417
55231
  configured: boolean(),
54418
55232
  /**
54419
- * The instance's own on/off switch (D996): always present, derived from the record body
54420
- * (`enabled !== false`, so a row written before the field existed is on).
55233
+ * The instance's own on/off switch (D996), derived from the record body (`enabled !== false`,
55234
+ * so a row written before the field existed is on). Absent when the `integrations` registry
55235
+ * owns the switch (`describe().role` is `devices`): read it from the registry row.
54421
55236
  */
54422
- enabled: boolean(),
55237
+ enabled: boolean().optional(),
54423
55238
  /** The kind of this instance (one of `describe().kinds[].id`), when the provider has kinds. */
54424
55239
  kind: string().optional(),
54425
55240
  /** Values for the instance form; a secret is a `SecretFieldView`, never text. */
@@ -54434,32 +55249,57 @@ var IntegrationInstancePatchSchema = object({
54434
55249
  /** Omitted / '' / redaction token keeps a secret; `{ $secretClear: true }` clears it. */
54435
55250
  values: record(string(), unknown())
54436
55251
  });
54437
- method(_void(), IntegrationInstanceDescriptionSchema, { auth: "admin" }), method(object({ id: IntegrationInstanceIdSchema.nullable() }), ConfigSchemaPassthrough$3, { auth: "admin" }), method(_void(), array(IntegrationInstanceSchema).readonly(), { auth: "admin" }), method(object({ id: IntegrationInstanceIdSchema }), IntegrationInstanceSchema.nullable(), { auth: "admin" }), method(object({
54438
- id: IntegrationInstanceIdSchema.optional(),
54439
- name: string().min(1),
54440
- kind: string().min(1).optional()
54441
- }), object({ id: string() }), {
54442
- kind: "mutation",
54443
- auth: "admin"
54444
- }), method(IntegrationInstancePatchSchema, object({ ok: literal(true) }), {
54445
- kind: "mutation",
54446
- auth: "admin"
54447
- }), method(object({
54448
- id: IntegrationInstanceIdSchema,
54449
- enabled: boolean()
54450
- }), object({ ok: literal(true) }), {
54451
- kind: "mutation",
54452
- auth: "admin"
54453
- }), method(object({ id: IntegrationInstanceIdSchema }), object({ ok: literal(true) }), {
54454
- kind: "mutation",
54455
- auth: "admin"
54456
- }), optionalMethod(object({
54457
- id: IntegrationInstanceIdSchema.nullable(),
54458
- values: record(string(), unknown())
54459
- }), TestConnectionResultSchema$1, {
54460
- kind: "mutation",
54461
- auth: "admin"
54462
- });
55252
+ var integrationInstancesCapability = {
55253
+ name: "integration-instances",
55254
+ scope: "system",
55255
+ mode: "collection",
55256
+ methods: {
55257
+ describe: method(_void(), IntegrationInstanceDescriptionSchema, { auth: "admin" }),
55258
+ /** The form; `id: null` is the create form. */
55259
+ instanceFormSchema: method(object({ id: IntegrationInstanceIdSchema.nullable() }), ConfigSchemaPassthrough$3, { auth: "admin" }),
55260
+ listInstances: method(_void(), array(IntegrationInstanceSchema).readonly(), { auth: "admin" }),
55261
+ getInstance: method(object({ id: IntegrationInstanceIdSchema }), IntegrationInstanceSchema.nullable(), { auth: "admin" }),
55262
+ /**
55263
+ * Insert the typed record. With `id` it is stored under that id (a duplicate id is refused);
55264
+ * without one the PROVIDER mints it and answers it. `kind` picks one of `describe().kinds`.
55265
+ */
55266
+ createInstance: method(object({
55267
+ id: IntegrationInstanceIdSchema.optional(),
55268
+ name: string().min(1),
55269
+ kind: string().min(1).optional()
55270
+ }), object({ id: string() }), {
55271
+ kind: "mutation",
55272
+ auth: "admin"
55273
+ }),
55274
+ updateInstance: method(IntegrationInstancePatchSchema, object({ ok: literal(true) }), {
55275
+ kind: "mutation",
55276
+ auth: "admin"
55277
+ }),
55278
+ /**
55279
+ * Switch ONE instance on or off. A row control, not a form field: `updateInstance.values` is the
55280
+ * form patch (D62, D996). An off instance keeps its record and secrets and does no work.
55281
+ */
55282
+ setInstanceEnabled: method(object({
55283
+ id: IntegrationInstanceIdSchema,
55284
+ enabled: boolean()
55285
+ }), object({ ok: literal(true) }), {
55286
+ kind: "mutation",
55287
+ auth: "admin"
55288
+ }),
55289
+ /** Delete the record and its keychain refs together. */
55290
+ deleteInstance: method(object({ id: IntegrationInstanceIdSchema }), object({ ok: literal(true) }), {
55291
+ kind: "mutation",
55292
+ auth: "admin"
55293
+ }),
55294
+ testInstance: optionalMethod(object({
55295
+ id: IntegrationInstanceIdSchema.nullable(),
55296
+ values: record(string(), unknown())
55297
+ }), TestConnectionResultSchema$1, {
55298
+ kind: "mutation",
55299
+ auth: "admin"
55300
+ })
55301
+ }
55302
+ };
54463
55303
  /**
54464
55304
  * Two-way audio / talk-back cap. Clients open a WebRTC audio-only
54465
55305
  * session (server-initiated offer pattern, identical to the main
@@ -76384,11 +77224,15 @@ discriminatedUnion("kind", [object({
76384
77224
  * 1. idle floor F = time-weighted median; noise ceiling N = highest value seen
76385
77225
  * near F. A device that is not near one level most of the time has no floor.
76386
77226
  * 2. coarse activity = above max(2N, N + 5 W); consecutive stretches are episodes.
76387
- * 3. gaps between episodes split in two by the largest log-scale jump (>= 3x):
76388
- * the short ones are pauses INSIDE a run (a soak), the long ones separate runs.
77227
+ * 3. an episode shorter than `PULSE_MAX_MS` is a PULSE (an anti-crease tumble, a
77228
+ * display waking): it is neither a run nor a pause. Among the remaining
77229
+ * episodes, gaps over `PAUSE_MAX_MS` always separate runs; the rest split in
77230
+ * two by the largest log-scale jump (>= 3x): the short ones are pauses INSIDE
77231
+ * a run (a soak), the long ones separate runs. A stretch under `MIN_RUN_MS`
77232
+ * is no run.
76389
77233
  * 4. T = geometric mean of N and the plateau's 10th percentile, snapped to a
76390
- * grid a person would type; stop dwell covers the longest pause; start dwell
76391
- * covers the longest standby blip above T.
77234
+ * grid a person would type; stop dwell covers the longest pause and the
77235
+ * kind's floor; start dwell covers the longest pulse and standby blip above T.
76392
77236
  * 5. the numbers are proved by REPLAY through the real `dwell` evaluation: each
76393
77237
  * run must hold exactly one true interval and nothing may flap outside.
76394
77238
  */
@@ -76399,6 +77243,10 @@ var MINUTE_MS$1 = 60 * SECOND_MS;
76399
77243
  30 * SECOND_MS;
76400
77244
  60 * SECOND_MS;
76401
77245
  20 * MINUTE_MS$1;
77246
+ 90 * SECOND_MS;
77247
+ 30 * MINUTE_MS$1;
77248
+ 10 * MINUTE_MS$1;
77249
+ DeviceType.Dryer, 3 * MINUTE_MS$1, DeviceType.Dishwasher, 3 * MINUTE_MS$1, DeviceType.Washer, 10 * MINUTE_MS$1;
76402
77250
  10 * SECOND_MS;
76403
77251
  10 * SECOND_MS;
76404
77252
  DeviceFeature.FanSpeed, DeviceFeature.FanPreset, DeviceFeature.FanDirection, DeviceFeature.FanOscillating, DeviceFeature.CoverStoppable, DeviceFeature.CoverPositionable, DeviceFeature.CoverTilt, DeviceFeature.ValvePositionable, DeviceFeature.MediaPlayerVolume, DeviceFeature.ClimateFanMode;
@@ -80119,6 +80967,13 @@ Object.freeze({
80119
80967
  access: "create",
80120
80968
  role: "admin"
80121
80969
  },
80970
+ "integrations.clearSettings": {
80971
+ capName: "integrations",
80972
+ capScope: "system",
80973
+ addonId: null,
80974
+ access: "delete",
80975
+ role: "admin"
80976
+ },
80122
80977
  "integrations.create": {
80123
80978
  capName: "integrations",
80124
80979
  capScope: "system",
@@ -91437,6 +92292,17 @@ object({
91437
92292
  delay: number().nonnegative().optional(),
91438
92293
  commands: record(string(), unknown())
91439
92294
  });
92295
+ //#endregion
92296
+ //#region src/custom-actions.ts
92297
+ /**
92298
+ * HomeKit Export — customActions catalog. `regenerateBridge` is the instance form's
92299
+ * "Regenerate setup code" button (`addon-action-button`, `paramsStatic.instanceId`); admin only,
92300
+ * because it unpairs every controller of the bridge.
92301
+ */
92302
+ var exportHapActions = defineCustomActions({ regenerateBridge: customAction(object({ instanceId: string().min(1) }), object({ regenerated: boolean() }), {
92303
+ kind: "mutation",
92304
+ auth: "admin"
92305
+ }) });
91440
92306
  process.platform, process.env["SystemRoot"];
91441
92307
  var DEFAULT_FIRST_UNIT_TIMEOUT_MS = 12e3;
91442
92308
  /** Heartbeat cadence — ~2 minutes of 4 s fragments. */
@@ -138336,14 +139202,60 @@ function clearPairingFiles(accessoryUuid, logger) {
138336
139202
  } });
138337
139203
  }
138338
139204
  }
139205
+ //#endregion
139206
+ //#region src/hap-instance-kinds.ts
139207
+ /**
139208
+ * The HomeKit export's instances as records (D985, D996): one `hap-bridges` row per bridge
139209
+ * identity, owned by `export-hap`. A row IS what a paired controller knows the bridge by: the
139210
+ * MAC-style `username`, the bridge `uuid` and the setup code (`pincode`, a keychain marker bound to
139211
+ * the row). The directory its pairing state lives in is derived from the id, never stored
139212
+ * (`hapPersistDirOf`). The default instance is keyed by the
139213
+ * addon id and ADOPTS the identity the addon held in its settings, byte for byte, so a
139214
+ * controller that paired before keeps working.
139215
+ */
139216
+ /** The default instance keeps its record under the addon id (it adopted the old identity). */
139217
+ var HAP_DEFAULT_INSTANCE_ID = "export-hap";
139218
+ /**
139219
+ * What an instance adds to the identity seed of every accessory it publishes. EMPTY for the
139220
+ * default instance (and for no instance at all), which keeps the legacy seed byte for byte so no
139221
+ * paired controller has to pair again; any other instance is salted with its id, so one camera
139222
+ * exposed by two bridges is two different HomeKit accessories, never one colliding MAC.
139223
+ */
139224
+ function instanceSalt(instanceId) {
139225
+ return instanceId === void 0 || instanceId === "export-hap" ? "" : `:instance:${instanceId}`;
139226
+ }
139227
+ /** Where the pairing state of the default instance has always lived, under the addon data dir. */
139228
+ var HAP_DEFAULT_PERSIST_DIR = "hap-store";
139229
+ /** The pairing-state directory of an instance, relative to the addon data dir: derived, not stored. */
139230
+ function hapPersistDirOf(instanceId) {
139231
+ return instanceId === "export-hap" ? HAP_DEFAULT_PERSIST_DIR : `hap-store-${instanceId}`;
139232
+ }
139233
+ var hapBridgesKind = defineEntryKind("hap-bridges", {
139234
+ title: "HomeKit bridge",
139235
+ nameField: "name",
139236
+ schema: object({
139237
+ name: string().min(1),
139238
+ username: string().min(1),
139239
+ uuid: string().min(1),
139240
+ pincode: string().min(1).meta({ secret: true }),
139241
+ enabled: boolean().optional()
139242
+ })
139243
+ });
139244
+ function identityOfBody(body) {
139245
+ return {
139246
+ username: body.username,
139247
+ uuid: body.uuid,
139248
+ pincode: body.pincode
139249
+ };
139250
+ }
138339
139251
  /** Deterministic and distinct from every device accessory uuid. */
138340
- function actionSwitchUuid(actionId) {
138341
- return import_dist.uuid.generate(`camstack:hap:action:${actionId}`);
139252
+ function actionSwitchUuid(actionId, instanceId) {
139253
+ return import_dist.uuid.generate(`camstack:hap:action:${actionId}${instanceSalt(instanceId)}`);
138342
139254
  }
138343
139255
  function buildActionSwitch(input) {
138344
139256
  const { actionId, displayName, run } = input;
138345
139257
  const autoOffMs = input.autoOffMs ?? 1e3;
138346
- const accessory = new import_dist.Accessory(displayName, actionSwitchUuid(actionId));
139258
+ const accessory = new import_dist.Accessory(displayName, actionSwitchUuid(actionId, input.instanceId));
138347
139259
  accessory.category = import_dist.Categories.SWITCH;
138348
139260
  const info = accessory.getService(import_dist.Service.AccessoryInformation);
138349
139261
  info?.setCharacteristic(import_dist.Characteristic.Manufacturer, "CamStack");
@@ -138417,6 +139329,10 @@ var ActionExports = class {
138417
139329
  exposedAs: e.displayName
138418
139330
  }));
138419
139331
  }
139332
+ /** Every accessory currently published for an action (to wipe their pairing state). */
139333
+ accessoryUuids() {
139334
+ return [...this.mappers.values()].flatMap((m) => m.accessories.map((a) => a.UUID));
139335
+ }
138420
139336
  /** Re-publish the persisted selection (boot). One failure does not stop the rest. */
138421
139337
  async attachAll() {
138422
139338
  for (const entry of this.entries) try {
@@ -138484,6 +139400,7 @@ var ActionExports = class {
138484
139400
  const mapper = buildActionSwitch({
138485
139401
  actionId: entry.actionId,
138486
139402
  displayName: entry.displayName,
139403
+ instanceId: this.ports.instanceId,
138487
139404
  run: async () => {
138488
139405
  await runExportedAction(this.ports.api, this.ports.logger, {
138489
139406
  exporter: EXPORTER,
@@ -138624,6 +139541,128 @@ var BridgeHost = class {
138624
139541
  }
138625
139542
  };
138626
139543
  //#endregion
139544
+ //#region src/mappers/kind.ts
139545
+ /**
139546
+ * Which orchestrator a device gets, which device types the picker offers, and
139547
+ * what a device's HomeKit accessory is called on the wire.
139548
+ *
139549
+ * Separate from `index.ts` (the factory registry) only so the orchestrators can
139550
+ * import the uuid convention without importing the registry that imports them.
139551
+ */
139552
+ var SUPPORTED_MAPPER_KINDS = ["camera", "generic"];
139553
+ /**
139554
+ * The device types the Export picker offers, and the answer to the cap's
139555
+ * `listSupportedDeviceKinds`.
139556
+ *
139557
+ * A UI FILTER, nothing more. Whether a device actually exports anything is
139558
+ * decided by its capabilities (`rowsForCaps` in the capability table) — the
139559
+ * doctrine the HA exporter writes down, and the thing that confined the
139560
+ * previous exporter to cameras when it was ignored.
139561
+ *
139562
+ * Tier A plus `alarm-panel`: the types whose HomeKit services exist today and
139563
+ * need no feature-dependent shape. `cover`, `climate`, `fan`, `valve`,
139564
+ * `humidifier`, `water-heater`, `button` and `media-player` are deliberately
139565
+ * absent — each needs a service whose semantics the table cannot yet honour,
139566
+ * and offering the tab before the mapping exists is how an operator gets an
139567
+ * accessory that pairs and does nothing.
139568
+ *
139569
+ * `alarm-panel` is no longer one of them. It maps to `Service.SecuritySystem`
139570
+ * (`builders/generic/security-system.ts`), and the two things the table could
139571
+ * not previously honour are now honoured explicitly: HomeKit is only ever
139572
+ * offered the arm modes the panel accepts, and a panel that requires a PIN
139573
+ * refuses the write out loud instead of pretending to arm.
139574
+ */
139575
+ var HAP_EXPORTABLE_DEVICE_TYPES = [
139576
+ DeviceType.Camera,
139577
+ DeviceType.Light,
139578
+ DeviceType.Switch,
139579
+ DeviceType.Siren,
139580
+ DeviceType.Sensor,
139581
+ DeviceType.Lock,
139582
+ DeviceType.Presence,
139583
+ DeviceType.AlarmPanel,
139584
+ DeviceType.Generic
139585
+ ];
139586
+ /**
139587
+ * Resolve the orchestrator for a device from its TYPE.
139588
+ *
139589
+ * `null` means "no Export tab": the picker must not offer a type no
139590
+ * orchestrator can build. An UNKNOWN type (the device-manager read failed) maps
139591
+ * to `camera` — that is what every entry persisted before this function existed
139592
+ * carries, and a transient API failure must never re-shape an exposed camera.
139593
+ */
139594
+ function pickMapperKind(deviceType) {
139595
+ if (deviceType === null || deviceType === void 0 || deviceType.length === 0) return "camera";
139596
+ if (deviceType === DeviceType.Camera) return "camera";
139597
+ const withheld = applianceExport("homekit", deviceType);
139598
+ if (withheld !== null && !withheld.exported) return null;
139599
+ return HAP_EXPORTABLE_DEVICE_TYPES.find((type) => type === deviceType) === void 0 ? null : "generic";
139600
+ }
139601
+ /**
139602
+ * The deterministic HAP accessory UUID for a device.
139603
+ *
139604
+ * One function, because three call sites depend on the answer agreeing: the
139605
+ * orchestrator that builds the accessory, `unexposeDevice` (which wipes
139606
+ * hap-nodejs' pairing blobs by uuid, on a device whose mapper is already gone)
139607
+ * and the export sync state that records it.
139608
+ *
139609
+ * The camera namespace is FROZEN — every camera paired to date derives its MAC
139610
+ * from `sha256("camstack:hap:" + uuid)` of this exact string, and changing it
139611
+ * would make every paired camera a stranger. Generic devices get their own
139612
+ * namespace so a switch and a camera that happen to share a device id are not
139613
+ * the same HomeKit accessory.
139614
+ */
139615
+ function accessoryUuidFor(kind, deviceId, instanceId) {
139616
+ const seed = kind === "camera" ? `camstack:camera:${deviceId}` : `camstack:device:${deviceId}`;
139617
+ return import_dist.uuid.generate(`${seed}${instanceSalt(instanceId)}`);
139618
+ }
139619
+ //#endregion
139620
+ //#region src/bridge-instance.ts
139621
+ var BridgeInstance = class {
139622
+ id;
139623
+ name;
139624
+ identity;
139625
+ bridgeHost;
139626
+ exposure;
139627
+ /** The devices of this bridge that have a live accessory, by device id. */
139628
+ exposed = /* @__PURE__ */ new Map();
139629
+ /** Pending rebuild timers per device id: debounce, cleared on detach. */
139630
+ pendingRebuildTimers = /* @__PURE__ */ new Map();
139631
+ actionExports = null;
139632
+ /** Last advertised export fingerprints (the reconcile cache) of a NON-default bridge; the default one persists its own. */
139633
+ syncState = /* @__PURE__ */ new Map();
139634
+ constructor(id, name, identity, bridgeHost, exposure) {
139635
+ this.id = id;
139636
+ this.name = name;
139637
+ this.identity = identity;
139638
+ this.bridgeHost = bridgeHost;
139639
+ this.exposure = exposure;
139640
+ }
139641
+ get pincode() {
139642
+ return this.identity.pincode;
139643
+ }
139644
+ findEntry(deviceId) {
139645
+ const id = String(deviceId);
139646
+ return this.exposure.devices.find((e) => e.deviceId === id) ?? null;
139647
+ }
139648
+ /** The HAP accessory uuid this bridge gives a device (`accessoryUuidFor`, salted per bridge). */
139649
+ accessoryUuidOf(kind, deviceId) {
139650
+ return accessoryUuidFor(kind, deviceId, this.id);
139651
+ }
139652
+ /**
139653
+ * Every accessory uuid whose pairing state belongs to this bridge: the bridge itself, each live
139654
+ * accessory of a device and each exported action. What a Regenerate or a delete must wipe.
139655
+ */
139656
+ pairingUuids() {
139657
+ const fromDevices = [...this.exposed.values()].flatMap((m) => m.accessories.map((a) => a.UUID));
139658
+ return [
139659
+ this.identity.uuid,
139660
+ ...fromDevices,
139661
+ ...this.actionExports?.accessoryUuids() ?? []
139662
+ ];
139663
+ }
139664
+ };
139665
+ //#endregion
138627
139666
  //#region src/exposed-entry.ts
138628
139667
  /**
138629
139668
  * Carrying an exposed-device entry across a re-expose.
@@ -138661,6 +139700,83 @@ function carryForward(base, existing, keys) {
138661
139700
  return out;
138662
139701
  }
138663
139702
  //#endregion
139703
+ //#region src/hap-export-records.ts
139704
+ /**
139705
+ * What one HomeKit bridge exposes (D985, D996): a `hap-bridge-exports` row per bridge instance,
139706
+ * under the instance's own id, holds the devices it mirrors (with their per-device export
139707
+ * settings) and the actions it publishes as momentary switches. The identity a controller pairs
139708
+ * with is the sibling `hap-bridges` row; this row is what that bridge CARRIES.
139709
+ *
139710
+ * It replaces the `exposed` and `exposedActions` addon settings. The migration moved them; the
139711
+ * addon reads this record and nothing else.
139712
+ */
139713
+ var ExportDeviceSettingsSchema = object({
139714
+ multiTierService: boolean().optional(),
139715
+ streamPreference: string(),
139716
+ useBridge: boolean().optional(),
139717
+ allowTranscode: boolean().optional(),
139718
+ keepClips: boolean().optional(),
139719
+ clipRetentionDays: number().optional()
139720
+ });
139721
+ var MapperKindSchema = _enum(["camera", "generic"]);
139722
+ var ExposedConfigEntrySchema = object({
139723
+ deviceId: string(),
139724
+ displayName: string(),
139725
+ mapperKind: MapperKindSchema,
139726
+ capabilities: array(string()).optional(),
139727
+ childAccessoryUuids: array(string()).optional(),
139728
+ addedAt: number().optional(),
139729
+ settings: ExportDeviceSettingsSchema.optional()
139730
+ });
139731
+ var ActionExportEntrySchema = object({
139732
+ actionId: string(),
139733
+ displayName: string(),
139734
+ addedAt: number()
139735
+ });
139736
+ var HapBridgeExportsBodySchema = object({
139737
+ name: string().min(1),
139738
+ devices: array(ExposedConfigEntrySchema),
139739
+ actions: array(ActionExportEntrySchema)
139740
+ });
139741
+ /** The label of every exposure record: it is the instance's, not an operator's name. */
139742
+ var HAP_EXPOSURE_NAME = "HomeKit exposure";
139743
+ var hapBridgeExportsKind = defineEntryKind("hap-bridge-exports", {
139744
+ title: "HomeKit exposure",
139745
+ nameField: "name",
139746
+ schema: HapBridgeExportsBodySchema,
139747
+ writeTrigger: "an operator exposes or unexposes a device or action to HomeKit"
139748
+ });
139749
+ /** The settings keys that moved into the record; the migrations name them. */
139750
+ var MOVED_EXPOSURE_KEYS = ["exposed", "exposedActions"];
139751
+ //#endregion
139752
+ //#region src/hap-identity.ts
139753
+ /**
139754
+ * Whether the DEFAULT HomeKit bridge exists at boot, and with which identity: the default instance
139755
+ * record, and nothing else. There is no fallback to the settings the identity once lived in; the
139756
+ * migration moved it. A fresh default identity is minted only when no default record exists, no
139757
+ * other bridge exists (the operator may have deleted the default one on purpose) AND no legacy
139758
+ * identity is still stored. A legacy identity without a record means the migration did not finish,
139759
+ * and minting then would unpair every controller, so the addon refuses to boot with the reason.
139760
+ *
139761
+ * Every other instance is read as it is stored; this module is only about the default one.
139762
+ */
139763
+ async function resolveDefaultBridge(ports) {
139764
+ const stored = await ports.readRecord();
139765
+ if (stored.kind === "unavailable") throw new Error("export-hap: the bridge identity exists but the keychain cannot serve it");
139766
+ if (stored.kind === "resolved") return {
139767
+ kind: "existing",
139768
+ identity: identityOfBody(stored.body)
139769
+ };
139770
+ if (await ports.legacyIdentityPresent()) throw new Error("export-hap: a bridge identity is still in the old settings but its instance record does not exist; the identity migration did not complete. Refusing to boot: a new identity would unpair every HomeKit controller");
139771
+ if (await ports.otherBridgesExist()) return { kind: "none" };
139772
+ const body = ports.mint();
139773
+ await ports.putFresh(body);
139774
+ return {
139775
+ kind: "minted",
139776
+ identity: identityOfBody(body)
139777
+ };
139778
+ }
139779
+ //#endregion
138664
139780
  //#region src/migrations/hub-node-fields.ts
138665
139781
  /**
138666
139782
  * Fields stored once for the cluster that are facts of ONE node become node settings (D986): a
@@ -138731,40 +139847,375 @@ async function moveFixedPinToKeychain(ports) {
138731
139847
  };
138732
139848
  }
138733
139849
  //#endregion
139850
+ //#region src/migrations/exposure-to-record.ts
139851
+ /**
139852
+ * The exposure lists the addon kept in its settings (`exposed`: the devices it mirrors, with
139853
+ * their per-device settings; `exposedActions`: the actions it publishes) move into the
139854
+ * `hap-bridge-exports` record of the default instance (D985, D996). Two migrations, in order:
139855
+ *
139856
+ * 1. `moveExposureToRecord` (procedure): put the record with `ifRev: 0`, read it BACK and
139857
+ * compare it with what the settings carried; a record that does not hold the same lists
139858
+ * throws and the settings are kept. An existing record is never overwritten.
139859
+ * 2. `planDropExposureKeys` (plan): the two keys are deleted from the canonical `addon-settings`
139860
+ * rows, and only while the record holds exactly what they carry. A record that differs (the
139861
+ * operator edited the lists since) keeps the old keys, which nothing reads any more.
139862
+ *
139863
+ * An entry the schema does not know (a mapper kind the addon no longer serves) is dropped on the
139864
+ * way, which is what the boot sweep did to it anyway.
139865
+ */
139866
+ /** Key-order-independent JSON, so "identical" does not depend on how a store orders keys. */
139867
+ function canonical(value) {
139868
+ if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
139869
+ if (typeof value === "object" && value !== null) return `{${Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(",")}}`;
139870
+ return JSON.stringify(value) ?? "null";
139871
+ }
139872
+ function parsedList(value, parse) {
139873
+ if (!Array.isArray(value)) return [];
139874
+ const kept = [];
139875
+ for (const entry of value) {
139876
+ const parsed = parse(entry);
139877
+ if (parsed.success) kept.push(parsed.data);
139878
+ }
139879
+ return kept;
139880
+ }
139881
+ /** The record body the legacy settings describe. */
139882
+ function exposureBodyFrom(stored) {
139883
+ return {
139884
+ name: HAP_EXPOSURE_NAME,
139885
+ devices: parsedList(stored["exposed"], (e) => ExposedConfigEntrySchema.safeParse(e)),
139886
+ actions: parsedList(stored["exposedActions"], (e) => ActionExportEntrySchema.safeParse(e))
139887
+ };
139888
+ }
139889
+ function sameLists(a, b) {
139890
+ return canonical(a.devices) === canonical(b.devices) && canonical(a.actions) === canonical(b.actions);
139891
+ }
139892
+ async function moveExposureToRecord(ports) {
139893
+ const stored = await ports.readStored(MOVED_EXPOSURE_KEYS);
139894
+ if (!MOVED_EXPOSURE_KEYS.some((key) => key in stored)) return {
139895
+ outcome: "already-done",
139896
+ summary: { moved: false }
139897
+ };
139898
+ const body = exposureBodyFrom(stored);
139899
+ const put = await ports.putExposure(body);
139900
+ const held = await ports.readExposure();
139901
+ if (held === null) throw new Error("the HomeKit exposure record cannot be read back");
139902
+ if (put === "created" && !sameLists(held, body)) throw new Error("the HomeKit exposure record does not hold the lists it adopted");
139903
+ return put === "created" ? {
139904
+ outcome: "done",
139905
+ summary: {
139906
+ moved: true,
139907
+ devices: body.devices.length
139908
+ }
139909
+ } : {
139910
+ outcome: "already-done",
139911
+ summary: { moved: false }
139912
+ };
139913
+ }
139914
+ var rowId = (key) => `${HAP_DEFAULT_INSTANCE_ID}.${key}`;
139915
+ async function planDropExposureKeys(ports) {
139916
+ const stored = await ports.readStored(MOVED_EXPOSURE_KEYS);
139917
+ const present = MOVED_EXPOSURE_KEYS.filter((key) => key in stored);
139918
+ if (present.length === 0) return { edits: [] };
139919
+ const held = await ports.readExposure();
139920
+ if (held === null || !sameLists(held, exposureBodyFrom(stored))) return { edits: [] };
139921
+ return { edits: [{
139922
+ op: "deleteKeys",
139923
+ scope: ADDON_SETTINGS_TABLE,
139924
+ keys: present.map(rowId),
139925
+ precondition: preconditionOf(Object.fromEntries(present.map((key) => [rowId(key), {
139926
+ addonId: HAP_DEFAULT_INSTANCE_ID,
139927
+ key,
139928
+ value: stored[key]
139929
+ }])))
139930
+ }] };
139931
+ }
139932
+ //#endregion
139933
+ //#region src/migrations/identity-to-instance.ts
139934
+ /**
139935
+ * The bridge identity the addon kept in its settings (`identity`: username, uuid, pincode) moves
139936
+ * into the default instance record (D985, D996). Paired controllers know the bridge by exactly
139937
+ * these values, so the record is created with them UNCHANGED and the pass proves it by reading the
139938
+ * record back and comparing, field by field, before it reports `done`.
139939
+ *
139940
+ * Only once the read-back matches is the old `identity` cleared (its keychain entry released with
139941
+ * it), in this same pass: one path, no copy. An existing record is never overwritten; when it is
139942
+ * already there and names the same bridge (username, uuid) the leftover old identity of an
139943
+ * interrupted pass is cleared, and when it names another bridge the pass fails rather than guess.
139944
+ * An incomplete or unreadable legacy identity is `already-done` or throws, and never mints a new
139945
+ * one (a new identity unpairs every controller).
139946
+ */
139947
+ async function moveIdentityToDefaultInstance(ports) {
139948
+ const legacy = await ports.readLegacyIdentity();
139949
+ if (legacy === null) return {
139950
+ outcome: "already-done",
139951
+ summary: { moved: false }
139952
+ };
139953
+ const name = (await ports.readBridgeName()).trim();
139954
+ const body = {
139955
+ name: name.length > 0 ? name : "CamStack Bridge",
139956
+ username: legacy.username,
139957
+ uuid: legacy.uuid,
139958
+ pincode: legacy.pincode
139959
+ };
139960
+ const put = await ports.putDefaultRecord(body);
139961
+ const held = await ports.readDefaultRecord();
139962
+ if (held === null) throw new Error("the HomeKit default instance record cannot be read back");
139963
+ if (put === "exists") {
139964
+ if (held.username !== body.username || held.uuid !== body.uuid) throw new Error("the HomeKit default instance is another bridge than the stored identity");
139965
+ await ports.clearLegacyIdentity();
139966
+ return {
139967
+ outcome: "done",
139968
+ summary: {
139969
+ moved: false,
139970
+ cleared: true
139971
+ }
139972
+ };
139973
+ }
139974
+ if (!sameIdentity(identityOfBody(held), identityOfBody(body))) throw new Error("the HomeKit default instance does not hold the identity it adopted");
139975
+ await ports.clearLegacyIdentity();
139976
+ return {
139977
+ outcome: "done",
139978
+ summary: { moved: true }
139979
+ };
139980
+ }
139981
+ function sameIdentity(a, b) {
139982
+ return a.username === b.username && a.uuid === b.uuid && a.pincode === b.pincode;
139983
+ }
139984
+ /**
139985
+ * The identity a settings value describes, secrets resolved; null when it is not a complete
139986
+ * identity (first boot, or the empty sentinel). A pincode still a keychain marker was not
139987
+ * resolved: that throws, because treating "unreadable" as "absent" would mint a new identity.
139988
+ */
139989
+ function legacyIdentityOf(value) {
139990
+ if (typeof value !== "object" || value === null) return null;
139991
+ const username = Reflect.get(value, "username");
139992
+ const uuid = Reflect.get(value, "uuid");
139993
+ const pincode = Reflect.get(value, "pincode");
139994
+ if (isSecretMarker(pincode)) throw new Error("the stored HomeKit setup code cannot be resolved");
139995
+ if (typeof username !== "string" || typeof uuid !== "string" || typeof pincode !== "string" || username === "" || uuid === "" || pincode === "") return null;
139996
+ return {
139997
+ username,
139998
+ uuid,
139999
+ pincode
140000
+ };
140001
+ }
140002
+ //#endregion
140003
+ //#region src/migrations/bridge-name-to-instance.ts
140004
+ async function moveBridgeNameToInstance(ports) {
140005
+ const name = (await ports.readBridgeName()).trim();
140006
+ if (name === "") return {
140007
+ outcome: "already-done",
140008
+ summary: { renamed: false }
140009
+ };
140010
+ const held = await ports.readDefaultRecord();
140011
+ if (held === null || held.name === name) return {
140012
+ outcome: "already-done",
140013
+ summary: { renamed: false }
140014
+ };
140015
+ await ports.patchDefaultName(name);
140016
+ const after = await ports.readDefaultRecord();
140017
+ if (after === null || after.name !== name) throw new Error("the HomeKit default instance does not carry the name it adopted");
140018
+ return {
140019
+ outcome: "done",
140020
+ summary: { renamed: true }
140021
+ };
140022
+ }
140023
+ //#endregion
140024
+ //#region src/migrations/drop-global-knobs.ts
140025
+ /**
140026
+ * The retired global knobs of the HomeKit export. `bridgeName` is the instance's name and
140027
+ * `fixedPin` was an operator-typed setup code (a bridge's setup code is read-only now and changes
140028
+ * only through Regenerate); the bare `interfaceName` is the cluster copy of a setting that is a
140029
+ * fact of one node, which the node row carries since the per-node migration.
140030
+ *
140031
+ * Two bodies, in this order, because a secret must be released before its row goes (the
140032
+ * keychain value would be orphaned otherwise):
140033
+ * 1. `clearFixedPin` (procedure): the keychain value and marker of `fixedPin`;
140034
+ * 2. `planDropGlobalKnobRows` (plan): the rows `bridgeName`, `fixedPin` and the bare
140035
+ * `interfaceName`. The bare interfaceName goes only when the node row exists, so deleting it
140036
+ * can never lose the value. A `@<nodeId>` row is never touched.
140037
+ */
140038
+ async function clearFixedPin(ports) {
140039
+ if (!("fixedPin" in await ports.readStored(["fixedPin"]))) return {
140040
+ outcome: "already-done",
140041
+ summary: { cleared: false }
140042
+ };
140043
+ await ports.clearFixedPin();
140044
+ return {
140045
+ outcome: "done",
140046
+ summary: { cleared: true }
140047
+ };
140048
+ }
140049
+ async function planDropGlobalKnobRows(addonId, ports) {
140050
+ const stored = await ports.readStored([
140051
+ "bridgeName",
140052
+ "fixedPin",
140053
+ "interfaceName",
140054
+ nodeKeyOf("interfaceName")
140055
+ ]);
140056
+ const present = [
140057
+ "bridgeName",
140058
+ "fixedPin",
140059
+ "interfaceName"
140060
+ ].filter((key) => key in stored && (key !== "interfaceName" || nodeKeyOf("interfaceName") in stored));
140061
+ if (present.length === 0) return { edits: [] };
140062
+ const rowId = (key) => `${addonId}.${key}`;
140063
+ return { edits: [{
140064
+ op: "deleteKeys",
140065
+ scope: ADDON_SETTINGS_TABLE,
140066
+ keys: present.map(rowId),
140067
+ precondition: preconditionOf(Object.fromEntries(present.map((key) => [rowId(key), {
140068
+ addonId,
140069
+ key,
140070
+ value: stored[key]
140071
+ }])))
140072
+ }] };
140073
+ }
140074
+ //#endregion
138734
140075
  //#region src/migrations/index.ts
138735
140076
  var EXPORT_HAP_ID = "export-hap";
140077
+ var INTERFACE_NAME_PER_NODE_ID = "export-hap/2026-11-03-interface-name-per-node";
140078
+ var FIXED_PIN_TO_KEYCHAIN_ID = "export-hap/2026-11-03-fixed-pin-to-keychain";
140079
+ var IDENTITY_TO_INSTANCE_ID = "export-hap/2026-11-04-identity-to-default-instance";
140080
+ var EXPOSURE_TO_RECORD_ID = "export-hap/2026-11-04-exposure-to-record";
140081
+ var DROP_EXPOSURE_KEYS_ID = "export-hap/2026-11-04-drop-exposure-keys";
140082
+ var BRIDGE_NAME_TO_INSTANCE_ID = "export-hap/2026-11-04-bridge-name-to-instance";
140083
+ var DROP_GLOBAL_KNOBS_ID = "export-hap/2026-11-04-drop-global-knobs";
138736
140084
  /** The `export-hap` catalogue (D987): offered to the engine when the addon initialises. */
138737
- var ADDON_MIGRATIONS = [{
138738
- meta: {
138739
- id: "export-hap/2026-11-03-interface-name-per-node",
138740
- owner: EXPORT_HAP_ID,
138741
- level: "addon-state",
138742
- seq: 1,
138743
- dependsOn: [],
138744
- store: "settings",
138745
- scope: "per-node",
138746
- onFailure: "tolerate",
138747
- bodyKind: "plan",
138748
- description: "Copy the bare network interface setting to its hub node row; the bare row stays for a release",
138749
- fixtureMark: "the bridge name the migration does not know"
138750
- },
138751
- plan: (ports) => planHubNodeFields(EXPORT_HAP_ID, ["interfaceName"], ports)
138752
- }, {
138753
- meta: {
138754
- id: "export-hap/2026-11-03-fixed-pin-to-keychain",
138755
- owner: EXPORT_HAP_ID,
138756
- level: "addon-state",
138757
- seq: 2,
138758
- dependsOn: [],
138759
- store: "settings",
138760
- scope: "cluster",
138761
- onFailure: "tolerate",
138762
- bodyKind: "procedure",
138763
- description: "Move the fixed setup code from an inline setting into the keychain, where a password field keeps it",
138764
- fixtureMark: "the bridge name the migration does not know"
138765
- },
138766
- procedure: moveFixedPinToKeychain
138767
- }];
140085
+ var ADDON_MIGRATIONS = [
140086
+ {
140087
+ meta: {
140088
+ id: INTERFACE_NAME_PER_NODE_ID,
140089
+ owner: EXPORT_HAP_ID,
140090
+ level: "addon-state",
140091
+ seq: 1,
140092
+ dependsOn: [],
140093
+ store: "settings",
140094
+ scope: "per-node",
140095
+ onFailure: "tolerate",
140096
+ bodyKind: "plan",
140097
+ description: "Copy the bare network interface setting to its hub node row; the bare row stays for a release",
140098
+ fixtureMark: "the bridge name the migration does not know"
140099
+ },
140100
+ plan: (ports) => planHubNodeFields(EXPORT_HAP_ID, ["interfaceName"], ports)
140101
+ },
140102
+ {
140103
+ meta: {
140104
+ id: FIXED_PIN_TO_KEYCHAIN_ID,
140105
+ owner: EXPORT_HAP_ID,
140106
+ level: "addon-state",
140107
+ seq: 2,
140108
+ dependsOn: [],
140109
+ store: "settings",
140110
+ scope: "cluster",
140111
+ onFailure: "tolerate",
140112
+ bodyKind: "procedure",
140113
+ description: "Move the fixed setup code from an inline setting into the keychain, where a password field keeps it",
140114
+ fixtureMark: "the bridge name the migration does not know"
140115
+ },
140116
+ procedure: moveFixedPinToKeychain
140117
+ },
140118
+ {
140119
+ meta: {
140120
+ id: IDENTITY_TO_INSTANCE_ID,
140121
+ owner: EXPORT_HAP_ID,
140122
+ level: "addon-state",
140123
+ seq: 3,
140124
+ dependsOn: [],
140125
+ store: "settings",
140126
+ scope: "cluster",
140127
+ onFailure: "block-owner",
140128
+ bodyKind: "procedure",
140129
+ description: "Move the bridge identity (username, uuid, setup code) into the default HomeKit instance record, unchanged, then clear the old setting and its keychain entry",
140130
+ fixtureMark: "the bridge name the migration does not know"
140131
+ },
140132
+ procedure: moveIdentityToDefaultInstance
140133
+ },
140134
+ {
140135
+ meta: {
140136
+ id: EXPOSURE_TO_RECORD_ID,
140137
+ owner: EXPORT_HAP_ID,
140138
+ level: "addon-state",
140139
+ seq: 4,
140140
+ dependsOn: [IDENTITY_TO_INSTANCE_ID],
140141
+ store: "settings",
140142
+ scope: "cluster",
140143
+ onFailure: "block-owner",
140144
+ bodyKind: "procedure",
140145
+ description: "Move the exposed devices and actions into the default bridge exposure record, verified by read-back",
140146
+ fixtureMark: "the bridge name the migration does not know"
140147
+ },
140148
+ procedure: moveExposureToRecord
140149
+ },
140150
+ {
140151
+ meta: {
140152
+ id: DROP_EXPOSURE_KEYS_ID,
140153
+ owner: EXPORT_HAP_ID,
140154
+ level: "addon-state",
140155
+ seq: 5,
140156
+ dependsOn: [EXPOSURE_TO_RECORD_ID],
140157
+ store: "settings",
140158
+ scope: "cluster",
140159
+ onFailure: "tolerate",
140160
+ bodyKind: "plan",
140161
+ description: "Delete the old exposed and exposedActions settings once the record holds exactly what they carried",
140162
+ fixtureMark: "the bridge name the migration does not know"
140163
+ },
140164
+ plan: planDropExposureKeys
140165
+ },
140166
+ {
140167
+ meta: {
140168
+ id: BRIDGE_NAME_TO_INSTANCE_ID,
140169
+ owner: EXPORT_HAP_ID,
140170
+ level: "addon-state",
140171
+ seq: 6,
140172
+ dependsOn: [IDENTITY_TO_INSTANCE_ID],
140173
+ store: "settings",
140174
+ scope: "cluster",
140175
+ onFailure: "block-owner",
140176
+ bodyKind: "procedure",
140177
+ description: "Make the installation name the name of the default HomeKit instance record, verified by read-back",
140178
+ fixtureMark: "the bridge name the migration does not know"
140179
+ },
140180
+ procedure: moveBridgeNameToInstance
140181
+ },
140182
+ {
140183
+ meta: {
140184
+ id: DROP_GLOBAL_KNOBS_ID,
140185
+ owner: EXPORT_HAP_ID,
140186
+ level: "addon-state",
140187
+ seq: 7,
140188
+ dependsOn: [FIXED_PIN_TO_KEYCHAIN_ID, IDENTITY_TO_INSTANCE_ID],
140189
+ store: "settings",
140190
+ scope: "cluster",
140191
+ onFailure: "tolerate",
140192
+ bodyKind: "procedure",
140193
+ description: "Release the retired fixed setup code from the keychain: a bridge setup code is read-only now",
140194
+ fixtureMark: "the bridge name the migration does not know"
140195
+ },
140196
+ procedure: clearFixedPin
140197
+ },
140198
+ {
140199
+ meta: {
140200
+ id: "export-hap/2026-11-04-drop-global-knob-rows",
140201
+ owner: EXPORT_HAP_ID,
140202
+ level: "addon-state",
140203
+ seq: 8,
140204
+ dependsOn: [
140205
+ BRIDGE_NAME_TO_INSTANCE_ID,
140206
+ DROP_GLOBAL_KNOBS_ID,
140207
+ INTERFACE_NAME_PER_NODE_ID
140208
+ ],
140209
+ store: "settings",
140210
+ scope: "cluster",
140211
+ onFailure: "tolerate",
140212
+ bodyKind: "plan",
140213
+ description: "Delete the retired bridgeName, fixedPin and cluster interfaceName rows; the node rows are untouched",
140214
+ fixtureMark: "the bridge name the migration does not know"
140215
+ },
140216
+ plan: (ports) => planDropGlobalKnobRows(EXPORT_HAP_ID, ports)
140217
+ }
140218
+ ];
138768
140219
  //#endregion
138769
140220
  //#region src/hap-setup-uri.ts
138770
140221
  function errMsg$15(e) {
@@ -156857,81 +158308,6 @@ function errMsg$3(err) {
156857
158308
  return err instanceof Error ? err.message : String(err);
156858
158309
  }
156859
158310
  //#endregion
156860
- //#region src/mappers/kind.ts
156861
- /**
156862
- * Which orchestrator a device gets, which device types the picker offers, and
156863
- * what a device's HomeKit accessory is called on the wire.
156864
- *
156865
- * Separate from `index.ts` (the factory registry) only so the orchestrators can
156866
- * import the uuid convention without importing the registry that imports them.
156867
- */
156868
- var SUPPORTED_MAPPER_KINDS = ["camera", "generic"];
156869
- /**
156870
- * The device types the Export picker offers, and the answer to the cap's
156871
- * `listSupportedDeviceKinds`.
156872
- *
156873
- * A UI FILTER, nothing more. Whether a device actually exports anything is
156874
- * decided by its capabilities (`rowsForCaps` in the capability table) — the
156875
- * doctrine the HA exporter writes down, and the thing that confined the
156876
- * previous exporter to cameras when it was ignored.
156877
- *
156878
- * Tier A plus `alarm-panel`: the types whose HomeKit services exist today and
156879
- * need no feature-dependent shape. `cover`, `climate`, `fan`, `valve`,
156880
- * `humidifier`, `water-heater`, `button` and `media-player` are deliberately
156881
- * absent — each needs a service whose semantics the table cannot yet honour,
156882
- * and offering the tab before the mapping exists is how an operator gets an
156883
- * accessory that pairs and does nothing.
156884
- *
156885
- * `alarm-panel` is no longer one of them. It maps to `Service.SecuritySystem`
156886
- * (`builders/generic/security-system.ts`), and the two things the table could
156887
- * not previously honour are now honoured explicitly: HomeKit is only ever
156888
- * offered the arm modes the panel accepts, and a panel that requires a PIN
156889
- * refuses the write out loud instead of pretending to arm.
156890
- */
156891
- var HAP_EXPORTABLE_DEVICE_TYPES = [
156892
- DeviceType.Camera,
156893
- DeviceType.Light,
156894
- DeviceType.Switch,
156895
- DeviceType.Siren,
156896
- DeviceType.Sensor,
156897
- DeviceType.Lock,
156898
- DeviceType.Presence,
156899
- DeviceType.AlarmPanel,
156900
- DeviceType.Generic
156901
- ];
156902
- /**
156903
- * Resolve the orchestrator for a device from its TYPE.
156904
- *
156905
- * `null` means "no Export tab": the picker must not offer a type no
156906
- * orchestrator can build. An UNKNOWN type (the device-manager read failed) maps
156907
- * to `camera` — that is what every entry persisted before this function existed
156908
- * carries, and a transient API failure must never re-shape an exposed camera.
156909
- */
156910
- function pickMapperKind(deviceType) {
156911
- if (deviceType === null || deviceType === void 0 || deviceType.length === 0) return "camera";
156912
- if (deviceType === DeviceType.Camera) return "camera";
156913
- const withheld = applianceExport("homekit", deviceType);
156914
- if (withheld !== null && !withheld.exported) return null;
156915
- return HAP_EXPORTABLE_DEVICE_TYPES.find((type) => type === deviceType) === void 0 ? null : "generic";
156916
- }
156917
- /**
156918
- * The deterministic HAP accessory UUID for a device.
156919
- *
156920
- * One function, because three call sites depend on the answer agreeing: the
156921
- * orchestrator that builds the accessory, `unexposeDevice` (which wipes
156922
- * hap-nodejs' pairing blobs by uuid, on a device whose mapper is already gone)
156923
- * and the export sync state that records it.
156924
- *
156925
- * The camera namespace is FROZEN — every camera paired to date derives its MAC
156926
- * from `sha256("camstack:hap:" + uuid)` of this exact string, and changing it
156927
- * would make every paired camera a stranger. Generic devices get their own
156928
- * namespace so a switch and a camera that happen to share a device id are not
156929
- * the same HomeKit accessory.
156930
- */
156931
- function accessoryUuidFor(kind, deviceId) {
156932
- return import_dist.uuid.generate(kind === "camera" ? `camstack:camera:${deviceId}` : `camstack:device:${deviceId}`);
156933
- }
156934
- //#endregion
156935
158311
  //#region src/multi-tier/rtp-streaming-control.ts
156936
158312
  /**
156937
158313
  * `RTP Streaming Control` (0x8045) — start and stop, on the new service.
@@ -157734,7 +159110,7 @@ async function buildCameraAccessory(input) {
157734
159110
  const capNames = new Set(proxy.binding?.entries.map((e) => e.capName) ?? []);
157735
159111
  const isDoorbell = capNames.has("doorbell");
157736
159112
  const category = isDoorbell ? import_dist.Categories.VIDEO_DOORBELL : import_dist.Categories.IP_CAMERA;
157737
- const accessory = new import_dist.Accessory(displayName, accessoryUuidFor("camera", numericId));
159113
+ const accessory = new import_dist.Accessory(displayName, accessoryUuidFor("camera", numericId, options.instanceId));
157738
159114
  accessory.category = category;
157739
159115
  await populateAccessoryInfo(accessory, proxy, displayName, "Camera");
157740
159116
  const bctx = {
@@ -157869,7 +159245,7 @@ async function buildGenericAccessory(input) {
157869
159245
  const rows = rowsForCaps(capNames);
157870
159246
  if (rows.length === 0) throw new Error(`export-hap: device ${numericId} carries no capability HomeKit can export (bound: ${[...capNames].toSorted().join(", ") || "none"})`);
157871
159247
  const deviceType = await resolveDeviceType(proxy);
157872
- const accessory = new import_dist.Accessory(displayName, accessoryUuidFor("generic", numericId));
159248
+ const accessory = new import_dist.Accessory(displayName, accessoryUuidFor("generic", numericId, options.instanceId));
157873
159249
  accessory.category = accessoryCategoryFor(deviceType);
157874
159250
  await populateAccessoryInfo(accessory, proxy, displayName, "Accessory");
157875
159251
  const bctx = {
@@ -157967,9 +159343,8 @@ function syncStateToJson(map) {
157967
159343
  * Operator flow:
157968
159344
  * 1. Install + enable the addon (hub-only, group `export-hap`).
157969
159345
  * 2. On first boot the addon generates a random pincode + bridge
157970
- * MAC username and persists them on `this.config.identity` via
157971
- * `updateGlobalSettings` (no JSON sidecar files — the kernel
157972
- * addon-store IS the cache).
159346
+ * MAC username and persists them in the default instance record
159347
+ * (`hap-bridges`, no JSON sidecar files).
157973
159348
  * 3. The setup URI (`X-HM://…`) is logged AND surfaced via the
157974
159349
  * `getStatus` cap method so the wizard UI can render the QR.
157975
159350
  * 4. Operator opens iOS Home → + → scan QR → enter pincode.
@@ -158103,17 +159478,8 @@ var HAP_STREAM_PREFERENCE_OPTIONS = [
158103
159478
  }
158104
159479
  ];
158105
159480
  var DEFAULT_CONFIG = {
158106
- bridgeName: "CamStack Bridge",
158107
- fixedPin: "",
158108
159481
  interfaceName: "",
158109
159482
  clipRetentionDays: 14,
158110
- identity: {
158111
- username: "",
158112
- pincode: "",
158113
- uuid: ""
158114
- },
158115
- exposed: [],
158116
- exposedActions: [],
158117
159483
  exportSyncState: {}
158118
159484
  };
158119
159485
  var BANNED_PINCODES = new Set([
@@ -158130,10 +159496,6 @@ var BANNED_PINCODES = new Set([
158130
159496
  "123-45-678",
158131
159497
  "876-54-321"
158132
159498
  ]);
158133
- var PINCODE_REGEX = /^\d{3}-\d{2}-\d{3}$/;
158134
- function isValidPincode(pin) {
158135
- return PINCODE_REGEX.test(pin) && !BANNED_PINCODES.has(pin);
158136
- }
158137
159499
  function generateUsername() {
158138
159500
  const bytes = randomBytes(6);
158139
159501
  return Array.from(bytes, (b) => b.toString(16).toUpperCase().padStart(2, "0")).join(":");
@@ -158148,18 +159510,23 @@ function generatePincode() {
158148
159510
  }
158149
159511
  throw new Error("export-hap: failed to generate a non-trivial pincode");
158150
159512
  }
159513
+ var DEFAULT_BRIDGE_NAME = "CamStack Bridge";
158151
159514
  function buildBridgeUuid(bridgeName) {
158152
159515
  return import_dist.uuid.generate(`camstack:bridge:${bridgeName}:${Date.now()}`);
158153
159516
  }
158154
159517
  var ExportHapAddon = class extends BaseAddon {
158155
- /** The bridge setup code pairs a controller: a credential, kept in the keychain (D787). */
158156
- secretStatePaths = ["identity.pincode"];
158157
- exposed = /* @__PURE__ */ new Map();
158158
- /** The exported actions — switches beside the devices (D968). */
158159
- actionExports = null;
159518
+ /**
159519
+ * The old `identity.pincode` and `fixedPin` secrets: declared only so the migrations can
159520
+ * release their keychain entries when they clear the old settings. The identity itself is a record now.
159521
+ */
159522
+ secretStatePaths = ["identity.pincode", "fixedPin"];
159523
+ /** The running bridges, by instance id: one runtime per ENABLED `hap-bridges` record. */
159524
+ bridges = /* @__PURE__ */ new Map();
159525
+ /** Start / stop / regenerate of bridges run one at a time: they share one HAP storage. */
159526
+ lifecycle = Promise.resolve();
158160
159527
  lastError;
158161
- /** Shared HAP setup code applied to every published accessory. */
158162
- pincode = "";
159528
+ /** The HomeKit instances (D985): one record per bridge identity. */
159529
+ instances = null;
158163
159530
  /** Optional mDNS/bind interface (config.interfaceName), or undefined. */
158164
159531
  bind;
158165
159532
  /**
@@ -158203,29 +159570,39 @@ var ExportHapAddon = class extends BaseAddon {
158203
159570
  hksvBuilds = new HksvBuildOutcomes();
158204
159571
  /** The clip byte + still routes. `null` until `onInitialize` has served them. */
158205
159572
  hksvClipPlanes = null;
158206
- /**
158207
- * THE bridge. Lazily created and published the first time a non-camera
158208
- * accessory needs it; never torn down while the addon runs, because an
158209
- * unpublish would drop a pairing the operator already entered a code for.
158210
- */
158211
- bridgeHost = null;
158212
159573
  constructor() {
158213
159574
  super({ ...DEFAULT_CONFIG });
158214
159575
  }
158215
159576
  async onInitialize() {
159577
+ const records = this.ctx.records;
159578
+ if (records === void 0) throw new Error("export-hap needs ctx.records — check execution.placement (hub-only)");
159579
+ await records.declare({
159580
+ "hap-bridges": hapBridgesKind,
159581
+ "hap-bridge-exports": hapBridgeExportsKind
159582
+ });
159583
+ this.instances = new RecordIntegrationInstances(records, hapBridgesKind, {
159584
+ description: {
159585
+ role: "services",
159586
+ instanceMode: "multiple",
159587
+ kind: "bridge",
159588
+ canTest: false
159589
+ },
159590
+ formSchema: (id) => this.bridgeForm(id),
159591
+ initialBody: (name) => ({
159592
+ name,
159593
+ username: generateUsername(),
159594
+ uuid: buildBridgeUuid(name),
159595
+ pincode: generatePincode()
159596
+ }),
159597
+ mintId: () => `hap-${randomUUID().slice(0, 8)}`,
159598
+ configured: (body) => body.username !== "" && body.pincode !== "",
159599
+ onChanged: (id, change) => this.enqueue(() => this.applyChange(id, change))
159600
+ });
158216
159601
  await this.migrateSettings();
158217
- const identity = await this.ensureIdentity();
158218
- this.pincode = identity.pincode;
159602
+ await this.ensureDefaultBridge();
158219
159603
  this.bind = this.config.interfaceName || void 0;
158220
- this.bridgeHost = new BridgeHost({
158221
- displayName: this.config.bridgeName,
158222
- uuid: identity.uuid,
158223
- pincode: identity.pincode,
158224
- bind: this.bind,
158225
- logger: this.ctx.logger
158226
- });
158227
159604
  try {
158228
- await initHapStorage(path.join(this.ctx.dataDir, "hap-store"));
159605
+ await initHapStorage(path.join(this.ctx.dataDir, hapPersistDirOf(HAP_DEFAULT_INSTANCE_ID)));
158229
159606
  } catch (err) {
158230
159607
  this.lastError = errMsg(err);
158231
159608
  this.ctx.logger.error("export-hap: HAP storage init failed", { meta: { error: this.lastError } });
@@ -158237,7 +159614,7 @@ var ExportHapAddon = class extends BaseAddon {
158237
159614
  this.hksvClipStore = new HksvClipStore({
158238
159615
  logger: this.ctx.logger.child("hksv-clips"),
158239
159616
  resolveRoot: () => this.hksvClipLocation?.root() ?? Promise.resolve(null),
158240
- maxAgeMsFor: (deviceId) => resolveClipRetentionDays(this.findEntry(deviceId)?.settings, this.config.clipRetentionDays) * 24 * 60 * 60 * 1e3,
159617
+ maxAgeMsFor: (deviceId) => resolveClipRetentionDays(this.instanceForDevice(deviceId)?.findEntry(deviceId)?.settings, this.config.clipRetentionDays) * 24 * 60 * 60 * 1e3,
158241
159618
  mintThumbnail: createClipThumbnailMinter({ runner: createBoundedFfmpegRunner({
158242
159619
  resolveFfmpeg: this.pinnedFfmpeg,
158243
159620
  spawnFn: spawn,
@@ -158250,187 +159627,391 @@ var ExportHapAddon = class extends BaseAddon {
158250
159627
  }) })
158251
159628
  });
158252
159629
  await this.serveHksvClipPlanes();
159630
+ const ordered = (await this.requireInstances().listResolved()).toSorted((x, y) => Number(y.id === HAP_DEFAULT_INSTANCE_ID) - Number(x.id === HAP_DEFAULT_INSTANCE_ID));
159631
+ for (const row of ordered) try {
159632
+ await this.startInstance(row.id);
159633
+ } catch (err) {
159634
+ this.ctx.logger.error("export-hap: bridge failed to start", { meta: {
159635
+ instanceId: row.id,
159636
+ error: errMsg(err)
159637
+ } });
159638
+ }
159639
+ this.ctx.addDisposer(async () => {
159640
+ await this.enqueue(async () => {
159641
+ for (const id of Array.from(this.bridges.keys())) await this.stopInstance(id);
159642
+ });
159643
+ });
159644
+ this.subscribeDeviceProvisionedForReconcile();
159645
+ this.subscribeDeviceReadyForReconcile();
159646
+ this.subscribeStorageLocationsForClips();
159647
+ const provider = this.buildExportProvider();
159648
+ const clipsProvider = createHksvVideoclipsProvider({
159649
+ logger: this.ctx.logger.child("hksv-clips"),
159650
+ addonId: EXPORT_HAP_ADDON_ID,
159651
+ describeCamera: (deviceId) => describeHksvCamera(this.instanceForDevice(deviceId)?.findEntry(deviceId) ?? null, this.hksvBuilds.lastFor(deviceId), readHomekitRecordingActive(this.instanceForDevice(deviceId)?.exposed.get(String(deviceId))?.accessories ?? [])),
159652
+ readCatalog: async (deviceId) => await this.hksvClipStore?.listCatalog(deviceId) ?? { kind: "no-root" },
159653
+ locationRefusal: () => this.hksvClipLocation?.lastRefusal ?? null,
159654
+ mediaUrl: (deviceId, stem) => this.hksvClipUrl("media", deviceId, stem),
159655
+ thumbnailUrl: (deviceId, stem) => this.hksvClipUrl("thumb", deviceId, stem),
159656
+ clipFilePath: async (deviceId, stem) => await this.hksvClipStore?.artifactPath(deviceId, stem, "clip") ?? null
159657
+ });
159658
+ return {
159659
+ providers: [
159660
+ {
159661
+ capability: deviceExportCapability,
159662
+ provider
159663
+ },
159664
+ {
159665
+ capability: videoclipsCapability,
159666
+ provider: clipsProvider
159667
+ },
159668
+ {
159669
+ capability: integrationInstancesCapability,
159670
+ provider: this.requireInstances().toProvider()
159671
+ }
159672
+ ],
159673
+ customActions: exportHapActions,
159674
+ actionHandlers: { regenerateBridge: async ({ instanceId }) => this.regenerateBridge(instanceId) }
159675
+ };
159676
+ }
159677
+ /** Run one start / stop / regenerate at a time: bridges share one HAP storage and one clip store. */
159678
+ enqueue(job) {
159679
+ const run = this.lifecycle.then(job);
159680
+ this.lifecycle = run.then(() => void 0, () => void 0);
159681
+ return run;
159682
+ }
159683
+ /** The bridge that owns a device: the one that exposes it (the default first), else the default, else any. */
159684
+ instanceForDevice(deviceId) {
159685
+ const key = String(deviceId);
159686
+ const ordered = [...this.bridges.values()].toSorted((x, y) => Number(y.id === HAP_DEFAULT_INSTANCE_ID) - Number(x.id === HAP_DEFAULT_INSTANCE_ID));
159687
+ return ordered.find((b) => b.exposed.has(key)) ?? ordered.find((b) => b.findEntry(deviceId) !== null) ?? ordered[0] ?? null;
159688
+ }
159689
+ requireBridge(instanceId) {
159690
+ const inst = this.bridges.get(instanceId);
159691
+ if (inst === void 0) throw new ExportInstanceUnknownError(EXPORT_HAP_ADDON_ID, instanceId);
159692
+ return inst;
159693
+ }
159694
+ /** Bring a record's runtime up from the record: (re)publish its bridge and every exposed device. */
159695
+ async startInstance(id) {
159696
+ await this.stopInstance(id);
159697
+ const resolved = await this.requireInstances().readResolved(id);
159698
+ if (resolved === null || !resolved.enabled) return;
159699
+ if (resolved.secrets === "unavailable") {
159700
+ this.ctx.logger.error("export-hap: bridge not started — the keychain cannot serve its setup code", { meta: { instanceId: id } });
159701
+ return;
159702
+ }
159703
+ const identity = identityOfBody(resolved.body);
159704
+ const exposure = await this.loadExposure(id);
159705
+ const inst = new BridgeInstance(id, resolved.body.name, identity, new BridgeHost({
159706
+ displayName: resolved.body.name,
159707
+ uuid: identity.uuid,
159708
+ pincode: identity.pincode,
159709
+ bind: this.bind,
159710
+ logger: this.ctx.logger
159711
+ }), exposure);
159712
+ this.bridges.set(id, inst);
159713
+ this.warnOnDuplicateName(inst);
158253
159714
  const validKinds = new Set(SUPPORTED_MAPPER_KINDS);
158254
- const cleaned = this.config.exposed.filter((entry) => {
159715
+ const cleaned = inst.exposure.devices.filter((entry) => {
158255
159716
  if (validKinds.has(entry.mapperKind)) return true;
158256
159717
  this.ctx.logger.withTags({ deviceId: Number.parseInt(entry.deviceId, 10) }).info("export-hap: dropping stale exposed entry (unknown mapperKind)", { meta: { mapperKind: entry.mapperKind } });
158257
159718
  return false;
158258
159719
  });
158259
- if (cleaned.length !== this.config.exposed.length) await this.updateGlobalSettings({ exposed: cleaned });
159720
+ if (cleaned.length !== inst.exposure.devices.length) await this.setExposedDevices(inst, cleaned);
158260
159721
  for (const entry of cleaned) {
158261
159722
  const log = this.ctx.logger.withTags({ deviceId: Number.parseInt(entry.deviceId, 10) });
158262
159723
  try {
158263
- await this.attachMapper(entry);
159724
+ await this.attachMapper(inst, entry);
158264
159725
  const numericId = Number.parseInt(entry.deviceId, 10);
158265
159726
  if (Number.isFinite(numericId)) {
158266
- const fp = await this.computeExportFingerprint(numericId);
158267
- if (fp !== null) await this.persistFingerprint(numericId, fp);
159727
+ const fp = await this.computeExportFingerprint(inst, numericId);
159728
+ if (fp !== null) await this.persistFingerprint(inst, numericId, fp);
158268
159729
  }
158269
159730
  } catch (err) {
158270
159731
  log.warn("export-hap: failed to re-attach mapper on boot", { meta: { error: errMsg(err) } });
158271
159732
  }
158272
159733
  }
158273
- this.actionExports = new ActionExports({
159734
+ inst.actionExports = new ActionExports({
158274
159735
  api: this.ctx.api,
158275
159736
  logger: this.ctx.logger,
159737
+ instanceId: id,
158276
159738
  publish: async (accessory) => {
158277
- if (this.bridgeHost !== null && await this.bridgeHost.add(accessory)) return;
159739
+ if (await inst.bridgeHost.add(accessory)) return;
158278
159740
  await publishStandalone(accessory, {
158279
- pincode: this.pincode,
159741
+ pincode: inst.pincode,
158280
159742
  port: 0,
158281
159743
  bind: this.bind,
158282
159744
  logger: this.ctx.logger
158283
159745
  });
158284
159746
  },
158285
159747
  unpublish: async (accessory) => {
158286
- if (this.bridgeHost?.holds(accessory) === true) {
158287
- this.bridgeHost.remove(accessory);
159748
+ if (inst.bridgeHost.holds(accessory)) {
159749
+ inst.bridgeHost.remove(accessory);
158288
159750
  return;
158289
159751
  }
158290
159752
  await unpublishAccessory(accessory, this.ctx.logger);
158291
159753
  },
158292
- persist: (entries) => this.updateGlobalSettings({ exposedActions: [...entries] })
158293
- }, this.config.exposedActions ?? []);
158294
- await this.actionExports.attachAll();
158295
- await this.actionExports.reconcile();
158296
- this.ctx.addDisposer(async () => {
158297
- await this.actionExports?.dispose();
158298
- await this.detachAll();
158299
- await this.bridgeHost?.dispose();
159754
+ persist: (entries) => this.setExposedActions(inst, entries)
159755
+ }, inst.exposure.actions);
159756
+ await inst.actionExports.attachAll();
159757
+ await inst.actionExports.reconcile();
159758
+ this.ctx.logger.info("export-hap: bridge started", { meta: {
159759
+ instanceId: id,
159760
+ name: inst.name,
159761
+ devices: inst.exposed.size
159762
+ } });
159763
+ }
159764
+ /** Take a bridge's runtime down. Its pairing files stay: a stop is not a withdrawal. */
159765
+ async stopInstance(id) {
159766
+ const inst = this.bridges.get(id);
159767
+ if (inst === void 0) return;
159768
+ this.bridges.delete(id);
159769
+ for (const timer of inst.pendingRebuildTimers.values()) clearTimeout(timer);
159770
+ inst.pendingRebuildTimers.clear();
159771
+ await inst.actionExports?.dispose();
159772
+ await this.detachAll(inst);
159773
+ await inst.bridgeHost.dispose();
159774
+ }
159775
+ /** A record changed: re-apply it. An edit that moved nothing the bridge publishes republishes nothing. */
159776
+ async applyChange(id, change) {
159777
+ if (change === "deleted") {
159778
+ await this.removeInstance(id);
159779
+ return;
159780
+ }
159781
+ const resolved = await this.requireInstances().readResolved(id);
159782
+ if (resolved === null || !resolved.enabled) {
159783
+ await this.stopInstance(id);
159784
+ return;
159785
+ }
159786
+ const running = this.bridges.get(id);
159787
+ if (change === "updated" && running !== void 0 && resolved.secrets === "resolved") {
159788
+ const next = identityOfBody(resolved.body);
159789
+ if (running.name === resolved.body.name && running.identity.uuid === next.uuid && running.identity.username === next.username && running.identity.pincode === next.pincode) return;
159790
+ }
159791
+ await this.startInstance(id);
159792
+ }
159793
+ /**
159794
+ * A bridge was deleted: unpublish it, wipe the pairing state of every accessory it carried (a
159795
+ * leftover blob makes a re-created accessory advertise as already paired) and drop its exposure.
159796
+ */
159797
+ async removeInstance(id) {
159798
+ const uuids = this.bridges.get(id)?.pairingUuids() ?? [];
159799
+ await this.stopInstance(id);
159800
+ for (const uuid of uuids) clearPairingFiles(uuid, this.ctx.logger);
159801
+ await this.exposureHandle().delete(id);
159802
+ if (id === "export-hap") await this.updateGlobalSettings({ exportSyncState: {} });
159803
+ this.ctx.logger.info("export-hap: bridge removed", { meta: { instanceId: id } });
159804
+ }
159805
+ /**
159806
+ * "Regenerate" (operator decision): a new setup code, every pairing of this bridge cleared and
159807
+ * the bridge republished. Every controller has to pair again; the instance and its exposed
159808
+ * devices stay.
159809
+ */
159810
+ regenerateBridge(instanceId) {
159811
+ return this.enqueue(async () => {
159812
+ const uuids = this.requireBridge(instanceId).pairingUuids();
159813
+ await this.stopInstance(instanceId);
159814
+ for (const uuid of uuids) clearPairingFiles(uuid, this.ctx.logger);
159815
+ await this.requireRecords().kind(hapBridgesKind).patch(instanceId, { pincode: generatePincode() });
159816
+ await this.startInstance(instanceId);
159817
+ this.ctx.logger.info("export-hap: bridge setup code regenerated; pairings cleared", { meta: {
159818
+ instanceId,
159819
+ accessories: uuids.length
159820
+ } });
159821
+ return { regenerated: true };
158300
159822
  });
158301
- this.subscribeDeviceProvisionedForReconcile();
158302
- this.subscribeDeviceReadyForReconcile();
158303
- this.subscribeStorageLocationsForClips();
158304
- this.disposeSharedRebuildTimers();
158305
- const ownInstance = (instanceId) => assertOwnExportInstance("export-hap", EXPORT_HAP_ADDON_ID, instanceId);
158306
- const provider = {
158307
- getStatus: async (input) => {
158308
- ownInstance(statusInstanceOf(input));
158309
- const anyPaired = Array.from(this.exposed.values()).some((m) => accessoryPaired(m.accessory));
158310
- const linkState = this.lastError ? "error" : anyPaired ? "linked" : "unlinked";
158311
- const setup = this.buildSetupBlock();
158312
- return {
158313
- linkState,
158314
- exposedDeviceCount: this.exposed.size,
158315
- ...this.lastError ? { error: this.lastError } : {},
158316
- ...setup ? { setup } : {}
158317
- };
158318
- },
158319
- listInstances: async () => [{
158320
- instanceId: EXPORT_HAP_ADDON_ID,
158321
- name: "HomeKit",
158322
- enabled: true,
159823
+ }
159824
+ warnOnDuplicateName(inst) {
159825
+ const key = inst.name.trim().toLowerCase();
159826
+ const others = [...this.bridges.values()].filter((b) => b.id !== inst.id && b.name.trim().toLowerCase() === key);
159827
+ if (others.length === 0) return;
159828
+ this.ctx.logger.warn("export-hap: two bridges share a name — iOS Home lists them under the same label", { meta: {
159829
+ instanceId: inst.id,
159830
+ name: inst.name,
159831
+ others: others.map((b) => b.id)
159832
+ } });
159833
+ }
159834
+ /** The instance form: the setup code is READ-ONLY (it changes only through Regenerate). */
159835
+ bridgeForm(id) {
159836
+ const inst = id === null ? void 0 : this.bridges.get(id);
159837
+ let qr = "";
159838
+ try {
159839
+ qr = inst?.bridgeHost.accessory?.setupURI() ?? "";
159840
+ } catch (err) {
159841
+ this.ctx.logger.debug("export-hap: bridge setupURI failed", { meta: {
159842
+ instanceId: id,
159843
+ error: errMsg(err)
159844
+ } });
159845
+ }
159846
+ return this.schema({ sections: [{
159847
+ id: "bridge",
159848
+ title: "HomeKit bridge",
159849
+ description: "One HomeKit bridge carries every exported device that is not a camera (switches, sensors, locks, alarm panels); each camera is published as its own accessory with the same setup code. In iOS Home tap + → Add Accessory and enter the setup code.",
159850
+ fields: [...inst === void 0 ? [] : [{
159851
+ type: "info",
159852
+ key: "setupCode",
159853
+ label: "Setup code",
159854
+ content: inst.pincode
159855
+ }, ...qr === "" ? [] : [{
159856
+ type: "qr-code",
159857
+ key: "setupQr",
159858
+ label: "Pairing QR",
159859
+ caption: "Scan with the iOS Camera app.",
159860
+ value: qr,
159861
+ size: 192
159862
+ }]], ...id === null ? [] : [{
159863
+ type: "addon-action-button",
159864
+ key: "__regenerate-bridge",
159865
+ label: "Regenerate setup code",
159866
+ description: "Creates a new setup code and unpairs every controller from this bridge: each iPhone, iPad and Apple TV must add it again. The bridge and its exported devices stay.",
159867
+ addonId: EXPORT_HAP_ADDON_ID,
159868
+ action: "regenerateBridge",
159869
+ buttonLabel: "Regenerate",
159870
+ variant: "danger",
159871
+ paramsStatic: { instanceId: id },
159872
+ confirmMessage: "Regenerate the setup code? Every controller paired with this bridge is unpaired, its pairings are cleared and the bridge is republished. You must pair each one again with the new code."
159873
+ }]]
159874
+ }] });
159875
+ }
159876
+ /** Whole-addon status of the bridges: linked when any is paired. */
159877
+ statusOf(bridges) {
159878
+ const anyPaired = bridges.some((b) => Array.from(b.exposed.values()).some((m) => accessoryPaired(m.accessory)));
159879
+ const linkState = this.lastError ? "error" : anyPaired ? "linked" : "unlinked";
159880
+ const setup = bridges.length > 0 ? this.buildSetupBlock(bridges[0]) : null;
159881
+ return {
159882
+ linkState,
159883
+ exposedDeviceCount: new Set(bridges.flatMap((b) => [...b.exposed.keys()])).size,
159884
+ ...this.lastError ? { error: this.lastError } : {},
159885
+ ...setup ? { setup } : {}
159886
+ };
159887
+ }
159888
+ /** The bridges a read names: one, or (no id) all of them with the default first. */
159889
+ bridgesOf(instanceId) {
159890
+ if (instanceId !== void 0) return [this.requireBridge(instanceId)];
159891
+ return [...this.bridges.values()].toSorted((x, y) => Number(y.id === HAP_DEFAULT_INSTANCE_ID) - Number(x.id === HAP_DEFAULT_INSTANCE_ID));
159892
+ }
159893
+ buildExportProvider() {
159894
+ return {
159895
+ getStatus: async (input) => this.statusOf(this.bridgesOf(statusInstanceOf(input))),
159896
+ listInstances: async () => (await this.requireInstances().listResolved()).map((row) => ({
159897
+ instanceId: row.id,
159898
+ name: row.body.name,
159899
+ enabled: row.enabled,
158323
159900
  kind: "hap-bridge"
158324
- }],
159901
+ })),
158325
159902
  listSupportedDeviceKinds: async ({ instanceId }) => {
158326
- ownInstance(instanceId);
159903
+ this.bridgesOf(instanceId);
158327
159904
  return [...HAP_EXPORTABLE_DEVICE_TYPES];
158328
159905
  },
158329
- listExposedDevices: async ({ instanceId }) => {
158330
- ownInstance(instanceId);
158331
- return Array.from(this.exposed.entries()).map(([deviceId, m]) => {
158332
- const entry = this.config.exposed.find((e) => e.deviceId === deviceId);
158333
- return {
158334
- deviceId,
158335
- exposedAs: m.accessory.displayName,
158336
- ...entry?.capabilities ? { capabilities: [...entry.capabilities] } : {}
158337
- };
158338
- });
158339
- },
158340
- exposeDevice: async ({ instanceId, deviceId, capabilities }) => {
158341
- ownInstance(instanceId);
158342
- return this.exposeDevice(deviceId, capabilities);
158343
- },
158344
- unexposeDevice: async ({ instanceId, deviceId }) => {
158345
- ownInstance(instanceId);
158346
- return this.unexposeDevice(deviceId);
158347
- },
159906
+ listExposedDevices: async ({ instanceId }) => this.bridgesOf(instanceId).flatMap((inst) => Array.from(inst.exposed.entries()).map(([deviceId, m]) => {
159907
+ const entry = inst.exposure.devices.find((e) => e.deviceId === deviceId);
159908
+ return {
159909
+ deviceId,
159910
+ exposedAs: m.accessory.displayName,
159911
+ ...entry?.capabilities ? { capabilities: [...entry.capabilities] } : {}
159912
+ };
159913
+ })),
159914
+ exposeDevice: async ({ instanceId, deviceId, capabilities }) => this.exposeDevice(this.requireBridge(instanceId), deviceId, capabilities),
159915
+ unexposeDevice: async ({ instanceId, deviceId }) => this.unexposeDevice(this.requireBridge(instanceId), deviceId),
158348
159916
  listSupportedEntityKinds: async () => ["device", "action"],
158349
159917
  listExposedEntities: async ({ instanceId }) => {
158350
- ownInstance(instanceId);
158351
- await this.actionExports?.reconcile();
158352
- return [...Array.from(this.exposed.entries()).map(([deviceId, m]) => ({
158353
- entity: {
158354
- kind: "device",
158355
- deviceId
158356
- },
158357
- exposedAs: m.accessory.displayName
158358
- })), ...this.actionExports?.list() ?? []];
159918
+ const out = [];
159919
+ for (const inst of this.bridgesOf(instanceId)) {
159920
+ await inst.actionExports?.reconcile();
159921
+ out.push(...Array.from(inst.exposed.entries()).map(([deviceId, m]) => ({
159922
+ entity: {
159923
+ kind: "device",
159924
+ deviceId
159925
+ },
159926
+ exposedAs: m.accessory.displayName
159927
+ })), ...inst.actionExports?.list() ?? []);
159928
+ }
159929
+ return out;
158359
159930
  },
158360
159931
  exposeEntity: async ({ instanceId, entity }) => {
158361
- ownInstance(instanceId);
158362
- if (entity.kind === "device") return this.exposeDevice(entity.deviceId);
158363
- if (entity.kind === "action") return this.requireActionExports().expose(entity.actionId);
159932
+ const inst = this.requireBridge(instanceId);
159933
+ if (entity.kind === "device") return this.exposeDevice(inst, entity.deviceId);
159934
+ if (entity.kind === "action") return this.requireActionExports(inst).expose(entity.actionId);
158364
159935
  throw new Error("export-hap: a notification target cannot be exported to HomeKit");
158365
159936
  },
158366
159937
  unexposeEntity: async ({ instanceId, entity }) => {
158367
- ownInstance(instanceId);
158368
- if (entity.kind === "device") return this.unexposeDevice(entity.deviceId);
158369
- if (entity.kind === "action") return this.requireActionExports().unexpose(entity.actionId);
159938
+ const inst = this.requireBridge(instanceId);
159939
+ if (entity.kind === "device") return this.unexposeDevice(inst, entity.deviceId);
159940
+ if (entity.kind === "action") return this.requireActionExports(inst).unexpose(entity.actionId);
158370
159941
  throw new Error("export-hap: a notification target cannot be exported to HomeKit");
158371
159942
  },
158372
159943
  getDeviceSettingsContribution: (input) => this.buildDeviceSettingsContribution(input.deviceId),
158373
159944
  getDeviceLiveContribution: async () => null,
158374
159945
  applyDeviceSettingsPatch: (input) => this.applyDeviceSettingsPatch(input.deviceId, input.patch)
158375
159946
  };
158376
- const clipsProvider = createHksvVideoclipsProvider({
158377
- logger: this.ctx.logger.child("hksv-clips"),
158378
- addonId: EXPORT_HAP_ADDON_ID,
158379
- describeCamera: (deviceId) => describeHksvCamera(this.findEntry(deviceId), this.hksvBuilds.lastFor(deviceId), readHomekitRecordingActive(this.exposed.get(String(deviceId))?.accessories ?? [])),
158380
- readCatalog: async (deviceId) => await this.hksvClipStore?.listCatalog(deviceId) ?? { kind: "no-root" },
158381
- locationRefusal: () => this.hksvClipLocation?.lastRefusal ?? null,
158382
- mediaUrl: (deviceId, stem) => this.hksvClipUrl("media", deviceId, stem),
158383
- thumbnailUrl: (deviceId, stem) => this.hksvClipUrl("thumb", deviceId, stem),
158384
- clipFilePath: async (deviceId, stem) => await this.hksvClipStore?.artifactPath(deviceId, stem, "clip") ?? null
158385
- });
158386
- return [{
158387
- capability: deviceExportCapability,
158388
- provider
158389
- }, {
158390
- capability: videoclipsCapability,
158391
- provider: clipsProvider
158392
- }];
158393
159947
  }
158394
- async onConfigChanged() {
158395
- if (this.config.fixedPin && isValidPincode(this.config.fixedPin) && this.config.identity.pincode !== this.config.fixedPin && this.config.identity.username !== "") {
158396
- const updated = {
158397
- username: this.config.identity.username,
158398
- uuid: this.config.identity.uuid,
158399
- pincode: this.config.fixedPin
158400
- };
158401
- await this.updateGlobalSettings({ identity: updated });
158402
- }
159948
+ requireInstances() {
159949
+ if (this.instances === null) throw new Error("export-hap: instances are not initialised");
159950
+ return this.instances;
158403
159951
  }
158404
- /**
158405
- * Resolve the persistent bridge identity. Empty `username` is the
158406
- * "first boot" sentinel — generate fresh + persist. On subsequent
158407
- * boots the persisted record is reused. An operator-supplied
158408
- * `fixedPin` overrides the persisted pincode (useful for CI replay)
158409
- * but never the username/uuid (those drive the iOS pairing record).
158410
- */
158411
- async ensureIdentity() {
158412
- const current = this.config.identity;
158413
- const fixedPin = this.config.fixedPin && isValidPincode(this.config.fixedPin) ? this.config.fixedPin : null;
158414
- if (current.username !== "" && current.uuid !== "" && current.pincode !== "") {
158415
- if (fixedPin && fixedPin !== current.pincode) {
158416
- const updated = {
158417
- username: current.username,
158418
- uuid: current.uuid,
158419
- pincode: fixedPin
158420
- };
158421
- await this.updateGlobalSettings({ identity: updated });
158422
- return updated;
158423
- }
158424
- return current;
158425
- }
158426
- const fresh = {
158427
- username: generateUsername(),
158428
- pincode: fixedPin ?? generatePincode(),
158429
- uuid: buildBridgeUuid(this.config.bridgeName)
159952
+ requireRecords() {
159953
+ const records = this.ctx.records;
159954
+ if (records === void 0) throw new Error("export-hap: records are not available");
159955
+ return records;
159956
+ }
159957
+ /** The ports the identity migration reads and writes through. */
159958
+ identityMigrationPorts() {
159959
+ const handle = this.requireRecords().kind(hapBridgesKind);
159960
+ return {
159961
+ readLegacyIdentity: async () => legacyIdentityOf((await this.resolveGlobalStore())["identity"]),
159962
+ clearLegacyIdentity: () => this.updateGlobalSettingsAsOperator({ identity: null }),
159963
+ readBridgeName: async () => {
159964
+ const name = (await this.resolveGlobalStore())["bridgeName"];
159965
+ return typeof name === "string" ? name : "";
159966
+ },
159967
+ putDefaultRecord: async (body) => {
159968
+ if (await handle.get("export-hap") !== null) return "exists";
159969
+ try {
159970
+ await handle.put({
159971
+ id: HAP_DEFAULT_INSTANCE_ID,
159972
+ data: body
159973
+ }, { ifRev: 0 });
159974
+ } catch (err) {
159975
+ if (err instanceof RevConflictError) return "exists";
159976
+ throw err;
159977
+ }
159978
+ return "created";
159979
+ },
159980
+ readDefaultRecord: async () => (await handle.getResolved("export-hap"))?.data ?? null,
159981
+ patchDefaultName: async (name) => {
159982
+ await handle.patch(HAP_DEFAULT_INSTANCE_ID, { name });
159983
+ },
159984
+ clearFixedPin: () => this.updateGlobalSettingsAsOperator({ fixedPin: SECRET_CLEAR })
158430
159985
  };
158431
- await this.updateGlobalSettings({ identity: fresh });
158432
- this.ctx.logger.info("export-hap: generated bridge identity on first boot", { meta: { username: fresh.username } });
158433
- return fresh;
159986
+ }
159987
+ /** The default bridge: read its record, or mint it on a first boot with no bridge at all. */
159988
+ async ensureDefaultBridge() {
159989
+ const handle = this.requireRecords().kind(hapBridgesKind);
159990
+ const boot = await resolveDefaultBridge({
159991
+ readRecord: async () => {
159992
+ const resolved = await this.requireInstances().readResolved(HAP_DEFAULT_INSTANCE_ID);
159993
+ if (resolved === null) return { kind: "absent" };
159994
+ return resolved.secrets === "resolved" ? {
159995
+ kind: "resolved",
159996
+ body: resolved.body
159997
+ } : { kind: "unavailable" };
159998
+ },
159999
+ legacyIdentityPresent: async () => legacyIdentityOf((await this.resolveGlobalStore())["identity"]) !== null,
160000
+ otherBridgesExist: async () => (await this.requireInstances().listResolved()).some((row) => row.id !== HAP_DEFAULT_INSTANCE_ID),
160001
+ putFresh: async (body) => {
160002
+ await handle.put({
160003
+ id: HAP_DEFAULT_INSTANCE_ID,
160004
+ data: body
160005
+ }, { ifRev: 0 });
160006
+ },
160007
+ mint: () => ({
160008
+ name: DEFAULT_BRIDGE_NAME,
160009
+ username: generateUsername(),
160010
+ uuid: buildBridgeUuid(DEFAULT_BRIDGE_NAME),
160011
+ pincode: generatePincode()
160012
+ })
160013
+ });
160014
+ if (boot.kind === "minted") this.ctx.logger.info("export-hap: generated bridge identity on first boot", { meta: { username: boot.identity.username } });
158434
160015
  }
158435
160016
  /**
158436
160017
  * Build the generic `device-export` `setup` block surfaced via
@@ -158439,10 +160020,10 @@ var ExportHapAddon = class extends BaseAddon {
158439
160020
  * a copyable field, and a short pairing instruction. Returns `null`
158440
160021
  * until the bridge has booted and produced both values.
158441
160022
  */
158442
- buildSetupBlock() {
158443
- const setupCode = this.config.identity.pincode;
160023
+ buildSetupBlock(inst) {
160024
+ const setupCode = inst.pincode;
158444
160025
  if (!setupCode) return null;
158445
- const qr = firstExposedAccessorySetupUri(this.exposed, this.ctx.logger);
160026
+ const qr = firstExposedAccessorySetupUri(inst.exposed, this.ctx.logger);
158446
160027
  return {
158447
160028
  ...qr !== void 0 ? { qr } : {},
158448
160029
  fields: [{
@@ -158463,18 +160044,18 @@ var ExportHapAddon = class extends BaseAddon {
158463
160044
  * Measured 2026-09-17 — the stored value read `mid` while the advertisement
158464
160045
  * still said `streamPreference=auto`.
158465
160046
  */
158466
- async exposeDevice(deviceId, capabilities, settings) {
160047
+ async exposeDevice(inst, deviceId, capabilities, settings) {
158467
160048
  const numericId = Number.parseInt(deviceId, 10);
158468
160049
  const log = this.ctx.logger.withTags({ deviceId: numericId });
158469
- if (this.exposed.has(deviceId)) {
160050
+ if (inst.exposed.has(deviceId)) {
158470
160051
  log.debug("export-hap: device already exposed — refreshing capabilities");
158471
- await this.detachMapper(deviceId);
160052
+ await this.detachMapper(inst, deviceId);
158472
160053
  }
158473
160054
  const summary = await this.fetchDeviceSummary(numericId);
158474
160055
  const mapperKind = pickMapperKind(summary?.type);
158475
160056
  if (!mapperKind) throw new Error(`export-hap: device ${numericId} has type '${summary?.type ?? "unknown"}', which HomeKit export does not support`);
158476
160057
  const displayName = summary?.name ?? `Device ${deviceId}`;
158477
- const previous = this.config.exposed.find((e) => e.deviceId === deviceId);
160058
+ const previous = inst.exposure.devices.find((e) => e.deviceId === deviceId);
158478
160059
  const rebuilt = {
158479
160060
  deviceId,
158480
160061
  displayName,
@@ -158486,37 +160067,38 @@ var ExportHapAddon = class extends BaseAddon {
158486
160067
  ...rebuilt,
158487
160068
  settings
158488
160069
  }, previous, ["settings", "capabilities"]);
158489
- const attached = await this.attachMapper(baseEntry);
160070
+ const attached = await this.attachMapper(inst, baseEntry);
158490
160071
  const finalEntry = {
158491
160072
  ...baseEntry,
158492
160073
  childAccessoryUuids: attached.childAccessoryUuids
158493
160074
  };
158494
- const next = this.config.exposed.filter((e) => e.deviceId !== deviceId);
160075
+ const next = inst.exposure.devices.filter((e) => e.deviceId !== deviceId);
158495
160076
  next.push(finalEntry);
158496
- await this.updateGlobalSettings({ exposed: next });
160077
+ await this.setExposedDevices(inst, next);
158497
160078
  if (Number.isFinite(numericId)) {
158498
- const fp = await this.computeExportFingerprint(numericId);
158499
- if (fp !== null) await this.persistFingerprint(numericId, fp);
160079
+ const fp = await this.computeExportFingerprint(inst, numericId);
160080
+ if (fp !== null) await this.persistFingerprint(inst, numericId, fp);
158500
160081
  }
158501
160082
  log.info("export-hap: exposed device", { meta: {
160083
+ instanceId: inst.id,
158502
160084
  displayName,
158503
160085
  mapperKind,
158504
160086
  childCount: attached.childAccessoryUuids.length
158505
160087
  } });
158506
160088
  }
158507
- async unexposeDevice(deviceId, options = {}) {
160089
+ async unexposeDevice(inst, deviceId, options = {}) {
158508
160090
  const numericId = Number.parseInt(deviceId, 10);
158509
160091
  const log = this.ctx.logger.withTags({ deviceId: numericId });
158510
- const mapperKind = this.findEntry(numericId)?.mapperKind ?? "camera";
158511
- await this.detachMapper(deviceId);
158512
- const next = this.config.exposed.filter((e) => e.deviceId !== deviceId);
158513
- if (next.length !== this.config.exposed.length) await this.updateGlobalSettings({ exposed: next });
158514
- if (options.clearPairing !== false) clearPairingFiles(accessoryUuidFor(mapperKind, numericId), this.ctx.logger);
158515
- await this.forgetFingerprint(numericId);
160092
+ const mapperKind = inst.findEntry(numericId)?.mapperKind ?? "camera";
160093
+ await this.detachMapper(inst, deviceId);
160094
+ const next = inst.exposure.devices.filter((e) => e.deviceId !== deviceId);
160095
+ if (next.length !== inst.exposure.devices.length) await this.setExposedDevices(inst, next);
160096
+ if (options.clearPairing !== false) clearPairingFiles(inst.accessoryUuidOf(mapperKind, numericId), this.ctx.logger);
160097
+ await this.forgetFingerprint(inst, numericId);
158516
160098
  this.hksvBuilds.forget(numericId);
158517
- log.info("export-hap: unexposed device");
160099
+ log.info("export-hap: unexposed device", { meta: { instanceId: inst.id } });
158518
160100
  }
158519
- async attachMapper(entry) {
160101
+ async attachMapper(inst, entry) {
158520
160102
  const factory = getMapperFactory(entry.mapperKind);
158521
160103
  const entrySettings = entry.settings ?? DEFAULT_DEVICE_SETTINGS;
158522
160104
  const mapper = await factory({
@@ -158524,6 +160106,7 @@ var ExportHapAddon = class extends BaseAddon {
158524
160106
  deviceId: entry.deviceId,
158525
160107
  displayName: entry.displayName,
158526
160108
  options: {
160109
+ instanceId: inst.id,
158527
160110
  decodeMemos: this.decodeMemos,
158528
160111
  resolveFfmpeg: this.pinnedFfmpeg,
158529
160112
  hksvClipStore: this.hksvClipStore,
@@ -158543,29 +160126,29 @@ var ExportHapAddon = class extends BaseAddon {
158543
160126
  useBridge: entry.settings?.useBridge
158544
160127
  });
158545
160128
  for (const accessory of mapper.accessories) {
158546
- if (wantsBridge && this.bridgeHost !== null && await this.bridgeHost.add(accessory)) continue;
160129
+ if (wantsBridge && await inst.bridgeHost.add(accessory)) continue;
158547
160130
  await publishStandalone(accessory, {
158548
- pincode: this.pincode,
160131
+ pincode: inst.pincode,
158549
160132
  port: 0,
158550
160133
  bind: this.bind,
158551
160134
  logger: this.ctx.logger
158552
160135
  });
158553
160136
  }
158554
- this.exposed.set(entry.deviceId, mapper);
160137
+ inst.exposed.set(entry.deviceId, mapper);
158555
160138
  return { childAccessoryUuids: [] };
158556
160139
  }
158557
- async detachMapper(deviceId) {
158558
- const pendingTimer = this.pendingRebuildTimers.get(deviceId);
160140
+ async detachMapper(inst, deviceId) {
160141
+ const pendingTimer = inst.pendingRebuildTimers.get(deviceId);
158559
160142
  if (pendingTimer) {
158560
160143
  clearTimeout(pendingTimer);
158561
- this.pendingRebuildTimers.delete(deviceId);
160144
+ inst.pendingRebuildTimers.delete(deviceId);
158562
160145
  }
158563
- const mapper = this.exposed.get(deviceId);
160146
+ const mapper = inst.exposed.get(deviceId);
158564
160147
  if (!mapper) return;
158565
- this.exposed.delete(deviceId);
160148
+ inst.exposed.delete(deviceId);
158566
160149
  for (const accessory of mapper.accessories) {
158567
- if (this.bridgeHost?.holds(accessory) === true) {
158568
- this.bridgeHost.remove(accessory);
160150
+ if (inst.bridgeHost.holds(accessory)) {
160151
+ inst.bridgeHost.remove(accessory);
158569
160152
  continue;
158570
160153
  }
158571
160154
  await unpublishAccessory(accessory, this.ctx.logger);
@@ -158574,21 +160157,22 @@ var ExportHapAddon = class extends BaseAddon {
158574
160157
  this.ctx.logger.withTags({ deviceId: Number.parseInt(deviceId, 10) }).warn("export-hap: mapper dispose failed", { meta: { error: errMsg(err) } });
158575
160158
  });
158576
160159
  }
158577
- requireActionExports() {
158578
- if (this.actionExports === null) throw new Error("export-hap: addon is not initialised");
158579
- return this.actionExports;
160160
+ requireActionExports(inst) {
160161
+ if (inst.actionExports === null) throw new Error("export-hap: bridge is not initialised");
160162
+ return inst.actionExports;
158580
160163
  }
158581
- async detachAll() {
158582
- const ids = Array.from(this.exposed.keys());
158583
- for (const id of ids) await this.detachMapper(id);
160164
+ async detachAll(inst) {
160165
+ const ids = Array.from(inst.exposed.keys());
160166
+ for (const id of ids) await this.detachMapper(inst, id);
158584
160167
  }
158585
- /** Pending rebuild timers per deviceId — used to debounce. Cleared
158586
- * on detach so stale timers can't republish a removed accessory. */
158587
- pendingRebuildTimers = /* @__PURE__ */ new Map();
158588
160168
  /** Deterministic HAP accessory UUID for a device — the same one the
158589
160169
  * orchestrator built it with (`mappers/kind.ts`). */
158590
- hapAccessoryUuid(deviceId) {
158591
- return accessoryUuidFor(this.findEntry(deviceId)?.mapperKind ?? "camera", deviceId);
160170
+ hapAccessoryUuid(inst, deviceId) {
160171
+ return inst.accessoryUuidOf(inst.findEntry(deviceId)?.mapperKind ?? "camera", deviceId);
160172
+ }
160173
+ /** The reconcile cache of a bridge: the default one is persisted, the others live in memory (boot re-attach seeds them). */
160174
+ syncStateOf(inst) {
160175
+ return inst.id === "export-hap" ? syncStateFromJson(this.config.exportSyncState) : inst.syncState;
158592
160176
  }
158593
160177
  /**
158594
160178
  * Export fingerprint of a device from its PERSISTED features + type
@@ -158606,7 +160190,7 @@ var ExportHapAddon = class extends BaseAddon {
158606
160190
  * A brand-new un-probed device with no persisted entry falls back to its
158607
160191
  * fresh fingerprint (publishes once, acceptable).
158608
160192
  */
158609
- async computeExportFingerprint(deviceId) {
160193
+ async computeExportFingerprint(inst, deviceId) {
158610
160194
  try {
158611
160195
  const device = await this.ctx.api.deviceManager.getDevice.query({ deviceId });
158612
160196
  if (!device) return null;
@@ -158615,10 +160199,10 @@ var ExportHapAddon = class extends BaseAddon {
158615
160199
  deviceType: device.type,
158616
160200
  features: device.features
158617
160201
  });
158618
- const persisted = syncStateFromJson(this.config.exportSyncState).get(deviceId)?.fingerprint;
160202
+ const persisted = this.syncStateOf(inst).get(deviceId)?.fingerprint;
158619
160203
  const withToken = withRecordabilityToken({
158620
160204
  base: fresh,
158621
- token: await this.readRecordabilityToken(deviceId, device.type),
160205
+ token: await this.readRecordabilityToken(inst, deviceId, device.type),
158622
160206
  persisted
158623
160207
  });
158624
160208
  return resolveExportFingerprint({
@@ -158638,12 +160222,12 @@ var ExportHapAddon = class extends BaseAddon {
158638
160222
  * republish every non-camera accessory once for nothing) and for a camera
158639
160223
  * whose profiles could not be read right now.
158640
160224
  */
158641
- async readRecordabilityToken(deviceId, type) {
160225
+ async readRecordabilityToken(inst, deviceId, type) {
158642
160226
  if (pickMapperKind(type) !== "camera") return null;
158643
160227
  try {
158644
160228
  const entries = await (await this.ctx.fetchDevice(deviceId)).cameraStreams?.getProfileRtspEntries({});
158645
160229
  return recordabilityTokenFor({
158646
- allowTranscode: this.findEntry(deviceId)?.settings?.allowTranscode !== false,
160230
+ allowTranscode: inst.findEntry(deviceId)?.settings?.allowTranscode !== false,
158647
160231
  entries: entries ?? null
158648
160232
  });
158649
160233
  } catch {
@@ -158652,20 +160236,20 @@ var ExportHapAddon = class extends BaseAddon {
158652
160236
  }
158653
160237
  /** Persist a device's current export fingerprint into `exportSyncState`
158654
160238
  * (best-effort; called after a successful attach). */
158655
- async persistFingerprint(deviceId, fingerprint) {
158656
- const state = syncStateFromJson(this.config.exportSyncState);
160239
+ async persistFingerprint(inst, deviceId, fingerprint) {
160240
+ const state = this.syncStateOf(inst);
158657
160241
  state.set(deviceId, {
158658
160242
  fingerprint,
158659
- externalIds: [this.hapAccessoryUuid(deviceId)]
160243
+ externalIds: [this.hapAccessoryUuid(inst, deviceId)]
158660
160244
  });
158661
- await this.updateGlobalSettings({ exportSyncState: syncStateToJson(state) });
160245
+ if (inst.id === "export-hap") await this.updateGlobalSettings({ exportSyncState: syncStateToJson(state) });
158662
160246
  }
158663
160247
  /** Drop a device's `exportSyncState` entry (on unexpose). */
158664
- async forgetFingerprint(deviceId) {
158665
- const state = syncStateFromJson(this.config.exportSyncState);
160248
+ async forgetFingerprint(inst, deviceId) {
160249
+ const state = this.syncStateOf(inst);
158666
160250
  if (!state.has(deviceId)) return;
158667
160251
  state.delete(deviceId);
158668
- await this.updateGlobalSettings({ exportSyncState: syncStateToJson(state) });
160252
+ if (inst.id === "export-hap") await this.updateGlobalSettings({ exportSyncState: syncStateToJson(state) });
158669
160253
  }
158670
160254
  /**
158671
160255
  * Subscribe to a device-lifecycle event category and reconcile the exposed
@@ -158696,34 +160280,23 @@ var ExportHapAddon = class extends BaseAddon {
158696
160280
  const deviceIdNumeric = typeof data?.deviceId === "number" ? data.deviceId : null;
158697
160281
  if (deviceIdNumeric === null) return;
158698
160282
  const deviceId = String(deviceIdNumeric);
158699
- if (!this.findEntry(deviceIdNumeric)) return;
158700
- const existing = this.pendingRebuildTimers.get(deviceId);
158701
- if (existing) clearTimeout(existing);
158702
- const timer = setTimeout(() => {
158703
- this.pendingRebuildTimers.delete(deviceId);
158704
- this.reconcileDevice(deviceId);
158705
- }, 500);
158706
- if (typeof timer.unref === "function") timer.unref();
158707
- this.pendingRebuildTimers.set(deviceId, timer);
160283
+ for (const inst of this.bridges.values()) {
160284
+ if (!inst.findEntry(deviceIdNumeric)) continue;
160285
+ const existing = inst.pendingRebuildTimers.get(deviceId);
160286
+ if (existing) clearTimeout(existing);
160287
+ const timer = setTimeout(() => {
160288
+ inst.pendingRebuildTimers.delete(deviceId);
160289
+ this.reconcileDevice(inst, deviceId);
160290
+ }, 500);
160291
+ if (typeof timer.unref === "function") timer.unref();
160292
+ inst.pendingRebuildTimers.set(deviceId, timer);
160293
+ }
158708
160294
  });
158709
160295
  this.ctx.addDisposer(async () => {
158710
160296
  unsubscribe();
158711
160297
  });
158712
160298
  }
158713
160299
  /**
158714
- * Register the SINGLE owner of the shared rebuild-timer cleanup. Called once
158715
- * from `onInitialize`. The per-category lifecycle subscriptions schedule
158716
- * per-device timers into `pendingRebuildTimers` but never clear the map on
158717
- * their own teardown — that shared resource is cleared here, exactly once, on
158718
- * shutdown.
158719
- */
158720
- disposeSharedRebuildTimers() {
158721
- this.ctx.addDisposer(async () => {
158722
- for (const timer of this.pendingRebuildTimers.values()) clearTimeout(timer);
158723
- this.pendingRebuildTimers.clear();
158724
- });
158725
- }
158726
- /**
158727
160300
  * Subscribe to `DeviceProvisioned` and reconcile an exposed device whenever
158728
160301
  * its persisted export shape changes. `DeviceProvisioned` is gated by
158729
160302
  * device-manager (fires ONLY on first registration or a real fingerprint
@@ -158753,22 +160326,22 @@ var ExportHapAddon = class extends BaseAddon {
158753
160326
  * Errors are logged and swallowed — a failed reconcile leaves the prior
158754
160327
  * accessory up, which is strictly better than removing it.
158755
160328
  */
158756
- async reconcileDevice(deviceId) {
160329
+ async reconcileDevice(inst, deviceId) {
158757
160330
  const numericId = Number.parseInt(deviceId, 10);
158758
160331
  if (!Number.isFinite(numericId)) return;
158759
- const entry = this.findEntry(numericId);
160332
+ const entry = inst.findEntry(numericId);
158760
160333
  if (!entry) return;
158761
160334
  const log = this.ctx.logger.withTags({ deviceId: numericId });
158762
- const current = await this.computeExportFingerprint(numericId);
160335
+ const current = await this.computeExportFingerprint(inst, numericId);
158763
160336
  if (current === null) {
158764
160337
  log.debug("export-hap: reconcile skipped — fingerprint unavailable (transient)");
158765
160338
  return;
158766
160339
  }
158767
- const last = syncStateFromJson(this.config.exportSyncState).get(numericId);
160340
+ const last = this.syncStateOf(inst).get(numericId);
158768
160341
  if (last?.fingerprint === current) {
158769
- if (!this.exposed.has(deviceId)) try {
158770
- await this.attachMapper(entry);
158771
- await this.persistFingerprint(numericId, current);
160342
+ if (!inst.exposed.has(deviceId)) try {
160343
+ await this.attachMapper(inst, entry);
160344
+ await this.persistFingerprint(inst, numericId, current);
158772
160345
  } catch (err) {
158773
160346
  log.warn("export-hap: reconcile attach failed", { meta: { error: errMsg(err) } });
158774
160347
  }
@@ -158780,9 +160353,9 @@ var ExportHapAddon = class extends BaseAddon {
158780
160353
  to: current.slice(0, 12)
158781
160354
  } });
158782
160355
  try {
158783
- await this.detachMapper(deviceId);
158784
- await this.attachMapper(entry);
158785
- await this.persistFingerprint(numericId, current);
160356
+ await this.detachMapper(inst, deviceId);
160357
+ await this.attachMapper(inst, entry);
160358
+ await this.persistFingerprint(inst, numericId, current);
158786
160359
  } catch (err) {
158787
160360
  log.warn("export-hap: reconcile rebuild failed", { meta: { error: errMsg(err) } });
158788
160361
  }
@@ -158845,7 +160418,7 @@ var ExportHapAddon = class extends BaseAddon {
158845
160418
  return null;
158846
160419
  }
158847
160420
  }
158848
- /** The one declaration of the bind-interface field, shared by the node form and the global form. */
160421
+ /** The one declaration of the bind-interface field: a fact of one node. */
158849
160422
  interfaceNameField() {
158850
160423
  return this.field({
158851
160424
  type: "text",
@@ -158865,58 +160438,53 @@ var ExportHapAddon = class extends BaseAddon {
158865
160438
  fields: [this.interfaceNameField()]
158866
160439
  }] }) : null;
158867
160440
  }
160441
+ /** The fleet default every camera's clip retention cascades from (same key, no data move). */
160442
+ async deviceDefaultsSchema(cap) {
160443
+ return cap === "device-export" ? this.schema({ sections: [{
160444
+ id: "export-hap-defaults",
160445
+ title: "HomeKit Export",
160446
+ fields: [this.field({
160447
+ type: "number",
160448
+ key: "clipRetentionDays",
160449
+ label: "Keep HomeKit clips for (days)",
160450
+ description: "CamStack keeps its own copy of every clip it sends to HomeKit Secure Video — HomeKit itself never gives one back. This is the fleet default; each camera can override it, and each can switch the copies off entirely. Clips are also capped at 200 per camera, 512 MB per camera and 4 GB overall — whichever limit is reached first wins, and the log names which one.",
160451
+ default: DEFAULT_CONFIG.clipRetentionDays,
160452
+ placement: { tab: "advanced" }
160453
+ })]
160454
+ }] }) : null;
160455
+ }
158868
160456
  /**
158869
- * Copy the bare `interfaceName` to its hub node row and move an inline `fixedPin` into the
158870
- * keychain (D986, D987). Re-resolves the config when either landed, so this boot binds the
158871
- * value the migration wrote.
160457
+ * Move the old settings to where they live now (D986, D987): the bare `interfaceName` to its
160458
+ * node row, the identity and exposure into records, the bridge name into the default instance,
160459
+ * and the retired `bridgeName` / `fixedPin` / bare `interfaceName` rows out. Re-resolves the
160460
+ * config when anything landed, so this boot binds the value the migration wrote.
158872
160461
  */
158873
160462
  async migrateSettings() {
158874
160463
  if ((await this.runMigrations(defineAddonMigrations(ADDON_MIGRATIONS, {
158875
160464
  readStored: (keys) => readRawKeys((key) => this.readStoredGlobalKey(key), "export-hap", keys),
158876
- storeFixedPin: (pin) => this.updateGlobalSettingsAsOperator({ fixedPin: pin })
160465
+ storeFixedPin: (pin) => this.updateGlobalSettingsAsOperator({ fixedPin: pin }),
160466
+ ...this.identityMigrationPorts(),
160467
+ ...this.exposureMigrationPorts()
158877
160468
  }))).applied.length > 0) await this.resolveConfig();
158878
160469
  }
160470
+ /**
160471
+ * Only the declaration `perNodeKeys()` derives the node-scoped keys from: `interfaceName` is a
160472
+ * fact of one node, and the settings machinery reads a per-node key through this schema. The
160473
+ * editable surfaces are the node form, the device defaults and each bridge's own form.
160474
+ */
158879
160475
  globalSettingsSchema() {
158880
160476
  return this.schema({ sections: [{
158881
160477
  id: "export-hap",
158882
160478
  title: "HomeKit Export",
158883
- description: "Publishes each exposed device as its own HomeKit accessory, sharing one setup code. Mark a device \"Expose to HomeKit\" on its settings page, then add it in the iOS Home app (+ → Add Accessory) and enter the setup code shown there.",
158884
- columns: 1,
158885
- fields: [
158886
- this.field({
158887
- type: "text",
158888
- key: "bridgeName",
158889
- label: "Installation name",
158890
- description: "The name of the shared bridge that carries every exposed device that is not a camera (switches, sensors, locks, alarm panels) — what iOS Home lists under Add Accessory. Cameras are never bridged: each one is published as its own accessory under its device name. Set it before you add the bridge in iOS Home.",
158891
- default: DEFAULT_CONFIG.bridgeName,
158892
- requiresRestart: true,
158893
- placement: { tab: "advanced" }
158894
- }),
158895
- this.field({
158896
- type: "password",
158897
- key: "fixedPin",
158898
- label: "Fixed setup code (XXX-XX-XXX)",
158899
- description: "Optional. Leave blank to use the auto-generated code persisted on first boot. Useful for CI replay.",
158900
- default: DEFAULT_CONFIG.fixedPin,
158901
- requiresRestart: true,
158902
- placement: { tab: "advanced" }
158903
- }),
158904
- this.interfaceNameField(),
158905
- this.field({
158906
- type: "number",
158907
- key: "clipRetentionDays",
158908
- label: "Keep HomeKit clips for (days)",
158909
- description: "CamStack keeps its own copy of every clip it sends to HomeKit Secure Video — HomeKit itself never gives one back. This is the fleet default; each camera can override it, and each can switch the copies off entirely. Clips are also capped at 200 per camera, 512 MB per camera and 4 GB overall — whichever limit is reached first wins, and the log names which one.",
158910
- default: DEFAULT_CONFIG.clipRetentionDays,
158911
- placement: { tab: "advanced" }
158912
- })
158913
- ]
160479
+ fields: [this.interfaceNameField()]
158914
160480
  }] });
158915
160481
  }
158916
160482
  async buildDeviceSettingsContribution(deviceId) {
158917
160483
  const kind = await this.resolveExportKind(deviceId);
158918
160484
  if (kind === null) return null;
158919
- const entry = this.findEntry(deviceId);
160485
+ const inst = this.instanceForDevice(deviceId);
160486
+ if (inst === null) return null;
160487
+ const entry = inst.findEntry(deviceId);
158920
160488
  const settings = entry?.settings ?? DEFAULT_DEVICE_SETTINGS;
158921
160489
  const enabled = entry !== null;
158922
160490
  const enabledKey = `hap:${deviceId}:enabled`;
@@ -158926,13 +160494,13 @@ var ExportHapAddon = class extends BaseAddon {
158926
160494
  const allowTranscodeKey = `hap:${deviceId}:allowTranscode`;
158927
160495
  const keepClipsKey = `hap:${deviceId}:keepClips`;
158928
160496
  const clipRetentionKey = `hap:${deviceId}:clipRetentionDays`;
158929
- const mapper = this.exposed.get(String(deviceId)) ?? null;
160497
+ const mapper = inst.exposed.get(String(deviceId)) ?? null;
158930
160498
  const paired = mapper ? accessoryPaired(mapper.accessory) : false;
158931
- const bridged = mapper !== null && this.bridgeHost?.holds(mapper.accessory) === true;
160499
+ const bridged = mapper !== null && inst.bridgeHost.holds(mapper.accessory);
158932
160500
  const name = entry?.displayName ?? `Device ${deviceId}`;
158933
- const bridgePaired = this.bridgeHost?.accessory !== null && this.bridgeHost?.accessory !== void 0 ? accessoryPaired(this.bridgeHost.accessory) : false;
158934
- const statusLabel = !enabled ? "Not exposed" : bridged ? bridgePaired ? `On the “${this.config.bridgeName}” bridge, as “${name}”` : `On the “${this.config.bridgeName}” bridge, as “${name}” — the BRIDGE is not paired yet. In iOS Home: + → Add Accessory → “${this.config.bridgeName}”, then enter setup code ${this.config.identity.pincode}. Every bridged device arrives with it.` : paired ? `Paired — exposed as “${name}”` : `Exposed as “${name}” — not paired yet. In iOS Home: + → Add Accessory → “${name}”, then enter setup code ${this.config.identity.pincode}.`;
158935
- const qrSource = bridged ? this.bridgeHost?.accessory ?? null : mapper?.accessory ?? null;
160501
+ const bridgePaired = inst.bridgeHost.accessory !== null ? accessoryPaired(inst.bridgeHost.accessory) : false;
160502
+ const statusLabel = !enabled ? "Not exposed" : bridged ? bridgePaired ? `On the “${inst.name}” bridge, as “${name}”` : `On the “${inst.name}” bridge, as “${name}” — the BRIDGE is not paired yet. In iOS Home: + → Add Accessory → “${inst.name}”, then enter setup code ${inst.pincode}. Every bridged device arrives with it.` : paired ? `Paired — exposed as “${name}”` : `Exposed as “${name}” — not paired yet. In iOS Home: + → Add Accessory → “${name}”, then enter setup code ${inst.pincode}.`;
160503
+ const qrSource = bridged ? inst.bridgeHost.accessory : mapper?.accessory ?? null;
158936
160504
  let qrValue = "";
158937
160505
  if (qrSource) try {
158938
160506
  qrValue = qrSource.setupURI();
@@ -158974,7 +160542,7 @@ var ExportHapAddon = class extends BaseAddon {
158974
160542
  type: "info",
158975
160543
  key: `hap:${deviceId}:hksvRecordingStatus`,
158976
160544
  label: "HomeKit recording (Secure Video)",
158977
- content: describeHomekitRecording(readHomekitRecordingActive(this.exposed.get(String(deviceId))?.accessories ?? []), this.hksvBuilds.lastFor(deviceId)),
160545
+ content: describeHomekitRecording(readHomekitRecordingActive(inst.exposed.get(String(deviceId))?.accessories ?? []), this.hksvBuilds.lastFor(deviceId)),
158978
160546
  showWhen: {
158979
160547
  field: enabledKey,
158980
160548
  equals: true
@@ -159058,7 +160626,7 @@ var ExportHapAddon = class extends BaseAddon {
159058
160626
  type: "qr-code",
159059
160627
  key: "__hap-pair-qr",
159060
160628
  label: paired ? "Pairing QR (already paired)" : "Pairing QR",
159061
- caption: paired ? `Already paired with at least one device. Scan from another iPhone / iPad to add it there too. Setup code: ${this.config.identity.pincode}.` : `Scan with the iOS Camera app to pair this accessory in HomeKit. Setup code: ${this.config.identity.pincode}.`,
160629
+ caption: paired ? `Already paired with at least one device. Scan from another iPhone / iPad to add it there too. Setup code: ${inst.pincode}.` : `Scan with the iOS Camera app to pair this accessory in HomeKit. Setup code: ${inst.pincode}.`,
159062
160630
  value: qrValue,
159063
160631
  size: 192,
159064
160632
  alt: `HomeKit pairing QR for ${name}`,
@@ -159097,8 +160665,10 @@ var ExportHapAddon = class extends BaseAddon {
159097
160665
  async applyDeviceSettingsPatch(deviceId, patch) {
159098
160666
  const deviceIdStr = String(deviceId);
159099
160667
  const log = this.ctx.logger.withTags({ deviceId });
159100
- const current = this.findEntry(deviceId);
159101
- const wasEnabled = this.exposed.has(deviceIdStr);
160668
+ const inst = this.instanceForDevice(deviceId);
160669
+ if (inst === null) throw new Error("export-hap: no HomeKit bridge is running — add or enable one first");
160670
+ const current = inst.findEntry(deviceId);
160671
+ const wasEnabled = inst.exposed.has(deviceIdStr);
159102
160672
  const enabledKey = `hap:${deviceId}:enabled`;
159103
160673
  const streamPreferenceKey = `hap:${deviceId}:streamPreference`;
159104
160674
  const useBridgeKey = `hap:${deviceId}:useBridge`;
@@ -159127,12 +160697,12 @@ var ExportHapAddon = class extends BaseAddon {
159127
160697
  clipRetentionDays
159128
160698
  };
159129
160699
  if (!enabledValue) {
159130
- if (wasEnabled) await this.unexposeDevice(deviceIdStr);
160700
+ if (wasEnabled) await this.unexposeDevice(inst, deviceIdStr);
159131
160701
  return { success: true };
159132
160702
  }
159133
160703
  if (!wasEnabled) {
159134
- await this.exposeDevice(deviceIdStr);
159135
- await this.updateEntrySettings(deviceIdStr, nextSettings);
160704
+ await this.exposeDevice(inst, deviceIdStr);
160705
+ await this.updateEntrySettings(inst, deviceIdStr, nextSettings);
159136
160706
  return { success: true };
159137
160707
  }
159138
160708
  const currentPref = current?.settings?.streamPreference ?? "auto";
@@ -159146,7 +160716,7 @@ var ExportHapAddon = class extends BaseAddon {
159146
160716
  mapperKind,
159147
160717
  useBridge
159148
160718
  });
159149
- await this.updateEntrySettings(deviceIdStr, nextSettings);
160719
+ await this.updateEntrySettings(inst, deviceIdStr, nextSettings);
159150
160720
  if (currentPref !== streamPreference || currentKeepClips !== keepClips || wasBridged !== willBridge) {
159151
160721
  log.info("export-hap: per-camera export settings changed — refreshing accessory", { meta: {
159152
160722
  streamPreference: {
@@ -159163,8 +160733,8 @@ var ExportHapAddon = class extends BaseAddon {
159163
160733
  }
159164
160734
  } });
159165
160735
  try {
159166
- await this.unexposeDevice(deviceIdStr, { clearPairing: wasBridged !== willBridge });
159167
- await this.exposeDevice(deviceIdStr, void 0, nextSettings);
160736
+ await this.unexposeDevice(inst, deviceIdStr, { clearPairing: wasBridged !== willBridge });
160737
+ await this.exposeDevice(inst, deviceIdStr, void 0, nextSettings);
159168
160738
  } catch (err) {
159169
160739
  log.warn("export-hap: failed to refresh accessory after a settings change", { meta: { error: errMsg(err) } });
159170
160740
  }
@@ -159222,20 +160792,75 @@ var ExportHapAddon = class extends BaseAddon {
159222
160792
  const planes = this.hksvClipPlanes;
159223
160793
  return `/addon/${EXPORT_HAP_ADDON_ID}/${kind === "media" ? planes?.mediaPrefix ?? "hksv-clip" : planes?.thumbPrefix ?? "hksv-clip-thumb"}/${String(deviceId)}/${stem}.${kind === "media" ? "mp4" : "jpg"}`;
159224
160794
  }
159225
- findEntry(deviceId) {
159226
- const id = String(deviceId);
159227
- return this.config.exposed.find((e) => e.deviceId === id) ?? null;
160795
+ /** The exposure record's handle: one row per bridge instance, under the instance id. */
160796
+ exposureHandle() {
160797
+ return this.requireRecords().kind(hapBridgeExportsKind);
160798
+ }
160799
+ /** Load a bridge's exposure record; create it empty when none exists. */
160800
+ async loadExposure(id) {
160801
+ const handle = this.exposureHandle();
160802
+ const row = await handle.get(id);
160803
+ if (row !== null) return row.data;
160804
+ const empty = {
160805
+ name: HAP_EXPOSURE_NAME,
160806
+ devices: [],
160807
+ actions: []
160808
+ };
160809
+ await handle.put({
160810
+ id,
160811
+ data: empty
160812
+ }, { ifRev: 0 });
160813
+ return empty;
160814
+ }
160815
+ async writeExposure(inst, next) {
160816
+ await this.exposureHandle().put({
160817
+ id: inst.id,
160818
+ data: next
160819
+ });
160820
+ inst.exposure = next;
160821
+ }
160822
+ setExposedDevices(inst, devices) {
160823
+ return this.writeExposure(inst, {
160824
+ ...inst.exposure,
160825
+ devices
160826
+ });
160827
+ }
160828
+ setExposedActions(inst, actions) {
160829
+ return this.writeExposure(inst, {
160830
+ ...inst.exposure,
160831
+ actions
160832
+ });
160833
+ }
160834
+ /** The ports the exposure migration reads and writes through. */
160835
+ exposureMigrationPorts() {
160836
+ const handle = this.exposureHandle();
160837
+ return {
160838
+ putExposure: async (body) => {
160839
+ if (await handle.get("export-hap") !== null) return "exists";
160840
+ try {
160841
+ await handle.put({
160842
+ id: HAP_DEFAULT_INSTANCE_ID,
160843
+ data: body
160844
+ }, { ifRev: 0 });
160845
+ } catch (err) {
160846
+ if (err instanceof RevConflictError) return "exists";
160847
+ throw err;
160848
+ }
160849
+ return "created";
160850
+ },
160851
+ readExposure: async () => (await handle.get("export-hap"))?.data ?? null
160852
+ };
159228
160853
  }
159229
- async updateEntrySettings(deviceIdStr, settings) {
159230
- const next = this.config.exposed.map((e) => e.deviceId === deviceIdStr ? {
160854
+ async updateEntrySettings(inst, deviceIdStr, settings) {
160855
+ const next = inst.exposure.devices.map((e) => e.deviceId === deviceIdStr ? {
159231
160856
  ...e,
159232
160857
  settings
159233
160858
  } : e);
159234
- await this.updateGlobalSettings({ exposed: next });
160859
+ await this.setExposedDevices(inst, next);
159235
160860
  }
159236
160861
  };
159237
160862
  function errMsg(err) {
159238
160863
  return err instanceof Error ? err.message : String(err);
159239
160864
  }
159240
160865
  //#endregion
159241
- export { DEFAULT_CLIP_RETENTION_DAYS, DEFAULT_DEVICE_SETTINGS, EXPORT_HAP_ADDON_ID, ExportHapAddon, ExportHapAddon as default, describeHksvCamera, unpublishAccessory as i, initHapStorage as n, publishStandalone as r, resolveClipRetentionDays, resolveKeepHomekitClips, resolveMultiTierService, deriveUsername as t };
160866
+ export { DEFAULT_CLIP_RETENTION_DAYS, DEFAULT_DEVICE_SETTINGS, EXPORT_HAP_ADDON_ID, ExportHapAddon, ExportHapAddon as default, exportHapActions as a, describeHksvCamera, unpublishAccessory as i, initHapStorage as n, publishStandalone as r, resolveClipRetentionDays, resolveKeepHomekitClips, resolveMultiTierService, deriveUsername as t };