@camstack/server 1.2.840 → 1.2.841

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.
Files changed (101) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/dist/api/trpc/generated-cap-routers.js +16 -0
  3. package/package.json +17 -7
  4. package/system/dist/addon-runner.js +4 -2
  5. package/system/dist/addon-runner.mjs +4 -2
  6. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.js +1 -1
  7. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.mjs +1 -1
  8. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js +1 -1
  9. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs +1 -1
  10. package/system/dist/builtins/alerts/alerts.addon.js +1 -1
  11. package/system/dist/builtins/alerts/alerts.addon.mjs +1 -1
  12. package/system/dist/builtins/autotrack/index.js +1 -1
  13. package/system/dist/builtins/autotrack/index.mjs +1 -1
  14. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.js +2 -2
  15. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.mjs +2 -2
  16. package/system/dist/builtins/calendars/calendars.addon.js +1 -1
  17. package/system/dist/builtins/calendars/calendars.addon.mjs +1 -1
  18. package/system/dist/builtins/camera-grid/index.js +1 -1
  19. package/system/dist/builtins/camera-grid/index.mjs +1 -1
  20. package/system/dist/builtins/composer/composer.addon.js +5 -5
  21. package/system/dist/builtins/composer/composer.addon.mjs +5 -5
  22. package/system/dist/builtins/console-logging/index.js +1 -1
  23. package/system/dist/builtins/console-logging/index.mjs +1 -1
  24. package/system/dist/builtins/core-blocks/composition-api.d.ts +2 -2
  25. package/system/dist/builtins/core-blocks/composition-sources.d.ts +9 -2
  26. package/system/dist/builtins/core-blocks/core-blocks.addon.d.ts +2 -0
  27. package/system/dist/builtins/core-blocks/core-blocks.addon.js +598 -395
  28. package/system/dist/builtins/core-blocks/core-blocks.addon.mjs +598 -395
  29. package/system/dist/builtins/core-blocks/fan-link-forward.d.ts +42 -0
  30. package/system/dist/builtins/core-blocks/fan-presets-service.d.ts +25 -39
  31. package/system/dist/builtins/core-blocks/fan-presets-wiring.d.ts +5 -3
  32. package/system/dist/builtins/core-blocks/migrations/helper-to-customize.d.ts +3 -1
  33. package/system/dist/builtins/core-blocks/power-source-service.d.ts +2 -0
  34. package/system/dist/builtins/core-blocks/timed-run/timed-run-service.d.ts +8 -2
  35. package/system/dist/builtins/device-history/device-history.addon.js +2 -2
  36. package/system/dist/builtins/device-history/device-history.addon.mjs +2 -2
  37. package/system/dist/builtins/device-manager/device-bindings-store.d.ts +8 -5
  38. package/system/dist/builtins/device-manager/device-manager.addon.js +116 -22
  39. package/system/dist/builtins/device-manager/device-manager.addon.mjs +116 -22
  40. package/system/dist/builtins/device-manager/device-row-store.d.ts +0 -52
  41. package/system/dist/builtins/hub-forwarder/index.js +1 -1
  42. package/system/dist/builtins/hub-forwarder/index.mjs +1 -1
  43. package/system/dist/builtins/keychain/index.js +4 -4
  44. package/system/dist/builtins/keychain/index.mjs +4 -4
  45. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.js +1 -1
  46. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.mjs +1 -1
  47. package/system/dist/builtins/local-auth/local-auth.addon.js +2 -2
  48. package/system/dist/builtins/local-auth/local-auth.addon.mjs +2 -2
  49. package/system/dist/builtins/local-network/local-network.addon.js +3 -3
  50. package/system/dist/builtins/local-network/local-network.addon.mjs +3 -3
  51. package/system/dist/builtins/loki-logging/index.js +1 -1
  52. package/system/dist/builtins/loki-logging/index.mjs +1 -1
  53. package/system/dist/builtins/native-metrics/native-metrics.addon.js +1 -1
  54. package/system/dist/builtins/native-metrics/native-metrics.addon.mjs +1 -1
  55. package/system/dist/builtins/platform-probe/index.js +1 -1
  56. package/system/dist/builtins/platform-probe/index.mjs +1 -1
  57. package/system/dist/builtins/record-entries/index.js +1 -1
  58. package/system/dist/builtins/record-entries/index.mjs +1 -1
  59. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.js +1 -1
  60. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.mjs +1 -1
  61. package/system/dist/builtins/snapshot/index.js +1 -1
  62. package/system/dist/builtins/snapshot/index.mjs +1 -1
  63. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.js +1 -1
  64. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.mjs +1 -1
  65. package/system/dist/builtins/sqlite-storage/index.js +1 -1
  66. package/system/dist/builtins/sqlite-storage/index.mjs +1 -1
  67. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.js +3 -3
  68. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs +3 -3
  69. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.js +1 -1
  70. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.mjs +1 -1
  71. package/system/dist/builtins/system-config/system-config.addon.js +3 -3
  72. package/system/dist/builtins/system-config/system-config.addon.mjs +3 -3
  73. package/system/dist/builtins/winston-logging/index.js +1 -1
  74. package/system/dist/builtins/winston-logging/index.mjs +1 -1
  75. package/system/dist/{capture-engine-7E2O4-UN.js → capture-engine-CGU4rnN-.js} +1 -1
  76. package/system/dist/{capture-engine-B5IBWIRT.mjs → capture-engine-CLrh3FG0.mjs} +1 -1
  77. package/system/dist/{composition-sources-Cfqn4cly.mjs → composition-sources-CoLbBru1.mjs} +32 -5
  78. package/system/dist/{composition-sources-DLtc8lSL.js → composition-sources-bhWIz4Rp.js} +32 -5
  79. package/system/dist/{constants-DjsgCnZk.mjs → constants-CfAS4Qm6.mjs} +1 -1
  80. package/system/dist/{constants-Cc70YreG.js → constants-DZwpZY5J.js} +1 -1
  81. package/system/dist/{device-ca-CVP5h3u1.mjs → device-ca-CAbEBLyf.mjs} +1 -1
  82. package/system/dist/{device-ca-C6JqeFfK.js → device-ca-ksS811fC.js} +1 -1
  83. package/system/dist/{dist-OmrC_RZs.mjs → dist-ByiDJLen.mjs} +1081 -327
  84. package/system/dist/{dist-CLnTYKFn.js → dist-DlRUArVs.js} +1128 -338
  85. package/system/dist/file-host-worker.js +1 -1
  86. package/system/dist/file-host-worker.mjs +1 -1
  87. package/system/dist/{hub-identity-CKQVXf4o.mjs → hub-identity-Bh28ooQx.mjs} +1 -1
  88. package/system/dist/{hub-identity-TrZcnJkB.js → hub-identity-C-1NeWlr.js} +1 -1
  89. package/system/dist/{hub-mdns-ciao-ocg6suyX.js → hub-mdns-ciao-CL-Z9yMs.js} +2 -2
  90. package/system/dist/{hub-mdns-ciao-C8G0K1Z1.mjs → hub-mdns-ciao-OWO6Bw-X.mjs} +2 -2
  91. package/system/dist/index.js +16 -12
  92. package/system/dist/index.mjs +16 -12
  93. package/system/dist/{legacy-integration-rows-door-BPkJUGaX.mjs → legacy-integration-rows-door-Be_QKUlY.mjs} +1 -1
  94. package/system/dist/{legacy-integration-rows-door-b6CUxtXX.js → legacy-integration-rows-door-CDPH26e8.js} +1 -1
  95. package/system/dist/{rename-composition-block-N7lslQJK.js → rename-composition-block-Bs5KT3Gn.js} +1 -1
  96. package/system/dist/{rename-composition-block-DPlsP1xF.mjs → rename-composition-block-CncvFIHl.mjs} +1 -1
  97. package/system/dist/{restore-archive-CcuEoEtj.js → restore-archive-CHUKcl3T.js} +1 -1
  98. package/system/dist/{restore-archive-Btc3H-Fg.mjs → restore-archive-DX7kK3LQ.mjs} +1 -1
  99. package/system/dist/{wal-maintenance-g7yvxLMj.mjs → wal-maintenance-Fibm7rsM.mjs} +0 -0
  100. package/system/dist/{wal-maintenance-B2_uCEi5.js → wal-maintenance-GNE9Oqdu.js} +0 -0
  101. package/system/package.json +1 -1
@@ -1,9 +1,9 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_chunk = require("../../chunk-Cek0wNdY.js");
3
- const require_dist = require("../../dist-CLnTYKFn.js");
3
+ const require_dist = require("../../dist-DlRUArVs.js");
4
4
  const require_read_all_rows$1 = require("../../read-all-rows-CVoO1ONM.js");
5
- const require_composition_sources = require("../../composition-sources-DLtc8lSL.js");
6
- const require_capture_engine = require("../../capture-engine-7E2O4-UN.js");
5
+ const require_composition_sources = require("../../composition-sources-bhWIz4Rp.js");
6
+ const require_capture_engine = require("../../capture-engine-CGU4rnN-.js");
7
7
  const require_prefix_range = require("../../prefix-range-D_KueXbQ.js");
8
8
  const require_prefix_walk = require("../../prefix-walk-Dv6MLZlM.js");
9
9
  const require_cap_call_scope = require("../../cap-call-scope-8eiugfLl.js");
@@ -2000,7 +2000,9 @@ async function dropFountainDrinkCounters(ports) {
2000
2000
  * `setState` to it, is kept exactly as it is;
2001
2001
  * - a heater with no meter runs while its plug is on (the plug as a `switch`
2002
2002
  * source, identity): it never used the threshold, so none is stored;
2003
- * - the `helper` key leaves the composition.
2003
+ * - the `helper` key leaves the composition;
2004
+ * - a heater's retired `heater` target type becomes a `switch` with the
2005
+ * `switch-heater` role (D1033), the same device under the role model.
2004
2006
  *
2005
2007
  * The block id, and with it the composed device stableId and the deviceId
2006
2008
  * the device registry holds, never moves, so the history stays attached. Only
@@ -2200,12 +2202,30 @@ function rewriteComposition(blockId, composition, helper) {
2200
2202
  if (!parsed.success) return refuse$1(blockId, `the rewritten composition is invalid: ${parsed.error.message}`);
2201
2203
  return parsed.data;
2202
2204
  }
2205
+ var RetiredHeaterTargetSchema = zod.z.looseObject({ target: zod.z.looseObject({
2206
+ kind: zod.z.literal("new"),
2207
+ type: zod.z.literal("heater")
2208
+ }) });
2209
+ /** D1033 retired the `heater` type: a stored heater target is a switch with the heater role. */
2210
+ function retypeRetiredHeater(composition) {
2211
+ const retired = RetiredHeaterTargetSchema.safeParse(composition);
2212
+ if (!retired.success) return composition;
2213
+ return {
2214
+ ...composition,
2215
+ target: {
2216
+ ...retired.data.target,
2217
+ type: require_dist.DeviceType.Switch,
2218
+ role: require_dist.DeviceRole.SwitchHeater
2219
+ }
2220
+ };
2221
+ }
2203
2222
  /** `null` when the row holds no appliance or heater helper; throws when it holds one it cannot read. */
2204
2223
  function legacyHelperOf(row) {
2205
2224
  if (!RawHelperBlockSchema.safeParse(row.data.block).success) return null;
2206
2225
  const envelope = LegacyHelperBlockSchema.safeParse(row.data.block);
2207
2226
  if (!envelope.success) return refuse$1(row.id, `the stored helper spec does not parse: ${envelope.error.message}`);
2208
- const { helper, ...composition } = envelope.data.source.composition;
2227
+ const { helper, ...stored } = envelope.data.source.composition;
2228
+ const composition = retypeRetiredHeater(stored);
2209
2229
  return {
2210
2230
  helper,
2211
2231
  withoutHelper: {
@@ -2317,7 +2337,7 @@ var OLD_COMMANDS = [
2317
2337
  "setPumpOnMinutes",
2318
2338
  "setPumpOffMinutes"
2319
2339
  ];
2320
- var UNKNOWN = {
2340
+ var UNKNOWN$1 = {
2321
2341
  kind: "expression",
2322
2342
  expr: "null",
2323
2343
  bindings: {}
@@ -2346,8 +2366,8 @@ function cycleFeature(old) {
2346
2366
  cap: "pump-cycle",
2347
2367
  fields: {
2348
2368
  enabled,
2349
- onTime: UNKNOWN,
2350
- offTime: UNKNOWN,
2369
+ onTime: UNKNOWN$1,
2370
+ offTime: UNKNOWN$1,
2351
2371
  lastFetchedAt: NOW
2352
2372
  },
2353
2373
  commands: {
@@ -4038,7 +4058,7 @@ var PowerSourceService = class {
4038
4058
  await this.deps.devices.setOn(switchId, false);
4039
4059
  } catch (err) {
4040
4060
  this.restarting.delete(deviceId);
4041
- return this.refuse(deviceId, "switch-call-failed", errorText$1(err), switchId);
4061
+ return this.refuse(deviceId, "switch-call-failed", errorText$2(err), switchId);
4042
4062
  }
4043
4063
  this.deps.logger.info("power-source: forced restart, power is off", {
4044
4064
  tags: { deviceId },
@@ -4076,7 +4096,7 @@ var PowerSourceService = class {
4076
4096
  tags: { deviceId },
4077
4097
  meta: {
4078
4098
  switchId,
4079
- error: errorText$1(err)
4099
+ error: errorText$2(err)
4080
4100
  }
4081
4101
  });
4082
4102
  } finally {
@@ -4091,7 +4111,7 @@ var PowerSourceService = class {
4091
4111
  try {
4092
4112
  await this.deps.devices.setOn(switchDevice.id, on);
4093
4113
  } catch (err) {
4094
- return this.refuse(deviceId, "switch-call-failed", errorText$1(err), switchDevice.id);
4114
+ return this.refuse(deviceId, "switch-call-failed", errorText$2(err), switchDevice.id);
4095
4115
  }
4096
4116
  this.deps.logger.info(`power-source: ${action}`, {
4097
4117
  tags: { deviceId },
@@ -4104,12 +4124,18 @@ var PowerSourceService = class {
4104
4124
  }
4105
4125
  /** The link and the switch, or the reason there is nothing to act on. Reads the switch state: unknown is refused. */
4106
4126
  async lookup(deviceId) {
4107
- const link = await this.linkOf(deviceId);
4108
- if (link === null) return {
4127
+ const stored = await this.storedLinkOf(deviceId);
4128
+ if (stored === null) return {
4109
4129
  kind: "refused",
4110
4130
  reason: "no-power-source",
4111
4131
  message: "no power source is linked"
4112
4132
  };
4133
+ const { link } = stored;
4134
+ if (stored.isActuator) return {
4135
+ kind: "refused",
4136
+ reason: "switch-is-actuator",
4137
+ message: `the linked switch ${link.switch.stableId} is one of this device's own switches, not its supply`
4138
+ };
4113
4139
  const switchDevice = await this.deps.devices.find(link.switch).catch(() => null);
4114
4140
  if (switchDevice === null) return {
4115
4141
  kind: "refused",
@@ -4136,11 +4162,19 @@ var PowerSourceService = class {
4136
4162
  }
4137
4163
  /** The stored link of the device `deviceId`, read from the customizations now. */
4138
4164
  async linkOf(deviceId) {
4165
+ return (await this.storedLinkOf(deviceId))?.link ?? null;
4166
+ }
4167
+ /** The stored link, and whether it names one of the device's own actuators (#462). */
4168
+ async storedLinkOf(deviceId) {
4139
4169
  for (const block of this.deps.blocks()) {
4140
- const link = require_dist.powerSourceLinkOfComposition(require_dist.coreBlockComposition(block), block.id);
4141
- if (link === null) continue;
4170
+ const composition = require_dist.coreBlockComposition(block);
4171
+ const link = require_dist.powerSourceLinkOfComposition(composition, block.id);
4172
+ if (link === null || composition === null) continue;
4142
4173
  const device = await this.deps.devices.find(link.device).catch(() => null);
4143
- if (device !== null && device.id === deviceId) return link;
4174
+ if (device !== null && device.id === deviceId) return {
4175
+ link,
4176
+ isActuator: require_dist.powerSourceActuatorConflicts(composition).length > 0
4177
+ };
4144
4178
  }
4145
4179
  return null;
4146
4180
  }
@@ -4160,7 +4194,7 @@ var PowerSourceService = class {
4160
4194
  };
4161
4195
  }
4162
4196
  };
4163
- function errorText$1(err) {
4197
+ function errorText$2(err) {
4164
4198
  return err instanceof Error ? err.message : String(err);
4165
4199
  }
4166
4200
  var TIMED_RUN_SETTLE_MS = 3e3;
@@ -4206,13 +4240,12 @@ var TimedRunService = class {
4206
4240
  await this.publishStatus(deviceId);
4207
4241
  };
4208
4242
  async limitOf(deviceId) {
4209
- const type = await this.deps.deviceTypeOf(deviceId);
4210
- return type === null ? null : require_dist.timedRunLimitOf(type);
4243
+ const kind = await this.deps.deviceKindOf(deviceId);
4244
+ return kind === null ? null : require_dist.timedRunLimitOf(kind.type, kind.role);
4211
4245
  }
4212
4246
  runFor = async (input) => {
4213
4247
  const { deviceId } = input;
4214
- const type = await this.deps.deviceTypeOf(deviceId);
4215
- const limit = type === null ? null : require_dist.timedRunLimitOf(type);
4248
+ const limit = await this.limitOf(deviceId);
4216
4249
  if (limit === null) {
4217
4250
  this.deps.logger.warn("timed-run refused: device type has no timed run", { tags: { deviceId } });
4218
4251
  return {
@@ -4465,12 +4498,15 @@ function buildTimedRunService(deps) {
4465
4498
  };
4466
4499
  return new TimedRunService({
4467
4500
  rows: rowsOver(deps.records),
4468
- deviceTypeOf: async (deviceId) => {
4501
+ deviceKindOf: async (deviceId) => {
4469
4502
  const found = await need().deviceManager.getDevice.query({ deviceId });
4470
- return found === null || found === void 0 ? null : found.type;
4503
+ return found === null || found === void 0 ? null : {
4504
+ type: found.type,
4505
+ role: found.role ?? null
4506
+ };
4471
4507
  },
4472
4508
  timedRunDeviceIds: async () => {
4473
- return (await need().deviceManager.listAll.query({ projection: "slim" })).filter((d) => require_dist.timedRunLimitOf(d.type) !== null).map((d) => d.id);
4509
+ return (await need().deviceManager.listAll.query({ projection: "slim" })).filter((d) => require_dist.timedRunLimitOf(d.type, d.role ?? null) !== null).map((d) => d.id);
4474
4510
  },
4475
4511
  actuation: actuationOver(deps.api),
4476
4512
  quickRuns: quickRunsOver(deps.settings),
@@ -6015,9 +6051,9 @@ var HeroLayoutService = class {
6015
6051
  constructor(deps) {
6016
6052
  this.deps = deps;
6017
6053
  }
6018
- getLayout = async ({ deviceType }) => ({
6054
+ getLayout = async ({ deviceType, role }) => ({
6019
6055
  type: deviceType,
6020
- rows: [...require_dist.resolveHeroLayout(deviceType).rows]
6056
+ rows: [...require_dist.resolveHeroLayout(deviceType, role ?? null).rows]
6021
6057
  });
6022
6058
  getHeroModel = async ({ deviceId, canActuate }) => {
6023
6059
  const { reader, logger } = this.deps;
@@ -6105,7 +6141,7 @@ var HeroLayoutService = class {
6105
6141
  //#region src/builtins/core-blocks/lock-door-gate.ts
6106
6142
  var LOCK_CONTROL = "lock-control";
6107
6143
  var DOOR_OPEN = "door-open";
6108
- var NOT_REDIRECTED = { kind: "not-redirected" };
6144
+ var NOT_REDIRECTED$1 = { kind: "not-redirected" };
6109
6145
  var LockDoorGate = class {
6110
6146
  deps;
6111
6147
  doorOpen = /* @__PURE__ */ new Map();
@@ -6129,7 +6165,7 @@ var LockDoorGate = class {
6129
6165
  }
6130
6166
  async attempt(call) {
6131
6167
  const known = this.doorOpen.get(call.deviceId);
6132
- if (known === false) return NOT_REDIRECTED;
6168
+ if (known === false) return NOT_REDIRECTED$1;
6133
6169
  const sensor = await this.deps.sensorOf(call.deviceId);
6134
6170
  if (known === void 0) {
6135
6171
  if (sensor !== null && !this.unknownLogged.has(call.deviceId)) {
@@ -6139,7 +6175,7 @@ var LockDoorGate = class {
6139
6175
  meta: { sensor }
6140
6176
  });
6141
6177
  }
6142
- return NOT_REDIRECTED;
6178
+ return NOT_REDIRECTED$1;
6143
6179
  }
6144
6180
  const named = sensor ?? "its door contact";
6145
6181
  this.deps.logger.warn("lock: lock() refused, the door is open", {
@@ -6159,7 +6195,7 @@ function composeRedirects(redirects) {
6159
6195
  const answer = await redirect.attempt(call);
6160
6196
  if (answer.kind === "redirected") return answer;
6161
6197
  }
6162
- return NOT_REDIRECTED;
6198
+ return NOT_REDIRECTED$1;
6163
6199
  }
6164
6200
  };
6165
6201
  }
@@ -6213,6 +6249,234 @@ async function seedLockDoors(deps) {
6213
6249
  }
6214
6250
  }
6215
6251
  //#endregion
6252
+ //#region src/builtins/core-blocks/fan-link-forward.ts
6253
+ /**
6254
+ * A write to a fan-control field the operator linked in Customize goes to the
6255
+ * linked device (D1034): `setOscillationAxis` and `setPreset` on a fan whose
6256
+ * stored composition claims the field are answered by the link — a switch's
6257
+ * `setState`, a control's `setValue` — at DISPATCH, through the device-call
6258
+ * redirect (D963), so every caller gets the same answer.
6259
+ *
6260
+ * The links are read from the STORED composition on each call, never kept as
6261
+ * a second copy (D676). A field nobody linked is the native provider's: when
6262
+ * no requested field is linked the call is not redirected. Writes run in the
6263
+ * order of the call and stop at the first refusal, which names the field and
6264
+ * lists what already landed. An angle is checked against the linked control's
6265
+ * own range, a preset against the linked select's live `options`.
6266
+ */
6267
+ var FAN_CONTROL = "fan-control";
6268
+ var NOT_REDIRECTED = { kind: "not-redirected" };
6269
+ /** A preset write the linked select refused; the message names the select and the reason. */
6270
+ var FanPresetRefusedError = class extends Error {
6271
+ reason;
6272
+ constructor(reason, detail) {
6273
+ super(`fan preset refused (${reason}): ${detail}`);
6274
+ this.reason = reason;
6275
+ this.name = "FanPresetRefusedError";
6276
+ }
6277
+ };
6278
+ var SetPresetArgsSchema = zod.z.object({
6279
+ deviceId: zod.z.number(),
6280
+ preset: zod.z.string().min(1)
6281
+ });
6282
+ /** Every fan-control field of a stored composition that reads ONE source field directly. */
6283
+ function linksOfBlock(block) {
6284
+ const composition = require_dist.coreBlockComposition(block);
6285
+ if (composition === null || composition.target.kind !== "existing") return null;
6286
+ const links = /* @__PURE__ */ new Map();
6287
+ for (const feature of composition.features) {
6288
+ if (!require_dist.compositionFeatureEnabled(feature) || feature.kind !== "fields") continue;
6289
+ if (feature.cap !== FAN_CONTROL) continue;
6290
+ for (const [path, source] of Object.entries(feature.fields)) {
6291
+ if (source.kind !== "from") continue;
6292
+ links.set(path, {
6293
+ source: source.source,
6294
+ cap: source.cap,
6295
+ fieldPath: source.fieldPath
6296
+ });
6297
+ }
6298
+ }
6299
+ return links.size === 0 ? null : {
6300
+ fan: composition.target.device,
6301
+ links
6302
+ };
6303
+ }
6304
+ async function linksOf(ports, deviceId) {
6305
+ for (const block of ports.blocks()) {
6306
+ const found = linksOfBlock(block);
6307
+ if (found === null) continue;
6308
+ if ((await ports.find(found.fan).catch(() => null))?.id === deviceId) return found.links;
6309
+ }
6310
+ return /* @__PURE__ */ new Map();
6311
+ }
6312
+ function describe(read) {
6313
+ return `${read.source.addonId}/${read.source.stableId} ${read.cap}.${read.fieldPath}`;
6314
+ }
6315
+ async function resolveSource(ports, read) {
6316
+ try {
6317
+ const found = await ports.find(read.source);
6318
+ if (found === null) return {
6319
+ ok: false,
6320
+ reason: "source-gone",
6321
+ detail: `${describe(read)} no longer exists`
6322
+ };
6323
+ return {
6324
+ ok: true,
6325
+ id: found.id
6326
+ };
6327
+ } catch (err) {
6328
+ const why = err instanceof Error ? err.message : String(err);
6329
+ return {
6330
+ ok: false,
6331
+ reason: "source-unknown",
6332
+ detail: `${describe(read)}: ${why}`
6333
+ };
6334
+ }
6335
+ }
6336
+ function requestedSteps(input) {
6337
+ return require_dist.FAN_OSCILLATION_AXIS_SETTABLE.flatMap((field) => {
6338
+ const value = input[field];
6339
+ return value === void 0 ? [] : [{
6340
+ field,
6341
+ value
6342
+ }];
6343
+ });
6344
+ }
6345
+ async function writeStep(ports, read, step) {
6346
+ const isSwitch = read.cap === "switch" && read.fieldPath === "on";
6347
+ const isControl = read.cap === "control" && read.fieldPath === "value";
6348
+ if (isSwitch !== (typeof step.value === "boolean") || !isSwitch && !isControl) return {
6349
+ ok: false,
6350
+ reason: "axis-not-linked",
6351
+ detail: `${step.field} is linked to ${describe(read)}, which takes no ${typeof step.value} command`
6352
+ };
6353
+ const source = await resolveSource(ports, read);
6354
+ if (!source.ok) return source;
6355
+ try {
6356
+ if (typeof step.value === "boolean") {
6357
+ await ports.setSwitch(source.id, step.value);
6358
+ return { ok: true };
6359
+ }
6360
+ const control = await ports.readControl(source.id);
6361
+ const below = control?.min !== void 0 && step.value < control.min;
6362
+ const above = control?.max !== void 0 && step.value > control.max;
6363
+ if (below || above) return {
6364
+ ok: false,
6365
+ reason: "out-of-range",
6366
+ detail: `${step.field} ${step.value} is outside ${control?.min}…${control?.max} of ${describe(read)}`
6367
+ };
6368
+ await ports.setControl(source.id, {
6369
+ kind: "numeric",
6370
+ value: step.value
6371
+ });
6372
+ return { ok: true };
6373
+ } catch (err) {
6374
+ const why = err instanceof Error ? err.message : String(err);
6375
+ return {
6376
+ ok: false,
6377
+ reason: "source-call-failed",
6378
+ detail: `${describe(read)}: ${why}`
6379
+ };
6380
+ }
6381
+ }
6382
+ async function setOscillationAxis(ports, call) {
6383
+ const parsed = require_dist.SetOscillationAxisInputSchema.safeParse(call.args);
6384
+ if (!parsed.success) return NOT_REDIRECTED;
6385
+ const steps = requestedSteps(parsed.data);
6386
+ const links = await linksOf(ports, call.deviceId);
6387
+ const linked = (step) => links.get(require_dist.fanAxisPath(parsed.data.axis, step.field));
6388
+ if (steps.length > 0 && steps.every((s) => linked(s) === void 0)) return NOT_REDIRECTED;
6389
+ const refuse = (reason, detail, applied, field) => {
6390
+ ports.logger.warn("fan: an oscillation axis write was refused", {
6391
+ tags: { deviceId: call.deviceId },
6392
+ meta: {
6393
+ axis: parsed.data.axis,
6394
+ reason,
6395
+ field,
6396
+ detail,
6397
+ applied
6398
+ }
6399
+ });
6400
+ return {
6401
+ kind: "redirected",
6402
+ result: {
6403
+ status: "refused",
6404
+ reason,
6405
+ detail,
6406
+ applied: [...applied],
6407
+ ...field === void 0 ? {} : { field }
6408
+ }
6409
+ };
6410
+ };
6411
+ if (steps.length === 0) return refuse("nothing-to-set", "no axis field was given", []);
6412
+ const applied = [];
6413
+ for (const step of steps) {
6414
+ const read = linked(step);
6415
+ if (read === void 0) return refuse("axis-not-linked", `${parsed.data.axis} ${step.field} is not linked in Customize, and a call is never split between a link and the native provider`, applied, step.field);
6416
+ const outcome = await writeStep(ports, read, step);
6417
+ if (!outcome.ok) return refuse(outcome.reason, outcome.detail, applied, step.field);
6418
+ applied.push(step.field);
6419
+ }
6420
+ return {
6421
+ kind: "redirected",
6422
+ result: { status: "applied" }
6423
+ };
6424
+ }
6425
+ async function setPreset(ports, call) {
6426
+ const parsed = SetPresetArgsSchema.safeParse(call.args);
6427
+ if (!parsed.success) return NOT_REDIRECTED;
6428
+ const read = (await linksOf(ports, call.deviceId)).get("preset");
6429
+ if (read === void 0) return NOT_REDIRECTED;
6430
+ const refuse = (reason, detail) => {
6431
+ ports.logger.warn("fan: a preset write was refused", {
6432
+ tags: { deviceId: call.deviceId },
6433
+ meta: {
6434
+ reason,
6435
+ detail,
6436
+ preset: parsed.data.preset
6437
+ }
6438
+ });
6439
+ throw new FanPresetRefusedError(reason, detail);
6440
+ };
6441
+ if (read.cap !== "control" || read.fieldPath !== "value") return refuse("axis-not-linked", `preset is linked to ${describe(read)}, which takes no command`);
6442
+ const source = await resolveSource(ports, read);
6443
+ if (!source.ok) return refuse(source.reason, source.detail);
6444
+ let control;
6445
+ try {
6446
+ control = await ports.readControl(source.id);
6447
+ } catch (err) {
6448
+ const why = err instanceof Error ? err.message : String(err);
6449
+ return refuse("source-unknown", `${describe(read)}: ${why}`);
6450
+ }
6451
+ if (control === null || control.kind !== "select" || !control.options.includes(parsed.data.preset)) {
6452
+ const offered = control === null ? "none read" : control.options.join(", ");
6453
+ return refuse("out-of-range", `"${parsed.data.preset}" is not an option of ${describe(read)} (${offered})`);
6454
+ }
6455
+ try {
6456
+ await ports.setControl(source.id, {
6457
+ kind: "select",
6458
+ value: parsed.data.preset
6459
+ });
6460
+ } catch (err) {
6461
+ const why = err instanceof Error ? err.message : String(err);
6462
+ return refuse("source-call-failed", `${describe(read)}: ${why}`);
6463
+ }
6464
+ return {
6465
+ kind: "redirected",
6466
+ result: void 0
6467
+ };
6468
+ }
6469
+ function fanLinkForwardRedirect(ports) {
6470
+ return {
6471
+ covers: (capName, method) => capName === FAN_CONTROL && (method === "setOscillationAxis" || method === "setPreset"),
6472
+ attempt: async (call) => {
6473
+ if (call.method === "setOscillationAxis") return setOscillationAxis(ports, call);
6474
+ if (call.method === "setPreset") return setPreset(ports, call);
6475
+ return NOT_REDIRECTED;
6476
+ }
6477
+ };
6478
+ }
6479
+ //#endregion
6216
6480
  //#region src/builtins/core-blocks/remote-call-redirect.ts
6217
6481
  /**
6218
6482
  * The device-call redirect the remote installs into the capability registry
@@ -6358,7 +6622,7 @@ function rolesFor(command) {
6358
6622
  case "playMedia": return [];
6359
6623
  }
6360
6624
  }
6361
- function errorText(err) {
6625
+ function errorText$1(err) {
6362
6626
  return err instanceof Error ? err.message : String(err);
6363
6627
  }
6364
6628
  var RemoteService = class {
@@ -6461,7 +6725,7 @@ var RemoteService = class {
6461
6725
  } catch (err) {
6462
6726
  this.deps.logger.warn("remote: the media-player slice could not be written", {
6463
6727
  tags: { deviceId },
6464
- meta: { error: errorText(err) }
6728
+ meta: { error: errorText$1(err) }
6465
6729
  });
6466
6730
  }
6467
6731
  }
@@ -6859,13 +7123,13 @@ var RemoteService = class {
6859
7123
  meta: {
6860
7124
  source: source.name,
6861
7125
  transmitterId,
6862
- error: errorText(err)
7126
+ error: errorText$1(err)
6863
7127
  }
6864
7128
  });
6865
7129
  return {
6866
7130
  status: "refused",
6867
7131
  reason: "action-failed",
6868
- detail: errorText(err)
7132
+ detail: errorText$1(err)
6869
7133
  };
6870
7134
  }
6871
7135
  const kept = await this.readAssumed(deviceId);
@@ -6933,13 +7197,13 @@ var RemoteService = class {
6933
7197
  meta: {
6934
7198
  role,
6935
7199
  sent,
6936
- error: errorText(err)
7200
+ error: errorText$1(err)
6937
7201
  }
6938
7202
  });
6939
7203
  return {
6940
7204
  status: "refused",
6941
7205
  reason: "action-failed",
6942
- detail: errorText(err)
7206
+ detail: errorText$1(err)
6943
7207
  };
6944
7208
  }
6945
7209
  }
@@ -7406,12 +7670,11 @@ function parseFanPresetActionId(addonId, actionId) {
7406
7670
  presetId: rest.slice(slash + 1)
7407
7671
  };
7408
7672
  }
7409
- /** The first step that did not apply, as "step 1 (switch.setState on 11): …". */
7673
+ /** The first field that did not apply, as "oscillationAxes.horizontal.angle: …". */
7410
7674
  function firstProblem(result) {
7411
- const bad = result.steps.find((s) => s.outcome === "failed" || s.outcome === "refused");
7675
+ const bad = result.fields.find((f) => f.outcome === "failed" || f.outcome === "refused");
7412
7676
  if (bad === void 0) return result.status === "refused" ? "the preset was not applied" : "";
7413
- const what = bad.cap === void 0 ? "" : ` (${bad.cap}.${bad.method ?? "?"}${bad.deviceId === void 0 ? "" : ` on ${bad.deviceId}`})`;
7414
- return `step ${bad.index}${what}: ${bad.message ?? bad.outcome}`;
7677
+ return `${bad.field}: ${bad.message ?? bad.outcome}`;
7415
7678
  }
7416
7679
  var FanPresetActionSource = class {
7417
7680
  deps;
@@ -7453,66 +7716,186 @@ var FanPresetActionSource = class {
7453
7716
  throw new Error(`fan preset ${result.status}: ${problem}`);
7454
7717
  }
7455
7718
  async stopAction(input) {
7456
- this.deps.logger.debug("fan preset stop ignored — a preset is a few quick steps", { meta: { actionId: input.actionId } });
7719
+ this.deps.logger.debug("fan preset stop ignored — a preset is a few quick fan-control calls", { meta: { actionId: input.actionId } });
7457
7720
  }
7458
7721
  };
7459
7722
  //#endregion
7460
7723
  //#region src/builtins/core-blocks/fan-presets-service.ts
7461
7724
  /**
7462
- * The `fan-presets` cap: named settings an operator composes for a fan — its
7463
- * own fields (speed, oscillation, direction, native preset) and the devices
7464
- * that sit in the same container (a light, a control). A preset is a short
7465
- * sequence of action steps kept in the fan's settings store (D865, key
7725
+ * The `fan-presets` cap: named DESIRED fan-control states an operator keeps
7726
+ * for a fan (D1034) — speed, the fan's preset mode, direction and the
7727
+ * oscillation axes — stored in the fan's settings store (D865, key
7466
7728
  * `fanPresets`).
7467
7729
  *
7468
7730
  * Decisions that shape this file:
7469
- * - **A step may only touch the fan or one of its siblings.** The sibling
7470
- * set is the children of the fan's parent device (the container), or the
7471
- * fan's own children when it has none. Checked at save AND again at apply,
7472
- * because the container changes after a preset was written.
7473
- * - **Apply runs the shared step runner** (`buildActionSteps` + `runSteps`),
7474
- * in order, stopping at the first failure; every step is reported and a
7475
- * failure names its step (D391). Nothing the operator did not write runs.
7476
- * - **Capture never stores a guess.** A reading that is unknown is left out
7477
- * and named, never written as 0 (D393).
7731
+ * - **A preset touches only the fan, through its own `fan-control` methods.**
7732
+ * An axis the operator linked in Customize reaches its sibling device
7733
+ * through the link's forward (`fan-link-forward.ts`), so a preset stores no
7734
+ * sibling and is never re-judged when the container changes.
7735
+ * - **Apply runs in a fixed order and stops at the first failure**: preset,
7736
+ * speed, direction, then each axis. Every field is reported — applied,
7737
+ * failed, not-run or refused — and a failure names its field (D391).
7738
+ * - **Capture never stores a guess.** It reads the fan's merged fan-control
7739
+ * state (a linked field reads its link); a reading that is unknown is left
7740
+ * out and named, never written as 0 (D393).
7478
7741
  */
7479
7742
  function nameKey(name) {
7480
7743
  return name.trim().toLowerCase();
7481
7744
  }
7482
- function fanTarget(deviceId) {
7745
+ function axisFields(axis) {
7746
+ if (axis === void 0) return [];
7747
+ return require_dist.FAN_OSCILLATION_AXIS_SETTABLE.filter((f) => axis[f] !== void 0);
7748
+ }
7749
+ /** Every state path a preset sets, in apply order. */
7750
+ function presetFields(state) {
7751
+ return [
7752
+ ...state.preset === void 0 ? [] : ["preset"],
7753
+ ...state.speed === void 0 ? [] : ["speed"],
7754
+ ...state.direction === void 0 ? [] : ["direction"],
7755
+ ...require_dist.FAN_OSCILLATION_AXES.flatMap((axis) => axisFields(state.oscillationAxes?.[axis]).map((f) => `oscillationAxes.${axis}.${f}`))
7756
+ ];
7757
+ }
7758
+ function errorText(err) {
7759
+ return err instanceof Error ? err.message : String(err);
7760
+ }
7761
+ function plainStep(field, call) {
7483
7762
  return {
7484
- kind: "devices",
7485
- ids: [deviceId]
7763
+ fields: [field],
7764
+ run: async () => {
7765
+ try {
7766
+ await call();
7767
+ return [{
7768
+ field,
7769
+ outcome: "applied"
7770
+ }];
7771
+ } catch (err) {
7772
+ return [{
7773
+ field,
7774
+ outcome: "failed",
7775
+ message: errorText(err)
7776
+ }];
7777
+ }
7778
+ }
7486
7779
  };
7487
7780
  }
7488
- function fanStep(deviceId, method, args) {
7781
+ function axisStep(fan, deviceId, axis, want) {
7782
+ const fields = axisFields(want);
7783
+ const path = (f) => `oscillationAxes.${axis}.${f}`;
7489
7784
  return {
7490
- kind: "cap",
7491
- target: fanTarget(deviceId),
7492
- cap: "fan-control",
7493
- method,
7494
- args
7785
+ fields: fields.map(path),
7786
+ run: async () => {
7787
+ let result;
7788
+ try {
7789
+ result = await fan.setOscillationAxis({
7790
+ deviceId,
7791
+ axis,
7792
+ ...want
7793
+ });
7794
+ } catch (err) {
7795
+ const message = errorText(err);
7796
+ return fields.map((f) => ({
7797
+ field: path(f),
7798
+ outcome: "failed",
7799
+ message
7800
+ }));
7801
+ }
7802
+ if (result.status === "applied") return fields.map((f) => ({
7803
+ field: path(f),
7804
+ outcome: "applied"
7805
+ }));
7806
+ return fields.map((f) => {
7807
+ if (result.applied.some((a) => a === f)) return {
7808
+ field: path(f),
7809
+ outcome: "applied"
7810
+ };
7811
+ if (result.field === f || result.field === void 0) return {
7812
+ field: path(f),
7813
+ outcome: "refused",
7814
+ message: `${result.reason}: ${result.detail}`
7815
+ };
7816
+ return {
7817
+ field: path(f),
7818
+ outcome: "not-run",
7819
+ message: `${result.field} was refused first`
7820
+ };
7821
+ });
7822
+ }
7495
7823
  };
7496
7824
  }
7497
- var RANK_BOUND = 0;
7498
- var RANK_SWITCH = 1;
7499
- var RANK_OSCILLATING = 1;
7500
- var RANK_ANGLE = 2;
7501
- var RANK_GIVEN = 3;
7502
- var FAN_FIELD_RANK = {
7503
- oscillating: RANK_OSCILLATING,
7504
- direction: 4,
7505
- preset: 5,
7506
- speed: 6
7507
- };
7508
- /** A control that sets one end of the sweep (left/right, top/bottom), by its name. */
7509
- var ANGLE_BOUND_NAME = /oscillazione.*(sinistra|destra|alto|basso)|oscillation.*(left|right|top|bottom|upper|lower)/i;
7510
- function orderProposals(proposals, omitted) {
7511
- const sorted = [...proposals].sort((a, b) => a.rank - b.rank);
7512
- const items = sorted.map((p) => p.item);
7825
+ function applySteps(fan, deviceId, state) {
7826
+ const { preset, speed, direction } = state;
7827
+ return [
7828
+ ...preset === void 0 ? [] : [plainStep("preset", () => fan.setPreset(deviceId, preset))],
7829
+ ...speed === void 0 ? [] : [plainStep("speed", () => fan.setPercentage(deviceId, speed))],
7830
+ ...direction === void 0 ? [] : [plainStep("direction", () => fan.setDirection(deviceId, direction))],
7831
+ ...require_dist.FAN_OSCILLATION_AXES.flatMap((axis) => {
7832
+ const want = state.oscillationAxes?.[axis];
7833
+ return want === void 0 || axisFields(want).length === 0 ? [] : [axisStep(fan, deviceId, axis, want)];
7834
+ })
7835
+ ];
7836
+ }
7837
+ var UNKNOWN = "the fan reports no value for it";
7838
+ function captureAxis(axis, reading) {
7839
+ if (reading === null || reading === void 0) return {
7840
+ want: null,
7841
+ omitted: [{
7842
+ what: `oscillationAxes.${axis}`,
7843
+ reason: "the fan has no such axis"
7844
+ }]
7845
+ };
7846
+ const omitted = [];
7847
+ const want = {};
7848
+ if (reading.oscillating === null) omitted.push({
7849
+ what: require_dist.fanAxisPath(axis, "oscillating"),
7850
+ reason: UNKNOWN
7851
+ });
7852
+ else want.oscillating = reading.oscillating;
7853
+ for (const field of [
7854
+ "angle",
7855
+ "sweepFrom",
7856
+ "sweepTo"
7857
+ ]) {
7858
+ const value = reading[field];
7859
+ if (value === null) omitted.push({
7860
+ what: require_dist.fanAxisPath(axis, field),
7861
+ reason: UNKNOWN
7862
+ });
7863
+ else want[field] = value;
7864
+ }
7513
7865
  return {
7514
- steps: sorted.map((p) => p.step),
7515
- items,
7866
+ want: Object.keys(want).length === 0 ? null : want,
7867
+ omitted
7868
+ };
7869
+ }
7870
+ function captureState(status, fields) {
7871
+ const omitted = [];
7872
+ const state = {};
7873
+ if (fields.includes("speed")) if (status.speed === null) omitted.push({
7874
+ what: "speed",
7875
+ reason: UNKNOWN
7876
+ });
7877
+ else state.speed = status.speed;
7878
+ if (fields.includes("direction")) if (status.direction === null) omitted.push({
7879
+ what: "direction",
7880
+ reason: UNKNOWN
7881
+ });
7882
+ else state.direction = status.direction;
7883
+ if (fields.includes("preset")) if (status.preset === "") omitted.push({
7884
+ what: "preset",
7885
+ reason: "no preset is active"
7886
+ });
7887
+ else state.preset = status.preset;
7888
+ if (fields.includes("oscillationAxes")) {
7889
+ const axes = {};
7890
+ for (const axis of require_dist.FAN_OSCILLATION_AXES) {
7891
+ const taken = captureAxis(axis, status.oscillationAxes?.[axis]);
7892
+ omitted.push(...taken.omitted);
7893
+ if (taken.want !== null) axes[axis] = taken.want;
7894
+ }
7895
+ if (Object.keys(axes).length > 0) state.oscillationAxes = axes;
7896
+ }
7897
+ return {
7898
+ state,
7516
7899
  omitted
7517
7900
  };
7518
7901
  }
@@ -7551,11 +7934,7 @@ var FanPresetsService = class {
7551
7934
  const key = nameKey(preset.name);
7552
7935
  if (names.has(key)) return refuse("duplicate-name", `two presets are called "${preset.name.trim()}"`);
7553
7936
  names.add(key);
7554
- }
7555
- const siblings = await this.siblingsOf(deviceId, facts);
7556
- for (const preset of presets) for (const [index, step] of preset.steps.entries()) {
7557
- const refusal = this.judgeStep(step, siblings);
7558
- if (refusal !== null) return refuse(refusal.reason, `preset "${preset.name}" step ${index}: ${refusal.message}`);
7937
+ if (presetFields(preset.state).length === 0) return refuse("empty-state", `preset "${preset.name.trim()}" sets nothing`);
7559
7938
  }
7560
7939
  await this.deps.store.write(deviceId, presets);
7561
7940
  this.deps.logger.info("fan presets saved", {
@@ -7577,305 +7956,59 @@ var FanPresetsService = class {
7577
7956
  });
7578
7957
  return {
7579
7958
  status: "refused",
7580
- steps: []
7959
+ fields: []
7581
7960
  };
7582
7961
  }
7583
- const facts = await this.deps.devices.describe(deviceId);
7584
- const siblings = await this.siblingsOf(deviceId, facts);
7585
- const refused = this.refusedSteps(preset, siblings);
7586
- if (refused !== null) {
7587
- this.deps.logger.warn("fan preset apply refused — a step left the fan container", {
7588
- tags: { deviceId },
7589
- meta: {
7590
- presetId,
7591
- name: preset.name
7592
- }
7593
- });
7594
- return {
7595
- status: "refused",
7596
- steps: refused
7597
- };
7598
- }
7599
- const result = await require_dist.runSteps(require_dist.buildActionSteps(preset.steps, {}, {
7600
- invokeCap: (call) => this.deps.invoke(call),
7601
- sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
7602
- resolveTarget: async (target) => ({ deviceIds: target.kind === "devices" ? target.ids : [] }),
7603
- owner: `fan-preset:${deviceId}/${presetId}`,
7604
- renderTemplates: stepRenderer(this.deps.templates, [deviceId]),
7605
- ...conditionDeps(stepConditionEvaluator(this.deps.conditions, [deviceId])),
7606
- onMissingVar: () => void 0
7607
- }), {
7608
- pathPrefix: "steps",
7609
- isAborted: () => false,
7610
- abortReason: "the run was stopped",
7611
- now: this.deps.now ?? Date.now,
7612
- onFailure: (failure) => {
7613
- this.deps.logger.warn("fan preset step failed — stopping the sequence", {
7614
- tags: { deviceId: failure.deviceId ?? deviceId },
7615
- meta: {
7616
- fanDeviceId: deviceId,
7617
- presetId,
7618
- step: failure.index,
7619
- error: failure.message
7620
- }
7621
- });
7622
- },
7623
- onGuardUnknown: (skipped) => {
7624
- this.deps.logger.warn("fan preset step skipped — its condition could not be read", {
7625
- tags: { deviceId: skipped.deviceId ?? deviceId },
7626
- meta: {
7627
- fanDeviceId: deviceId,
7628
- presetId,
7629
- step: skipped.index,
7630
- reason: skipped.reason
7631
- }
7632
- });
7962
+ const results = [];
7963
+ let stopped = null;
7964
+ for (const step of applySteps(this.deps.fanControl, deviceId, preset.state)) {
7965
+ if (stopped !== null) {
7966
+ results.push(...step.fields.map((field) => ({
7967
+ field,
7968
+ outcome: "not-run",
7969
+ message: `${stopped} did not apply`
7970
+ })));
7971
+ continue;
7633
7972
  }
7634
- });
7635
- const steps = result.steps.map((trace, index) => ({
7636
- index,
7637
- outcome: trace.outcome === "ok" ? "applied" : trace.outcome === "not-run" ? "not-run" : "failed",
7638
- ...trace.deviceId === void 0 ? {} : { deviceId: trace.deviceId },
7639
- ...trace.cap === void 0 ? {} : { cap: trace.cap },
7640
- ...trace.method === void 0 ? {} : { method: trace.method },
7641
- ...trace.message === void 0 ? {} : { message: trace.message }
7642
- }));
7643
- const failed = steps.some((s) => s.outcome === "failed");
7644
- const appliedCap = result.steps.some((t) => t.kind === "cap" && t.outcome === "ok");
7645
- const status = !failed ? "applied" : appliedCap ? "partial" : "refused";
7646
- this.deps.logger.info("fan preset applied", {
7973
+ const outcome = await step.run();
7974
+ results.push(...outcome);
7975
+ const bad = outcome.find((r) => r.outcome !== "applied");
7976
+ if (bad !== void 0) stopped = bad.field;
7977
+ }
7978
+ const landed = results.filter((r) => r.outcome === "applied").length;
7979
+ const status = stopped === null ? "applied" : landed > 0 ? "partial" : "refused";
7980
+ const log = status === "applied" ? "info" : "warn";
7981
+ this.deps.logger[log](`fan preset ${status}`, {
7647
7982
  tags: { deviceId },
7648
7983
  meta: {
7649
7984
  presetId,
7650
- status,
7651
- steps: steps.length
7985
+ fields: results.map((r) => `${r.field}=${r.outcome}`),
7986
+ ...stopped === null ? {} : { stoppedAt: stopped }
7652
7987
  }
7653
7988
  });
7654
7989
  return {
7655
7990
  status,
7656
- steps
7991
+ fields: results
7657
7992
  };
7658
7993
  }
7659
7994
  async capturePreset(input) {
7660
- const { deviceId } = input;
7661
7995
  const fields = input.fields ?? require_dist.FAN_CAPTURE_FIELDS;
7662
- const omitted = [];
7663
- const omit = (what, reason) => {
7664
- omitted.push({
7665
- what,
7666
- reason
7667
- });
7668
- this.deps.logger.info("fan preset capture left a value out", {
7669
- tags: { deviceId },
7670
- meta: {
7996
+ const status = await this.deps.readings.fan(input.deviceId);
7997
+ if (status === null) {
7998
+ this.deps.logger.warn("fan preset capture: the fan state could not be read", { tags: { deviceId: input.deviceId } });
7999
+ return {
8000
+ state: {},
8001
+ omitted: fields.map((what) => ({
7671
8002
  what,
7672
- reason
7673
- }
7674
- });
7675
- };
7676
- const fanSteps = await this.captureFanFields(deviceId, fields, omit);
7677
- return orderProposals([...input.steps.length === 0 ? await this.captureSiblings(deviceId, omit) : await this.captureGiven(deviceId, input.steps, omit), ...fanSteps], omitted);
7678
- }
7679
- async captureFanFields(deviceId, fields, omit) {
7680
- const out = [];
7681
- const fan = await this.deps.readings.fan(deviceId);
7682
- for (const field of require_dist.FAN_CAPTURE_FIELDS) {
7683
- if (!fields.includes(field)) continue;
7684
- if (fan === null) {
7685
- omit(field, "the fan reports no current state");
7686
- continue;
7687
- }
7688
- const captured = this.fanFieldStep(deviceId, field, fan);
7689
- if (captured === null) omit(field, `${field} is unknown on this fan`);
7690
- else out.push({
7691
- step: captured,
7692
- rank: FAN_FIELD_RANK[field],
7693
- item: {
7694
- group: field === "oscillating" ? "oscillation" : "fan",
7695
- label: field
7696
- }
7697
- });
7698
- }
7699
- return out;
7700
- }
7701
- /** The steps the caller composed, each refreshed with its current value. */
7702
- async captureGiven(deviceId, steps, omit) {
7703
- const out = [];
7704
- for (const [index, step] of steps.entries()) {
7705
- if (step.kind === "wait") {
7706
- out.push({
7707
- step,
7708
- rank: RANK_GIVEN,
7709
- item: {
7710
- group: "fan",
7711
- label: "wait"
7712
- }
7713
- });
7714
- continue;
7715
- }
7716
- const target = require_dist.normalizeCapStep(step).target;
7717
- if (target.kind !== "devices" || target.ids.length !== 1) {
7718
- omit(`step ${index}`, "its target is not one device, so there is no value to read");
7719
- continue;
7720
- }
7721
- const [targetId] = target.ids;
7722
- if (targetId === void 0 || targetId === deviceId) continue;
7723
- const captured = await this.siblingStep(step, targetId);
7724
- if (captured.step === null) omit(`step ${index}`, captured.reason);
7725
- else out.push({
7726
- step: captured.step,
7727
- rank: RANK_GIVEN,
7728
- item: {
7729
- group: step.cap === "switch" ? "oscillation" : "angles",
7730
- label: `step ${index}`
7731
- }
7732
- });
7733
- }
7734
- return out;
7735
- }
7736
- /** Every switch and control in the fan's container, read as they are now. */
7737
- async captureSiblings(deviceId, omit) {
7738
- const out = [];
7739
- const facts = await this.deps.devices.describe(deviceId);
7740
- const siblings = await this.siblingsOf(deviceId, facts);
7741
- for (const id of siblings) {
7742
- if (id === deviceId) continue;
7743
- const sibling = await this.deps.devices.describe(id);
7744
- if (sibling === null) continue;
7745
- if (sibling.type === require_dist.DeviceType.Switch) {
7746
- const status = await this.deps.readings.switchState(id);
7747
- if (status === null) {
7748
- omit(sibling.name, `switch ${id} reports no state`);
7749
- continue;
7750
- }
7751
- out.push({
7752
- step: {
7753
- kind: "cap",
7754
- target: fanTarget(id),
7755
- cap: "switch",
7756
- method: "setState",
7757
- args: { on: status.on }
7758
- },
7759
- rank: RANK_SWITCH,
7760
- item: {
7761
- group: "oscillation",
7762
- label: sibling.name
7763
- }
7764
- });
7765
- } else if (sibling.type === require_dist.DeviceType.Control) {
7766
- const status = await this.deps.readings.control(id);
7767
- if (status === null) {
7768
- omit(sibling.name, `control ${id} reports no value`);
7769
- continue;
7770
- }
7771
- out.push({
7772
- step: {
7773
- kind: "cap",
7774
- target: fanTarget(id),
7775
- cap: "control",
7776
- method: "setValue",
7777
- args: { control: {
7778
- kind: status.kind,
7779
- value: status.value
7780
- } }
7781
- },
7782
- rank: ANGLE_BOUND_NAME.test(sibling.name) ? RANK_BOUND : RANK_ANGLE,
7783
- item: {
7784
- group: "angles",
7785
- label: sibling.name
7786
- }
7787
- });
7788
- }
7789
- }
7790
- return out;
7791
- }
7792
- fanFieldStep(deviceId, field, fan) {
7793
- switch (field) {
7794
- case "speed": return fan.speed === null ? null : fanStep(deviceId, "setPercentage", { speed: fan.speed });
7795
- case "oscillating": return fan.oscillating === null ? null : fanStep(deviceId, "setOscillating", { oscillating: fan.oscillating });
7796
- case "direction": return fan.direction === null ? null : fanStep(deviceId, "setDirection", { direction: fan.direction });
7797
- case "preset": return fan.preset === "" ? null : fanStep(deviceId, "setPreset", { preset: fan.preset });
7798
- }
7799
- }
7800
- async siblingStep(step, targetId) {
7801
- if (step.cap === "control" && step.method === "setValue") {
7802
- const status = await this.deps.readings.control(targetId);
7803
- if (status === null) return {
7804
- step: null,
7805
- reason: `control ${targetId} reports no value`
7806
- };
7807
- return { step: {
7808
- ...step,
7809
- args: {
7810
- ...step.args,
7811
- control: {
7812
- kind: status.kind,
7813
- value: status.value
7814
- }
7815
- }
7816
- } };
7817
- }
7818
- if (step.cap === "switch" && step.method === "setState") {
7819
- const status = await this.deps.readings.switchState(targetId);
7820
- if (status === null) return {
7821
- step: null,
7822
- reason: `switch ${targetId} reports no state`
8003
+ reason: "the fan state could not be read"
8004
+ }))
7823
8005
  };
7824
- return { step: {
7825
- ...step,
7826
- args: {
7827
- ...step.args,
7828
- on: status.on
7829
- }
7830
- } };
7831
8006
  }
8007
+ const captured = captureState(status, fields);
7832
8008
  return {
7833
- step: null,
7834
- reason: `${step.cap}.${step.method} has no current value to read`
7835
- };
7836
- }
7837
- /** The fan and every device in its container. */
7838
- async siblingsOf(deviceId, facts) {
7839
- const parent = facts?.parentDeviceId ?? null;
7840
- const children = await this.deps.devices.childrenOf(parent ?? deviceId);
7841
- return new Set([deviceId, ...children]);
7842
- }
7843
- judgeStep(step, siblings) {
7844
- if (step.kind === "wait") return null;
7845
- const target = require_dist.normalizeCapStep(step).target;
7846
- if (target.kind !== "devices") return {
7847
- reason: "bad-target",
7848
- message: "a preset step names devices, not a domain or variable"
7849
- };
7850
- const outside = target.ids.filter((id) => !siblings.has(id));
7851
- if (outside.length > 0) return {
7852
- reason: "not-sibling",
7853
- message: `[not-sibling] device ${outside.join(", ")} is not in the fan's container`
8009
+ state: captured.state,
8010
+ omitted: [...captured.omitted]
7854
8011
  };
7855
- return null;
7856
- }
7857
- /** Every step reported, the offending ones `refused`, nothing run; null when all pass. */
7858
- refusedSteps(preset, siblings) {
7859
- const verdicts = preset.steps.map((step) => this.judgeStep(step, siblings));
7860
- if (verdicts.every((v) => v === null)) return null;
7861
- return preset.steps.map((step, index) => {
7862
- const verdict = verdicts[index] ?? null;
7863
- const where = step.kind === "cap" ? {
7864
- cap: step.cap,
7865
- method: step.method
7866
- } : {};
7867
- return verdict === null ? {
7868
- index,
7869
- outcome: "not-run",
7870
- ...where,
7871
- message: "an earlier step was refused"
7872
- } : {
7873
- index,
7874
- outcome: "refused",
7875
- ...where,
7876
- message: verdict.message.startsWith("[") ? verdict.message : `[${verdict.reason}] ${verdict.message}`
7877
- };
7878
- });
7879
8012
  }
7880
8013
  };
7881
8014
  //#endregion
@@ -7883,8 +8016,8 @@ var FanPresetsService = class {
7883
8016
  /**
7884
8017
  * Builds the `fan-presets` runtime out of what core-blocks owns: the
7885
8018
  * per-device settings store (D865: a fan's presets live under the key
7886
- * `fanPresets`) and the cluster API (a device's type and container, the
7887
- * current readings, the cap call a step makes).
8019
+ * `fanPresets`) and the cluster API (a device's type, the fan's current
8020
+ * fan-control state, the fan-control calls a preset makes).
7888
8021
  *
7889
8022
  * Kept out of `core-blocks.addon.ts` so the seams are read and specced
7890
8023
  * without booting the addon.
@@ -7927,18 +8060,41 @@ function fanPresetsDevicesOver(api) {
7927
8060
  if (current === void 0) throw new Error("core-blocks: no ctx.api — devices cannot be read");
7928
8061
  return current;
7929
8062
  };
8063
+ return { describe: async (deviceId) => {
8064
+ const found = await need().deviceManager.getDevice.query({ deviceId });
8065
+ return found === null || found === void 0 ? null : {
8066
+ name: found.name,
8067
+ type: found.type
8068
+ };
8069
+ } };
8070
+ }
8071
+ /** The fan's own fan-control methods, through `ctx.api` (a linked field is forwarded at dispatch). */
8072
+ function fanPresetsFanControlOver(api) {
8073
+ const need = () => {
8074
+ const current = api();
8075
+ if (current === void 0) throw new Error("core-blocks: no ctx.api — the fan cannot be reached");
8076
+ return current;
8077
+ };
7930
8078
  return {
7931
- describe: async (deviceId) => {
7932
- const found = await need().deviceManager.getDevice.query({ deviceId });
7933
- return found === null || found === void 0 ? null : {
7934
- name: found.name,
7935
- type: found.type,
7936
- parentDeviceId: found.parentDeviceId
7937
- };
8079
+ setPreset: async (deviceId, preset) => {
8080
+ await need().fanControl.setPreset.mutate({
8081
+ deviceId,
8082
+ preset
8083
+ });
7938
8084
  },
7939
- childrenOf: async (parentDeviceId) => {
7940
- return (await need().deviceManager.getChildren.query({ parentDeviceId })).map((row) => row.id);
7941
- }
8085
+ setPercentage: async (deviceId, speed) => {
8086
+ await need().fanControl.setPercentage.mutate({
8087
+ deviceId,
8088
+ speed
8089
+ });
8090
+ },
8091
+ setDirection: async (deviceId, direction) => {
8092
+ await need().fanControl.setDirection.mutate({
8093
+ deviceId,
8094
+ direction
8095
+ });
8096
+ },
8097
+ setOscillationAxis: async (input) => need().fanControl.setOscillationAxis.mutate(input)
7942
8098
  };
7943
8099
  }
7944
8100
  /** A reading that errors or does not parse is unknown (null), never a default (D393). */
@@ -7957,11 +8113,7 @@ function fanPresetsReadingsOver(api, logger) {
7957
8113
  return null;
7958
8114
  }
7959
8115
  };
7960
- return {
7961
- fan: (deviceId) => read(deviceId, "fan-control", (a) => a.fanControl.getStatus.query({ deviceId }), require_dist.FanControlStatusSchema),
7962
- control: (deviceId) => read(deviceId, "control", (a) => a.control.getStatus.query({ deviceId }), require_dist.ControlStatusSchema),
7963
- switchState: (deviceId) => read(deviceId, "switch", (a) => a.switch.getStatus.query({ deviceId }), require_dist.SwitchStatusSchema)
7964
- };
8116
+ return { fan: (deviceId) => read(deviceId, "fan-control", (a) => a.fanControl.getStatus.query({ deviceId }), require_dist.FanControlStatusSchema) };
7965
8117
  }
7966
8118
  function buildFanPresetsRuntime(deps) {
7967
8119
  const store = fanPresetsStoreOver(deps.settings, deps.logger.child("fan-presets"));
@@ -7970,9 +8122,7 @@ function buildFanPresetsRuntime(deps) {
7970
8122
  store,
7971
8123
  devices,
7972
8124
  readings: fanPresetsReadingsOver(deps.api, deps.logger.child("fan-presets")),
7973
- invoke: invokeCapOver(deps.api),
7974
- templates: templateDoorOver(deps.api),
7975
- conditions: conditionDoorOver(deps.api),
8125
+ fanControl: fanPresetsFanControlOver(deps.api),
7976
8126
  logger: deps.logger.child("fan-presets")
7977
8127
  });
7978
8128
  return {
@@ -8438,7 +8588,7 @@ async function validateAgainstStore(deps, composition, blockId) {
8438
8588
  const ownKeys = new Set([self, target].flatMap((ref) => ref === null ? [] : [require_dist.compositionSourceKey(ref)]));
8439
8589
  const refs = require_dist.compositionSourceRefs(composition).filter((r) => !ownKeys.has(require_dist.compositionSourceKey(r)));
8440
8590
  const blocks = deps.store.list();
8441
- const read = await deps.describe(refs, [...target === null ? [] : [target], ...storedCustomizationTargets(blocks)]);
8591
+ const read = await deps.describe(refs, [...target === null ? [] : [target], ...storedCustomizationTargets(blocks)], require_dist.compositionUnionReads(composition, deps.lookupCap));
8442
8592
  const stored = storedPeers(blocks, read.targets, deps.lookupCap, blockId);
8443
8593
  return {
8444
8594
  validation: require_dist.validateComposition(composition, {
@@ -9108,11 +9258,57 @@ var CoreBlocksAddon = class extends require_dist.BaseAddon {
9108
9258
  this.seedLockDoorGate = () => this.seedGate(gate);
9109
9259
  this.seedLockDoorGate();
9110
9260
  const runtime = this.remoteRuntime;
9111
- registry.setDeviceCallRedirect(composeRedirects([...runtime === null ? [] : [remoteCallRedirect({
9112
- remote: runtime.remote,
9113
- hasNative: (deviceId) => this.hasNativeMediaPlayer(deviceId),
9114
- logger: this.ctx.logger.child("remote")
9115
- })], gate.redirect()]));
9261
+ registry.setDeviceCallRedirect(composeRedirects([
9262
+ ...runtime === null ? [] : [remoteCallRedirect({
9263
+ remote: runtime.remote,
9264
+ hasNative: (deviceId) => this.hasNativeMediaPlayer(deviceId),
9265
+ logger: this.ctx.logger.child("remote")
9266
+ })],
9267
+ gate.redirect(),
9268
+ fanLinkForwardRedirect(this.fanLinkPorts())
9269
+ ]));
9270
+ }
9271
+ /** The fan link forward's reach (D1034): the stored blocks and the linked devices, through `ctx.api`. */
9272
+ fanLinkPorts() {
9273
+ const requireApi = () => {
9274
+ const api = this.ctx.api;
9275
+ if (!api) throw new Error("core-blocks: no ctx.api on this node — a fan link cannot be reached");
9276
+ return api;
9277
+ };
9278
+ return {
9279
+ blocks: () => this.requireStore().list(),
9280
+ find: async (ref) => this.deviceNames(requireApi()).find(ref),
9281
+ readControl: async (deviceId) => {
9282
+ const slice = await requireApi().deviceState.getCapSlice.query({
9283
+ deviceId,
9284
+ capName: "control"
9285
+ });
9286
+ if (slice === null) return null;
9287
+ const kind = slice["kind"];
9288
+ const options = slice["options"];
9289
+ const min = slice["min"];
9290
+ const max = slice["max"];
9291
+ return {
9292
+ kind: typeof kind === "string" ? kind : "unknown",
9293
+ options: Array.isArray(options) ? options.filter((o) => typeof o === "string") : [],
9294
+ ...typeof min === "number" ? { min } : {},
9295
+ ...typeof max === "number" ? { max } : {}
9296
+ };
9297
+ },
9298
+ setSwitch: async (deviceId, on) => {
9299
+ await requireApi().switch.setState.mutate({
9300
+ deviceId,
9301
+ on
9302
+ });
9303
+ },
9304
+ setControl: async (deviceId, control) => {
9305
+ await requireApi().control.setValue.mutate({
9306
+ deviceId,
9307
+ control
9308
+ });
9309
+ },
9310
+ logger: this.ctx.logger.child("fan-links")
9311
+ };
9116
9312
  }
9117
9313
  /**
9118
9314
  * The remote writes each of its devices' `media-player` slice itself: seeded
@@ -9556,7 +9752,7 @@ var CoreBlocksAddon = class extends require_dist.BaseAddon {
9556
9752
  };
9557
9753
  return buildCompositionApi({
9558
9754
  store: this.requireStore(),
9559
- describe: (sources, targets) => require_composition_sources.describeCompositionSources({
9755
+ describe: (sources, targets, unionReads) => require_composition_sources.describeCompositionSources({
9560
9756
  listByAddon: async (addonId) => {
9561
9757
  return (await requireApi().deviceManager.listAll.query({
9562
9758
  addonId,
@@ -9568,8 +9764,15 @@ var CoreBlocksAddon = class extends require_dist.BaseAddon {
9568
9764
  ...row.sourceInfo?.quantity === void 0 ? {} : { quantity: row.sourceInfo.quantity }
9569
9765
  }));
9570
9766
  },
9571
- bindings: async (deviceId) => (await requireApi().deviceManager.getBindings.query({ deviceId })).entries
9572
- }, sources, targets),
9767
+ bindings: async (deviceId) => (await requireApi().deviceManager.getBindings.query({ deviceId })).entries,
9768
+ readField: async (deviceId, cap, fieldPath) => {
9769
+ const slice = await requireApi().deviceState.getCapSlice.query({
9770
+ deviceId,
9771
+ capName: cap
9772
+ });
9773
+ return slice === null ? void 0 : slice[fieldPath];
9774
+ }
9775
+ }, sources, targets, unionReads),
9573
9776
  lookupCap: require_dist.buildCapabilityLookup(require_dist.ALL_CAPABILITY_DEFINITIONS),
9574
9777
  composerStates: async (blockIds) => (await requireApi().composer.getStates.query({ blockIds: [...blockIds] })).states,
9575
9778
  convergeSoon: () => {