@camstack/addon-export-hap 1.2.190 → 1.2.192

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.
@@ -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-BKClVk0K.mjs
6024
+ //#region ../types/dist/sleep-BaWhXZFm.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
@@ -6688,11 +6828,36 @@ function projectStore(store, perNodeKeys, nodeId) {
6688
6828
  }
6689
6829
  return out;
6690
6830
  }
6831
+ /**
6832
+ * The address of one keychain value: `secret://<owner>/<scope>/<fieldPath>`.
6833
+ *
6834
+ * A ref is DETERMINISTIC from where the value lives — the owner addon, the
6835
+ * scope (global, one node, one device, one integration, one row of a business
6836
+ * collection) and the field path inside that scope — so saving the same field
6837
+ * twice updates the same ref, and the ref itself says which settings blob
6838
+ * points at it. It is also the AAD of the value's ciphertext: a ciphertext
6839
+ * copied onto another ref does not decrypt.
6840
+ *
6841
+ * Array items are addressed by ITEM ID, never by index
6842
+ * (`providers[authentik].clientSecret`), so reordering a list keeps every ref.
6843
+ *
6844
+ * Pure and browser-safe: no node builtins, no I/O.
6845
+ */
6846
+ /** The URI scheme of every keychain ref. */
6847
+ var SECRET_REF_SCHEME = "secret://";
6691
6848
  var GLOBAL_SCOPE = { kind: "global" };
6692
6849
  /** The scope every addon-wide (not per-node, not per-device) setting lives in. */
6693
6850
  function globalSecretScope() {
6694
6851
  return GLOBAL_SCOPE;
6695
6852
  }
6853
+ /**
6854
+ * An addon id as a ref owner. A hub in-process builtin's context id is
6855
+ * `addon:<id>`; the owner of its secrets is `<id>`, exactly as for the same
6856
+ * addon running forked.
6857
+ */
6858
+ function normalizeSecretOwner(addonId) {
6859
+ return addonId.startsWith("addon:") ? addonId.slice(6) : addonId;
6860
+ }
6696
6861
  function encodeSegment(value) {
6697
6862
  return encodeURIComponent(value);
6698
6863
  }
@@ -6703,6 +6868,16 @@ function decodeSegment(value) {
6703
6868
  return null;
6704
6869
  }
6705
6870
  }
6871
+ /** The scope as it appears inside a ref (`global`, `node/<id>`, …). */
6872
+ function formatSecretScope(scope) {
6873
+ switch (scope.kind) {
6874
+ case "global": return "global";
6875
+ case "node": return `node/${encodeSegment(scope.nodeId)}`;
6876
+ case "device": return `device/${scope.deviceId}`;
6877
+ case "integration": return `integration/${encodeSegment(scope.integrationId)}`;
6878
+ case "row": return `row/${encodeSegment(scope.collection)}/${encodeSegment(scope.rowId)}`;
6879
+ }
6880
+ }
6706
6881
  /**
6707
6882
  * The field path of a value inside an array item, addressed by the item's id:
6708
6883
  * `arrayItemFieldPath('providers', 'authentik', 'clientSecret')` →
@@ -6711,6 +6886,13 @@ function decodeSegment(value) {
6711
6886
  function arrayItemFieldPath(arrayKey, itemId, fieldKey) {
6712
6887
  return `${arrayKey}[${encodeSegment(itemId)}].${fieldKey}`;
6713
6888
  }
6889
+ /** Build a ref. Throws on an empty owner or field path — both are bugs. */
6890
+ function buildSecretRef(parts) {
6891
+ const owner = normalizeSecretOwner(parts.owner);
6892
+ if (owner.length === 0) throw new Error("buildSecretRef: owner is empty");
6893
+ if (parts.fieldPath.length === 0) throw new Error("buildSecretRef: fieldPath is empty");
6894
+ return `${SECRET_REF_SCHEME}${encodeSegment(owner)}/${formatSecretScope(parts.scope)}/${parts.fieldPath}`;
6895
+ }
6714
6896
  function parseScope(segments) {
6715
6897
  switch (segments[0]) {
6716
6898
  case "global": return {
@@ -6851,7 +7033,7 @@ async function writeMembers(ctx, children, incoming, stored, pathOf) {
6851
7033
  for (const [member, node] of children) applyMember(out, member, await writeNode(ctx, node, incoming[member], stored[member], pathOf(member)), stored);
6852
7034
  return out;
6853
7035
  }
6854
- function rowId(row, idKey) {
7036
+ function rowId$1(row, idKey) {
6855
7037
  const raw = row[idKey];
6856
7038
  if (typeof raw === "string" && raw.length > 0) return raw;
6857
7039
  if (typeof raw === "number" && Number.isFinite(raw)) return String(raw);
@@ -6868,7 +7050,7 @@ async function writeArray(ctx, node, incoming, stored, fieldPath) {
6868
7050
  }
6869
7051
  const storedById = /* @__PURE__ */ new Map();
6870
7052
  for (const row of storedRows) {
6871
- const id = rowId(row, node.idKey);
7053
+ const id = rowId$1(row, node.idKey);
6872
7054
  if (id !== null) storedById.set(id, row);
6873
7055
  }
6874
7056
  const kept = /* @__PURE__ */ new Set();
@@ -6878,13 +7060,13 @@ async function writeArray(ctx, node, incoming, stored, fieldPath) {
6878
7060
  rows.push(row);
6879
7061
  continue;
6880
7062
  }
6881
- const id = rowId(row, node.idKey) ?? ctx.mintId();
7063
+ const id = rowId$1(row, node.idKey) ?? ctx.mintId();
6882
7064
  kept.add(id);
6883
7065
  const withId = {
6884
7066
  ...row,
6885
7067
  [node.idKey]: row[node.idKey] ?? id
6886
7068
  };
6887
- if (rowId(withId, node.idKey) === null) withId[node.idKey] = id;
7069
+ if (rowId$1(withId, node.idKey) === null) withId[node.idKey] = id;
6888
7070
  const storedRow = storedById.get(id) ?? {};
6889
7071
  rows.push(await writeMembers(ctx, node.item, withId, storedRow, (member) => arrayItemFieldPath(fieldPath, id, member)));
6890
7072
  }
@@ -7976,6 +8158,10 @@ var BaseAddon = class {
7976
8158
  const stored = keychain ? await this.readAddonStoreWithRetry() : {};
7977
8159
  const patch = {};
7978
8160
  for (const key of keys) {
8161
+ if (tree.get(key)?.kind === "array") {
8162
+ patch[key] = [];
8163
+ continue;
8164
+ }
7979
8165
  const keychainStored = tree.has(key) || collectSecretMarkerRefs(stored[key]).length > 0;
7980
8166
  patch[key] = keychain && keychainStored ? SECRET_CLEAR : "";
7981
8167
  }
@@ -8615,6 +8801,45 @@ function normalizeAddonInitResult(result) {
8615
8801
  if (Array.isArray(result)) return { providers: result };
8616
8802
  return result;
8617
8803
  }
8804
+ var PREFIX = "records/";
8805
+ /** The base of every records failure. `detail` is the human part of the message. */
8806
+ var RecordsError = class extends Error {
8807
+ code;
8808
+ detail;
8809
+ constructor(code, detail) {
8810
+ super(`${PREFIX}${code}: ${detail}`);
8811
+ this.name = "RecordsError";
8812
+ this.code = code;
8813
+ this.detail = detail;
8814
+ }
8815
+ };
8816
+ /** A write guarded by `ifRev` found another revision (or an existing row for `ifRev: 0`). */
8817
+ var RevConflictError = class extends RecordsError {
8818
+ constructor(detail) {
8819
+ super("rev-conflict", detail);
8820
+ this.name = "RevConflictError";
8821
+ }
8822
+ };
8823
+ /** The keychain could not store or serve a value: explicit, never an empty string. */
8824
+ var RecordSecretUnavailableError = class extends RecordsError {
8825
+ constructor(detail) {
8826
+ super("secret-unavailable", detail);
8827
+ this.name = "RecordSecretUnavailableError";
8828
+ }
8829
+ };
8830
+ var InvalidRecordError = class extends RecordsError {
8831
+ constructor(detail) {
8832
+ super("invalid-record", detail);
8833
+ this.name = "InvalidRecordError";
8834
+ }
8835
+ };
8836
+ /** A kind declaration the engine refuses (non-additive change, bad shape, wrong file). */
8837
+ var DeclarationRefusedError = class extends RecordsError {
8838
+ constructor(detail) {
8839
+ super("declaration-refused", detail);
8840
+ this.name = "DeclarationRefusedError";
8841
+ }
8842
+ };
8618
8843
  /** Limits and names of `ctx.records` (D881). One authority; the engine and the facade read it. */
8619
8844
  /** The files a kind may live in. `history` is device-history's (D850), never records. */
8620
8845
  var RECORD_DATABASES = ["settings", "events"];
@@ -8630,6 +8855,174 @@ var RECORD_DEFAULT_MAX_DATA_BYTES = 64 * 1024;
8630
8855
  var RECORD_MAX_DATA_BYTES = 1024 * 1024;
8631
8856
  var RECORD_BATCH_MAX = 1e3;
8632
8857
  var RECORD_QUERY_MAX = 1e3;
8858
+ /** A kind in the `settings` file may not bound itself above this (D447: high volume is `events`). */
8859
+ var RECORD_SETTINGS_MAX_ROWS = 5e4;
8860
+ /** The `Column`-free proof prefix: a ref collection for a kind's secret fields. */
8861
+ var RECORD_SECRET_COLLECTION_PREFIX = "records:";
8862
+ /**
8863
+ * Secret fields of a record, addressed the way a Zod schema declares them
8864
+ * (`collectZodSecretPaths`): dotted keys, `[]` for "each element of this array"
8865
+ * (`auth.accessToken`, `headers[].value`).
8866
+ *
8867
+ * `{}` after a key means "each value of this map" (`applianceSecrets{}`): the map's own key
8868
+ * names the value (`applianceSecrets{fridge}`), so no id key is declared and a body that drops a
8869
+ * key releases exactly that key's secret.
8870
+ *
8871
+ * Array elements are matched by a DECLARED id key (`secretArrayKeys`:
8872
+ * `{ headers: 'name' }`), never by index, so reordering a list keeps every
8873
+ * keychain ref (the same rule as `arrayItemFieldPath`). The concrete path of a
8874
+ * leaf names its element: `headers[X-Api].value`.
8875
+ *
8876
+ * Pure and browser-safe. Nothing here mutates: every transform returns a new value.
8877
+ */
8878
+ /** The array prefixes (declared form, e.g. `headers` or `a.headers`) of a path. */
8879
+ function parseSecretPath(path) {
8880
+ if (path.length === 0) throw new InvalidRecordError("an empty secret path");
8881
+ return path.split(".").map((raw) => {
8882
+ const each = raw.endsWith("[]");
8883
+ const map = raw.endsWith("{}");
8884
+ const key = each || map ? raw.slice(0, -2) : raw;
8885
+ if (key.length === 0) throw new InvalidRecordError(`secret path "${path}" has an empty segment`);
8886
+ return {
8887
+ key,
8888
+ each,
8889
+ map
8890
+ };
8891
+ });
8892
+ }
8893
+ /** The declared array prefixes of `path` that need an id key (`headers`, `a.rows`). */
8894
+ function secretArrayPrefixes(path) {
8895
+ const segments = parseSecretPath(path);
8896
+ const prefixes = [];
8897
+ const walked = [];
8898
+ for (const segment of segments) {
8899
+ walked.push(segment.key);
8900
+ if (segment.each) prefixes.push(walked.join("."));
8901
+ }
8902
+ return prefixes;
8903
+ }
8904
+ function isRecord$4(value) {
8905
+ return typeof value === "object" && value !== null && !Array.isArray(value);
8906
+ }
8907
+ function elementId(element, idKey, declared, prefix) {
8908
+ const id = isRecord$4(element) ? element[idKey] : void 0;
8909
+ 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`);
8910
+ return id;
8911
+ }
8912
+ /**
8913
+ * Visit every secret leaf PRESENT in `data` (an absent branch has nothing to
8914
+ * visit). `replace` returns the new leaf value, or {@link REMOVE_LEAF}; the
8915
+ * result is a new body, `data` is untouched.
8916
+ */
8917
+ var REMOVE_LEAF = Symbol("remove-leaf");
8918
+ function mapAt(node, segments, index, walkedKeys, concretePrefix, declared, arrayKeys, visit) {
8919
+ if (!isRecord$4(node)) return node;
8920
+ const segment = segments[index];
8921
+ if (segment === void 0) return node;
8922
+ if (!Object.prototype.hasOwnProperty.call(node, segment.key)) return node;
8923
+ const child = node[segment.key];
8924
+ const keys = [...walkedKeys, segment.key];
8925
+ const last = index === segments.length - 1;
8926
+ if (segment.each) {
8927
+ if (!Array.isArray(child)) return node;
8928
+ const prefix = keys.join(".");
8929
+ const idKey = arrayKeys[prefix];
8930
+ if (idKey === void 0) throw new InvalidRecordError(`"${declared}": no id key declared for the array "${prefix}"`);
8931
+ const mapped = child.map((element) => {
8932
+ const id = elementId(element, idKey, declared, prefix);
8933
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}[${encodeURIComponent(id)}]`;
8934
+ return last ? element : mapAt(element, segments, index + 1, keys, concrete, declared, arrayKeys, visit);
8935
+ });
8936
+ return {
8937
+ ...node,
8938
+ [segment.key]: mapped
8939
+ };
8940
+ }
8941
+ if (segment.map) {
8942
+ if (!isRecord$4(child)) return node;
8943
+ const kept = Object.entries(child).map(([mapKey, value]) => {
8944
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}{${encodeURIComponent(mapKey)}}`;
8945
+ if (!last) return [mapKey, mapAt(value, segments, index + 1, keys, concrete, declared, arrayKeys, visit)];
8946
+ return [mapKey, visit({
8947
+ declared,
8948
+ concrete,
8949
+ value
8950
+ })];
8951
+ }).filter(([, value]) => value !== REMOVE_LEAF);
8952
+ return {
8953
+ ...node,
8954
+ [segment.key]: Object.fromEntries(kept)
8955
+ };
8956
+ }
8957
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}`;
8958
+ if (last) {
8959
+ const replacement = visit({
8960
+ declared,
8961
+ concrete,
8962
+ value: child
8963
+ });
8964
+ if (replacement === REMOVE_LEAF) return Object.fromEntries(Object.entries(node).filter(([key]) => key !== segment.key));
8965
+ return {
8966
+ ...node,
8967
+ [segment.key]: replacement
8968
+ };
8969
+ }
8970
+ return {
8971
+ ...node,
8972
+ [segment.key]: mapAt(child, segments, index + 1, keys, concrete, declared, arrayKeys, visit)
8973
+ };
8974
+ }
8975
+ /** Replace/remove every present secret leaf; returns a NEW body. */
8976
+ function mapSecretLeaves(data, paths, arrayKeys, visit) {
8977
+ let current = data;
8978
+ for (const declared of paths) current = mapAt(current, parseSecretPath(declared), 0, [], "", declared, arrayKeys, visit);
8979
+ return current;
8980
+ }
8981
+ /**
8982
+ * The keychain collection name a kind's secrets live under. Prefixed so a
8983
+ * record's refs never collide with the refs a legacy collection of the same name
8984
+ * already holds during an adoption.
8985
+ */
8986
+ function recordSecretCollection(kind) {
8987
+ return `${RECORD_SECRET_COLLECTION_PREFIX}${kind}`;
8988
+ }
8989
+ /** The ONE ref a row's secret field may carry: the engine and the facade both build it here. */
8990
+ function recordSecretRef(owner, kind, rowId, concretePath) {
8991
+ return buildSecretRef({
8992
+ owner,
8993
+ scope: {
8994
+ kind: "row",
8995
+ collection: recordSecretCollection(kind),
8996
+ rowId
8997
+ },
8998
+ fieldPath: concretePath
8999
+ });
9000
+ }
9001
+ /**
9002
+ * A stored secret, as an admin read shows it: a VIEW naming the row's own
9003
+ * keychain ref (`set: true`), never the value and no longer the bare redaction
9004
+ * token. The form hands it to the secret field, which reveals the value by ref
9005
+ * through the audited `keychain-admin.reveal`; sent back untouched it keeps the
9006
+ * stored secret (the records door reads a view as KEEP).
9007
+ *
9008
+ * ONE implementation for the entries service and for every addon that serves
9009
+ * its own instances (`RecordIntegrationInstances`).
9010
+ */
9011
+ function isRecord$3(value) {
9012
+ return typeof value === "object" && value !== null && !Array.isArray(value);
9013
+ }
9014
+ function secretViewsOf(owner, kind, id, decl, data) {
9015
+ if (decl.secretPaths.length === 0) return data;
9016
+ const shown = mapSecretLeaves(data, decl.secretPaths, decl.secretArrayKeys, (leaf) => {
9017
+ if (leaf.value !== "__camstack_redacted__") return leaf.value;
9018
+ return {
9019
+ $secret: recordSecretRef(owner, kind, id, leaf.concrete),
9020
+ v: 1,
9021
+ set: true
9022
+ };
9023
+ });
9024
+ return isRecord$3(shown) ? shown : data;
9025
+ }
8633
9026
  /**
8634
9027
  * The share-view scope kinds a share-link token can carry. The hub mints
8635
9028
  * and validates them (`ShareViewGrantSchema` builds its
@@ -8654,6 +9047,75 @@ var PeerBytesTicketSchema = object({
8654
9047
  */
8655
9048
  declaredBytes: number().int().nonnegative().nullable()
8656
9049
  });
9050
+ function defOf(schema) {
9051
+ const zodBag = Reflect.get(schema, "_zod");
9052
+ if (typeof zodBag !== "object" || zodBag === null) return {};
9053
+ const def = Reflect.get(zodBag, "def");
9054
+ if (typeof def !== "object" || def === null) return {};
9055
+ return def;
9056
+ }
9057
+ function declaredHere(schema) {
9058
+ return globalRegistry.get(schema)?.secret === true;
9059
+ }
9060
+ /** Wrapper kinds whose `innerType` is the field itself. */
9061
+ var WRAPPERS = new Set([
9062
+ "optional",
9063
+ "nullable",
9064
+ "default",
9065
+ "prefault",
9066
+ "catch",
9067
+ "readonly",
9068
+ "nonoptional"
9069
+ ]);
9070
+ /**
9071
+ * The schema layers that make up ONE field: the schema itself and every
9072
+ * wrapper below it (optional / default / nullable / readonly / catch), plus
9073
+ * both sides of a pipe (`z.preprocess` puts the real schema on `out`,
9074
+ * `.transform` on `in`).
9075
+ */
9076
+ function layersOf(schema) {
9077
+ const out = [];
9078
+ const queue = [schema];
9079
+ while (queue.length > 0) {
9080
+ const s = queue.shift();
9081
+ if (!s || out.includes(s)) continue;
9082
+ out.push(s);
9083
+ const def = defOf(s);
9084
+ if (def.type !== void 0 && WRAPPERS.has(def.type) && def.innerType) queue.push(def.innerType);
9085
+ if (def.type === "pipe") {
9086
+ if (def.in) queue.push(def.in);
9087
+ if (def.out) queue.push(def.out);
9088
+ }
9089
+ }
9090
+ return out;
9091
+ }
9092
+ /** True when any layer of this field declares `.meta({ secret: true })`. */
9093
+ function isZodSecret(schema) {
9094
+ return layersOf(schema).some(declaredHere);
9095
+ }
9096
+ /**
9097
+ * Every declared secret path in a config schema: dotted keys, `[]` for "each
9098
+ * element of this array" (`connection.password`, `rows[].token`), `{}` for "each value of this
9099
+ * map" (`applianceSecrets{}`). A declared
9100
+ * object or array is reported as one path and not descended into — everything
9101
+ * under it is secret.
9102
+ */
9103
+ function collectZodSecretPaths(schema, prefix = "") {
9104
+ if (isZodSecret(schema)) return prefix.length > 0 ? [prefix] : [];
9105
+ const paths = [];
9106
+ for (const layer of layersOf(schema)) {
9107
+ const def = defOf(layer);
9108
+ if (def.type === "object" && def.shape) for (const [key, child] of Object.entries(def.shape)) paths.push(...collectZodSecretPaths(child, prefix ? `${prefix}.${key}` : key));
9109
+ else if (def.type === "array" && def.element) paths.push(...collectZodSecretPaths(def.element, `${prefix}[]`));
9110
+ else if (def.type === "record" && def.valueType) paths.push(...collectZodSecretPaths(def.valueType, `${prefix}{}`));
9111
+ else if (def.type === "union" && def.options) for (const option of def.options) paths.push(...collectZodSecretPaths(option, prefix));
9112
+ else if (def.type === "intersection") {
9113
+ if (def.left) paths.push(...collectZodSecretPaths(def.left, prefix));
9114
+ if (def.right) paths.push(...collectZodSecretPaths(def.right, prefix));
9115
+ }
9116
+ }
9117
+ return [...new Set(paths)];
9118
+ }
8657
9119
  /**
8658
9120
  * Record kinds (D881): the declaration an addon makes of one kind of fact, the
8659
9121
  * Zod row schema that describes it, and the helper that turns the two into the
@@ -8720,6 +9182,111 @@ var RecordKindDeclarationSchema = object({
8720
9182
  }).strict();
8721
9183
  /** The kind names: lower-case, dash separated, short enough for an index name. */
8722
9184
  var RecordKindNameSchema = string().regex(/^[a-z][a-z0-9-]{0,47}$/);
9185
+ /** Cross-field rules a declaration must satisfy. Throws {@link DeclarationRefusedError}. */
9186
+ function assertValidDeclaration(name, decl) {
9187
+ const refuse = (why) => {
9188
+ throw new DeclarationRefusedError(`kind "${name}": ${why}`);
9189
+ };
9190
+ if (!RecordKindNameSchema.safeParse(name).success) refuse("the name must be lower-case-dashed");
9191
+ const seen = /* @__PURE__ */ new Set();
9192
+ for (const index of decl.indexes) {
9193
+ if (seen.has(index.name)) refuse(`index name "${index.name}" is declared twice`);
9194
+ seen.add(index.name);
9195
+ }
9196
+ const { retention } = decl;
9197
+ const hasSecrets = decl.secretPaths.length > 0;
9198
+ if ("ttlMs" in retention) {
9199
+ if (retention.from === "at" && decl.at !== "required") refuse("a ttl from \"at\" needs at: \"required\"");
9200
+ if (hasSecrets) refuse("a kind with secret fields cannot use engine TTL (its keychain values would be orphaned)");
9201
+ }
9202
+ if ("maxRows" in retention || "maxRowsPerDevice" in retention) {
9203
+ if (retention.maxRowsPerDevice !== void 0 && decl.device !== "required") refuse("maxRowsPerDevice needs device: \"required\"");
9204
+ if (decl.at !== "required") refuse("a row bound trims the oldest \"at\": it needs at: \"required\"");
9205
+ if (hasSecrets) refuse("a kind with secret fields cannot use an engine row bound");
9206
+ const bound = Math.max(retention.maxRows ?? 0, retention.maxRowsPerDevice ?? 0);
9207
+ 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)`);
9208
+ }
9209
+ if (decl.deviceRemoval === "delete" && decl.device === "none") refuse("deviceRemoval: \"delete\" needs a device: \"required\" or \"optional\"");
9210
+ 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`);
9211
+ }
9212
+ function bodyFieldsOf(schema) {
9213
+ return { ...toJSONSchema(schema, {
9214
+ unrepresentable: "any",
9215
+ io: "input"
9216
+ }) };
9217
+ }
9218
+ function isRecordLike(value) {
9219
+ return typeof value === "object" && value !== null && !Array.isArray(value);
9220
+ }
9221
+ /** Does every branch of the body schema carry `field`? (A discriminated union has several.) */
9222
+ function hasNameField(json, field) {
9223
+ const branches = json["oneOf"] ?? json["anyOf"];
9224
+ if (Array.isArray(branches)) return branches.length > 0 && branches.every((b) => isRecordLike(b) && hasNameField(b, field));
9225
+ const properties = json["properties"];
9226
+ return isRecordLike(properties) && Object.prototype.hasOwnProperty.call(properties, field);
9227
+ }
9228
+ /**
9229
+ * Declare the kinds of a package. The keys are the kind names. The result is
9230
+ * what `ctx.records.declare` sends to the engine and what `ctx.records.kind`
9231
+ * types its handle from.
9232
+ */
9233
+ function defineRecordKinds(specs) {
9234
+ const out = {};
9235
+ for (const [name, spec] of Object.entries(specs)) {
9236
+ const secretPaths = collectZodSecretPaths(spec.schema);
9237
+ const nameField = spec.entry?.nameField ?? "name";
9238
+ const fields = bodyFieldsOf(spec.schema);
9239
+ if (spec.entry !== void 0 && !hasNameField(fields, nameField)) throw new DeclarationRefusedError(`kind "${name}": an entry kind's schema needs a "${nameField}" field`);
9240
+ const parsed = RecordKindDeclarationSchema.parse({
9241
+ database: spec.database,
9242
+ class: spec.class,
9243
+ writeTrigger: spec.writeTrigger,
9244
+ device: spec.device,
9245
+ at: spec.at,
9246
+ indexes: spec.indexes === void 0 ? void 0 : [...spec.indexes],
9247
+ retention: spec.retention,
9248
+ deviceRemoval: spec.deviceRemoval,
9249
+ maxDataBytes: spec.maxDataBytes,
9250
+ secretPaths: [...new Set([...secretPaths, ...spec.retiredSecretPaths ?? []])],
9251
+ secretArrayKeys: spec.secretArrayKeys === void 0 ? void 0 : { ...spec.secretArrayKeys },
9252
+ transactFamily: spec.transactFamily,
9253
+ entry: spec.entry === void 0 ? void 0 : {
9254
+ title: spec.entry.title,
9255
+ nameField,
9256
+ fields
9257
+ }
9258
+ });
9259
+ assertValidDeclaration(name, parsed);
9260
+ out[name] = {
9261
+ name,
9262
+ schema: spec.schema,
9263
+ declaration: parsed
9264
+ };
9265
+ }
9266
+ return out;
9267
+ }
9268
+ /**
9269
+ * Declare one entry kind. An entry is configuration: never trimmed by the
9270
+ * engine, never aged, belonging to no device.
9271
+ */
9272
+ function defineEntryKind(name, spec) {
9273
+ const defined = defineRecordKinds({ [name]: {
9274
+ schema: spec.schema,
9275
+ class: "config",
9276
+ writeTrigger: spec.writeTrigger ?? "an operator adds or edits an entry in the entries UI",
9277
+ retention: { none: "an entry goes only when the operator deletes it" },
9278
+ ...spec.database === void 0 ? {} : { database: spec.database },
9279
+ ...spec.indexes === void 0 ? {} : { indexes: spec.indexes },
9280
+ ...spec.secretArrayKeys === void 0 ? {} : { secretArrayKeys: spec.secretArrayKeys },
9281
+ ...spec.retiredSecretPaths === void 0 ? {} : { retiredSecretPaths: spec.retiredSecretPaths },
9282
+ entry: {
9283
+ title: spec.title,
9284
+ ...spec.nameField === void 0 ? {} : { nameField: spec.nameField }
9285
+ }
9286
+ } })[name];
9287
+ if (defined === void 0) throw new DeclarationRefusedError(`entry kind "${name}" was not built`);
9288
+ return defined;
9289
+ }
8723
9290
  object({
8724
9291
  field: string().min(1),
8725
9292
  on: literal("advance")
@@ -11432,7 +11999,7 @@ object({
11432
11999
  params: record(string(), union([string(), number()])).optional()
11433
12000
  });
11434
12001
  //#endregion
11435
- //#region ../types/dist/composition-BodkvOV0.mjs
12002
+ //#region ../types/dist/composition-CRNwcFYY.mjs
11436
12003
  var AUDIO_ENCODER_BY_CODEC = {
11437
12004
  opus: "libopus",
11438
12005
  aac: "aac",
@@ -11609,6 +12176,7 @@ function buildVideoArgs(video, outputArgs, filterGraph, hwEncode) {
11609
12176
  if (video.level !== void 0) args.push("-level", video.level);
11610
12177
  if (video.pixelFormat !== void 0) args.push("-pix_fmt", video.pixelFormat);
11611
12178
  if (video.fps !== void 0) args.push("-r", String(video.fps));
12179
+ if (video.fpsMode !== void 0) args.push("-fps_mode", video.fpsMode);
11612
12180
  if (video.gopFrames !== void 0) args.push("-g", String(video.gopFrames));
11613
12181
  if (video.forceKeyFramesSeconds !== void 0) args.push("-force_key_frames", `expr:gte(t,n_forced*${video.forceKeyFramesSeconds})`);
11614
12182
  if (video.bf !== void 0) args.push("-bf", String(video.bf));
@@ -12790,38 +13358,6 @@ function validateExpressionSource(src) {
12790
13358
  return null;
12791
13359
  }
12792
13360
  /**
12793
- * One power reading becomes a washer, dryer or dishwasher (D944 helper).
12794
- *
12795
- * Standby of the control board is under 5 W; a motor or a heater is far
12796
- * above that, so 5 W is the line. A door lock or a short pump spike is not
12797
- * a cycle, so running starts only after 30 s above the line.
12798
- *
12799
- * A wash, dry or dishwasher pause (soak, heat-wait, heater off between
12800
- * bursts) lasts several minutes. Ending the cycle on the first dip would
12801
- * report "finished" in the middle of the program, so the stop dwell is
12802
- * 10 minutes on every type. The number is stored per type so one machine
12803
- * can move later without moving the others.
12804
- */
12805
- var APPLIANCE_TEMPLATE_ID = "appliance";
12806
- var APPLIANCE_KINDS = [
12807
- "washer",
12808
- "dryer",
12809
- "dishwasher"
12810
- ];
12811
- DeviceType.Washer, DeviceType.Dryer, DeviceType.Dishwasher;
12812
- /**
12813
- * A dumb plug-in stove or heater, built from a smart plug (a `Heater`).
12814
- *
12815
- * The plug is the actuator: `switch.setState` is a FORWARD to the plug's own
12816
- * (D967), so the heater switches exactly as the plug does. Running is the
12817
- * plug being on; when a power reading is also named, running is the draw
12818
- * staying above the line instead (a plug left on with the stove's own
12819
- * thermostat open is not heating). 50 W is far above any standby and below
12820
- * the smallest radiator.
12821
- */
12822
- var HEATER_TEMPLATE_ID = "heater";
12823
- DeviceType.Heater;
12824
- /**
12825
13361
  * Statistics and integrals over a history read (D944).
12826
13362
  *
12827
13363
  * Pure: the same points always give the same answer, so a restart recomputes
@@ -12965,34 +13501,6 @@ var HelperSpecSchema = discriminatedUnion("kind", [
12965
13501
  /** Actuator groups only. Readings leave this unset. */
12966
13502
  active: ActiveCriterionSchema.optional()
12967
13503
  }),
12968
- object({
12969
- kind: literal("appliance"),
12970
- templateId: literal(APPLIANCE_TEMPLATE_ID),
12971
- appliance: _enum(APPLIANCE_KINDS),
12972
- thresholdWatts: number().positive(),
12973
- startDwellMs: number().int().nonnegative(),
12974
- stopDwellMs: number().int().nonnegative(),
12975
- member: HelperMemberSchema,
12976
- /**
12977
- * The plug that powers the appliance (`switch.on`). Optional: when set, the
12978
- * composition carries a `power-source` feature, so the hub can cut and restore
12979
- * that plug (power-source link of a NEW-target composition).
12980
- */
12981
- powerSwitch: HelperMemberSchema.optional(),
12982
- /** How long a forced restart keeps the plug off; the cap's default when unset. */
12983
- offSeconds: number().optional()
12984
- }),
12985
- object({
12986
- kind: literal("heater"),
12987
- templateId: literal(HEATER_TEMPLATE_ID),
12988
- /** The plug, read and commanded at `switch.on`. */
12989
- plug: HelperMemberSchema,
12990
- /** The plug's power reading, when it has one: running is then the draw, not the switch. */
12991
- meter: HelperMemberSchema.optional(),
12992
- thresholdWatts: number().positive(),
12993
- startDwellMs: number().int().nonnegative(),
12994
- stopDwellMs: number().int().nonnegative()
12995
- }),
12996
13504
  object({
12997
13505
  kind: literal("statistic"),
12998
13506
  stat: _enum(STATISTIC_STATS),
@@ -13216,7 +13724,7 @@ var CompositionSchema = object({
13216
13724
  kind: literal("existing"),
13217
13725
  device: CompositionSourceRefSchema
13218
13726
  })]),
13219
- features: array(CompositionFeatureSchema).min(1).max(16),
13727
+ features: array(CompositionFeatureSchema).min(0).max(16),
13220
13728
  /**
13221
13729
  * Present when the block is a helper template. Absent on a free
13222
13730
  * composition (the room example, device 4603). The editor reads this,
@@ -13434,6 +13942,205 @@ var IntegrationInstanceRefSchema = object({
13434
13942
  ]),
13435
13943
  candidateStableId: string().optional()
13436
13944
  });
13945
+ /**
13946
+ * `RecordIntegrationInstances` - the `integration-instances` provider over ONE
13947
+ * entry kind, so an addon that holds a connection serves it in ~30 lines.
13948
+ *
13949
+ * Every instance is one record of the addon's own kind, keyed by the
13950
+ * `integrations` registry id. The records door does the secret work: a field the
13951
+ * kind marks `.meta({ secret: true })` is a keychain marker bound to the row, so
13952
+ * deleting the row deletes the secret, and one row's value is never another's.
13953
+ *
13954
+ * Patch rules for a secret (`updateInstance`): omitted, `''`, the redaction
13955
+ * token or the view the form was given KEEP the stored secret;
13956
+ * `{ $secretClear: true }` clears it; any other string replaces it.
13957
+ */
13958
+ /** The most instances one addon lists (an integrations page, not a table). */
13959
+ var INSTANCES_LIST_MAX = 1e3;
13960
+ /** The keys of the kind's secret fields that sit at the top level of the body. */
13961
+ function topLevelSecretKeys(paths) {
13962
+ return new Set(paths.filter((p) => !p.includes(".") && !p.includes("[") && !p.includes("{")));
13963
+ }
13964
+ /** The keys of the kind's top-level MAPS whose values are secrets (`applianceSecrets{}`). */
13965
+ function secretMapKeys(paths) {
13966
+ return new Set(paths.filter((p) => p.endsWith("{}") && !p.slice(0, -2).match(/[.[{]/)).map((p) => p.slice(0, -2)));
13967
+ }
13968
+ /**
13969
+ * A patch value for a map of secrets: an entry that is omitted, `''`, the redaction token or the
13970
+ * view the form was given KEEPS its stored secret (it is left out of the merge); `{ $secretClear }`
13971
+ * or `null` removes the entry; any other string replaces it. Null when nothing is left to merge.
13972
+ */
13973
+ function secretMapPatch(value) {
13974
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
13975
+ const out = {};
13976
+ for (const [key, entry] of Object.entries(value)) if (entry === null || isSecretClear(entry)) out[key] = null;
13977
+ else if (typeof entry === "string" && entry !== "" && entry !== "__camstack_redacted__" && !isSecretFieldView(entry)) out[key] = entry;
13978
+ return Object.keys(out).length > 0 ? out : null;
13979
+ }
13980
+ /** Does the kind's body schema carry an `enabled` field? */
13981
+ function declaresEnabled(kind) {
13982
+ const json = toJSONSchema(kind.schema, {
13983
+ unrepresentable: "any",
13984
+ io: "input"
13985
+ });
13986
+ const properties = Reflect.get(json, "properties");
13987
+ return typeof properties === "object" && properties !== null && "enabled" in properties;
13988
+ }
13989
+ var RecordIntegrationInstances = class {
13990
+ records;
13991
+ kind;
13992
+ hooks;
13993
+ handle;
13994
+ secretKeys;
13995
+ secretMaps;
13996
+ nameField;
13997
+ /** The `integrations` registry owns the on/off switch (`role: devices`); the body has none. */
13998
+ registryOwnsEnabled;
13999
+ constructor(records, kind, hooks) {
14000
+ this.records = records;
14001
+ this.kind = kind;
14002
+ this.hooks = hooks;
14003
+ this.handle = records.kind(kind);
14004
+ this.secretKeys = topLevelSecretKeys(kind.declaration.secretPaths);
14005
+ this.secretMaps = secretMapKeys(kind.declaration.secretPaths);
14006
+ this.nameField = kind.declaration.entry?.nameField ?? "name";
14007
+ this.registryOwnsEnabled = hooks.description.role === "devices";
14008
+ 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"`);
14009
+ }
14010
+ /**
14011
+ * One instance read for the addon's own runtime; null when absent. When the keychain is
14012
+ * locked the row is served WITHOUT its secrets and says so (`secrets: 'unavailable'`), so the
14013
+ * caller can keep what it had instead of reconfiguring with an empty secret (D49).
14014
+ */
14015
+ async readResolved(id) {
14016
+ try {
14017
+ const record = await this.handle.getResolved(id);
14018
+ return record === null ? null : {
14019
+ id,
14020
+ body: record.data,
14021
+ enabled: record.data.enabled !== false,
14022
+ secrets: "resolved"
14023
+ };
14024
+ } catch (err) {
14025
+ if (!(err instanceof RecordSecretUnavailableError)) throw err;
14026
+ const stored = await this.handle.get(id);
14027
+ if (stored === null) return null;
14028
+ return {
14029
+ id,
14030
+ body: Object.fromEntries(Object.entries(stored.data).filter(([key]) => !this.secretKeys.has(key))),
14031
+ enabled: stored.data.enabled !== false,
14032
+ secrets: "unavailable"
14033
+ };
14034
+ }
14035
+ }
14036
+ /** The body of {@link readResolved} alone; a locked keychain yields the row without secrets. */
14037
+ async getResolved(id) {
14038
+ return (await this.readResolved(id))?.body ?? null;
14039
+ }
14040
+ /** Every instance, secrets resolved where the keychain allows; an absent one is skipped. */
14041
+ async listResolved() {
14042
+ const page = await this.handle.query({ limit: INSTANCES_LIST_MAX });
14043
+ const out = [];
14044
+ for (const record of page.records) {
14045
+ const read = await this.readResolved(record.id);
14046
+ if (read !== null) out.push(read);
14047
+ }
14048
+ return out;
14049
+ }
14050
+ viewOf(record) {
14051
+ const shown = secretViewsOf(this.records.owner, this.kind.name, record.id, this.kind.declaration, record.data);
14052
+ const rawName = record.data[this.nameField];
14053
+ const kind = this.hooks.kindOf?.(record.data);
14054
+ const health = this.hooks.health?.(record.data, record.id);
14055
+ return {
14056
+ id: record.id,
14057
+ name: typeof rawName === "string" ? rawName : record.id,
14058
+ configured: this.hooks.configured(record.data),
14059
+ ...this.registryOwnsEnabled ? {} : { enabled: record.data.enabled !== false },
14060
+ formValues: shown,
14061
+ ...kind !== void 0 ? { kind } : {},
14062
+ ...health?.status !== void 0 ? { status: health.status } : {},
14063
+ ...health?.lastCheckedAt !== void 0 ? { lastCheckedAt: health.lastCheckedAt } : {}
14064
+ };
14065
+ }
14066
+ describe = async () => this.hooks.mintId === void 0 ? this.hooks.description : {
14067
+ ...this.hooks.description,
14068
+ mintsId: true
14069
+ };
14070
+ instanceFormSchema = async ({ id }) => this.hooks.formSchema(id);
14071
+ listInstances = async () => {
14072
+ return (await this.handle.query({ limit: INSTANCES_LIST_MAX })).records.map((record) => this.viewOf(record));
14073
+ };
14074
+ getInstance = async ({ id }) => {
14075
+ const record = await this.handle.get(id);
14076
+ return record === null ? null : this.viewOf(record);
14077
+ };
14078
+ /** Insert ONE row (`ifRev: 0`: an existing id is refused, never overwritten). */
14079
+ createInstance = async ({ id, name, kind }) => {
14080
+ const minted = id ?? this.hooks.mintId?.({
14081
+ name,
14082
+ ...kind !== void 0 ? { kind } : {}
14083
+ });
14084
+ if (minted === void 0) throw new Error("createInstance needs an id: this provider does not mint one");
14085
+ await this.handle.put({
14086
+ id: minted,
14087
+ data: this.hooks.initialBody(name, kind)
14088
+ }, { ifRev: 0 });
14089
+ await this.hooks.onChanged?.(minted, "created");
14090
+ return { id: minted };
14091
+ };
14092
+ updateInstance = async ({ id, name, values }) => {
14093
+ const patch = {};
14094
+ for (const [key, value] of Object.entries(values)) {
14095
+ if (value === void 0) continue;
14096
+ if (this.secretMaps.has(key)) {
14097
+ const entries = secretMapPatch(value);
14098
+ if (entries !== null) patch[key] = entries;
14099
+ } else if (!this.secretKeys.has(key)) patch[key] = value;
14100
+ else if (isSecretClear(value)) patch[key] = null;
14101
+ else if (typeof value === "string" && value !== "" && value !== "__camstack_redacted__" && !isSecretFieldView(value)) patch[key] = value;
14102
+ }
14103
+ if (name !== void 0) patch[this.nameField] = name;
14104
+ await this.handle.patch(id, patch);
14105
+ await this.hooks.onChanged?.(id, "updated");
14106
+ return { ok: true };
14107
+ };
14108
+ /** The switch lives in the record body; the addon is told so it applies it (D996). */
14109
+ setInstanceEnabled = async ({ id, enabled }) => {
14110
+ if (this.registryOwnsEnabled) throw new Error(`instance "${id}": the integrations registry owns the on/off switch of this addon; set it with integrations.update`);
14111
+ await this.handle.patch(id, { enabled });
14112
+ await this.hooks.onChanged?.(id, "enabled");
14113
+ return { ok: true };
14114
+ };
14115
+ /** The row and its keychain refs go together (the records door). */
14116
+ deleteInstance = async ({ id }) => {
14117
+ await this.handle.delete(id);
14118
+ await this.hooks.onChanged?.(id, "deleted");
14119
+ return { ok: true };
14120
+ };
14121
+ testInstance = async (input) => {
14122
+ if (this.hooks.test === void 0) return {
14123
+ success: false,
14124
+ status: "unsupported",
14125
+ error: "This integration declares no connection test"
14126
+ };
14127
+ return this.hooks.test(input);
14128
+ };
14129
+ /** The flat provider object to hand to `registerProvider`. */
14130
+ toProvider() {
14131
+ return {
14132
+ describe: this.describe,
14133
+ instanceFormSchema: this.instanceFormSchema,
14134
+ listInstances: this.listInstances,
14135
+ getInstance: this.getInstance,
14136
+ createInstance: this.createInstance,
14137
+ updateInstance: this.updateInstance,
14138
+ setInstanceEnabled: this.setInstanceEnabled,
14139
+ deleteInstance: this.deleteInstance,
14140
+ testInstance: this.testInstance
14141
+ };
14142
+ }
14143
+ };
13437
14144
  var EncodeProfileSchema = object({
13438
14145
  video: object({
13439
14146
  codec: _enum([
@@ -49136,49 +49843,6 @@ function actuator(input) {
49136
49843
  };
49137
49844
  }
49138
49845
  new Map(GROUP_TEMPLATES.map((template) => [template.id, template]));
49139
- var PowerSourceRefusalReasonSchema = _enum([
49140
- "no-power-source",
49141
- "switch-missing",
49142
- "switch-offline",
49143
- "switch-unknown",
49144
- "restart-in-progress",
49145
- "switch-call-failed"
49146
- ]);
49147
- var PowerSourceActionResultSchema = discriminatedUnion("accepted", [object({ accepted: literal(true) }), object({
49148
- accepted: literal(false),
49149
- reason: PowerSourceRefusalReasonSchema,
49150
- /** One line for the operator, naming the switch. */
49151
- message: string()
49152
- })]);
49153
- var PowerSourceInfoSchema = object({
49154
- /** False when the device has no power source linked; the rest is then empty. */
49155
- linked: boolean(),
49156
- switchDeviceId: number().nullable(),
49157
- switchName: string().nullable(),
49158
- /** The switch's on/off state, or null when it is unknown. Never false for unknown (D393). */
49159
- switchOn: boolean().nullable(),
49160
- switchOnline: boolean().nullable(),
49161
- restartInProgress: boolean(),
49162
- offSeconds: number().int()
49163
- });
49164
- object({
49165
- /** Null while the switch has not reported: unknown is never `false` (D393). */
49166
- switchOn: boolean().nullable(),
49167
- offSeconds: number().int(),
49168
- lastFetchedAt: number()
49169
- });
49170
- DeviceType.Gateway, DeviceType.Hub, DeviceType.Camera, DeviceType.Sensor, DeviceType.MediaPlayer, DeviceType.Vacuum, DeviceType.Generic, DeviceType.Washer, DeviceType.Dryer, DeviceType.Dishwasher, DeviceType.PetFountain, DeviceType.Fan, DeviceType.Humidifier, DeviceType.Climate, DeviceType.WaterHeater;
49171
- var deviceInput$2 = object({ deviceId: number().int().nonnegative() });
49172
- systemMethod(deviceInput$2, PowerSourceInfoSchema, { auth: "admin" }), systemMethod(deviceInput$2, PowerSourceActionResultSchema, {
49173
- kind: "mutation",
49174
- auth: "admin"
49175
- }), systemMethod(deviceInput$2, PowerSourceActionResultSchema, {
49176
- kind: "mutation",
49177
- auth: "admin"
49178
- }), systemMethod(deviceInput$2, PowerSourceActionResultSchema, {
49179
- kind: "mutation",
49180
- auth: "admin"
49181
- });
49182
49846
  DeviceFeature.LightColorRgb, DeviceFeature.LightColorHsv, DeviceFeature.LightColorMired;
49183
49847
  DeviceType.Camera;
49184
49848
  `${COMPOSED_DEVICE_STABLE_ID_PREFIX}`;
@@ -49206,6 +49870,165 @@ var ComposableCapabilitiesSchema = object({ caps: array(object({
49206
49870
  }).optional()
49207
49871
  })) });
49208
49872
  /**
49873
+ * A saved Customize assignment (D936). The schema is the type: callers use
49874
+ * `z.infer`, they do not restate the shape.
49875
+ */
49876
+ var OverrideSourceSchema = object({
49877
+ addonId: string().min(1),
49878
+ stableId: string().min(1),
49879
+ cap: string().min(1),
49880
+ fieldPath: string().min(1)
49881
+ });
49882
+ var IdentityTransformDraftSchema = object({ kind: literal("identity") });
49883
+ var InvertTransformDraftSchema = object({ kind: literal("invert") });
49884
+ var ThresholdTransformDraftSchema = object({
49885
+ kind: literal("threshold"),
49886
+ comparison: _enum(["gte", "lte"]),
49887
+ threshold: number(),
49888
+ startDwellMs: number().nonnegative(),
49889
+ stopDwellMs: number().nonnegative()
49890
+ });
49891
+ var CustomizeTransformDraftSchema = discriminatedUnion("kind", [
49892
+ IdentityTransformDraftSchema,
49893
+ InvertTransformDraftSchema,
49894
+ ThresholdTransformDraftSchema,
49895
+ object({
49896
+ kind: literal("linear"),
49897
+ scale: number(),
49898
+ offset: number(),
49899
+ clampMin: number().optional(),
49900
+ clampMax: number().optional()
49901
+ }),
49902
+ object({
49903
+ kind: literal("enum-map"),
49904
+ mapping: record(string(), string().nullable())
49905
+ }),
49906
+ object({ kind: literal("number") })
49907
+ ]);
49908
+ var ScalarOverrideDraftSchema = object({
49909
+ kind: literal("scalar"),
49910
+ cap: string().min(1),
49911
+ targetId: string().min(1),
49912
+ source: OverrideSourceSchema,
49913
+ transform: CustomizeTransformDraftSchema
49914
+ });
49915
+ var KeyedArrayOverrideDraftSchema = object({
49916
+ kind: literal("keyedArray"),
49917
+ cap: string().min(1),
49918
+ targetId: string().min(1),
49919
+ key: string().min(1),
49920
+ label: string().min(1),
49921
+ fieldPath: string().min(1),
49922
+ source: OverrideSourceSchema,
49923
+ transform: CustomizeTransformDraftSchema
49924
+ });
49925
+ var PulseOverrideDraftSchema = object({
49926
+ kind: literal("pulse"),
49927
+ cap: string().min(1),
49928
+ targetId: string().min(1),
49929
+ enabled: boolean(),
49930
+ debounceMs: number().nonnegative(),
49931
+ edges: array(_enum([
49932
+ "rising",
49933
+ "button",
49934
+ "native-event"
49935
+ ])).min(1).optional(),
49936
+ sources: array(OverrideSourceSchema).min(1)
49937
+ });
49938
+ var SpanSourceDraftSchema = OverrideSourceSchema.extend({ mode: _enum([
49939
+ "in-addition",
49940
+ "confirm",
49941
+ "replace"
49942
+ ]).optional() });
49943
+ discriminatedUnion("kind", [
49944
+ ScalarOverrideDraftSchema,
49945
+ KeyedArrayOverrideDraftSchema,
49946
+ PulseOverrideDraftSchema,
49947
+ object({
49948
+ kind: literal("span"),
49949
+ cap: string().min(1),
49950
+ targetId: string().min(1),
49951
+ timeoutMs: number().nonnegative(),
49952
+ cooldownMs: number().nonnegative().optional(),
49953
+ sources: array(SpanSourceDraftSchema)
49954
+ })
49955
+ ]);
49956
+ object({
49957
+ targetId: string().min(1),
49958
+ configured: boolean(),
49959
+ source: _enum(["native", "assigned"]),
49960
+ state: _enum([
49961
+ "active",
49962
+ "stale",
49963
+ "released",
49964
+ "unavailable"
49965
+ ]),
49966
+ reason: string().nullable()
49967
+ });
49968
+ /**
49969
+ * What a running-threshold proposal says (planning#405). The schema is the
49970
+ * type: the algorithm, the capability method and the UI all read `z.infer`.
49971
+ *
49972
+ * A proposal is read-only advice: it carries the numbers it was derived from
49973
+ * (`evidence`) so the operator can judge it, and an `insufficient` answer names
49974
+ * WHY with a typed reason and the catalog defaults, never an invented number.
49975
+ */
49976
+ var RunningProposalTierSchema = _enum(["raw", "5m"]);
49977
+ var RunningProposalConfidenceSchema = _enum([
49978
+ "high",
49979
+ "medium",
49980
+ "low"
49981
+ ]);
49982
+ var RunningProposalInsufficientReasonSchema = _enum([
49983
+ "no-history",
49984
+ "span-too-short",
49985
+ "truncated",
49986
+ "no-idle-floor",
49987
+ "no-runs",
49988
+ "no-separation"
49989
+ ]);
49990
+ var RunningProposalReplaySchema = object({
49991
+ /** Intervals the real dwell expression held true over the window. */
49992
+ intervals: number().int().nonnegative(),
49993
+ /** Intervals outside every run, or a second interval inside one. */
49994
+ extra: number().int().nonnegative(),
49995
+ /** Runs without an interval of their own (none, or merged into a neighbour). */
49996
+ missed: number().int().nonnegative()
49997
+ });
49998
+ var RunningProposalEvidenceSchema = object({
49999
+ tier: RunningProposalTierSchema,
50000
+ spanMs: number().nonnegative(),
50001
+ from: number(),
50002
+ to: number(),
50003
+ points: number().int().nonnegative(),
50004
+ runsFound: number().int().nonnegative(),
50005
+ pausesFound: number().int().nonnegative(),
50006
+ longestPauseMs: number().nonnegative(),
50007
+ idleFloorW: number(),
50008
+ noiseCeilingW: number(),
50009
+ plateauW: number(),
50010
+ replay: RunningProposalReplaySchema
50011
+ });
50012
+ var RunningProposalInsufficientEvidenceSchema = object({
50013
+ spanMs: number().nonnegative(),
50014
+ points: number().int().nonnegative(),
50015
+ runsFound: number().int().nonnegative()
50016
+ });
50017
+ var RunningThresholdProposalSchema = discriminatedUnion("state", [object({
50018
+ state: literal("proposal"),
50019
+ transform: ThresholdTransformDraftSchema,
50020
+ evidence: RunningProposalEvidenceSchema,
50021
+ confidence: RunningProposalConfidenceSchema,
50022
+ /** Why the confidence is not higher; empty when nothing held it back. */
50023
+ notes: array(string())
50024
+ }), object({
50025
+ state: literal("insufficient"),
50026
+ reason: RunningProposalInsufficientReasonSchema,
50027
+ evidence: RunningProposalInsufficientEvidenceSchema,
50028
+ /** The catalog defaults, offered as what stands when nothing better is known. */
50029
+ fallback: ThresholdTransformDraftSchema
50030
+ })]);
50031
+ /**
49209
50032
  * The report of a one-shot "move this owner's plaintext secrets into the
49210
50033
  * keychain" run (D878). COUNTS only - never a value, never a ref.
49211
50034
  *
@@ -49495,6 +50318,14 @@ method(object({}), object({ blocks: array(CoreBlockSchema) }), { auth: "admin" }
49495
50318
  kind: "mutation",
49496
50319
  auth: "admin",
49497
50320
  access: "view"
50321
+ }), method(object({
50322
+ deviceId: number().int(),
50323
+ cap: string().min(1),
50324
+ fieldPath: string().min(1),
50325
+ deviceType: _enum(DeviceType).optional()
50326
+ }), RunningThresholdProposalSchema, {
50327
+ auth: "admin",
50328
+ access: "view"
49498
50329
  }), method(object({
49499
50330
  blockId: string().min(1),
49500
50331
  trace: AutomationRunTraceSchema.optional(),
@@ -50359,7 +51190,53 @@ method(object({
50359
51190
  * exposes only the COMMON surface: link state, supported device
50360
51191
  * kinds (so the UI can filter the device picker), and per-device
50361
51192
  * expose/unexpose.
51193
+ *
51194
+ * INSTANCES. One export addon can serve several independent targets (a
51195
+ * HomeKit bridge, a Home Assistant broker). `listInstances` names them.
51196
+ * `instanceId` on a READ is optional: absent = the whole addon (linked if any
51197
+ * enabled instance is, `exposedDeviceCount` = distinct devices, `setup` = the
51198
+ * default instance's); present = that instance; an id the provider does not
51199
+ * serve is refused with `ExportInstanceUnknownError` (`export-instance-unknown`),
51200
+ * never answered empty. `instanceId` on a WRITE is REQUIRED: a membership
51201
+ * change always names the target it changes. A single-instance provider
51202
+ * accepts an absent id on a read or its own id, and refuses any other.
51203
+ */
51204
+ /** Which instance of an export addon a call addresses. Absent on a read = the whole addon. */
51205
+ var InstanceIdSchema$1 = string().min(1);
51206
+ var InstancePinSchema = object({ instanceId: InstanceIdSchema$1.optional() });
51207
+ /** One independent export target of an addon. */
51208
+ var ExportInstanceSchema = object({
51209
+ instanceId: InstanceIdSchema$1,
51210
+ name: string(),
51211
+ enabled: boolean(),
51212
+ kind: string().optional()
51213
+ });
51214
+ var EXPORT_INSTANCE_UNKNOWN = "export-instance-unknown";
51215
+ /** The named failure of an `instanceId` the provider does not serve. The message starts with the code. */
51216
+ var ExportInstanceUnknownError = class extends Error {
51217
+ code = EXPORT_INSTANCE_UNKNOWN;
51218
+ instanceId;
51219
+ constructor(addon, instanceId) {
51220
+ super(`${EXPORT_INSTANCE_UNKNOWN}: ${addon} serves no instance "${instanceId}"`);
51221
+ this.name = "ExportInstanceUnknownError";
51222
+ this.instanceId = instanceId;
51223
+ }
51224
+ };
51225
+ /**
51226
+ * The instance a `getStatus` call names. The cap's `status` block injects a per-device
51227
+ * `getStatus({ deviceId })` beside the method's own `{ instanceId? }`, so the provider sees
51228
+ * both shapes; only the second names an instance (a per-device status read is addon-wide).
50362
51229
  */
51230
+ function statusInstanceOf(input) {
51231
+ return "instanceId" in input ? input.instanceId : void 0;
51232
+ }
51233
+ /**
51234
+ * A single-instance provider's check: an absent id or its own passes, any other throws
51235
+ * `ExportInstanceUnknownError`.
51236
+ */
51237
+ function assertOwnExportInstance(addon, own, instanceId) {
51238
+ if (instanceId !== void 0 && instanceId !== own) throw new ExportInstanceUnknownError(addon, instanceId);
51239
+ }
50363
51240
  var LinkStateSchema = _enum([
50364
51241
  "unlinked",
50365
51242
  "linked",
@@ -50410,10 +51287,14 @@ var ExposedDeviceSchema = object({
50410
51287
  capabilities: array(string()).optional()
50411
51288
  });
50412
51289
  var ExposeInputSchema = object({
51290
+ instanceId: InstanceIdSchema$1,
50413
51291
  deviceId: string(),
50414
51292
  capabilities: array(string()).optional()
50415
51293
  });
50416
- var UnexposeInputSchema = object({ deviceId: string() });
51294
+ var UnexposeInputSchema = object({
51295
+ instanceId: InstanceIdSchema$1,
51296
+ deviceId: string()
51297
+ });
50417
51298
  /**
50418
51299
  * What an exporter may expose besides devices (D968). An action and a
50419
51300
  * notification target are LIST ENTRIES, never devices (D954): they enter an
@@ -50442,8 +51323,14 @@ var ExposedEntitySchema = object({
50442
51323
  entity: ExportEntityRefSchema,
50443
51324
  exposedAs: string().optional()
50444
51325
  });
50445
- var ExposeEntityInputSchema = object({ entity: ExportEntityRefSchema });
50446
- var UnexposeEntityInputSchema = object({ entity: ExportEntityRefSchema });
51326
+ var ExposeEntityInputSchema = object({
51327
+ instanceId: InstanceIdSchema$1,
51328
+ entity: ExportEntityRefSchema
51329
+ });
51330
+ var UnexposeEntityInputSchema = object({
51331
+ instanceId: InstanceIdSchema$1,
51332
+ entity: ExportEntityRefSchema
51333
+ });
50447
51334
  var deviceExportCapability = {
50448
51335
  name: "device-export",
50449
51336
  scope: "system",
@@ -50463,9 +51350,10 @@ var deviceExportCapability = {
50463
51350
  */
50464
51351
  exposesDeviceSettings: true,
50465
51352
  methods: {
50466
- getStatus: method(_void(), DeviceExportStatusSchema),
50467
- listSupportedDeviceKinds: method(_void(), array(DeviceKindSchema)),
50468
- listExposedDevices: method(_void(), array(ExposedDeviceSchema)),
51353
+ getStatus: method(InstancePinSchema, DeviceExportStatusSchema),
51354
+ listInstances: method(_void(), array(ExportInstanceSchema)),
51355
+ listSupportedDeviceKinds: method(InstancePinSchema, array(DeviceKindSchema)),
51356
+ listExposedDevices: method(InstancePinSchema, array(ExposedDeviceSchema)),
50469
51357
  exposeDevice: method(ExposeInputSchema, _void(), {
50470
51358
  kind: "mutation",
50471
51359
  auth: "admin"
@@ -50475,7 +51363,7 @@ var deviceExportCapability = {
50475
51363
  auth: "admin"
50476
51364
  }),
50477
51365
  listSupportedEntityKinds: optionalMethod(_void(), array(ExportEntityKindSchema)),
50478
- listExposedEntities: optionalMethod(_void(), array(ExposedEntitySchema)),
51366
+ listExposedEntities: optionalMethod(InstancePinSchema, array(ExposedEntitySchema)),
50479
51367
  exposeEntity: optionalMethod(ExposeEntityInputSchema, _void(), {
50480
51368
  kind: "mutation",
50481
51369
  auth: "admin"
@@ -53680,15 +54568,15 @@ var FanPresetCaptureResultSchema = object({
53680
54568
  items: array(FanCaptureItemSchema),
53681
54569
  omitted: array(FanCaptureOmissionSchema)
53682
54570
  });
53683
- var deviceInput$1 = object({ deviceId: number().int().nonnegative() });
54571
+ var deviceInput$2 = object({ deviceId: number().int().nonnegative() });
53684
54572
  DeviceType.Fan;
53685
- method(deviceInput$1, array(FanPresetSchema), { auth: "protected" }), method(deviceInput$1.extend({ presets: array(FanPresetSchema).max(12) }), FanPresetsSetResultSchema, {
54573
+ method(deviceInput$2, array(FanPresetSchema), { auth: "protected" }), method(deviceInput$2.extend({ presets: array(FanPresetSchema).max(12) }), FanPresetsSetResultSchema, {
53686
54574
  kind: "mutation",
53687
54575
  auth: "admin"
53688
- }), method(deviceInput$1.extend({ presetId: string().min(1) }), FanPresetApplyResultSchema, {
54576
+ }), method(deviceInput$2.extend({ presetId: string().min(1) }), FanPresetApplyResultSchema, {
53689
54577
  kind: "mutation",
53690
54578
  auth: "protected"
53691
- }), method(deviceInput$1.extend({
54579
+ }), method(deviceInput$2.extend({
53692
54580
  fields: array(FanCaptureFieldSchema).optional(),
53693
54581
  steps: array(ActionStepSchema).max(20).default([])
53694
54582
  }), FanPresetCaptureResultSchema, { auth: "protected" });
@@ -54228,13 +55116,65 @@ method(_void(), array(IntegrationWithStateSchema)), method(object({ id: string()
54228
55116
  */
54229
55117
  var ConfigSchemaPassthrough$3 = custom();
54230
55118
  var IntegrationInstanceIdSchema = string().min(1);
55119
+ var IntegrationInstanceModeSchema = _enum(["single", "multiple"]);
55120
+ /**
55121
+ * One kind of instance a provider can create (an adapter, an account type). The sign-in and
55122
+ * connect fields follow the `broker` contract (`broker.cap.ts`): `signIn.basePath` is a
55123
+ * hub-relative route set speaking the sign-in contract, `connectPath` / `disconnectPath` open an
55124
+ * interactive account link (popup) and may carry `{{brokerId}}`, which the UI replaces with the
55125
+ * instance id.
55126
+ */
55127
+ var IntegrationInstanceKindSchema = object({
55128
+ /** Stable id of the kind, sent back as `createInstance.kind`. */
55129
+ id: string().min(1),
55130
+ label: string().min(1),
55131
+ /** The kind signs in through a server-held interactive session. */
55132
+ signIn: object({
55133
+ basePath: string().min(1),
55134
+ methods: array(_enum(["device-code", "proxy"])).optional()
55135
+ }).optional(),
55136
+ /** Relative hub path to start an interactive account link of an instance of this kind. */
55137
+ connectPath: string().min(1).optional(),
55138
+ /** Relative hub path to disconnect that account. */
55139
+ disconnectPath: string().min(1).optional()
55140
+ });
54231
55141
  var IntegrationInstanceDescriptionSchema = object({
55142
+ /** What the instances are for the Integrations page; see {@link IntegrationInstanceRoleSchema}. */
55143
+ role: _enum([
55144
+ "devices",
55145
+ "services",
55146
+ "both"
55147
+ ]),
55148
+ /** How the devices of an instance are found; absent means `{ mode: 'none' }`. */
55149
+ discovery: object({
55150
+ mode: _enum([
55151
+ "none",
55152
+ "lan",
55153
+ "account"
55154
+ ]),
55155
+ scopedToInstance: boolean()
55156
+ }).optional(),
54232
55157
  /** `single`: at most one instance can exist (Loki). `multiple`: an account each. */
54233
- instanceMode: _enum(["single", "multiple"]),
55158
+ instanceMode: IntegrationInstanceModeSchema,
54234
55159
  /** What the instance is, for the UI (`destination`, `relay`, `account`). */
54235
55160
  kind: string(),
54236
55161
  /** True when `testInstance` really probes the remote. */
54237
- canTest: boolean()
55162
+ canTest: boolean(),
55163
+ /**
55164
+ * The kinds an instance can be of. Absent or one entry: nothing to choose; more than one: the
55165
+ * Add flow asks which first and sends it as `createInstance.kind`.
55166
+ */
55167
+ kinds: array(IntegrationInstanceKindSchema).optional(),
55168
+ /**
55169
+ * The provider accepts `createInstance.id` for an id that once existed (an adopted id, because
55170
+ * devices carry it). The UI then offers "restore under its old id" on Add. Absent means no.
55171
+ */
55172
+ allowRestoreId: boolean().optional(),
55173
+ /**
55174
+ * `createInstance` without an `id` works: the provider mints it. Absent means the caller must
55175
+ * send an id (the UI then mints an opaque one).
55176
+ */
55177
+ mintsId: boolean().optional()
54238
55178
  });
54239
55179
  var IntegrationInstanceStatusSchema = object({
54240
55180
  state: _enum([
@@ -54243,7 +55183,9 @@ var IntegrationInstanceStatusSchema = object({
54243
55183
  "error",
54244
55184
  "unknown"
54245
55185
  ]),
54246
- detail: string().optional()
55186
+ detail: string().optional(),
55187
+ /** A short human word for the state ("Signed in", "Token expired"); shown instead of `state`. */
55188
+ label: string().optional()
54247
55189
  });
54248
55190
  var IntegrationInstanceSchema = object({
54249
55191
  id: IntegrationInstanceIdSchema,
@@ -54251,13 +55193,18 @@ var IntegrationInstanceSchema = object({
54251
55193
  /** The addon's own rule (an URL is present, a client id is present...). */
54252
55194
  configured: boolean(),
54253
55195
  /**
54254
- * The instance's own on/off switch (D996): always present, derived from the record body
54255
- * (`enabled !== false`, so a row written before the field existed is on).
55196
+ * The instance's own on/off switch (D996), derived from the record body (`enabled !== false`,
55197
+ * so a row written before the field existed is on). Absent when the `integrations` registry
55198
+ * owns the switch (`describe().role` is `devices`): read it from the registry row.
54256
55199
  */
54257
- enabled: boolean(),
55200
+ enabled: boolean().optional(),
55201
+ /** The kind of this instance (one of `describe().kinds[].id`), when the provider has kinds. */
55202
+ kind: string().optional(),
54258
55203
  /** Values for the instance form; a secret is a `SecretFieldView`, never text. */
54259
55204
  formValues: record(string(), unknown()),
54260
- status: IntegrationInstanceStatusSchema.optional()
55205
+ status: IntegrationInstanceStatusSchema.optional(),
55206
+ /** Epoch ms of the last probe of the remote that produced `status`; absent when never checked. */
55207
+ lastCheckedAt: number().optional()
54261
55208
  });
54262
55209
  var IntegrationInstancePatchSchema = object({
54263
55210
  id: IntegrationInstanceIdSchema,
@@ -54265,31 +55212,57 @@ var IntegrationInstancePatchSchema = object({
54265
55212
  /** Omitted / '' / redaction token keeps a secret; `{ $secretClear: true }` clears it. */
54266
55213
  values: record(string(), unknown())
54267
55214
  });
54268
- 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({
54269
- id: IntegrationInstanceIdSchema,
54270
- name: string().min(1)
54271
- }), object({ id: string() }), {
54272
- kind: "mutation",
54273
- auth: "admin"
54274
- }), method(IntegrationInstancePatchSchema, object({ ok: literal(true) }), {
54275
- kind: "mutation",
54276
- auth: "admin"
54277
- }), method(object({
54278
- id: IntegrationInstanceIdSchema,
54279
- enabled: boolean()
54280
- }), object({ ok: literal(true) }), {
54281
- kind: "mutation",
54282
- auth: "admin"
54283
- }), method(object({ id: IntegrationInstanceIdSchema }), object({ ok: literal(true) }), {
54284
- kind: "mutation",
54285
- auth: "admin"
54286
- }), optionalMethod(object({
54287
- id: IntegrationInstanceIdSchema.nullable(),
54288
- values: record(string(), unknown())
54289
- }), TestConnectionResultSchema$1, {
54290
- kind: "mutation",
54291
- auth: "admin"
54292
- });
55215
+ var integrationInstancesCapability = {
55216
+ name: "integration-instances",
55217
+ scope: "system",
55218
+ mode: "collection",
55219
+ methods: {
55220
+ describe: method(_void(), IntegrationInstanceDescriptionSchema, { auth: "admin" }),
55221
+ /** The form; `id: null` is the create form. */
55222
+ instanceFormSchema: method(object({ id: IntegrationInstanceIdSchema.nullable() }), ConfigSchemaPassthrough$3, { auth: "admin" }),
55223
+ listInstances: method(_void(), array(IntegrationInstanceSchema).readonly(), { auth: "admin" }),
55224
+ getInstance: method(object({ id: IntegrationInstanceIdSchema }), IntegrationInstanceSchema.nullable(), { auth: "admin" }),
55225
+ /**
55226
+ * Insert the typed record. With `id` it is stored under that id (a duplicate id is refused);
55227
+ * without one the PROVIDER mints it and answers it. `kind` picks one of `describe().kinds`.
55228
+ */
55229
+ createInstance: method(object({
55230
+ id: IntegrationInstanceIdSchema.optional(),
55231
+ name: string().min(1),
55232
+ kind: string().min(1).optional()
55233
+ }), object({ id: string() }), {
55234
+ kind: "mutation",
55235
+ auth: "admin"
55236
+ }),
55237
+ updateInstance: method(IntegrationInstancePatchSchema, object({ ok: literal(true) }), {
55238
+ kind: "mutation",
55239
+ auth: "admin"
55240
+ }),
55241
+ /**
55242
+ * Switch ONE instance on or off. A row control, not a form field: `updateInstance.values` is the
55243
+ * form patch (D62, D996). An off instance keeps its record and secrets and does no work.
55244
+ */
55245
+ setInstanceEnabled: method(object({
55246
+ id: IntegrationInstanceIdSchema,
55247
+ enabled: boolean()
55248
+ }), object({ ok: literal(true) }), {
55249
+ kind: "mutation",
55250
+ auth: "admin"
55251
+ }),
55252
+ /** Delete the record and its keychain refs together. */
55253
+ deleteInstance: method(object({ id: IntegrationInstanceIdSchema }), object({ ok: literal(true) }), {
55254
+ kind: "mutation",
55255
+ auth: "admin"
55256
+ }),
55257
+ testInstance: optionalMethod(object({
55258
+ id: IntegrationInstanceIdSchema.nullable(),
55259
+ values: record(string(), unknown())
55260
+ }), TestConnectionResultSchema$1, {
55261
+ kind: "mutation",
55262
+ auth: "admin"
55263
+ })
55264
+ }
55265
+ };
54293
55266
  /**
54294
55267
  * Two-way audio / talk-back cap. Clients open a WebRTC audio-only
54295
55268
  * session (server-initiated offer pattern, identical to the main
@@ -56088,6 +57061,11 @@ var LogEntrySchema = object({
56088
57061
  * flight, and not asking for the next slice ends the scan.
56089
57062
  */
56090
57063
  var LogReadQuerySchema = object({
57064
+ /**
57065
+ * Which destination INSTANCE answers (a destination addon may hold several records). Absent ⇒
57066
+ * the provider's first readable one, so a caller written before instances existed is unchanged.
57067
+ */
57068
+ instanceId: string().min(1).max(200).optional(),
56091
57069
  /** Correlates `cancelRead`. Caller-chosen, unique per in-flight read. */
56092
57070
  requestId: string().min(1).max(64).optional(),
56093
57071
  /** The device the line is about (`tags.deviceId`, numeric). */
@@ -56150,6 +57128,8 @@ var LogReadResultSchema = object({
56150
57128
  /** True when `cancelRead` ended this slice early. */
56151
57129
  cancelled: boolean().optional()
56152
57130
  });
57131
+ /** Names one destination instance; absent ⇒ the provider's first readable one. */
57132
+ var LogInstanceSelectorSchema = object({ instanceId: string().min(1).max(200).optional() });
56153
57133
  var LogReadCapabilitiesSchema = object({
56154
57134
  /** False ⇒ this destination only ships lines (console, forwarder, an unconfigured Loki). */
56155
57135
  readable: boolean(),
@@ -56168,7 +57148,7 @@ var LogReadCapabilitiesSchema = object({
56168
57148
  /** How far back the store reaches, when the provider knows (days). */
56169
57149
  retentionDays: number().nullable()
56170
57150
  });
56171
- method(LogEntrySchema, _void(), { kind: "mutation" }), optionalMethod(_void(), LogReadCapabilitiesSchema, { auth: "admin" }), optionalMethod(LogReadQuerySchema, LogReadResultSchema, { auth: "admin" }), optionalMethod(object({ requestId: string().min(1).max(64) }), object({ cancelled: boolean() }), {
57151
+ method(LogEntrySchema, _void(), { kind: "mutation" }), optionalMethod(LogInstanceSelectorSchema, LogReadCapabilitiesSchema, { auth: "admin" }), optionalMethod(LogReadQuerySchema, LogReadResultSchema, { auth: "admin" }), optionalMethod(object({ requestId: string().min(1).max(64) }), object({ cancelled: boolean() }), {
56172
57152
  kind: "mutation",
56173
57153
  auth: "admin"
56174
57154
  });
@@ -67740,6 +68720,49 @@ object({
67740
68720
  DeviceType.PetFeeder,
67741
68721
  DeviceType.Heater
67742
68722
  ].filter((type) => type !== DeviceType.Sensor);
68723
+ var PowerSourceRefusalReasonSchema = _enum([
68724
+ "no-power-source",
68725
+ "switch-missing",
68726
+ "switch-offline",
68727
+ "switch-unknown",
68728
+ "restart-in-progress",
68729
+ "switch-call-failed"
68730
+ ]);
68731
+ var PowerSourceActionResultSchema = discriminatedUnion("accepted", [object({ accepted: literal(true) }), object({
68732
+ accepted: literal(false),
68733
+ reason: PowerSourceRefusalReasonSchema,
68734
+ /** One line for the operator, naming the switch. */
68735
+ message: string()
68736
+ })]);
68737
+ var PowerSourceInfoSchema = object({
68738
+ /** False when the device has no power source linked; the rest is then empty. */
68739
+ linked: boolean(),
68740
+ switchDeviceId: number().nullable(),
68741
+ switchName: string().nullable(),
68742
+ /** The switch's on/off state, or null when it is unknown. Never false for unknown (D393). */
68743
+ switchOn: boolean().nullable(),
68744
+ switchOnline: boolean().nullable(),
68745
+ restartInProgress: boolean(),
68746
+ offSeconds: number().int()
68747
+ });
68748
+ object({
68749
+ /** Null while the switch has not reported: unknown is never `false` (D393). */
68750
+ switchOn: boolean().nullable(),
68751
+ offSeconds: number().int(),
68752
+ lastFetchedAt: number()
68753
+ });
68754
+ DeviceType.Gateway, DeviceType.Hub, DeviceType.Camera, DeviceType.Sensor, DeviceType.MediaPlayer, DeviceType.Vacuum, DeviceType.Generic, DeviceType.Washer, DeviceType.Dryer, DeviceType.Dishwasher, DeviceType.PetFountain, DeviceType.Fan, DeviceType.Humidifier, DeviceType.Climate, DeviceType.WaterHeater;
68755
+ var deviceInput$1 = object({ deviceId: number().int().nonnegative() });
68756
+ systemMethod(deviceInput$1, PowerSourceInfoSchema, { auth: "admin" }), systemMethod(deviceInput$1, PowerSourceActionResultSchema, {
68757
+ kind: "mutation",
68758
+ auth: "admin"
68759
+ }), systemMethod(deviceInput$1, PowerSourceActionResultSchema, {
68760
+ kind: "mutation",
68761
+ auth: "admin"
68762
+ }), systemMethod(deviceInput$1, PowerSourceActionResultSchema, {
68763
+ kind: "mutation",
68764
+ auth: "admin"
68765
+ });
67743
68766
  /**
67744
68767
  * Presence cap. Models HA `person.*` and `device_tracker.*` entities
67745
68768
  * on `DeviceType.Presence`. Read-only — no setters: presence is
@@ -76007,6 +77030,25 @@ function buildDescriptor(capName, kind) {
76007
77030
  * contributes one entry per bound cap present in this map.
76008
77031
  */
76009
77032
  var EVENT_KIND_BY_CAP = Object.freeze(Object.fromEntries(Object.entries(CAP_TO_KIND).map(([capName, kind]) => [capName, buildDescriptor(capName, kind)])));
77033
+ /**
77034
+ * What a remote key is CALLED and what it LOOKS like, for every role (D963),
77035
+ * shared by the admin UI and the viewer. A role is data on the wire; each
77036
+ * client resolves its name from `label` (English and Italian side by side) and
77037
+ * its glyph from `icon`, a lucide id from the shared icon catalogue — the
77038
+ * server sends an id, a client maps it to its own icon set.
77039
+ *
77040
+ * `legend` is text printed on the key INSTEAD of a glyph (a digit has no
77041
+ * pictogram): a client that can draw text shows it, one that cannot falls back
77042
+ * to `icon`.
77043
+ */
77044
+ function digit(n) {
77045
+ return {
77046
+ label: t(n, n),
77047
+ icon: "hash",
77048
+ legend: n
77049
+ };
77050
+ }
77051
+ digit("0"), digit("1"), digit("2"), digit("3"), digit("4"), digit("5"), digit("6"), digit("7"), digit("8"), digit("9");
76010
77052
  DeviceFeature.MediaPlayerPower, DeviceFeature.MediaPlayerVolumeStep, DeviceFeature.MediaPlayerChannelStep, DeviceFeature.MediaPlayerMute, DeviceFeature.MediaPlayerStop, DeviceFeature.MediaPlayerNext, DeviceFeature.MediaPlayerPrevious;
76011
77053
  var btn = (idSuffix, row, col, init) => ({
76012
77054
  idSuffix,
@@ -76134,6 +77176,34 @@ discriminatedUnion("kind", [object({
76134
77176
  kind: literal("pronto"),
76135
77177
  code: string()
76136
77178
  })]);
77179
+ /**
77180
+ * Propose a running threshold from a device's own power history (planning#405).
77181
+ *
77182
+ * Pure and deterministic: the same series gives the same answer. The series is
77183
+ * a HELD-VALUE step series — a point's value stands until the next point — which
77184
+ * is how device-history stores a gauge, so "time at a level" is exact, not a
77185
+ * count of samples.
77186
+ *
77187
+ * 1. idle floor F = time-weighted median; noise ceiling N = highest value seen
77188
+ * near F. A device that is not near one level most of the time has no floor.
77189
+ * 2. coarse activity = above max(2N, N + 5 W); consecutive stretches are episodes.
77190
+ * 3. gaps between episodes split in two by the largest log-scale jump (>= 3x):
77191
+ * the short ones are pauses INSIDE a run (a soak), the long ones separate runs.
77192
+ * 4. T = geometric mean of N and the plateau's 10th percentile, snapped to a
77193
+ * grid a person would type; stop dwell covers the longest pause; start dwell
77194
+ * covers the longest standby blip above T.
77195
+ * 5. the numbers are proved by REPLAY through the real `dwell` evaluation: each
77196
+ * run must hold exactly one true interval and nothing may flap outside.
77197
+ */
77198
+ var SECOND_MS = 1e3;
77199
+ var MINUTE_MS$1 = 60 * SECOND_MS;
77200
+ 24 * (60 * MINUTE_MS$1);
77201
+ 10 * MINUTE_MS$1;
77202
+ 30 * SECOND_MS;
77203
+ 60 * SECOND_MS;
77204
+ 20 * MINUTE_MS$1;
77205
+ 10 * SECOND_MS;
77206
+ 10 * SECOND_MS;
76137
77207
  DeviceFeature.FanSpeed, DeviceFeature.FanPreset, DeviceFeature.FanDirection, DeviceFeature.FanOscillating, DeviceFeature.CoverStoppable, DeviceFeature.CoverPositionable, DeviceFeature.CoverTilt, DeviceFeature.ValvePositionable, DeviceFeature.MediaPlayerVolume, DeviceFeature.ClimateFanMode;
76138
77208
  SOURCE_CAPS.filter((cap) => cap !== "switch" && cap !== "motion");
76139
77209
  String.raw`rose\(active(\d+), changed(\d+), (\d+(?:\.\d+)?)\)`;
@@ -77675,6 +78745,13 @@ Object.freeze({
77675
78745
  access: "create",
77676
78746
  role: "admin"
77677
78747
  },
78748
+ "coreBlocks.proposeRunningThreshold": {
78749
+ capName: "core-blocks",
78750
+ capScope: "system",
78751
+ addonId: null,
78752
+ access: "view",
78753
+ role: "admin"
78754
+ },
77678
78755
  "coreBlocks.reportAutomationRun": {
77679
78756
  capName: "core-blocks",
77680
78757
  capScope: "system",
@@ -78186,6 +79263,13 @@ Object.freeze({
78186
79263
  access: "view",
78187
79264
  role: "admin"
78188
79265
  },
79266
+ "deviceExport.listInstances": {
79267
+ capName: "device-export",
79268
+ capScope: "system",
79269
+ addonId: null,
79270
+ access: "view",
79271
+ role: "admin"
79272
+ },
78189
79273
  "deviceExport.listSupportedDeviceKinds": {
78190
79274
  capName: "device-export",
78191
79275
  capScope: "system",
@@ -87158,6 +88242,11 @@ Object.freeze({
87158
88242
  form: "single",
87159
88243
  optional: false
87160
88244
  }],
88245
+ "coreBlocks.proposeRunningThreshold": [{
88246
+ name: "deviceId",
88247
+ form: "single",
88248
+ optional: false
88249
+ }],
87161
88250
  "cover.close": [{
87162
88251
  name: "deviceId",
87163
88252
  form: "single",
@@ -89821,99 +90910,6 @@ Object.freeze({
89821
90910
  "network-access": "ingress",
89822
90911
  "smtp-provider": "email"
89823
90912
  });
89824
- /**
89825
- * A saved Customize assignment (D936). The schema is the type: callers use
89826
- * `z.infer`, they do not restate the shape.
89827
- */
89828
- var OverrideSourceSchema = object({
89829
- addonId: string().min(1),
89830
- stableId: string().min(1),
89831
- cap: string().min(1),
89832
- fieldPath: string().min(1)
89833
- });
89834
- var CustomizeTransformDraftSchema = discriminatedUnion("kind", [
89835
- object({ kind: literal("identity") }),
89836
- object({ kind: literal("invert") }),
89837
- object({
89838
- kind: literal("threshold"),
89839
- comparison: _enum(["gte", "lte"]),
89840
- threshold: number(),
89841
- startDwellMs: number().nonnegative(),
89842
- stopDwellMs: number().nonnegative()
89843
- }),
89844
- object({
89845
- kind: literal("linear"),
89846
- scale: number(),
89847
- offset: number(),
89848
- clampMin: number().optional(),
89849
- clampMax: number().optional()
89850
- }),
89851
- object({
89852
- kind: literal("enum-map"),
89853
- mapping: record(string(), string().nullable())
89854
- }),
89855
- object({ kind: literal("number") })
89856
- ]);
89857
- var ScalarOverrideDraftSchema = object({
89858
- kind: literal("scalar"),
89859
- cap: string().min(1),
89860
- targetId: string().min(1),
89861
- source: OverrideSourceSchema,
89862
- transform: CustomizeTransformDraftSchema
89863
- });
89864
- var KeyedArrayOverrideDraftSchema = object({
89865
- kind: literal("keyedArray"),
89866
- cap: string().min(1),
89867
- targetId: string().min(1),
89868
- key: string().min(1),
89869
- label: string().min(1),
89870
- fieldPath: string().min(1),
89871
- source: OverrideSourceSchema,
89872
- transform: CustomizeTransformDraftSchema
89873
- });
89874
- var PulseOverrideDraftSchema = object({
89875
- kind: literal("pulse"),
89876
- cap: string().min(1),
89877
- targetId: string().min(1),
89878
- enabled: boolean(),
89879
- debounceMs: number().nonnegative(),
89880
- edges: array(_enum([
89881
- "rising",
89882
- "button",
89883
- "native-event"
89884
- ])).min(1).optional(),
89885
- sources: array(OverrideSourceSchema).min(1)
89886
- });
89887
- var SpanSourceDraftSchema = OverrideSourceSchema.extend({ mode: _enum([
89888
- "in-addition",
89889
- "confirm",
89890
- "replace"
89891
- ]).optional() });
89892
- discriminatedUnion("kind", [
89893
- ScalarOverrideDraftSchema,
89894
- KeyedArrayOverrideDraftSchema,
89895
- PulseOverrideDraftSchema,
89896
- object({
89897
- kind: literal("span"),
89898
- cap: string().min(1),
89899
- targetId: string().min(1),
89900
- timeoutMs: number().nonnegative(),
89901
- cooldownMs: number().nonnegative().optional(),
89902
- sources: array(SpanSourceDraftSchema)
89903
- })
89904
- ]);
89905
- object({
89906
- targetId: string().min(1),
89907
- configured: boolean(),
89908
- source: _enum(["native", "assigned"]),
89909
- state: _enum([
89910
- "active",
89911
- "stale",
89912
- "released",
89913
- "unavailable"
89914
- ]),
89915
- reason: string().nullable()
89916
- });
89917
90913
  var G711_SCALE_CORRECTION_DB = {
89918
90914
  PCMU: 20 * Math.log10(4),
89919
90915
  PCMA: 20 * Math.log10(8)
@@ -138468,6 +139464,133 @@ function carryForward(base, existing, keys) {
138468
139464
  return out;
138469
139465
  }
138470
139466
  //#endregion
139467
+ //#region src/hap-export-records.ts
139468
+ /**
139469
+ * What one HomeKit bridge exposes (D985, D996): a `hap-bridge-exports` row per bridge instance,
139470
+ * under the instance's own id, holds the devices it mirrors (with their per-device export
139471
+ * settings) and the actions it publishes as momentary switches. The identity a controller pairs
139472
+ * with is the sibling `hap-bridges` row; this row is what that bridge CARRIES.
139473
+ *
139474
+ * It replaces the `exposed` and `exposedActions` addon settings. The migration moved them; the
139475
+ * addon reads this record and nothing else.
139476
+ */
139477
+ var ExportDeviceSettingsSchema = object({
139478
+ multiTierService: boolean().optional(),
139479
+ streamPreference: string(),
139480
+ useBridge: boolean().optional(),
139481
+ allowTranscode: boolean().optional(),
139482
+ keepClips: boolean().optional(),
139483
+ clipRetentionDays: number().optional()
139484
+ });
139485
+ var MapperKindSchema = _enum(["camera", "generic"]);
139486
+ var ExposedConfigEntrySchema = object({
139487
+ deviceId: string(),
139488
+ displayName: string(),
139489
+ mapperKind: MapperKindSchema,
139490
+ capabilities: array(string()).optional(),
139491
+ childAccessoryUuids: array(string()).optional(),
139492
+ addedAt: number().optional(),
139493
+ settings: ExportDeviceSettingsSchema.optional()
139494
+ });
139495
+ var ActionExportEntrySchema = object({
139496
+ actionId: string(),
139497
+ displayName: string(),
139498
+ addedAt: number()
139499
+ });
139500
+ var HapBridgeExportsBodySchema = object({
139501
+ name: string().min(1),
139502
+ devices: array(ExposedConfigEntrySchema),
139503
+ actions: array(ActionExportEntrySchema)
139504
+ });
139505
+ /** The label of every exposure record: it is the instance's, not an operator's name. */
139506
+ var HAP_EXPOSURE_NAME = "HomeKit exposure";
139507
+ var hapBridgeExportsKind = defineEntryKind("hap-bridge-exports", {
139508
+ title: "HomeKit exposure",
139509
+ nameField: "name",
139510
+ schema: HapBridgeExportsBodySchema,
139511
+ writeTrigger: "an operator exposes or unexposes a device or action to HomeKit"
139512
+ });
139513
+ /** The settings keys that moved into the record; the migrations name them. */
139514
+ var MOVED_EXPOSURE_KEYS = ["exposed", "exposedActions"];
139515
+ //#endregion
139516
+ //#region src/hap-instance-kinds.ts
139517
+ /**
139518
+ * The HomeKit export's instances as records (D985, D996): one `hap-bridges` row per bridge
139519
+ * identity, owned by `export-hap`. A row IS what a paired controller knows the bridge by: the
139520
+ * MAC-style `username`, the bridge `uuid` and the setup code (`pincode`, a keychain marker bound to
139521
+ * the row). The directory its pairing state lives in is derived from the id, never stored
139522
+ * (`hapPersistDirOf`). The default instance is keyed by the
139523
+ * addon id and ADOPTS the identity the addon held in its settings, byte for byte, so a
139524
+ * controller that paired before keeps working.
139525
+ */
139526
+ /** The default instance keeps its record under the addon id (it adopted the old identity). */
139527
+ var HAP_DEFAULT_INSTANCE_ID = "export-hap";
139528
+ /** Where the pairing state of the default instance has always lived, under the addon data dir. */
139529
+ var HAP_DEFAULT_PERSIST_DIR = "hap-store";
139530
+ /** The pairing-state directory of an instance, relative to the addon data dir: derived, not stored. */
139531
+ function hapPersistDirOf(instanceId) {
139532
+ return instanceId === "export-hap" ? HAP_DEFAULT_PERSIST_DIR : `hap-store-${instanceId}`;
139533
+ }
139534
+ var hapBridgesKind = defineEntryKind("hap-bridges", {
139535
+ title: "HomeKit bridge",
139536
+ nameField: "name",
139537
+ schema: object({
139538
+ name: string().min(1),
139539
+ username: string().min(1),
139540
+ uuid: string().min(1),
139541
+ pincode: string().min(1).meta({ secret: true }),
139542
+ enabled: boolean().optional()
139543
+ })
139544
+ });
139545
+ function identityOfBody(body) {
139546
+ return {
139547
+ username: body.username,
139548
+ uuid: body.uuid,
139549
+ pincode: body.pincode
139550
+ };
139551
+ }
139552
+ //#endregion
139553
+ //#region src/hap-identity.ts
139554
+ /**
139555
+ * Which HomeKit bridge identity the addon boots with: the default instance record, and nothing
139556
+ * else. There is no fallback to the settings the identity once lived in; the migration moved it.
139557
+ * A fresh identity is minted only when no record exists AND no legacy identity is still stored.
139558
+ * A legacy identity without a record means the migration did not finish, and minting then would
139559
+ * unpair every controller, so the addon refuses to boot with the reason.
139560
+ */
139561
+ /** An operator-supplied `fixedPin` overrides the pincode, never the username/uuid. */
139562
+ async function resolveBridgeIdentity(fixedPin, ports) {
139563
+ const stored = await ports.readRecord();
139564
+ if (stored.kind === "unavailable") throw new Error("export-hap: the bridge identity exists but the keychain cannot serve it");
139565
+ if (stored.kind === "resolved") {
139566
+ if (fixedPin !== null && fixedPin !== stored.body.pincode) {
139567
+ await ports.patchPincode(fixedPin);
139568
+ return {
139569
+ identity: identityOfBody({
139570
+ ...stored.body,
139571
+ pincode: fixedPin
139572
+ }),
139573
+ minted: false
139574
+ };
139575
+ }
139576
+ return {
139577
+ identity: identityOfBody(stored.body),
139578
+ minted: false
139579
+ };
139580
+ }
139581
+ 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");
139582
+ const fresh = ports.mint();
139583
+ const body = fixedPin === null ? fresh : {
139584
+ ...fresh,
139585
+ pincode: fixedPin
139586
+ };
139587
+ await ports.putFresh(body);
139588
+ return {
139589
+ identity: identityOfBody(body),
139590
+ minted: true
139591
+ };
139592
+ }
139593
+ //#endregion
138471
139594
  //#region src/migrations/hub-node-fields.ts
138472
139595
  /**
138473
139596
  * Fields stored once for the cluster that are facts of ONE node become node settings (D986): a
@@ -138538,40 +139661,248 @@ async function moveFixedPinToKeychain(ports) {
138538
139661
  };
138539
139662
  }
138540
139663
  //#endregion
139664
+ //#region src/migrations/exposure-to-record.ts
139665
+ /**
139666
+ * The exposure lists the addon kept in its settings (`exposed`: the devices it mirrors, with
139667
+ * their per-device settings; `exposedActions`: the actions it publishes) move into the
139668
+ * `hap-bridge-exports` record of the default instance (D985, D996). Two migrations, in order:
139669
+ *
139670
+ * 1. `moveExposureToRecord` (procedure): put the record with `ifRev: 0`, read it BACK and
139671
+ * compare it with what the settings carried; a record that does not hold the same lists
139672
+ * throws and the settings are kept. An existing record is never overwritten.
139673
+ * 2. `planDropExposureKeys` (plan): the two keys are deleted from the canonical `addon-settings`
139674
+ * rows, and only while the record holds exactly what they carry. A record that differs (the
139675
+ * operator edited the lists since) keeps the old keys, which nothing reads any more.
139676
+ *
139677
+ * An entry the schema does not know (a mapper kind the addon no longer serves) is dropped on the
139678
+ * way, which is what the boot sweep did to it anyway.
139679
+ */
139680
+ /** Key-order-independent JSON, so "identical" does not depend on how a store orders keys. */
139681
+ function canonical(value) {
139682
+ if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
139683
+ 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(",")}}`;
139684
+ return JSON.stringify(value) ?? "null";
139685
+ }
139686
+ function parsedList(value, parse) {
139687
+ if (!Array.isArray(value)) return [];
139688
+ const kept = [];
139689
+ for (const entry of value) {
139690
+ const parsed = parse(entry);
139691
+ if (parsed.success) kept.push(parsed.data);
139692
+ }
139693
+ return kept;
139694
+ }
139695
+ /** The record body the legacy settings describe. */
139696
+ function exposureBodyFrom(stored) {
139697
+ return {
139698
+ name: HAP_EXPOSURE_NAME,
139699
+ devices: parsedList(stored["exposed"], (e) => ExposedConfigEntrySchema.safeParse(e)),
139700
+ actions: parsedList(stored["exposedActions"], (e) => ActionExportEntrySchema.safeParse(e))
139701
+ };
139702
+ }
139703
+ function sameLists(a, b) {
139704
+ return canonical(a.devices) === canonical(b.devices) && canonical(a.actions) === canonical(b.actions);
139705
+ }
139706
+ async function moveExposureToRecord(ports) {
139707
+ const stored = await ports.readStored(MOVED_EXPOSURE_KEYS);
139708
+ if (!MOVED_EXPOSURE_KEYS.some((key) => key in stored)) return {
139709
+ outcome: "already-done",
139710
+ summary: { moved: false }
139711
+ };
139712
+ const body = exposureBodyFrom(stored);
139713
+ const put = await ports.putExposure(body);
139714
+ const held = await ports.readExposure();
139715
+ if (held === null) throw new Error("the HomeKit exposure record cannot be read back");
139716
+ if (put === "created" && !sameLists(held, body)) throw new Error("the HomeKit exposure record does not hold the lists it adopted");
139717
+ return put === "created" ? {
139718
+ outcome: "done",
139719
+ summary: {
139720
+ moved: true,
139721
+ devices: body.devices.length
139722
+ }
139723
+ } : {
139724
+ outcome: "already-done",
139725
+ summary: { moved: false }
139726
+ };
139727
+ }
139728
+ var rowId = (key) => `${HAP_DEFAULT_INSTANCE_ID}.${key}`;
139729
+ async function planDropExposureKeys(ports) {
139730
+ const stored = await ports.readStored(MOVED_EXPOSURE_KEYS);
139731
+ const present = MOVED_EXPOSURE_KEYS.filter((key) => key in stored);
139732
+ if (present.length === 0) return { edits: [] };
139733
+ const held = await ports.readExposure();
139734
+ if (held === null || !sameLists(held, exposureBodyFrom(stored))) return { edits: [] };
139735
+ return { edits: [{
139736
+ op: "deleteKeys",
139737
+ scope: ADDON_SETTINGS_TABLE,
139738
+ keys: present.map(rowId),
139739
+ precondition: preconditionOf(Object.fromEntries(present.map((key) => [rowId(key), {
139740
+ addonId: HAP_DEFAULT_INSTANCE_ID,
139741
+ key,
139742
+ value: stored[key]
139743
+ }])))
139744
+ }] };
139745
+ }
139746
+ //#endregion
139747
+ //#region src/migrations/identity-to-instance.ts
139748
+ /**
139749
+ * The bridge identity the addon kept in its settings (`identity`: username, uuid, pincode) moves
139750
+ * into the default instance record (D985, D996). Paired controllers know the bridge by exactly
139751
+ * these values, so the record is created with them UNCHANGED and the pass proves it by reading the
139752
+ * record back and comparing, field by field, before it reports `done`.
139753
+ *
139754
+ * Only once the read-back matches is the old `identity` cleared (its keychain entry released with
139755
+ * it), in this same pass: one path, no copy. An existing record is never overwritten; when it is
139756
+ * already there and names the same bridge (username, uuid) the leftover old identity of an
139757
+ * interrupted pass is cleared, and when it names another bridge the pass fails rather than guess.
139758
+ * An incomplete or unreadable legacy identity is `already-done` or throws, and never mints a new
139759
+ * one (a new identity unpairs every controller).
139760
+ */
139761
+ async function moveIdentityToDefaultInstance(ports) {
139762
+ const legacy = await ports.readLegacyIdentity();
139763
+ if (legacy === null) return {
139764
+ outcome: "already-done",
139765
+ summary: { moved: false }
139766
+ };
139767
+ const name = (await ports.readBridgeName()).trim();
139768
+ const body = {
139769
+ name: name.length > 0 ? name : "CamStack Bridge",
139770
+ username: legacy.username,
139771
+ uuid: legacy.uuid,
139772
+ pincode: legacy.pincode
139773
+ };
139774
+ const put = await ports.putDefaultRecord(body);
139775
+ const held = await ports.readDefaultRecord();
139776
+ if (held === null) throw new Error("the HomeKit default instance record cannot be read back");
139777
+ if (put === "exists") {
139778
+ if (held.username !== body.username || held.uuid !== body.uuid) throw new Error("the HomeKit default instance is another bridge than the stored identity");
139779
+ await ports.clearLegacyIdentity();
139780
+ return {
139781
+ outcome: "done",
139782
+ summary: {
139783
+ moved: false,
139784
+ cleared: true
139785
+ }
139786
+ };
139787
+ }
139788
+ if (!sameIdentity(identityOfBody(held), identityOfBody(body))) throw new Error("the HomeKit default instance does not hold the identity it adopted");
139789
+ await ports.clearLegacyIdentity();
139790
+ return {
139791
+ outcome: "done",
139792
+ summary: { moved: true }
139793
+ };
139794
+ }
139795
+ function sameIdentity(a, b) {
139796
+ return a.username === b.username && a.uuid === b.uuid && a.pincode === b.pincode;
139797
+ }
139798
+ /**
139799
+ * The identity a settings value describes, secrets resolved; null when it is not a complete
139800
+ * identity (first boot, or the empty sentinel). A pincode still a keychain marker was not
139801
+ * resolved: that throws, because treating "unreadable" as "absent" would mint a new identity.
139802
+ */
139803
+ function legacyIdentityOf(value) {
139804
+ if (typeof value !== "object" || value === null) return null;
139805
+ const username = Reflect.get(value, "username");
139806
+ const uuid = Reflect.get(value, "uuid");
139807
+ const pincode = Reflect.get(value, "pincode");
139808
+ if (isSecretMarker(pincode)) throw new Error("the stored HomeKit setup code cannot be resolved");
139809
+ if (typeof username !== "string" || typeof uuid !== "string" || typeof pincode !== "string" || username === "" || uuid === "" || pincode === "") return null;
139810
+ return {
139811
+ username,
139812
+ uuid,
139813
+ pincode
139814
+ };
139815
+ }
139816
+ //#endregion
138541
139817
  //#region src/migrations/index.ts
138542
139818
  var EXPORT_HAP_ID = "export-hap";
139819
+ var INTERFACE_NAME_PER_NODE_ID = "export-hap/2026-11-03-interface-name-per-node";
139820
+ var FIXED_PIN_TO_KEYCHAIN_ID = "export-hap/2026-11-03-fixed-pin-to-keychain";
139821
+ var IDENTITY_TO_INSTANCE_ID = "export-hap/2026-11-04-identity-to-default-instance";
139822
+ var EXPOSURE_TO_RECORD_ID = "export-hap/2026-11-04-exposure-to-record";
138543
139823
  /** The `export-hap` catalogue (D987): offered to the engine when the addon initialises. */
138544
- var ADDON_MIGRATIONS = [{
138545
- meta: {
138546
- id: "export-hap/2026-11-03-interface-name-per-node",
138547
- owner: EXPORT_HAP_ID,
138548
- level: "addon-state",
138549
- seq: 1,
138550
- dependsOn: [],
138551
- store: "settings",
138552
- scope: "per-node",
138553
- onFailure: "tolerate",
138554
- bodyKind: "plan",
138555
- description: "Copy the bare network interface setting to its hub node row; the bare row stays for a release",
138556
- fixtureMark: "the bridge name the migration does not know"
138557
- },
138558
- plan: (ports) => planHubNodeFields(EXPORT_HAP_ID, ["interfaceName"], ports)
138559
- }, {
138560
- meta: {
138561
- id: "export-hap/2026-11-03-fixed-pin-to-keychain",
138562
- owner: EXPORT_HAP_ID,
138563
- level: "addon-state",
138564
- seq: 2,
138565
- dependsOn: [],
138566
- store: "settings",
138567
- scope: "cluster",
138568
- onFailure: "tolerate",
138569
- bodyKind: "procedure",
138570
- description: "Move the fixed setup code from an inline setting into the keychain, where a password field keeps it",
138571
- fixtureMark: "the bridge name the migration does not know"
138572
- },
138573
- procedure: moveFixedPinToKeychain
138574
- }];
139824
+ var ADDON_MIGRATIONS = [
139825
+ {
139826
+ meta: {
139827
+ id: INTERFACE_NAME_PER_NODE_ID,
139828
+ owner: EXPORT_HAP_ID,
139829
+ level: "addon-state",
139830
+ seq: 1,
139831
+ dependsOn: [],
139832
+ store: "settings",
139833
+ scope: "per-node",
139834
+ onFailure: "tolerate",
139835
+ bodyKind: "plan",
139836
+ description: "Copy the bare network interface setting to its hub node row; the bare row stays for a release",
139837
+ fixtureMark: "the bridge name the migration does not know"
139838
+ },
139839
+ plan: (ports) => planHubNodeFields(EXPORT_HAP_ID, ["interfaceName"], ports)
139840
+ },
139841
+ {
139842
+ meta: {
139843
+ id: FIXED_PIN_TO_KEYCHAIN_ID,
139844
+ owner: EXPORT_HAP_ID,
139845
+ level: "addon-state",
139846
+ seq: 2,
139847
+ dependsOn: [],
139848
+ store: "settings",
139849
+ scope: "cluster",
139850
+ onFailure: "tolerate",
139851
+ bodyKind: "procedure",
139852
+ description: "Move the fixed setup code from an inline setting into the keychain, where a password field keeps it",
139853
+ fixtureMark: "the bridge name the migration does not know"
139854
+ },
139855
+ procedure: moveFixedPinToKeychain
139856
+ },
139857
+ {
139858
+ meta: {
139859
+ id: IDENTITY_TO_INSTANCE_ID,
139860
+ owner: EXPORT_HAP_ID,
139861
+ level: "addon-state",
139862
+ seq: 3,
139863
+ dependsOn: [],
139864
+ store: "settings",
139865
+ scope: "cluster",
139866
+ onFailure: "block-owner",
139867
+ bodyKind: "procedure",
139868
+ 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",
139869
+ fixtureMark: "the bridge name the migration does not know"
139870
+ },
139871
+ procedure: moveIdentityToDefaultInstance
139872
+ },
139873
+ {
139874
+ meta: {
139875
+ id: EXPOSURE_TO_RECORD_ID,
139876
+ owner: EXPORT_HAP_ID,
139877
+ level: "addon-state",
139878
+ seq: 4,
139879
+ dependsOn: [IDENTITY_TO_INSTANCE_ID],
139880
+ store: "settings",
139881
+ scope: "cluster",
139882
+ onFailure: "block-owner",
139883
+ bodyKind: "procedure",
139884
+ description: "Move the exposed devices and actions into the default bridge exposure record, verified by read-back",
139885
+ fixtureMark: "the bridge name the migration does not know"
139886
+ },
139887
+ procedure: moveExposureToRecord
139888
+ },
139889
+ {
139890
+ meta: {
139891
+ id: "export-hap/2026-11-04-drop-exposure-keys",
139892
+ owner: EXPORT_HAP_ID,
139893
+ level: "addon-state",
139894
+ seq: 5,
139895
+ dependsOn: [EXPOSURE_TO_RECORD_ID],
139896
+ store: "settings",
139897
+ scope: "cluster",
139898
+ onFailure: "tolerate",
139899
+ bodyKind: "plan",
139900
+ description: "Delete the old exposed and exposedActions settings once the record holds exactly what they carried",
139901
+ fixtureMark: "the bridge name the migration does not know"
139902
+ },
139903
+ plan: planDropExposureKeys
139904
+ }
139905
+ ];
138575
139906
  //#endregion
138576
139907
  //#region src/hap-setup-uri.ts
138577
139908
  function errMsg$15(e) {
@@ -157774,9 +159105,8 @@ function syncStateToJson(map) {
157774
159105
  * Operator flow:
157775
159106
  * 1. Install + enable the addon (hub-only, group `export-hap`).
157776
159107
  * 2. On first boot the addon generates a random pincode + bridge
157777
- * MAC username and persists them on `this.config.identity` via
157778
- * `updateGlobalSettings` (no JSON sidecar files — the kernel
157779
- * addon-store IS the cache).
159108
+ * MAC username and persists them in the default instance record
159109
+ * (`hap-bridges`, no JSON sidecar files).
157780
159110
  * 3. The setup URI (`X-HM://…`) is logged AND surfaced via the
157781
159111
  * `getStatus` cap method so the wizard UI can render the QR.
157782
159112
  * 4. Operator opens iOS Home → + → scan QR → enter pincode.
@@ -157914,13 +159244,6 @@ var DEFAULT_CONFIG = {
157914
159244
  fixedPin: "",
157915
159245
  interfaceName: "",
157916
159246
  clipRetentionDays: 14,
157917
- identity: {
157918
- username: "",
157919
- pincode: "",
157920
- uuid: ""
157921
- },
157922
- exposed: [],
157923
- exposedActions: [],
157924
159247
  exportSyncState: {}
157925
159248
  };
157926
159249
  var BANNED_PINCODES = new Set([
@@ -157959,12 +159282,27 @@ function buildBridgeUuid(bridgeName) {
157959
159282
  return import_dist.uuid.generate(`camstack:bridge:${bridgeName}:${Date.now()}`);
157960
159283
  }
157961
159284
  var ExportHapAddon = class extends BaseAddon {
157962
- /** The bridge setup code pairs a controller: a credential, kept in the keychain (D787). */
159285
+ /**
159286
+ * The old `identity.pincode` secret: declared only so the identity migration can release its
159287
+ * keychain entry when it clears the old setting. The identity itself is a record now.
159288
+ */
157963
159289
  secretStatePaths = ["identity.pincode"];
157964
159290
  exposed = /* @__PURE__ */ new Map();
157965
159291
  /** The exported actions — switches beside the devices (D968). */
157966
159292
  actionExports = null;
157967
159293
  lastError;
159294
+ /** The HomeKit instances (D985): one record per bridge identity. */
159295
+ instances = null;
159296
+ /**
159297
+ * What the bridge exposes: the devices (with their per-device settings) and the actions, held in
159298
+ * the `hap-bridge-exports` record of the default instance. The in-memory copy is loaded once at
159299
+ * boot and written through on every change; this addon is the record's only writer.
159300
+ */
159301
+ exposure = {
159302
+ name: HAP_EXPOSURE_NAME,
159303
+ devices: [],
159304
+ actions: []
159305
+ };
157968
159306
  /** Shared HAP setup code applied to every published accessory. */
157969
159307
  pincode = "";
157970
159308
  /** Optional mDNS/bind interface (config.interfaceName), or undefined. */
@@ -158020,8 +159358,31 @@ var ExportHapAddon = class extends BaseAddon {
158020
159358
  super({ ...DEFAULT_CONFIG });
158021
159359
  }
158022
159360
  async onInitialize() {
159361
+ const records = this.ctx.records;
159362
+ if (records === void 0) throw new Error("export-hap needs ctx.records — check execution.placement (hub-only)");
159363
+ await records.declare({
159364
+ "hap-bridges": hapBridgesKind,
159365
+ "hap-bridge-exports": hapBridgeExportsKind
159366
+ });
159367
+ this.instances = new RecordIntegrationInstances(records, hapBridgesKind, {
159368
+ description: {
159369
+ role: "services",
159370
+ instanceMode: "single",
159371
+ kind: "bridge",
159372
+ canTest: false
159373
+ },
159374
+ formSchema: () => this.schema({ sections: [] }),
159375
+ initialBody: (name) => ({
159376
+ name,
159377
+ username: generateUsername(),
159378
+ uuid: buildBridgeUuid(name),
159379
+ pincode: generatePincode()
159380
+ }),
159381
+ configured: (body) => body.username !== "" && body.pincode !== ""
159382
+ });
158023
159383
  await this.migrateSettings();
158024
159384
  const identity = await this.ensureIdentity();
159385
+ await this.loadExposure();
158025
159386
  this.pincode = identity.pincode;
158026
159387
  this.bind = this.config.interfaceName || void 0;
158027
159388
  this.bridgeHost = new BridgeHost({
@@ -158032,7 +159393,7 @@ var ExportHapAddon = class extends BaseAddon {
158032
159393
  logger: this.ctx.logger
158033
159394
  });
158034
159395
  try {
158035
- await initHapStorage(path.join(this.ctx.dataDir, "hap-store"));
159396
+ await initHapStorage(path.join(this.ctx.dataDir, hapPersistDirOf(HAP_DEFAULT_INSTANCE_ID)));
158036
159397
  } catch (err) {
158037
159398
  this.lastError = errMsg(err);
158038
159399
  this.ctx.logger.error("export-hap: HAP storage init failed", { meta: { error: this.lastError } });
@@ -158058,12 +159419,12 @@ var ExportHapAddon = class extends BaseAddon {
158058
159419
  });
158059
159420
  await this.serveHksvClipPlanes();
158060
159421
  const validKinds = new Set(SUPPORTED_MAPPER_KINDS);
158061
- const cleaned = this.config.exposed.filter((entry) => {
159422
+ const cleaned = this.exposure.devices.filter((entry) => {
158062
159423
  if (validKinds.has(entry.mapperKind)) return true;
158063
159424
  this.ctx.logger.withTags({ deviceId: Number.parseInt(entry.deviceId, 10) }).info("export-hap: dropping stale exposed entry (unknown mapperKind)", { meta: { mapperKind: entry.mapperKind } });
158064
159425
  return false;
158065
159426
  });
158066
- if (cleaned.length !== this.config.exposed.length) await this.updateGlobalSettings({ exposed: cleaned });
159427
+ if (cleaned.length !== this.exposure.devices.length) await this.setExposedDevices(cleaned);
158067
159428
  for (const entry of cleaned) {
158068
159429
  const log = this.ctx.logger.withTags({ deviceId: Number.parseInt(entry.deviceId, 10) });
158069
159430
  try {
@@ -158096,8 +159457,8 @@ var ExportHapAddon = class extends BaseAddon {
158096
159457
  }
158097
159458
  await unpublishAccessory(accessory, this.ctx.logger);
158098
159459
  },
158099
- persist: (entries) => this.updateGlobalSettings({ exposedActions: [...entries] })
158100
- }, this.config.exposedActions ?? []);
159460
+ persist: (entries) => this.setExposedActions(entries)
159461
+ }, this.exposure.actions);
158101
159462
  await this.actionExports.attachAll();
158102
159463
  await this.actionExports.reconcile();
158103
159464
  this.ctx.addDisposer(async () => {
@@ -158109,8 +159470,10 @@ var ExportHapAddon = class extends BaseAddon {
158109
159470
  this.subscribeDeviceReadyForReconcile();
158110
159471
  this.subscribeStorageLocationsForClips();
158111
159472
  this.disposeSharedRebuildTimers();
159473
+ const ownInstance = (instanceId) => assertOwnExportInstance("export-hap", EXPORT_HAP_ADDON_ID, instanceId);
158112
159474
  const provider = {
158113
- getStatus: async () => {
159475
+ getStatus: async (input) => {
159476
+ ownInstance(statusInstanceOf(input));
158114
159477
  const anyPaired = Array.from(this.exposed.values()).some((m) => accessoryPaired(m.accessory));
158115
159478
  const linkState = this.lastError ? "error" : anyPaired ? "linked" : "unlinked";
158116
159479
  const setup = this.buildSetupBlock();
@@ -158121,19 +159484,38 @@ var ExportHapAddon = class extends BaseAddon {
158121
159484
  ...setup ? { setup } : {}
158122
159485
  };
158123
159486
  },
158124
- listSupportedDeviceKinds: async () => [...HAP_EXPORTABLE_DEVICE_TYPES],
158125
- listExposedDevices: async () => Array.from(this.exposed.entries()).map(([deviceId, m]) => {
158126
- const entry = this.config.exposed.find((e) => e.deviceId === deviceId);
158127
- return {
158128
- deviceId,
158129
- exposedAs: m.accessory.displayName,
158130
- ...entry?.capabilities ? { capabilities: [...entry.capabilities] } : {}
158131
- };
158132
- }),
158133
- exposeDevice: async ({ deviceId, capabilities }) => this.exposeDevice(deviceId, capabilities),
158134
- unexposeDevice: async ({ deviceId }) => this.unexposeDevice(deviceId),
159487
+ listInstances: async () => [{
159488
+ instanceId: EXPORT_HAP_ADDON_ID,
159489
+ name: "HomeKit",
159490
+ enabled: true,
159491
+ kind: "hap-bridge"
159492
+ }],
159493
+ listSupportedDeviceKinds: async ({ instanceId }) => {
159494
+ ownInstance(instanceId);
159495
+ return [...HAP_EXPORTABLE_DEVICE_TYPES];
159496
+ },
159497
+ listExposedDevices: async ({ instanceId }) => {
159498
+ ownInstance(instanceId);
159499
+ return Array.from(this.exposed.entries()).map(([deviceId, m]) => {
159500
+ const entry = this.exposure.devices.find((e) => e.deviceId === deviceId);
159501
+ return {
159502
+ deviceId,
159503
+ exposedAs: m.accessory.displayName,
159504
+ ...entry?.capabilities ? { capabilities: [...entry.capabilities] } : {}
159505
+ };
159506
+ });
159507
+ },
159508
+ exposeDevice: async ({ instanceId, deviceId, capabilities }) => {
159509
+ ownInstance(instanceId);
159510
+ return this.exposeDevice(deviceId, capabilities);
159511
+ },
159512
+ unexposeDevice: async ({ instanceId, deviceId }) => {
159513
+ ownInstance(instanceId);
159514
+ return this.unexposeDevice(deviceId);
159515
+ },
158135
159516
  listSupportedEntityKinds: async () => ["device", "action"],
158136
- listExposedEntities: async () => {
159517
+ listExposedEntities: async ({ instanceId }) => {
159518
+ ownInstance(instanceId);
158137
159519
  await this.actionExports?.reconcile();
158138
159520
  return [...Array.from(this.exposed.entries()).map(([deviceId, m]) => ({
158139
159521
  entity: {
@@ -158143,12 +159525,14 @@ var ExportHapAddon = class extends BaseAddon {
158143
159525
  exposedAs: m.accessory.displayName
158144
159526
  })), ...this.actionExports?.list() ?? []];
158145
159527
  },
158146
- exposeEntity: async ({ entity }) => {
159528
+ exposeEntity: async ({ instanceId, entity }) => {
159529
+ ownInstance(instanceId);
158147
159530
  if (entity.kind === "device") return this.exposeDevice(entity.deviceId);
158148
159531
  if (entity.kind === "action") return this.requireActionExports().expose(entity.actionId);
158149
159532
  throw new Error("export-hap: a notification target cannot be exported to HomeKit");
158150
159533
  },
158151
- unexposeEntity: async ({ entity }) => {
159534
+ unexposeEntity: async ({ instanceId, entity }) => {
159535
+ ownInstance(instanceId);
158152
159536
  if (entity.kind === "device") return this.unexposeDevice(entity.deviceId);
158153
159537
  if (entity.kind === "action") return this.requireActionExports().unexpose(entity.actionId);
158154
159538
  throw new Error("export-hap: a notification target cannot be exported to HomeKit");
@@ -158167,54 +159551,95 @@ var ExportHapAddon = class extends BaseAddon {
158167
159551
  thumbnailUrl: (deviceId, stem) => this.hksvClipUrl("thumb", deviceId, stem),
158168
159552
  clipFilePath: async (deviceId, stem) => await this.hksvClipStore?.artifactPath(deviceId, stem, "clip") ?? null
158169
159553
  });
158170
- return [{
158171
- capability: deviceExportCapability,
158172
- provider
158173
- }, {
158174
- capability: videoclipsCapability,
158175
- provider: clipsProvider
158176
- }];
159554
+ return [
159555
+ {
159556
+ capability: deviceExportCapability,
159557
+ provider
159558
+ },
159559
+ {
159560
+ capability: videoclipsCapability,
159561
+ provider: clipsProvider
159562
+ },
159563
+ {
159564
+ capability: integrationInstancesCapability,
159565
+ provider: this.requireInstances().toProvider()
159566
+ }
159567
+ ];
158177
159568
  }
158178
159569
  async onConfigChanged() {
158179
- if (this.config.fixedPin && isValidPincode(this.config.fixedPin) && this.config.identity.pincode !== this.config.fixedPin && this.config.identity.username !== "") {
158180
- const updated = {
158181
- username: this.config.identity.username,
158182
- uuid: this.config.identity.uuid,
158183
- pincode: this.config.fixedPin
158184
- };
158185
- await this.updateGlobalSettings({ identity: updated });
158186
- }
159570
+ const fixedPin = this.config.fixedPin;
159571
+ if (!fixedPin || !isValidPincode(fixedPin)) return;
159572
+ const handle = this.requireRecords().kind(hapBridgesKind);
159573
+ const row = await handle.getResolved(HAP_DEFAULT_INSTANCE_ID);
159574
+ if (row === null || row.data.pincode === fixedPin) return;
159575
+ await handle.patch(HAP_DEFAULT_INSTANCE_ID, { pincode: fixedPin });
159576
+ }
159577
+ requireInstances() {
159578
+ if (this.instances === null) throw new Error("export-hap: instances are not initialised");
159579
+ return this.instances;
159580
+ }
159581
+ requireRecords() {
159582
+ const records = this.ctx.records;
159583
+ if (records === void 0) throw new Error("export-hap: records are not available");
159584
+ return records;
159585
+ }
159586
+ /** The ports the identity migration reads and writes through. */
159587
+ identityMigrationPorts() {
159588
+ const handle = this.requireRecords().kind(hapBridgesKind);
159589
+ return {
159590
+ readLegacyIdentity: async () => legacyIdentityOf((await this.resolveGlobalStore())["identity"]),
159591
+ clearLegacyIdentity: () => this.updateGlobalSettingsAsOperator({ identity: null }),
159592
+ readBridgeName: async () => {
159593
+ const name = (await this.resolveGlobalStore())["bridgeName"];
159594
+ return typeof name === "string" ? name : "";
159595
+ },
159596
+ putDefaultRecord: async (body) => {
159597
+ if (await handle.get("export-hap") !== null) return "exists";
159598
+ try {
159599
+ await handle.put({
159600
+ id: HAP_DEFAULT_INSTANCE_ID,
159601
+ data: body
159602
+ }, { ifRev: 0 });
159603
+ } catch (err) {
159604
+ if (err instanceof RevConflictError) return "exists";
159605
+ throw err;
159606
+ }
159607
+ return "created";
159608
+ },
159609
+ readDefaultRecord: async () => (await handle.getResolved("export-hap"))?.data ?? null
159610
+ };
158187
159611
  }
158188
- /**
158189
- * Resolve the persistent bridge identity. Empty `username` is the
158190
- * "first boot" sentinel — generate fresh + persist. On subsequent
158191
- * boots the persisted record is reused. An operator-supplied
158192
- * `fixedPin` overrides the persisted pincode (useful for CI replay)
158193
- * but never the username/uuid (those drive the iOS pairing record).
158194
- */
159612
+ /** The identity of the default instance; see `resolveBridgeIdentity`. */
158195
159613
  async ensureIdentity() {
158196
- const current = this.config.identity;
158197
- const fixedPin = this.config.fixedPin && isValidPincode(this.config.fixedPin) ? this.config.fixedPin : null;
158198
- if (current.username !== "" && current.uuid !== "" && current.pincode !== "") {
158199
- if (fixedPin && fixedPin !== current.pincode) {
158200
- const updated = {
158201
- username: current.username,
158202
- uuid: current.uuid,
158203
- pincode: fixedPin
158204
- };
158205
- await this.updateGlobalSettings({ identity: updated });
158206
- return updated;
158207
- }
158208
- return current;
158209
- }
158210
- const fresh = {
158211
- username: generateUsername(),
158212
- pincode: fixedPin ?? generatePincode(),
158213
- uuid: buildBridgeUuid(this.config.bridgeName)
158214
- };
158215
- await this.updateGlobalSettings({ identity: fresh });
158216
- this.ctx.logger.info("export-hap: generated bridge identity on first boot", { meta: { username: fresh.username } });
158217
- return fresh;
159614
+ const handle = this.requireRecords().kind(hapBridgesKind);
159615
+ const { identity, minted } = await resolveBridgeIdentity(this.config.fixedPin && isValidPincode(this.config.fixedPin) ? this.config.fixedPin : null, {
159616
+ readRecord: async () => {
159617
+ const resolved = await this.requireInstances().readResolved(HAP_DEFAULT_INSTANCE_ID);
159618
+ if (resolved === null) return { kind: "absent" };
159619
+ return resolved.secrets === "resolved" ? {
159620
+ kind: "resolved",
159621
+ body: resolved.body
159622
+ } : { kind: "unavailable" };
159623
+ },
159624
+ legacyIdentityPresent: async () => legacyIdentityOf((await this.resolveGlobalStore())["identity"]) !== null,
159625
+ patchPincode: async (pincode) => {
159626
+ await handle.patch(HAP_DEFAULT_INSTANCE_ID, { pincode });
159627
+ },
159628
+ putFresh: async (body) => {
159629
+ await handle.put({
159630
+ id: HAP_DEFAULT_INSTANCE_ID,
159631
+ data: body
159632
+ }, { ifRev: 0 });
159633
+ },
159634
+ mint: () => ({
159635
+ name: this.config.bridgeName,
159636
+ username: generateUsername(),
159637
+ uuid: buildBridgeUuid(this.config.bridgeName),
159638
+ pincode: generatePincode()
159639
+ })
159640
+ });
159641
+ if (minted) this.ctx.logger.info("export-hap: generated bridge identity on first boot", { meta: { username: identity.username } });
159642
+ return identity;
158218
159643
  }
158219
159644
  /**
158220
159645
  * Build the generic `device-export` `setup` block surfaced via
@@ -158224,7 +159649,7 @@ var ExportHapAddon = class extends BaseAddon {
158224
159649
  * until the bridge has booted and produced both values.
158225
159650
  */
158226
159651
  buildSetupBlock() {
158227
- const setupCode = this.config.identity.pincode;
159652
+ const setupCode = this.pincode;
158228
159653
  if (!setupCode) return null;
158229
159654
  const qr = firstExposedAccessorySetupUri(this.exposed, this.ctx.logger);
158230
159655
  return {
@@ -158258,7 +159683,7 @@ var ExportHapAddon = class extends BaseAddon {
158258
159683
  const mapperKind = pickMapperKind(summary?.type);
158259
159684
  if (!mapperKind) throw new Error(`export-hap: device ${numericId} has type '${summary?.type ?? "unknown"}', which HomeKit export does not support`);
158260
159685
  const displayName = summary?.name ?? `Device ${deviceId}`;
158261
- const previous = this.config.exposed.find((e) => e.deviceId === deviceId);
159686
+ const previous = this.exposure.devices.find((e) => e.deviceId === deviceId);
158262
159687
  const rebuilt = {
158263
159688
  deviceId,
158264
159689
  displayName,
@@ -158275,9 +159700,9 @@ var ExportHapAddon = class extends BaseAddon {
158275
159700
  ...baseEntry,
158276
159701
  childAccessoryUuids: attached.childAccessoryUuids
158277
159702
  };
158278
- const next = this.config.exposed.filter((e) => e.deviceId !== deviceId);
159703
+ const next = this.exposure.devices.filter((e) => e.deviceId !== deviceId);
158279
159704
  next.push(finalEntry);
158280
- await this.updateGlobalSettings({ exposed: next });
159705
+ await this.setExposedDevices(next);
158281
159706
  if (Number.isFinite(numericId)) {
158282
159707
  const fp = await this.computeExportFingerprint(numericId);
158283
159708
  if (fp !== null) await this.persistFingerprint(numericId, fp);
@@ -158293,8 +159718,8 @@ var ExportHapAddon = class extends BaseAddon {
158293
159718
  const log = this.ctx.logger.withTags({ deviceId: numericId });
158294
159719
  const mapperKind = this.findEntry(numericId)?.mapperKind ?? "camera";
158295
159720
  await this.detachMapper(deviceId);
158296
- const next = this.config.exposed.filter((e) => e.deviceId !== deviceId);
158297
- if (next.length !== this.config.exposed.length) await this.updateGlobalSettings({ exposed: next });
159721
+ const next = this.exposure.devices.filter((e) => e.deviceId !== deviceId);
159722
+ if (next.length !== this.exposure.devices.length) await this.setExposedDevices(next);
158298
159723
  if (options.clearPairing !== false) clearPairingFiles(accessoryUuidFor(mapperKind, numericId), this.ctx.logger);
158299
159724
  await this.forgetFingerprint(numericId);
158300
159725
  this.hksvBuilds.forget(numericId);
@@ -158657,7 +160082,9 @@ var ExportHapAddon = class extends BaseAddon {
158657
160082
  async migrateSettings() {
158658
160083
  if ((await this.runMigrations(defineAddonMigrations(ADDON_MIGRATIONS, {
158659
160084
  readStored: (keys) => readRawKeys((key) => this.readStoredGlobalKey(key), "export-hap", keys),
158660
- storeFixedPin: (pin) => this.updateGlobalSettingsAsOperator({ fixedPin: pin })
160085
+ storeFixedPin: (pin) => this.updateGlobalSettingsAsOperator({ fixedPin: pin }),
160086
+ ...this.identityMigrationPorts(),
160087
+ ...this.exposureMigrationPorts()
158661
160088
  }))).applied.length > 0) await this.resolveConfig();
158662
160089
  }
158663
160090
  globalSettingsSchema() {
@@ -158715,7 +160142,7 @@ var ExportHapAddon = class extends BaseAddon {
158715
160142
  const bridged = mapper !== null && this.bridgeHost?.holds(mapper.accessory) === true;
158716
160143
  const name = entry?.displayName ?? `Device ${deviceId}`;
158717
160144
  const bridgePaired = this.bridgeHost?.accessory !== null && this.bridgeHost?.accessory !== void 0 ? accessoryPaired(this.bridgeHost.accessory) : false;
158718
- 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}.`;
160145
+ 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.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.pincode}.`;
158719
160146
  const qrSource = bridged ? this.bridgeHost?.accessory ?? null : mapper?.accessory ?? null;
158720
160147
  let qrValue = "";
158721
160148
  if (qrSource) try {
@@ -158842,7 +160269,7 @@ var ExportHapAddon = class extends BaseAddon {
158842
160269
  type: "qr-code",
158843
160270
  key: "__hap-pair-qr",
158844
160271
  label: paired ? "Pairing QR (already paired)" : "Pairing QR",
158845
- 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}.`,
160272
+ caption: paired ? `Already paired with at least one device. Scan from another iPhone / iPad to add it there too. Setup code: ${this.pincode}.` : `Scan with the iOS Camera app to pair this accessory in HomeKit. Setup code: ${this.pincode}.`,
158846
160273
  value: qrValue,
158847
160274
  size: 192,
158848
160275
  alt: `HomeKit pairing QR for ${name}`,
@@ -159006,16 +160433,72 @@ var ExportHapAddon = class extends BaseAddon {
159006
160433
  const planes = this.hksvClipPlanes;
159007
160434
  return `/addon/${EXPORT_HAP_ADDON_ID}/${kind === "media" ? planes?.mediaPrefix ?? "hksv-clip" : planes?.thumbPrefix ?? "hksv-clip-thumb"}/${String(deviceId)}/${stem}.${kind === "media" ? "mp4" : "jpg"}`;
159008
160435
  }
160436
+ /** The exposure record's handle: one row per bridge instance, under the instance id. */
160437
+ exposureHandle() {
160438
+ return this.requireRecords().kind(hapBridgeExportsKind);
160439
+ }
160440
+ /** Load the default instance's exposure record; create it empty when none exists. */
160441
+ async loadExposure() {
160442
+ const handle = this.exposureHandle();
160443
+ const row = await handle.get(HAP_DEFAULT_INSTANCE_ID);
160444
+ if (row !== null) {
160445
+ this.exposure = row.data;
160446
+ return;
160447
+ }
160448
+ await handle.put({
160449
+ id: HAP_DEFAULT_INSTANCE_ID,
160450
+ data: this.exposure
160451
+ }, { ifRev: 0 });
160452
+ }
160453
+ async writeExposure(next) {
160454
+ await this.exposureHandle().put({
160455
+ id: HAP_DEFAULT_INSTANCE_ID,
160456
+ data: next
160457
+ });
160458
+ this.exposure = next;
160459
+ }
160460
+ setExposedDevices(devices) {
160461
+ return this.writeExposure({
160462
+ ...this.exposure,
160463
+ devices
160464
+ });
160465
+ }
160466
+ setExposedActions(actions) {
160467
+ return this.writeExposure({
160468
+ ...this.exposure,
160469
+ actions
160470
+ });
160471
+ }
160472
+ /** The ports the exposure migration reads and writes through. */
160473
+ exposureMigrationPorts() {
160474
+ const handle = this.exposureHandle();
160475
+ return {
160476
+ putExposure: async (body) => {
160477
+ if (await handle.get("export-hap") !== null) return "exists";
160478
+ try {
160479
+ await handle.put({
160480
+ id: HAP_DEFAULT_INSTANCE_ID,
160481
+ data: body
160482
+ }, { ifRev: 0 });
160483
+ } catch (err) {
160484
+ if (err instanceof RevConflictError) return "exists";
160485
+ throw err;
160486
+ }
160487
+ return "created";
160488
+ },
160489
+ readExposure: async () => (await handle.get("export-hap"))?.data ?? null
160490
+ };
160491
+ }
159009
160492
  findEntry(deviceId) {
159010
160493
  const id = String(deviceId);
159011
- return this.config.exposed.find((e) => e.deviceId === id) ?? null;
160494
+ return this.exposure.devices.find((e) => e.deviceId === id) ?? null;
159012
160495
  }
159013
160496
  async updateEntrySettings(deviceIdStr, settings) {
159014
- const next = this.config.exposed.map((e) => e.deviceId === deviceIdStr ? {
160497
+ const next = this.exposure.devices.map((e) => e.deviceId === deviceIdStr ? {
159015
160498
  ...e,
159016
160499
  settings
159017
160500
  } : e);
159018
- await this.updateGlobalSettings({ exposed: next });
160501
+ await this.setExposedDevices(next);
159019
160502
  }
159020
160503
  };
159021
160504
  function errMsg(err) {