@camstack/addon-export-hap 1.2.200 → 1.2.202

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.
@@ -851,7 +851,7 @@ var EventCategory = /* @__PURE__ */ function(EventCategory) {
851
851
  return EventCategory;
852
852
  }({});
853
853
  //#endregion
854
- //#region ../types/dist/composed-stable-id-CPp3votu.mjs
854
+ //#region ../types/dist/composed-stable-id-iddnCQ51.mjs
855
855
  /**
856
856
  import { errMsg } from '@camstack/types'
857
857
  * Extract a human-readable message from an unknown error value.
@@ -1193,6 +1193,11 @@ var DeviceRole = /* @__PURE__ */ function(DeviceRole) {
1193
1193
  * with the switch's on/off only. Speed or oscillation appear only when the
1194
1194
  * device also has a fan cap (D1033). */
1195
1195
  DeviceRole["SwitchFan"] = "switch-fan";
1196
+ /** A relay driving an on/off-only lamp: drawn as a light (bulb and glow, no
1197
+ * slider), presented to the exports as a light with power only. Not a
1198
+ * `light` type: the provider owns the type, and a light implies brightness
1199
+ * or colour this relay lacks. */
1200
+ DeviceRole["SwitchLight"] = "switch-light";
1196
1201
  /** Air conditioner / split unit: cooling, fan speed, louvres. */
1197
1202
  DeviceRole["ClimateAc"] = "climate-ac";
1198
1203
  /** Room thermostat: a setpoint and a room temperature. The default. */
@@ -6093,7 +6098,7 @@ var ZodIssueCode = {
6093
6098
  var ZodFirstPartyTypeKind;
6094
6099
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
6095
6100
  //#endregion
6096
- //#region ../types/dist/sleep-DyIxjZZt.mjs
6101
+ //#region ../types/dist/sleep-BvVGLl30.mjs
6097
6102
  /**
6098
6103
  * The audio chunk plane's byte format, and the ONE expansion from a coded
6099
6104
  * window to float samples (D455).
@@ -10806,6 +10811,13 @@ var ACTUATOR_CAP_VOCABULARY = {
10806
10811
  },
10807
10812
  state: { on: { icon: "lightbulb" } }
10808
10813
  },
10814
+ [DeviceRole.SwitchLight]: {
10815
+ actions: {
10816
+ "switch.on": { icon: "lightbulb" },
10817
+ "switch.off": { icon: "lightbulb-off" }
10818
+ },
10819
+ state: { on: { icon: "lightbulb" } }
10820
+ },
10809
10821
  [DeviceRole.Chime]: { actions: {
10810
10822
  "switch.on": {
10811
10823
  label: t("Enable chime", "Attiva il campanello"),
@@ -17585,7 +17597,7 @@ Object.freeze({
17585
17597
  }
17586
17598
  });
17587
17599
  //#endregion
17588
- //#region ../types/dist/implemented-methods-5YMDeE3f.mjs
17600
+ //#region ../types/dist/implemented-methods-CSTk6zYK.mjs
17589
17601
  var AUDIO_ENCODER_BY_CODEC = {
17590
17602
  opus: "libopus",
17591
17603
  aac: "aac",
@@ -18235,6 +18247,60 @@ function portable(target) {
18235
18247
  }
18236
18248
  portable("linux64"), portable("linuxarm64"), portable("macarm64"), portable("mac64"), `${BASE}${FFMPEG_RELEASE}`;
18237
18249
  /**
18250
+ * A device's KIND is its type plus its role (D1033): the type is the set of
18251
+ * controls it has, the role says which thing it is among the devices that
18252
+ * share those controls. A plug-in heater is a `switch` with role
18253
+ * `switch-heater`; an air conditioner and a radiator valve are both `climate`,
18254
+ * told apart by their `climate-*` role.
18255
+ */
18256
+ /**
18257
+ * Type values a persisted row may still carry after the type was retired, and
18258
+ * the type each one is read as. The row is rewritten by the next registration
18259
+ * of the device (its provider stamps the live type), so this is a read alias,
18260
+ * not a migration.
18261
+ *
18262
+ * `heater` is deliberately absent: the only heaters were composed devices the
18263
+ * operator deletes. Such a row stays an unknown type, which every reader
18264
+ * treats as a generic device.
18265
+ */
18266
+ var RETIRED_DEVICE_TYPES = { thermostat: DeviceType.Climate };
18267
+ /** The live type a stored `type` value stands for (itself unless retired). */
18268
+ function canonicalStoredDeviceType(stored) {
18269
+ return RETIRED_DEVICE_TYPES[stored] ?? stored;
18270
+ }
18271
+ preprocess((value) => typeof value === "string" ? canonicalStoredDeviceType(value) : value, _enum(DeviceType));
18272
+ DeviceRole.ClimateThermostat, DeviceRole.ClimateAc, DeviceRole.ClimateRadiator, DeviceRole.ClimateFloor, DeviceRole.ClimateHeater, DeviceRole.ClimateHeatPumpCircuit;
18273
+ /**
18274
+ * A relay driving an on/off-only lamp (a `switch` with role `switch-light`):
18275
+ * drawn and exported as a light, with the switch's power only. The one place
18276
+ * that reads the role for it — a consumer asks this, never the role string.
18277
+ */
18278
+ function isSwitchLight(type, role) {
18279
+ return type === DeviceType.Switch && role === DeviceRole.SwitchLight;
18280
+ }
18281
+ /**
18282
+ * A smart plug (a `switch` with role `outlet`, D875): exported as a plug /
18283
+ * outlet. Exports ask this, never the role string.
18284
+ */
18285
+ function isOutlet(type, role) {
18286
+ return type === DeviceType.Switch && role === DeviceRole.Outlet;
18287
+ }
18288
+ /**
18289
+ * A plain fan behind a switch (a `switch` with role `switch-fan`): exported as
18290
+ * a fan with the switch's on/off only — no speed it does not have.
18291
+ */
18292
+ function isSwitchFan(type, role) {
18293
+ return type === DeviceType.Switch && role === DeviceRole.SwitchFan;
18294
+ }
18295
+ /**
18296
+ * A plug-in heater behind a switch (a `switch` with role `switch-heater`): it
18297
+ * has power only, no setpoint and no room temperature, so an export never
18298
+ * presents it as a thermostat.
18299
+ */
18300
+ function isSwitchHeater(type, role) {
18301
+ return type === DeviceType.Switch && role === DeviceRole.SwitchHeater;
18302
+ }
18303
+ /**
18238
18304
  * THE table "which boolean of this device type counts as HIGH", and the
18239
18305
  * pure evaluator of its EDGE.
18240
18306
  *
@@ -24162,7 +24228,7 @@ var DeviceTokenScopeSchema = object({
24162
24228
  function migrateLegacyTokenScope(raw) {
24163
24229
  if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return raw;
24164
24230
  if (Reflect.get(raw, "type") !== "device") return raw;
24165
- if (Reflect.get(raw, "selector") !== void 0) return raw;
24231
+ if (Reflect.get(raw, "selector") !== void 0) return canonicalSelectorTypes(raw);
24166
24232
  const targets = Reflect.get(raw, "targets");
24167
24233
  if (!Array.isArray(targets)) return raw;
24168
24234
  return {
@@ -24174,6 +24240,27 @@ function migrateLegacyTokenScope(raw) {
24174
24240
  access: Reflect.get(raw, "access")
24175
24241
  };
24176
24242
  }
24243
+ /**
24244
+ * A stored `types` selector may name a type D1033 retired (`thermostat`). The
24245
+ * grant is read back through this same preprocess, so the retired name is
24246
+ * rewritten to its canonical type here and {@link DeviceSelectorSchema} itself
24247
+ * stays a strict enum on the wire.
24248
+ */
24249
+ function canonicalSelectorTypes(raw) {
24250
+ const selector = Reflect.get(raw, "selector");
24251
+ if (selector === null || typeof selector !== "object") return raw;
24252
+ if (Reflect.get(selector, "kind") !== "types") return raw;
24253
+ const types = Reflect.get(selector, "types");
24254
+ if (!Array.isArray(types)) return raw;
24255
+ const canonical = types.map((t) => typeof t === "string" ? canonicalStoredDeviceType(t) : t);
24256
+ return {
24257
+ ...raw,
24258
+ selector: {
24259
+ ...selector,
24260
+ types: canonical
24261
+ }
24262
+ };
24263
+ }
24177
24264
  var TokenScopeSchema = preprocess(migrateLegacyTokenScope, discriminatedUnion("type", [
24178
24265
  object({
24179
24266
  type: literal("category"),
@@ -52228,8 +52315,8 @@ function actuator(input) {
52228
52315
  };
52229
52316
  }
52230
52317
  new Map(GROUP_TEMPLATES.map((template) => [template.id, template]));
52231
- DeviceFeature.LightColorRgb, DeviceFeature.LightColorHsv, DeviceFeature.LightColorMired;
52232
52318
  DeviceType.Camera;
52319
+ DeviceFeature.LightColorRgb, DeviceFeature.LightColorHsv, DeviceFeature.LightColorMired;
52233
52320
  var PowerSourceRefusalReasonSchema = _enum([
52234
52321
  "no-power-source",
52235
52322
  "switch-missing",
@@ -57714,6 +57801,15 @@ var HeroTextSchema = object({
57714
57801
  it: string()
57715
57802
  });
57716
57803
  /**
57804
+ * What a device that has not reported says in place of its value: an empty "—",
57805
+ * never a word like "Unknown" and never a 0 (D393). The card stays its normal
57806
+ * self; only the value is empty.
57807
+ */
57808
+ var NOT_REPORTED = {
57809
+ en: "—",
57810
+ it: "—"
57811
+ };
57812
+ /**
57717
57813
  * The ONE measurement a simple sensor shows (card wave, phase 1).
57718
57814
  *
57719
57815
  * A sensor that measures a single quantity (a temperature, a humidity, a power,
@@ -57830,6 +57926,62 @@ function textMeasurement(text, since) {
57830
57926
  historyKey: null
57831
57927
  };
57832
57928
  }
57929
+ /** What each quantity draws beside its value, reported or not. */
57930
+ var QUANTITY_FACE = {
57931
+ temperature: {
57932
+ icon: "thermometer",
57933
+ unit: "°C",
57934
+ sinceKind: "updated",
57935
+ historyKey: "cap:temperature-sensor.temperature"
57936
+ },
57937
+ humidity: {
57938
+ icon: "droplets",
57939
+ unit: "%",
57940
+ sinceKind: "updated",
57941
+ historyKey: "cap:humidity-sensor.humidity"
57942
+ },
57943
+ power: {
57944
+ icon: "zap",
57945
+ unit: "W",
57946
+ sinceKind: "updated",
57947
+ historyKey: "cap:power-meter.power"
57948
+ },
57949
+ contact: {
57950
+ icon: null,
57951
+ unit: null,
57952
+ sinceKind: "changed",
57953
+ historyKey: null
57954
+ },
57955
+ text: {
57956
+ icon: null,
57957
+ unit: null,
57958
+ sinceKind: "updated",
57959
+ historyKey: null
57960
+ }
57961
+ };
57962
+ /**
57963
+ * The measurement of a sensor that has not reported yet: its normal card with
57964
+ * an empty "—" value and its unit — never a placeholder, never a 0 (D393). The
57965
+ * reading is `null` (nothing to format), the scene does not move, and nothing
57966
+ * claims a moment.
57967
+ */
57968
+ function emptyMeasurement(quantity) {
57969
+ const face = QUANTITY_FACE[quantity];
57970
+ return {
57971
+ quantity,
57972
+ reading: null,
57973
+ icon: face.icon,
57974
+ value: NOT_REPORTED,
57975
+ unit: face.unit,
57976
+ band: null,
57977
+ level: null,
57978
+ word: NOT_REPORTED,
57979
+ tone: "muted",
57980
+ since: null,
57981
+ sinceKind: face.sinceKind,
57982
+ historyKey: face.historyKey
57983
+ };
57984
+ }
57833
57985
  /** The scene as the model carries it. `null` = the device did not say (never a guess). */
57834
57986
  var HeroSceneSchema = object({
57835
57987
  id: _enum([
@@ -57880,7 +58032,7 @@ var HeroSceneSchema = object({
57880
58032
  level: number$1().min(0).max(1).nullable()
57881
58033
  });
57882
58034
  DeviceType.Camera, DeviceType.Hub, DeviceType.Light, DeviceType.Siren, DeviceType.Switch, DeviceType.Sensor, DeviceType.Climate, DeviceType.Button, DeviceType.EventEmitter, DeviceType.Update, DeviceType.Generic, DeviceType.Notifier, DeviceType.Script, DeviceType.Automation, DeviceType.Lock, DeviceType.Cover, DeviceType.Valve, DeviceType.Humidifier, DeviceType.WaterHeater, DeviceType.HeatPump, DeviceType.Fan, DeviceType.MediaPlayer, DeviceType.AlarmPanel, DeviceType.Control, DeviceType.Presence, DeviceType.Weather, DeviceType.Vacuum, DeviceType.LawnMower, DeviceType.Container, DeviceType.Image, DeviceType.PetFeeder, DeviceType.PetFountain, DeviceType.Dishwasher, DeviceType.Washer, DeviceType.Dryer, DeviceType.Gateway;
57883
- DeviceRole.Siren, DeviceRole.Floodlight, DeviceRole.Spotlight, DeviceRole.PirSensor, DeviceRole.Chime, DeviceRole.Autotrack, DeviceRole.Nightvision, DeviceRole.PrivacyMask, DeviceRole.Doorbell, DeviceRole.CoverBlind, DeviceRole.CoverShutter, DeviceRole.CoverAwning, DeviceRole.CoverCurtain, DeviceRole.CoverGarage, DeviceRole.CoverGate, DeviceRole.CoverDoor, DeviceRole.CoverWindow, DeviceRole.BinaryHelper, DeviceRole.Outlet, DeviceRole.SwitchHeater, DeviceRole.SwitchFan, DeviceRole.ClimateAc, DeviceRole.ClimateThermostat, DeviceRole.ClimateFloor, DeviceRole.ClimateRadiator, DeviceRole.ClimateHeater, DeviceRole.ClimateHeatPumpCircuit, DeviceRole.MotionSensor, DeviceRole.ContactSensor, DeviceRole.LeakSensor, DeviceRole.SmokeSensor, DeviceRole.COSensor, DeviceRole.GasSensor, DeviceRole.TamperSensor, DeviceRole.VibrationSensor, DeviceRole.ConnectivitySensor, DeviceRole.SoundSensor, DeviceRole.BinarySensor, DeviceRole.TemperatureSensor, DeviceRole.HumiditySensor, DeviceRole.AmbientLightSensor, DeviceRole.PressureSensor, DeviceRole.WindSensor, DeviceRole.RainSensor, DeviceRole.UvSensor, DeviceRole.SolarRadiationSensor, DeviceRole.SoilMoistureSensor, DeviceRole.PowerSensor, DeviceRole.EnergySensor, DeviceRole.VoltageSensor, DeviceRole.CurrentSensor, DeviceRole.AirQualitySensor, DeviceRole.BatterySensor, DeviceRole.NumericSensor, DeviceRole.EnumSensor, DeviceRole.DateTimeSensor, DeviceRole.GenericSensor, DeviceRole.NumericControl, DeviceRole.SelectControl, DeviceRole.TextControl, DeviceRole.DateTimeControl, DeviceRole.MobilePushNotifier, DeviceRole.MessagingNotifier, DeviceRole.EmailNotifier, DeviceRole.GenericNotifier, DeviceRole.IrTransmitter;
58035
+ DeviceRole.Siren, DeviceRole.Floodlight, DeviceRole.Spotlight, DeviceRole.PirSensor, DeviceRole.Chime, DeviceRole.Autotrack, DeviceRole.Nightvision, DeviceRole.PrivacyMask, DeviceRole.Doorbell, DeviceRole.CoverBlind, DeviceRole.CoverShutter, DeviceRole.CoverAwning, DeviceRole.CoverCurtain, DeviceRole.CoverGarage, DeviceRole.CoverGate, DeviceRole.CoverDoor, DeviceRole.CoverWindow, DeviceRole.BinaryHelper, DeviceRole.Outlet, DeviceRole.SwitchHeater, DeviceRole.SwitchFan, DeviceRole.SwitchLight, DeviceRole.ClimateAc, DeviceRole.ClimateThermostat, DeviceRole.ClimateFloor, DeviceRole.ClimateRadiator, DeviceRole.ClimateHeater, DeviceRole.ClimateHeatPumpCircuit, DeviceRole.MotionSensor, DeviceRole.ContactSensor, DeviceRole.LeakSensor, DeviceRole.SmokeSensor, DeviceRole.COSensor, DeviceRole.GasSensor, DeviceRole.TamperSensor, DeviceRole.VibrationSensor, DeviceRole.ConnectivitySensor, DeviceRole.SoundSensor, DeviceRole.BinarySensor, DeviceRole.TemperatureSensor, DeviceRole.HumiditySensor, DeviceRole.AmbientLightSensor, DeviceRole.PressureSensor, DeviceRole.WindSensor, DeviceRole.RainSensor, DeviceRole.UvSensor, DeviceRole.SolarRadiationSensor, DeviceRole.SoilMoistureSensor, DeviceRole.PowerSensor, DeviceRole.EnergySensor, DeviceRole.VoltageSensor, DeviceRole.CurrentSensor, DeviceRole.AirQualitySensor, DeviceRole.BatterySensor, DeviceRole.NumericSensor, DeviceRole.EnumSensor, DeviceRole.DateTimeSensor, DeviceRole.GenericSensor, DeviceRole.NumericControl, DeviceRole.SelectControl, DeviceRole.TextControl, DeviceRole.DateTimeControl, DeviceRole.MobilePushNotifier, DeviceRole.MessagingNotifier, DeviceRole.EmailNotifier, DeviceRole.GenericNotifier, DeviceRole.IrTransmitter;
57884
58036
  var HeroRowIdSchema = _enum([
57885
58037
  "progress",
57886
58038
  "run-for",
@@ -80985,8 +81137,6 @@ var AccessoryKind = {
80985
81137
  };
80986
81138
  AccessoryKind.Siren, AccessoryKind.Floodlight, AccessoryKind.Spotlight, AccessoryKind.PirSensor, AccessoryKind.Chime, AccessoryKind.Autotrack, AccessoryKind.Nightvision, AccessoryKind.PrivacyMask;
80987
81139
  DeviceType.HeatPump;
80988
- DeviceType.Climate;
80989
- DeviceRole.ClimateThermostat, DeviceRole.ClimateAc, DeviceRole.ClimateRadiator, DeviceRole.ClimateFloor, DeviceRole.ClimateHeater, DeviceRole.ClimateHeatPumpCircuit;
80990
81140
  DeviceType.Cover, DeviceType.Valve, DeviceType.Humidifier, DeviceType.WaterHeater, DeviceType.HeatPump, DeviceType.Camera, DeviceType.Hub, DeviceType.Switch, DeviceType.Siren, DeviceType.Light, DeviceType.Fan, DeviceType.Sensor, DeviceType.Climate, DeviceType.Button, DeviceType.EventEmitter, DeviceType.Update, DeviceType.Generic, DeviceType.Notifier, DeviceType.Script, DeviceType.Automation, DeviceType.Lock, DeviceType.MediaPlayer, DeviceType.AlarmPanel, DeviceType.Control, DeviceType.Presence, DeviceType.Weather, DeviceType.Vacuum, DeviceType.LawnMower, DeviceType.Container, DeviceType.Image, DeviceType.PetFeeder, DeviceType.PetFountain, DeviceType.Dishwasher, DeviceType.Washer, DeviceType.Dryer, DeviceType.Gateway;
80991
81141
  new Set(Object.values(DeviceType));
80992
81142
  /** Parses the raw slice with the cap's own schema; `undefined` when it does not parse. */
@@ -81125,7 +81275,7 @@ var lockContribution = contribution("lock-control", LockControlStatusSchema, (sl
81125
81275
  const state = slice?.state ?? null;
81126
81276
  const words = state === null ? null : LOCK_WORDS[state];
81127
81277
  const since = slice === void 0 ? null : elapsedText(slice.lastChangedAt, ctx.now);
81128
- const title = words?.title ?? t("Unknown", "Sconosciuto");
81278
+ const title = words?.title ?? NOT_REPORTED;
81129
81279
  return {
81130
81280
  reading: reading("lock-control", words?.state ?? "unknown", false, words?.title),
81131
81281
  rows: [row$1("lock", state === "locked" || state === "locking" ? "lock" : "lock-open", joinText([title, since]), lockControls(state, ctx.features.includes(DeviceFeature.LockOpen)))],
@@ -81217,7 +81367,7 @@ var ACCESS_FAMILY_CONTRIBUTIONS = {
81217
81367
  const modes = slice === void 0 ? ALARM_MODES : slice.availableModes;
81218
81368
  return {
81219
81369
  reading: reading("alarm-panel", words?.state ?? "unknown", false, words?.title),
81220
- rows: [row$1("alarm", state === "triggered" ? "shield-alert" : state === "disarmed" ? "shield-off" : "shield-check", joinText([words?.title ?? t("Unknown", "Sconosciuto"), since]), alarmControls(state, modes, slice?.requiresCode ?? false))],
81370
+ rows: [row$1("alarm", state === "triggered" ? "shield-alert" : state === "disarmed" ? "shield-off" : "shield-check", joinText([words?.title ?? NOT_REPORTED, since]), alarmControls(state, modes, slice?.requiresCode ?? false))],
81221
81371
  ...since === null || words === null ? {} : { facts: [fact("since", "clock", since, state === "triggered" ? "danger" : "muted")] },
81222
81372
  ...words === null ? {} : { tiles: {
81223
81373
  left: [{
@@ -81248,7 +81398,7 @@ var ACCESS_FAMILY_CONTRIBUTIONS = {
81248
81398
  return {
81249
81399
  reading: reading("automation-control", state, false, title),
81250
81400
  rows: [row$1("automation", "workflow", joinText([
81251
- title ?? t("Unknown", "Sconosciuto"),
81401
+ title ?? NOT_REPORTED,
81252
81402
  last === null ? null : t(`Ran ${last.en}`, `Eseguita ${last.it}`),
81253
81403
  slice?.lastError == null ? null : t(slice.lastError, slice.lastError)
81254
81404
  ]), [asAction(run), toggle])],
@@ -81264,7 +81414,7 @@ var ACCESS_FAMILY_CONTRIBUTIONS = {
81264
81414
  return {
81265
81415
  reading: reading("script-runner", state, false, title),
81266
81416
  rows: [row$1("script", "scroll-text", joinText([
81267
- title ?? t("Unknown", "Sconosciuto"),
81417
+ title ?? NOT_REPORTED,
81268
81418
  last === null ? null : t(`Ran ${last.en}`, `Eseguito ${last.it}`),
81269
81419
  slice?.lastError == null ? null : t(slice.lastError, slice.lastError)
81270
81420
  ]), [asAction(control)])],
@@ -81273,7 +81423,7 @@ var ACCESS_FAMILY_CONTRIBUTIONS = {
81273
81423
  }),
81274
81424
  "do-not-disturb": contribution("do-not-disturb", DoNotDisturbStatusSchema, (slice) => {
81275
81425
  const on = slice?.enabled ?? null;
81276
- return { rows: [row$1("do-not-disturb", "bell-off", on === null ? t("Unknown", "Sconosciuto") : on ? t("Do not disturb on", "Non disturbare attivo") : t("Do not disturb off", "Non disturbare spento"), [{
81426
+ return { rows: [row$1("do-not-disturb", "bell-off", on === null ? NOT_REPORTED : on ? t("Do not disturb on", "Non disturbare attivo") : t("Do not disturb off", "Non disturbare spento"), [{
81277
81427
  kind: "toggle",
81278
81428
  id: "do-not-disturb.toggle",
81279
81429
  label: t("Do not disturb", "Non disturbare"),
@@ -81291,7 +81441,7 @@ var ACCESS_FAMILY_CONTRIBUTIONS = {
81291
81441
  * is absent from the facts, never a zero (D393).
81292
81442
  */
81293
81443
  var has$3 = (ctx, f) => ctx.features.includes(f);
81294
- var unknownText = t("Unknown", "Sconosciuto");
81444
+ var unknownText = NOT_REPORTED;
81295
81445
  var pct$2 = (n) => t(`${Math.round(n)}%`, `${Math.round(n)}%`);
81296
81446
  var unit = (n) => Math.min(1, Math.max(0, n / 100));
81297
81447
  /** Battery as a fact, unless the device is also bound to the `battery` cap (it already says so). */
@@ -82697,13 +82847,13 @@ function sensorFragment(value, id, icon, en, it, text) {
82697
82847
  tiles: { right: [tile$1(en, it, text)] }
82698
82848
  };
82699
82849
  }
82700
- var temperatureContribution = contribution("temperature-sensor", TemperatureSensorStatusSchema, (slice) => measured(sensorFragment(slice?.temperature ?? null, "temperature", "thermometer", "Temperature", "Temperatura", formatDegrees(slice?.temperature ?? 0)), slice?.temperature == null ? void 0 : temperatureMeasurement(slice.temperature, slice.lastFetchedAt)));
82701
- var humidityContribution = contribution("humidity-sensor", HumiditySensorStatusSchema, (slice) => measured(sensorFragment(slice?.humidity ?? null, "humidity", "droplets", "Humidity", "Umidità", `${Math.round(slice?.humidity ?? 0)}%`), slice?.humidity == null ? void 0 : humidityMeasurement(slice.humidity, slice.lastFetchedAt)));
82850
+ var temperatureContribution = contribution("temperature-sensor", TemperatureSensorStatusSchema, (slice) => measured(sensorFragment(slice?.temperature ?? null, "temperature", "thermometer", "Temperature", "Temperatura", formatDegrees(slice?.temperature ?? 0)), slice?.temperature == null ? emptyMeasurement("temperature") : temperatureMeasurement(slice.temperature, slice.lastFetchedAt)));
82851
+ var humidityContribution = contribution("humidity-sensor", HumiditySensorStatusSchema, (slice) => measured(sensorFragment(slice?.humidity ?? null, "humidity", "droplets", "Humidity", "Umidità", `${Math.round(slice?.humidity ?? 0)}%`), slice?.humidity == null ? emptyMeasurement("humidity") : humidityMeasurement(slice.humidity, slice.lastFetchedAt)));
82702
82852
  var pressureContribution = contribution("pressure-sensor", PressureSensorStatusSchema, (slice) => sensorFragment(slice?.pressure ?? null, "pressure", "gauge", "Pressure", "Pressione", `${Math.round(slice?.pressure ?? 0)} hPa`));
82703
82853
  var illuminanceContribution = contribution("ambient-light-sensor", AmbientLightSensorStatusSchema, (slice) => sensorFragment(slice?.illuminance ?? null, "illuminance", "sun", "Light", "Luce", `${Math.round(slice?.illuminance ?? 0)} lx`));
82704
82854
  var numericContribution = contribution("numeric-sensor", NumericSensorStatusSchema, (slice) => sensorFragment(slice?.value ?? null, "reading", "gauge", "Value", "Valore", String(Number((slice?.value ?? 0).toFixed(2)))));
82705
82855
  var enumContribution = contribution("enum-sensor", EnumSensorStatusSchema, (slice) => {
82706
- if (slice === void 0 || slice.value === "") return { reading: reading("sensor", "unknown") };
82856
+ if (slice === void 0 || slice.value === "") return measured({ reading: reading("sensor", "unknown") }, emptyMeasurement("text"));
82707
82857
  if (slice.timestamp === true) return { reading: reading("sensor", "on") };
82708
82858
  return measured(sensorFragment(slice.value, "reading", "gauge", "State", "Stato", slice.value), textMeasurement(slice.value, slice.lastFetchedAt));
82709
82859
  });
@@ -82827,7 +82977,7 @@ function circuitControl(circuit) {
82827
82977
  return picker(`heat-pump.${circuit.id}.mode`, t("Mode", "Modalità"), circuit.operationMode, method, args);
82828
82978
  }
82829
82979
  /** A circuit with no reading is still a row: it shows that nothing is known, not nothing. */
82830
- var UNKNOWN_STATUS = same("—");
82980
+ var UNKNOWN_STATUS = NOT_REPORTED;
82831
82981
  function circuitRow(circuit) {
82832
82982
  const control = circuitControl(circuit);
82833
82983
  const status = thermalStatusText(circuit.targetTemp, circuit.currentTemp) ?? UNKNOWN_STATUS;
@@ -83051,9 +83201,8 @@ function look(icon, tone, background, animation) {
83051
83201
  animation
83052
83202
  };
83053
83203
  }
83054
- /** A state a device is in whatever it is: unreachable, or silent. Identical for every look. */
83204
+ /** Unreachable: identical for every look. */
83055
83205
  var OFFLINE = look("wifi-off", "muted", "plain", "none");
83056
- var UNKNOWN = look("circle-question-mark", "muted", "plain", "none");
83057
83206
  var ALERT = look("triangle-alert", "danger", "alert-wash", "pulse");
83058
83207
  function lookOf(spec) {
83059
83208
  const at = (s) => look(spec.icon, s[0], s[1], s[2]);
@@ -83065,7 +83214,7 @@ function lookOf(spec) {
83065
83214
  standby: at(spec.standby),
83066
83215
  alert: spec.alert ?? ALERT,
83067
83216
  offline: OFFLINE,
83068
- unknown: UNKNOWN
83217
+ unknown: look(spec.icon, "muted", "plain", "none")
83069
83218
  };
83070
83219
  }
83071
83220
  var MUTED = [
@@ -83674,7 +83823,7 @@ lookOf({
83674
83823
  });
83675
83824
  DeviceType.Climate;
83676
83825
  DeviceType.Camera, DeviceType.Hub, DeviceType.Light, DeviceType.Siren, DeviceType.Switch, DeviceType.Sensor, DeviceType.Climate, DeviceType.Button, DeviceType.EventEmitter, DeviceType.Update, DeviceType.Generic, DeviceType.Notifier, DeviceType.Script, DeviceType.Automation, DeviceType.Lock, DeviceType.Cover, DeviceType.Valve, DeviceType.Humidifier, DeviceType.WaterHeater, DeviceType.HeatPump, DeviceType.Fan, DeviceType.MediaPlayer, DeviceType.AlarmPanel, DeviceType.Control, DeviceType.Presence, DeviceType.Weather, DeviceType.Vacuum, DeviceType.LawnMower, DeviceType.Container, DeviceType.Image, DeviceType.PetFeeder, DeviceType.PetFountain, DeviceType.Dishwasher, DeviceType.Washer, DeviceType.Dryer, DeviceType.Gateway;
83677
- DeviceRole.Siren, DeviceRole.Floodlight, DeviceRole.Spotlight, DeviceRole.PirSensor, DeviceRole.Chime, DeviceRole.Autotrack, DeviceRole.Nightvision, DeviceRole.PrivacyMask, DeviceRole.Doorbell, DeviceRole.CoverBlind, DeviceRole.CoverShutter, DeviceRole.CoverAwning, DeviceRole.CoverCurtain, DeviceRole.CoverGarage, DeviceRole.CoverGate, DeviceRole.CoverDoor, DeviceRole.CoverWindow, DeviceRole.BinaryHelper, DeviceRole.Outlet, DeviceRole.SwitchHeater, DeviceRole.SwitchFan, DeviceRole.ClimateAc, DeviceRole.ClimateThermostat, DeviceRole.ClimateFloor, DeviceRole.ClimateRadiator, DeviceRole.ClimateHeater, DeviceRole.ClimateHeatPumpCircuit, DeviceRole.MotionSensor, DeviceRole.ContactSensor, DeviceRole.LeakSensor, DeviceRole.SmokeSensor, DeviceRole.COSensor, DeviceRole.GasSensor, DeviceRole.TamperSensor, DeviceRole.VibrationSensor, DeviceRole.ConnectivitySensor, DeviceRole.SoundSensor, DeviceRole.BinarySensor, DeviceRole.TemperatureSensor, DeviceRole.HumiditySensor, DeviceRole.AmbientLightSensor, DeviceRole.PressureSensor, DeviceRole.WindSensor, DeviceRole.RainSensor, DeviceRole.UvSensor, DeviceRole.SolarRadiationSensor, DeviceRole.SoilMoistureSensor, DeviceRole.PowerSensor, DeviceRole.EnergySensor, DeviceRole.VoltageSensor, DeviceRole.CurrentSensor, DeviceRole.AirQualitySensor, DeviceRole.BatterySensor, DeviceRole.NumericSensor, DeviceRole.EnumSensor, DeviceRole.DateTimeSensor, DeviceRole.GenericSensor, DeviceRole.NumericControl, DeviceRole.SelectControl, DeviceRole.TextControl, DeviceRole.DateTimeControl, DeviceRole.MobilePushNotifier, DeviceRole.MessagingNotifier, DeviceRole.EmailNotifier, DeviceRole.GenericNotifier, DeviceRole.IrTransmitter;
83826
+ DeviceRole.Siren, DeviceRole.Floodlight, DeviceRole.Spotlight, DeviceRole.PirSensor, DeviceRole.Chime, DeviceRole.Autotrack, DeviceRole.Nightvision, DeviceRole.PrivacyMask, DeviceRole.Doorbell, DeviceRole.CoverBlind, DeviceRole.CoverShutter, DeviceRole.CoverAwning, DeviceRole.CoverCurtain, DeviceRole.CoverGarage, DeviceRole.CoverGate, DeviceRole.CoverDoor, DeviceRole.CoverWindow, DeviceRole.BinaryHelper, DeviceRole.Outlet, DeviceRole.SwitchHeater, DeviceRole.SwitchFan, DeviceRole.SwitchLight, DeviceRole.ClimateAc, DeviceRole.ClimateThermostat, DeviceRole.ClimateFloor, DeviceRole.ClimateRadiator, DeviceRole.ClimateHeater, DeviceRole.ClimateHeatPumpCircuit, DeviceRole.MotionSensor, DeviceRole.ContactSensor, DeviceRole.LeakSensor, DeviceRole.SmokeSensor, DeviceRole.COSensor, DeviceRole.GasSensor, DeviceRole.TamperSensor, DeviceRole.VibrationSensor, DeviceRole.ConnectivitySensor, DeviceRole.SoundSensor, DeviceRole.BinarySensor, DeviceRole.TemperatureSensor, DeviceRole.HumiditySensor, DeviceRole.AmbientLightSensor, DeviceRole.PressureSensor, DeviceRole.WindSensor, DeviceRole.RainSensor, DeviceRole.UvSensor, DeviceRole.SolarRadiationSensor, DeviceRole.SoilMoistureSensor, DeviceRole.PowerSensor, DeviceRole.EnergySensor, DeviceRole.VoltageSensor, DeviceRole.CurrentSensor, DeviceRole.AirQualitySensor, DeviceRole.BatterySensor, DeviceRole.NumericSensor, DeviceRole.EnumSensor, DeviceRole.DateTimeSensor, DeviceRole.GenericSensor, DeviceRole.NumericControl, DeviceRole.SelectControl, DeviceRole.TextControl, DeviceRole.DateTimeControl, DeviceRole.MobilePushNotifier, DeviceRole.MessagingNotifier, DeviceRole.EmailNotifier, DeviceRole.GenericNotifier, DeviceRole.IrTransmitter;
83678
83827
  Object.freeze({
83679
83828
  "accessories.getStatus": {
83680
83829
  capName: "accessories",
@@ -94155,6 +94304,10 @@ function applianceExport(ecosystem, deviceType) {
94155
94304
  if (!isPlugApplianceType(deviceType)) return null;
94156
94305
  return APPLIANCE_EXPORT[ecosystem][deviceType];
94157
94306
  }
94307
+ DeviceType.Camera, DeviceType.Hub, DeviceType.Light, DeviceType.Siren, DeviceType.Switch, DeviceType.Sensor, DeviceType.Climate, DeviceType.HeatPump, DeviceType.Button, DeviceType.EventEmitter, DeviceType.Update, DeviceType.Generic, DeviceType.Notifier, DeviceType.Script, DeviceType.Automation, DeviceType.Lock, DeviceType.Cover, DeviceType.Valve, DeviceType.Humidifier, DeviceType.WaterHeater, DeviceType.Fan, DeviceType.MediaPlayer, DeviceType.AlarmPanel, DeviceType.Control, DeviceType.Presence, DeviceType.Weather, DeviceType.Vacuum, DeviceType.LawnMower, DeviceType.Container, DeviceType.Image, DeviceType.PetFeeder, DeviceType.PetFountain, DeviceType.Dishwasher, DeviceType.Washer, DeviceType.Dryer, DeviceType.Gateway;
94308
+ DeviceRole.Siren, DeviceRole.Floodlight, DeviceRole.Spotlight, DeviceRole.PirSensor, DeviceRole.Chime, DeviceRole.Autotrack, DeviceRole.Nightvision, DeviceRole.PrivacyMask, DeviceRole.Doorbell, DeviceRole.CoverBlind, DeviceRole.CoverShutter, DeviceRole.CoverAwning, DeviceRole.CoverCurtain, DeviceRole.CoverGarage, DeviceRole.CoverGate, DeviceRole.CoverDoor, DeviceRole.CoverWindow, DeviceRole.BinaryHelper, DeviceRole.Outlet, DeviceRole.SwitchHeater, DeviceRole.SwitchFan, DeviceRole.SwitchLight, DeviceRole.ClimateAc, DeviceRole.ClimateThermostat, DeviceRole.ClimateFloor, DeviceRole.ClimateRadiator, DeviceRole.ClimateHeater, DeviceRole.ClimateHeatPumpCircuit, DeviceRole.MotionSensor, DeviceRole.ContactSensor, DeviceRole.LeakSensor, DeviceRole.SmokeSensor, DeviceRole.COSensor, DeviceRole.GasSensor, DeviceRole.TamperSensor, DeviceRole.VibrationSensor, DeviceRole.ConnectivitySensor, DeviceRole.SoundSensor, DeviceRole.BinarySensor, DeviceRole.TemperatureSensor, DeviceRole.HumiditySensor, DeviceRole.AmbientLightSensor, DeviceRole.PressureSensor, DeviceRole.WindSensor, DeviceRole.RainSensor, DeviceRole.UvSensor, DeviceRole.SolarRadiationSensor, DeviceRole.SoilMoistureSensor, DeviceRole.PowerSensor, DeviceRole.EnergySensor, DeviceRole.VoltageSensor, DeviceRole.CurrentSensor, DeviceRole.AirQualitySensor, DeviceRole.BatterySensor, DeviceRole.NumericSensor, DeviceRole.EnumSensor, DeviceRole.DateTimeSensor, DeviceRole.GenericSensor, DeviceRole.NumericControl, DeviceRole.SelectControl, DeviceRole.TextControl, DeviceRole.DateTimeControl, DeviceRole.MobilePushNotifier, DeviceRole.MessagingNotifier, DeviceRole.EmailNotifier, DeviceRole.GenericNotifier, DeviceRole.IrTransmitter;
94309
+ new Set(Object.values(DeviceType));
94310
+ new Set(Object.values(DeviceRole));
94158
94311
  Object.freeze({
94159
94312
  "accessories.getStatus": [{
94160
94313
  name: "deviceId",
@@ -146262,446 +146415,6 @@ async function resolveDefaultBridge(ports) {
146262
146415
  };
146263
146416
  }
146264
146417
  //#endregion
146265
- //#region src/migrations/hub-node-fields.ts
146266
- /**
146267
- * Fields stored once for the cluster that are facts of ONE node become node settings (D986): a
146268
- * node's row is `<addonId>.<key>@<nodeId>` carrying `nodeId`, and a node never falls back to a
146269
- * bare row. This owner is placed `hub-only`, so the one node that ever held a value is the hub:
146270
- * each bare row is COPIED to `<key>@hub`. The bare row stays for a release (a copy, not a move),
146271
- * and a value already on the node row is never overwritten (a seed never overwrites).
146272
- *
146273
- * A keychain marker is copied verbatim: it names the owner and the secret, not the row that
146274
- * points at it. Idempotent: with every bare row copied the plan is empty.
146275
- */
146276
- /** The canonical settings table: one row per key, id `<addonId>.<key>`. */
146277
- var ADDON_SETTINGS_TABLE = "addon-settings";
146278
- var nodeKeyOf = (key) => `${key}@hub`;
146279
- async function planHubNodeFields(addonId, keys, ports) {
146280
- const stored = await ports.readStored([...keys, ...keys.map(nodeKeyOf)]);
146281
- const pending = keys.filter((key) => key in stored && !(nodeKeyOf(key) in stored));
146282
- if (pending.length === 0) return { edits: [] };
146283
- const rowId = (key) => `${addonId}.${nodeKeyOf(key)}`;
146284
- return { edits: [{
146285
- op: "setKeys",
146286
- scope: ADDON_SETTINGS_TABLE,
146287
- values: Object.fromEntries(pending.map((key) => [rowId(key), {
146288
- addonId,
146289
- key: nodeKeyOf(key),
146290
- value: stored[key],
146291
- nodeId: "hub"
146292
- }])),
146293
- precondition: preconditionOf(Object.fromEntries(pending.map((key) => [rowId(key), null])))
146294
- }] };
146295
- }
146296
- /**
146297
- * The port's read over an addon's three-way key read: each of `keys` that has a row, raw. A key
146298
- * the store could not answer for throws, so the migration fails instead of treating a failed read
146299
- * as "nothing to copy".
146300
- */
146301
- async function readRawKeys(read, addonId, keys) {
146302
- const found = {};
146303
- for (const key of keys) {
146304
- const answer = await read(key);
146305
- if (answer.kind === "unreadable") throw new Error(`${addonId}: the setting ${key} cannot be read (${answer.reason})`);
146306
- if (answer.kind === "present") found[key] = answer.value;
146307
- }
146308
- return found;
146309
- }
146310
- //#endregion
146311
- //#region src/migrations/fixed-pin-to-keychain.ts
146312
- /**
146313
- * The fixed HomeKit setup code pairs a controller with the bridge: a credential. It was a plain
146314
- * text setting, stored inline in the settings row; it is a `password` field now (D783), and a
146315
- * password lives in the keychain with a marker in the row. This procedure moves a stored inline
146316
- * code there, through the operator write path (the one that stores an inline value of a
146317
- * pre-keychain addon as a keychain secret).
146318
- *
146319
- * Idempotent: an absent, empty or already marker-backed code is `already-done`, so a crash
146320
- * between the keychain write and the ledger row costs nothing on the rerun.
146321
- */
146322
- async function moveFixedPinToKeychain(ports) {
146323
- const stored = (await ports.readStored(["fixedPin"]))["fixedPin"];
146324
- if (typeof stored !== "string" || stored === "" || isSecretMarker(stored)) return {
146325
- outcome: "already-done",
146326
- summary: { moved: false }
146327
- };
146328
- await ports.storeFixedPin(stored);
146329
- return {
146330
- outcome: "done",
146331
- summary: { moved: true }
146332
- };
146333
- }
146334
- //#endregion
146335
- //#region src/migrations/exposure-to-record.ts
146336
- /**
146337
- * The exposure lists the addon kept in its settings (`exposed`: the devices it mirrors, with
146338
- * their per-device settings; `exposedActions`: the actions it publishes) move into the
146339
- * `hap-bridge-exports` record of the default instance (D985, D996). Two migrations, in order:
146340
- *
146341
- * 1. `moveExposureToRecord` (procedure): put the record with `ifRev: 0`, read it BACK and
146342
- * compare it with what the settings carried; a record that does not hold the same lists
146343
- * throws and the settings are kept. An existing record is never overwritten.
146344
- * 2. `planDropExposureKeys` (plan): the two keys are deleted from the canonical `addon-settings`
146345
- * rows, and only while the record holds exactly what they carry. A record that differs (the
146346
- * operator edited the lists since) keeps the old keys, which nothing reads any more.
146347
- *
146348
- * An entry the schema does not know (a mapper kind the addon no longer serves) is dropped on the
146349
- * way, which is what the boot sweep did to it anyway.
146350
- */
146351
- /** Key-order-independent JSON, so "identical" does not depend on how a store orders keys. */
146352
- function canonical(value) {
146353
- if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
146354
- 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(",")}}`;
146355
- return JSON.stringify(value) ?? "null";
146356
- }
146357
- function parsedList(value, parse) {
146358
- if (!Array.isArray(value)) return [];
146359
- const kept = [];
146360
- for (const entry of value) {
146361
- const parsed = parse(entry);
146362
- if (parsed.success) kept.push(parsed.data);
146363
- }
146364
- return kept;
146365
- }
146366
- /** The record body the legacy settings describe. */
146367
- function exposureBodyFrom(stored) {
146368
- return {
146369
- name: HAP_EXPOSURE_NAME,
146370
- devices: parsedList(stored["exposed"], (e) => ExposedConfigEntrySchema.safeParse(e)),
146371
- actions: parsedList(stored["exposedActions"], (e) => ActionExportEntrySchema.safeParse(e))
146372
- };
146373
- }
146374
- function sameLists(a, b) {
146375
- return canonical(a.devices) === canonical(b.devices) && canonical(a.actions) === canonical(b.actions);
146376
- }
146377
- async function moveExposureToRecord(ports) {
146378
- const stored = await ports.readStored(MOVED_EXPOSURE_KEYS);
146379
- if (!MOVED_EXPOSURE_KEYS.some((key) => key in stored)) return {
146380
- outcome: "already-done",
146381
- summary: { moved: false }
146382
- };
146383
- const body = exposureBodyFrom(stored);
146384
- const put = await ports.putExposure(body);
146385
- const held = await ports.readExposure();
146386
- if (held === null) throw new Error("the HomeKit exposure record cannot be read back");
146387
- if (put === "created" && !sameLists(held, body)) throw new Error("the HomeKit exposure record does not hold the lists it adopted");
146388
- return put === "created" ? {
146389
- outcome: "done",
146390
- summary: {
146391
- moved: true,
146392
- devices: body.devices.length
146393
- }
146394
- } : {
146395
- outcome: "already-done",
146396
- summary: { moved: false }
146397
- };
146398
- }
146399
- var rowId = (key) => `${HAP_DEFAULT_INSTANCE_ID}.${key}`;
146400
- async function planDropExposureKeys(ports) {
146401
- const stored = await ports.readStored(MOVED_EXPOSURE_KEYS);
146402
- const present = MOVED_EXPOSURE_KEYS.filter((key) => key in stored);
146403
- if (present.length === 0) return { edits: [] };
146404
- const held = await ports.readExposure();
146405
- if (held === null || !sameLists(held, exposureBodyFrom(stored))) return { edits: [] };
146406
- return { edits: [{
146407
- op: "deleteKeys",
146408
- scope: ADDON_SETTINGS_TABLE,
146409
- keys: present.map(rowId),
146410
- precondition: preconditionOf(Object.fromEntries(present.map((key) => [rowId(key), {
146411
- addonId: HAP_DEFAULT_INSTANCE_ID,
146412
- key,
146413
- value: stored[key]
146414
- }])))
146415
- }] };
146416
- }
146417
- //#endregion
146418
- //#region src/migrations/identity-to-instance.ts
146419
- /**
146420
- * The bridge identity the addon kept in its settings (`identity`: username, uuid, pincode) moves
146421
- * into the default instance record (D985, D996). Paired controllers know the bridge by exactly
146422
- * these values, so the record is created with them UNCHANGED and the pass proves it by reading the
146423
- * record back and comparing, field by field, before it reports `done`.
146424
- *
146425
- * Only once the read-back matches is the old `identity` cleared (its keychain entry released with
146426
- * it), in this same pass: one path, no copy. An existing record is never overwritten; when it is
146427
- * already there and names the same bridge (username, uuid) the leftover old identity of an
146428
- * interrupted pass is cleared, and when it names another bridge the pass fails rather than guess.
146429
- * An incomplete or unreadable legacy identity is `already-done` or throws, and never mints a new
146430
- * one (a new identity unpairs every controller).
146431
- */
146432
- async function moveIdentityToDefaultInstance(ports) {
146433
- const legacy = await ports.readLegacyIdentity();
146434
- if (legacy === null) return {
146435
- outcome: "already-done",
146436
- summary: { moved: false }
146437
- };
146438
- const name = (await ports.readBridgeName()).trim();
146439
- const body = {
146440
- name: name.length > 0 ? name : "CamStack Bridge",
146441
- username: legacy.username,
146442
- uuid: legacy.uuid,
146443
- pincode: legacy.pincode
146444
- };
146445
- const put = await ports.putDefaultRecord(body);
146446
- const held = await ports.readDefaultRecord();
146447
- if (held === null) throw new Error("the HomeKit default instance record cannot be read back");
146448
- if (put === "exists") {
146449
- if (held.username !== body.username || held.uuid !== body.uuid) throw new Error("the HomeKit default instance is another bridge than the stored identity");
146450
- await ports.clearLegacyIdentity();
146451
- return {
146452
- outcome: "done",
146453
- summary: {
146454
- moved: false,
146455
- cleared: true
146456
- }
146457
- };
146458
- }
146459
- if (!sameIdentity(identityOfBody(held), identityOfBody(body))) throw new Error("the HomeKit default instance does not hold the identity it adopted");
146460
- await ports.clearLegacyIdentity();
146461
- return {
146462
- outcome: "done",
146463
- summary: { moved: true }
146464
- };
146465
- }
146466
- function sameIdentity(a, b) {
146467
- return a.username === b.username && a.uuid === b.uuid && a.pincode === b.pincode;
146468
- }
146469
- /**
146470
- * The identity a settings value describes, secrets resolved; null when it is not a complete
146471
- * identity (first boot, or the empty sentinel). A pincode still a keychain marker was not
146472
- * resolved: that throws, because treating "unreadable" as "absent" would mint a new identity.
146473
- */
146474
- function legacyIdentityOf(value) {
146475
- if (typeof value !== "object" || value === null) return null;
146476
- const username = Reflect.get(value, "username");
146477
- const uuid = Reflect.get(value, "uuid");
146478
- const pincode = Reflect.get(value, "pincode");
146479
- if (isSecretMarker(pincode)) throw new Error("the stored HomeKit setup code cannot be resolved");
146480
- if (typeof username !== "string" || typeof uuid !== "string" || typeof pincode !== "string" || username === "" || uuid === "" || pincode === "") return null;
146481
- return {
146482
- username,
146483
- uuid,
146484
- pincode
146485
- };
146486
- }
146487
- //#endregion
146488
- //#region src/migrations/bridge-name-to-instance.ts
146489
- async function moveBridgeNameToInstance(ports) {
146490
- const name = (await ports.readBridgeName()).trim();
146491
- if (name === "") return {
146492
- outcome: "already-done",
146493
- summary: { renamed: false }
146494
- };
146495
- const held = await ports.readDefaultRecord();
146496
- if (held === null || held.name === name) return {
146497
- outcome: "already-done",
146498
- summary: { renamed: false }
146499
- };
146500
- await ports.patchDefaultName(name);
146501
- const after = await ports.readDefaultRecord();
146502
- if (after === null || after.name !== name) throw new Error("the HomeKit default instance does not carry the name it adopted");
146503
- return {
146504
- outcome: "done",
146505
- summary: { renamed: true }
146506
- };
146507
- }
146508
- //#endregion
146509
- //#region src/migrations/drop-global-knobs.ts
146510
- /**
146511
- * The retired global knobs of the HomeKit export. `bridgeName` is the instance's name and
146512
- * `fixedPin` was an operator-typed setup code (a bridge's setup code is read-only now and changes
146513
- * only through Regenerate); the bare `interfaceName` is the cluster copy of a setting that is a
146514
- * fact of one node, which the node row carries since the per-node migration.
146515
- *
146516
- * Two bodies, in this order, because a secret must be released before its row goes (the
146517
- * keychain value would be orphaned otherwise):
146518
- * 1. `clearFixedPin` (procedure): the keychain value and marker of `fixedPin`;
146519
- * 2. `planDropGlobalKnobRows` (plan): the rows `bridgeName`, `fixedPin` and the bare
146520
- * `interfaceName`. The bare interfaceName goes only when the node row exists, so deleting it
146521
- * can never lose the value. A `@<nodeId>` row is never touched.
146522
- */
146523
- async function clearFixedPin(ports) {
146524
- if (!("fixedPin" in await ports.readStored(["fixedPin"]))) return {
146525
- outcome: "already-done",
146526
- summary: { cleared: false }
146527
- };
146528
- await ports.clearFixedPin();
146529
- return {
146530
- outcome: "done",
146531
- summary: { cleared: true }
146532
- };
146533
- }
146534
- async function planDropGlobalKnobRows(addonId, ports) {
146535
- const stored = await ports.readStored([
146536
- "bridgeName",
146537
- "fixedPin",
146538
- "interfaceName",
146539
- nodeKeyOf("interfaceName")
146540
- ]);
146541
- const present = [
146542
- "bridgeName",
146543
- "fixedPin",
146544
- "interfaceName"
146545
- ].filter((key) => key in stored && (key !== "interfaceName" || nodeKeyOf("interfaceName") in stored));
146546
- if (present.length === 0) return { edits: [] };
146547
- const rowId = (key) => `${addonId}.${key}`;
146548
- return { edits: [{
146549
- op: "deleteKeys",
146550
- scope: ADDON_SETTINGS_TABLE,
146551
- keys: present.map(rowId),
146552
- precondition: preconditionOf(Object.fromEntries(present.map((key) => [rowId(key), {
146553
- addonId,
146554
- key,
146555
- value: stored[key]
146556
- }])))
146557
- }] };
146558
- }
146559
- //#endregion
146560
- //#region src/migrations/index.ts
146561
- var EXPORT_HAP_ID = "export-hap";
146562
- var INTERFACE_NAME_PER_NODE_ID = "export-hap/2026-11-03-interface-name-per-node";
146563
- var FIXED_PIN_TO_KEYCHAIN_ID = "export-hap/2026-11-03-fixed-pin-to-keychain";
146564
- var IDENTITY_TO_INSTANCE_ID = "export-hap/2026-11-04-identity-to-default-instance";
146565
- var EXPOSURE_TO_RECORD_ID = "export-hap/2026-11-04-exposure-to-record";
146566
- var DROP_EXPOSURE_KEYS_ID = "export-hap/2026-11-04-drop-exposure-keys";
146567
- var BRIDGE_NAME_TO_INSTANCE_ID = "export-hap/2026-11-04-bridge-name-to-instance";
146568
- var DROP_GLOBAL_KNOBS_ID = "export-hap/2026-11-04-drop-global-knobs";
146569
- /** The `export-hap` catalogue (D987): offered to the engine when the addon initialises. */
146570
- var ADDON_MIGRATIONS = [
146571
- {
146572
- meta: {
146573
- id: INTERFACE_NAME_PER_NODE_ID,
146574
- owner: EXPORT_HAP_ID,
146575
- level: "addon-state",
146576
- seq: 1,
146577
- dependsOn: [],
146578
- store: "settings",
146579
- scope: "per-node",
146580
- onFailure: "tolerate",
146581
- bodyKind: "plan",
146582
- description: "Copy the bare network interface setting to its hub node row; the bare row stays for a release",
146583
- fixtureMark: "the bridge name the migration does not know"
146584
- },
146585
- plan: (ports) => planHubNodeFields(EXPORT_HAP_ID, ["interfaceName"], ports)
146586
- },
146587
- {
146588
- meta: {
146589
- id: FIXED_PIN_TO_KEYCHAIN_ID,
146590
- owner: EXPORT_HAP_ID,
146591
- level: "addon-state",
146592
- seq: 2,
146593
- dependsOn: [],
146594
- store: "settings",
146595
- scope: "cluster",
146596
- onFailure: "tolerate",
146597
- bodyKind: "procedure",
146598
- description: "Move the fixed setup code from an inline setting into the keychain, where a password field keeps it",
146599
- fixtureMark: "the bridge name the migration does not know"
146600
- },
146601
- procedure: moveFixedPinToKeychain
146602
- },
146603
- {
146604
- meta: {
146605
- id: IDENTITY_TO_INSTANCE_ID,
146606
- owner: EXPORT_HAP_ID,
146607
- level: "addon-state",
146608
- seq: 3,
146609
- dependsOn: [],
146610
- store: "settings",
146611
- scope: "cluster",
146612
- onFailure: "block-owner",
146613
- bodyKind: "procedure",
146614
- 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",
146615
- fixtureMark: "the bridge name the migration does not know"
146616
- },
146617
- procedure: moveIdentityToDefaultInstance
146618
- },
146619
- {
146620
- meta: {
146621
- id: EXPOSURE_TO_RECORD_ID,
146622
- owner: EXPORT_HAP_ID,
146623
- level: "addon-state",
146624
- seq: 4,
146625
- dependsOn: [IDENTITY_TO_INSTANCE_ID],
146626
- store: "settings",
146627
- scope: "cluster",
146628
- onFailure: "block-owner",
146629
- bodyKind: "procedure",
146630
- description: "Move the exposed devices and actions into the default bridge exposure record, verified by read-back",
146631
- fixtureMark: "the bridge name the migration does not know"
146632
- },
146633
- procedure: moveExposureToRecord
146634
- },
146635
- {
146636
- meta: {
146637
- id: DROP_EXPOSURE_KEYS_ID,
146638
- owner: EXPORT_HAP_ID,
146639
- level: "addon-state",
146640
- seq: 5,
146641
- dependsOn: [EXPOSURE_TO_RECORD_ID],
146642
- store: "settings",
146643
- scope: "cluster",
146644
- onFailure: "tolerate",
146645
- bodyKind: "plan",
146646
- description: "Delete the old exposed and exposedActions settings once the record holds exactly what they carried",
146647
- fixtureMark: "the bridge name the migration does not know"
146648
- },
146649
- plan: planDropExposureKeys
146650
- },
146651
- {
146652
- meta: {
146653
- id: BRIDGE_NAME_TO_INSTANCE_ID,
146654
- owner: EXPORT_HAP_ID,
146655
- level: "addon-state",
146656
- seq: 6,
146657
- dependsOn: [IDENTITY_TO_INSTANCE_ID],
146658
- store: "settings",
146659
- scope: "cluster",
146660
- onFailure: "block-owner",
146661
- bodyKind: "procedure",
146662
- description: "Make the installation name the name of the default HomeKit instance record, verified by read-back",
146663
- fixtureMark: "the bridge name the migration does not know"
146664
- },
146665
- procedure: moveBridgeNameToInstance
146666
- },
146667
- {
146668
- meta: {
146669
- id: DROP_GLOBAL_KNOBS_ID,
146670
- owner: EXPORT_HAP_ID,
146671
- level: "addon-state",
146672
- seq: 7,
146673
- dependsOn: [FIXED_PIN_TO_KEYCHAIN_ID, IDENTITY_TO_INSTANCE_ID],
146674
- store: "settings",
146675
- scope: "cluster",
146676
- onFailure: "tolerate",
146677
- bodyKind: "procedure",
146678
- description: "Release the retired fixed setup code from the keychain: a bridge setup code is read-only now",
146679
- fixtureMark: "the bridge name the migration does not know"
146680
- },
146681
- procedure: clearFixedPin
146682
- },
146683
- {
146684
- meta: {
146685
- id: "export-hap/2026-11-04-drop-global-knob-rows",
146686
- owner: EXPORT_HAP_ID,
146687
- level: "addon-state",
146688
- seq: 8,
146689
- dependsOn: [
146690
- BRIDGE_NAME_TO_INSTANCE_ID,
146691
- DROP_GLOBAL_KNOBS_ID,
146692
- INTERFACE_NAME_PER_NODE_ID
146693
- ],
146694
- store: "settings",
146695
- scope: "cluster",
146696
- onFailure: "tolerate",
146697
- bodyKind: "plan",
146698
- description: "Delete the retired bridgeName, fixedPin and cluster interfaceName rows; the node rows are untouched",
146699
- fixtureMark: "the bridge name the migration does not know"
146700
- },
146701
- plan: (ports) => planDropGlobalKnobRows(EXPORT_HAP_ID, ports)
146702
- }
146703
- ];
146704
- //#endregion
146705
146418
  //#region src/hap-setup-uri.ts
146706
146419
  function errMsg$15(e) {
146707
146420
  return e instanceof Error ? e.message : String(e);
@@ -147954,38 +147667,6 @@ function createClipThumbnailMinter(input) {
147954
147667
  };
147955
147668
  }
147956
147669
  //#endregion
147957
- //#region src/hksv/recording-active.ts
147958
- /**
147959
- * `true`/`false` as HomeKit holds it, or `null` when this accessory does not
147960
- * offer recording at all.
147961
- */
147962
- function readHomekitRecordingActive(accessories) {
147963
- for (const accessory of accessories) {
147964
- const service = accessory.getService(import_dist.Service.CameraRecordingManagement);
147965
- if (service === void 0) continue;
147966
- const value = service.getCharacteristic(import_dist.Characteristic.Active).value;
147967
- if (typeof value === "number") return value === 1;
147968
- if (typeof value === "boolean") return value;
147969
- return null;
147970
- }
147971
- return null;
147972
- }
147973
- /**
147974
- * One sentence for the settings page: what HomeKit says, or why it was never
147975
- * asked.
147976
- *
147977
- * The cost stays in the text even though the switch is gone. It is still the
147978
- * operator's to understand — a camera recording here runs a permanent ffmpeg —
147979
- * and a status line that reported only the state would have quietly dropped
147980
- * the one number that decides whether to turn it on.
147981
- */
147982
- function describeHomekitRecording(active, lastBuild) {
147983
- if (active === true) return "HomeKit is recording this camera. Turn it off in the Home app (Camera settings → “Stream”), not here — iOS owns this switch and keeps it across reboots. While it is on, this camera runs a permanent prebuffer (~0.7% of one CPU core on the copy branch).";
147984
- if (active === false) return "This camera offers recording and HomeKit has it off. Turn it on in the Home app (Camera settings → “Stream and Allow Recording”); it needs iCloud+ and a home hub. Nothing runs here until you do.";
147985
- if (lastBuild !== null && !lastBuild.advertised) return `Recording is not offered for this camera: ${lastBuild.detail ?? "the accessory could not advertise it"}.`;
147986
- return "Not known yet — this camera’s accessory has not published its recording service in this process. It appears once the accessory is built.";
147987
- }
147988
- //#endregion
147989
147670
  //#region src/hksv/recording-source.ts
147990
147671
  /** The tallest frame the recording path will hold in its prebuffer. */
147991
147672
  var MAX_RECORDING_HEIGHT = 1080;
@@ -148101,6 +147782,38 @@ function recordabilityTokenFor(input) {
148101
147782
  return recordabilityToken(input.entries, { allowTranscode: input.allowTranscode !== false });
148102
147783
  }
148103
147784
  //#endregion
147785
+ //#region src/hksv/recording-active.ts
147786
+ /**
147787
+ * `true`/`false` as HomeKit holds it, or `null` when this accessory does not
147788
+ * offer recording at all.
147789
+ */
147790
+ function readHomekitRecordingActive(accessories) {
147791
+ for (const accessory of accessories) {
147792
+ const service = accessory.getService(import_dist.Service.CameraRecordingManagement);
147793
+ if (service === void 0) continue;
147794
+ const value = service.getCharacteristic(import_dist.Characteristic.Active).value;
147795
+ if (typeof value === "number") return value === 1;
147796
+ if (typeof value === "boolean") return value;
147797
+ return null;
147798
+ }
147799
+ return null;
147800
+ }
147801
+ /**
147802
+ * One sentence for the settings page: what HomeKit says, or why it was never
147803
+ * asked.
147804
+ *
147805
+ * The cost stays in the text even though the switch is gone. It is still the
147806
+ * operator's to understand — a camera recording here runs a permanent ffmpeg —
147807
+ * and a status line that reported only the state would have quietly dropped
147808
+ * the one number that decides whether to turn it on.
147809
+ */
147810
+ function describeHomekitRecording(active, lastBuild) {
147811
+ if (active === true) return "HomeKit is recording this camera. Turn it off in the Home app (Camera settings → “Stream”), not here — iOS owns this switch and keeps it across reboots. While it is on, this camera runs a permanent prebuffer (~0.7% of one CPU core on the copy branch).";
147812
+ if (active === false) return "This camera offers recording and HomeKit has it off. Turn it on in the Home app (Camera settings → “Stream and Allow Recording”); it needs iCloud+ and a home hub. Nothing runs here until you do.";
147813
+ if (lastBuild !== null && !lastBuild.advertised) return `Recording is not offered for this camera: ${lastBuild.detail ?? "the accessory could not advertise it"}.`;
147814
+ return "Not known yet — this camera’s accessory has not published its recording service in this process. It appears once the accessory is built.";
147815
+ }
147816
+ //#endregion
148104
147817
  //#region src/hksv/videoclips-plane.ts
148105
147818
  /**
148106
147819
  * The two data-plane routes behind the HomeKit clip source.
@@ -148882,7 +148595,8 @@ function errMsg$14(err) {
148882
148595
  * hands this builder the PARENT accessory + the CHILD's proxy + a
148883
148596
  * unique subtype so each service round-trips deterministically through
148884
148597
  * HAP serialisation. The builder:
148885
- * - Maps `switch` cap → `Service.Switch`.
148598
+ * - Maps `switch` cap → `Service.Switch`, or the service the device's switch
148599
+ * sub-role names (`onOffServiceKind`).
148886
148600
  * - Maps `switch` + `brightness` cap → `Service.Lightbulb` with
148887
148601
  * Brightness characteristic (lighting devices only — see below).
148888
148602
  * - Hydrates initial state from `getStatus({})`.
@@ -148904,7 +148618,21 @@ function errMsg$14(err) {
148904
148618
  * Child devices without `switch` / `brightness` cap (status sensors,
148905
148619
  * IR LED, etc.) return a no-op handle.
148906
148620
  */
148907
- async function buildChildSwitch(bctx, subtype, deviceType) {
148621
+ function onOffServiceKind(deviceType, role, hasBrightness) {
148622
+ const isLightingDevice = deviceType === DeviceType.Light || deviceType === DeviceType.Generic;
148623
+ if (hasBrightness && isLightingDevice) return "dimmable-lightbulb";
148624
+ if (isSwitchLight(deviceType, role)) return "lightbulb";
148625
+ if (isOutlet(deviceType, role)) return "outlet";
148626
+ if (isSwitchFan(deviceType, role)) return "fan";
148627
+ return "switch";
148628
+ }
148629
+ function addOnOffService(accessory, kind, displayName, subtype) {
148630
+ if (kind === "dimmable-lightbulb" || kind === "lightbulb") return accessory.addService(import_dist.Service.Lightbulb, displayName, subtype);
148631
+ if (kind === "outlet") return accessory.addService(import_dist.Service.Outlet, displayName, subtype);
148632
+ if (kind === "fan") return accessory.addService(import_dist.Service.Fan, displayName, subtype);
148633
+ return accessory.addService(import_dist.Service.Switch, displayName, subtype);
148634
+ }
148635
+ async function buildChildSwitch(bctx, subtype, deviceType, role = null) {
148908
148636
  const { ctx, accessory, proxy, numericDeviceId, displayName } = bctx;
148909
148637
  const log = ctx.logger.withTags({ deviceId: numericDeviceId });
148910
148638
  const hasSwitch = !!proxy.switch;
@@ -148913,17 +148641,21 @@ async function buildChildSwitch(bctx, subtype, deviceType) {
148913
148641
  log.debug("export-hap: child has no switch/brightness cap — skipping");
148914
148642
  return { async dispose() {} };
148915
148643
  }
148916
- const isLightingDevice = deviceType === DeviceType.Light || deviceType === DeviceType.Generic;
148917
- const useLightbulb = hasBrightness && isLightingDevice;
148918
- const service = useLightbulb ? accessory.addService(import_dist.Service.Lightbulb, displayName, subtype) : accessory.addService(import_dist.Service.Switch, displayName, subtype);
148644
+ const kind = onOffServiceKind(deviceType, role, hasBrightness);
148645
+ const dimmable = kind === "dimmable-lightbulb";
148646
+ const service = addOnOffService(accessory, kind, displayName, subtype);
148919
148647
  applyServiceLabel(service, displayName);
148648
+ const setOn = (on) => {
148649
+ service.updateCharacteristic(import_dist.Characteristic.On, on);
148650
+ if (kind === "outlet") service.updateCharacteristic(import_dist.Characteristic.OutletInUse, on);
148651
+ };
148920
148652
  try {
148921
148653
  const switchStatus = await proxy.switch?.getStatus({});
148922
- if (switchStatus && typeof switchStatus.on === "boolean") service.updateCharacteristic(import_dist.Characteristic.On, switchStatus.on);
148654
+ if (switchStatus && typeof switchStatus.on === "boolean") setOn(switchStatus.on);
148923
148655
  } catch (err) {
148924
148656
  log.debug("export-hap: child switch.getStatus failed (non-fatal)", { meta: { error: errMsg$13(err) } });
148925
148657
  }
148926
- if (useLightbulb) try {
148658
+ if (dimmable) try {
148927
148659
  const status = await proxy.brightness?.getStatus({});
148928
148660
  if (status && typeof status.level === "number") service.updateCharacteristic(import_dist.Characteristic.Brightness, status.level);
148929
148661
  } catch (err) {
@@ -148940,7 +148672,7 @@ async function buildChildSwitch(bctx, subtype, deviceType) {
148940
148672
  } });
148941
148673
  }
148942
148674
  });
148943
- if (useLightbulb) service.getCharacteristic(import_dist.Characteristic.Brightness).onSet(async (value) => {
148675
+ if (dimmable) service.getCharacteristic(import_dist.Characteristic.Brightness).onSet(async (value) => {
148944
148676
  const percentage = typeof value === "number" ? value : Number(value);
148945
148677
  if (!Number.isFinite(percentage)) return;
148946
148678
  try {
@@ -148955,11 +148687,11 @@ async function buildChildSwitch(bctx, subtype, deviceType) {
148955
148687
  const unsubscribes = [];
148956
148688
  if (proxy.state.switch) {
148957
148689
  const unsubSwitch = proxy.state.switch.subscribe((value) => {
148958
- if (value && typeof value.on === "boolean") service.updateCharacteristic(import_dist.Characteristic.On, value.on);
148690
+ if (value && typeof value.on === "boolean") setOn(value.on);
148959
148691
  });
148960
148692
  unsubscribes.push(unsubSwitch);
148961
148693
  }
148962
- if (useLightbulb && proxy.state.brightness) {
148694
+ if (dimmable && proxy.state.brightness) {
148963
148695
  const unsubBrightness = proxy.state.brightness.subscribe((value) => {
148964
148696
  if (value && typeof value.level === "number") service.updateCharacteristic(import_dist.Characteristic.Brightness, value.level);
148965
148697
  });
@@ -149567,10 +149299,10 @@ var HAP_CAP_SERVICES = [
149567
149299
  {
149568
149300
  caps: ["switch", "brightness"],
149569
149301
  label: "Power",
149570
- build: ({ bctx, name, deviceType }) => buildChildSwitch({
149302
+ build: ({ bctx, name, deviceType, role }) => buildChildSwitch({
149571
149303
  ...bctx,
149572
149304
  displayName: name
149573
- }, "switch", deviceType)
149305
+ }, "switch", deviceType, role)
149574
149306
  },
149575
149307
  {
149576
149308
  caps: ["lock-control"],
@@ -149628,7 +149360,17 @@ var ACCESSORY_CATEGORY_BY_TYPE = {
149628
149360
  [DeviceType.Presence]: import_dist.Categories.SENSOR,
149629
149361
  [DeviceType.AlarmPanel]: import_dist.Categories.SECURITY_SYSTEM
149630
149362
  };
149631
- function accessoryCategoryFor(deviceType) {
149363
+ /**
149364
+ * The category, by type and then by the switch's sub-role (read only through
149365
+ * the `@camstack/types` accessors). A heater keeps a Switch service (see
149366
+ * `onOffServiceKind`) and takes HomeKit's heater category, which is an icon
149367
+ * and promises no characteristic. A helper boolean stays a SWITCH.
149368
+ */
149369
+ function accessoryCategoryFor(deviceType, role) {
149370
+ if (isSwitchLight(deviceType, role)) return import_dist.Categories.LIGHTBULB;
149371
+ if (isOutlet(deviceType, role)) return import_dist.Categories.OUTLET;
149372
+ if (isSwitchFan(deviceType, role)) return import_dist.Categories.FAN;
149373
+ if (isSwitchHeater(deviceType, role)) return import_dist.Categories.AIR_HEATER;
149632
149374
  return ACCESSORY_CATEGORY_BY_TYPE[deviceType] ?? import_dist.Categories.OTHER;
149633
149375
  }
149634
149376
  //#endregion
@@ -164615,7 +164357,7 @@ async function buildChildServicesFor(input) {
164615
164357
  options
164616
164358
  };
164617
164359
  const subtype = `child-${child.id}`;
164618
- handles.push(await buildChildSwitch(childCtx, subtype, asDeviceType(child.type)));
164360
+ handles.push(await buildChildSwitch(childCtx, subtype, asDeviceType(child.type), child.role ?? null));
164619
164361
  }
164620
164362
  return { async dispose() {
164621
164363
  for (const h of handles) try {
@@ -165593,9 +165335,9 @@ async function buildGenericAccessory(input) {
165593
165335
  const capNames = new Set(proxy.binding?.entries.map((e) => e.capName) ?? []);
165594
165336
  const rows = rowsForCaps(capNames);
165595
165337
  if (rows.length === 0) throw new Error(`export-hap: device ${numericId} carries no capability HomeKit can export (bound: ${[...capNames].toSorted().join(", ") || "none"})`);
165596
- const deviceType = await resolveDeviceType(proxy);
165338
+ const { type: deviceType, role } = await resolveDeviceKind(proxy);
165597
165339
  const accessory = new import_dist.Accessory(displayName, accessoryUuidFor("generic", numericId, options.instanceId));
165598
- accessory.category = accessoryCategoryFor(deviceType);
165340
+ accessory.category = accessoryCategoryFor(deviceType, role);
165599
165341
  await populateAccessoryInfo(accessory, proxy, displayName, "Accessory");
165600
165342
  const bctx = {
165601
165343
  ctx,
@@ -165611,11 +165353,13 @@ async function buildGenericAccessory(input) {
165611
165353
  handles.push(await row.build({
165612
165354
  bctx,
165613
165355
  name,
165614
- deviceType
165356
+ deviceType,
165357
+ role
165615
165358
  }));
165616
165359
  }
165617
165360
  log.info("export-hap: built generic accessory", { meta: {
165618
165361
  deviceType,
165362
+ role,
165619
165363
  services: rows.map((row) => row.caps[0]).join(",")
165620
165364
  } });
165621
165365
  return {
@@ -165631,20 +165375,27 @@ async function buildGenericAccessory(input) {
165631
165375
  };
165632
165376
  }
165633
165377
  /**
165634
- * The device's own type, or `Generic`.
165378
+ * The device's own type, or `Generic`, and its role (null when unread).
165635
165379
  *
165636
165380
  * Used ONLY where one capability has two HomeKit shapes — a siren's
165637
- * `brightness` is alarm volume, not luminosity — and for the accessory's icon.
165381
+ * `brightness` is alarm volume, not luminosity; a `switch-light` relay is a
165382
+ * Lightbulb, not a Switch — and for the accessory's icon.
165638
165383
  * `Generic` is the safe reading: it is the shape `child-switch.ts` already
165639
165384
  * treats as "a lamp if it dims, a switch otherwise".
165640
165385
  */
165641
- async function resolveDeviceType(proxy) {
165386
+ async function resolveDeviceKind(proxy) {
165642
165387
  try {
165643
165388
  const device = await proxy.deviceManager?.getDevice({});
165644
165389
  const raw = typeof device?.type === "string" ? device.type.toLowerCase() : "";
165645
- return Object.values(DeviceType).find((value) => value === raw) ?? DeviceType.Generic;
165390
+ return {
165391
+ type: Object.values(DeviceType).find((value) => value === raw) ?? DeviceType.Generic,
165392
+ role: typeof device?.role === "string" ? device.role : null
165393
+ };
165646
165394
  } catch {
165647
- return DeviceType.Generic;
165395
+ return {
165396
+ type: DeviceType.Generic,
165397
+ role: null
165398
+ };
165648
165399
  }
165649
165400
  }
165650
165401
  function errMsg$1(err) {
@@ -165662,6 +165413,446 @@ function getMapperFactory(kind) {
165662
165413
  return factory;
165663
165414
  }
165664
165415
  //#endregion
165416
+ //#region src/migrations/hub-node-fields.ts
165417
+ /**
165418
+ * Fields stored once for the cluster that are facts of ONE node become node settings (D986): a
165419
+ * node's row is `<addonId>.<key>@<nodeId>` carrying `nodeId`, and a node never falls back to a
165420
+ * bare row. This owner is placed `hub-only`, so the one node that ever held a value is the hub:
165421
+ * each bare row is COPIED to `<key>@hub`. The bare row stays for a release (a copy, not a move),
165422
+ * and a value already on the node row is never overwritten (a seed never overwrites).
165423
+ *
165424
+ * A keychain marker is copied verbatim: it names the owner and the secret, not the row that
165425
+ * points at it. Idempotent: with every bare row copied the plan is empty.
165426
+ */
165427
+ /** The canonical settings table: one row per key, id `<addonId>.<key>`. */
165428
+ var ADDON_SETTINGS_TABLE = "addon-settings";
165429
+ var nodeKeyOf = (key) => `${key}@hub`;
165430
+ async function planHubNodeFields(addonId, keys, ports) {
165431
+ const stored = await ports.readStored([...keys, ...keys.map(nodeKeyOf)]);
165432
+ const pending = keys.filter((key) => key in stored && !(nodeKeyOf(key) in stored));
165433
+ if (pending.length === 0) return { edits: [] };
165434
+ const rowId = (key) => `${addonId}.${nodeKeyOf(key)}`;
165435
+ return { edits: [{
165436
+ op: "setKeys",
165437
+ scope: ADDON_SETTINGS_TABLE,
165438
+ values: Object.fromEntries(pending.map((key) => [rowId(key), {
165439
+ addonId,
165440
+ key: nodeKeyOf(key),
165441
+ value: stored[key],
165442
+ nodeId: "hub"
165443
+ }])),
165444
+ precondition: preconditionOf(Object.fromEntries(pending.map((key) => [rowId(key), null])))
165445
+ }] };
165446
+ }
165447
+ /**
165448
+ * The port's read over an addon's three-way key read: each of `keys` that has a row, raw. A key
165449
+ * the store could not answer for throws, so the migration fails instead of treating a failed read
165450
+ * as "nothing to copy".
165451
+ */
165452
+ async function readRawKeys(read, addonId, keys) {
165453
+ const found = {};
165454
+ for (const key of keys) {
165455
+ const answer = await read(key);
165456
+ if (answer.kind === "unreadable") throw new Error(`${addonId}: the setting ${key} cannot be read (${answer.reason})`);
165457
+ if (answer.kind === "present") found[key] = answer.value;
165458
+ }
165459
+ return found;
165460
+ }
165461
+ //#endregion
165462
+ //#region src/migrations/fixed-pin-to-keychain.ts
165463
+ /**
165464
+ * The fixed HomeKit setup code pairs a controller with the bridge: a credential. It was a plain
165465
+ * text setting, stored inline in the settings row; it is a `password` field now (D783), and a
165466
+ * password lives in the keychain with a marker in the row. This procedure moves a stored inline
165467
+ * code there, through the operator write path (the one that stores an inline value of a
165468
+ * pre-keychain addon as a keychain secret).
165469
+ *
165470
+ * Idempotent: an absent, empty or already marker-backed code is `already-done`, so a crash
165471
+ * between the keychain write and the ledger row costs nothing on the rerun.
165472
+ */
165473
+ async function moveFixedPinToKeychain(ports) {
165474
+ const stored = (await ports.readStored(["fixedPin"]))["fixedPin"];
165475
+ if (typeof stored !== "string" || stored === "" || isSecretMarker(stored)) return {
165476
+ outcome: "already-done",
165477
+ summary: { moved: false }
165478
+ };
165479
+ await ports.storeFixedPin(stored);
165480
+ return {
165481
+ outcome: "done",
165482
+ summary: { moved: true }
165483
+ };
165484
+ }
165485
+ //#endregion
165486
+ //#region src/migrations/exposure-to-record.ts
165487
+ /**
165488
+ * The exposure lists the addon kept in its settings (`exposed`: the devices it mirrors, with
165489
+ * their per-device settings; `exposedActions`: the actions it publishes) move into the
165490
+ * `hap-bridge-exports` record of the default instance (D985, D996). Two migrations, in order:
165491
+ *
165492
+ * 1. `moveExposureToRecord` (procedure): put the record with `ifRev: 0`, read it BACK and
165493
+ * compare it with what the settings carried; a record that does not hold the same lists
165494
+ * throws and the settings are kept. An existing record is never overwritten.
165495
+ * 2. `planDropExposureKeys` (plan): the two keys are deleted from the canonical `addon-settings`
165496
+ * rows, and only while the record holds exactly what they carry. A record that differs (the
165497
+ * operator edited the lists since) keeps the old keys, which nothing reads any more.
165498
+ *
165499
+ * An entry the schema does not know (a mapper kind the addon no longer serves) is dropped on the
165500
+ * way, which is what the boot sweep did to it anyway.
165501
+ */
165502
+ /** Key-order-independent JSON, so "identical" does not depend on how a store orders keys. */
165503
+ function canonical(value) {
165504
+ if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
165505
+ 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(",")}}`;
165506
+ return JSON.stringify(value) ?? "null";
165507
+ }
165508
+ function parsedList(value, parse) {
165509
+ if (!Array.isArray(value)) return [];
165510
+ const kept = [];
165511
+ for (const entry of value) {
165512
+ const parsed = parse(entry);
165513
+ if (parsed.success) kept.push(parsed.data);
165514
+ }
165515
+ return kept;
165516
+ }
165517
+ /** The record body the legacy settings describe. */
165518
+ function exposureBodyFrom(stored) {
165519
+ return {
165520
+ name: HAP_EXPOSURE_NAME,
165521
+ devices: parsedList(stored["exposed"], (e) => ExposedConfigEntrySchema.safeParse(e)),
165522
+ actions: parsedList(stored["exposedActions"], (e) => ActionExportEntrySchema.safeParse(e))
165523
+ };
165524
+ }
165525
+ function sameLists(a, b) {
165526
+ return canonical(a.devices) === canonical(b.devices) && canonical(a.actions) === canonical(b.actions);
165527
+ }
165528
+ async function moveExposureToRecord(ports) {
165529
+ const stored = await ports.readStored(MOVED_EXPOSURE_KEYS);
165530
+ if (!MOVED_EXPOSURE_KEYS.some((key) => key in stored)) return {
165531
+ outcome: "already-done",
165532
+ summary: { moved: false }
165533
+ };
165534
+ const body = exposureBodyFrom(stored);
165535
+ const put = await ports.putExposure(body);
165536
+ const held = await ports.readExposure();
165537
+ if (held === null) throw new Error("the HomeKit exposure record cannot be read back");
165538
+ if (put === "created" && !sameLists(held, body)) throw new Error("the HomeKit exposure record does not hold the lists it adopted");
165539
+ return put === "created" ? {
165540
+ outcome: "done",
165541
+ summary: {
165542
+ moved: true,
165543
+ devices: body.devices.length
165544
+ }
165545
+ } : {
165546
+ outcome: "already-done",
165547
+ summary: { moved: false }
165548
+ };
165549
+ }
165550
+ var rowId = (key) => `${HAP_DEFAULT_INSTANCE_ID}.${key}`;
165551
+ async function planDropExposureKeys(ports) {
165552
+ const stored = await ports.readStored(MOVED_EXPOSURE_KEYS);
165553
+ const present = MOVED_EXPOSURE_KEYS.filter((key) => key in stored);
165554
+ if (present.length === 0) return { edits: [] };
165555
+ const held = await ports.readExposure();
165556
+ if (held === null || !sameLists(held, exposureBodyFrom(stored))) return { edits: [] };
165557
+ return { edits: [{
165558
+ op: "deleteKeys",
165559
+ scope: ADDON_SETTINGS_TABLE,
165560
+ keys: present.map(rowId),
165561
+ precondition: preconditionOf(Object.fromEntries(present.map((key) => [rowId(key), {
165562
+ addonId: HAP_DEFAULT_INSTANCE_ID,
165563
+ key,
165564
+ value: stored[key]
165565
+ }])))
165566
+ }] };
165567
+ }
165568
+ //#endregion
165569
+ //#region src/migrations/identity-to-instance.ts
165570
+ /**
165571
+ * The bridge identity the addon kept in its settings (`identity`: username, uuid, pincode) moves
165572
+ * into the default instance record (D985, D996). Paired controllers know the bridge by exactly
165573
+ * these values, so the record is created with them UNCHANGED and the pass proves it by reading the
165574
+ * record back and comparing, field by field, before it reports `done`.
165575
+ *
165576
+ * Only once the read-back matches is the old `identity` cleared (its keychain entry released with
165577
+ * it), in this same pass: one path, no copy. An existing record is never overwritten; when it is
165578
+ * already there and names the same bridge (username, uuid) the leftover old identity of an
165579
+ * interrupted pass is cleared, and when it names another bridge the pass fails rather than guess.
165580
+ * An incomplete or unreadable legacy identity is `already-done` or throws, and never mints a new
165581
+ * one (a new identity unpairs every controller).
165582
+ */
165583
+ async function moveIdentityToDefaultInstance(ports) {
165584
+ const legacy = await ports.readLegacyIdentity();
165585
+ if (legacy === null) return {
165586
+ outcome: "already-done",
165587
+ summary: { moved: false }
165588
+ };
165589
+ const name = (await ports.readBridgeName()).trim();
165590
+ const body = {
165591
+ name: name.length > 0 ? name : "CamStack Bridge",
165592
+ username: legacy.username,
165593
+ uuid: legacy.uuid,
165594
+ pincode: legacy.pincode
165595
+ };
165596
+ const put = await ports.putDefaultRecord(body);
165597
+ const held = await ports.readDefaultRecord();
165598
+ if (held === null) throw new Error("the HomeKit default instance record cannot be read back");
165599
+ if (put === "exists") {
165600
+ if (held.username !== body.username || held.uuid !== body.uuid) throw new Error("the HomeKit default instance is another bridge than the stored identity");
165601
+ await ports.clearLegacyIdentity();
165602
+ return {
165603
+ outcome: "done",
165604
+ summary: {
165605
+ moved: false,
165606
+ cleared: true
165607
+ }
165608
+ };
165609
+ }
165610
+ if (!sameIdentity(identityOfBody(held), identityOfBody(body))) throw new Error("the HomeKit default instance does not hold the identity it adopted");
165611
+ await ports.clearLegacyIdentity();
165612
+ return {
165613
+ outcome: "done",
165614
+ summary: { moved: true }
165615
+ };
165616
+ }
165617
+ function sameIdentity(a, b) {
165618
+ return a.username === b.username && a.uuid === b.uuid && a.pincode === b.pincode;
165619
+ }
165620
+ /**
165621
+ * The identity a settings value describes, secrets resolved; null when it is not a complete
165622
+ * identity (first boot, or the empty sentinel). A pincode still a keychain marker was not
165623
+ * resolved: that throws, because treating "unreadable" as "absent" would mint a new identity.
165624
+ */
165625
+ function legacyIdentityOf(value) {
165626
+ if (typeof value !== "object" || value === null) return null;
165627
+ const username = Reflect.get(value, "username");
165628
+ const uuid = Reflect.get(value, "uuid");
165629
+ const pincode = Reflect.get(value, "pincode");
165630
+ if (isSecretMarker(pincode)) throw new Error("the stored HomeKit setup code cannot be resolved");
165631
+ if (typeof username !== "string" || typeof uuid !== "string" || typeof pincode !== "string" || username === "" || uuid === "" || pincode === "") return null;
165632
+ return {
165633
+ username,
165634
+ uuid,
165635
+ pincode
165636
+ };
165637
+ }
165638
+ //#endregion
165639
+ //#region src/migrations/bridge-name-to-instance.ts
165640
+ async function moveBridgeNameToInstance(ports) {
165641
+ const name = (await ports.readBridgeName()).trim();
165642
+ if (name === "") return {
165643
+ outcome: "already-done",
165644
+ summary: { renamed: false }
165645
+ };
165646
+ const held = await ports.readDefaultRecord();
165647
+ if (held === null || held.name === name) return {
165648
+ outcome: "already-done",
165649
+ summary: { renamed: false }
165650
+ };
165651
+ await ports.patchDefaultName(name);
165652
+ const after = await ports.readDefaultRecord();
165653
+ if (after === null || after.name !== name) throw new Error("the HomeKit default instance does not carry the name it adopted");
165654
+ return {
165655
+ outcome: "done",
165656
+ summary: { renamed: true }
165657
+ };
165658
+ }
165659
+ //#endregion
165660
+ //#region src/migrations/drop-global-knobs.ts
165661
+ /**
165662
+ * The retired global knobs of the HomeKit export. `bridgeName` is the instance's name and
165663
+ * `fixedPin` was an operator-typed setup code (a bridge's setup code is read-only now and changes
165664
+ * only through Regenerate); the bare `interfaceName` is the cluster copy of a setting that is a
165665
+ * fact of one node, which the node row carries since the per-node migration.
165666
+ *
165667
+ * Two bodies, in this order, because a secret must be released before its row goes (the
165668
+ * keychain value would be orphaned otherwise):
165669
+ * 1. `clearFixedPin` (procedure): the keychain value and marker of `fixedPin`;
165670
+ * 2. `planDropGlobalKnobRows` (plan): the rows `bridgeName`, `fixedPin` and the bare
165671
+ * `interfaceName`. The bare interfaceName goes only when the node row exists, so deleting it
165672
+ * can never lose the value. A `@<nodeId>` row is never touched.
165673
+ */
165674
+ async function clearFixedPin(ports) {
165675
+ if (!("fixedPin" in await ports.readStored(["fixedPin"]))) return {
165676
+ outcome: "already-done",
165677
+ summary: { cleared: false }
165678
+ };
165679
+ await ports.clearFixedPin();
165680
+ return {
165681
+ outcome: "done",
165682
+ summary: { cleared: true }
165683
+ };
165684
+ }
165685
+ async function planDropGlobalKnobRows(addonId, ports) {
165686
+ const stored = await ports.readStored([
165687
+ "bridgeName",
165688
+ "fixedPin",
165689
+ "interfaceName",
165690
+ nodeKeyOf("interfaceName")
165691
+ ]);
165692
+ const present = [
165693
+ "bridgeName",
165694
+ "fixedPin",
165695
+ "interfaceName"
165696
+ ].filter((key) => key in stored && (key !== "interfaceName" || nodeKeyOf("interfaceName") in stored));
165697
+ if (present.length === 0) return { edits: [] };
165698
+ const rowId = (key) => `${addonId}.${key}`;
165699
+ return { edits: [{
165700
+ op: "deleteKeys",
165701
+ scope: ADDON_SETTINGS_TABLE,
165702
+ keys: present.map(rowId),
165703
+ precondition: preconditionOf(Object.fromEntries(present.map((key) => [rowId(key), {
165704
+ addonId,
165705
+ key,
165706
+ value: stored[key]
165707
+ }])))
165708
+ }] };
165709
+ }
165710
+ //#endregion
165711
+ //#region src/migrations/index.ts
165712
+ var EXPORT_HAP_ID = "export-hap";
165713
+ var INTERFACE_NAME_PER_NODE_ID = "export-hap/2026-11-03-interface-name-per-node";
165714
+ var FIXED_PIN_TO_KEYCHAIN_ID = "export-hap/2026-11-03-fixed-pin-to-keychain";
165715
+ var IDENTITY_TO_INSTANCE_ID = "export-hap/2026-11-04-identity-to-default-instance";
165716
+ var EXPOSURE_TO_RECORD_ID = "export-hap/2026-11-04-exposure-to-record";
165717
+ var DROP_EXPOSURE_KEYS_ID = "export-hap/2026-11-04-drop-exposure-keys";
165718
+ var BRIDGE_NAME_TO_INSTANCE_ID = "export-hap/2026-11-04-bridge-name-to-instance";
165719
+ var DROP_GLOBAL_KNOBS_ID = "export-hap/2026-11-04-drop-global-knobs";
165720
+ /** The `export-hap` catalogue (D987): offered to the engine when the addon initialises. */
165721
+ var ADDON_MIGRATIONS = [
165722
+ {
165723
+ meta: {
165724
+ id: INTERFACE_NAME_PER_NODE_ID,
165725
+ owner: EXPORT_HAP_ID,
165726
+ level: "addon-state",
165727
+ seq: 1,
165728
+ dependsOn: [],
165729
+ store: "settings",
165730
+ scope: "per-node",
165731
+ onFailure: "tolerate",
165732
+ bodyKind: "plan",
165733
+ description: "Copy the bare network interface setting to its hub node row; the bare row stays for a release",
165734
+ fixtureMark: "the bridge name the migration does not know"
165735
+ },
165736
+ plan: (ports) => planHubNodeFields(EXPORT_HAP_ID, ["interfaceName"], ports)
165737
+ },
165738
+ {
165739
+ meta: {
165740
+ id: FIXED_PIN_TO_KEYCHAIN_ID,
165741
+ owner: EXPORT_HAP_ID,
165742
+ level: "addon-state",
165743
+ seq: 2,
165744
+ dependsOn: [],
165745
+ store: "settings",
165746
+ scope: "cluster",
165747
+ onFailure: "tolerate",
165748
+ bodyKind: "procedure",
165749
+ description: "Move the fixed setup code from an inline setting into the keychain, where a password field keeps it",
165750
+ fixtureMark: "the bridge name the migration does not know"
165751
+ },
165752
+ procedure: moveFixedPinToKeychain
165753
+ },
165754
+ {
165755
+ meta: {
165756
+ id: IDENTITY_TO_INSTANCE_ID,
165757
+ owner: EXPORT_HAP_ID,
165758
+ level: "addon-state",
165759
+ seq: 3,
165760
+ dependsOn: [],
165761
+ store: "settings",
165762
+ scope: "cluster",
165763
+ onFailure: "block-owner",
165764
+ bodyKind: "procedure",
165765
+ 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",
165766
+ fixtureMark: "the bridge name the migration does not know"
165767
+ },
165768
+ procedure: moveIdentityToDefaultInstance
165769
+ },
165770
+ {
165771
+ meta: {
165772
+ id: EXPOSURE_TO_RECORD_ID,
165773
+ owner: EXPORT_HAP_ID,
165774
+ level: "addon-state",
165775
+ seq: 4,
165776
+ dependsOn: [IDENTITY_TO_INSTANCE_ID],
165777
+ store: "settings",
165778
+ scope: "cluster",
165779
+ onFailure: "block-owner",
165780
+ bodyKind: "procedure",
165781
+ description: "Move the exposed devices and actions into the default bridge exposure record, verified by read-back",
165782
+ fixtureMark: "the bridge name the migration does not know"
165783
+ },
165784
+ procedure: moveExposureToRecord
165785
+ },
165786
+ {
165787
+ meta: {
165788
+ id: DROP_EXPOSURE_KEYS_ID,
165789
+ owner: EXPORT_HAP_ID,
165790
+ level: "addon-state",
165791
+ seq: 5,
165792
+ dependsOn: [EXPOSURE_TO_RECORD_ID],
165793
+ store: "settings",
165794
+ scope: "cluster",
165795
+ onFailure: "tolerate",
165796
+ bodyKind: "plan",
165797
+ description: "Delete the old exposed and exposedActions settings once the record holds exactly what they carried",
165798
+ fixtureMark: "the bridge name the migration does not know"
165799
+ },
165800
+ plan: planDropExposureKeys
165801
+ },
165802
+ {
165803
+ meta: {
165804
+ id: BRIDGE_NAME_TO_INSTANCE_ID,
165805
+ owner: EXPORT_HAP_ID,
165806
+ level: "addon-state",
165807
+ seq: 6,
165808
+ dependsOn: [IDENTITY_TO_INSTANCE_ID],
165809
+ store: "settings",
165810
+ scope: "cluster",
165811
+ onFailure: "block-owner",
165812
+ bodyKind: "procedure",
165813
+ description: "Make the installation name the name of the default HomeKit instance record, verified by read-back",
165814
+ fixtureMark: "the bridge name the migration does not know"
165815
+ },
165816
+ procedure: moveBridgeNameToInstance
165817
+ },
165818
+ {
165819
+ meta: {
165820
+ id: DROP_GLOBAL_KNOBS_ID,
165821
+ owner: EXPORT_HAP_ID,
165822
+ level: "addon-state",
165823
+ seq: 7,
165824
+ dependsOn: [FIXED_PIN_TO_KEYCHAIN_ID, IDENTITY_TO_INSTANCE_ID],
165825
+ store: "settings",
165826
+ scope: "cluster",
165827
+ onFailure: "tolerate",
165828
+ bodyKind: "procedure",
165829
+ description: "Release the retired fixed setup code from the keychain: a bridge setup code is read-only now",
165830
+ fixtureMark: "the bridge name the migration does not know"
165831
+ },
165832
+ procedure: clearFixedPin
165833
+ },
165834
+ {
165835
+ meta: {
165836
+ id: "export-hap/2026-11-04-drop-global-knob-rows",
165837
+ owner: EXPORT_HAP_ID,
165838
+ level: "addon-state",
165839
+ seq: 8,
165840
+ dependsOn: [
165841
+ BRIDGE_NAME_TO_INSTANCE_ID,
165842
+ DROP_GLOBAL_KNOBS_ID,
165843
+ INTERFACE_NAME_PER_NODE_ID
165844
+ ],
165845
+ store: "settings",
165846
+ scope: "cluster",
165847
+ onFailure: "tolerate",
165848
+ bodyKind: "plan",
165849
+ description: "Delete the retired bridgeName, fixedPin and cluster interfaceName rows; the node rows are untouched",
165850
+ fixtureMark: "the bridge name the migration does not know"
165851
+ },
165852
+ plan: (ports) => planDropGlobalKnobRows(EXPORT_HAP_ID, ports)
165853
+ }
165854
+ ];
165855
+ //#endregion
165665
165856
  //#region src/reconcile/sync-state.ts
165666
165857
  function syncStateFromJson(json) {
165667
165858
  const map = /* @__PURE__ */ new Map();
@@ -166927,18 +167118,31 @@ var ExportHapAddon = class extends BaseAddon {
166927
167118
  async buildDeviceSettingsContribution(deviceId) {
166928
167119
  const kind = await this.resolveExportKind(deviceId);
166929
167120
  if (kind === null) return null;
166930
- const inst = this.instanceForDevice(deviceId);
166931
- if (inst === null) return null;
167121
+ const bridges = [...this.bridges.values()].toSorted((x, y) => Number(y.id === HAP_DEFAULT_INSTANCE_ID) - Number(x.id === HAP_DEFAULT_INSTANCE_ID));
167122
+ if (bridges.length === 0) return null;
167123
+ const named = bridges.length > 1;
167124
+ return {
167125
+ tabs: [{
167126
+ id: "export",
167127
+ label: "Export",
167128
+ icon: "share-2",
167129
+ order: 80
167130
+ }],
167131
+ sections: bridges.map((inst, index) => this.buildBridgeDeviceSection(inst, deviceId, kind, named, index))
167132
+ };
167133
+ }
167134
+ /** The Export section of one bridge for one device. Every key names the bridge. */
167135
+ buildBridgeDeviceSection(inst, deviceId, kind, named, index) {
166932
167136
  const entry = inst.findEntry(deviceId);
166933
167137
  const settings = entry?.settings ?? DEFAULT_DEVICE_SETTINGS;
166934
167138
  const enabled = entry !== null;
166935
- const enabledKey = `hap:${deviceId}:enabled`;
166936
- const streamPreferenceKey = `hap:${deviceId}:streamPreference`;
166937
- const multiTierKey = `hap:${deviceId}:multiTierService`;
166938
- const useBridgeKey = `hap:${deviceId}:useBridge`;
166939
- const allowTranscodeKey = `hap:${deviceId}:allowTranscode`;
166940
- const keepClipsKey = `hap:${deviceId}:keepClips`;
166941
- const clipRetentionKey = `hap:${deviceId}:clipRetentionDays`;
167139
+ const enabledKey = `hap:${inst.id}:${deviceId}:enabled`;
167140
+ const streamPreferenceKey = `hap:${inst.id}:${deviceId}:streamPreference`;
167141
+ const multiTierKey = `hap:${inst.id}:${deviceId}:multiTierService`;
167142
+ const useBridgeKey = `hap:${inst.id}:${deviceId}:useBridge`;
167143
+ const allowTranscodeKey = `hap:${inst.id}:${deviceId}:allowTranscode`;
167144
+ const keepClipsKey = `hap:${inst.id}:${deviceId}:keepClips`;
167145
+ const clipRetentionKey = `hap:${inst.id}:${deviceId}:clipRetentionDays`;
166942
167146
  const mapper = inst.exposed.get(String(deviceId)) ?? null;
166943
167147
  const paired = mapper ? accessoryPaired(mapper.accessory) : false;
166944
167148
  const bridged = mapper !== null && inst.bridgeHost.holds(mapper.accessory);
@@ -166985,7 +167189,7 @@ var ExportHapAddon = class extends BaseAddon {
166985
167189
  },
166986
167190
  {
166987
167191
  type: "info",
166988
- key: `hap:${deviceId}:hksvRecordingStatus`,
167192
+ key: `hap:${inst.id}:${deviceId}:hksvRecordingStatus`,
166989
167193
  label: "HomeKit recording (Secure Video)",
166990
167194
  content: describeHomekitRecording(readHomekitRecordingActive(inst.exposed.get(String(deviceId))?.accessories ?? []), this.hksvBuilds.lastFor(deviceId)),
166991
167195
  showWhen: {
@@ -167046,53 +167250,45 @@ var ExportHapAddon = class extends BaseAddon {
167046
167250
  }
167047
167251
  ];
167048
167252
  return {
167049
- tabs: [{
167050
- id: "export",
167051
- label: "Export",
167052
- icon: "share-2",
167053
- order: 80
167054
- }],
167055
- sections: [{
167056
- id: "export-hap",
167057
- title: "HomeKit Export",
167058
- description: kind === "camera" ? "Publish this camera as its own HomeKit accessory so iOS Home can pair with it." : "Publish this device as its own HomeKit accessory. Its capabilities decide which controls iOS Home shows.",
167059
- tab: "export",
167060
- columns: 1,
167061
- order: 10,
167062
- fields: [
167063
- {
167064
- type: "info",
167065
- key: "__hap-status",
167066
- label: "Status",
167067
- content: statusLabel,
167068
- variant: "info"
167069
- },
167070
- {
167071
- type: "qr-code",
167072
- key: "__hap-pair-qr",
167073
- label: paired ? "Pairing QR (already paired)" : "Pairing QR",
167074
- caption: paired ? `Already paired with at least one device. Scan from another iPhone / iPad to add it there too. Setup code: ${inst.pincode}.` : `Scan with the iOS Camera app to pair this accessory in HomeKit. Setup code: ${inst.pincode}.`,
167075
- value: qrValue,
167076
- size: 192,
167077
- alt: `HomeKit pairing QR for ${name}`,
167078
- showWhen: {
167079
- field: enabledKey,
167080
- equals: true
167081
- }
167082
- },
167083
- {
167084
- type: "boolean",
167085
- key: enabledKey,
167086
- label: "Expose to HomeKit",
167087
- description: "Toggle to publish this device as a HomeKit accessory.",
167088
- style: "switch",
167089
- value: enabled,
167090
- immediate: true
167091
- },
167092
- ...bridgeFields,
167093
- ...cameraFields
167094
- ]
167095
- }]
167253
+ id: `${EXPORT_HAP_ADDON_ID}:${inst.id}`,
167254
+ title: named ? `HomeKit Export — ${inst.name}` : "HomeKit Export",
167255
+ description: kind === "camera" ? "Publish this camera as its own HomeKit accessory so iOS Home can pair with it." : "Publish this device as its own HomeKit accessory. Its capabilities decide which controls iOS Home shows.",
167256
+ tab: "export",
167257
+ columns: 1,
167258
+ order: 10 + index,
167259
+ fields: [
167260
+ {
167261
+ type: "info",
167262
+ key: `__hap-status:${inst.id}`,
167263
+ label: "Status",
167264
+ content: statusLabel,
167265
+ variant: "info"
167266
+ },
167267
+ {
167268
+ type: "qr-code",
167269
+ key: `__hap-pair-qr:${inst.id}`,
167270
+ label: paired ? "Pairing QR (already paired)" : "Pairing QR",
167271
+ caption: paired ? `Already paired with at least one device. Scan from another iPhone / iPad to add it there too. Setup code: ${inst.pincode}.` : `Scan with the iOS Camera app to pair this accessory in HomeKit. Setup code: ${inst.pincode}.`,
167272
+ value: qrValue,
167273
+ size: 192,
167274
+ alt: `HomeKit pairing QR for ${name}`,
167275
+ showWhen: {
167276
+ field: enabledKey,
167277
+ equals: true
167278
+ }
167279
+ },
167280
+ {
167281
+ type: "boolean",
167282
+ key: enabledKey,
167283
+ label: "Expose to HomeKit",
167284
+ description: "Toggle to publish this device as a HomeKit accessory.",
167285
+ style: "switch",
167286
+ value: enabled,
167287
+ immediate: true
167288
+ },
167289
+ ...bridgeFields,
167290
+ ...cameraFields
167291
+ ]
167096
167292
  };
167097
167293
  }
167098
167294
  /**
@@ -167108,19 +167304,33 @@ var ExportHapAddon = class extends BaseAddon {
167108
167304
  * note in CLAUDE.md (Remaining work).
167109
167305
  */
167110
167306
  async applyDeviceSettingsPatch(deviceId, patch) {
167307
+ const instanceIds = bridgeIdsInPatch(deviceId, patch);
167308
+ if (instanceIds.length === 0) {
167309
+ const stale = Object.keys(patch).filter((k) => k.startsWith("hap:"));
167310
+ if (stale.length > 0) throw new Error(`export-hap: device ${deviceId} patch names no HomeKit bridge (${stale.join(", ")}) — reload the Export tab`);
167311
+ this.ctx.logger.warn("export-hap: a device patch carried no HomeKit key — nothing applied", {
167312
+ tags: { deviceId },
167313
+ meta: { keys: Object.keys(patch) }
167314
+ });
167315
+ return { success: true };
167316
+ }
167317
+ for (const instanceId of instanceIds) this.requireBridge(instanceId);
167318
+ for (const instanceId of instanceIds) await this.applyBridgeDevicePatch(this.requireBridge(instanceId), deviceId, patch);
167319
+ return { success: true };
167320
+ }
167321
+ /** Apply the keys of ONE bridge (`hap:<inst.id>:<deviceId>:…`) to that bridge. */
167322
+ async applyBridgeDevicePatch(inst, deviceId, patch) {
167111
167323
  const deviceIdStr = String(deviceId);
167112
167324
  const log = this.ctx.logger.withTags({ deviceId });
167113
- const inst = this.instanceForDevice(deviceId);
167114
- if (inst === null) throw new Error("export-hap: no HomeKit bridge is running — add or enable one first");
167115
167325
  const current = inst.findEntry(deviceId);
167116
167326
  const wasEnabled = inst.exposed.has(deviceIdStr);
167117
- const enabledKey = `hap:${deviceId}:enabled`;
167118
- const streamPreferenceKey = `hap:${deviceId}:streamPreference`;
167119
- const useBridgeKey = `hap:${deviceId}:useBridge`;
167120
- const allowTranscodeKey = `hap:${deviceId}:allowTranscode`;
167121
- const multiTierKey = `hap:${deviceId}:multiTierService`;
167122
- const keepClipsKey = `hap:${deviceId}:keepClips`;
167123
- const clipRetentionKey = `hap:${deviceId}:clipRetentionDays`;
167327
+ const enabledKey = `hap:${inst.id}:${deviceId}:enabled`;
167328
+ const streamPreferenceKey = `hap:${inst.id}:${deviceId}:streamPreference`;
167329
+ const useBridgeKey = `hap:${inst.id}:${deviceId}:useBridge`;
167330
+ const allowTranscodeKey = `hap:${inst.id}:${deviceId}:allowTranscode`;
167331
+ const multiTierKey = `hap:${inst.id}:${deviceId}:multiTierService`;
167332
+ const keepClipsKey = `hap:${inst.id}:${deviceId}:keepClips`;
167333
+ const clipRetentionKey = `hap:${inst.id}:${deviceId}:clipRetentionDays`;
167124
167334
  const enabledValue = enabledKey in patch ? Boolean(patch[enabledKey]) : wasEnabled;
167125
167335
  const streamPreferenceRaw = streamPreferenceKey in patch ? patch[streamPreferenceKey] : current?.settings?.streamPreference;
167126
167336
  const streamPreference = typeof streamPreferenceRaw === "string" && streamPreferenceRaw.trim().length > 0 ? streamPreferenceRaw : "auto";
@@ -167304,6 +167514,21 @@ var ExportHapAddon = class extends BaseAddon {
167304
167514
  await this.setExposedDevices(inst, next);
167305
167515
  }
167306
167516
  };
167517
+ /**
167518
+ * The bridges a device patch addresses, read from its keys (`hap:<instanceId>:<deviceId>:<setting>`),
167519
+ * in first-seen order. Keys of another device or another exporter are not this patch's.
167520
+ */
167521
+ function bridgeIdsInPatch(deviceId, patch) {
167522
+ const ids = /* @__PURE__ */ new Set();
167523
+ for (const key of Object.keys(patch)) {
167524
+ const match = HAP_DEVICE_KEY.exec(key);
167525
+ if (match === null || match[2] !== String(deviceId)) continue;
167526
+ const instanceId = match[1];
167527
+ if (instanceId !== void 0) ids.add(instanceId);
167528
+ }
167529
+ return [...ids];
167530
+ }
167531
+ var HAP_DEVICE_KEY = /^hap:([^:]+):(\d+):\w+$/;
167307
167532
  function errMsg(err) {
167308
167533
  return err instanceof Error ? err.message : String(err);
167309
167534
  }