@camstack/addon-export-hap 1.2.196 → 1.2.197

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -7,6 +7,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [1.2.197] - 2026-11-07
11
+
12
+ ### Changed
13
+
14
+ - Internal: its stored state is now read and written through the typed state API under the same storage key; nothing changes for the operator.
15
+
10
16
  ## [1.2.196] - 2026-11-07
11
17
 
12
18
  ### Changed
@@ -6048,7 +6048,7 @@ var ZodIssueCode = {
6048
6048
  var ZodFirstPartyTypeKind;
6049
6049
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
6050
6050
  //#endregion
6051
- //#region ../types/dist/sleep-AEnTN3b4.mjs
6051
+ //#region ../types/dist/sleep-CQP-REJp.mjs
6052
6052
  /**
6053
6053
  * The audio chunk plane's byte format, and the ONE expansion from a coded
6054
6054
  * window to float samples (D455).
@@ -6412,6 +6412,59 @@ Object.fromEntries([
6412
6412
  function isValuelessField(field) {
6413
6413
  return field.type === "separator" || field.type === "info" || field.type === "qr-code" || field.type === "button" || field.type === "object-array" || field.type === "widget" || field.type === "addon-action-button" || field.type === "device-action-button" || field.type === "account-sign-in" || field.type === "secret-presence";
6414
6414
  }
6415
+ /**
6416
+ * Base collector: flatten a hydrated `ConfigUISchemaWithValues` into
6417
+ * `key → { value, default }`, recursing through `group` and `sub-tabs`
6418
+ * layout fields. Keeping `value` and `default` SEPARATE (rather than
6419
+ * pre-resolving) lets callers both read the effective value AND detect
6420
+ * overrides (`value` differs from `default`). Structural over `unknown`;
6421
+ * malformed input yields an empty map, never throws.
6422
+ */
6423
+ function collectHydratedFieldEntries(schema) {
6424
+ const out = /* @__PURE__ */ new Map();
6425
+ if (typeof schema !== "object" || schema === null) return out;
6426
+ const sections = schema.sections;
6427
+ if (!Array.isArray(sections)) return out;
6428
+ for (const section of sections) if (typeof section === "object" && section !== null) collectFieldEntriesInto(section.fields, out);
6429
+ return out;
6430
+ }
6431
+ /** Recursive field walker for {@link collectHydratedFieldEntries}. */
6432
+ function collectFieldEntriesInto(fields, into) {
6433
+ if (!Array.isArray(fields)) return;
6434
+ for (const field of fields) {
6435
+ if (typeof field !== "object" || field === null) continue;
6436
+ const type = field.type;
6437
+ if (type === "group") {
6438
+ collectFieldEntriesInto(field.fields, into);
6439
+ continue;
6440
+ }
6441
+ if (type === "sub-tabs") {
6442
+ const tabs = field.tabs;
6443
+ if (Array.isArray(tabs)) {
6444
+ for (const tab of tabs) if (typeof tab === "object" && tab !== null) collectFieldEntriesInto(tab.fields, into);
6445
+ }
6446
+ continue;
6447
+ }
6448
+ const key = field.key;
6449
+ if (typeof key !== "string" || key.length === 0) continue;
6450
+ if (!("value" in field)) continue;
6451
+ into.set(key, {
6452
+ value: field.value,
6453
+ default: field.default
6454
+ });
6455
+ }
6456
+ }
6457
+ /**
6458
+ * Flatten a hydrated settings payload into `key → EFFECTIVE value`
6459
+ * (`value ?? default`). The read-side inverse of `hydrateSchema` for the
6460
+ * common "just give me the resolved values" case. Built on
6461
+ * {@link collectHydratedFieldEntries}.
6462
+ */
6463
+ function collectHydratedFieldValues(schema) {
6464
+ const out = /* @__PURE__ */ new Map();
6465
+ for (const [key, entry] of collectHydratedFieldEntries(schema)) out.set(key, entry.value ?? entry.default);
6466
+ return out;
6467
+ }
6415
6468
  function hydrateSchema(schema, values, options = {}) {
6416
6469
  return {
6417
6470
  ...schema.tabs ? { tabs: [...schema.tabs] } : {},
@@ -7635,6 +7688,21 @@ var SCOPED_SETTINGS_SCOPES = [
7635
7688
  "device-defaults",
7636
7689
  "node"
7637
7690
  ];
7691
+ /** The one refusal of a key a scope did not declare. */
7692
+ function assertDeclaredKeys(keys, declared) {
7693
+ const undeclared = keys.filter((key) => !declared.has(key));
7694
+ if (undeclared.length > 0) throw new Error(`scoped settings: [${undeclared.join(", ")}] not declared for this scope (declared: [${[...declared].join(", ")}])`);
7695
+ }
7696
+ /** Build the handle over an addon's scoped read, write and unset. */
7697
+ function createScopedSettings(deps) {
7698
+ return {
7699
+ async get() {
7700
+ return deps.schema.parse(await deps.read());
7701
+ },
7702
+ patch: (patch) => deps.write(Object.fromEntries(Object.entries(patch))),
7703
+ unset: (keys) => deps.unset(keys)
7704
+ };
7705
+ }
7638
7706
  /** A write to a secret path could not be stored in the keychain, so it was refused. */
7639
7707
  var KeychainWriteRefusedError = class extends Error {
7640
7708
  fieldPath;
@@ -8210,7 +8278,16 @@ function createHandle(raw, opts) {
8210
8278
  return blob;
8211
8279
  }
8212
8280
  },
8213
- writeAddonStore: writeAddon
8281
+ writeAddonStore: writeAddon,
8282
+ removeClearedKeys: (keys) => serialize("addon", async () => {
8283
+ const stored = await readStoredAddonBlob(raw);
8284
+ index.seen("addon", stored);
8285
+ const removable = keys.filter((key) => collectSecretMarkerRefs(stored[key]).length === 0);
8286
+ if (removable.length === 0) return;
8287
+ const patch = Object.fromEntries(removable.map((key) => [key, void 0]));
8288
+ await raw.writeAddonStore(patch);
8289
+ index.wrote("addon", patch);
8290
+ })
8214
8291
  };
8215
8292
  }
8216
8293
  /** The context the addon sees, plus the private raw view and write outcome. */
@@ -8755,6 +8832,151 @@ var BaseAddon = class {
8755
8832
  }
8756
8833
  }
8757
8834
  /**
8835
+ * Hook: values layered over the stored ones when the FORM of one scope is served
8836
+ * ({@link getScopedSettings}) — a preview that derives dependent options without writing.
8837
+ * Never applied to {@link ScopedSettings.get} or to a write. `null` ⇒ no overlay.
8838
+ */
8839
+ async scopedSettingsOverlay(_scope, _cap, _nodeId) {
8840
+ return null;
8841
+ }
8842
+ /**
8843
+ * Hook: a write of one scope changed stored values (not called when the store reports no change,
8844
+ * e.g. the write-back of a stored secret). `keys` are the bare field keys of the write, node keys included.
8845
+ */
8846
+ async onScopedSettingsChanged(_scope, _cap, _keys) {}
8847
+ /** Typed handle over the CLUSTER settings `cap` declares (`clusterSettingsSchema`). */
8848
+ clusterSettings(cap, schema) {
8849
+ return this.scopedHandle("cluster", cap, schema);
8850
+ }
8851
+ /** Typed handle over the fleet defaults of the per-device settings `cap` declares. */
8852
+ deviceDefaults(cap, schema) {
8853
+ return this.scopedHandle("device-defaults", cap, schema);
8854
+ }
8855
+ /**
8856
+ * Typed handle over the settings `cap` owns PER NODE. `nodeId` omitted ⇒ the local node. A node
8857
+ * with no row yields the schema defaults — never a bare-key fallback.
8858
+ */
8859
+ nodeSettings(cap, schema, nodeId) {
8860
+ return this.scopedHandle("node", cap, schema, nodeId);
8861
+ }
8862
+ /**
8863
+ * {@link state} for a value that is kept per node: stored under `<key>@<nodeId>`, and the
8864
+ * settings store carries `nodeId` in the row data (D986 §1), so a forgotten node's rows go in one
8865
+ * central delete. `nodeId` omitted ⇒ the local node.
8866
+ */
8867
+ nodeState(key, schema, fallback, nodeId) {
8868
+ this._declaredStateKeys.add(key);
8869
+ return createDurableState({
8870
+ key: nodeScopedKey(key, nodeId ?? this._ctx?.kernel?.localNodeId ?? ""),
8871
+ schema,
8872
+ fallback,
8873
+ read: async () => this.resolveStoredSecrets(await this.readAddonStoreWithRetry()),
8874
+ write: async (patch) => {
8875
+ await this._ctx?.settings?.writeAddonStore(patch);
8876
+ },
8877
+ onParseError: (k, e) => this._ctx?.logger?.warn?.(`durable-state: stored "${k}" failed validation — using fallback`, { meta: {
8878
+ addonId: this._ctx?.id,
8879
+ key: k,
8880
+ error: String(e)
8881
+ } })
8882
+ });
8883
+ }
8884
+ /** The loaded schema `cap` declares for `scope`, or `null`. */
8885
+ async declaredScopedSchema(scope, cap) {
8886
+ await this.loadScopedSchemas(cap);
8887
+ return this.loadedScopedSchemas(cap).find((entry) => entry.scope === scope)?.schema ?? null;
8888
+ }
8889
+ async requireScopedSchema(scope, cap) {
8890
+ const schema = await this.declaredScopedSchema(scope, cap);
8891
+ if (schema === null) throw new Error(`${this.constructor.name}: cap "${cap}" declares no ${scope} settings`);
8892
+ return schema;
8893
+ }
8894
+ scopedKeys(schema) {
8895
+ return new Set(schema.sections.flatMap((section) => collectValueFieldKeys(section.fields)));
8896
+ }
8897
+ /** `store` narrowed to the keys `schema` declares. */
8898
+ narrowToScope(store, schema) {
8899
+ const keys = this.scopedKeys(schema);
8900
+ return Object.fromEntries(Object.entries(store).filter(([key]) => keys.has(key)));
8901
+ }
8902
+ scopedHandle(scope, cap, schema, nodeId) {
8903
+ return createScopedSettings({
8904
+ schema,
8905
+ read: async () => {
8906
+ const declared = await this.requireScopedSchema(scope, cap);
8907
+ const stored = this.narrowToScope(await this.resolveGlobalStore(nodeId, cap), declared);
8908
+ const effective = collectHydratedFieldValues(hydrateSchema(declared, stored));
8909
+ return {
8910
+ ...Object.fromEntries([...effective].filter(([, value]) => value !== void 0)),
8911
+ ...stored
8912
+ };
8913
+ },
8914
+ write: (patch) => this.writeScoped(scope, cap, patch, nodeId),
8915
+ unset: (keys) => this.unsetScoped(scope, cap, keys, nodeId)
8916
+ });
8917
+ }
8918
+ /** The one write path of the scoped API: declared keys only, then the global patch. */
8919
+ async writeScoped(scope, cap, patch, nodeId) {
8920
+ assertDeclaredKeys(Object.keys(patch), this.scopedKeys(await this.requireScopedSchema(scope, cap)));
8921
+ if (await this.applyGlobalPatch(patch, scope === "node" ? nodeId : void 0, cap)) await this.onScopedSettingsChanged(scope, cap, Object.keys(patch));
8922
+ }
8923
+ /**
8924
+ * Remove declared keys of one scope. A secret goes through {@link clearSecrets} — its keychain
8925
+ * value is released exactly as there — and the emptied row is then removed; every other key is
8926
+ * removed by an `undefined` patch (which a secret transform would read as "keep").
8927
+ */
8928
+ async unsetScoped(scope, cap, keys, nodeId) {
8929
+ assertDeclaredKeys(keys, this.scopedKeys(await this.requireScopedSchema(scope, cap)));
8930
+ const target = scope === "node" ? nodeId : void 0;
8931
+ const tree = this.addonSecretTree();
8932
+ const secretKeys = keys.filter((key) => tree.has(key));
8933
+ const plainKeys = keys.filter((key) => !tree.has(key));
8934
+ let changed = false;
8935
+ if (plainKeys.length > 0) {
8936
+ const patch = Object.fromEntries(plainKeys.map((key) => [key, void 0]));
8937
+ changed = await this.applyGlobalPatch(patch, target, cap) || changed;
8938
+ }
8939
+ if (secretKeys.length > 0) {
8940
+ await this.clearSecretKeys(secretKeys, target, cap);
8941
+ const node = normalizeNodeId(target ?? this._ctx?.kernel?.localNodeId);
8942
+ const rows = secretKeys.map((key) => scope === "node" ? nodeScopedKey(key, node) : key);
8943
+ if (this._secretSettings !== null) await this._secretSettings.removeClearedKeys(rows);
8944
+ else await this._ctx?.settings?.writeAddonStore(Object.fromEntries(rows.map((row) => [row, void 0])));
8945
+ changed = true;
8946
+ }
8947
+ if (changed) await this.onScopedSettingsChanged(scope, cap, [...keys]);
8948
+ }
8949
+ /**
8950
+ * The hydrated form of one scope of one capability's settings (any
8951
+ * {@link scopedSettingsOverlay} applied), or `null` when the capability declares nothing there.
8952
+ */
8953
+ async getScopedSettings(scope, cap, nodeId) {
8954
+ const schema = await this.declaredScopedSchema(scope, cap);
8955
+ if (schema === null) return null;
8956
+ const stored = this.narrowToScope(await this.readRawProjectedStore(nodeId, cap), schema);
8957
+ const overlay = await this.scopedSettingsOverlay(scope, cap, nodeId);
8958
+ return hydrateSchema(schema, overlay ? await this.overlayKeepingMarkers(stored, overlay) : stored, { inlineSecretsAsViews: true });
8959
+ }
8960
+ /** The OPERATOR's write of declared keys of one scope (D787 secret semantics). */
8961
+ async updateScopedSettings(scope, cap, patch, nodeId) {
8962
+ this._operatorWriteDepth++;
8963
+ try {
8964
+ await this.writeScoped(scope, cap, patch, nodeId);
8965
+ } finally {
8966
+ this._operatorWriteDepth--;
8967
+ }
8968
+ }
8969
+ /**
8970
+ * The effective values (`stored ?? default`) of one scope, a secret as its `set` view — never
8971
+ * its value. `null` when the capability declares nothing for the scope.
8972
+ */
8973
+ async readScopedValues(scope, cap, nodeId) {
8974
+ const schema = await this.declaredScopedSchema(scope, cap);
8975
+ if (schema === null) return null;
8976
+ const form = hydrateSchema(schema, this.narrowToScope(await this.readRawProjectedStore(nodeId, cap), schema), { inlineSecretsAsViews: true });
8977
+ return Object.fromEntries([...collectHydratedFieldValues(form)].filter(([, value]) => value !== void 0));
8978
+ }
8979
+ /**
8758
8980
  * What the create wizard and the integration edit page render for one instance: the addon's
8759
8981
  * per-instance schema when it declares one, else its global schema (what they always showed).
8760
8982
  */
@@ -8906,6 +9128,9 @@ var BaseAddon = class {
8906
9128
  * a keychain (an older kernel) it writes `''`, as such code always did.
8907
9129
  */
8908
9130
  async clearSecrets(keys, nodeId) {
9131
+ await this.clearSecretKeys(keys, nodeId);
9132
+ }
9133
+ async clearSecretKeys(keys, nodeId, cap) {
8909
9134
  const tree = this.addonSecretTree();
8910
9135
  const keychain = this._ctx?.secrets !== void 0;
8911
9136
  const stored = keychain ? await this.readAddonStoreWithRetry() : {};
@@ -8918,25 +9143,27 @@ var BaseAddon = class {
8918
9143
  const keychainStored = tree.has(key) || collectSecretMarkerRefs(stored[key]).length > 0;
8919
9144
  patch[key] = keychain && keychainStored ? SECRET_CLEAR : "";
8920
9145
  }
8921
- await this.applyGlobalPatch(patch, nodeId);
9146
+ await this.applyGlobalPatch(patch, nodeId, cap);
8922
9147
  }
8923
- async applyGlobalPatch(barePatch, nodeId) {
8924
- await this.loadScopedSchemas();
8925
- const keys = this.perNodeKeys();
9148
+ /** Resolves `true` when the write changed stored values. */
9149
+ async applyGlobalPatch(barePatch, nodeId, cap) {
9150
+ await this.loadScopedSchemas(cap);
9151
+ const keys = this.perNodeKeys(cap);
8926
9152
  const localNode = normalizeNodeId(this._ctx?.kernel?.localNodeId);
8927
9153
  const target = normalizeNodeId(nodeId ?? this._ctx?.kernel?.localNodeId);
8928
9154
  const scoped = keys.size > 0 ? scopePatch(barePatch, keys, target) : barePatch;
8929
9155
  const handle = this._secretSettings;
8930
9156
  if (handle !== null) {
8931
9157
  const { changed } = await handle.writeAddonStore(scoped);
8932
- if (!changed) return;
9158
+ if (!changed) return false;
8933
9159
  } else await this._ctx?.settings?.writeAddonStore(scoped);
8934
- if (target !== localNode) return;
9160
+ if (target !== localNode) return true;
8935
9161
  await this.resolveConfig();
8936
9162
  await this.onConfigChanged();
8937
9163
  this.emitLifecycle(EventCategory.AddonUpdated, { level: "global" });
8938
9164
  const legacy = this.globalSettingsSchema();
8939
9165
  this.maybeAutoRestart(Object.keys(barePatch), [...legacy === null ? [] : [legacy], ...this.loadedScopedSchemas().map((entry) => entry.schema)]);
9166
+ return true;
8940
9167
  }
8941
9168
  /**
8942
9169
  * The set of field keys the global settings schema declares `perNode: true`
@@ -45728,6 +45955,8 @@ var SettingsSchemaWithValuesSchema = object({
45728
45955
  });
45729
45956
  /** Patch object — keys are field names, values are the new field values. */
45730
45957
  var SettingsPatchSchema = record(string(), unknown());
45958
+ /** The scope of a scoped-settings call (D986): where the capability declared the values. */
45959
+ var ScopedSettingsScopeSchema = _enum(SCOPED_SETTINGS_SCOPES);
45731
45960
  /** Standard success response for update operations. */
45732
45961
  var SettingsUpdateResultSchema = object({ success: literal(true) });
45733
45962
  method(object({
@@ -45743,6 +45972,25 @@ method(object({
45743
45972
  kind: "mutation",
45744
45973
  auth: "admin"
45745
45974
  }), method(object({
45975
+ addonId: string(),
45976
+ cap: string(),
45977
+ scope: ScopedSettingsScopeSchema,
45978
+ nodeId: string().optional()
45979
+ }), SettingsSchemaWithValuesSchema.nullable()), method(object({
45980
+ addonId: string(),
45981
+ cap: string(),
45982
+ scope: ScopedSettingsScopeSchema,
45983
+ nodeId: string().optional(),
45984
+ patch: SettingsPatchSchema
45985
+ }), SettingsUpdateResultSchema, {
45986
+ kind: "mutation",
45987
+ auth: "admin"
45988
+ }), method(object({
45989
+ addonId: string(),
45990
+ cap: string(),
45991
+ scope: ScopedSettingsScopeSchema,
45992
+ nodeId: string().optional()
45993
+ }), record(string(), unknown()).nullable()), method(object({
45746
45994
  addonId: string(),
45747
45995
  nodeId: string().optional()
45748
45996
  }), SettingsSchemaWithValuesSchema.nullable()), method(object({
@@ -77976,6 +78224,20 @@ Object.freeze({
77976
78224
  access: "view",
77977
78225
  role: "admin"
77978
78226
  },
78227
+ "addonSettings.getScopedSettings": {
78228
+ capName: "addon-settings",
78229
+ capScope: "system",
78230
+ addonId: null,
78231
+ access: "view",
78232
+ role: "admin"
78233
+ },
78234
+ "addonSettings.readScopedValues": {
78235
+ capName: "addon-settings",
78236
+ capScope: "system",
78237
+ addonId: null,
78238
+ access: "view",
78239
+ role: "admin"
78240
+ },
77979
78241
  "addonSettings.unsetStoredSettingsKeys": {
77980
78242
  capName: "addon-settings",
77981
78243
  capScope: "system",
@@ -77997,6 +78259,13 @@ Object.freeze({
77997
78259
  access: "create",
77998
78260
  role: "admin"
77999
78261
  },
78262
+ "addonSettings.updateScopedSettings": {
78263
+ capName: "addon-settings",
78264
+ capScope: "system",
78265
+ addonId: null,
78266
+ access: "create",
78267
+ role: "admin"
78268
+ },
78000
78269
  "addonWidgets.listWidgets": {
78001
78270
  capName: "addon-widgets",
78002
78271
  capScope: "system",
@@ -159470,10 +159739,23 @@ var HAP_STREAM_PREFERENCE_OPTIONS = [
159470
159739
  label: "Low"
159471
159740
  }
159472
159741
  ];
159742
+ /** One device's advertised HAP state, persisted in the addon store. JSON-plain
159743
+ * mirror of `ExportTargetEntry` from `@camstack/types/node`. Keyed by
159744
+ * `String(deviceId)` in the `exportSyncState` store key. `externalIds` holds
159745
+ * the deterministic accessory UUID (diagnostic; rebuild uses the live mapper). */
159746
+ var ExportTargetEntrySchema = object({
159747
+ fingerprint: string(),
159748
+ externalIds: array(string())
159749
+ });
159750
+ /** Durable per-device export sync state — the Phase-C reconciler cache, kept under the
159751
+ * addon-store key `exportSyncState` (the key the addon always used).
159752
+ * Key = `String(deviceId)`, value = the device's export fingerprint at last
159753
+ * attach. Drives `diffExportTargets`: an unchanged restart hashes to the same
159754
+ * fingerprint → no rebuild. */
159755
+ var ExportSyncStateSchema = record(string(), ExportTargetEntrySchema);
159473
159756
  var DEFAULT_CONFIG = {
159474
159757
  interfaceName: "",
159475
- clipRetentionDays: 14,
159476
- exportSyncState: {}
159758
+ clipRetentionDays: 14
159477
159759
  };
159478
159760
  var BANNED_PINCODES = new Set([
159479
159761
  "000-00-000",
@@ -159792,7 +160074,7 @@ var ExportHapAddon = class extends BaseAddon {
159792
160074
  await this.stopInstance(id);
159793
160075
  for (const uuid of uuids) clearPairingFiles(uuid, this.ctx.logger);
159794
160076
  await this.exposureHandle().delete(id);
159795
- if (id === "export-hap") await this.updateGlobalSettings({ exportSyncState: {} });
160077
+ if (id === "export-hap") await this.exportSyncState.set({});
159796
160078
  this.ctx.logger.info("export-hap: bridge removed", { meta: { instanceId: id } });
159797
160079
  }
159798
160080
  /**
@@ -160164,9 +160446,11 @@ var ExportHapAddon = class extends BaseAddon {
160164
160446
  return inst.accessoryUuidOf(inst.findEntry(deviceId)?.mapperKind ?? "camera", deviceId);
160165
160447
  }
160166
160448
  /** The reconcile cache of a bridge: the default one is persisted, the others live in memory (boot re-attach seeds them). */
160167
- syncStateOf(inst) {
160168
- return inst.id === "export-hap" ? syncStateFromJson(this.config.exportSyncState) : inst.syncState;
160449
+ async syncStateOf(inst) {
160450
+ return inst.id === "export-hap" ? syncStateFromJson(await this.exportSyncState.get()) : inst.syncState;
160169
160451
  }
160452
+ /** The persisted reconcile cache of the default bridge (store key `exportSyncState`). */
160453
+ exportSyncState = this.state("exportSyncState", ExportSyncStateSchema, {});
160170
160454
  /**
160171
160455
  * Export fingerprint of a device from its PERSISTED features + type
160172
160456
  * (`canonicalDeviceFingerprint`). Returns `null` on a transient API error or
@@ -160192,7 +160476,7 @@ var ExportHapAddon = class extends BaseAddon {
160192
160476
  deviceType: device.type,
160193
160477
  features: device.features
160194
160478
  });
160195
- const persisted = this.syncStateOf(inst).get(deviceId)?.fingerprint;
160479
+ const persisted = (await this.syncStateOf(inst)).get(deviceId)?.fingerprint;
160196
160480
  const withToken = withRecordabilityToken({
160197
160481
  base: fresh,
160198
160482
  token: await this.readRecordabilityToken(inst, deviceId, device.type),
@@ -160227,22 +160511,35 @@ var ExportHapAddon = class extends BaseAddon {
160227
160511
  return null;
160228
160512
  }
160229
160513
  }
160514
+ /** Tail of the pending cache writes of each bridge: a read-modify-write of one bridge never overlaps another. */
160515
+ syncWrites = /* @__PURE__ */ new Map();
160516
+ /** Run one read-modify-write of a bridge's reconcile cache after the previous one finished. */
160517
+ serialisedSyncWrite(inst, write) {
160518
+ const next = (this.syncWrites.get(inst.id) ?? Promise.resolve()).then(write);
160519
+ this.syncWrites.set(inst.id, next.catch(() => void 0));
160520
+ return next;
160521
+ }
160230
160522
  /** Persist a device's current export fingerprint into `exportSyncState`
160231
- * (best-effort; called after a successful attach). */
160232
- async persistFingerprint(inst, deviceId, fingerprint) {
160233
- const state = this.syncStateOf(inst);
160234
- state.set(deviceId, {
160235
- fingerprint,
160236
- externalIds: [this.hapAccessoryUuid(inst, deviceId)]
160523
+ * (best-effort; called after a successful attach). Serialised per bridge, so two attaches
160524
+ * finishing together cannot each write back a cache that lacks the other's entry. */
160525
+ persistFingerprint(inst, deviceId, fingerprint) {
160526
+ return this.serialisedSyncWrite(inst, async () => {
160527
+ const state = await this.syncStateOf(inst);
160528
+ state.set(deviceId, {
160529
+ fingerprint,
160530
+ externalIds: [this.hapAccessoryUuid(inst, deviceId)]
160531
+ });
160532
+ if (inst.id === "export-hap") await this.exportSyncState.set(syncStateToJson(state));
160237
160533
  });
160238
- if (inst.id === "export-hap") await this.updateGlobalSettings({ exportSyncState: syncStateToJson(state) });
160239
160534
  }
160240
- /** Drop a device's `exportSyncState` entry (on unexpose). */
160241
- async forgetFingerprint(inst, deviceId) {
160242
- const state = this.syncStateOf(inst);
160243
- if (!state.has(deviceId)) return;
160244
- state.delete(deviceId);
160245
- if (inst.id === "export-hap") await this.updateGlobalSettings({ exportSyncState: syncStateToJson(state) });
160535
+ /** Drop a device's `exportSyncState` entry (on unexpose). Serialised with the writes above. */
160536
+ forgetFingerprint(inst, deviceId) {
160537
+ return this.serialisedSyncWrite(inst, async () => {
160538
+ const state = await this.syncStateOf(inst);
160539
+ if (!state.has(deviceId)) return;
160540
+ state.delete(deviceId);
160541
+ if (inst.id === "export-hap") await this.exportSyncState.set(syncStateToJson(state));
160542
+ });
160246
160543
  }
160247
160544
  /**
160248
160545
  * Subscribe to a device-lifecycle event category and reconcile the exposed
@@ -160330,7 +160627,7 @@ var ExportHapAddon = class extends BaseAddon {
160330
160627
  log.debug("export-hap: reconcile skipped — fingerprint unavailable (transient)");
160331
160628
  return;
160332
160629
  }
160333
- const last = this.syncStateOf(inst).get(numericId);
160630
+ const last = (await this.syncStateOf(inst)).get(numericId);
160334
160631
  if (last?.fingerprint === current) {
160335
160632
  if (!inst.exposed.has(deviceId)) try {
160336
160633
  await this.attachMapper(inst, entry);
@@ -160852,6 +161149,7 @@ exports.DEFAULT_DEVICE_SETTINGS = DEFAULT_DEVICE_SETTINGS;
160852
161149
  exports.EXPORT_HAP_ADDON_ID = EXPORT_HAP_ADDON_ID;
160853
161150
  exports.ExportHapAddon = ExportHapAddon;
160854
161151
  exports.default = ExportHapAddon;
161152
+ exports.ExportSyncStateSchema = ExportSyncStateSchema;
160855
161153
  exports.__toCommonJS = __toCommonJS;
160856
161154
  exports.deriveUsername = deriveUsername;
160857
161155
  exports.describeHksvCamera = describeHksvCamera;
@@ -6038,7 +6038,7 @@ var ZodIssueCode = {
6038
6038
  var ZodFirstPartyTypeKind;
6039
6039
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
6040
6040
  //#endregion
6041
- //#region ../types/dist/sleep-AEnTN3b4.mjs
6041
+ //#region ../types/dist/sleep-CQP-REJp.mjs
6042
6042
  /**
6043
6043
  * The audio chunk plane's byte format, and the ONE expansion from a coded
6044
6044
  * window to float samples (D455).
@@ -6402,6 +6402,59 @@ Object.fromEntries([
6402
6402
  function isValuelessField(field) {
6403
6403
  return field.type === "separator" || field.type === "info" || field.type === "qr-code" || field.type === "button" || field.type === "object-array" || field.type === "widget" || field.type === "addon-action-button" || field.type === "device-action-button" || field.type === "account-sign-in" || field.type === "secret-presence";
6404
6404
  }
6405
+ /**
6406
+ * Base collector: flatten a hydrated `ConfigUISchemaWithValues` into
6407
+ * `key → { value, default }`, recursing through `group` and `sub-tabs`
6408
+ * layout fields. Keeping `value` and `default` SEPARATE (rather than
6409
+ * pre-resolving) lets callers both read the effective value AND detect
6410
+ * overrides (`value` differs from `default`). Structural over `unknown`;
6411
+ * malformed input yields an empty map, never throws.
6412
+ */
6413
+ function collectHydratedFieldEntries(schema) {
6414
+ const out = /* @__PURE__ */ new Map();
6415
+ if (typeof schema !== "object" || schema === null) return out;
6416
+ const sections = schema.sections;
6417
+ if (!Array.isArray(sections)) return out;
6418
+ for (const section of sections) if (typeof section === "object" && section !== null) collectFieldEntriesInto(section.fields, out);
6419
+ return out;
6420
+ }
6421
+ /** Recursive field walker for {@link collectHydratedFieldEntries}. */
6422
+ function collectFieldEntriesInto(fields, into) {
6423
+ if (!Array.isArray(fields)) return;
6424
+ for (const field of fields) {
6425
+ if (typeof field !== "object" || field === null) continue;
6426
+ const type = field.type;
6427
+ if (type === "group") {
6428
+ collectFieldEntriesInto(field.fields, into);
6429
+ continue;
6430
+ }
6431
+ if (type === "sub-tabs") {
6432
+ const tabs = field.tabs;
6433
+ if (Array.isArray(tabs)) {
6434
+ for (const tab of tabs) if (typeof tab === "object" && tab !== null) collectFieldEntriesInto(tab.fields, into);
6435
+ }
6436
+ continue;
6437
+ }
6438
+ const key = field.key;
6439
+ if (typeof key !== "string" || key.length === 0) continue;
6440
+ if (!("value" in field)) continue;
6441
+ into.set(key, {
6442
+ value: field.value,
6443
+ default: field.default
6444
+ });
6445
+ }
6446
+ }
6447
+ /**
6448
+ * Flatten a hydrated settings payload into `key → EFFECTIVE value`
6449
+ * (`value ?? default`). The read-side inverse of `hydrateSchema` for the
6450
+ * common "just give me the resolved values" case. Built on
6451
+ * {@link collectHydratedFieldEntries}.
6452
+ */
6453
+ function collectHydratedFieldValues(schema) {
6454
+ const out = /* @__PURE__ */ new Map();
6455
+ for (const [key, entry] of collectHydratedFieldEntries(schema)) out.set(key, entry.value ?? entry.default);
6456
+ return out;
6457
+ }
6405
6458
  function hydrateSchema(schema, values, options = {}) {
6406
6459
  return {
6407
6460
  ...schema.tabs ? { tabs: [...schema.tabs] } : {},
@@ -7625,6 +7678,21 @@ var SCOPED_SETTINGS_SCOPES = [
7625
7678
  "device-defaults",
7626
7679
  "node"
7627
7680
  ];
7681
+ /** The one refusal of a key a scope did not declare. */
7682
+ function assertDeclaredKeys(keys, declared) {
7683
+ const undeclared = keys.filter((key) => !declared.has(key));
7684
+ if (undeclared.length > 0) throw new Error(`scoped settings: [${undeclared.join(", ")}] not declared for this scope (declared: [${[...declared].join(", ")}])`);
7685
+ }
7686
+ /** Build the handle over an addon's scoped read, write and unset. */
7687
+ function createScopedSettings(deps) {
7688
+ return {
7689
+ async get() {
7690
+ return deps.schema.parse(await deps.read());
7691
+ },
7692
+ patch: (patch) => deps.write(Object.fromEntries(Object.entries(patch))),
7693
+ unset: (keys) => deps.unset(keys)
7694
+ };
7695
+ }
7628
7696
  /** A write to a secret path could not be stored in the keychain, so it was refused. */
7629
7697
  var KeychainWriteRefusedError = class extends Error {
7630
7698
  fieldPath;
@@ -8200,7 +8268,16 @@ function createHandle(raw, opts) {
8200
8268
  return blob;
8201
8269
  }
8202
8270
  },
8203
- writeAddonStore: writeAddon
8271
+ writeAddonStore: writeAddon,
8272
+ removeClearedKeys: (keys) => serialize("addon", async () => {
8273
+ const stored = await readStoredAddonBlob(raw);
8274
+ index.seen("addon", stored);
8275
+ const removable = keys.filter((key) => collectSecretMarkerRefs(stored[key]).length === 0);
8276
+ if (removable.length === 0) return;
8277
+ const patch = Object.fromEntries(removable.map((key) => [key, void 0]));
8278
+ await raw.writeAddonStore(patch);
8279
+ index.wrote("addon", patch);
8280
+ })
8204
8281
  };
8205
8282
  }
8206
8283
  /** The context the addon sees, plus the private raw view and write outcome. */
@@ -8745,6 +8822,151 @@ var BaseAddon = class {
8745
8822
  }
8746
8823
  }
8747
8824
  /**
8825
+ * Hook: values layered over the stored ones when the FORM of one scope is served
8826
+ * ({@link getScopedSettings}) — a preview that derives dependent options without writing.
8827
+ * Never applied to {@link ScopedSettings.get} or to a write. `null` ⇒ no overlay.
8828
+ */
8829
+ async scopedSettingsOverlay(_scope, _cap, _nodeId) {
8830
+ return null;
8831
+ }
8832
+ /**
8833
+ * Hook: a write of one scope changed stored values (not called when the store reports no change,
8834
+ * e.g. the write-back of a stored secret). `keys` are the bare field keys of the write, node keys included.
8835
+ */
8836
+ async onScopedSettingsChanged(_scope, _cap, _keys) {}
8837
+ /** Typed handle over the CLUSTER settings `cap` declares (`clusterSettingsSchema`). */
8838
+ clusterSettings(cap, schema) {
8839
+ return this.scopedHandle("cluster", cap, schema);
8840
+ }
8841
+ /** Typed handle over the fleet defaults of the per-device settings `cap` declares. */
8842
+ deviceDefaults(cap, schema) {
8843
+ return this.scopedHandle("device-defaults", cap, schema);
8844
+ }
8845
+ /**
8846
+ * Typed handle over the settings `cap` owns PER NODE. `nodeId` omitted ⇒ the local node. A node
8847
+ * with no row yields the schema defaults — never a bare-key fallback.
8848
+ */
8849
+ nodeSettings(cap, schema, nodeId) {
8850
+ return this.scopedHandle("node", cap, schema, nodeId);
8851
+ }
8852
+ /**
8853
+ * {@link state} for a value that is kept per node: stored under `<key>@<nodeId>`, and the
8854
+ * settings store carries `nodeId` in the row data (D986 §1), so a forgotten node's rows go in one
8855
+ * central delete. `nodeId` omitted ⇒ the local node.
8856
+ */
8857
+ nodeState(key, schema, fallback, nodeId) {
8858
+ this._declaredStateKeys.add(key);
8859
+ return createDurableState({
8860
+ key: nodeScopedKey(key, nodeId ?? this._ctx?.kernel?.localNodeId ?? ""),
8861
+ schema,
8862
+ fallback,
8863
+ read: async () => this.resolveStoredSecrets(await this.readAddonStoreWithRetry()),
8864
+ write: async (patch) => {
8865
+ await this._ctx?.settings?.writeAddonStore(patch);
8866
+ },
8867
+ onParseError: (k, e) => this._ctx?.logger?.warn?.(`durable-state: stored "${k}" failed validation — using fallback`, { meta: {
8868
+ addonId: this._ctx?.id,
8869
+ key: k,
8870
+ error: String(e)
8871
+ } })
8872
+ });
8873
+ }
8874
+ /** The loaded schema `cap` declares for `scope`, or `null`. */
8875
+ async declaredScopedSchema(scope, cap) {
8876
+ await this.loadScopedSchemas(cap);
8877
+ return this.loadedScopedSchemas(cap).find((entry) => entry.scope === scope)?.schema ?? null;
8878
+ }
8879
+ async requireScopedSchema(scope, cap) {
8880
+ const schema = await this.declaredScopedSchema(scope, cap);
8881
+ if (schema === null) throw new Error(`${this.constructor.name}: cap "${cap}" declares no ${scope} settings`);
8882
+ return schema;
8883
+ }
8884
+ scopedKeys(schema) {
8885
+ return new Set(schema.sections.flatMap((section) => collectValueFieldKeys(section.fields)));
8886
+ }
8887
+ /** `store` narrowed to the keys `schema` declares. */
8888
+ narrowToScope(store, schema) {
8889
+ const keys = this.scopedKeys(schema);
8890
+ return Object.fromEntries(Object.entries(store).filter(([key]) => keys.has(key)));
8891
+ }
8892
+ scopedHandle(scope, cap, schema, nodeId) {
8893
+ return createScopedSettings({
8894
+ schema,
8895
+ read: async () => {
8896
+ const declared = await this.requireScopedSchema(scope, cap);
8897
+ const stored = this.narrowToScope(await this.resolveGlobalStore(nodeId, cap), declared);
8898
+ const effective = collectHydratedFieldValues(hydrateSchema(declared, stored));
8899
+ return {
8900
+ ...Object.fromEntries([...effective].filter(([, value]) => value !== void 0)),
8901
+ ...stored
8902
+ };
8903
+ },
8904
+ write: (patch) => this.writeScoped(scope, cap, patch, nodeId),
8905
+ unset: (keys) => this.unsetScoped(scope, cap, keys, nodeId)
8906
+ });
8907
+ }
8908
+ /** The one write path of the scoped API: declared keys only, then the global patch. */
8909
+ async writeScoped(scope, cap, patch, nodeId) {
8910
+ assertDeclaredKeys(Object.keys(patch), this.scopedKeys(await this.requireScopedSchema(scope, cap)));
8911
+ if (await this.applyGlobalPatch(patch, scope === "node" ? nodeId : void 0, cap)) await this.onScopedSettingsChanged(scope, cap, Object.keys(patch));
8912
+ }
8913
+ /**
8914
+ * Remove declared keys of one scope. A secret goes through {@link clearSecrets} — its keychain
8915
+ * value is released exactly as there — and the emptied row is then removed; every other key is
8916
+ * removed by an `undefined` patch (which a secret transform would read as "keep").
8917
+ */
8918
+ async unsetScoped(scope, cap, keys, nodeId) {
8919
+ assertDeclaredKeys(keys, this.scopedKeys(await this.requireScopedSchema(scope, cap)));
8920
+ const target = scope === "node" ? nodeId : void 0;
8921
+ const tree = this.addonSecretTree();
8922
+ const secretKeys = keys.filter((key) => tree.has(key));
8923
+ const plainKeys = keys.filter((key) => !tree.has(key));
8924
+ let changed = false;
8925
+ if (plainKeys.length > 0) {
8926
+ const patch = Object.fromEntries(plainKeys.map((key) => [key, void 0]));
8927
+ changed = await this.applyGlobalPatch(patch, target, cap) || changed;
8928
+ }
8929
+ if (secretKeys.length > 0) {
8930
+ await this.clearSecretKeys(secretKeys, target, cap);
8931
+ const node = normalizeNodeId(target ?? this._ctx?.kernel?.localNodeId);
8932
+ const rows = secretKeys.map((key) => scope === "node" ? nodeScopedKey(key, node) : key);
8933
+ if (this._secretSettings !== null) await this._secretSettings.removeClearedKeys(rows);
8934
+ else await this._ctx?.settings?.writeAddonStore(Object.fromEntries(rows.map((row) => [row, void 0])));
8935
+ changed = true;
8936
+ }
8937
+ if (changed) await this.onScopedSettingsChanged(scope, cap, [...keys]);
8938
+ }
8939
+ /**
8940
+ * The hydrated form of one scope of one capability's settings (any
8941
+ * {@link scopedSettingsOverlay} applied), or `null` when the capability declares nothing there.
8942
+ */
8943
+ async getScopedSettings(scope, cap, nodeId) {
8944
+ const schema = await this.declaredScopedSchema(scope, cap);
8945
+ if (schema === null) return null;
8946
+ const stored = this.narrowToScope(await this.readRawProjectedStore(nodeId, cap), schema);
8947
+ const overlay = await this.scopedSettingsOverlay(scope, cap, nodeId);
8948
+ return hydrateSchema(schema, overlay ? await this.overlayKeepingMarkers(stored, overlay) : stored, { inlineSecretsAsViews: true });
8949
+ }
8950
+ /** The OPERATOR's write of declared keys of one scope (D787 secret semantics). */
8951
+ async updateScopedSettings(scope, cap, patch, nodeId) {
8952
+ this._operatorWriteDepth++;
8953
+ try {
8954
+ await this.writeScoped(scope, cap, patch, nodeId);
8955
+ } finally {
8956
+ this._operatorWriteDepth--;
8957
+ }
8958
+ }
8959
+ /**
8960
+ * The effective values (`stored ?? default`) of one scope, a secret as its `set` view — never
8961
+ * its value. `null` when the capability declares nothing for the scope.
8962
+ */
8963
+ async readScopedValues(scope, cap, nodeId) {
8964
+ const schema = await this.declaredScopedSchema(scope, cap);
8965
+ if (schema === null) return null;
8966
+ const form = hydrateSchema(schema, this.narrowToScope(await this.readRawProjectedStore(nodeId, cap), schema), { inlineSecretsAsViews: true });
8967
+ return Object.fromEntries([...collectHydratedFieldValues(form)].filter(([, value]) => value !== void 0));
8968
+ }
8969
+ /**
8748
8970
  * What the create wizard and the integration edit page render for one instance: the addon's
8749
8971
  * per-instance schema when it declares one, else its global schema (what they always showed).
8750
8972
  */
@@ -8896,6 +9118,9 @@ var BaseAddon = class {
8896
9118
  * a keychain (an older kernel) it writes `''`, as such code always did.
8897
9119
  */
8898
9120
  async clearSecrets(keys, nodeId) {
9121
+ await this.clearSecretKeys(keys, nodeId);
9122
+ }
9123
+ async clearSecretKeys(keys, nodeId, cap) {
8899
9124
  const tree = this.addonSecretTree();
8900
9125
  const keychain = this._ctx?.secrets !== void 0;
8901
9126
  const stored = keychain ? await this.readAddonStoreWithRetry() : {};
@@ -8908,25 +9133,27 @@ var BaseAddon = class {
8908
9133
  const keychainStored = tree.has(key) || collectSecretMarkerRefs(stored[key]).length > 0;
8909
9134
  patch[key] = keychain && keychainStored ? SECRET_CLEAR : "";
8910
9135
  }
8911
- await this.applyGlobalPatch(patch, nodeId);
9136
+ await this.applyGlobalPatch(patch, nodeId, cap);
8912
9137
  }
8913
- async applyGlobalPatch(barePatch, nodeId) {
8914
- await this.loadScopedSchemas();
8915
- const keys = this.perNodeKeys();
9138
+ /** Resolves `true` when the write changed stored values. */
9139
+ async applyGlobalPatch(barePatch, nodeId, cap) {
9140
+ await this.loadScopedSchemas(cap);
9141
+ const keys = this.perNodeKeys(cap);
8916
9142
  const localNode = normalizeNodeId(this._ctx?.kernel?.localNodeId);
8917
9143
  const target = normalizeNodeId(nodeId ?? this._ctx?.kernel?.localNodeId);
8918
9144
  const scoped = keys.size > 0 ? scopePatch(barePatch, keys, target) : barePatch;
8919
9145
  const handle = this._secretSettings;
8920
9146
  if (handle !== null) {
8921
9147
  const { changed } = await handle.writeAddonStore(scoped);
8922
- if (!changed) return;
9148
+ if (!changed) return false;
8923
9149
  } else await this._ctx?.settings?.writeAddonStore(scoped);
8924
- if (target !== localNode) return;
9150
+ if (target !== localNode) return true;
8925
9151
  await this.resolveConfig();
8926
9152
  await this.onConfigChanged();
8927
9153
  this.emitLifecycle(EventCategory.AddonUpdated, { level: "global" });
8928
9154
  const legacy = this.globalSettingsSchema();
8929
9155
  this.maybeAutoRestart(Object.keys(barePatch), [...legacy === null ? [] : [legacy], ...this.loadedScopedSchemas().map((entry) => entry.schema)]);
9156
+ return true;
8930
9157
  }
8931
9158
  /**
8932
9159
  * The set of field keys the global settings schema declares `perNode: true`
@@ -45718,6 +45945,8 @@ var SettingsSchemaWithValuesSchema = object({
45718
45945
  });
45719
45946
  /** Patch object — keys are field names, values are the new field values. */
45720
45947
  var SettingsPatchSchema = record(string(), unknown());
45948
+ /** The scope of a scoped-settings call (D986): where the capability declared the values. */
45949
+ var ScopedSettingsScopeSchema = _enum(SCOPED_SETTINGS_SCOPES);
45721
45950
  /** Standard success response for update operations. */
45722
45951
  var SettingsUpdateResultSchema = object({ success: literal(true) });
45723
45952
  method(object({
@@ -45733,6 +45962,25 @@ method(object({
45733
45962
  kind: "mutation",
45734
45963
  auth: "admin"
45735
45964
  }), method(object({
45965
+ addonId: string(),
45966
+ cap: string(),
45967
+ scope: ScopedSettingsScopeSchema,
45968
+ nodeId: string().optional()
45969
+ }), SettingsSchemaWithValuesSchema.nullable()), method(object({
45970
+ addonId: string(),
45971
+ cap: string(),
45972
+ scope: ScopedSettingsScopeSchema,
45973
+ nodeId: string().optional(),
45974
+ patch: SettingsPatchSchema
45975
+ }), SettingsUpdateResultSchema, {
45976
+ kind: "mutation",
45977
+ auth: "admin"
45978
+ }), method(object({
45979
+ addonId: string(),
45980
+ cap: string(),
45981
+ scope: ScopedSettingsScopeSchema,
45982
+ nodeId: string().optional()
45983
+ }), record(string(), unknown()).nullable()), method(object({
45736
45984
  addonId: string(),
45737
45985
  nodeId: string().optional()
45738
45986
  }), SettingsSchemaWithValuesSchema.nullable()), method(object({
@@ -77966,6 +78214,20 @@ Object.freeze({
77966
78214
  access: "view",
77967
78215
  role: "admin"
77968
78216
  },
78217
+ "addonSettings.getScopedSettings": {
78218
+ capName: "addon-settings",
78219
+ capScope: "system",
78220
+ addonId: null,
78221
+ access: "view",
78222
+ role: "admin"
78223
+ },
78224
+ "addonSettings.readScopedValues": {
78225
+ capName: "addon-settings",
78226
+ capScope: "system",
78227
+ addonId: null,
78228
+ access: "view",
78229
+ role: "admin"
78230
+ },
77969
78231
  "addonSettings.unsetStoredSettingsKeys": {
77970
78232
  capName: "addon-settings",
77971
78233
  capScope: "system",
@@ -77987,6 +78249,13 @@ Object.freeze({
77987
78249
  access: "create",
77988
78250
  role: "admin"
77989
78251
  },
78252
+ "addonSettings.updateScopedSettings": {
78253
+ capName: "addon-settings",
78254
+ capScope: "system",
78255
+ addonId: null,
78256
+ access: "create",
78257
+ role: "admin"
78258
+ },
77990
78259
  "addonWidgets.listWidgets": {
77991
78260
  capName: "addon-widgets",
77992
78261
  capScope: "system",
@@ -159460,10 +159729,23 @@ var HAP_STREAM_PREFERENCE_OPTIONS = [
159460
159729
  label: "Low"
159461
159730
  }
159462
159731
  ];
159732
+ /** One device's advertised HAP state, persisted in the addon store. JSON-plain
159733
+ * mirror of `ExportTargetEntry` from `@camstack/types/node`. Keyed by
159734
+ * `String(deviceId)` in the `exportSyncState` store key. `externalIds` holds
159735
+ * the deterministic accessory UUID (diagnostic; rebuild uses the live mapper). */
159736
+ var ExportTargetEntrySchema = object({
159737
+ fingerprint: string(),
159738
+ externalIds: array(string())
159739
+ });
159740
+ /** Durable per-device export sync state — the Phase-C reconciler cache, kept under the
159741
+ * addon-store key `exportSyncState` (the key the addon always used).
159742
+ * Key = `String(deviceId)`, value = the device's export fingerprint at last
159743
+ * attach. Drives `diffExportTargets`: an unchanged restart hashes to the same
159744
+ * fingerprint → no rebuild. */
159745
+ var ExportSyncStateSchema = record(string(), ExportTargetEntrySchema);
159463
159746
  var DEFAULT_CONFIG = {
159464
159747
  interfaceName: "",
159465
- clipRetentionDays: 14,
159466
- exportSyncState: {}
159748
+ clipRetentionDays: 14
159467
159749
  };
159468
159750
  var BANNED_PINCODES = new Set([
159469
159751
  "000-00-000",
@@ -159782,7 +160064,7 @@ var ExportHapAddon = class extends BaseAddon {
159782
160064
  await this.stopInstance(id);
159783
160065
  for (const uuid of uuids) clearPairingFiles(uuid, this.ctx.logger);
159784
160066
  await this.exposureHandle().delete(id);
159785
- if (id === "export-hap") await this.updateGlobalSettings({ exportSyncState: {} });
160067
+ if (id === "export-hap") await this.exportSyncState.set({});
159786
160068
  this.ctx.logger.info("export-hap: bridge removed", { meta: { instanceId: id } });
159787
160069
  }
159788
160070
  /**
@@ -160154,9 +160436,11 @@ var ExportHapAddon = class extends BaseAddon {
160154
160436
  return inst.accessoryUuidOf(inst.findEntry(deviceId)?.mapperKind ?? "camera", deviceId);
160155
160437
  }
160156
160438
  /** The reconcile cache of a bridge: the default one is persisted, the others live in memory (boot re-attach seeds them). */
160157
- syncStateOf(inst) {
160158
- return inst.id === "export-hap" ? syncStateFromJson(this.config.exportSyncState) : inst.syncState;
160439
+ async syncStateOf(inst) {
160440
+ return inst.id === "export-hap" ? syncStateFromJson(await this.exportSyncState.get()) : inst.syncState;
160159
160441
  }
160442
+ /** The persisted reconcile cache of the default bridge (store key `exportSyncState`). */
160443
+ exportSyncState = this.state("exportSyncState", ExportSyncStateSchema, {});
160160
160444
  /**
160161
160445
  * Export fingerprint of a device from its PERSISTED features + type
160162
160446
  * (`canonicalDeviceFingerprint`). Returns `null` on a transient API error or
@@ -160182,7 +160466,7 @@ var ExportHapAddon = class extends BaseAddon {
160182
160466
  deviceType: device.type,
160183
160467
  features: device.features
160184
160468
  });
160185
- const persisted = this.syncStateOf(inst).get(deviceId)?.fingerprint;
160469
+ const persisted = (await this.syncStateOf(inst)).get(deviceId)?.fingerprint;
160186
160470
  const withToken = withRecordabilityToken({
160187
160471
  base: fresh,
160188
160472
  token: await this.readRecordabilityToken(inst, deviceId, device.type),
@@ -160217,22 +160501,35 @@ var ExportHapAddon = class extends BaseAddon {
160217
160501
  return null;
160218
160502
  }
160219
160503
  }
160504
+ /** Tail of the pending cache writes of each bridge: a read-modify-write of one bridge never overlaps another. */
160505
+ syncWrites = /* @__PURE__ */ new Map();
160506
+ /** Run one read-modify-write of a bridge's reconcile cache after the previous one finished. */
160507
+ serialisedSyncWrite(inst, write) {
160508
+ const next = (this.syncWrites.get(inst.id) ?? Promise.resolve()).then(write);
160509
+ this.syncWrites.set(inst.id, next.catch(() => void 0));
160510
+ return next;
160511
+ }
160220
160512
  /** Persist a device's current export fingerprint into `exportSyncState`
160221
- * (best-effort; called after a successful attach). */
160222
- async persistFingerprint(inst, deviceId, fingerprint) {
160223
- const state = this.syncStateOf(inst);
160224
- state.set(deviceId, {
160225
- fingerprint,
160226
- externalIds: [this.hapAccessoryUuid(inst, deviceId)]
160513
+ * (best-effort; called after a successful attach). Serialised per bridge, so two attaches
160514
+ * finishing together cannot each write back a cache that lacks the other's entry. */
160515
+ persistFingerprint(inst, deviceId, fingerprint) {
160516
+ return this.serialisedSyncWrite(inst, async () => {
160517
+ const state = await this.syncStateOf(inst);
160518
+ state.set(deviceId, {
160519
+ fingerprint,
160520
+ externalIds: [this.hapAccessoryUuid(inst, deviceId)]
160521
+ });
160522
+ if (inst.id === "export-hap") await this.exportSyncState.set(syncStateToJson(state));
160227
160523
  });
160228
- if (inst.id === "export-hap") await this.updateGlobalSettings({ exportSyncState: syncStateToJson(state) });
160229
160524
  }
160230
- /** Drop a device's `exportSyncState` entry (on unexpose). */
160231
- async forgetFingerprint(inst, deviceId) {
160232
- const state = this.syncStateOf(inst);
160233
- if (!state.has(deviceId)) return;
160234
- state.delete(deviceId);
160235
- if (inst.id === "export-hap") await this.updateGlobalSettings({ exportSyncState: syncStateToJson(state) });
160525
+ /** Drop a device's `exportSyncState` entry (on unexpose). Serialised with the writes above. */
160526
+ forgetFingerprint(inst, deviceId) {
160527
+ return this.serialisedSyncWrite(inst, async () => {
160528
+ const state = await this.syncStateOf(inst);
160529
+ if (!state.has(deviceId)) return;
160530
+ state.delete(deviceId);
160531
+ if (inst.id === "export-hap") await this.exportSyncState.set(syncStateToJson(state));
160532
+ });
160236
160533
  }
160237
160534
  /**
160238
160535
  * Subscribe to a device-lifecycle event category and reconcile the exposed
@@ -160320,7 +160617,7 @@ var ExportHapAddon = class extends BaseAddon {
160320
160617
  log.debug("export-hap: reconcile skipped — fingerprint unavailable (transient)");
160321
160618
  return;
160322
160619
  }
160323
- const last = this.syncStateOf(inst).get(numericId);
160620
+ const last = (await this.syncStateOf(inst)).get(numericId);
160324
160621
  if (last?.fingerprint === current) {
160325
160622
  if (!inst.exposed.has(deviceId)) try {
160326
160623
  await this.attachMapper(inst, entry);
@@ -160837,4 +161134,4 @@ function errMsg(err) {
160837
161134
  return err instanceof Error ? err.message : String(err);
160838
161135
  }
160839
161136
  //#endregion
160840
- export { DEFAULT_CLIP_RETENTION_DAYS, DEFAULT_DEVICE_SETTINGS, EXPORT_HAP_ADDON_ID, ExportHapAddon, ExportHapAddon as default, exportHapActions as a, describeHksvCamera, unpublishAccessory as i, initHapStorage as n, publishStandalone as r, resolveClipRetentionDays, resolveKeepHomekitClips, resolveMultiTierService, deriveUsername as t };
161137
+ export { DEFAULT_CLIP_RETENTION_DAYS, DEFAULT_DEVICE_SETTINGS, EXPORT_HAP_ADDON_ID, ExportHapAddon, ExportHapAddon as default, ExportSyncStateSchema, exportHapActions as a, describeHksvCamera, unpublishAccessory as i, initHapStorage as n, publishStandalone as r, resolveClipRetentionDays, resolveKeepHomekitClips, resolveMultiTierService, deriveUsername as t };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@camstack/addon-export-hap",
3
- "version": "1.2.196",
3
+ "version": "1.2.197",
4
4
  "description": "HomeKit (HAP) exporter for CamStack devices. Publishes each exposed device as its own HomeKit accessory: cameras and doorbells with SRTP streaming, HomeKit Secure Video, motion, two-way audio, PTZ and battery; switches, lights, locks and sensors through a capability→service table.",
5
5
  "keywords": [
6
6
  "camstack",
@@ -67,7 +67,7 @@
67
67
  }
68
68
  ],
69
69
  "requires": {
70
- "server": ">=1.2.790"
70
+ "server": ">=1.2.791"
71
71
  }
72
72
  },
73
73
  "files": [