@camstack/server 1.2.928 → 1.2.930

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 (241) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/package.json +10 -10
  3. package/system/dist/addon-id-CVg1_r5E.mjs +39 -0
  4. package/system/dist/addon-id-Di0lNJ89.js +50 -0
  5. package/system/dist/addon-pages.cap-Df9FQwN1.js +49 -0
  6. package/system/dist/addon-pages.cap-DksUlE8j.mjs +44 -0
  7. package/system/dist/addon-settings.cap-3-TIIMq_.mjs +592 -0
  8. package/system/dist/addon-settings.cap-DAiE0Nb0.js +651 -0
  9. package/system/dist/addon-utils.mjs +1 -1
  10. package/system/dist/addon-widgets.cap-C4jxflbF.js +200 -0
  11. package/system/dist/addon-widgets.cap-D9m48X78.mjs +183 -0
  12. package/system/dist/base-addon-DD5dIfcZ.js +4624 -0
  13. package/system/dist/base-addon-Md14i7pe.mjs +4505 -0
  14. package/system/dist/base-device-2sL1DMm1.js +1103 -0
  15. package/system/dist/base-device-IuM1AwXZ.mjs +1098 -0
  16. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.js +8 -6
  17. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.mjs +6 -4
  18. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js +8 -6
  19. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs +7 -5
  20. package/system/dist/builtins/alerts/alerts.addon.js +113 -56
  21. package/system/dist/builtins/alerts/alerts.addon.mjs +60 -3
  22. package/system/dist/builtins/autotrack/index.js +21 -17
  23. package/system/dist/builtins/autotrack/index.mjs +5 -1
  24. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.js +14 -11
  25. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.mjs +8 -5
  26. package/system/dist/builtins/calendars/calendars.addon.js +8 -6
  27. package/system/dist/builtins/calendars/calendars.addon.mjs +3 -1
  28. package/system/dist/builtins/camera-grid/index.js +615 -58
  29. package/system/dist/builtins/camera-grid/index.mjs +558 -1
  30. package/system/dist/builtins/composer/composer.addon.js +788 -209
  31. package/system/dist/builtins/composer/composer.addon.mjs +583 -4
  32. package/system/dist/builtins/console-logging/index.js +4 -3
  33. package/system/dist/builtins/console-logging/index.mjs +2 -1
  34. package/system/dist/builtins/core-blocks/actions-service.d.ts +18 -1
  35. package/system/dist/builtins/core-blocks/core-blocks.addon.js +8670 -386
  36. package/system/dist/builtins/core-blocks/core-blocks.addon.mjs +8294 -11
  37. package/system/dist/builtins/core-blocks/tcp-connect.d.ts +3 -0
  38. package/system/dist/builtins/core-notifier/core-notifier.addon.js +250 -21
  39. package/system/dist/builtins/core-notifier/core-notifier.addon.mjs +230 -1
  40. package/system/dist/builtins/device-history/device-history.addon.js +110 -31
  41. package/system/dist/builtins/device-history/device-history.addon.mjs +81 -2
  42. package/system/dist/builtins/device-manager/device-manager.addon.js +12806 -227
  43. package/system/dist/builtins/device-manager/device-manager.addon.mjs +12583 -5
  44. package/system/dist/builtins/hub-forwarder/index.js +4 -3
  45. package/system/dist/builtins/hub-forwarder/index.mjs +2 -1
  46. package/system/dist/builtins/keychain/index.js +31 -28
  47. package/system/dist/builtins/keychain/index.mjs +7 -4
  48. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.js +15 -12
  49. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.mjs +4 -1
  50. package/system/dist/builtins/local-auth/local-auth.addon.js +140 -39
  51. package/system/dist/builtins/local-auth/local-auth.addon.mjs +106 -6
  52. package/system/dist/builtins/local-network/local-network.addon.js +43 -39
  53. package/system/dist/builtins/local-network/local-network.addon.mjs +7 -3
  54. package/system/dist/builtins/loki-logging/index.js +23 -17
  55. package/system/dist/builtins/loki-logging/index.mjs +7 -1
  56. package/system/dist/builtins/native-metrics/native-metrics.addon.js +156 -15
  57. package/system/dist/builtins/native-metrics/native-metrics.addon.mjs +151 -10
  58. package/system/dist/builtins/platform-probe/index.js +25 -23
  59. package/system/dist/builtins/platform-probe/index.mjs +12 -10
  60. package/system/dist/builtins/record-entries/index.js +9 -7
  61. package/system/dist/builtins/record-entries/index.mjs +3 -1
  62. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.js +4 -4
  63. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.mjs +1 -1
  64. package/system/dist/builtins/snapshot/index.js +97 -44
  65. package/system/dist/builtins/snapshot/index.mjs +54 -1
  66. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.js +5 -4
  67. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.mjs +21 -20
  68. package/system/dist/builtins/sqlite-storage/index.js +1 -1
  69. package/system/dist/builtins/sqlite-storage/index.mjs +1 -1
  70. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.js +87 -61
  71. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs +29 -3
  72. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.js +81 -72
  73. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.mjs +10 -1
  74. package/system/dist/builtins/system-config/system-config.addon.js +17 -14
  75. package/system/dist/builtins/system-config/system-config.addon.mjs +118 -115
  76. package/system/dist/builtins/winston-logging/index.js +7 -5
  77. package/system/dist/builtins/winston-logging/index.mjs +3 -1
  78. package/system/dist/calendars.cap-CaFlShS9.js +155 -0
  79. package/system/dist/calendars.cap-_C4eD4fi.mjs +138 -0
  80. package/system/dist/camstack-error-DJ-TUAi1.js +23 -0
  81. package/system/dist/camstack-error-viZYfcj9.mjs +18 -0
  82. package/system/dist/cap-call-context-Bd76CbOW.js +95 -0
  83. package/system/dist/cap-call-context-DNwdgGSQ.mjs +78 -0
  84. package/system/dist/capability-definition-C2rJdVeX.mjs +177 -0
  85. package/system/dist/capability-definition-HCmTem8c.js +242 -0
  86. package/system/dist/{capture-engine-BcuwOSXv.js → capture-engine-DZ0LIUqA.js} +5 -4
  87. package/system/dist/{capture-engine-Bz7eXFjT.mjs → capture-engine-DiwbjoWp.mjs} +2 -1
  88. package/system/dist/command-origin-claim-Cief660O.js +35 -0
  89. package/system/dist/command-origin-claim-D1Wy7Qld.mjs +24 -0
  90. package/system/dist/composition-sources-BEUWn2s_.mjs +391 -0
  91. package/system/dist/composition-sources-acfR4hDq.js +408 -0
  92. package/system/dist/{constants-D2etJ02O.js → constants-Ba3FTIHl.js} +1 -1
  93. package/system/dist/constants-C860Y6U4.js +26 -0
  94. package/system/dist/{constants-BcUTQd1M.mjs → constants-DB4piTD5.mjs} +1 -1
  95. package/system/dist/constants-DCLpoF4L.mjs +21 -0
  96. package/system/dist/coral-accelerators-7o8hqvcN.js +564 -0
  97. package/system/dist/coral-accelerators-BKcXP59c.mjs +521 -0
  98. package/system/dist/core-blocks.cap-BMeMCBrx.js +18733 -0
  99. package/system/dist/core-blocks.cap-BRPsLAij.mjs +18008 -0
  100. package/system/dist/{custom-action-registry-N7flBDwT.mjs → custom-action-registry-B9zFBNVa.mjs} +37 -37
  101. package/system/dist/custom-actions-BFUSalC9.mjs +25 -0
  102. package/system/dist/custom-actions-D92NRi2c.js +36 -0
  103. package/system/dist/database-snapshot.cap-DF38e-0P.js +162 -0
  104. package/system/dist/database-snapshot.cap-dhrc9xnY.mjs +133 -0
  105. package/system/dist/declared-device-BWphj9WE.js +303 -0
  106. package/system/dist/declared-device-CKERA1Hi.mjs +286 -0
  107. package/system/dist/{device-ca-ExMN3xW3.mjs → device-ca-BLM6fccc.mjs} +2 -1
  108. package/system/dist/{device-ca-CU8zh9Pi.js → device-ca-C5kJE6mL.js} +7 -6
  109. package/system/dist/device-certificate-Cddm4Idn.mjs +91 -0
  110. package/system/dist/device-certificate-CguVACQO.js +162 -0
  111. package/system/dist/device-identifiers-BQg9EQi1.js +600 -0
  112. package/system/dist/device-identifiers-iSuQCKmK.mjs +529 -0
  113. package/system/dist/device-kind-BJ2pfsjw.mjs +78 -0
  114. package/system/dist/device-kind-CsSiv_YF.js +101 -0
  115. package/system/dist/device-manager.cap-2abwVLCM.js +2874 -0
  116. package/system/dist/device-manager.cap-CFZSPfUh.mjs +2749 -0
  117. package/system/dist/device-provider.cap-3Uvk6f5-.mjs +331 -0
  118. package/system/dist/device-provider.cap-D7TV2kVH.js +366 -0
  119. package/system/dist/{device-row-store-CeW_GWh9.mjs → device-row-store-YF3jtmkk.mjs} +4 -1
  120. package/system/dist/{device-row-store-BMIR-n3m.js → device-row-store-doTfMOqn.js} +12 -9
  121. package/system/dist/device-transitions.cap-B5w5PYU_.js +860 -0
  122. package/system/dist/device-transitions.cap-DojcwEuX.mjs +819 -0
  123. package/system/dist/device-type-CbQsnFdC.js +477 -0
  124. package/system/dist/device-type-DgEvK3ch.mjs +454 -0
  125. package/system/dist/entry-kind-D9MuVJCK.mjs +44 -0
  126. package/system/dist/entry-kind-cq90c--V.js +55 -0
  127. package/system/dist/error.cap-CSM_SRfR.mjs +3423 -0
  128. package/system/dist/error.cap-DBhgPeWK.js +3848 -0
  129. package/system/dist/file-host-worker.js +1 -1
  130. package/system/dist/file-host-worker.mjs +1 -1
  131. package/system/dist/history-catalog-BKRarIL_.js +831 -0
  132. package/system/dist/history-catalog-BwTeQ4Mr.mjs +802 -0
  133. package/system/dist/{hub-identity-Csxx2Q8k.js → hub-identity-BMdR3Mw9.js} +2 -2
  134. package/system/dist/{hub-identity-CYC1820R.mjs → hub-identity-DjMN9Ac2.mjs} +10 -10
  135. package/system/dist/{hub-mdns-ciao-By5577HM.js → hub-mdns-ciao--0v1TKME.js} +5 -5
  136. package/system/dist/{hub-mdns-ciao-CCDxM5qz.mjs → hub-mdns-ciao-DBrtHOcc.mjs} +2 -2
  137. package/system/dist/index.js +763 -151
  138. package/system/dist/index.mjs +832 -220
  139. package/system/dist/integration-instances.cap-Cl9O-k4h.mjs +538 -0
  140. package/system/dist/integration-instances.cap-dJIxg2_s.js +549 -0
  141. package/system/dist/keychain-admin.cap-Db_oFX4H.js +425 -0
  142. package/system/dist/keychain-admin.cap-GtM7gVGG.mjs +396 -0
  143. package/system/dist/l10n-Bu6aUvSY.mjs +10 -0
  144. package/system/dist/l10n-CGMvp7NF.js +15 -0
  145. package/system/dist/labels-DX5S8deC.js +81 -0
  146. package/system/dist/labels-DsBcU7md.mjs +64 -0
  147. package/system/dist/{legacy-integration-rows-door-CVwOo5aq.js → legacy-integration-rows-door-B1nzxxr5.js} +2 -2
  148. package/system/dist/{legacy-integration-rows-door-D9tQOUzh.mjs → legacy-integration-rows-door-nTvo_6jQ.mjs} +1 -1
  149. package/system/dist/log-destination.cap-CxZzAVaR.mjs +143 -0
  150. package/system/dist/log-destination.cap-DELPJkZ0.js +148 -0
  151. package/system/dist/low-power-sleep.cap-7lfVU41N.js +103 -0
  152. package/system/dist/low-power-sleep.cap-tGPmaZ_V.mjs +92 -0
  153. package/system/dist/mask-shape-Ci8Co9w0.mjs +57 -0
  154. package/system/dist/mask-shape-CmPA2fst.js +92 -0
  155. package/system/dist/metrics-provider.cap-BNmcHDkQ.mjs +405 -0
  156. package/system/dist/metrics-provider.cap-BcmQUt6l.js +410 -0
  157. package/system/dist/migration-BMjgkyG2.js +380 -0
  158. package/system/dist/migration-DRJAtdy7.mjs +321 -0
  159. package/system/dist/network-access.cap-B5TWLDCC.js +1099 -0
  160. package/system/dist/network-access.cap-BJnGbE6n.mjs +1004 -0
  161. package/system/dist/notification-rules.cap-BDh0LDhV.js +3428 -0
  162. package/system/dist/notification-rules.cap-DUmiMBQB.mjs +3357 -0
  163. package/system/dist/notification-targets-CRH-9Dy5.js +509 -0
  164. package/system/dist/notification-targets-DaNE-pIt.mjs +486 -0
  165. package/system/dist/ops-log-CB4pIdqi.mjs +64 -0
  166. package/system/dist/ops-log-pxt9176Z.js +81 -0
  167. package/system/dist/pinned-binary-BOhOSNff.js +28 -0
  168. package/system/dist/pinned-binary-CrIRAi4G.mjs +23 -0
  169. package/system/dist/platform-probe.cap-1WrMhWHx.js +250 -0
  170. package/system/dist/platform-probe.cap-BFeqFLtQ.mjs +233 -0
  171. package/system/dist/prefix-walk-BkMxoXpL.js +843 -0
  172. package/system/dist/prefix-walk-ifwg_ukx.mjs +790 -0
  173. package/system/dist/ptz-autotrack.cap-BW7w0zHD.js +229 -0
  174. package/system/dist/ptz-autotrack.cap-DT2GypXw.mjs +224 -0
  175. package/system/dist/quantity-D3g5SxsZ.mjs +114 -0
  176. package/system/dist/quantity-lY1KiTSZ.js +143 -0
  177. package/system/dist/raw-secret-migration-DxuBFtvi.js +50 -0
  178. package/system/dist/raw-secret-migration-iv88mLoc.mjs +39 -0
  179. package/system/dist/record-entries.cap-sMUhTvTU.mjs +75 -0
  180. package/system/dist/record-entries.cap-ti1C046R.js +80 -0
  181. package/system/dist/record-kind-DoBfYHCs.js +203 -0
  182. package/system/dist/record-kind-ub6NXqfh.mjs +162 -0
  183. package/system/dist/recording-archive.cap-7OrIn9e5.mjs +1299 -0
  184. package/system/dist/recording-archive.cap-D7bo-QSM.js +1328 -0
  185. package/system/dist/records.cap-ClcWV64i.js +329 -0
  186. package/system/dist/records.cap-CwLT2ByG.mjs +294 -0
  187. package/system/dist/relocate-CdVQAk-w.js +804 -0
  188. package/system/dist/relocate-CoZZTui1.mjs +661 -0
  189. package/system/dist/rename-composition-block-BJsL58Ih.js +34798 -0
  190. package/system/dist/rename-composition-block-OAtErZgq.mjs +33631 -0
  191. package/system/dist/{restore-archive-BJfyu0sG.mjs → restore-archive-CjAyKpgX.mjs} +96 -94
  192. package/system/dist/{restore-archive-CIFvqOze.js → restore-archive-CkTkv3Ss.js} +6 -4
  193. package/system/dist/scoped-settings-CylSSq_8.js +955 -0
  194. package/system/dist/scoped-settings-DVWUIP7Z.mjs +650 -0
  195. package/system/dist/server-name-BIhLuHvX.mjs +35 -0
  196. package/system/dist/server-name-OALNvpqC.js +52 -0
  197. package/system/dist/settings-store.cap-Ci4F2zul.mjs +569 -0
  198. package/system/dist/settings-store.cap-wlJhCspr.js +640 -0
  199. package/system/dist/snapshot.cap-3suPdBHV.js +250 -0
  200. package/system/dist/snapshot.cap-Bs8Oyaqh.mjs +245 -0
  201. package/system/dist/source-info-DGB7SdB_.mjs +190 -0
  202. package/system/dist/source-info-DtWf4k2j.js +225 -0
  203. package/system/dist/storage-admin.cap-BSv1NjKJ.mjs +883 -0
  204. package/system/dist/storage-admin.cap-he0OqvVM.js +906 -0
  205. package/system/dist/storage-location-CBT8GCD6.mjs +163 -0
  206. package/system/dist/storage-location-CTweDMZf.js +198 -0
  207. package/system/dist/storage-location-mode-B21UVRRX.mjs +167 -0
  208. package/system/dist/storage-location-mode-CS4sMzo-.js +232 -0
  209. package/system/dist/storage-migration.cap-CyyATY_p.js +330 -0
  210. package/system/dist/storage-migration.cap-D7QqGobp.mjs +313 -0
  211. package/system/dist/storage-occupancy.cap-2rmnS58Z.js +622 -0
  212. package/system/dist/storage-occupancy.cap-CqBztTl9.mjs +611 -0
  213. package/system/dist/storage-provider.cap-Bw0CfxVc.js +213 -0
  214. package/system/dist/storage-provider.cap-CMeck2w4.mjs +202 -0
  215. package/system/dist/stream-catalog.cap-Bp7SkgIf.mjs +6560 -0
  216. package/system/dist/stream-catalog.cap-D3uwePiA.js +6763 -0
  217. package/system/dist/streaming-shared-B8cXatuU.mjs +431 -0
  218. package/system/dist/streaming-shared-DQwFZOSi.js +526 -0
  219. package/system/dist/system-reasons-Be_k1W8g.js +25 -0
  220. package/system/dist/system-reasons-CYj4qwyS.mjs +20 -0
  221. package/system/dist/tag-BxLazvVb.js +2138 -0
  222. package/system/dist/tag-uZBAq6ox.mjs +2073 -0
  223. package/system/dist/user-management.cap-B9QDu8NE.js +825 -0
  224. package/system/dist/user-management.cap-DBIi77sB.mjs +766 -0
  225. package/system/dist/vector-store.cap-DnyfrYDn.js +330 -0
  226. package/system/dist/vector-store.cap-h2GHWQ1t.mjs +319 -0
  227. package/system/dist/{wal-maintenance-CTrCPzds.mjs → wal-maintenance-BG01rOn9.mjs} +0 -0
  228. package/system/dist/{wal-maintenance-dq7T3quB.js → wal-maintenance-DyrebYKF.js} +0 -0
  229. package/system/dist/zod-secret-DS7mj1bk.js +78 -0
  230. package/system/dist/zod-secret-zY4nM61M.mjs +73 -0
  231. package/system/package.json +1 -1
  232. package/system/dist/composition-sources-BI614LJx.mjs +0 -141
  233. package/system/dist/composition-sources-v_kkb8A9.js +0 -152
  234. package/system/dist/coral-accelerators-BSVsBVzt.js +0 -250
  235. package/system/dist/coral-accelerators-BW3OcrLD.mjs +0 -231
  236. package/system/dist/dist-BCHMSqzc.mjs +0 -143467
  237. package/system/dist/dist-BZfvhfS1.js +0 -146970
  238. package/system/dist/prefix-walk-DAOBSyH1.mjs +0 -88
  239. package/system/dist/prefix-walk-Dv6MLZlM.js +0 -99
  240. package/system/dist/rename-composition-block-C9HuBrKS.js +0 -112
  241. package/system/dist/rename-composition-block-DtaYmYAR.mjs +0 -101
@@ -0,0 +1,3423 @@
1
+ import { c as method } from "./capability-definition-C2rJdVeX.mjs";
2
+ import { n as baseUnitOf } from "./quantity-D3g5SxsZ.mjs";
3
+ import { n as DeviceRole, r as DeviceType, t as DeviceFeature } from "./device-type-DgEvK3ch.mjs";
4
+ import { t as canonicalStoredDeviceType } from "./device-kind-BJ2pfsjw.mjs";
5
+ import { t } from "./l10n-Bu6aUvSY.mjs";
6
+ import { a as wattMillisecondsToKwh, i as historyFieldsFor } from "./history-catalog-BwTeQ4Mr.mjs";
7
+ import { z } from "zod";
8
+ //#region ../types/dist/esm/catalogs/sensor-active-state.mjs
9
+ /**
10
+ * How recent a source's own transition timestamp must be for a FIRST
11
+ * sighting that is already active to count as a genuine rise rather than a
12
+ * hydration of long-standing state.
13
+ */
14
+ var DEFAULT_FIRST_SIGHTING_FRESHNESS_MS = 3e4;
15
+ /**
16
+ * The source-independent edge rule. The caller supplies an already extracted
17
+ * boolean level and source timestamp; this function owns first-sighting
18
+ * freshness and false-to-true detection.
19
+ */
20
+ function evaluateSensorLevelEdge(input) {
21
+ const timestamp = input.changedAt;
22
+ const freshFloor = Math.max(input.startedAtMs, input.nowMs - input.firstSightingFreshnessMs);
23
+ const firstRise = input.priorLevel === void 0 && input.level && timestamp !== null && Number.isFinite(timestamp) && timestamp >= freshFloor;
24
+ const transitionRise = input.priorLevel === false && input.level && timestamp !== null && Number.isFinite(timestamp);
25
+ if ((firstRise || transitionRise) && timestamp !== null) return {
26
+ kind: "rise",
27
+ timestamp
28
+ };
29
+ return {
30
+ kind: "none",
31
+ nextPriorLevel: input.level
32
+ };
33
+ }
34
+ //#endregion
35
+ //#region ../types/dist/esm/expression/errors.mjs
36
+ /**
37
+ * Error types for the safe expression engine. Two distinct classes so callers
38
+ * can tell a compile-time (grammar) failure from a runtime (evaluation)
39
+ * failure — both are non-fatal to the host: read paths degrade to "skip link".
40
+ */
41
+ /** Thrown by the tokenizer / parser. Carries a 0-based source `position` when
42
+ * the failure is anchored to a character (author-facing inline feedback). */
43
+ var ExpressionParseError = class extends Error {
44
+ position;
45
+ constructor(message, position) {
46
+ super(message);
47
+ this.name = "ExpressionParseError";
48
+ this.position = position;
49
+ }
50
+ };
51
+ /** Thrown by the evaluator (unknown identifier, type mismatch, non-finite
52
+ * result, unknown builtin, step-budget exceeded). */
53
+ var ExpressionEvalError = class extends Error {
54
+ constructor(message) {
55
+ super(message);
56
+ this.name = "ExpressionEvalError";
57
+ }
58
+ };
59
+ //#endregion
60
+ //#region ../types/dist/esm/expression/builtins.mjs
61
+ function isStatefulBuiltin(name) {
62
+ return name === "rose" || name === "count" || name === "dwell" || name === "latchedAt" || name === "schmitt";
63
+ }
64
+ function asFiniteNumber(value, name, index) {
65
+ if (typeof value !== "number" || !Number.isFinite(value)) throw new ExpressionEvalError(`${name}: argument ${index + 1} must be a finite number`);
66
+ return value;
67
+ }
68
+ function asString(value, name, index) {
69
+ if (typeof value !== "string") throw new ExpressionEvalError(`${name}: argument ${index + 1} must be a string`);
70
+ return value;
71
+ }
72
+ function finiteResult(value, name) {
73
+ if (!Number.isFinite(value)) throw new ExpressionEvalError(`${name}: produced a non-finite result`);
74
+ return value;
75
+ }
76
+ function allFiniteNumbers(args, name) {
77
+ return args.map((a, idx) => asFiniteNumber(a, name, idx));
78
+ }
79
+ function asBoolean(value, name, index) {
80
+ if (typeof value !== "boolean") throw new ExpressionEvalError(`${name}: argument ${index + 1} must be a boolean`);
81
+ return value;
82
+ }
83
+ /** A plain decimal (optional sign, fraction, exponent) — never hex, never `Infinity`, never a unit suffix. */
84
+ var DECIMAL = /^[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?$/;
85
+ /**
86
+ * `number(x)`: a finite number, or a string that IS one, as a number; every
87
+ * other value — `''`, `'unavailable'`, a boolean, null — is `null`
88
+ * (unavailable, never 0: D393). The one bridge from a string-valued source (an
89
+ * HA sensor with a unit and no device_class is an `enum-sensor`) to a number.
90
+ */
91
+ function toNumberOrNull(value) {
92
+ if (typeof value === "number") return Number.isFinite(value) ? value : null;
93
+ if (typeof value !== "string") return null;
94
+ const trimmed = value.trim();
95
+ if (!DECIMAL.test(trimmed)) return null;
96
+ const parsed = Number(trimmed);
97
+ return Number.isFinite(parsed) ? parsed : null;
98
+ }
99
+ var DEFAULT_ROSE_DEBOUNCE_MS = 2e3;
100
+ function evaluateRose(level, changedAt, debounceMs, call, field, env) {
101
+ const active = asBoolean(level, "rose", 0);
102
+ const timestamp = typeof changedAt === "number" && Number.isFinite(changedAt) ? changedAt : null;
103
+ const debounce = debounceMs === void 0 ? DEFAULT_ROSE_DEBOUNCE_MS : asFiniteNumber(debounceMs, "rose", 2);
104
+ if (debounce < 0) throw new ExpressionEvalError("rose: debounce must be a non-negative finite number");
105
+ if (call.disarmNext === true || field.disarmRoseNext) {
106
+ call.disarmNext = false;
107
+ if (call.priorLevel === void 0) call.priorLevel = active;
108
+ return env.currentOutput;
109
+ }
110
+ const verdict = evaluateSensorLevelEdge({
111
+ level: active,
112
+ changedAt: timestamp,
113
+ priorLevel: call.priorLevel,
114
+ startedAtMs: env.startedAtMs,
115
+ nowMs: env.nowMs,
116
+ firstSightingFreshnessMs: DEFAULT_FIRST_SIGHTING_FRESHNESS_MS
117
+ });
118
+ call.priorLevel = verdict.kind === "rise" ? true : verdict.nextPriorLevel;
119
+ if (verdict.kind === "none") return env.currentOutput;
120
+ if (field.acceptedEdgeAt !== null && verdict.timestamp - field.acceptedEdgeAt < debounce) return env.currentOutput;
121
+ field.acceptedEdgeAt = verdict.timestamp;
122
+ return verdict.timestamp;
123
+ }
124
+ /** Next evaluation of every `rose` call baselines without rising. */
125
+ function disarmRoseMemory(memory) {
126
+ memory.disarmRoseNext = true;
127
+ for (const [path, call] of memory.calls) {
128
+ if (call.kind !== "rose") continue;
129
+ memory.calls.set(path, {
130
+ ...call,
131
+ disarmNext: true
132
+ });
133
+ }
134
+ }
135
+ /**
136
+ * `count(x)`: how many times `x` strictly advanced (D670). It starts on the
137
+ * first ANSWERED read of `x`:
138
+ * - an answered `null` ("never happened") primes it with no high-water, so the
139
+ * next finite value is a real advance and counts 1;
140
+ * - an answered finite value primes it with that value as the high-water and
141
+ * no increment — it is history, not an event;
142
+ * - anything else (a read that did not answer reaches here as neither) does
143
+ * NOT prime it (D393: unknown is not null).
144
+ * An unavailable binding never reaches this function at all: the field is
145
+ * judged unavailable before the expression runs.
146
+ *
147
+ * Edge case, accepted: an input that answers `null` and LATER reports a
148
+ * historical value (a sensor's `lastChangedAt` that was null until its first
149
+ * report) counts that value once. For the doorbell it cannot happen — its
150
+ * input is its own `lastPressedAt`, which only advances on a `rose` edge that
151
+ * also emits the press — but an external input can overcount by one.
152
+ */
153
+ function asNonNegativeMs(value, name, index) {
154
+ const ms = asFiniteNumber(value, name, index);
155
+ if (ms < 0) throw new ExpressionEvalError(`${name}: delay must be a non-negative finite number`);
156
+ return ms;
157
+ }
158
+ /**
159
+ * `dwell(active, onForMs, offForMs[, minSamples])`: unknown until a delay elapses, then holds
160
+ * the latched boolean through gaps shorter than the opposing delay (D933). A new
161
+ * call state seeded with the restored output starts latched on it, so it is never
162
+ * unknown after a boot.
163
+ *
164
+ * With `minSamples` above 1 (opt-in; default 1 = time only, as a single-event
165
+ * binary sensor needs) a flip to ON needs EVIDENCE, not only time: at least that
166
+ * many input samples that satisfy the condition (the one that opened the pending transition and later
167
+ * ones, all from source readings), so a deadline timer firing over one held
168
+ * value never starts a run. A standby plug reports one 5-9 W sample and then
169
+ * stays silent; the held value used to confirm a start 30 s later. A flip to OFF
170
+ * is deliberately NOT symmetric: a quiet sensor is how a finished run looks (the
171
+ * plug reports the drop once and goes silent), so the held "off" value must still
172
+ * confirm after `offForMs`. A zero ON delay asks for no persistence, so one
173
+ * sample is enough.
174
+ */
175
+ function evaluateDwell(activeRaw, onForMsRaw, offForMsRaw, minSamplesRaw, call, nowMs, hooks) {
176
+ const active = asBoolean(activeRaw, "dwell", 0);
177
+ const onForMs = asNonNegativeMs(onForMsRaw, "dwell", 1);
178
+ const offForMs = asNonNegativeMs(offForMsRaw, "dwell", 2);
179
+ const minSamples = minSamplesRaw === void 0 ? 1 : asMinSamples(minSamplesRaw);
180
+ call.transition = null;
181
+ if (call.latched === null) {
182
+ if (call.seenSince === null) {
183
+ call.seenSince = nowMs;
184
+ call.pendingSamples = 0;
185
+ }
186
+ if (hooks?.timerDriven !== true) call.pendingSamples += 1;
187
+ const delay = active ? onForMs : offForMs;
188
+ const sustained = !active || delay === 0 || minSamples <= 1 || call.pendingSamples >= minSamples;
189
+ if (nowMs - call.seenSince >= delay && sustained) {
190
+ call.latched = active;
191
+ call.pendingSamples = 0;
192
+ return call.latched;
193
+ }
194
+ if (nowMs - call.seenSince < delay) hooks?.noteDeadline?.(call.seenSince + delay);
195
+ return null;
196
+ }
197
+ if (active === call.latched) return holdAgainstReturn(call, active, onForMs, nowMs, hooks);
198
+ call.returnSince = null;
199
+ if (call.pendingSince === null) {
200
+ call.pendingSince = nowMs;
201
+ call.pendingSamples = 0;
202
+ }
203
+ if (hooks?.timerDriven !== true) call.pendingSamples += 1;
204
+ const delay = active ? onForMs : offForMs;
205
+ const sustained = !active || delay === 0 || minSamples <= 1 || call.pendingSamples >= minSamples;
206
+ if (nowMs - call.pendingSince >= delay && sustained) return flip(call, active, call.pendingSince);
207
+ if (nowMs - call.pendingSince < delay) hooks?.noteDeadline?.(call.pendingSince + delay);
208
+ return call.latched;
209
+ }
210
+ function asMinSamples(value) {
211
+ const n = asFiniteNumber(value, "dwell", 3);
212
+ if (!Number.isInteger(n) || n < 1) throw new ExpressionEvalError("dwell: minSamples must be a whole number of at least 1");
213
+ return n;
214
+ }
215
+ function flip(call, to, startedAt) {
216
+ const transition = {
217
+ value: to,
218
+ startedAt
219
+ };
220
+ call.latched = to;
221
+ call.pendingSince = null;
222
+ call.pendingSamples = 0;
223
+ call.returnSince = null;
224
+ call.transition = transition;
225
+ return to;
226
+ }
227
+ /**
228
+ * The input is on the latched side. Without a pending transition that is the
229
+ * steady state. A pending ON is dropped at once (a start needs `onForMs` of
230
+ * unbroken activity). A pending OFF survives a return until the return has held
231
+ * `onForMs`: a shorter one (an anti-crease pulse) must not re-arm a finished
232
+ * run, and the original deadline still fires once the input is off again.
233
+ */
234
+ function holdAgainstReturn(call, latched, onForMs, nowMs, hooks) {
235
+ if (call.pendingSince === null) {
236
+ call.returnSince = null;
237
+ return latched;
238
+ }
239
+ if (!latched) {
240
+ call.pendingSince = null;
241
+ call.returnSince = null;
242
+ return latched;
243
+ }
244
+ if (call.returnSince === null) call.returnSince = nowMs;
245
+ const returnDeadline = call.returnSince + onForMs;
246
+ if (nowMs >= returnDeadline) {
247
+ call.pendingSince = null;
248
+ call.returnSince = null;
249
+ return latched;
250
+ }
251
+ hooks?.noteDeadline?.(returnDeadline);
252
+ return latched;
253
+ }
254
+ /**
255
+ * `schmitt(x, high, low[, onForMs, offForMs])`: true once `x >= high`, false
256
+ * once `x <= low`, and the last answer in between. A transition waits its delay
257
+ * and is dropped if `x` returns to the held side first. The first answer needs
258
+ * a crossing, or the restored output as `seed`: a reading inside the band with
259
+ * nothing to hold is unknown, never off (D393). A null reading throws, so the
260
+ * field is unavailable and the latch is kept.
261
+ */
262
+ function evaluateSchmitt(args, call, nowMs, seed, hooks) {
263
+ const x = asFiniteNumber(args[0], "schmitt", 0);
264
+ const high = asFiniteNumber(args[1], "schmitt", 1);
265
+ const low = asFiniteNumber(args[2], "schmitt", 2);
266
+ const onForMs = args.length > 3 ? asNonNegativeMs(args[3], "schmitt", 3) : 0;
267
+ const offForMs = args.length > 4 ? asNonNegativeMs(args[4], "schmitt", 4) : 0;
268
+ if (low > high) throw new ExpressionEvalError("schmitt: the low edge is above the high edge");
269
+ if (call.latched === null && seed !== null) call.latched = seed;
270
+ const wants = x >= high ? true : x <= low ? false : call.latched;
271
+ if (call.latched === null) {
272
+ if (wants !== null) call.latched = wants;
273
+ return call.latched;
274
+ }
275
+ if (wants === null || wants === call.latched) {
276
+ call.pendingSince = null;
277
+ return call.latched;
278
+ }
279
+ if (call.pendingSince === null) call.pendingSince = nowMs;
280
+ const delay = wants ? onForMs : offForMs;
281
+ if (nowMs - call.pendingSince >= delay) {
282
+ call.latched = wants;
283
+ call.pendingSince = null;
284
+ return call.latched;
285
+ }
286
+ hooks?.noteDeadline?.(call.pendingSince + delay);
287
+ return call.latched;
288
+ }
289
+ /** `latchedAt(value)`: epoch ms when `value` last changed; null clears the stamp. */
290
+ function evaluateLatchedAt(value, call, nowMs, dwellTransition = null) {
291
+ if (value === null) {
292
+ call.last = null;
293
+ call.at = null;
294
+ return null;
295
+ }
296
+ if (typeof value !== "boolean" && typeof value !== "number" && typeof value !== "string") return call.at;
297
+ if (call.last !== value) {
298
+ call.last = value;
299
+ call.at = dwellTransition?.value === false && value === false ? dwellTransition.startedAt : nowMs;
300
+ }
301
+ return call.at;
302
+ }
303
+ function evaluateCount(input, call, currentOutput) {
304
+ const currentCount = typeof currentOutput === "number" && Number.isFinite(currentOutput) && currentOutput >= 0 ? currentOutput : 0;
305
+ if (input === null) {
306
+ call.primed = true;
307
+ return currentCount;
308
+ }
309
+ if (typeof input !== "number" || !Number.isFinite(input)) return currentCount;
310
+ if (!call.primed) {
311
+ call.primed = true;
312
+ call.highWater = input;
313
+ return currentCount;
314
+ }
315
+ if (call.highWater !== null && input <= call.highWater) return currentCount;
316
+ call.highWater = input;
317
+ return currentCount + 1;
318
+ }
319
+ var INF = Number.POSITIVE_INFINITY;
320
+ var table = {
321
+ min: {
322
+ minArgs: 1,
323
+ maxArgs: INF,
324
+ apply: (args) => finiteResult(Math.min(...allFiniteNumbers(args, "min")), "min")
325
+ },
326
+ max: {
327
+ minArgs: 1,
328
+ maxArgs: INF,
329
+ apply: (args) => finiteResult(Math.max(...allFiniteNumbers(args, "max")), "max")
330
+ },
331
+ abs: {
332
+ minArgs: 1,
333
+ maxArgs: 1,
334
+ apply: (args) => finiteResult(Math.abs(asFiniteNumber(args[0], "abs", 0)), "abs")
335
+ },
336
+ floor: {
337
+ minArgs: 1,
338
+ maxArgs: 1,
339
+ apply: (args) => finiteResult(Math.floor(asFiniteNumber(args[0], "floor", 0)), "floor")
340
+ },
341
+ ceil: {
342
+ minArgs: 1,
343
+ maxArgs: 1,
344
+ apply: (args) => finiteResult(Math.ceil(asFiniteNumber(args[0], "ceil", 0)), "ceil")
345
+ },
346
+ sqrt: {
347
+ minArgs: 1,
348
+ maxArgs: 1,
349
+ apply: (args) => finiteResult(Math.sqrt(asFiniteNumber(args[0], "sqrt", 0)), "sqrt")
350
+ },
351
+ round: {
352
+ minArgs: 1,
353
+ maxArgs: 2,
354
+ apply: (args) => {
355
+ const x = asFiniteNumber(args[0], "round", 0);
356
+ const digits = args.length > 1 ? Math.trunc(asFiniteNumber(args[1], "round", 1)) : 0;
357
+ if (digits < 0 || digits > 100) throw new ExpressionEvalError("round: digits must be between 0 and 100");
358
+ const factor = 10 ** digits;
359
+ return finiteResult(Math.round(x * factor) / factor, "round");
360
+ }
361
+ },
362
+ pow: {
363
+ minArgs: 2,
364
+ maxArgs: 2,
365
+ apply: (args) => finiteResult(asFiniteNumber(args[0], "pow", 0) ** asFiniteNumber(args[1], "pow", 1), "pow")
366
+ },
367
+ clamp: {
368
+ minArgs: 3,
369
+ maxArgs: 3,
370
+ apply: (args) => {
371
+ const x = asFiniteNumber(args[0], "clamp", 0);
372
+ const lo = asFiniteNumber(args[1], "clamp", 1);
373
+ const hi = asFiniteNumber(args[2], "clamp", 2);
374
+ if (lo > hi) throw new ExpressionEvalError("clamp: lower bound is greater than upper bound");
375
+ return finiteResult(Math.min(hi, Math.max(lo, x)), "clamp");
376
+ }
377
+ },
378
+ avg: {
379
+ minArgs: 1,
380
+ maxArgs: INF,
381
+ apply: (args) => {
382
+ const nums = allFiniteNumbers(args, "avg");
383
+ return finiteResult(nums.reduce((acc, v) => acc + v, 0) / nums.length, "avg");
384
+ }
385
+ },
386
+ sum: {
387
+ minArgs: 1,
388
+ maxArgs: INF,
389
+ apply: (args) => finiteResult(allFiniteNumbers(args, "sum").reduce((acc, v) => acc + v, 0), "sum")
390
+ },
391
+ coalesce: {
392
+ minArgs: 1,
393
+ maxArgs: INF,
394
+ apply: (args) => {
395
+ for (const a of args) if (a !== null) return a;
396
+ return null;
397
+ }
398
+ },
399
+ age: {
400
+ minArgs: 2,
401
+ maxArgs: 2,
402
+ apply: (args) => finiteResult(asFiniteNumber(args[0], "age", 0) - asFiniteNumber(args[1], "age", 1), "age")
403
+ },
404
+ convert: {
405
+ minArgs: 3,
406
+ maxArgs: 3,
407
+ apply: (args, hooks) => {
408
+ const x = asFiniteNumber(args[0], "convert", 0);
409
+ const from = asString(args[1], "convert", 1).trim();
410
+ const to = asString(args[2], "convert", 2).trim();
411
+ if (hooks.convert) {
412
+ const out = hooks.convert(x, from, to);
413
+ if (out === null) throw new ExpressionEvalError(`convert: cannot convert '${from}' to '${to}'`);
414
+ return finiteResult(out, "convert");
415
+ }
416
+ if (from === to) return x;
417
+ throw new ExpressionEvalError("convert: unit conversion table not installed");
418
+ }
419
+ },
420
+ any: {
421
+ minArgs: 1,
422
+ maxArgs: INF,
423
+ apply: (args) => args.map((a, i) => asBoolean(a, "any", i)).some((b) => b)
424
+ },
425
+ all: {
426
+ minArgs: 1,
427
+ maxArgs: INF,
428
+ apply: (args) => args.map((a, i) => asBoolean(a, "all", i)).every((b) => b)
429
+ },
430
+ within: {
431
+ minArgs: 2,
432
+ maxArgs: 2,
433
+ apply: (args, hooks) => {
434
+ const windowMs = asFiniteNumber(args[1], "within", 1);
435
+ if (windowMs < 0) throw new ExpressionEvalError("within: the window must not be negative");
436
+ const at = args[0];
437
+ if (at === null) return false;
438
+ const ts = asFiniteNumber(at, "within", 0);
439
+ const now = hooks.now;
440
+ if (now === void 0 || !Number.isFinite(now)) throw new ExpressionEvalError("within: no clock was supplied to this evaluation");
441
+ const inside = now - ts <= windowMs;
442
+ if (inside) hooks.noteDeadline?.(ts + windowMs + 1);
443
+ return inside;
444
+ }
445
+ },
446
+ number: {
447
+ minArgs: 1,
448
+ maxArgs: 1,
449
+ apply: (args) => toNumberOrNull(args[0])
450
+ },
451
+ latest: {
452
+ minArgs: 1,
453
+ maxArgs: INF,
454
+ apply: (args) => {
455
+ const present = args.flatMap((a, i) => a === null ? [] : [asFiniteNumber(a, "latest", i)]);
456
+ return present.length === 0 ? null : finiteResult(Math.max(...present), "latest");
457
+ }
458
+ },
459
+ rose: {
460
+ minArgs: 2,
461
+ maxArgs: 3,
462
+ apply: () => {
463
+ throw new ExpressionEvalError("rose: stateful evaluation context is required");
464
+ }
465
+ },
466
+ count: {
467
+ minArgs: 1,
468
+ maxArgs: 1,
469
+ apply: () => {
470
+ throw new ExpressionEvalError("count: stateful evaluation context is required");
471
+ }
472
+ },
473
+ dwell: {
474
+ minArgs: 3,
475
+ maxArgs: 4,
476
+ apply: () => {
477
+ throw new ExpressionEvalError("dwell: stateful evaluation context is required");
478
+ }
479
+ },
480
+ latchedAt: {
481
+ minArgs: 1,
482
+ maxArgs: 1,
483
+ apply: () => {
484
+ throw new ExpressionEvalError("latchedAt: stateful evaluation context is required");
485
+ }
486
+ },
487
+ schmitt: {
488
+ minArgs: 3,
489
+ maxArgs: 5,
490
+ apply: () => {
491
+ throw new ExpressionEvalError("schmitt: stateful evaluation context is required");
492
+ }
493
+ }
494
+ };
495
+ /** Frozen, null-prototype builtin table. */
496
+ var EXPRESSION_BUILTINS = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.assign(/* @__PURE__ */ Object.create(null), table));
497
+ /** The set of valid builtin names — used by the parser to reject unknown
498
+ * callees at parse time (immediate author feedback). */
499
+ var EXPRESSION_BUILTIN_NAMES = /* @__PURE__ */ new Set(/* @__PURE__ */ Object.keys(table));
500
+ //#endregion
501
+ //#region ../types/dist/esm/expression/limits.mjs
502
+ /**
503
+ * Resource-bound constants for the safe expression engine.
504
+ *
505
+ * Every bound is defense-in-depth: the grammar is non-Turing-complete (no
506
+ * loops, recursion, lambdas or member access — see `ast.ts`), so evaluation is
507
+ * O(nodeCount) by construction. These caps merely put a hard ceiling on the
508
+ * work a single author-supplied expression can request, so a hostile or
509
+ * accidental pathological string can never spend unbounded CPU/memory.
510
+ */
511
+ /** Max source length (chars) — checked BEFORE tokenizing so a huge string is
512
+ * rejected without allocation. */
513
+ var MAX_EXPRESSION_SOURCE_LENGTH = 2048;
514
+ /** A legal binding / identifier name. */
515
+ var EXPRESSION_IDENTIFIER_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
516
+ /** Binding names an author may NOT use: `now` is auto-injected; the literal
517
+ * keywords lex as values, not identifiers, so binding to them is meaningless. */
518
+ var RESERVED_BINDING_NAMES = /* @__PURE__ */ new Set([
519
+ "now",
520
+ "true",
521
+ "false",
522
+ "null"
523
+ ]);
524
+ //#endregion
525
+ //#region ../types/dist/esm/expression/tokenizer.mjs
526
+ /**
527
+ * Tokenizer for the safe expression mini-language. Hand-rolled, single-pass,
528
+ * zero-dependency. The grammar is deliberately boring: decimal numbers,
529
+ * single/double-quoted strings with a tiny escape set, identifiers, the three
530
+ * value keywords (`true`/`false`/`null`) and a fixed punctuator set. Anything
531
+ * outside that — a bare `.`, `=`, `[`, `]`, `{`, `}`, `;`, backtick, `&`, `|` —
532
+ * is a parse error with a source position, so member access / assignment /
533
+ * template literals are lexically impossible.
534
+ */
535
+ var KEYWORDS = /* @__PURE__ */ new Set([
536
+ "true",
537
+ "false",
538
+ "null"
539
+ ]);
540
+ function isDigit(ch) {
541
+ return ch >= "0" && ch <= "9";
542
+ }
543
+ function isIdentStart(ch) {
544
+ return ch >= "A" && ch <= "Z" || ch >= "a" && ch <= "z" || ch === "_";
545
+ }
546
+ function isIdentPart(ch) {
547
+ return isIdentStart(ch) || isDigit(ch);
548
+ }
549
+ function isWhitespace(ch) {
550
+ return ch === " " || ch === " " || ch === "\n" || ch === "\r" || ch === "\f" || ch === "\v";
551
+ }
552
+ /** Tokenize `source` into a flat token list ending with a single `eof` token.
553
+ * Throws `ExpressionParseError` on any illegal character or unterminated
554
+ * string. */
555
+ function tokenize(source) {
556
+ if (source.length > 2048) throw new ExpressionParseError(`expression too long (${source.length} > ${MAX_EXPRESSION_SOURCE_LENGTH} chars)`, 0);
557
+ const tokens = [];
558
+ let i = 0;
559
+ const n = source.length;
560
+ while (i < n) {
561
+ const ch = source[i];
562
+ if (isWhitespace(ch)) {
563
+ i += 1;
564
+ continue;
565
+ }
566
+ if (isDigit(ch)) {
567
+ const start = i;
568
+ while (i < n && isDigit(source[i])) i += 1;
569
+ if (i < n && source[i] === ".") {
570
+ if (i + 1 >= n || !isDigit(source[i + 1])) throw new ExpressionParseError("malformed number: decimal point needs a digit", i);
571
+ i += 1;
572
+ while (i < n && isDigit(source[i])) i += 1;
573
+ }
574
+ const text = source.slice(start, i);
575
+ const value = Number(text);
576
+ if (!Number.isFinite(value)) throw new ExpressionParseError(`malformed number: '${text}'`, start);
577
+ tokens.push({
578
+ type: "number",
579
+ value,
580
+ pos: start
581
+ });
582
+ continue;
583
+ }
584
+ if (ch === "'" || ch === "\"") {
585
+ const quote = ch;
586
+ const start = i;
587
+ i += 1;
588
+ let out = "";
589
+ let closed = false;
590
+ while (i < n) {
591
+ const c = source[i];
592
+ if (c === "\\") {
593
+ const next = i + 1 < n ? source[i + 1] : "";
594
+ if (next === "\\" || next === "'" || next === "\"") {
595
+ out += next;
596
+ i += 2;
597
+ continue;
598
+ }
599
+ throw new ExpressionParseError(`invalid string escape: '\\${next}'`, i);
600
+ }
601
+ if (c === quote) {
602
+ closed = true;
603
+ i += 1;
604
+ break;
605
+ }
606
+ out += c;
607
+ i += 1;
608
+ }
609
+ if (!closed) throw new ExpressionParseError("unterminated string literal", start);
610
+ tokens.push({
611
+ type: "string",
612
+ value: out,
613
+ pos: start
614
+ });
615
+ continue;
616
+ }
617
+ if (isIdentStart(ch)) {
618
+ const start = i;
619
+ while (i < n && isIdentPart(source[i])) i += 1;
620
+ const text = source.slice(start, i);
621
+ if (KEYWORDS.has(text)) tokens.push({
622
+ type: "keyword",
623
+ keyword: keywordOf(text),
624
+ pos: start
625
+ });
626
+ else tokens.push({
627
+ type: "identifier",
628
+ name: text,
629
+ pos: start
630
+ });
631
+ continue;
632
+ }
633
+ const two = i + 1 < n ? source.slice(i, i + 2) : "";
634
+ if (two === "<=" || two === ">=" || two === "==" || two === "!=" || two === "&&" || two === "||") {
635
+ tokens.push({
636
+ type: "punct",
637
+ punct: two,
638
+ pos: i
639
+ });
640
+ i += 2;
641
+ continue;
642
+ }
643
+ if (isSinglePunct(ch)) {
644
+ tokens.push({
645
+ type: "punct",
646
+ punct: ch,
647
+ pos: i
648
+ });
649
+ i += 1;
650
+ continue;
651
+ }
652
+ throw new ExpressionParseError(`unexpected character '${ch}'`, i);
653
+ }
654
+ tokens.push({
655
+ type: "eof",
656
+ pos: n
657
+ });
658
+ return tokens;
659
+ }
660
+ function keywordOf(text) {
661
+ if (text === "true") return "true";
662
+ if (text === "false") return "false";
663
+ return "null";
664
+ }
665
+ function isSinglePunct(ch) {
666
+ return ch === "(" || ch === ")" || ch === "," || ch === "?" || ch === ":" || ch === "+" || ch === "-" || ch === "*" || ch === "/" || ch === "%" || ch === "!" || ch === "<" || ch === ">";
667
+ }
668
+ //#endregion
669
+ //#region ../types/dist/esm/expression/parser.mjs
670
+ /**
671
+ * Pratt (precedence-climbing) parser for the safe expression mini-language.
672
+ *
673
+ * Precedence (low → high): ternary `?:` (right-assoc) → `||` → `&&` → equality
674
+ * → relational → additive → multiplicative → unary `! -` → call / primary.
675
+ * Calls are ONLY `IDENT '(' args? ')'` at primary position — the callee is a
676
+ * string validated against the builtin table at parse time, so an unknown
677
+ * function is rejected immediately (author feedback) and a persisted expression
678
+ * that references a since-removed builtin degrades at read.
679
+ *
680
+ * A node counter caps total AST size (`MAX_EXPRESSION_AST_NODES`) and call
681
+ * arity is capped (`MAX_EXPRESSION_CALL_ARGS`) — both raise `ExpressionParseError`.
682
+ */
683
+ /** Binary/logical operator precedence (higher binds tighter). */
684
+ var BINARY_PRECEDENCE = {
685
+ "||": 1,
686
+ "&&": 2,
687
+ "==": 3,
688
+ "!=": 3,
689
+ "<": 4,
690
+ "<=": 4,
691
+ ">": 4,
692
+ ">=": 4,
693
+ "+": 5,
694
+ "-": 5,
695
+ "*": 6,
696
+ "/": 6,
697
+ "%": 6
698
+ };
699
+ function isLogicalOp(op) {
700
+ return op === "&&" || op === "||";
701
+ }
702
+ function isBinaryOp(op) {
703
+ return op === "+" || op === "-" || op === "*" || op === "/" || op === "%" || op === "==" || op === "!=" || op === "<" || op === "<=" || op === ">" || op === ">=";
704
+ }
705
+ var Parser = class {
706
+ tokens;
707
+ pos = 0;
708
+ nodeCount = 0;
709
+ identifiers = /* @__PURE__ */ new Set();
710
+ callees = /* @__PURE__ */ new Set();
711
+ constructor(tokens) {
712
+ this.tokens = tokens;
713
+ }
714
+ parse() {
715
+ const ast = this.parseTernary();
716
+ const tok = this.peek();
717
+ if (tok.type !== "eof") throw new ExpressionParseError("unexpected trailing input", tok.pos);
718
+ return {
719
+ ast,
720
+ identifiers: this.identifiers,
721
+ callees: this.callees,
722
+ nodeCount: this.nodeCount
723
+ };
724
+ }
725
+ peek() {
726
+ return this.tokens[this.pos];
727
+ }
728
+ next() {
729
+ return this.tokens[this.pos++];
730
+ }
731
+ /** Consume a punctuator token, erroring if the next token isn't it. */
732
+ expectPunct(punct) {
733
+ const tok = this.peek();
734
+ if (tok.type !== "punct" || tok.punct !== punct) throw new ExpressionParseError(`expected '${punct}'`, tok.pos);
735
+ this.pos += 1;
736
+ }
737
+ matchPunct(punct) {
738
+ const tok = this.peek();
739
+ if (tok.type === "punct" && tok.punct === punct) {
740
+ this.pos += 1;
741
+ return true;
742
+ }
743
+ return false;
744
+ }
745
+ countNode() {
746
+ this.nodeCount += 1;
747
+ if (this.nodeCount > 256) throw new ExpressionParseError("expression too complex", this.peek().pos);
748
+ }
749
+ parseTernary() {
750
+ const test = this.parseBinary(1);
751
+ if (this.matchPunct("?")) {
752
+ const consequent = this.parseTernary();
753
+ this.expectPunct(":");
754
+ const alternate = this.parseTernary();
755
+ this.countNode();
756
+ return {
757
+ kind: "conditional",
758
+ test,
759
+ consequent,
760
+ alternate
761
+ };
762
+ }
763
+ return test;
764
+ }
765
+ parseBinary(minPrec) {
766
+ let left = this.parseUnary();
767
+ for (;;) {
768
+ const tok = this.peek();
769
+ if (tok.type !== "punct") break;
770
+ const prec = BINARY_PRECEDENCE[tok.punct];
771
+ if (prec === void 0 || prec < minPrec) break;
772
+ const op = tok.punct;
773
+ this.pos += 1;
774
+ const right = this.parseBinary(prec + 1);
775
+ this.countNode();
776
+ if (isLogicalOp(op)) left = {
777
+ kind: "logical",
778
+ op,
779
+ left,
780
+ right
781
+ };
782
+ else if (isBinaryOp(op)) left = {
783
+ kind: "binary",
784
+ op,
785
+ left,
786
+ right
787
+ };
788
+ else throw new ExpressionParseError(`unexpected operator '${op}'`, tok.pos);
789
+ }
790
+ return left;
791
+ }
792
+ parseUnary() {
793
+ const tok = this.peek();
794
+ if (tok.type === "punct" && (tok.punct === "!" || tok.punct === "-")) {
795
+ const op = tok.punct;
796
+ this.pos += 1;
797
+ const operand = this.parseUnary();
798
+ this.countNode();
799
+ return {
800
+ kind: "unary",
801
+ op,
802
+ operand
803
+ };
804
+ }
805
+ return this.parsePrimary();
806
+ }
807
+ parsePrimary() {
808
+ const tok = this.next();
809
+ switch (tok.type) {
810
+ case "number":
811
+ this.countNode();
812
+ return {
813
+ kind: "literal",
814
+ value: tok.value
815
+ };
816
+ case "string":
817
+ this.countNode();
818
+ return {
819
+ kind: "literal",
820
+ value: tok.value
821
+ };
822
+ case "keyword":
823
+ this.countNode();
824
+ return {
825
+ kind: "literal",
826
+ value: tok.keyword === "null" ? null : tok.keyword === "true"
827
+ };
828
+ case "identifier": {
829
+ const nextTok = this.peek();
830
+ if (nextTok.type === "punct" && nextTok.punct === "(") return this.parseCall(tok.name, tok.pos);
831
+ this.identifiers.add(tok.name);
832
+ this.countNode();
833
+ return {
834
+ kind: "identifier",
835
+ name: tok.name
836
+ };
837
+ }
838
+ case "punct":
839
+ if (tok.punct === "(") {
840
+ const inner = this.parseTernary();
841
+ this.expectPunct(")");
842
+ return inner;
843
+ }
844
+ throw new ExpressionParseError(`unexpected token '${tok.punct}'`, tok.pos);
845
+ case "eof": throw new ExpressionParseError("unexpected end of expression", tok.pos);
846
+ }
847
+ }
848
+ parseCall(callee, pos) {
849
+ if (!EXPRESSION_BUILTIN_NAMES.has(callee)) throw new ExpressionParseError(`unknown function '${callee}'`, pos);
850
+ this.expectPunct("(");
851
+ const args = [];
852
+ if (!this.matchPunct(")")) for (;;) {
853
+ args.push(this.parseTernary());
854
+ if (args.length > 16) throw new ExpressionParseError(`too many arguments to '${callee}'`, pos);
855
+ if (this.matchPunct(",")) continue;
856
+ this.expectPunct(")");
857
+ break;
858
+ }
859
+ this.callees.add(callee);
860
+ this.countNode();
861
+ return {
862
+ kind: "call",
863
+ callee,
864
+ args
865
+ };
866
+ }
867
+ };
868
+ /** Tokenize + parse `source` into a validated `ParsedExpression`. Throws
869
+ * `ExpressionParseError` on any lexical or grammatical failure. */
870
+ function parseExpression(source) {
871
+ return new Parser(tokenize(source)).parse();
872
+ }
873
+ //#endregion
874
+ //#region ../types/dist/esm/expression/compile.mjs
875
+ /**
876
+ * LRU compile cache for parsed expressions (spec §2.4 "parse once … LRU keyed
877
+ * by expr"). The cache stores BOTH successes and failures (negative caching),
878
+ * so a corrupt persisted string costs exactly one tokenize+parse total — not
879
+ * one per read on a hot resolve path.
880
+ *
881
+ * The cache is a module-level singleton: entries are pure, content-addressed
882
+ * ASTs keyed by the raw source string, so sharing one instance across all
883
+ * callers is safe and maximises hit rate.
884
+ */
885
+ var cache = /* @__PURE__ */ new Map();
886
+ function getCached(source) {
887
+ const hit = cache.get(source);
888
+ if (hit !== void 0) {
889
+ cache.delete(source);
890
+ cache.set(source, hit);
891
+ return hit;
892
+ }
893
+ let result;
894
+ try {
895
+ result = {
896
+ ok: true,
897
+ parsed: parseExpression(source)
898
+ };
899
+ } catch (err) {
900
+ result = {
901
+ ok: false,
902
+ error: err instanceof ExpressionParseError ? err.message : String(err)
903
+ };
904
+ }
905
+ cache.set(source, result);
906
+ if (cache.size > 256) {
907
+ const oldest = cache.keys().next().value;
908
+ if (oldest !== void 0) cache.delete(oldest);
909
+ }
910
+ return result;
911
+ }
912
+ /** Compile `source`, returning a discriminated result instead of throwing.
913
+ * Used by read paths that must degrade rather than raise. LRU/negative-cached. */
914
+ function compileExpressionSafe(source) {
915
+ return getCached(source);
916
+ }
917
+ //#endregion
918
+ //#region ../types/dist/esm/expression/evaluator.mjs
919
+ /**
920
+ * Tree-walking evaluator for the safe expression mini-language.
921
+ *
922
+ * SECURITY (spec §4 rule 2/5):
923
+ * - The scope is an `Object.create(null)` copy of ONLY the caller's own
924
+ * enumerable binding entries, so `name in scope` is a pure own-key check and
925
+ * `constructor` / `__proto__` / `toString` are plain unknown identifiers.
926
+ * - Performs ZERO I/O and never touches `globalThis` / `Date` / `Math`
927
+ * directly — the only external calls are into the frozen builtin table.
928
+ * - The grammar has no loops/recursion/lambdas, so a walk is O(nodeCount) by
929
+ * construction; the step counter is defense-in-depth for a crafted max-size
930
+ * AST. Nothing blocks: there are no timers, awaits or unbounded loops.
931
+ */
932
+ var EMPTY_HOOKS = /* @__PURE__ */ Object.freeze({});
933
+ /** Build a null-prototype scope from own-enumerable binding entries. Inherited
934
+ * keys of the input (e.g. from a `{__proto__: {...}}` payload) are NOT copied,
935
+ * so nothing smuggles in via the prototype chain. */
936
+ function createExpressionScope(bindings) {
937
+ const scope = Object.create(null);
938
+ for (const key of Object.keys(bindings)) if (Object.prototype.hasOwnProperty.call(bindings, key)) scope[key] = bindings[key];
939
+ return scope;
940
+ }
941
+ function isFiniteNumber(value) {
942
+ return typeof value === "number" && Number.isFinite(value);
943
+ }
944
+ /** JS truthiness of a primitive value. */
945
+ function truthy(value) {
946
+ return Boolean(value);
947
+ }
948
+ function requireFinite(value, context) {
949
+ if (!Number.isFinite(value)) throw new ExpressionEvalError(`${context} produced a non-finite result`);
950
+ return value;
951
+ }
952
+ function step(ctx) {
953
+ ctx.steps += 1;
954
+ if (ctx.steps > ctx.maxSteps) throw new ExpressionEvalError("expression evaluation step budget exceeded");
955
+ }
956
+ function childPath(path, child) {
957
+ return `${path}/${child}`;
958
+ }
959
+ function evalNode(node, ctx, path) {
960
+ step(ctx);
961
+ switch (node.kind) {
962
+ case "literal": return node.value;
963
+ case "identifier":
964
+ if (!(node.name in ctx.scope)) throw new ExpressionEvalError(`unknown identifier: ${node.name}`);
965
+ return ctx.scope[node.name];
966
+ case "unary": return evalUnary(node.op, evalNode(node.operand, ctx, childPath(path, "operand")));
967
+ case "binary": return evalBinary(node.op, evalNode(node.left, ctx, childPath(path, "left")), evalNode(node.right, ctx, childPath(path, "right")));
968
+ case "logical": {
969
+ const left = evalNode(node.left, ctx, childPath(path, "left"));
970
+ if (node.op === "&&") return truthy(left) ? evalNode(node.right, ctx, childPath(path, "right")) : left;
971
+ return truthy(left) ? left : evalNode(node.right, ctx, childPath(path, "right"));
972
+ }
973
+ case "conditional": return truthy(evalNode(node.test, ctx, childPath(path, "test"))) ? evalNode(node.consequent, ctx, childPath(path, "consequent")) : evalNode(node.alternate, ctx, childPath(path, "alternate"));
974
+ case "call": {
975
+ const args = node.args.map((arg, index) => evalNode(arg, ctx, childPath(path, `arg:${index}`)));
976
+ return invokeCall(node.callee, args, path, ctx);
977
+ }
978
+ }
979
+ }
980
+ function evalUnary(op, operand) {
981
+ if (op === "!") return !truthy(operand);
982
+ if (!isFiniteNumber(operand)) throw new ExpressionEvalError("unary \"-\" requires a finite number");
983
+ return requireFinite(-operand, "unary \"-\"");
984
+ }
985
+ function evalBinary(op, left, right) {
986
+ switch (op) {
987
+ case "==": return left === right;
988
+ case "!=": return left !== right;
989
+ case "+":
990
+ if (typeof left === "string" && typeof right === "string") return left + right;
991
+ if (isFiniteNumber(left) && isFiniteNumber(right)) return requireFinite(left + right, "\"+\"");
992
+ throw new ExpressionEvalError("\"+\" requires two numbers or two strings");
993
+ case "-":
994
+ case "*":
995
+ case "/":
996
+ case "%":
997
+ if (!isFiniteNumber(left) || !isFiniteNumber(right)) throw new ExpressionEvalError(`"${op}" requires two finite numbers`);
998
+ return requireFinite(op === "-" ? left - right : op === "*" ? left * right : op === "/" ? left / right : left % right, `"${op}"`);
999
+ case "<":
1000
+ case "<=":
1001
+ case ">":
1002
+ case ">=":
1003
+ if (isFiniteNumber(left) && isFiniteNumber(right)) return op === "<" ? left < right : op === "<=" ? left <= right : op === ">" ? left > right : left >= right;
1004
+ if (typeof left === "string" && typeof right === "string") return op === "<" ? left < right : op === "<=" ? left <= right : op === ">" ? left > right : left >= right;
1005
+ throw new ExpressionEvalError(`"${op}" requires two numbers or two strings`);
1006
+ }
1007
+ }
1008
+ function invokeCall(callee, args, path, ctx) {
1009
+ if (!Object.prototype.hasOwnProperty.call(EXPRESSION_BUILTINS, callee)) throw new ExpressionEvalError(`unknown function: ${callee}`);
1010
+ const builtin = EXPRESSION_BUILTINS[callee];
1011
+ if (args.length < builtin.minArgs || args.length > builtin.maxArgs) throw new ExpressionEvalError(`${callee}: wrong number of arguments (${args.length})`);
1012
+ if (isStatefulBuiltin(callee)) {
1013
+ if (ctx.invokeStateful === void 0) throw new ExpressionEvalError(`${callee}: stateful evaluation context is required`);
1014
+ return ctx.invokeStateful({
1015
+ name: callee,
1016
+ path,
1017
+ args
1018
+ });
1019
+ }
1020
+ return builtin.apply(args, ctx.hooks);
1021
+ }
1022
+ /** Evaluate an AST node against a scope. Throws `ExpressionEvalError` on any
1023
+ * runtime failure (unknown identifier, type mismatch, non-finite result,
1024
+ * step-budget exhaustion). */
1025
+ function evaluateAst(node, scope, opts) {
1026
+ return evalNode(node, {
1027
+ scope,
1028
+ hooks: opts?.hooks ?? EMPTY_HOOKS,
1029
+ maxSteps: opts?.maxSteps ?? 4096,
1030
+ ...opts?.invokeStateful === void 0 ? {} : { invokeStateful: opts.invokeStateful },
1031
+ steps: 0
1032
+ }, "root");
1033
+ }
1034
+ //#endregion
1035
+ //#region ../types/dist/esm/expression/expression-source.mjs
1036
+ function createStatefulExpressionMemory() {
1037
+ return {
1038
+ calls: /* @__PURE__ */ new Map(),
1039
+ acceptedEdgeAt: null,
1040
+ dwellTransition: null,
1041
+ disarmRoseNext: false
1042
+ };
1043
+ }
1044
+ function cloneStatefulExpressionMemory(memory) {
1045
+ return {
1046
+ calls: new Map([...memory.calls].map(([path, call]) => [path, { ...call }])),
1047
+ acceptedEdgeAt: memory.acceptedEdgeAt,
1048
+ dwellTransition: memory.dwellTransition,
1049
+ disarmRoseNext: memory.disarmRoseNext
1050
+ };
1051
+ }
1052
+ function evaluateStatefulExpressionCall(invocation, memory, env, hooks) {
1053
+ const existing = memory.calls.get(invocation.path);
1054
+ switch (invocation.name) {
1055
+ case "rose": {
1056
+ const call = existing?.kind === "rose" ? existing : { kind: "rose" };
1057
+ memory.calls.set(invocation.path, call);
1058
+ const currentOutput = env.currentOutput === null || typeof env.currentOutput === "number" && Number.isFinite(env.currentOutput) ? env.currentOutput : null;
1059
+ return evaluateRose(invocation.args[0], invocation.args[1], invocation.args[2], call, memory, {
1060
+ currentOutput,
1061
+ startedAtMs: env.startedAtMs,
1062
+ nowMs: env.nowMs
1063
+ });
1064
+ }
1065
+ case "count": {
1066
+ const call = existing?.kind === "count" ? existing : {
1067
+ kind: "count",
1068
+ highWater: null,
1069
+ primed: false
1070
+ };
1071
+ memory.calls.set(invocation.path, call);
1072
+ return evaluateCount(invocation.args[0], call, env.currentOutput);
1073
+ }
1074
+ case "dwell": {
1075
+ const call = existing?.kind === "dwell" ? existing : {
1076
+ kind: "dwell",
1077
+ pendingSince: null,
1078
+ pendingSamples: 0,
1079
+ returnSince: null,
1080
+ transition: null,
1081
+ latched: typeof env.currentOutput === "boolean" ? env.currentOutput : null,
1082
+ seenSince: null
1083
+ };
1084
+ memory.calls.set(invocation.path, call);
1085
+ const dwelled = evaluateDwell(invocation.args[0], invocation.args[1], invocation.args[2], invocation.args[3], call, env.nowMs, hooks);
1086
+ memory.dwellTransition = call.transition;
1087
+ return dwelled;
1088
+ }
1089
+ case "schmitt": {
1090
+ const call = existing?.kind === "schmitt" ? existing : {
1091
+ kind: "schmitt",
1092
+ latched: null,
1093
+ pendingSince: null
1094
+ };
1095
+ memory.calls.set(invocation.path, call);
1096
+ const seed = typeof env.currentOutput === "boolean" ? env.currentOutput : null;
1097
+ return evaluateSchmitt(invocation.args, call, env.nowMs, seed, hooks);
1098
+ }
1099
+ case "latchedAt": {
1100
+ const call = existing?.kind === "latchedAt" ? existing : {
1101
+ kind: "latchedAt",
1102
+ last: void 0,
1103
+ at: null
1104
+ };
1105
+ memory.calls.set(invocation.path, call);
1106
+ const stamped = evaluateLatchedAt(invocation.args[0], call, env.nowMs, memory.dwellTransition);
1107
+ memory.dwellTransition = null;
1108
+ return stamped;
1109
+ }
1110
+ }
1111
+ }
1112
+ /**
1113
+ * Coerce an untrusted `getByPath` / mirror read to an `ExpressionValue`.
1114
+ * Non-primitive values (objects, arrays, `undefined`, functions, bigint,
1115
+ * symbol) and non-finite numbers become `undefined` so the caller can apply
1116
+ * its binding-miss policy (→ `null`). `null` itself is a valid value.
1117
+ */
1118
+ function toExpressionValue(raw) {
1119
+ if (raw === null) return null;
1120
+ if (typeof raw === "string") return raw;
1121
+ if (typeof raw === "boolean") return raw;
1122
+ if (typeof raw === "number") return Number.isFinite(raw) ? raw : void 0;
1123
+ }
1124
+ /**
1125
+ * Author-time validation. Returns `null` when the source is valid, else a
1126
+ * human-readable error message. Checks: the expression compiles; binding count
1127
+ * is within `MAX_EXPRESSION_BINDINGS`; every binding name is a legal identifier,
1128
+ * is not reserved (`now`/keywords) and does not shadow a builtin; and every
1129
+ * FREE identifier of the AST is covered by a binding or the injected `now`.
1130
+ */
1131
+ function validateExpressionSource(src) {
1132
+ const names = Object.keys(src.bindings);
1133
+ if (names.length > 32) return `too many bindings (${names.length} > 32)`;
1134
+ for (const name of names) {
1135
+ if (!EXPRESSION_IDENTIFIER_RE.test(name)) return `invalid binding name '${name}'`;
1136
+ if (RESERVED_BINDING_NAMES.has(name)) return `binding name '${name}' is reserved`;
1137
+ if (EXPRESSION_BUILTIN_NAMES.has(name)) return `binding name '${name}' shadows a builtin function`;
1138
+ }
1139
+ const compiled = compileExpressionSafe(src.expr);
1140
+ if (!compiled.ok) return compiled.error;
1141
+ const bound = new Set(names);
1142
+ for (const id of compiled.parsed.identifiers) {
1143
+ if (id === "now") continue;
1144
+ if (!bound.has(id)) return `expression references unbound identifier '${id}'`;
1145
+ }
1146
+ return null;
1147
+ }
1148
+ /**
1149
+ * Shared read-path evaluation. Builds a null-proto scope from `bindingValues`
1150
+ * plus the injected `now` (supplied by the caller for determinism and
1151
+ * testability), compiles via the LRU, and evaluates. Stateful calls are
1152
+ * delegated through `opts.invokeStateful` with their stable AST path. Any
1153
+ * failure (parse or eval) returns `{ ok: false }` — the caller treats that as
1154
+ * "skip this derivation", never as a throw that takes the pass down.
1155
+ */
1156
+ function evaluateExpressionSource(expr, bindingValues, now, opts) {
1157
+ const compiled = compileExpressionSafe(expr);
1158
+ if (!compiled.ok) return {
1159
+ ok: false,
1160
+ error: compiled.error
1161
+ };
1162
+ const scope = createExpressionScope({
1163
+ ...bindingValues,
1164
+ ["now"]: now
1165
+ });
1166
+ const hooks = {
1167
+ ...opts?.hooks,
1168
+ now
1169
+ };
1170
+ try {
1171
+ return {
1172
+ ok: true,
1173
+ value: evaluateAst(compiled.parsed.ast, scope, {
1174
+ ...opts,
1175
+ hooks
1176
+ })
1177
+ };
1178
+ } catch (err) {
1179
+ return {
1180
+ ok: false,
1181
+ error: err instanceof ExpressionEvalError ? err.message : String(err)
1182
+ };
1183
+ }
1184
+ }
1185
+ //#endregion
1186
+ //#region ../types/dist/esm/composition/helpers/history-math.mjs
1187
+ /**
1188
+ * Statistics and integrals over a history read (D944).
1189
+ *
1190
+ * Pure: the same points always give the same answer, so a restart recomputes
1191
+ * rather than trusting a buffer. A gauge mean is time-weighted (value × ms),
1192
+ * never the mean of the samples. A hole with no held value is not integrated
1193
+ * as zero. A truncated read is not published.
1194
+ */
1195
+ var STATISTIC_STATS = [
1196
+ "min",
1197
+ "max",
1198
+ "mean",
1199
+ "sum",
1200
+ "count",
1201
+ "change"
1202
+ ];
1203
+ function finite(value) {
1204
+ return typeof value === "number" && Number.isFinite(value);
1205
+ }
1206
+ function pointValue(point) {
1207
+ if (finite(point.value)) return point.value;
1208
+ if (finite(point.last)) return point.last;
1209
+ return null;
1210
+ }
1211
+ function stepCoverage(read) {
1212
+ const points = read.points.filter((point) => point.t >= read.from && point.t < read.to);
1213
+ const start = finite(read.before?.value) ? read.before.value : null;
1214
+ let held = start;
1215
+ let cursor = read.from;
1216
+ let gaps = 0;
1217
+ const segments = [];
1218
+ if (held === null) {
1219
+ const first = points.find((point) => pointValue(point) !== null);
1220
+ if (first === void 0) return {
1221
+ segments,
1222
+ included: 0,
1223
+ gaps: 1,
1224
+ end: null,
1225
+ start: null
1226
+ };
1227
+ if (first.t > read.from) gaps += 1;
1228
+ cursor = first.t;
1229
+ held = pointValue(first);
1230
+ }
1231
+ for (const point of points) {
1232
+ const next = pointValue(point);
1233
+ if (held !== null && point.t > cursor) segments.push({
1234
+ value: held,
1235
+ ms: point.t - cursor
1236
+ });
1237
+ if (next !== null) held = next;
1238
+ if (point.t > cursor) cursor = point.t;
1239
+ }
1240
+ if (held !== null && read.to > cursor) segments.push({
1241
+ value: held,
1242
+ ms: read.to - cursor
1243
+ });
1244
+ const end = points.reduce((latest, point) => pointValue(point) ?? latest, held);
1245
+ return {
1246
+ segments,
1247
+ included: points.length,
1248
+ gaps,
1249
+ end,
1250
+ start
1251
+ };
1252
+ }
1253
+ function rollupCoverage(read) {
1254
+ const weighted = read.points.filter((point) => finite(point.twMean) && finite(point.twMs) && point.twMs > 0);
1255
+ if (weighted.length === 0) return null;
1256
+ const first = weighted[0];
1257
+ const gaps = read.before === null && first !== void 0 && first.t > read.from ? 1 : 0;
1258
+ const levels = read.points.flatMap((point) => finite(point.last) ? [point.last] : []);
1259
+ const end = levels.length > 0 ? levels[levels.length - 1] ?? null : null;
1260
+ return {
1261
+ segments: weighted.flatMap((point) => finite(point.twMean) && finite(point.twMs) ? [{
1262
+ value: point.twMean,
1263
+ ms: point.twMs
1264
+ }] : []),
1265
+ included: weighted.length,
1266
+ gaps,
1267
+ end,
1268
+ start: finite(read.before?.value) ? read.before.value : null
1269
+ };
1270
+ }
1271
+ function coverageOf(read) {
1272
+ if (read.tier !== "raw") {
1273
+ const rolled = rollupCoverage(read);
1274
+ if (rolled !== null) return rolled;
1275
+ }
1276
+ return stepCoverage(read);
1277
+ }
1278
+ function timeWeighted(segments) {
1279
+ let ms = 0;
1280
+ let sum = 0;
1281
+ for (const segment of segments) {
1282
+ ms += segment.ms;
1283
+ sum += segment.value * segment.ms;
1284
+ }
1285
+ if (ms <= 0) return null;
1286
+ return sum / ms;
1287
+ }
1288
+ function extremes(read, covered) {
1289
+ const lows = [];
1290
+ const highs = [];
1291
+ for (const point of read.points) {
1292
+ if (finite(point.min)) lows.push(point.min);
1293
+ if (finite(point.max)) highs.push(point.max);
1294
+ }
1295
+ if (covered.start !== null) {
1296
+ lows.push(covered.start);
1297
+ highs.push(covered.start);
1298
+ }
1299
+ return {
1300
+ min: lows.length === 0 ? null : Math.min(...lows),
1301
+ max: highs.length === 0 ? null : Math.max(...highs)
1302
+ };
1303
+ }
1304
+ function counterGrowth(read) {
1305
+ const deltas = read.points.flatMap((point) => finite(point.delta) ? [point.delta] : []);
1306
+ if (deltas.length === 0) return null;
1307
+ return deltas.reduce((sum, delta) => sum + delta, 0);
1308
+ }
1309
+ function hold(reason) {
1310
+ return {
1311
+ write: "hold",
1312
+ value: null,
1313
+ included: 0,
1314
+ excluded: 0,
1315
+ reason
1316
+ };
1317
+ }
1318
+ function gapValue(reason, included) {
1319
+ return {
1320
+ write: "null",
1321
+ value: null,
1322
+ included,
1323
+ excluded: 1,
1324
+ reason
1325
+ };
1326
+ }
1327
+ function numberValue(value, included, gaps, reason) {
1328
+ return {
1329
+ write: "number",
1330
+ value,
1331
+ included,
1332
+ excluded: gaps,
1333
+ reason: gaps > 0 ? reason : null
1334
+ };
1335
+ }
1336
+ var GAP_REASON = "history has a gap — that interval was not counted as zero";
1337
+ function evaluateStatistic(stat, read) {
1338
+ if (read.truncated) return hold("the history query was truncated — the last statistic is kept");
1339
+ if (stat === "sum" && read.kind !== "counter") return hold("a gauge has no sum — that is the integral template");
1340
+ if (read.to <= read.from) return gapValue("the range is empty", 0);
1341
+ const covered = coverageOf(read);
1342
+ if (covered.segments.length === 0 && covered.start === null) return gapValue(GAP_REASON, covered.included);
1343
+ if (stat === "count") return numberValue(covered.included, covered.included, covered.gaps, GAP_REASON);
1344
+ if (stat === "sum" || stat === "change" && read.kind === "counter") {
1345
+ const growth = counterGrowth(read);
1346
+ if (growth === null) return gapValue("the counter has no growth in this range", covered.included);
1347
+ return numberValue(growth, covered.included, covered.gaps, GAP_REASON);
1348
+ }
1349
+ if (stat === "change") {
1350
+ if (covered.start === null || covered.end === null) return gapValue("the change has no value at the start of the range", covered.included);
1351
+ return numberValue(covered.end - covered.start, covered.included, covered.gaps, GAP_REASON);
1352
+ }
1353
+ if (stat === "min" || stat === "max") {
1354
+ const ends = extremes(read, covered);
1355
+ const value = stat === "min" ? ends.min : ends.max;
1356
+ if (value === null) return gapValue(GAP_REASON, covered.included);
1357
+ return numberValue(value, covered.included, covered.gaps, GAP_REASON);
1358
+ }
1359
+ const mean = timeWeighted(covered.segments);
1360
+ if (mean === null) return gapValue(GAP_REASON, covered.included);
1361
+ return numberValue(mean, covered.included, covered.gaps, GAP_REASON);
1362
+ }
1363
+ function integrateReading(read, scale) {
1364
+ if (read.truncated) return hold("the history query was truncated — the last total is kept");
1365
+ if (read.kind === "counter") return hold("a counter is already a total — it is not integrated again");
1366
+ if (read.to <= read.from) return gapValue("the range is empty", 0);
1367
+ const covered = coverageOf(read);
1368
+ if (covered.segments.length === 0) return {
1369
+ write: "hold",
1370
+ value: null,
1371
+ included: covered.included,
1372
+ excluded: covered.gaps,
1373
+ reason: GAP_REASON
1374
+ };
1375
+ let unitMs = 0;
1376
+ for (const segment of covered.segments) unitMs += segment.value * segment.ms;
1377
+ return numberValue(scale === "energy-kwh" ? wattMillisecondsToKwh(unitMs) : unitMs / 1e3, covered.included, covered.gaps, GAP_REASON);
1378
+ }
1379
+ function samplesOf(read) {
1380
+ const out = [];
1381
+ if (read.before !== null && finite(read.before.value)) out.push({
1382
+ at: read.from,
1383
+ value: read.before.value
1384
+ });
1385
+ for (const point of read.points) {
1386
+ if (point.t < read.from || point.t > read.to) continue;
1387
+ const value = pointValue(point);
1388
+ if (value === null) continue;
1389
+ const at = read.tier === "raw" || !finite(point.twMs) ? point.t : point.t + point.twMs;
1390
+ out.push({
1391
+ at: Math.min(at, read.to),
1392
+ value
1393
+ });
1394
+ }
1395
+ return out.toSorted((a, b) => a.at - b.at);
1396
+ }
1397
+ /** A sample-less tail or head longer than this share of the window is counted as a gap. */
1398
+ var UNCOVERED_LIMIT = .1;
1399
+ var DERIVATIVE_GAP_REASON = "history stops short of the window — the rate is over the part that was measured";
1400
+ function derivativeValue(change, spanMs, perMs, included, windowMs) {
1401
+ return numberValue(change / (spanMs / perMs), included, windowMs - spanMs > windowMs * UNCOVERED_LIMIT ? 1 : 0, DERIVATIVE_GAP_REASON);
1402
+ }
1403
+ /**
1404
+ * Rate of change over a window, per `perMs`. The slope is taken between the
1405
+ * first and the last measured sample, so a hole inside the window neither
1406
+ * counts as zero nor stretches the elapsed time. A gauge that reported
1407
+ * nothing after the value held at the start is flat (rate 0); fewer than two
1408
+ * samples and no held value is a known gap (D393).
1409
+ */
1410
+ function evaluateDerivative(read, perMs) {
1411
+ if (read.truncated) return hold("the history query was truncated — the last rate is kept");
1412
+ if (read.to <= read.from) return gapValue("the range is empty", 0);
1413
+ const windowMs = read.to - read.from;
1414
+ const samples = samplesOf(read);
1415
+ const first = samples[0];
1416
+ const last = samples[samples.length - 1];
1417
+ if (first === void 0 || last === void 0) return gapValue("history has no reading in this window", 0);
1418
+ if (read.kind === "counter") {
1419
+ const heldAtStart = read.before !== null && finite(read.before.value);
1420
+ const startsAt = heldAtStart ? read.from : first.at;
1421
+ const deltas = read.points.flatMap((point) => point.t >= read.from && point.t <= read.to && finite(point.delta) && (heldAtStart || point.t > first.at) ? [point.delta] : []);
1422
+ const spanMs = last.at - startsAt;
1423
+ if (deltas.length === 0 || spanMs <= 0) return gapValue("the counter has no growth in this window", samples.length);
1424
+ return derivativeValue(deltas.reduce((sum, delta) => sum + delta, 0), spanMs, perMs, samples.length, windowMs);
1425
+ }
1426
+ if (samples.length === 1 && first.at === read.from && read.before !== null) return numberValue(0, 1, 0, null);
1427
+ const spanMs = last.at - first.at;
1428
+ if (samples.length < 2 || spanMs <= 0) return gapValue("the rate needs two readings in the window", samples.length);
1429
+ return derivativeValue(last.value - first.value, spanMs, perMs, samples.length, windowMs);
1430
+ }
1431
+ //#endregion
1432
+ //#region ../types/dist/esm/composition/helpers/history-window.mjs
1433
+ /**
1434
+ * The range a statistics or integral helper asks history for (D944).
1435
+ *
1436
+ * Calendar edges are the hub's timezone, never UTC midnight: a day is 23, 24
1437
+ * or 25 hours across a DST change. A tier is eligible only when its retention
1438
+ * is strictly longer than the longest that range can be. Forever qualifies.
1439
+ * Equal to a tier's retention is a refusal, not a short answer.
1440
+ */
1441
+ var MINUTE_MS = 6e4;
1442
+ var HOUR_MS = 60 * MINUTE_MS;
1443
+ var DAY_MS = 24 * HOUR_MS;
1444
+ var ROLLING_SPANS = [
1445
+ "1h",
1446
+ "24h",
1447
+ "2d",
1448
+ "7d",
1449
+ "30d",
1450
+ "custom"
1451
+ ];
1452
+ var CALENDAR_PERIODS = [
1453
+ "today",
1454
+ "yesterday",
1455
+ "this-week",
1456
+ "this-month"
1457
+ ];
1458
+ var RESET_PERIODS = [
1459
+ "never",
1460
+ "daily",
1461
+ "weekly",
1462
+ "monthly"
1463
+ ];
1464
+ /** Faster than this is not a history query. Rolling windows at most this often. */
1465
+ var HISTORY_FAST_MS = 6e4;
1466
+ var HISTORY_SLOW_MS = 5 * MINUTE_MS;
1467
+ var ROLLING_MS = {
1468
+ "1h": HOUR_MS,
1469
+ "24h": 24 * HOUR_MS,
1470
+ "2d": 2 * DAY_MS,
1471
+ "7d": 7 * DAY_MS,
1472
+ "30d": 30 * DAY_MS
1473
+ };
1474
+ /** The device-history defaults: raw 7 d, 5 m 30 d, 1 h 365 d, 1 d forever. */
1475
+ var DEFAULT_HISTORY_RETENTION = {
1476
+ rawMs: 7 * DAY_MS,
1477
+ fiveMinuteMs: 30 * DAY_MS,
1478
+ hourMs: 365 * DAY_MS,
1479
+ dayMs: null
1480
+ };
1481
+ /**
1482
+ * The retention a device-history settings document states. A missing or
1483
+ * invalid number is the default; a `dayDays` of 0 (or none) keeps the daily
1484
+ * tier forever.
1485
+ */
1486
+ function historyRetentionFromSettings(raw) {
1487
+ return {
1488
+ rawMs: positiveDays(raw["rawDays"], DEFAULT_HISTORY_RETENTION.rawMs),
1489
+ fiveMinuteMs: positiveDays(raw["fiveMinuteDays"], DEFAULT_HISTORY_RETENTION.fiveMinuteMs),
1490
+ hourMs: positiveDays(raw["hourDays"], DEFAULT_HISTORY_RETENTION.hourMs),
1491
+ dayMs: positiveDaysOrForever(raw["dayDays"])
1492
+ };
1493
+ }
1494
+ function positiveDays(value, fallbackMs) {
1495
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? value * DAY_MS : fallbackMs;
1496
+ }
1497
+ function positiveDaysOrForever(value) {
1498
+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) return null;
1499
+ return value * DAY_MS;
1500
+ }
1501
+ var rollingWindowObject = /* @__PURE__ */ z.object({
1502
+ kind: /* @__PURE__ */ z.literal("rolling"),
1503
+ span: /* @__PURE__ */ z.enum(ROLLING_SPANS),
1504
+ customMinutes: /* @__PURE__ */ z.number().int().min(5).optional()
1505
+ }).check((payload) => {
1506
+ if (payload.value.span === "custom" && payload.value.customMinutes === void 0) payload.issues.push({
1507
+ code: "custom",
1508
+ message: "a custom range needs a duration in minutes",
1509
+ path: ["customMinutes"],
1510
+ input: payload.value
1511
+ });
1512
+ if (payload.value.span !== "custom" && payload.value.customMinutes !== void 0) payload.issues.push({
1513
+ code: "custom",
1514
+ message: "only a custom range carries a duration",
1515
+ path: ["customMinutes"],
1516
+ input: payload.value
1517
+ });
1518
+ });
1519
+ var RollingWindowSchema = rollingWindowObject;
1520
+ var calendarWindowObject = /* @__PURE__ */ z.object({
1521
+ kind: /* @__PURE__ */ z.literal("calendar"),
1522
+ period: /* @__PURE__ */ z.enum(CALENDAR_PERIODS)
1523
+ });
1524
+ var StatisticWindowSchema = /* @__PURE__ */ z.discriminatedUnion("kind", [rollingWindowObject, calendarWindowObject]);
1525
+ var WEEKDAY_INDEX = {
1526
+ Sun: 0,
1527
+ Mon: 1,
1528
+ Tue: 2,
1529
+ Wed: 3,
1530
+ Thu: 4,
1531
+ Fri: 5,
1532
+ Sat: 6
1533
+ };
1534
+ var FORMATTERS = /* @__PURE__ */ new Map();
1535
+ function formatterFor(timeZone) {
1536
+ const held = FORMATTERS.get(timeZone);
1537
+ if (held !== void 0) return held;
1538
+ let made;
1539
+ try {
1540
+ made = new Intl.DateTimeFormat("en-US", {
1541
+ timeZone,
1542
+ weekday: "short",
1543
+ year: "numeric",
1544
+ month: "2-digit",
1545
+ day: "2-digit",
1546
+ hour: "2-digit",
1547
+ minute: "2-digit",
1548
+ second: "2-digit",
1549
+ hourCycle: "h23"
1550
+ });
1551
+ } catch {
1552
+ made = null;
1553
+ }
1554
+ FORMATTERS.set(timeZone, made);
1555
+ return made;
1556
+ }
1557
+ function zonedClock(ms, timeZone) {
1558
+ const formatter = formatterFor(timeZone);
1559
+ if (formatter === null) return null;
1560
+ const parts = formatter.formatToParts(new Date(ms));
1561
+ const read = (type) => parts.find((part) => part.type === type)?.value;
1562
+ const year = Number(read("year"));
1563
+ const month = Number(read("month"));
1564
+ const day = Number(read("day"));
1565
+ const hourRaw = Number(read("hour"));
1566
+ const minute = Number(read("minute"));
1567
+ const second = Number(read("second"));
1568
+ const weekday = WEEKDAY_INDEX[read("weekday") ?? ""];
1569
+ if (!Number.isInteger(year) || !Number.isInteger(month) || !Number.isInteger(day) || !Number.isInteger(hourRaw) || !Number.isInteger(minute) || !Number.isInteger(second) || weekday === void 0) return null;
1570
+ return {
1571
+ year,
1572
+ month,
1573
+ day,
1574
+ hour: hourRaw === 24 ? 0 : hourRaw,
1575
+ minute,
1576
+ second,
1577
+ weekday
1578
+ };
1579
+ }
1580
+ function utcOf(clock, timeZone) {
1581
+ const guess = Date.UTC(clock.year, clock.month - 1, clock.day, clock.hour, clock.minute, clock.second);
1582
+ const first = zonedClock(guess, timeZone);
1583
+ if (first === null) return null;
1584
+ const offset = Date.UTC(first.year, first.month - 1, first.day, first.hour, first.minute, first.second) - guess;
1585
+ const shifted = guess - offset;
1586
+ const second = zonedClock(shifted, timeZone);
1587
+ if (second === null) return null;
1588
+ const offset2 = Date.UTC(second.year, second.month - 1, second.day, second.hour, second.minute, second.second) - shifted;
1589
+ return offset2 === offset ? shifted : guess - offset2;
1590
+ }
1591
+ function midnightOf(ms, timeZone) {
1592
+ const clock = zonedClock(ms, timeZone);
1593
+ if (clock === null) return null;
1594
+ return utcOf({
1595
+ ...clock,
1596
+ hour: 0,
1597
+ minute: 0,
1598
+ second: 0
1599
+ }, timeZone);
1600
+ }
1601
+ function monthStart(ms, timeZone) {
1602
+ const clock = zonedClock(ms, timeZone);
1603
+ if (clock === null) return null;
1604
+ return utcOf({
1605
+ ...clock,
1606
+ day: 1,
1607
+ hour: 0,
1608
+ minute: 0,
1609
+ second: 0
1610
+ }, timeZone);
1611
+ }
1612
+ function weekStart(ms, timeZone) {
1613
+ const clock = zonedClock(ms, timeZone);
1614
+ let cursor = midnightOf(ms, timeZone);
1615
+ if (clock === null || cursor === null) return null;
1616
+ const back = clock.weekday === 0 ? 6 : clock.weekday - 1;
1617
+ for (let step = 0; step < back; step++) {
1618
+ const previous = midnightOf(cursor - 1, timeZone);
1619
+ if (previous === null) return null;
1620
+ cursor = previous;
1621
+ }
1622
+ return cursor;
1623
+ }
1624
+ function keptLabel(ms) {
1625
+ if (ms === null) return "forever";
1626
+ if (ms % 864e5 === 0) return `${ms / DAY_MS} d`;
1627
+ if (ms % 36e5 === 0) return `${ms / HOUR_MS} h`;
1628
+ return `${ms / MINUTE_MS} min`;
1629
+ }
1630
+ function retentionSentence(retention) {
1631
+ return `raw ${keptLabel(retention.rawMs)}, 5m ${keptLabel(retention.fiveMinuteMs)}, 1h ${keptLabel(retention.hourMs)}, 1d ${keptLabel(retention.dayMs)}`;
1632
+ }
1633
+ function tierFor(durationMs, retention) {
1634
+ const rows = [
1635
+ {
1636
+ tier: "raw",
1637
+ keptMs: retention.rawMs
1638
+ },
1639
+ {
1640
+ tier: "5m",
1641
+ keptMs: retention.fiveMinuteMs
1642
+ },
1643
+ {
1644
+ tier: "1h",
1645
+ keptMs: retention.hourMs
1646
+ },
1647
+ {
1648
+ tier: "1d",
1649
+ keptMs: retention.dayMs
1650
+ }
1651
+ ];
1652
+ for (const row of rows) if (row.keptMs === null || row.keptMs > durationMs) return {
1653
+ ok: true,
1654
+ tier: row.tier,
1655
+ maxDurationMs: durationMs
1656
+ };
1657
+ return {
1658
+ ok: false,
1659
+ reason: `the range is ${keptLabel(durationMs)} and no history tier is kept strictly longer (${retentionSentence(retention)})`
1660
+ };
1661
+ }
1662
+ function rollingDurationMs(window) {
1663
+ if (window.span === "custom") return window.customMinutes === void 0 ? null : window.customMinutes * MINUTE_MS;
1664
+ return ROLLING_MS[window.span];
1665
+ }
1666
+ /** Longest the window can be. Calendar periods use their full length, not the elapsed part. */
1667
+ function maxDurationMs(window) {
1668
+ if (window.kind === "rolling") return rollingDurationMs(window);
1669
+ switch (window.period) {
1670
+ case "today":
1671
+ case "yesterday": return 25 * HOUR_MS;
1672
+ case "this-week": return 6084e5;
1673
+ case "this-month": return 2682e6;
1674
+ }
1675
+ }
1676
+ function planStatisticTier(window, retention) {
1677
+ const duration = maxDurationMs(window);
1678
+ if (duration === null) return {
1679
+ ok: false,
1680
+ reason: "a custom range needs a duration of at least 5 minutes"
1681
+ };
1682
+ return tierFor(duration, retention);
1683
+ }
1684
+ function planResetTier(reset, retention) {
1685
+ switch (reset) {
1686
+ case "never": return tierFor(Number.POSITIVE_INFINITY, retention);
1687
+ case "daily": return tierFor(25 * HOUR_MS, retention);
1688
+ case "weekly": return tierFor(6084e5, retention);
1689
+ case "monthly": return tierFor(2682e6, retention);
1690
+ }
1691
+ }
1692
+ function openStatistic(window, now, timeZone) {
1693
+ if (window.kind === "rolling") {
1694
+ const duration = rollingDurationMs(window);
1695
+ if (duration === null) return null;
1696
+ return {
1697
+ from: now - duration,
1698
+ to: now
1699
+ };
1700
+ }
1701
+ const today = midnightOf(now, timeZone);
1702
+ if (today === null) return null;
1703
+ switch (window.period) {
1704
+ case "today": return {
1705
+ from: today,
1706
+ to: now
1707
+ };
1708
+ case "yesterday": {
1709
+ const start = midnightOf(today - 1, timeZone);
1710
+ return start === null ? null : {
1711
+ from: start,
1712
+ to: today
1713
+ };
1714
+ }
1715
+ case "this-week": {
1716
+ const start = weekStart(now, timeZone);
1717
+ return start === null ? null : {
1718
+ from: start,
1719
+ to: now
1720
+ };
1721
+ }
1722
+ case "this-month": {
1723
+ const start = monthStart(now, timeZone);
1724
+ return start === null ? null : {
1725
+ from: start,
1726
+ to: now
1727
+ };
1728
+ }
1729
+ }
1730
+ }
1731
+ function openReset(reset, now, timeZone) {
1732
+ if (reset === "never") return {
1733
+ from: 0,
1734
+ to: now
1735
+ };
1736
+ const today = midnightOf(now, timeZone);
1737
+ if (today === null) return null;
1738
+ if (reset === "daily") return {
1739
+ from: today,
1740
+ to: now
1741
+ };
1742
+ if (reset === "weekly") {
1743
+ const start = weekStart(now, timeZone);
1744
+ return start === null ? null : {
1745
+ from: start,
1746
+ to: now
1747
+ };
1748
+ }
1749
+ const start = monthStart(now, timeZone);
1750
+ return start === null ? null : {
1751
+ from: start,
1752
+ to: now
1753
+ };
1754
+ }
1755
+ /** The next hub-local midnight, strictly after `now`. Monday is one of these. */
1756
+ function nextLocalMidnight(now, timeZone) {
1757
+ const today = midnightOf(now, timeZone);
1758
+ if (today === null) return null;
1759
+ return midnightOf(today + 26 * HOUR_MS, timeZone);
1760
+ }
1761
+ function statisticCadenceMs(window) {
1762
+ if (window.kind === "calendar") return window.period === "today" ? HISTORY_FAST_MS : HISTORY_SLOW_MS;
1763
+ const duration = rollingDurationMs(window);
1764
+ if (duration !== null && duration <= 24 * 36e5) return HISTORY_FAST_MS;
1765
+ return HISTORY_SLOW_MS;
1766
+ }
1767
+ //#endregion
1768
+ //#region ../types/dist/esm/composition/source-ref.mjs
1769
+ /**
1770
+ * A composition source identity: `(addonId, stableId)`, never a numeric device
1771
+ * id. Split out so helper schemas can name it without a cycle through
1772
+ * `composition.ts` (D659).
1773
+ */
1774
+ var CompositionSourceRefSchema = /* @__PURE__ */ z.object({
1775
+ /** The owning addon; `stableId` is unique only within it. */
1776
+ addonId: /* @__PURE__ */ z.string().min(1),
1777
+ stableId: /* @__PURE__ */ z.string().min(1)
1778
+ });
1779
+ //#endregion
1780
+ //#region ../types/dist/esm/composition/helpers/spec.mjs
1781
+ var GROUP_TEMPLATE_IDS = [
1782
+ "temperature",
1783
+ "humidity",
1784
+ "pressure",
1785
+ "illuminance",
1786
+ "power",
1787
+ "energy",
1788
+ "battery",
1789
+ "numeric",
1790
+ "motion",
1791
+ "contact",
1792
+ "leak",
1793
+ "smoke",
1794
+ "occupancy",
1795
+ "binary",
1796
+ "switch",
1797
+ "light",
1798
+ "fan",
1799
+ "cover",
1800
+ "valve",
1801
+ "lock",
1802
+ "media-player",
1803
+ "climate"
1804
+ ];
1805
+ var NUMERIC_AGGREGATES = [
1806
+ "mean",
1807
+ "median",
1808
+ "min",
1809
+ "max",
1810
+ "sum"
1811
+ ];
1812
+ var BINARY_AGGREGATES = ["any", "all"];
1813
+ /** How an actuator group decides it is on. Unknown members never count as off. */
1814
+ var ACTIVE_CRITERIA = ["at-least-one", "all"];
1815
+ var AGGREGATE_REDUCERS = [
1816
+ "mean",
1817
+ "median",
1818
+ "min",
1819
+ "max",
1820
+ "sum",
1821
+ "any",
1822
+ "all"
1823
+ ];
1824
+ var GroupTemplateIdSchema = /* @__PURE__ */ z.enum(GROUP_TEMPLATE_IDS);
1825
+ var AggregateReducerSchema = /* @__PURE__ */ z.enum(AGGREGATE_REDUCERS);
1826
+ var ActiveCriterionSchema = /* @__PURE__ */ z.enum(ACTIVE_CRITERIA);
1827
+ /** One member. The field is stored so occupancy can name motion or binary. */
1828
+ var HelperMemberSchema = /* @__PURE__ */ z.object({
1829
+ source: CompositionSourceRefSchema,
1830
+ cap: /* @__PURE__ */ z.string().min(1),
1831
+ fieldPath: /* @__PURE__ */ z.string().min(1)
1832
+ });
1833
+ /** A group, a statistic, or an integral (D944). The composer runs all three. */
1834
+ var GroupHelperSpecSchema = /* @__PURE__ */ z.object({
1835
+ kind: /* @__PURE__ */ z.literal("group"),
1836
+ templateId: GroupTemplateIdSchema,
1837
+ aggregate: AggregateReducerSchema,
1838
+ members: /* @__PURE__ */ z.array(HelperMemberSchema).min(1).max(64),
1839
+ /** Actuator groups only. Readings leave this unset. */
1840
+ active: /* @__PURE__ */ ActiveCriterionSchema.optional()
1841
+ });
1842
+ var statisticHelperObject = /* @__PURE__ */ z.object({
1843
+ kind: /* @__PURE__ */ z.literal("statistic"),
1844
+ stat: /* @__PURE__ */ z.enum(STATISTIC_STATS),
1845
+ window: StatisticWindowSchema,
1846
+ source: HelperMemberSchema
1847
+ });
1848
+ var integralHelperObject = /* @__PURE__ */ z.object({
1849
+ kind: /* @__PURE__ */ z.literal("integral"),
1850
+ reset: /* @__PURE__ */ z.enum(RESET_PERIODS),
1851
+ output: /* @__PURE__ */ z.enum(["energy", "meter"]),
1852
+ source: HelperMemberSchema
1853
+ });
1854
+ var thresholdHelperObject = /* @__PURE__ */ z.object({
1855
+ kind: /* @__PURE__ */ z.literal("threshold"),
1856
+ source: HelperMemberSchema,
1857
+ high: /* @__PURE__ */ z.number(),
1858
+ low: /* @__PURE__ */ z.number(),
1859
+ onForMs: /* @__PURE__ */ z.number().int().nonnegative(),
1860
+ offForMs: /* @__PURE__ */ z.number().int().nonnegative()
1861
+ });
1862
+ var arithmeticHelperObject = /* @__PURE__ */ z.object({
1863
+ kind: /* @__PURE__ */ z.literal("arithmetic"),
1864
+ op: /* @__PURE__ */ z.enum([
1865
+ "sum",
1866
+ "difference",
1867
+ "ratio"
1868
+ ]),
1869
+ inputs: /* @__PURE__ */ z.array(HelperMemberSchema).min(2).max(64)
1870
+ });
1871
+ var expressionHelperObject = /* @__PURE__ */ z.object({
1872
+ kind: /* @__PURE__ */ z.literal("expression"),
1873
+ expr: /* @__PURE__ */ z.string().min(1),
1874
+ inputs: /* @__PURE__ */ z.array(/* @__PURE__ */ z.object({
1875
+ name: /* @__PURE__ */ z.string().min(1),
1876
+ member: HelperMemberSchema
1877
+ })).min(1).max(64),
1878
+ output: /* @__PURE__ */ z.enum(["number", "boolean"])
1879
+ });
1880
+ var derivativeHelperObject = /* @__PURE__ */ z.object({
1881
+ kind: /* @__PURE__ */ z.literal("derivative"),
1882
+ window: RollingWindowSchema,
1883
+ per: /* @__PURE__ */ z.enum([
1884
+ "second",
1885
+ "minute",
1886
+ "hour"
1887
+ ]),
1888
+ source: HelperMemberSchema
1889
+ });
1890
+ /** The stream profiles a camera grid can publish. */
1891
+ var GRID_PROFILES = [
1892
+ "high",
1893
+ "mid",
1894
+ "low"
1895
+ ];
1896
+ /** A rectangle in normalized [0,1] coordinates of whatever contains it. */
1897
+ var GridRectSchema = /* @__PURE__ */ z.object({
1898
+ x: /* @__PURE__ */ z.number().min(0).max(1),
1899
+ y: /* @__PURE__ */ z.number().min(0).max(1),
1900
+ width: /* @__PURE__ */ z.number().gt(0).max(1),
1901
+ height: /* @__PURE__ */ z.number().gt(0).max(1)
1902
+ });
1903
+ var GridCellSpecSchema = /* @__PURE__ */ z.object({
1904
+ source: CompositionSourceRefSchema,
1905
+ region: GridRectSchema,
1906
+ cell: GridRectSchema
1907
+ });
1908
+ var gridHelperObject = /* @__PURE__ */ z.object({
1909
+ kind: /* @__PURE__ */ z.literal("grid"),
1910
+ fps: /* @__PURE__ */ z.number().int().min(1).max(60),
1911
+ publishedProfiles: /* @__PURE__ */ z.array(/* @__PURE__ */ z.enum(GRID_PROFILES)).max(3),
1912
+ cells: /* @__PURE__ */ z.array(GridCellSpecSchema).max(16)
1913
+ });
1914
+ var cropHelperObject = /* @__PURE__ */ z.object({
1915
+ kind: /* @__PURE__ */ z.literal("crop"),
1916
+ source: CompositionSourceRefSchema,
1917
+ rect: GridRectSchema,
1918
+ aspect: /* @__PURE__ */ z.enum([
1919
+ "16:9",
1920
+ "4:3",
1921
+ "1:1",
1922
+ "free"
1923
+ ]),
1924
+ fps: /* @__PURE__ */ z.number().int().min(1).max(60),
1925
+ publishedProfiles: /* @__PURE__ */ z.array(/* @__PURE__ */ z.enum(GRID_PROFILES)).max(3)
1926
+ });
1927
+ var terminalHelperObject = /* @__PURE__ */ z.object({
1928
+ kind: /* @__PURE__ */ z.literal("terminal"),
1929
+ terminalId: /* @__PURE__ */ z.string().uuid()
1930
+ });
1931
+ var HelperSpecSchema = /* @__PURE__ */ z.discriminatedUnion("kind", [
1932
+ gridHelperObject,
1933
+ cropHelperObject,
1934
+ terminalHelperObject,
1935
+ GroupHelperSpecSchema,
1936
+ statisticHelperObject,
1937
+ integralHelperObject,
1938
+ thresholdHelperObject,
1939
+ arithmeticHelperObject,
1940
+ expressionHelperObject,
1941
+ derivativeHelperObject
1942
+ ]);
1943
+ function isHistoryHelper(spec) {
1944
+ return spec.kind === "statistic" || spec.kind === "integral" || spec.kind === "derivative";
1945
+ }
1946
+ /** Every member a helper reads. A group has many; the others have one. */
1947
+ function helperMembers(spec) {
1948
+ switch (spec.kind) {
1949
+ case "group": return spec.members;
1950
+ case "statistic":
1951
+ case "integral":
1952
+ case "threshold":
1953
+ case "derivative": return [spec.source];
1954
+ case "arithmetic": return spec.inputs;
1955
+ case "expression": return spec.inputs.map((input) => input.member);
1956
+ case "grid":
1957
+ case "crop":
1958
+ case "terminal": return [];
1959
+ }
1960
+ }
1961
+ function isEngineHostedHelper(spec) {
1962
+ return spec.kind === "grid" || spec.kind === "crop" || spec.kind === "terminal";
1963
+ }
1964
+ //#endregion
1965
+ //#region ../types/dist/esm/composition/composed-stable-id.mjs
1966
+ /**
1967
+ * A composed device's stableId is this prefix plus the block id. Its own module,
1968
+ * free of zod, so the addon runner can read it through `@camstack/types/addon`
1969
+ * without loading the schema barrel (D28).
1970
+ */
1971
+ var COMPOSED_DEVICE_STABLE_ID_PREFIX = "composed-";
1972
+ //#endregion
1973
+ //#region ../types/dist/esm/composition/composition.mjs
1974
+ /**
1975
+ * A COMPOSITION: a device assembled from other devices' state (D659).
1976
+ *
1977
+ * The data half of the composed-devices spec §1. A composition is stored inside
1978
+ * a core block (`CoreBlock.source.kind === 'composition'`) and run by the shared
1979
+ * `composer` runner. It names a TARGET and, for each capability of the target, a
1980
+ * FIELD MAP: every state field has exactly one source.
1981
+ *
1982
+ * Sources are keyed by `(addonId, stableId)`, NEVER by numeric device id. A
1983
+ * resync reissues numeric ids, and a composition that stored them would be
1984
+ * orphaned by the first re-adoption (the linked-devices lesson). A `stableId` is
1985
+ * unique only within its owning addon, so the owner travels with it.
1986
+ *
1987
+ * Later slices EXTEND these unions and do not reshape them. The variants a later
1988
+ * slice implements are already in the wire shape, and `validateComposition`
1989
+ * refuses them BY NAME until then:
1990
+ * feature `passthrough` → slice 3 · `commands` (`forward`) → slice 3 ·
1991
+ * source `code` → slice 4. Target `existing` (customize a device) is slice 2 (D663).
1992
+ */
1993
+ /** The owner of every composed device: the `composer` builtin. */
1994
+ var COMPOSER_ADDON_ID = "composer";
1995
+ /** Longest snippet a `code` source may carry (slice 4). */
1996
+ var MAX_COMPOSITION_CODE_LENGTH = 2e4;
1997
+ /** One field of one capability of one source device. */
1998
+ var CompositionFieldReadSchema = /* @__PURE__ */ z.object({
1999
+ source: CompositionSourceRefSchema,
2000
+ cap: /* @__PURE__ */ z.string().min(1),
2001
+ /** Dotted path into the source cap's runtime-state slice. */
2002
+ fieldPath: /* @__PURE__ */ z.string().min(1)
2003
+ });
2004
+ /** `from`: copy one source field verbatim. It is also an expression's `from` binding. */
2005
+ var CompositionFromSourceSchema = /* @__PURE__ */ CompositionFieldReadSchema.extend({ kind: /* @__PURE__ */ z.literal("from") });
2006
+ /** A constant binding. No device is read. */
2007
+ var CompositionLiteralBindingSchema = /* @__PURE__ */ z.object({
2008
+ kind: /* @__PURE__ */ z.literal("literal"),
2009
+ value: /* @__PURE__ */ z.union([
2010
+ /* @__PURE__ */ z.string(),
2011
+ /* @__PURE__ */ z.number(),
2012
+ /* @__PURE__ */ z.boolean(),
2013
+ /* @__PURE__ */ z.null()
2014
+ ])
2015
+ });
2016
+ var CompositionBindingSchema = /* @__PURE__ */ z.discriminatedUnion("kind", [CompositionFromSourceSchema, CompositionLiteralBindingSchema]);
2017
+ /**
2018
+ * `expression`: a formula over named bindings, in the salvaged expression
2019
+ * engine. Validated at parse by the SAME function every other consumer runs,
2020
+ * so the editor and the store cannot disagree.
2021
+ */
2022
+ var CompositionExpressionSourceSchema = /* @__PURE__ */ z.object({
2023
+ kind: /* @__PURE__ */ z.literal("expression"),
2024
+ expr: /* @__PURE__ */ z.string().min(1).max(MAX_EXPRESSION_SOURCE_LENGTH),
2025
+ bindings: /* @__PURE__ */ z.record(/* @__PURE__ */ z.string().regex(EXPRESSION_IDENTIFIER_RE), CompositionBindingSchema)
2026
+ }).superRefine((src, ctx) => {
2027
+ const err = validateExpressionSource(src);
2028
+ if (err !== null) ctx.addIssue({
2029
+ code: "custom",
2030
+ message: err,
2031
+ path: ["expr"]
2032
+ });
2033
+ });
2034
+ /** `code`: RESERVED for slice 4 (own runner, one-way eject). */
2035
+ var CompositionCodeSourceSchema = /* @__PURE__ */ z.object({
2036
+ kind: /* @__PURE__ */ z.literal("code"),
2037
+ code: /* @__PURE__ */ z.string().min(1).max(MAX_COMPOSITION_CODE_LENGTH)
2038
+ });
2039
+ /**
2040
+ * `aggregate`: a group reducer. Offline and unknown reads are excluded, not
2041
+ * folded in as 0 or false (D944). Free expressions stay `expression` so a
2042
+ * stale member is still included there.
2043
+ */
2044
+ var CompositionAggregateSourceSchema = /* @__PURE__ */ z.object({
2045
+ kind: /* @__PURE__ */ z.literal("aggregate"),
2046
+ reducer: /* @__PURE__ */ z.enum([
2047
+ "mean",
2048
+ "median",
2049
+ "min",
2050
+ "max",
2051
+ "sum",
2052
+ "any",
2053
+ "all"
2054
+ ]),
2055
+ reads: /* @__PURE__ */ z.array(CompositionFieldReadSchema).min(1).max(64),
2056
+ /**
2057
+ * Set when the reads are an enum state, not a yes/no: the listed states
2058
+ * count as active (a cover is `open`). A state outside the list is inactive;
2059
+ * a read that is not a state at all is left out. Only `any` / `all` use it.
2060
+ */
2061
+ activeWhen: /* @__PURE__ */ z.array(/* @__PURE__ */ z.string().min(1)).min(1).optional(),
2062
+ /** `value` is the reading; the others are the member counts. */
2063
+ publish: /* @__PURE__ */ z.enum([
2064
+ "value",
2065
+ "included",
2066
+ "excluded",
2067
+ "total"
2068
+ ]),
2069
+ /** What a `value` publish does when nobody is included. Counts ignore this. */
2070
+ empty: /* @__PURE__ */ z.enum([
2071
+ "null",
2072
+ "omit",
2073
+ "offline"
2074
+ ])
2075
+ });
2076
+ /**
2077
+ * `series`: a statistics or integral field. The composer writes it from a
2078
+ * history query. The live pass does not recompute it (D944).
2079
+ */
2080
+ var CompositionSeriesSourceSchema = /* @__PURE__ */ z.object({
2081
+ kind: /* @__PURE__ */ z.literal("series"),
2082
+ read: CompositionFieldReadSchema,
2083
+ /** `value` is the statistic or the integral. The others are the gap counts. */
2084
+ publish: /* @__PURE__ */ z.enum([
2085
+ "value",
2086
+ "included",
2087
+ "excluded",
2088
+ "total"
2089
+ ]),
2090
+ /**
2091
+ * What an unanswered `value` does. Counts ignore this. `offline` leaves the
2092
+ * device unseeded until history answers, so a restart cannot publish 0.
2093
+ */
2094
+ empty: /* @__PURE__ */ z.enum([
2095
+ "null",
2096
+ "omit",
2097
+ "offline"
2098
+ ])
2099
+ });
2100
+ var CompositionFieldSourceSchema = /* @__PURE__ */ z.discriminatedUnion("kind", [
2101
+ CompositionFromSourceSchema,
2102
+ CompositionExpressionSourceSchema,
2103
+ CompositionCodeSourceSchema,
2104
+ CompositionAggregateSourceSchema,
2105
+ CompositionSeriesSourceSchema
2106
+ ]);
2107
+ var forwardArgUnion = /* @__PURE__ */ z.union([
2108
+ /* @__PURE__ */ z.string(),
2109
+ /* @__PURE__ */ z.number(),
2110
+ /* @__PURE__ */ z.boolean(),
2111
+ /* @__PURE__ */ z.strictObject({ ["$input"]: /* @__PURE__ */ z.string().min(1) }),
2112
+ /* @__PURE__ */ z.record(/* @__PURE__ */ z.string().min(1), /* @__PURE__ */ z.lazy(() => forwardArgUnion))
2113
+ ]);
2114
+ var CompositionForwardArgSchema = forwardArgUnion;
2115
+ /** True for `{ $input: '<field>' }`. */
2116
+ function isForwardInputRef(value) {
2117
+ return typeof value === "object" && typeof value.$input === "string";
2118
+ }
2119
+ /**
2120
+ * `forward` (D659, amended by D967): one method of a BUILT capability is one
2121
+ * call of `cap.method` on `source`. Without `args` the built method's input
2122
+ * passes through minus `deviceId`; with `args` the template IS the source's
2123
+ * whole input. `deviceId` is always the source's own, never an argument.
2124
+ */
2125
+ var CompositionForwardCommandSchema = /* @__PURE__ */ z.object({
2126
+ kind: /* @__PURE__ */ z.literal("forward"),
2127
+ source: CompositionSourceRefSchema,
2128
+ cap: /* @__PURE__ */ z.string().min(1),
2129
+ method: /* @__PURE__ */ z.string().min(1),
2130
+ args: /* @__PURE__ */ z.record(/* @__PURE__ */ z.string().min(1), CompositionForwardArgSchema).optional()
2131
+ });
2132
+ /**
2133
+ * `extension` (D967 amendment): a method of a BUILT `media-player` is served by
2134
+ * the device's `remote` extension (D963/D964). No source is named — the remote
2135
+ * is the device's own. The dispatch redirect runs the bound role; a method whose
2136
+ * role is not bound answers a typed `media-player.unsupported`.
2137
+ */
2138
+ var CompositionExtensionCommandSchema = /* @__PURE__ */ z.object({
2139
+ kind: /* @__PURE__ */ z.literal("extension"),
2140
+ target: /* @__PURE__ */ z.literal("remote")
2141
+ });
2142
+ var CompositionCommandTargetSchema = /* @__PURE__ */ z.discriminatedUnion("kind", [
2143
+ CompositionForwardCommandSchema,
2144
+ CompositionCodeSourceSchema,
2145
+ CompositionExtensionCommandSchema
2146
+ ]);
2147
+ /** An item key inside an item-array cap (`consumables.items[<key>]`). */
2148
+ var COMPOSITION_ITEM_KEY_RE = /^[a-z0-9][a-z0-9-]{0,47}$/;
2149
+ /** The item-array path of every item-array cap that exists (`consumables.items`). */
2150
+ var COMPOSITION_ITEM_ARRAY_PATH = "items";
2151
+ /**
2152
+ * One item of an item-array cap (D663), addressed through the cap's
2153
+ * `status.itemArray` descriptor. `fields` are paths INSIDE the item, nested
2154
+ * allowed (`remaining.value`); the key and label come from the entry itself.
2155
+ */
2156
+ var CompositionItemEntrySchema = /* @__PURE__ */ z.object({
2157
+ label: /* @__PURE__ */ z.string().min(1).max(80),
2158
+ fields: /* @__PURE__ */ z.record(/* @__PURE__ */ z.string().min(1), CompositionFieldSourceSchema),
2159
+ /**
2160
+ * What the cap's `reset` does for THIS item (consumables). Present = the item
2161
+ * is resettable and a `reset` call naming its key forwards here. The item key
2162
+ * selects the command, so it is never an argument: there is no pass-through.
2163
+ */
2164
+ reset: /* @__PURE__ */ CompositionForwardCommandSchema.optional()
2165
+ });
2166
+ /** Which identity link added a feature (D1063). */
2167
+ var CompositionContributedBySchema = /* @__PURE__ */ z.object({ linkId: /* @__PURE__ */ z.string().min(1) });
2168
+ var CompositionFieldsFeatureSchema = /* @__PURE__ */ z.object({
2169
+ kind: /* @__PURE__ */ z.literal("fields"),
2170
+ cap: /* @__PURE__ */ z.string().min(1),
2171
+ enabled: /* @__PURE__ */ z.boolean().optional(),
2172
+ fields: /* @__PURE__ */ z.record(/* @__PURE__ */ z.string().min(1), CompositionFieldSourceSchema).refine((fields) => Object.keys(fields).length <= 32, { message: `at most 32 fields per capability` }),
2173
+ /**
2174
+ * Items of the cap's item array, keyed by item key (D663). Naming `items`
2175
+ * owns the WHOLE array field: the composed value holds exactly these items.
2176
+ */
2177
+ items: /* @__PURE__ */ z.record(/* @__PURE__ */ z.string().regex(COMPOSITION_ITEM_KEY_RE), CompositionItemEntrySchema).refine((items) => Object.keys(items).length <= 16, { message: `at most 16 items` }).optional(),
2178
+ /** Method name → what serves it. Only a BUILT capability takes commands (D967). */
2179
+ commands: /* @__PURE__ */ z.record(/* @__PURE__ */ z.string().min(1), CompositionCommandTargetSchema).optional(),
2180
+ /**
2181
+ * Provenance only (D1063): the identity link that added this feature. The
2182
+ * source ref stays in `fields`; `enabled` stays the operator's switch. An
2183
+ * operator edit of the source drops the stamp and the feature becomes the
2184
+ * operator's; a lost link removes only stamped features.
2185
+ */
2186
+ contributedBy: /* @__PURE__ */ CompositionContributedBySchema.optional()
2187
+ });
2188
+ /** RESERVED for slice 3: a media / data-plane cap, whole, from one source. */
2189
+ var CompositionPassthroughFeatureSchema = /* @__PURE__ */ z.object({
2190
+ kind: /* @__PURE__ */ z.literal("passthrough"),
2191
+ cap: /* @__PURE__ */ z.string().min(1),
2192
+ enabled: /* @__PURE__ */ z.boolean().optional(),
2193
+ source: CompositionSourceRefSchema
2194
+ });
2195
+ var CompositionFeatureSchema = /* @__PURE__ */ z.discriminatedUnion("kind", [CompositionFieldsFeatureSchema, CompositionPassthroughFeatureSchema]);
2196
+ /** Only an explicit `false` disables a feature; omitted preserves the existing wire default. */
2197
+ function compositionFeatureEnabled(feature) {
2198
+ return feature.enabled !== false;
2199
+ }
2200
+ /**
2201
+ * A NEW device. It has no `name` of its own: the block's name IS the device's
2202
+ * name (2026-08-08). A second copy here would be a second writer of one string (D62).
2203
+ */
2204
+ var CompositionNewTargetSchema = /* @__PURE__ */ z.object({
2205
+ kind: /* @__PURE__ */ z.literal("new"),
2206
+ type: /* @__PURE__ */ z.enum(DeviceType),
2207
+ role: /* @__PURE__ */ z.enum(DeviceRole).optional()
2208
+ });
2209
+ /**
2210
+ * A STORED block, read back: the `new` target of its composition may name a
2211
+ * device type D1033 retired (`thermostat`). {@link CompositionNewTargetSchema}
2212
+ * stays a strict enum on the wire, so the store rewrites the retired name to
2213
+ * its canonical type (`source.composition.target.type`) before it parses the
2214
+ * row. Anything else is returned untouched, for the schema to judge.
2215
+ */
2216
+ function canonicalStoredBlockTarget(block) {
2217
+ if (!isPlainObject(block)) return block;
2218
+ const source = Reflect.get(block, "source");
2219
+ if (!isPlainObject(source)) return block;
2220
+ const composition = Reflect.get(source, "composition");
2221
+ if (!isPlainObject(composition)) return block;
2222
+ const target = Reflect.get(composition, "target");
2223
+ if (!isPlainObject(target)) return block;
2224
+ const type = Reflect.get(target, "type");
2225
+ if (typeof type !== "string") return block;
2226
+ const canonical = {
2227
+ ...target,
2228
+ type: canonicalStoredDeviceType(type)
2229
+ };
2230
+ return {
2231
+ ...block,
2232
+ source: {
2233
+ ...source,
2234
+ composition: {
2235
+ ...composition,
2236
+ target: canonical
2237
+ }
2238
+ }
2239
+ };
2240
+ }
2241
+ function isPlainObject(value) {
2242
+ return value !== null && typeof value === "object" && !Array.isArray(value);
2243
+ }
2244
+ /** Customize an EXISTING device: each feature adds a capability or replaces fields of a native one (D663). */
2245
+ var CompositionExistingTargetSchema = /* @__PURE__ */ z.object({
2246
+ kind: /* @__PURE__ */ z.literal("existing"),
2247
+ device: CompositionSourceRefSchema
2248
+ });
2249
+ var CompositionTargetSchema = /* @__PURE__ */ z.discriminatedUnion("kind", [CompositionNewTargetSchema, CompositionExistingTargetSchema]);
2250
+ var CompositionSchema = /* @__PURE__ */ z.object({
2251
+ target: CompositionTargetSchema,
2252
+ features: /* @__PURE__ */ z.array(CompositionFeatureSchema).min(0).max(16),
2253
+ /**
2254
+ * Present when the block is a helper template. Absent on a free
2255
+ * composition (the room example, device 4603). The editor reads this,
2256
+ * never the compiled features.
2257
+ */
2258
+ helper: /* @__PURE__ */ HelperSpecSchema.optional()
2259
+ }).superRefine((composition, ctx) => {
2260
+ const seen = /* @__PURE__ */ new Set();
2261
+ composition.features.forEach((feature, index) => {
2262
+ if (seen.has(feature.cap)) ctx.addIssue({
2263
+ code: "custom",
2264
+ message: `capability \`${feature.cap}\` is composed twice — one feature per capability`,
2265
+ path: [
2266
+ "features",
2267
+ index,
2268
+ "cap"
2269
+ ]
2270
+ });
2271
+ seen.add(feature.cap);
2272
+ });
2273
+ });
2274
+ function compositionSourceKey(ref) {
2275
+ return `${ref.addonId}/${ref.stableId}`;
2276
+ }
2277
+ function compositionSliceKey(ref, cap) {
2278
+ return `${compositionSourceKey(ref)}#${cap}`;
2279
+ }
2280
+ function compositionReadKey(read) {
2281
+ return `${compositionSliceKey(read.source, read.cap)}.${read.fieldPath}`;
2282
+ }
2283
+ function composedDeviceStableId(blockId) {
2284
+ return `${COMPOSED_DEVICE_STABLE_ID_PREFIX}${blockId}`;
2285
+ }
2286
+ function composedDeviceRef(blockId) {
2287
+ return {
2288
+ addonId: COMPOSER_ADDON_ID,
2289
+ stableId: composedDeviceStableId(blockId)
2290
+ };
2291
+ }
2292
+ /** Every device field a source reads: `from` is one read, an expression is its `from` bindings. */
2293
+ function fieldReads(source) {
2294
+ switch (source.kind) {
2295
+ case "from": return [{
2296
+ source: source.source,
2297
+ cap: source.cap,
2298
+ fieldPath: source.fieldPath
2299
+ }];
2300
+ case "expression": return Object.values(source.bindings).flatMap((binding) => binding.kind === "from" ? [{
2301
+ source: binding.source,
2302
+ cap: binding.cap,
2303
+ fieldPath: binding.fieldPath
2304
+ }] : []);
2305
+ case "aggregate": return source.reads;
2306
+ case "series": return [source.read];
2307
+ case "code": return [];
2308
+ }
2309
+ }
2310
+ /** The ONE spelling of an item leaf as a field path: `items[desiccant].remaining.value`. */
2311
+ function compositionItemFieldPath(arrayPath, key, path) {
2312
+ return `${arrayPath}[${key}].${path}`;
2313
+ }
2314
+ /**
2315
+ * Every written field of a feature, item leaves under their bracketed path.
2316
+ * `arrayPath` is `'items'` for every item-array cap that exists
2317
+ * (`consumables.cap.ts`); the graph has no cap lookup, so the default stands
2318
+ * and `planItems` asserts it agrees with the cap's descriptor.
2319
+ */
2320
+ function featureFieldEntries(feature, arrayPath = COMPOSITION_ITEM_ARRAY_PATH) {
2321
+ return [...Object.entries(feature.fields).map(([fieldPath, source]) => ({
2322
+ fieldPath,
2323
+ source
2324
+ })), ...Object.entries(feature.items ?? {}).flatMap(([key, item]) => Object.entries(item.fields).map(([path, source]) => ({
2325
+ fieldPath: compositionItemFieldPath(arrayPath, key, path),
2326
+ source
2327
+ })))];
2328
+ }
2329
+ function featureSources(feature) {
2330
+ return featureFieldEntries(feature).map((e) => e.source);
2331
+ }
2332
+ //#endregion
2333
+ //#region ../types/dist/esm/composition/plan-result.mjs
2334
+ function problem(code, path, message) {
2335
+ return {
2336
+ code,
2337
+ path,
2338
+ message
2339
+ };
2340
+ }
2341
+ function refused(...problems) {
2342
+ return {
2343
+ problems,
2344
+ fields: [],
2345
+ features: [],
2346
+ events: []
2347
+ };
2348
+ }
2349
+ /** Where a planned field sits in the composition: `features[N].fields.<path>` or `features[N].items.<key>.fields.<path>`. */
2350
+ function compositionFieldAt(field) {
2351
+ const inner = field.item === void 0 ? "fields" : `items.${field.item.key}.fields`;
2352
+ return `features[${field.featureIndex}].${inner}.${field.path}`;
2353
+ }
2354
+ //#endregion
2355
+ //#region ../types/dist/esm/composition/helpers/catalog.mjs
2356
+ /**
2357
+ * One catalog row per base reading a group helper can build (D944 §3).
2358
+ * Data, not a form default written into the block.
2359
+ */
2360
+ var NOW$2 = {
2361
+ fieldPath: "lastFetchedAt",
2362
+ expr: "now"
2363
+ };
2364
+ var CHANGED = {
2365
+ fieldPath: "lastChangedAt",
2366
+ expr: "now"
2367
+ };
2368
+ function numeric(input) {
2369
+ const { alsoFrom, ...base } = input;
2370
+ return {
2371
+ ...base,
2372
+ family: "numeric",
2373
+ deviceType: DeviceType.Sensor,
2374
+ memberDeviceType: DeviceType.Sensor,
2375
+ memberDeviceTypes: [DeviceType.Sensor, ...alsoFrom?.deviceTypes ?? []],
2376
+ activeWhen: void 0,
2377
+ commandCaps: [],
2378
+ baseUnit: baseUnitOf(input.quantity),
2379
+ aggregates: NUMERIC_AGGREGATES,
2380
+ accept: [{
2381
+ cap: input.outputCap,
2382
+ fieldPath: input.outputField
2383
+ }, ...alsoFrom === void 0 ? [] : [alsoFrom.accept]]
2384
+ };
2385
+ }
2386
+ var CLIMATE_DEVICES = [DeviceType.Climate];
2387
+ function binary(input) {
2388
+ return {
2389
+ ...input,
2390
+ family: "binary",
2391
+ deviceType: DeviceType.Sensor,
2392
+ memberDeviceType: DeviceType.Sensor,
2393
+ memberDeviceTypes: [DeviceType.Sensor],
2394
+ activeWhen: void 0,
2395
+ commandCaps: [],
2396
+ quantity: "none",
2397
+ baseUnit: void 0,
2398
+ aggregates: BINARY_AGGREGATES,
2399
+ empty: "offline"
2400
+ };
2401
+ }
2402
+ var GROUP_TEMPLATES = [
2403
+ /* @__PURE__ */ numeric({
2404
+ id: "temperature",
2405
+ summary: "Mean, median, min, max or sum of temperatures. Offline and unknown members are left out, never read as 0 °C.",
2406
+ role: DeviceRole.TemperatureSensor,
2407
+ outputCap: "temperature-sensor",
2408
+ outputField: "temperature",
2409
+ quantity: "temperature",
2410
+ defaultAggregate: "mean",
2411
+ empty: "null",
2412
+ companions: [NOW$2],
2413
+ alsoFrom: {
2414
+ deviceTypes: CLIMATE_DEVICES,
2415
+ accept: {
2416
+ cap: "climate-control",
2417
+ fieldPath: "currentTemp"
2418
+ }
2419
+ }
2420
+ }),
2421
+ /* @__PURE__ */ numeric({
2422
+ id: "humidity",
2423
+ summary: "Humidity in percent. Offline and unknown members are left out, never read as 0 %.",
2424
+ role: DeviceRole.HumiditySensor,
2425
+ outputCap: "humidity-sensor",
2426
+ outputField: "humidity",
2427
+ quantity: "humidity",
2428
+ defaultAggregate: "mean",
2429
+ empty: "null",
2430
+ companions: [NOW$2],
2431
+ alsoFrom: {
2432
+ deviceTypes: CLIMATE_DEVICES,
2433
+ accept: {
2434
+ cap: "climate-control",
2435
+ fieldPath: "currentHumidity"
2436
+ }
2437
+ }
2438
+ }),
2439
+ /* @__PURE__ */ numeric({
2440
+ id: "pressure",
2441
+ summary: "Pressure in hectopascals. Offline and unknown members are left out, never read as 0 hPa.",
2442
+ role: DeviceRole.PressureSensor,
2443
+ outputCap: "pressure-sensor",
2444
+ outputField: "pressure",
2445
+ quantity: "pressure",
2446
+ defaultAggregate: "mean",
2447
+ empty: "null",
2448
+ companions: [NOW$2]
2449
+ }),
2450
+ /* @__PURE__ */ numeric({
2451
+ id: "illuminance",
2452
+ summary: "Illuminance in lux. Offline and unknown members are left out, never read as 0 lx.",
2453
+ role: DeviceRole.AmbientLightSensor,
2454
+ outputCap: "ambient-light-sensor",
2455
+ outputField: "illuminance",
2456
+ quantity: "illuminance",
2457
+ defaultAggregate: "mean",
2458
+ empty: "null",
2459
+ companions: [NOW$2]
2460
+ }),
2461
+ /* @__PURE__ */ numeric({
2462
+ id: "power",
2463
+ summary: "Power in watts, summed by default. Nobody reporting omits the key rather than writing 0 W.",
2464
+ role: DeviceRole.PowerSensor,
2465
+ outputCap: "power-meter",
2466
+ outputField: "power",
2467
+ quantity: "power",
2468
+ defaultAggregate: "sum",
2469
+ empty: "omit",
2470
+ companions: [NOW$2]
2471
+ }),
2472
+ /* @__PURE__ */ numeric({
2473
+ id: "energy",
2474
+ summary: "Energy in kilowatt-hours, summed by default. Nobody reporting omits the key rather than writing 0 kWh.",
2475
+ role: DeviceRole.EnergySensor,
2476
+ outputCap: "power-meter",
2477
+ outputField: "energy",
2478
+ quantity: "energy",
2479
+ defaultAggregate: "sum",
2480
+ empty: "omit",
2481
+ companions: [NOW$2]
2482
+ }),
2483
+ /* @__PURE__ */ numeric({
2484
+ id: "battery",
2485
+ summary: "Battery charge in percent. Offline and unknown members are left out, never read as 0 %.",
2486
+ role: DeviceRole.BatterySensor,
2487
+ outputCap: "battery",
2488
+ outputField: "level",
2489
+ quantity: "percentage",
2490
+ defaultAggregate: "mean",
2491
+ empty: "null",
2492
+ companions: [
2493
+ {
2494
+ fieldPath: "charging",
2495
+ expr: "\"unknown\""
2496
+ },
2497
+ {
2498
+ fieldPath: "sleeping",
2499
+ expr: "false"
2500
+ },
2501
+ {
2502
+ fieldPath: "lastUpdated",
2503
+ expr: "now"
2504
+ }
2505
+ ]
2506
+ }),
2507
+ /* @__PURE__ */ numeric({
2508
+ id: "numeric",
2509
+ summary: "A numeric reading in the members’ shared quantity. Mixed quantities are refused. Nobody reporting publishes null, not 0.",
2510
+ role: DeviceRole.NumericSensor,
2511
+ outputCap: "numeric-sensor",
2512
+ outputField: "value",
2513
+ quantity: "device",
2514
+ defaultAggregate: "mean",
2515
+ empty: "null",
2516
+ companions: [NOW$2]
2517
+ }),
2518
+ /* @__PURE__ */ binary({
2519
+ id: "motion",
2520
+ summary: "Any or all motion. Offline and unknown members are left out, never read as off. Nobody reporting takes the device offline.",
2521
+ role: DeviceRole.MotionSensor,
2522
+ outputCap: "motion",
2523
+ outputField: "detected",
2524
+ defaultAggregate: "any",
2525
+ accept: [{
2526
+ cap: "motion",
2527
+ fieldPath: "detected"
2528
+ }],
2529
+ companions: [{
2530
+ fieldPath: "lastDetectedAt",
2531
+ expr: "null"
2532
+ }, {
2533
+ fieldPath: "autoClearAfterMs",
2534
+ expr: "null"
2535
+ }]
2536
+ }),
2537
+ /* @__PURE__ */ binary({
2538
+ id: "contact",
2539
+ summary: "Any or all open contacts. Offline and unknown members are left out, never read as closed.",
2540
+ role: DeviceRole.ContactSensor,
2541
+ outputCap: "contact",
2542
+ outputField: "entryOpen",
2543
+ defaultAggregate: "any",
2544
+ accept: [{
2545
+ cap: "contact",
2546
+ fieldPath: "entryOpen"
2547
+ }],
2548
+ companions: [CHANGED]
2549
+ }),
2550
+ /* @__PURE__ */ binary({
2551
+ id: "leak",
2552
+ summary: "Any or all leak detections. Offline and unknown members are left out, never read as dry.",
2553
+ role: DeviceRole.LeakSensor,
2554
+ outputCap: "flood",
2555
+ outputField: "flooded",
2556
+ defaultAggregate: "any",
2557
+ accept: [{
2558
+ cap: "flood",
2559
+ fieldPath: "flooded"
2560
+ }],
2561
+ companions: [CHANGED]
2562
+ }),
2563
+ /* @__PURE__ */ binary({
2564
+ id: "smoke",
2565
+ summary: "Any or all smoke detections. Offline and unknown members are left out, never read as clear.",
2566
+ role: DeviceRole.SmokeSensor,
2567
+ outputCap: "smoke",
2568
+ outputField: "detected",
2569
+ defaultAggregate: "any",
2570
+ accept: [{
2571
+ cap: "smoke",
2572
+ fieldPath: "detected"
2573
+ }],
2574
+ companions: [CHANGED]
2575
+ }),
2576
+ /* @__PURE__ */ binary({
2577
+ id: "occupancy",
2578
+ summary: "Any or all of motion or binary sensors, published as a binary. Presence zones are not aggregated. Nobody reporting is offline, not off.",
2579
+ role: DeviceRole.BinarySensor,
2580
+ outputCap: "binary",
2581
+ outputField: "on",
2582
+ defaultAggregate: "any",
2583
+ accept: [{
2584
+ cap: "motion",
2585
+ fieldPath: "detected"
2586
+ }, {
2587
+ cap: "binary",
2588
+ fieldPath: "on"
2589
+ }],
2590
+ companions: [CHANGED]
2591
+ }),
2592
+ /* @__PURE__ */ binary({
2593
+ id: "binary",
2594
+ summary: "Any or all generic binary sensors. Offline and unknown members are left out, never read as off.",
2595
+ role: DeviceRole.BinarySensor,
2596
+ outputCap: "binary",
2597
+ outputField: "on",
2598
+ defaultAggregate: "any",
2599
+ accept: [{
2600
+ cap: "binary",
2601
+ fieldPath: "on"
2602
+ }],
2603
+ companions: [CHANGED]
2604
+ }),
2605
+ /* @__PURE__ */ actuator({
2606
+ id: "switch",
2607
+ summary: "On when at least one switch is on, or when all of them are. Offline and unknown members are left out of that decision, never read as off, and still receive the command.",
2608
+ deviceType: DeviceType.Switch,
2609
+ outputCap: "switch",
2610
+ outputField: "on",
2611
+ member: {
2612
+ cap: "switch",
2613
+ fieldPath: "on"
2614
+ },
2615
+ commandCaps: ["switch"]
2616
+ }),
2617
+ /* @__PURE__ */ actuator({
2618
+ id: "light",
2619
+ summary: "On when at least one light is on, or when all of them are. Brightness and colour are offered only when every member has them. A command is not sent to a member that lacks it.",
2620
+ deviceType: DeviceType.Light,
2621
+ outputCap: "switch",
2622
+ outputField: "on",
2623
+ member: {
2624
+ cap: "switch",
2625
+ fieldPath: "on"
2626
+ },
2627
+ commandCaps: [
2628
+ "switch",
2629
+ "brightness",
2630
+ "color"
2631
+ ]
2632
+ }),
2633
+ /* @__PURE__ */ actuator({
2634
+ id: "fan",
2635
+ summary: "On when at least one fan is on, or when all of them are. Speed, preset, direction and oscillation are offered only when every fan has them. A command is not sent to a fan that lacks it.",
2636
+ deviceType: DeviceType.Fan,
2637
+ outputCap: "switch",
2638
+ outputField: "on",
2639
+ member: {
2640
+ cap: "switch",
2641
+ fieldPath: "on"
2642
+ },
2643
+ commandCaps: ["switch", "fan-control"]
2644
+ }),
2645
+ /* @__PURE__ */ actuator({
2646
+ id: "cover",
2647
+ summary: "Open when at least one cover is open or part-open, or only when all of them are. Position and tilt are offered only when every cover has them. A cover that reports nothing is left out, never read as closed.",
2648
+ deviceType: DeviceType.Cover,
2649
+ outputCap: "group-active",
2650
+ outputField: "active",
2651
+ member: {
2652
+ cap: "cover",
2653
+ fieldPath: "state"
2654
+ },
2655
+ activeWhen: [
2656
+ "open",
2657
+ "opening",
2658
+ "stopped"
2659
+ ],
2660
+ commandCaps: ["cover"]
2661
+ }),
2662
+ /* @__PURE__ */ actuator({
2663
+ id: "valve",
2664
+ summary: "Open when at least one valve is open or part-open, or only when all of them are. Position is offered only when every valve has it. A valve that reports nothing is left out, never read as closed.",
2665
+ deviceType: DeviceType.Valve,
2666
+ outputCap: "group-active",
2667
+ outputField: "active",
2668
+ member: {
2669
+ cap: "valve",
2670
+ fieldPath: "state"
2671
+ },
2672
+ activeWhen: [
2673
+ "open",
2674
+ "opening",
2675
+ "stopped"
2676
+ ],
2677
+ commandCaps: ["valve"]
2678
+ }),
2679
+ /* @__PURE__ */ actuator({
2680
+ id: "lock",
2681
+ summary: "Locked when at least one lock is locked, or only when all of them are. A jammed or moving lock is not locked. Locking is one tap; unlocking the group needs a confirmation every time, and nothing is sent without it.",
2682
+ deviceType: DeviceType.Lock,
2683
+ outputCap: "group-active",
2684
+ outputField: "active",
2685
+ member: {
2686
+ cap: "lock-control",
2687
+ fieldPath: "state"
2688
+ },
2689
+ activeWhen: ["locked"],
2690
+ commandCaps: ["lock-control"]
2691
+ }),
2692
+ /* @__PURE__ */ actuator({
2693
+ id: "media-player",
2694
+ summary: "Playing when at least one player is playing, or only when all of them are. Volume is offered only when every player has it. A player that reports nothing is left out, never read as stopped.",
2695
+ deviceType: DeviceType.MediaPlayer,
2696
+ outputCap: "group-active",
2697
+ outputField: "active",
2698
+ member: {
2699
+ cap: "media-player",
2700
+ fieldPath: "state"
2701
+ },
2702
+ activeWhen: ["playing", "buffering"],
2703
+ commandCaps: ["media-player"]
2704
+ }),
2705
+ /* @__PURE__ */ actuator({
2706
+ id: "climate",
2707
+ summary: "Running when at least one thermostat or air conditioner is not off, or only when all of them are. Target temperature and fan are offered only when every device has them. A device that reports nothing is left out, never read as off.",
2708
+ deviceType: DeviceType.Climate,
2709
+ memberDeviceTypes: [DeviceType.Climate],
2710
+ outputCap: "group-active",
2711
+ outputField: "active",
2712
+ member: {
2713
+ cap: "climate-control",
2714
+ fieldPath: "mode"
2715
+ },
2716
+ activeWhen: [
2717
+ "heat",
2718
+ "cool",
2719
+ "auto",
2720
+ "heat_cool",
2721
+ "fan_only",
2722
+ "dry"
2723
+ ],
2724
+ commandCaps: ["climate-control"]
2725
+ })
2726
+ ];
2727
+ function actuator(input) {
2728
+ return {
2729
+ id: input.id,
2730
+ summary: input.summary,
2731
+ deviceType: input.deviceType,
2732
+ outputCap: input.outputCap,
2733
+ outputField: input.outputField,
2734
+ commandCaps: input.commandCaps,
2735
+ family: "actuator",
2736
+ role: void 0,
2737
+ memberDeviceType: input.deviceType,
2738
+ memberDeviceTypes: input.memberDeviceTypes ?? [input.deviceType],
2739
+ activeWhen: input.activeWhen,
2740
+ quantity: "none",
2741
+ baseUnit: void 0,
2742
+ aggregates: BINARY_AGGREGATES,
2743
+ defaultAggregate: "any",
2744
+ empty: "offline",
2745
+ accept: [input.member],
2746
+ companions: [CHANGED]
2747
+ };
2748
+ }
2749
+ var BY_ID = /* @__PURE__ */ new Map(/* @__PURE__ */ GROUP_TEMPLATES.map((template) => [template.id, template]));
2750
+ function groupTemplate(id) {
2751
+ return BY_ID.get(id) ?? null;
2752
+ }
2753
+ //#endregion
2754
+ //#region ../types/dist/esm/composition/helpers/actuator.mjs
2755
+ var COLOR_MODE_FEATURES = [
2756
+ DeviceFeature.LightColorRgb,
2757
+ DeviceFeature.LightColorHsv,
2758
+ DeviceFeature.LightColorMired
2759
+ ];
2760
+ /** `at-least-one` is any included member on; `all` is every included member on. */
2761
+ function reducerForActive(active) {
2762
+ return active === "all" ? "all" : "any";
2763
+ }
2764
+ /**
2765
+ * Colour modes every member advertises. Offline does not remove a mode:
2766
+ * the caller passes device features, not liveness. No members → no mode.
2767
+ */
2768
+ function sharedColorModes(memberFeatures) {
2769
+ if (memberFeatures.length === 0) return [];
2770
+ return COLOR_MODE_FEATURES.filter((mode) => memberFeatures.every((features) => features.includes(mode)));
2771
+ }
2772
+ /**
2773
+ * One call per member that binds `cap`. Offline members stay in the list.
2774
+ * A member without the cap is not called — the command cannot reach it.
2775
+ */
2776
+ function fanOutTargets(members, cap, method, args) {
2777
+ return members.flatMap((member) => member.caps.includes(cap) ? [{
2778
+ deviceId: member.deviceId,
2779
+ cap,
2780
+ method,
2781
+ args: { ...args }
2782
+ }] : []);
2783
+ }
2784
+ /**
2785
+ * Run every call. A throw is that member's result; the other calls still run.
2786
+ * At most {@link FAN_OUT_CONCURRENCY} are in flight.
2787
+ */
2788
+ async function runFanOut(calls, invoke) {
2789
+ const results = [];
2790
+ let next = 0;
2791
+ const worker = async () => {
2792
+ for (;;) {
2793
+ const index = next;
2794
+ next += 1;
2795
+ const call = calls[index];
2796
+ if (call === void 0) return;
2797
+ try {
2798
+ await invoke(call);
2799
+ results[index] = {
2800
+ deviceId: call.deviceId,
2801
+ ok: true
2802
+ };
2803
+ } catch (err) {
2804
+ const error = err instanceof Error ? err.message : String(err);
2805
+ results[index] = {
2806
+ deviceId: call.deviceId,
2807
+ ok: false,
2808
+ error
2809
+ };
2810
+ }
2811
+ }
2812
+ };
2813
+ const width = Math.min(4, calls.length);
2814
+ await Promise.all(Array.from({ length: width }, () => worker()));
2815
+ return results;
2816
+ }
2817
+ //#endregion
2818
+ //#region ../types/dist/esm/composition/helpers/compile-history.mjs
2819
+ /**
2820
+ * Project a statistics or integral helper onto a new device (D944 §3).
2821
+ * The value field is `series`: the composer fills it from history.
2822
+ */
2823
+ var NOW$1 = {
2824
+ kind: "expression",
2825
+ expr: "now",
2826
+ bindings: {}
2827
+ };
2828
+ function series(member, publish, empty) {
2829
+ return {
2830
+ kind: "series",
2831
+ read: {
2832
+ source: member.source,
2833
+ cap: member.cap,
2834
+ fieldPath: member.fieldPath
2835
+ },
2836
+ publish,
2837
+ empty
2838
+ };
2839
+ }
2840
+ function counts(member) {
2841
+ return {
2842
+ included: series(member, "included", "offline"),
2843
+ excluded: series(member, "excluded", "offline"),
2844
+ total: series(member, "total", "offline")
2845
+ };
2846
+ }
2847
+ function declaredSeriesKind(member) {
2848
+ const field = historyFieldsFor(member.cap)[member.fieldPath];
2849
+ if (field === void 0) return null;
2850
+ return field.kind;
2851
+ }
2852
+ function historyProblems(member) {
2853
+ if (declaredSeriesKind(member) !== null) return [];
2854
+ return [problem("member-constraint", "helper.source", `${member.cap}.${member.fieldPath} has no history declaration`)];
2855
+ }
2856
+ function draft(input) {
2857
+ return {
2858
+ target: {
2859
+ kind: "new",
2860
+ type: DeviceType.Sensor,
2861
+ role: input.role
2862
+ },
2863
+ helper: input.spec,
2864
+ features: [{
2865
+ kind: "fields",
2866
+ cap: input.cap,
2867
+ fields: {
2868
+ [input.field]: series(input.member, "value", input.empty),
2869
+ lastFetchedAt: NOW$1
2870
+ }
2871
+ }, {
2872
+ kind: "fields",
2873
+ cap: "group-status",
2874
+ fields: counts(input.member)
2875
+ }]
2876
+ };
2877
+ }
2878
+ function statisticDraft(spec, retention = DEFAULT_HISTORY_RETENTION) {
2879
+ const problems = [...historyProblems(spec.source)];
2880
+ const kind = declaredSeriesKind(spec.source);
2881
+ if (kind === "enum") problems.push(problem("kind-mismatch", "helper.source", "a statistic reads a number or a boolean, not a state"));
2882
+ if (spec.stat === "sum" && kind !== "counter") problems.push(problem("kind-mismatch", "helper.stat", "a gauge has no sum — that is the integral template"));
2883
+ const tier = planStatisticTier(spec.window, retention);
2884
+ if (!tier.ok) problems.push(problem("retention", "helper.window", tier.reason));
2885
+ return {
2886
+ problems,
2887
+ draft: draft({
2888
+ role: DeviceRole.NumericSensor,
2889
+ cap: "numeric-sensor",
2890
+ field: "value",
2891
+ empty: "null",
2892
+ spec,
2893
+ member: spec.source
2894
+ })
2895
+ };
2896
+ }
2897
+ /**
2898
+ * A derivative reads a gauge or a counter and publishes its rate per second,
2899
+ * minute or hour. The output is a plain number: a rate of a temperature is not
2900
+ * a temperature, so the chart carries no inherited unit.
2901
+ */
2902
+ function derivativeDraft(spec, retention = DEFAULT_HISTORY_RETENTION) {
2903
+ const problems = [...historyProblems(spec.source)];
2904
+ const kind = declaredSeriesKind(spec.source);
2905
+ if (kind === "enum" || kind === "boolean") problems.push(problem("kind-mismatch", "helper.source", "a derivative reads a number that moves, not a yes/no or a state"));
2906
+ const tier = planStatisticTier(spec.window, retention);
2907
+ if (!tier.ok) problems.push(problem("retention", "helper.window", tier.reason));
2908
+ return {
2909
+ problems,
2910
+ draft: draft({
2911
+ role: DeviceRole.NumericSensor,
2912
+ cap: "numeric-sensor",
2913
+ field: "value",
2914
+ empty: "null",
2915
+ spec,
2916
+ member: spec.source
2917
+ })
2918
+ };
2919
+ }
2920
+ function integralDraft(spec, retention = DEFAULT_HISTORY_RETENTION) {
2921
+ const problems = [...historyProblems(spec.source)];
2922
+ const kind = declaredSeriesKind(spec.source);
2923
+ const isPower = spec.source.cap === "power-meter" && spec.source.fieldPath === "power";
2924
+ if (kind === "counter" || kind === "boolean" || kind === "enum") problems.push(problem("kind-mismatch", "helper.source", "an integral reads an instantaneous gauge, not a counter or a state"));
2925
+ if (spec.output === "energy" && !isPower) problems.push(problem("kind-mismatch", "helper.output", "energy is the integral of power-meter.power; another reading uses the meter"));
2926
+ if (spec.output === "meter" && isPower) problems.push(problem("kind-mismatch", "helper.output", "power integrates to power-meter.energy, which energy dashboards already read"));
2927
+ const tier = planResetTier(spec.reset, retention);
2928
+ if (!tier.ok) problems.push(problem("retention", "helper.reset", tier.reason));
2929
+ const energy = spec.output === "energy";
2930
+ return {
2931
+ problems,
2932
+ draft: draft({
2933
+ role: energy ? DeviceRole.EnergySensor : DeviceRole.NumericSensor,
2934
+ cap: energy ? "power-meter" : "meter",
2935
+ field: energy ? "energy" : "value",
2936
+ empty: "offline",
2937
+ spec,
2938
+ member: spec.source
2939
+ })
2940
+ };
2941
+ }
2942
+ //#endregion
2943
+ //#region ../types/dist/esm/composition/customize/scalar-expr.mjs
2944
+ var UNSIGNED = /^\d+(?:\.\d+)?$/;
2945
+ var SIGNED = /^-?\d+(?:\.\d+)?$/;
2946
+ var IDENT = /^[A-Za-z_][A-Za-z0-9_]*$/;
2947
+ function unsignedToken(value) {
2948
+ return token(value, UNSIGNED);
2949
+ }
2950
+ function signedToken(value) {
2951
+ return token(value, SIGNED);
2952
+ }
2953
+ function constantExpr(value) {
2954
+ if (typeof value === "string") return JSON.stringify(value);
2955
+ if (typeof value === "number") return signedToken(value);
2956
+ if (typeof value === "boolean") return value ? "true" : "false";
2957
+ return "null";
2958
+ }
2959
+ /**
2960
+ * Canonical text of a replace target's override (D984): the field keeps its
2961
+ * NATIVE value (`native`) when that value is one of `unlessNative`, becomes
2962
+ * `whenSourceTrue` while the boolean source (`x`) is true, else keeps native.
2963
+ * A null source is falsy, so an unknown source leaves the native value.
2964
+ */
2965
+ function overrideExpr(whenSourceTrue, unlessNative) {
2966
+ const guard = unlessNative.map((value) => `native == ${JSON.stringify(value)}`).join(" || ");
2967
+ const inner = `(x ? ${JSON.stringify(whenSourceTrue)} : native)`;
2968
+ return guard === "" ? inner.slice(1, -1) : `${guard} ? native : ${inner}`;
2969
+ }
2970
+ function isIdentifier(path) {
2971
+ return IDENT.test(path);
2972
+ }
2973
+ function dwellExpr(comparison, threshold, start, stop, minSamples = 1) {
2974
+ return `dwell(x ${comparison === "gte" ? ">=" : "<="} ${threshold}, ${start}, ${stop}${minSamples > 1 ? `, ${minSamples}` : ""})`;
2975
+ }
2976
+ function linearExpr(inner, scale, offset, clampMin, clampMax) {
2977
+ const arithmetic = `${inner} * ${scale} + ${offset}`;
2978
+ if (clampMin === null || clampMax === null) return arithmetic;
2979
+ return `clamp(${arithmetic}, ${clampMin}, ${clampMax})`;
2980
+ }
2981
+ function token(value, pattern) {
2982
+ if (!Number.isFinite(value)) return null;
2983
+ const text = Object.is(value, -0) ? "0" : String(value);
2984
+ return pattern.test(text) ? text : null;
2985
+ }
2986
+ //#endregion
2987
+ //#region ../types/dist/esm/composition/helpers/compile-math.mjs
2988
+ /**
2989
+ * Math helpers projected onto a new sensor (D944 phase 3). A threshold is the
2990
+ * `schmitt` builtin, a difference and a ratio are small expressions, a sum is
2991
+ * the group reducer (so an unreporting input is left out, not read as 0), and
2992
+ * a free expression is the expression engine unchanged — it still includes a
2993
+ * stale input, and the template says so.
2994
+ */
2995
+ var NOW = {
2996
+ kind: "expression",
2997
+ expr: "now",
2998
+ bindings: {}
2999
+ };
3000
+ function from(member) {
3001
+ return {
3002
+ kind: "from",
3003
+ source: member.source,
3004
+ cap: member.cap,
3005
+ fieldPath: member.fieldPath
3006
+ };
3007
+ }
3008
+ function expression(expr, bindings) {
3009
+ return {
3010
+ kind: "expression",
3011
+ expr,
3012
+ bindings
3013
+ };
3014
+ }
3015
+ function sameMember$1(a, b) {
3016
+ return a.source.addonId === b.source.addonId && a.source.stableId === b.source.stableId && a.cap === b.cap && a.fieldPath === b.fieldPath;
3017
+ }
3018
+ function numericSensor(helper, value, extra = []) {
3019
+ return {
3020
+ target: {
3021
+ kind: "new",
3022
+ type: DeviceType.Sensor,
3023
+ role: DeviceRole.NumericSensor
3024
+ },
3025
+ helper,
3026
+ features: [{
3027
+ kind: "fields",
3028
+ cap: "numeric-sensor",
3029
+ fields: {
3030
+ value,
3031
+ lastFetchedAt: NOW
3032
+ }
3033
+ }, ...extra]
3034
+ };
3035
+ }
3036
+ function binarySensor(helper, on) {
3037
+ return {
3038
+ target: {
3039
+ kind: "new",
3040
+ type: DeviceType.Sensor,
3041
+ role: DeviceRole.BinarySensor
3042
+ },
3043
+ helper,
3044
+ features: [{
3045
+ kind: "fields",
3046
+ cap: "binary",
3047
+ fields: {
3048
+ on,
3049
+ lastChangedAt: NOW
3050
+ }
3051
+ }]
3052
+ };
3053
+ }
3054
+ function thresholdDraft(spec) {
3055
+ const problems = [];
3056
+ const high = signedToken(spec.high);
3057
+ const low = signedToken(spec.low);
3058
+ if (high === null) problems.push(problem("kind-mismatch", "helper.high", "the high edge is a finite number"));
3059
+ if (low === null) problems.push(problem("kind-mismatch", "helper.low", "the low edge is a finite number"));
3060
+ if (high !== null && low !== null && spec.low > spec.high) problems.push(problem("kind-mismatch", "helper.low", `the low edge (${spec.low}) is above the high edge (${spec.high}) — it turns on at the high edge and off at the low one`));
3061
+ const onFor = unsignedToken(spec.onForMs);
3062
+ const offFor = unsignedToken(spec.offForMs);
3063
+ if (onFor === null || offFor === null) problems.push(problem("kind-mismatch", "helper.onForMs", "the on and off delays are a non-negative number of milliseconds"));
3064
+ const delays = onFor !== null && offFor !== null && (spec.onForMs > 0 || spec.offForMs > 0) ? `, ${onFor}, ${offFor}` : "";
3065
+ return {
3066
+ problems,
3067
+ draft: binarySensor(spec, expression(`coalesce(schmitt(x, ${high ?? "0"}, ${low ?? "0"}${delays}), false)`, { x: from(spec.source) }))
3068
+ };
3069
+ }
3070
+ var NAMES = ["a", "b"];
3071
+ function arithmeticProblems(spec) {
3072
+ const problems = [];
3073
+ const exactlyTwo = spec.op !== "sum";
3074
+ if (exactlyTwo && spec.inputs.length !== 2) problems.push(problem("member-constraint", "helper.inputs", `a ${spec.op} takes exactly two readings, the first ${spec.op === "ratio" ? "over" : "minus"} the second`));
3075
+ if (!exactlyTwo && spec.inputs.length < 2) problems.push(problem("member-constraint", "helper.inputs", "a sum takes two or more readings"));
3076
+ spec.inputs.forEach((input, index) => {
3077
+ if (spec.inputs.slice(0, index).some((other) => sameMember$1(other, input))) problems.push(problem("member-constraint", `helper.inputs[${index}]`, "this reading is already an input"));
3078
+ });
3079
+ return problems;
3080
+ }
3081
+ var GROUP_COUNTS = [
3082
+ "included",
3083
+ "excluded",
3084
+ "total"
3085
+ ];
3086
+ function arithmeticDraft(spec) {
3087
+ const problems = arithmeticProblems(spec);
3088
+ if (spec.op === "sum") {
3089
+ const reads = spec.inputs.map((input) => ({
3090
+ source: input.source,
3091
+ cap: input.cap,
3092
+ fieldPath: input.fieldPath
3093
+ }));
3094
+ const aggregate = (publish) => ({
3095
+ kind: "aggregate",
3096
+ reducer: "sum",
3097
+ reads,
3098
+ publish,
3099
+ empty: "null"
3100
+ });
3101
+ const counts = Object.fromEntries(GROUP_COUNTS.map((name) => [name, aggregate(name)]));
3102
+ return {
3103
+ problems,
3104
+ draft: numericSensor(spec, aggregate("value"), [{
3105
+ kind: "fields",
3106
+ cap: "group-status",
3107
+ fields: counts
3108
+ }])
3109
+ };
3110
+ }
3111
+ const bindings = Object.fromEntries(spec.inputs.slice(0, 2).map((input, index) => [NAMES[index] ?? "a", from(input)]));
3112
+ return {
3113
+ problems,
3114
+ draft: numericSensor(spec, expression(spec.op === "difference" ? "a - b" : "b == 0 ? null : a / b", bindings))
3115
+ };
3116
+ }
3117
+ function expressionProblems(spec) {
3118
+ const problems = [];
3119
+ const seen = /* @__PURE__ */ new Set();
3120
+ spec.inputs.forEach((input, index) => {
3121
+ const at = `helper.inputs[${index}].name`;
3122
+ if (!isIdentifier(input.name)) problems.push(problem("expression-invalid", at, `\`${input.name}\` is not a name — use letters, digits and _, starting with a letter`));
3123
+ if (seen.has(input.name)) problems.push(problem("expression-invalid", at, `the name \`${input.name}\` is used twice`));
3124
+ seen.add(input.name);
3125
+ });
3126
+ if (problems.length > 0) return problems;
3127
+ const bindings = Object.fromEntries(spec.inputs.map((input) => [input.name, from(input.member)]));
3128
+ const message = validateExpressionSource({
3129
+ expr: spec.expr,
3130
+ bindings
3131
+ });
3132
+ return message === null ? [] : [problem("expression-invalid", "helper.expr", message)];
3133
+ }
3134
+ function expressionDraft(spec) {
3135
+ const problems = expressionProblems(spec);
3136
+ const bindings = Object.fromEntries(spec.inputs.map((input) => [input.name, from(input.member)]));
3137
+ const source = expression(spec.expr, bindings);
3138
+ return {
3139
+ problems,
3140
+ draft: spec.output === "boolean" ? binarySensor(spec, source) : numericSensor(spec, source)
3141
+ };
3142
+ }
3143
+ //#endregion
3144
+ //#region ../types/dist/esm/composition/helpers/compile.mjs
3145
+ /**
3146
+ * Project a helper spec onto the composition the composer already runs (D944).
3147
+ * Pure: it stores nothing. A group does not compile to `avg(...)` / `any(...)`.
3148
+ */
3149
+ function sameSource(a, b) {
3150
+ return a.addonId === b.addonId && a.stableId === b.stableId;
3151
+ }
3152
+ function sameMember(a, b) {
3153
+ return sameSource(a.source, b.source) && a.cap === b.cap && a.fieldPath === b.fieldPath;
3154
+ }
3155
+ function accepted(template, member) {
3156
+ return template.accept.some((field) => field.cap === member.cap && field.fieldPath === member.fieldPath);
3157
+ }
3158
+ function memberProblems(template, spec) {
3159
+ return spec.members.flatMap((member, index) => {
3160
+ const at = `helper.members[${index}]`;
3161
+ const problems = [];
3162
+ if (!accepted(template, member)) {
3163
+ const allowed = template.accept.map((field) => `${field.cap}.${field.fieldPath}`).join(" or ");
3164
+ problems.push(problem("member-constraint", at, `a ${template.id} group reads ${allowed}; this member is ${member.cap}.${member.fieldPath}`));
3165
+ }
3166
+ if (spec.members.slice(0, index).some((other) => sameMember(other, member))) problems.push(problem("member-constraint", at, "this member is already in the group"));
3167
+ return problems;
3168
+ });
3169
+ }
3170
+ function aggregateSource(template, spec, reads, publish) {
3171
+ return {
3172
+ kind: "aggregate",
3173
+ reducer: spec.aggregate,
3174
+ reads: [...reads],
3175
+ publish,
3176
+ empty: template.empty,
3177
+ ...template.activeWhen === void 0 ? {} : { activeWhen: [...template.activeWhen] }
3178
+ };
3179
+ }
3180
+ function draftOf(template, spec) {
3181
+ const reads = spec.members.map((member) => ({
3182
+ source: member.source,
3183
+ cap: member.cap,
3184
+ fieldPath: member.fieldPath
3185
+ }));
3186
+ const companions = Object.fromEntries(template.companions.map((companion) => [companion.fieldPath, expressionSource(companion.expr)]));
3187
+ return {
3188
+ target: {
3189
+ kind: "new",
3190
+ type: template.deviceType,
3191
+ ...template.role === void 0 ? {} : { role: template.role }
3192
+ },
3193
+ helper: spec,
3194
+ features: [{
3195
+ kind: "fields",
3196
+ cap: template.outputCap,
3197
+ fields: {
3198
+ [template.outputField]: aggregateSource(template, spec, reads, "value"),
3199
+ ...companions
3200
+ }
3201
+ }, {
3202
+ kind: "fields",
3203
+ cap: "group-status",
3204
+ fields: {
3205
+ included: aggregateSource(template, spec, reads, "included"),
3206
+ excluded: aggregateSource(template, spec, reads, "excluded"),
3207
+ total: aggregateSource(template, spec, reads, "total")
3208
+ }
3209
+ }]
3210
+ };
3211
+ }
3212
+ function criterionProblems(template, spec) {
3213
+ if (template.family === "actuator") {
3214
+ if (spec.active === void 0) return [problem("kind-mismatch", "helper.active", `a ${template.id} group needs an active criterion (at-least-one or all)`)];
3215
+ const reducer = reducerForActive(spec.active);
3216
+ if (spec.aggregate !== reducer) return [problem("kind-mismatch", "helper.aggregate", `active \`${spec.active}\` aggregates by \`${reducer}\`, not \`${spec.aggregate}\``)];
3217
+ return [];
3218
+ }
3219
+ if (spec.active !== void 0) return [problem("kind-mismatch", "helper.active", `a ${template.id} group has no active criterion — that belongs to an actuator group`)];
3220
+ return [];
3221
+ }
3222
+ function parseDraft(draft) {
3223
+ const parsed = CompositionSchema.safeParse(draft);
3224
+ if (parsed.success) return {
3225
+ ok: true,
3226
+ composition: parsed.data
3227
+ };
3228
+ return {
3229
+ ok: false,
3230
+ problems: [problem("helper-mismatch", "helper", `the template did not compile: ${parsed.error.issues.map((issue) => issue.message).join("; ")}`)]
3231
+ };
3232
+ }
3233
+ function expressionSource(expr, bindings = {}) {
3234
+ return {
3235
+ kind: "expression",
3236
+ expr,
3237
+ bindings
3238
+ };
3239
+ }
3240
+ /** Compile a helper template to a new-device composition. Refusals are named. */
3241
+ function compileHelper(spec, retention = DEFAULT_HISTORY_RETENTION) {
3242
+ switch (spec.kind) {
3243
+ case "group": return compileGroup(spec);
3244
+ case "statistic": {
3245
+ const built = statisticDraft(spec, retention);
3246
+ if (built.problems.length > 0) return {
3247
+ ok: false,
3248
+ problems: built.problems
3249
+ };
3250
+ return parseDraft(built.draft);
3251
+ }
3252
+ case "integral": {
3253
+ const built = integralDraft(spec, retention);
3254
+ if (built.problems.length > 0) return {
3255
+ ok: false,
3256
+ problems: built.problems
3257
+ };
3258
+ return parseDraft(built.draft);
3259
+ }
3260
+ case "derivative": {
3261
+ const built = derivativeDraft(spec, retention);
3262
+ if (built.problems.length > 0) return {
3263
+ ok: false,
3264
+ problems: built.problems
3265
+ };
3266
+ return parseDraft(built.draft);
3267
+ }
3268
+ case "threshold": return compileMath(thresholdDraft(spec));
3269
+ case "arithmetic": return compileMath(arithmeticDraft(spec));
3270
+ case "expression": return compileMath(expressionDraft(spec));
3271
+ case "grid":
3272
+ case "crop":
3273
+ case "terminal": return parseDraft(engineHostedDraft(spec));
3274
+ }
3275
+ }
3276
+ /**
3277
+ * A grid or a Terminal camera (planning#580): a bare `new` Camera. The composer
3278
+ * declares the row; the engine serves every cap on it, so there is nothing to
3279
+ * compose.
3280
+ */
3281
+ function engineHostedDraft(spec) {
3282
+ return {
3283
+ target: {
3284
+ kind: "new",
3285
+ type: DeviceType.Camera
3286
+ },
3287
+ helper: spec,
3288
+ features: []
3289
+ };
3290
+ }
3291
+ function compileMath(built) {
3292
+ if (built.problems.length > 0) return {
3293
+ ok: false,
3294
+ problems: built.problems
3295
+ };
3296
+ return parseDraft(built.draft);
3297
+ }
3298
+ function compileGroup(spec) {
3299
+ const template = groupTemplate(spec.templateId);
3300
+ if (template === null) return {
3301
+ ok: false,
3302
+ problems: [problem("member-constraint", "helper.templateId", `unknown template \`${spec.templateId}\``)]
3303
+ };
3304
+ const criterion = criterionProblems(template, spec);
3305
+ if (criterion.length > 0) return {
3306
+ ok: false,
3307
+ problems: criterion
3308
+ };
3309
+ if (!template.aggregates.includes(spec.aggregate)) {
3310
+ const allowed = template.aggregates.join(", ");
3311
+ return {
3312
+ ok: false,
3313
+ problems: [problem("kind-mismatch", "helper.aggregate", `a ${template.id} group aggregates by ${allowed}, not \`${spec.aggregate}\``)]
3314
+ };
3315
+ }
3316
+ const members = memberProblems(template, spec);
3317
+ if (members.length > 0) return {
3318
+ ok: false,
3319
+ problems: members
3320
+ };
3321
+ return parseDraft(draftOf(template, spec));
3322
+ }
3323
+ /** The built body, ignoring `helper`, so a save can demand one writer. */
3324
+ function sameHelperBody(stored, compiled) {
3325
+ return JSON.stringify(stored.target) === JSON.stringify(compiled.target) && JSON.stringify(stored.features) === JSON.stringify(compiled.features);
3326
+ }
3327
+ //#endregion
3328
+ //#region ../types/dist/esm/capabilities/error.cap.mjs
3329
+ /** How loudly a fault wants the operator. Both tiers raise the attention event. */
3330
+ var DeviceErrorSeveritySchema = /* @__PURE__ */ z.enum(["warning", "error"]);
3331
+ /** One fault of a device that can raise several at once. */
3332
+ var DeviceFaultSchema = /* @__PURE__ */ z.object({
3333
+ /** The device's own code, as the vendor names it. */
3334
+ code: /* @__PURE__ */ z.string(),
3335
+ /** Already translated by the provider (it owns the vendor vocabulary). */
3336
+ label: /* @__PURE__ */ z.string(),
3337
+ severity: DeviceErrorSeveritySchema
3338
+ });
3339
+ /** One kind of fault a device CAN raise: the integration's own declared catalog entry. */
3340
+ var DeviceFaultTypeSchema = DeviceFaultSchema;
3341
+ /**
3342
+ * The fault catalog of a device, declared by its integration at runtime (never a
3343
+ * code enum). A fault outside the catalog is still published and still matches
3344
+ * a rule that names no code.
3345
+ */
3346
+ var ListFaultTypesInputSchema = /* @__PURE__ */ z.object({ deviceId: /* @__PURE__ */ z.number().int().nonnegative() });
3347
+ var FaultTypesSchema = /* @__PURE__ */ z.object({ types: /* @__PURE__ */ z.array(DeviceFaultTypeSchema) });
3348
+ /**
3349
+ * The fault a device reports right now. One slice per device.
3350
+ *
3351
+ * `active` is tri-state: `null` is "the provider has not read it yet" and is
3352
+ * never drawn as "no fault" nor as a fault (D315, D393). The provider filters
3353
+ * what is not a fault (a completion or reminder code) BEFORE it writes `true`.
3354
+ *
3355
+ * The cap's name is the key a template reads (`{{ alias.error.label }}`, D1021).
3356
+ */
3357
+ var ErrorStatusSchema = /* @__PURE__ */ z.object({
3358
+ active: /* @__PURE__ */ z.boolean().nullable(),
3359
+ /** The code of the principal fault; `null` when none (or unknown). */
3360
+ code: /* @__PURE__ */ z.string().nullable(),
3361
+ /** The principal fault's words, provider-translated; `null` when none. */
3362
+ label: /* @__PURE__ */ z.string().nullable(),
3363
+ severity: DeviceErrorSeveritySchema,
3364
+ /** Ms epoch the current fault started; `null` when none or not known. */
3365
+ since: /* @__PURE__ */ z.number().nullable(),
3366
+ /** Every fault, for a device that raises several. The principal is the first. */
3367
+ faults: /* @__PURE__ */ z.array(DeviceFaultSchema).optional(),
3368
+ /** Ms epoch of the last read the provider made of the fault. */
3369
+ lastFetchedAt: /* @__PURE__ */ z.number()
3370
+ });
3371
+ /** The slice before the provider has read anything: unknown, not "fine". */
3372
+ var ERROR_STATUS_COLD = {
3373
+ active: null,
3374
+ code: null,
3375
+ label: null,
3376
+ severity: "error",
3377
+ since: null,
3378
+ lastFetchedAt: 0
3379
+ };
3380
+ var errorCapability = {
3381
+ name: "error",
3382
+ scope: "device",
3383
+ deviceNative: true,
3384
+ mode: "singleton",
3385
+ methods: {
3386
+ /** The fault codes this device's integration can raise; `[]` when it declares none. */
3387
+ listFaultTypes: /* @__PURE__ */ method(ListFaultTypesInputSchema, FaultTypesSchema, {
3388
+ kind: "query",
3389
+ auth: "protected"
3390
+ }) },
3391
+ status: {
3392
+ schema: ErrorStatusSchema,
3393
+ kind: "push",
3394
+ empty: ERROR_STATUS_COLD
3395
+ },
3396
+ runtimeState: ErrorStatusSchema,
3397
+ /**
3398
+ * Runtime-state durability: **restored** — the previous observation is what
3399
+ * lets the first reading after a restart be a COMPARISON: a fault that was
3400
+ * already open must not announce itself a second time.
3401
+ *
3402
+ * See `RuntimeStateDurability`. Enforced by
3403
+ * `scripts/check-runtime-state-durability.ts`.
3404
+ */
3405
+ durability: "restored",
3406
+ volatileStateFields: ["lastFetchedAt"],
3407
+ /** The fault itself is carried by the attention alerts; no series is recorded. */
3408
+ history: "none",
3409
+ vocabulary: {
3410
+ noun: /* @__PURE__ */ t("Fault", "Guasto"),
3411
+ order: 5265,
3412
+ state: [{
3413
+ kind: "boolean",
3414
+ field: "active",
3415
+ label: /* @__PURE__ */ t("Fault", "Guasto"),
3416
+ whenTrue: /* @__PURE__ */ t("When {device} reports a fault", "Quando {device} segnala un guasto"),
3417
+ whenFalse: /* @__PURE__ */ t("When the fault of {device} clears", "Quando il guasto di {device} si risolve"),
3418
+ icon: "triangle-alert"
3419
+ }]
3420
+ }
3421
+ };
3422
+ //#endregion
3423
+ export { planResetTier as $, compositionItemFieldPath as A, helperMembers as B, CompositionFieldReadSchema as C, composedDeviceRef as D, canonicalStoredBlockTarget as E, featureSources as F, HISTORY_FAST_MS as G, isHistoryHelper as H, fieldReads as I, MINUTE_MS as J, HISTORY_SLOW_MS as K, isForwardInputRef as L, compositionSliceKey as M, compositionSourceKey as N, composedDeviceStableId as O, featureFieldEntries as P, openStatistic as Q, COMPOSED_DEVICE_STABLE_ID_PREFIX as R, COMPOSITION_ITEM_ARRAY_PATH as S, CompositionSchema as T, DAY_MS as U, isEngineHostedHelper as V, DEFAULT_HISTORY_RETENTION as W, nextLocalMidnight as X, historyRetentionFromSettings as Y, openReset as Z, groupTemplate as _, evaluateDwell as _t, sameHelperBody as a, cloneStatefulExpressionMemory as at, refused as b, isIdentifier as c, evaluateStatefulExpressionCall as ct, signedToken as d, compileExpressionSafe as dt, planStatisticTier as et, unsignedToken as f, EXPRESSION_IDENTIFIER_RE as ft, sharedColorModes as g, evaluateCount as gt, runFanOut as h, disarmRoseMemory as ht, compileHelper as i, integrateReading as it, compositionReadKey as j, compositionFeatureEnabled as k, linearExpr as l, toExpressionValue as lt, fanOutTargets as m, EXPRESSION_BUILTINS as mt, ERROR_STATUS_COLD as n, evaluateDerivative as nt, constantExpr as o, createStatefulExpressionMemory as ot, declaredSeriesKind as p, MAX_EXPRESSION_SOURCE_LENGTH as pt, HOUR_MS as q, errorCapability as r, evaluateStatistic as rt, dwellExpr as s, evaluateExpressionSource as st, DeviceFaultSchema as t, statisticCadenceMs as tt, overrideExpr as u, validateExpressionSource as ut, compositionFieldAt as v, CompositionFieldSourceSchema as w, COMPOSER_ADDON_ID as x, problem as y, HelperMemberSchema as z };