mqtt2matter 0.0.0-stage → 0.2.0

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 (279) hide show
  1. package/CHANGELOG.md +76 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +23 -0
  4. package/README.md +172 -2
  5. package/dist/app.d.ts +34 -0
  6. package/dist/app.js +157 -0
  7. package/dist/app.js.map +1 -0
  8. package/dist/commands/import-z2m.d.ts +20 -0
  9. package/dist/commands/import-z2m.js +173 -0
  10. package/dist/commands/import-z2m.js.map +1 -0
  11. package/dist/commands/install.d.ts +41 -0
  12. package/dist/commands/install.js +250 -0
  13. package/dist/commands/install.js.map +1 -0
  14. package/dist/commands/update.d.ts +14 -0
  15. package/dist/commands/update.js +109 -0
  16. package/dist/commands/update.js.map +1 -0
  17. package/dist/config/index.d.ts +2 -0
  18. package/dist/config/index.js +3 -0
  19. package/dist/config/index.js.map +1 -0
  20. package/dist/config/load.d.ts +57 -0
  21. package/dist/config/load.js +137 -0
  22. package/dist/config/load.js.map +1 -0
  23. package/dist/config/schema.d.ts +496 -0
  24. package/dist/config/schema.js +115 -0
  25. package/dist/config/schema.js.map +1 -0
  26. package/dist/engine/payload.d.ts +94 -0
  27. package/dist/engine/payload.js +515 -0
  28. package/dist/engine/payload.js.map +1 -0
  29. package/dist/engine/runtime.d.ts +79 -0
  30. package/dist/engine/runtime.js +438 -0
  31. package/dist/engine/runtime.js.map +1 -0
  32. package/dist/engine/template.d.ts +20 -0
  33. package/dist/engine/template.js +264 -0
  34. package/dist/engine/template.js.map +1 -0
  35. package/dist/engine/units.d.ts +9 -0
  36. package/dist/engine/units.js +42 -0
  37. package/dist/engine/units.js.map +1 -0
  38. package/dist/families/climate.d.ts +11 -0
  39. package/dist/families/climate.js +68 -0
  40. package/dist/families/climate.js.map +1 -0
  41. package/dist/families/color.d.ts +30 -0
  42. package/dist/families/color.js +152 -0
  43. package/dist/families/color.js.map +1 -0
  44. package/dist/families/cover.d.ts +17 -0
  45. package/dist/families/cover.js +308 -0
  46. package/dist/families/cover.js.map +1 -0
  47. package/dist/families/fan.d.ts +16 -0
  48. package/dist/families/fan.js +154 -0
  49. package/dist/families/fan.js.map +1 -0
  50. package/dist/families/index.d.ts +32 -0
  51. package/dist/families/index.js +162 -0
  52. package/dist/families/index.js.map +1 -0
  53. package/dist/families/light.d.ts +36 -0
  54. package/dist/families/light.js +258 -0
  55. package/dist/families/light.js.map +1 -0
  56. package/dist/families/lock.d.ts +10 -0
  57. package/dist/families/lock.js +31 -0
  58. package/dist/families/lock.js.map +1 -0
  59. package/dist/families/on-off.d.ts +7 -0
  60. package/dist/families/on-off.js +56 -0
  61. package/dist/families/on-off.js.map +1 -0
  62. package/dist/families/power-source.d.ts +12 -0
  63. package/dist/families/power-source.js +60 -0
  64. package/dist/families/power-source.js.map +1 -0
  65. package/dist/families/registry.d.ts +40 -0
  66. package/dist/families/registry.js +72 -0
  67. package/dist/families/registry.js.map +1 -0
  68. package/dist/families/rvc.d.ts +40 -0
  69. package/dist/families/rvc.js +83 -0
  70. package/dist/families/rvc.js.map +1 -0
  71. package/dist/families/switch.d.ts +19 -0
  72. package/dist/families/switch.js +94 -0
  73. package/dist/families/switch.js.map +1 -0
  74. package/dist/importers/actions.d.ts +19 -0
  75. package/dist/importers/actions.js +98 -0
  76. package/dist/importers/actions.js.map +1 -0
  77. package/dist/importers/ha/areas.d.ts +6 -0
  78. package/dist/importers/ha/areas.js +279 -0
  79. package/dist/importers/ha/areas.js.map +1 -0
  80. package/dist/importers/ha/generate.d.ts +51 -0
  81. package/dist/importers/ha/generate.js +1376 -0
  82. package/dist/importers/ha/generate.js.map +1 -0
  83. package/dist/importers/ha/index.d.ts +6 -0
  84. package/dist/importers/ha/index.js +7 -0
  85. package/dist/importers/ha/index.js.map +1 -0
  86. package/dist/importers/ha/source.d.ts +36 -0
  87. package/dist/importers/ha/source.js +95 -0
  88. package/dist/importers/ha/source.js.map +1 -0
  89. package/dist/importers/ha/sync.d.ts +29 -0
  90. package/dist/importers/ha/sync.js +132 -0
  91. package/dist/importers/ha/sync.js.map +1 -0
  92. package/dist/importers/ha/templates.d.ts +18 -0
  93. package/dist/importers/ha/templates.js +285 -0
  94. package/dist/importers/ha/templates.js.map +1 -0
  95. package/dist/importers/ha/types.d.ts +78 -0
  96. package/dist/importers/ha/types.js +479 -0
  97. package/dist/importers/ha/types.js.map +1 -0
  98. package/dist/importers/index.d.ts +5 -0
  99. package/dist/importers/index.js +8 -0
  100. package/dist/importers/index.js.map +1 -0
  101. package/dist/importers/patch.d.ts +50 -0
  102. package/dist/importers/patch.js +224 -0
  103. package/dist/importers/patch.js.map +1 -0
  104. package/dist/importers/sync.d.ts +112 -0
  105. package/dist/importers/sync.js +220 -0
  106. package/dist/importers/sync.js.map +1 -0
  107. package/dist/importers/twins.d.ts +10 -0
  108. package/dist/importers/twins.js +34 -0
  109. package/dist/importers/twins.js.map +1 -0
  110. package/dist/importers/z2m/generate.d.ts +81 -0
  111. package/dist/importers/z2m/generate.js +1171 -0
  112. package/dist/importers/z2m/generate.js.map +1 -0
  113. package/dist/importers/z2m/index.d.ts +5 -0
  114. package/dist/importers/z2m/index.js +6 -0
  115. package/dist/importers/z2m/index.js.map +1 -0
  116. package/dist/importers/z2m/source.d.ts +18 -0
  117. package/dist/importers/z2m/source.js +46 -0
  118. package/dist/importers/z2m/source.js.map +1 -0
  119. package/dist/importers/z2m/sync.d.ts +29 -0
  120. package/dist/importers/z2m/sync.js +92 -0
  121. package/dist/importers/z2m/sync.js.map +1 -0
  122. package/dist/importers/z2m/types.d.ts +72 -0
  123. package/dist/importers/z2m/types.js +46 -0
  124. package/dist/importers/z2m/types.js.map +1 -0
  125. package/dist/index.d.ts +5 -0
  126. package/dist/index.js +7 -0
  127. package/dist/index.js.map +1 -0
  128. package/dist/log.d.ts +17 -0
  129. package/dist/log.js +54 -0
  130. package/dist/log.js.map +1 -0
  131. package/dist/main.d.ts +2 -0
  132. package/dist/main.js +202 -0
  133. package/dist/main.js.map +1 -0
  134. package/dist/matter/bridge.d.ts +113 -0
  135. package/dist/matter/bridge.js +467 -0
  136. package/dist/matter/bridge.js.map +1 -0
  137. package/dist/matter/check.d.ts +11 -0
  138. package/dist/matter/check.js +116 -0
  139. package/dist/matter/check.js.map +1 -0
  140. package/dist/matter/cluster-defaults.d.ts +6 -0
  141. package/dist/matter/cluster-defaults.js +63 -0
  142. package/dist/matter/cluster-defaults.js.map +1 -0
  143. package/dist/matter/commissioning.d.ts +21 -0
  144. package/dist/matter/commissioning.js +88 -0
  145. package/dist/matter/commissioning.js.map +1 -0
  146. package/dist/matter/device-types.d.ts +44 -0
  147. package/dist/matter/device-types.js +230 -0
  148. package/dist/matter/device-types.js.map +1 -0
  149. package/dist/matter/ids.d.ts +31 -0
  150. package/dist/matter/ids.js +83 -0
  151. package/dist/matter/ids.js.map +1 -0
  152. package/dist/matter/index.d.ts +7 -0
  153. package/dist/matter/index.js +8 -0
  154. package/dist/matter/index.js.map +1 -0
  155. package/dist/matter/node-manager.d.ts +39 -0
  156. package/dist/matter/node-manager.js +161 -0
  157. package/dist/matter/node-manager.js.map +1 -0
  158. package/dist/matter/shards.d.ts +26 -0
  159. package/dist/matter/shards.js +93 -0
  160. package/dist/matter/shards.js.map +1 -0
  161. package/dist/model/attribute.d.ts +18 -0
  162. package/dist/model/attribute.js +28 -0
  163. package/dist/model/attribute.js.map +1 -0
  164. package/dist/model/catalog.d.ts +79 -0
  165. package/dist/model/catalog.js +223 -0
  166. package/dist/model/catalog.js.map +1 -0
  167. package/dist/model/index.d.ts +7 -0
  168. package/dist/model/index.js +8 -0
  169. package/dist/model/index.js.map +1 -0
  170. package/dist/model/migrate.d.ts +4 -0
  171. package/dist/model/migrate.js +39 -0
  172. package/dist/model/migrate.js.map +1 -0
  173. package/dist/model/options.d.ts +102 -0
  174. package/dist/model/options.js +88 -0
  175. package/dist/model/options.js.map +1 -0
  176. package/dist/model/presets.d.ts +37 -0
  177. package/dist/model/presets.js +105 -0
  178. package/dist/model/presets.js.map +1 -0
  179. package/dist/model/schema.d.ts +1747 -0
  180. package/dist/model/schema.js +243 -0
  181. package/dist/model/schema.js.map +1 -0
  182. package/dist/model/validate.d.ts +21 -0
  183. package/dist/model/validate.js +484 -0
  184. package/dist/model/validate.js.map +1 -0
  185. package/dist/mqtt/client.d.ts +38 -0
  186. package/dist/mqtt/client.js +94 -0
  187. package/dist/mqtt/client.js.map +1 -0
  188. package/dist/mqtt/index.d.ts +2 -0
  189. package/dist/mqtt/index.js +3 -0
  190. package/dist/mqtt/index.js.map +1 -0
  191. package/dist/mqtt/topic-cache.d.ts +20 -0
  192. package/dist/mqtt/topic-cache.js +58 -0
  193. package/dist/mqtt/topic-cache.js.map +1 -0
  194. package/dist/server/auth.d.ts +59 -0
  195. package/dist/server/auth.js +185 -0
  196. package/dist/server/auth.js.map +1 -0
  197. package/dist/server/catalog.d.ts +52 -0
  198. package/dist/server/catalog.js +96 -0
  199. package/dist/server/catalog.js.map +1 -0
  200. package/dist/server/compact.d.ts +3 -0
  201. package/dist/server/compact.js +105 -0
  202. package/dist/server/compact.js.map +1 -0
  203. package/dist/server/config-store.d.ts +36 -0
  204. package/dist/server/config-store.js +155 -0
  205. package/dist/server/config-store.js.map +1 -0
  206. package/dist/server/events.d.ts +50 -0
  207. package/dist/server/events.js +71 -0
  208. package/dist/server/events.js.map +1 -0
  209. package/dist/server/http.d.ts +27 -0
  210. package/dist/server/http.js +168 -0
  211. package/dist/server/http.js.map +1 -0
  212. package/dist/server/importers.d.ts +40 -0
  213. package/dist/server/importers.js +75 -0
  214. package/dist/server/importers.js.map +1 -0
  215. package/dist/server/index.d.ts +6 -0
  216. package/dist/server/index.js +8 -0
  217. package/dist/server/index.js.map +1 -0
  218. package/dist/server/log-buffer.d.ts +22 -0
  219. package/dist/server/log-buffer.js +55 -0
  220. package/dist/server/log-buffer.js.map +1 -0
  221. package/dist/server/presets.d.ts +17 -0
  222. package/dist/server/presets.js +55 -0
  223. package/dist/server/presets.js.map +1 -0
  224. package/dist/server/preview.d.ts +19 -0
  225. package/dist/server/preview.js +121 -0
  226. package/dist/server/preview.js.map +1 -0
  227. package/dist/server/server.d.ts +107 -0
  228. package/dist/server/server.js +810 -0
  229. package/dist/server/server.js.map +1 -0
  230. package/dist/server/update.d.ts +60 -0
  231. package/dist/server/update.js +191 -0
  232. package/dist/server/update.js.map +1 -0
  233. package/docs/api.md +128 -0
  234. package/docs/architecture.md +121 -0
  235. package/docs/config.md +538 -0
  236. package/docs/importers.md +241 -0
  237. package/example/mqtt2matter.json +276 -0
  238. package/package.json +90 -4
  239. package/presets/mqtt-smarthome/button.json +47 -0
  240. package/presets/mqtt-smarthome/contact.json +37 -0
  241. package/presets/mqtt-smarthome/cover.json +50 -0
  242. package/presets/mqtt-smarthome/dimmer.json +57 -0
  243. package/presets/mqtt-smarthome/humidity.json +38 -0
  244. package/presets/mqtt-smarthome/light.json +47 -0
  245. package/presets/mqtt-smarthome/occupancy.json +46 -0
  246. package/presets/mqtt-smarthome/switch.json +47 -0
  247. package/presets/mqtt-smarthome/temperature.json +38 -0
  248. package/presets/openbeken/color-light.json +64 -0
  249. package/presets/openbeken/ct-light.json +51 -0
  250. package/presets/openbeken/dimmer.json +47 -0
  251. package/presets/openbeken/humidity.json +37 -0
  252. package/presets/openbeken/relay.json +40 -0
  253. package/presets/openbeken/temperature.json +41 -0
  254. package/presets/shelly-gen1/dimmer.json +48 -0
  255. package/presets/shelly-gen1/door-window.json +43 -0
  256. package/presets/shelly-gen1/ht.json +43 -0
  257. package/presets/shelly-gen1/relay-pm.json +60 -0
  258. package/presets/shelly-gen1/relay.json +36 -0
  259. package/presets/shelly-gen1/roller.json +52 -0
  260. package/presets/shelly-gen2/cover.json +68 -0
  261. package/presets/shelly-gen2/dimmer.json +61 -0
  262. package/presets/shelly-gen2/ht.json +47 -0
  263. package/presets/shelly-gen2/i4.json +82 -0
  264. package/presets/shelly-gen2/switch-pm.json +101 -0
  265. package/presets/shelly-gen2/switch.json +47 -0
  266. package/presets/tasmota/climate.json +52 -0
  267. package/presets/tasmota/color-light.json +63 -0
  268. package/presets/tasmota/ct-light.json +50 -0
  269. package/presets/tasmota/dimmer.json +45 -0
  270. package/presets/tasmota/relay.json +39 -0
  271. package/presets/tasmota/shutter.json +46 -0
  272. package/presets/tasmota/temperature-humidity.json +42 -0
  273. package/presets/tasmota/temperature.json +32 -0
  274. package/presets/valetudo/vacuum.json +103 -0
  275. package/presets/wled/dimmer.json +46 -0
  276. package/presets/wled/light.json +59 -0
  277. package/ui/dist/assets/index-BDtT6bdH.js +10 -0
  278. package/ui/dist/assets/index-CHiG-aoU.css +1 -0
  279. package/ui/dist/index.html +18 -0
@@ -0,0 +1,810 @@
1
+ /* The web server: the REST API and the event stream of docs/api.md over node:http, and the built UI as
2
+ static files. It is the only thing the UI talks to. Everything it does goes through the application
3
+ (devices, the MQTT connection, the bridges), the config store (the file) and the catalogue; it owns
4
+ no state of its own beyond the connected event clients. */
5
+ import { createServer } from 'node:http';
6
+ import { resolve } from 'node:path';
7
+ import { Minutes } from '@matter/main';
8
+ import { DeviceCommissioner, FabricManager } from '@matter/main/protocol';
9
+ import { checkConfig } from "../matter/check.js";
10
+ import { migrateDevices } from "../model/migrate.js";
11
+ import { applyPreset } from "../model/presets.js";
12
+ import { DeviceSchema } from "../model/schema.js";
13
+ import { validateDevice } from "../model/validate.js";
14
+ import { catalogJson, clusterJson } from "./catalog.js";
15
+ import { compactDevice } from "./compact.js";
16
+ import { EventHub } from "./events.js";
17
+ import { AuthConfigSchema } from "../config/schema.js";
18
+ import { Auth, hashPassword } from "./auth.js";
19
+ import { HttpError, Router, sendJson, serveStatic } from "./http.js";
20
+ import { Updater } from "./update.js";
21
+ import { loadPresets } from "./presets.js";
22
+ import { previewCommand, previewStatus } from "./preview.js";
23
+ /** the package's `ui/dist`, from `src/server/` or `dist/server/` alike */
24
+ export const UI_DIST = resolve(new URL('../../ui/dist', import.meta.url).pathname);
25
+ /** attributes every cluster has and no one wants in the event stream */
26
+ const GLOBAL_ATTRIBUTES = new Set([
27
+ 'attributeList',
28
+ 'acceptedCommandList',
29
+ 'generatedCommandList',
30
+ 'eventList',
31
+ 'featureMap',
32
+ 'clusterRevision',
33
+ ]);
34
+ function isRecord(value) {
35
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
36
+ }
37
+ /** what answers without a login: the login itself, and what the UI needs to show it */
38
+ const PUBLIC_PATHS = new Set(['/api/auth', '/api/auth/login', '/api/auth/logout']);
39
+ function body(request) {
40
+ return isRecord(request.body) ? request.body : {};
41
+ }
42
+ export class Server {
43
+ options;
44
+ app;
45
+ store;
46
+ log;
47
+ hub;
48
+ router = new Router();
49
+ http;
50
+ observers = new Map();
51
+ unsubscribe = [];
52
+ startedAt = Date.now();
53
+ auth;
54
+ updater;
55
+ constructor(options) {
56
+ this.options = options;
57
+ this.app = options.app;
58
+ this.store = options.store;
59
+ this.log = options.log;
60
+ this.auth = options.auth ?? Auth.open();
61
+ this.updater = options.updater ?? new Updater({ current: options.version });
62
+ this.hub = new EventHub(options.log.child('events'), () => ({ type: 'hello', version: options.version }));
63
+ this.http = createServer((request, response) => {
64
+ const path = new URL(request.url ?? '/', 'http://localhost').pathname;
65
+ if (path.startsWith('/api/')) {
66
+ if (!PUBLIC_PATHS.has(path) && !this.auth.check(request)) {
67
+ sendJson(response, 401, { error: 'authentication required' });
68
+ return;
69
+ }
70
+ this.router.dispatch(request, response).then((matched) => {
71
+ if (!matched) {
72
+ sendJson(response, 404, { error: `no route ${path}` });
73
+ }
74
+ }, (error) => {
75
+ this.log.error(`${request.method ?? ''} ${path} failed`, error);
76
+ if (!response.headersSent) {
77
+ sendJson(response, 500, { error: 'internal error' });
78
+ }
79
+ });
80
+ return;
81
+ }
82
+ serveStatic(options.uiDir ?? UI_DIST, path, response).catch((error) => {
83
+ this.log.error(`serving ${path} failed`, error);
84
+ });
85
+ });
86
+ this.http.on('upgrade', (request, socket, head) => {
87
+ const path = new URL(request.url ?? '/', 'http://localhost').pathname;
88
+ if (path === '/api/events' && !this.auth.check(request)) {
89
+ socket.end('HTTP/1.1 401 Unauthorized\r\nConnection: close\r\nContent-Length: 0\r\n\r\n');
90
+ }
91
+ else if (path === '/api/events') {
92
+ this.hub.upgrade(request, socket, head);
93
+ }
94
+ else {
95
+ socket.destroy();
96
+ }
97
+ });
98
+ this.routes();
99
+ }
100
+ /** the bound port */
101
+ get port() {
102
+ const address = this.http.address();
103
+ return address?.port ?? 0;
104
+ }
105
+ async listen() {
106
+ const host = this.options.host ?? '0.0.0.0';
107
+ await new Promise((resolveListen, reject) => {
108
+ this.http.once('error', reject);
109
+ this.http.listen(this.options.port ?? 0, host, () => {
110
+ this.http.off('error', reject);
111
+ resolveListen();
112
+ });
113
+ });
114
+ this.log.info(`listening on http://${host}:${this.port}`);
115
+ }
116
+ /** wire the running application: the topic subscriptions, the events of the built devices */
117
+ async start() {
118
+ for (const topic of this.options.topics ?? []) {
119
+ try {
120
+ await this.app.mqtt.subscribe(topic);
121
+ }
122
+ catch (error) {
123
+ this.log.warn(`subscribing ${topic} for the UI failed: ${String(error)}`);
124
+ }
125
+ }
126
+ for (const importer of this.importers()) {
127
+ for (const topic of importer.topics) {
128
+ try {
129
+ await this.app.mqtt.subscribe(topic);
130
+ }
131
+ catch (error) {
132
+ this.log.warn(`subscribing ${topic} for ${importer.kind} failed: ${String(error)}`);
133
+ }
134
+ }
135
+ importer.load(this.app.mqtt.cache);
136
+ }
137
+ const onMessage = (topic, payload, retain) => {
138
+ this.hub.broadcast({
139
+ type: 'mqtt',
140
+ topic,
141
+ payload: payload.toString('utf8').slice(0, 16_384),
142
+ retain,
143
+ ts: Date.now(),
144
+ });
145
+ for (const importer of this.importers()) {
146
+ if (importer.handle(topic, payload)) {
147
+ this.hub.broadcast({ type: 'discovered' });
148
+ }
149
+ }
150
+ };
151
+ this.app.mqtt.on('message', onMessage);
152
+ this.unsubscribe.push(() => {
153
+ this.app.mqtt.off('message', onMessage);
154
+ });
155
+ const onConnect = () => {
156
+ this.hub.broadcast({ type: 'status', mqtt: true });
157
+ };
158
+ const onClose = () => {
159
+ this.hub.broadcast({ type: 'status', mqtt: false });
160
+ };
161
+ this.app.mqtt.on('connect', onConnect);
162
+ this.app.mqtt.on('close', onClose);
163
+ this.unsubscribe.push(() => {
164
+ this.app.mqtt.off('connect', onConnect);
165
+ this.app.mqtt.off('close', onClose);
166
+ });
167
+ this.unsubscribe.push(this.options.logBuffer.onEntry((entry) => {
168
+ this.hub.broadcast({ type: 'log', entry });
169
+ }));
170
+ for (const [key, handle] of this.app.nodes.handles()) {
171
+ this.observe(key, handle);
172
+ }
173
+ for (const bridge of this.app.nodes.allBridges()) {
174
+ const node = bridge.serverNode;
175
+ if (node === undefined) {
176
+ continue;
177
+ }
178
+ const notify = () => {
179
+ this.hub.broadcast({ type: 'bridges' });
180
+ };
181
+ node.events.commissioning.commissioned.on(notify);
182
+ node.events.commissioning.decommissioned.on(notify);
183
+ node.events.commissioning.fabricsChanged.on(notify);
184
+ this.unsubscribe.push(() => {
185
+ node.events.commissioning.commissioned.off(notify);
186
+ node.events.commissioning.decommissioned.off(notify);
187
+ node.events.commissioning.fabricsChanged.off(notify);
188
+ });
189
+ }
190
+ }
191
+ async close() {
192
+ for (const off of this.unsubscribe.splice(0)) {
193
+ off();
194
+ }
195
+ for (const key of [...this.observers.keys()]) {
196
+ this.unobserve(key);
197
+ }
198
+ this.hub.close();
199
+ await new Promise((resolveClose) => {
200
+ this.http.close(() => {
201
+ resolveClose();
202
+ });
203
+ this.http.closeAllConnections();
204
+ });
205
+ }
206
+ /** every attribute change of a device's endpoints goes to the event stream */
207
+ observe(key, handle) {
208
+ this.unobserve(key);
209
+ const offs = [];
210
+ for (const [endpointId, endpoint] of handle.endpoints) {
211
+ const clusters = new Map([...endpoint.built.clusters].map(([cluster, behaviorId]) => [behaviorId, cluster]));
212
+ const events = endpoint.endpoint.events;
213
+ for (const [behaviorId, attributes] of Object.entries(endpoint.state)) {
214
+ const cluster = clusters.get(behaviorId) ?? behaviorId;
215
+ for (const attribute of Object.keys(attributes)) {
216
+ if (GLOBAL_ATTRIBUTES.has(attribute)) {
217
+ continue;
218
+ }
219
+ const observable = events[behaviorId]?.[`${attribute}$Changed`];
220
+ if (observable === undefined || typeof observable.on !== 'function') {
221
+ continue;
222
+ }
223
+ const listener = (value) => {
224
+ this.hub.broadcast({ type: 'attribute', key, endpoint: endpointId, cluster, attribute, value });
225
+ };
226
+ observable.on(listener);
227
+ offs.push(() => {
228
+ observable.off(listener);
229
+ });
230
+ }
231
+ }
232
+ }
233
+ this.observers.set(key, offs);
234
+ }
235
+ unobserve(key) {
236
+ for (const off of this.observers.get(key) ?? []) {
237
+ off();
238
+ }
239
+ this.observers.delete(key);
240
+ }
241
+ // ── the device list and one device ────────────────────────────────────────────────────────────
242
+ placement() {
243
+ const map = new Map();
244
+ for (const info of this.app.nodes.info()) {
245
+ for (const device of info.devices) {
246
+ map.set(device.key, { bridge: info.id, number: device.number, violations: device.violations });
247
+ }
248
+ }
249
+ return map;
250
+ }
251
+ listDevices() {
252
+ const placement = this.placement();
253
+ const handles = this.app.nodes.handles();
254
+ return Object.entries(this.app.config.devices).map(([key, device]) => {
255
+ const placed = placement.get(key);
256
+ const handle = handles.get(key);
257
+ const result = validateDevice(device);
258
+ const reachable = handle?.state.bridgedDeviceBasicInformation?.reachable;
259
+ return {
260
+ key,
261
+ name: device.name,
262
+ enabled: device.enabled,
263
+ deviceTypes: device.endpoints[0]?.deviceTypes ?? [],
264
+ endpoints: device.endpoints.length,
265
+ source: device.source,
266
+ bridge: placed?.bridge ?? device.bridge,
267
+ number: placed?.number,
268
+ reachable: typeof reachable === 'boolean' ? reachable : undefined,
269
+ built: handle !== undefined,
270
+ violations: placed?.violations ?? 0,
271
+ errors: result.errors.length,
272
+ warnings: result.warnings.length,
273
+ };
274
+ });
275
+ }
276
+ deviceJson(key) {
277
+ const device = this.app.config.devices[key];
278
+ if (device === undefined) {
279
+ throw new HttpError(404, `no device ${key}`);
280
+ }
281
+ const handle = this.app.nodes.handle(key);
282
+ const issues = [...validateDevice(device).issues];
283
+ for (const { endpointId, violation } of handle?.violations() ?? []) {
284
+ issues.push({
285
+ level: 'warning',
286
+ path: `endpoints[${device.endpoints.findIndex((e) => e.id === endpointId)}]`,
287
+ message: `${violation.deviceType}: ${violation.kind} ${violation.requirement} — ${violation.detail}`,
288
+ });
289
+ }
290
+ return {
291
+ key,
292
+ device,
293
+ issues,
294
+ built: handle !== undefined,
295
+ bridge: this.placement().get(key)?.bridge ?? device.bridge,
296
+ number: handle?.number,
297
+ state: handle === undefined ? undefined : this.stateJson(handle),
298
+ };
299
+ }
300
+ stateJson(handle) {
301
+ const out = {};
302
+ for (const [id, endpoint] of handle.endpoints) {
303
+ const state = {};
304
+ const clusters = new Map([...endpoint.built.clusters].map(([cluster, behaviorId]) => [behaviorId, cluster]));
305
+ for (const [behaviorId, attributes] of Object.entries(endpoint.state)) {
306
+ const cluster = clusters.get(behaviorId);
307
+ if (cluster === undefined) {
308
+ continue;
309
+ }
310
+ state[cluster] = Object.fromEntries(Object.entries(attributes).filter(([name]) => !GLOBAL_ATTRIBUTES.has(name)));
311
+ }
312
+ out[id] = { number: endpoint.number, state };
313
+ }
314
+ return out;
315
+ }
316
+ /** save a device (compact in the file, parsed in the app), build it, tell the clients */
317
+ async saveDevice(key, raw) {
318
+ const parsed = DeviceSchema.safeParse(raw);
319
+ if (!parsed.success) {
320
+ throw new HttpError(400, 'the device is invalid', {
321
+ issues: parsed.error.issues.map((issue) => ({
322
+ level: 'error',
323
+ path: issue.path.map(String).join('.'),
324
+ message: issue.message,
325
+ })),
326
+ });
327
+ }
328
+ const device = parsed.data;
329
+ await this.store.saveDevice(key, compactDevice(device));
330
+ const handle = await this.app.applyDevice(key, device);
331
+ this.unobserve(key);
332
+ if (handle !== undefined) {
333
+ this.observe(key, handle);
334
+ }
335
+ this.hub.broadcast({ type: 'devices' });
336
+ return this.deviceJson(key);
337
+ }
338
+ async removeDevice(key) {
339
+ if (this.app.config.devices[key] === undefined) {
340
+ throw new HttpError(404, `no device ${key}`);
341
+ }
342
+ this.unobserve(key);
343
+ await this.store.deleteDevice(key);
344
+ await this.app.removeDevice(key);
345
+ this.hub.broadcast({ type: 'devices' });
346
+ }
347
+ // ── bridges ────────────────────────────────────────────────────────────────────────────────────
348
+ bridgesJson() {
349
+ return this.app.nodes.allBridges().map((bridge) => {
350
+ const node = bridge.serverNode;
351
+ const fabrics = node === undefined
352
+ ? []
353
+ : node.env.get(FabricManager).map((f) => ({
354
+ index: Number(f.fabricIndex),
355
+ label: f.label,
356
+ vendorId: f.rootVendorId,
357
+ nodeId: String(f.nodeId),
358
+ fabricId: String(f.fabricId),
359
+ }));
360
+ let windowStatus = 0;
361
+ if (node !== undefined) {
362
+ try {
363
+ windowStatus = node.env.get(DeviceCommissioner).windowStatus;
364
+ }
365
+ catch {
366
+ windowStatus = 0;
367
+ }
368
+ }
369
+ const info = bridge.info();
370
+ return {
371
+ id: info.id,
372
+ port: info.port,
373
+ online: info.online,
374
+ commissioned: info.commissioned,
375
+ pairingCodes: info.pairingCodes,
376
+ devices: info.devices.length,
377
+ fabrics,
378
+ windowStatus,
379
+ };
380
+ });
381
+ }
382
+ bridgeNode(id) {
383
+ const bridge = this.app.nodes.bridge(id);
384
+ if (bridge === undefined) {
385
+ throw new HttpError(404, `no bridge ${id}`);
386
+ }
387
+ const node = bridge.serverNode;
388
+ if (node === undefined) {
389
+ throw new HttpError(409, `bridge ${id} is not running`);
390
+ }
391
+ return node;
392
+ }
393
+ // ── adopt ──────────────────────────────────────────────────────────────────────────────────────
394
+ importers() {
395
+ return this.options.importers ?? [];
396
+ }
397
+ importer(kind) {
398
+ const importer = this.importers().find((i) => i.kind === kind);
399
+ if (importer === undefined) {
400
+ throw new HttpError(404, `no importer ${kind}`);
401
+ }
402
+ return importer;
403
+ }
404
+ /** the importers' reports over the file's devices, each entry tagged with its importer */
405
+ adoptReport() {
406
+ const devices = this.store.rawDevices;
407
+ return this.importers().flatMap((importer) => importer.diff(devices).map((entry) => ({ ...entry, importer: importer.kind })));
408
+ }
409
+ /** write the devices an adoption changed into the file and the bridge; returns the keys written */
410
+ async applyAdoption(before, after, only) {
411
+ const written = [];
412
+ for (const [key, device] of Object.entries(after)) {
413
+ if (only !== undefined && !only.has(key)) {
414
+ continue;
415
+ }
416
+ if (JSON.stringify(before[key]) === JSON.stringify(device)) {
417
+ continue;
418
+ }
419
+ await this.saveDevice(key, device);
420
+ written.push(key);
421
+ }
422
+ return written;
423
+ }
424
+ // ── authentication ─────────────────────────────────────────────────────────────────────────────
425
+ authRoutes() {
426
+ const r = this.router;
427
+ r.add('GET', '/api/auth', (request) => this.auth.state(request.raw));
428
+ r.add('POST', '/api/auth/login', async (request, response) => {
429
+ if (this.auth.mode !== 'password') {
430
+ throw new HttpError(400, `there is no password login in ${this.auth.mode} mode`);
431
+ }
432
+ const address = request.raw.socket.remoteAddress ?? '';
433
+ if (this.auth.throttled(address)) {
434
+ throw new HttpError(429, 'too many failed logins; try again in a few minutes');
435
+ }
436
+ const password = body(request).password;
437
+ const token = typeof password === 'string' ? await this.auth.login(password, address) : undefined;
438
+ if (token === undefined) {
439
+ this.log.warn(`failed login from ${address}`);
440
+ throw new HttpError(401, 'wrong password');
441
+ }
442
+ response.setHeader('set-cookie', this.auth.cookie(request.raw, token));
443
+ return { mode: this.auth.mode, authenticated: true };
444
+ });
445
+ r.add('POST', '/api/auth/logout', (request, response) => {
446
+ this.auth.logout(request.raw);
447
+ response.setHeader('set-cookie', this.auth.cookie(request.raw, undefined));
448
+ return { mode: this.auth.mode, authenticated: this.auth.mode !== 'password' && this.auth.check(request.raw) };
449
+ });
450
+ // the access settings, applied at once and written to the file (behind the login like every other route)
451
+ r.add('PUT', '/api/auth', async (request, response) => {
452
+ const b = body(request);
453
+ const mode = b.mode;
454
+ if (mode !== 'none' && mode !== 'password' && mode !== 'proxy') {
455
+ throw new HttpError(400, 'mode is none, password or proxy');
456
+ }
457
+ const settings = this.store.rawSettings();
458
+ const server = isRecord(settings.server) ? { ...settings.server } : {};
459
+ const current = isRecord(server.auth) ? server.auth : {};
460
+ const raw = { mode };
461
+ for (const key of ['proxyHeader', 'proxyLogoutUrl', 'sessionHours']) {
462
+ const value = b[key] === undefined ? current[key] : b[key];
463
+ if (value !== undefined && value !== '' && value !== null) {
464
+ raw[key] = value;
465
+ }
466
+ }
467
+ let hash = this.auth.passwordHash;
468
+ if (typeof b.password === 'string' && b.password !== '') {
469
+ hash = await hashPassword(b.password);
470
+ }
471
+ if (mode === 'password') {
472
+ if (hash === undefined) {
473
+ throw new HttpError(400, 'password mode needs a password');
474
+ }
475
+ raw.password = hash;
476
+ }
477
+ const parsed = AuthConfigSchema.safeParse(raw);
478
+ if (!parsed.success) {
479
+ throw new HttpError(400, `the access settings are invalid: ${parsed.error.issues[0]?.message ?? ''}`);
480
+ }
481
+ // the request that switches to proxy mode must already come through the proxy
482
+ const header = parsed.data.proxyHeader;
483
+ if (mode === 'proxy' && request.raw.headers[header.toLowerCase()] === undefined) {
484
+ throw new HttpError(409, `this request does not carry ${header}: in proxy mode the UI would lock you out`);
485
+ }
486
+ server.auth = raw;
487
+ settings.server = server;
488
+ await this.store.saveSettings(settings);
489
+ this.auth.reconfigure(parsed.data, mode === 'password' ? hash : undefined);
490
+ this.log.info(`access: ${mode}`);
491
+ if (mode === 'password') {
492
+ // whoever set the password stays logged in
493
+ response.setHeader('set-cookie', this.auth.cookie(request.raw, this.auth.newSession()));
494
+ }
495
+ return { mode, authenticated: true };
496
+ });
497
+ }
498
+ // ── the routes ─────────────────────────────────────────────────────────────────────────────────
499
+ routes() {
500
+ const r = this.router;
501
+ r.add('GET', '/api/status', () => ({
502
+ version: this.options.version,
503
+ uptime: Math.round((Date.now() - this.startedAt) / 1000),
504
+ running: this.app.running,
505
+ configPath: this.store.path,
506
+ mqtt: { url: this.app.config.mqtt.url, connected: this.app.mqtt.connected },
507
+ bridges: this.bridgesJson(),
508
+ devices: Object.keys(this.app.config.devices).length,
509
+ importers: this.importers().map((i) => i.kind),
510
+ update: this.updater.known,
511
+ }));
512
+ r.add('GET', '/api/update', async (request) => {
513
+ await this.updater.check(request.query.get('check') === '1');
514
+ return await this.updater.status();
515
+ });
516
+ r.add('POST', '/api/update', async (request) => {
517
+ const version = body(request).version;
518
+ const reason = await this.updater.request(typeof version === 'string' ? version : '');
519
+ if (reason !== undefined) {
520
+ throw new HttpError(409, reason);
521
+ }
522
+ this.log.info(`update to ${String(version)} requested`);
523
+ return { requested: version };
524
+ });
525
+ r.add('POST', '/api/restart', () => {
526
+ const reason = this.updater.restartReason;
527
+ if (reason !== undefined) {
528
+ throw new HttpError(409, reason);
529
+ }
530
+ this.log.info('restart requested from the UI');
531
+ setTimeout(() => this.options.onRestart?.(), 300).unref();
532
+ return { restarting: true };
533
+ });
534
+ r.add('GET', '/api/config', () => ({
535
+ path: this.store.path,
536
+ settings: this.store.rawSettings(),
537
+ overridden: this.store.overridden,
538
+ effective: {
539
+ mqtt: {
540
+ ...this.app.config.mqtt,
541
+ password: this.app.config.mqtt.password === undefined ? undefined : '***',
542
+ },
543
+ storage: this.app.config.storage,
544
+ log: this.app.config.log,
545
+ vendorId: this.app.config.vendorId,
546
+ productId: this.app.config.productId,
547
+ bridges: this.app.config.bridges,
548
+ server: {
549
+ ...this.app.config.server,
550
+ auth: this.auth.view(),
551
+ },
552
+ presets: this.app.config.presets,
553
+ importers: this.app.config.importers,
554
+ },
555
+ }));
556
+ r.add('PUT', '/api/config', async (request) => {
557
+ await this.store.saveSettings(request.body);
558
+ return { saved: true, restartNeeded: true };
559
+ });
560
+ this.authRoutes();
561
+ r.add('GET', '/api/devices', () => this.listDevices());
562
+ r.add('GET', '/api/devices/:key', (request) => this.deviceJson(request.params.key ?? ''));
563
+ r.add('PUT', '/api/devices/:key', async (request) => {
564
+ return await this.saveDevice(request.params.key ?? '', request.body);
565
+ });
566
+ r.add('DELETE', '/api/devices/:key', async (request) => {
567
+ await this.removeDevice(request.params.key ?? '');
568
+ });
569
+ r.add('GET', '/api/devices/:key/state', (request) => {
570
+ const key = request.params.key ?? '';
571
+ const handle = this.app.nodes.handle(key);
572
+ if (handle === undefined) {
573
+ throw new HttpError(404, `device ${key} is not built`);
574
+ }
575
+ return this.stateJson(handle);
576
+ });
577
+ r.add('POST', '/api/validate', (request) => {
578
+ const parsed = DeviceSchema.safeParse(body(request).device);
579
+ if (!parsed.success) {
580
+ return {
581
+ ok: false,
582
+ issues: parsed.error.issues.map((issue) => ({
583
+ level: 'error',
584
+ path: issue.path.map(String).join('.'),
585
+ message: issue.message,
586
+ })),
587
+ };
588
+ }
589
+ const result = validateDevice(parsed.data);
590
+ return { ok: result.ok, issues: result.issues };
591
+ });
592
+ r.add('POST', '/api/check', async (request) => {
593
+ const wanted = body(request).devices;
594
+ let devices = this.app.config.devices;
595
+ if (isRecord(wanted)) {
596
+ devices = {};
597
+ for (const [key, raw] of Object.entries(wanted)) {
598
+ const parsed = DeviceSchema.safeParse(raw);
599
+ if (!parsed.success) {
600
+ throw new HttpError(400, `device ${key} is invalid`, { issues: parsed.error.issues });
601
+ }
602
+ devices[key] = parsed.data;
603
+ }
604
+ }
605
+ const result = await checkConfig({ ...this.app.config, devices });
606
+ return { ok: result.ok, devices: Object.fromEntries(result.devices) };
607
+ });
608
+ r.add('POST', '/api/preview', (request) => {
609
+ const b = body(request);
610
+ const attribute = typeof b.attribute === 'string' ? b.attribute : undefined;
611
+ if (b.direction === 'status') {
612
+ const payload = typeof b.payload === 'string' ? b.payload : JSON.stringify(b.payload ?? '');
613
+ return previewStatus(b.half, payload, attribute, typeof b.topic === 'string' ? b.topic : undefined);
614
+ }
615
+ if (b.direction === 'command') {
616
+ return previewCommand(b.half, b.value, attribute, isRecord(b.fields) ? b.fields : {});
617
+ }
618
+ throw new HttpError(400, 'direction is "status" or "command"');
619
+ });
620
+ r.add('POST', '/api/publish', async (request) => {
621
+ const b = body(request);
622
+ if (typeof b.topic !== 'string' || b.topic === '') {
623
+ throw new HttpError(400, 'topic is required');
624
+ }
625
+ const payload = typeof b.payload === 'string' ? b.payload : JSON.stringify(b.payload ?? '');
626
+ const qos = b.qos === 1 || b.qos === 2 ? b.qos : 0;
627
+ await this.app.mqtt.publish(b.topic, payload, { retain: b.retain === true, qos });
628
+ return { published: true };
629
+ });
630
+ r.add('GET', '/api/topics', (request) => {
631
+ const prefix = request.query.get('prefix') ?? '';
632
+ return this.app.mqtt.cache
633
+ .topics()
634
+ .filter((topic) => topic.startsWith(prefix))
635
+ .sort()
636
+ .map((topic) => {
637
+ const message = this.app.mqtt.cache.get(topic);
638
+ return {
639
+ topic,
640
+ payload: message?.payload.toString('utf8').slice(0, 16_384) ?? '',
641
+ retain: message?.retain ?? false,
642
+ ts: message?.ts ?? 0,
643
+ };
644
+ });
645
+ });
646
+ r.add('GET', '/api/catalog', () => catalogJson());
647
+ r.add('GET', '/api/catalog/clusters/:name', (request) => clusterJson(request.params.name ?? ''));
648
+ r.add('GET', '/api/presets', async () => {
649
+ const library = await loadPresets(this.app.config.presets);
650
+ return {
651
+ presets: library.presets.map(({ preset, file, shipped }) => ({
652
+ id: preset.id,
653
+ name: preset.name,
654
+ description: preset.description,
655
+ vendor: preset.vendor,
656
+ variables: preset.variables,
657
+ shipped,
658
+ file,
659
+ })),
660
+ problems: library.problems,
661
+ };
662
+ });
663
+ r.add('POST', '/api/presets/:id/apply', async (request) => {
664
+ const id = request.params.id ?? '';
665
+ const library = await loadPresets(this.app.config.presets);
666
+ const entry = library.presets.find((p) => p.preset.id === id);
667
+ if (entry === undefined) {
668
+ throw new HttpError(404, `no preset ${id}`);
669
+ }
670
+ const values = body(request).values;
671
+ try {
672
+ const device = applyPreset(entry.preset, isRecord(values) ? Object.fromEntries(Object.entries(values).map(([k, v]) => [k, String(v)])) : {});
673
+ return { device, issues: validateDevice(device).issues };
674
+ }
675
+ catch (error) {
676
+ throw new HttpError(400, error.message);
677
+ }
678
+ });
679
+ r.add('GET', '/api/bridges', () => this.bridgesJson());
680
+ r.add('POST', '/api/bridges/:id/commissioning', async (request) => {
681
+ const node = this.bridgeNode(request.params.id ?? '');
682
+ const commissioner = node.env.get(DeviceCommissioner);
683
+ const b = body(request);
684
+ if (b.open === false) {
685
+ await commissioner.endCommissioning();
686
+ }
687
+ else {
688
+ const minutes = typeof b.minutes === 'number' && b.minutes > 0 ? Math.min(b.minutes, 15) : 15;
689
+ await commissioner.allowBasicCommissioning({ timeout: Minutes(minutes) });
690
+ }
691
+ this.hub.broadcast({ type: 'bridges' });
692
+ return this.bridgesJson().find((bridge) => bridge.id === request.params.id);
693
+ });
694
+ r.add('DELETE', '/api/bridges/:id/fabrics/:index', async (request) => {
695
+ const node = this.bridgeNode(request.params.id ?? '');
696
+ const index = Number(request.params.index);
697
+ const fabric = node.env.get(FabricManager).find((f) => Number(f.fabricIndex) === index);
698
+ if (fabric === undefined) {
699
+ throw new HttpError(404, `no fabric ${index}`);
700
+ }
701
+ await fabric.delete();
702
+ this.hub.broadcast({ type: 'bridges' });
703
+ });
704
+ r.add('GET', '/api/adopt', () => ({
705
+ importers: this.importers().map((i) => i.kind),
706
+ entries: this.adoptReport(),
707
+ }));
708
+ r.add('POST', '/api/adopt/resync', async () => {
709
+ const written = [];
710
+ for (const importer of this.importers()) {
711
+ const before = structuredClone(this.store.rawDevices);
712
+ const { devices } = importer.adopt(before, { keys: [], resync: true, orphan: true });
713
+ written.push(...(await this.applyAdoption(before, devices)));
714
+ }
715
+ return { importers: this.importers().map((i) => i.kind), entries: this.adoptReport(), written };
716
+ });
717
+ r.add('POST', '/api/adopt/:kind/:key', async (request) => {
718
+ const importer = this.importer(request.params.kind ?? '');
719
+ const key = request.params.key ?? '';
720
+ const b = body(request);
721
+ const force = b.force === true;
722
+ const replace = force && b.replace === true;
723
+ const before = structuredClone(this.store.rawDevices);
724
+ const { devices, report } = importer.adopt(before, {
725
+ keys: [key],
726
+ resync: true,
727
+ orphan: false,
728
+ force,
729
+ replace,
730
+ });
731
+ const entry = report.find((e) => e.key === key);
732
+ if (entry === undefined) {
733
+ throw new HttpError(404, `${importer.kind} does not know ${key}`);
734
+ }
735
+ if (entry.status === 'unsupported' || entry.status === 'invalid') {
736
+ throw new HttpError(409, `${key} cannot be adopted: ${entry.notes.join('; ')}`);
737
+ }
738
+ if (entry.status === 'covered' && !force) {
739
+ throw new HttpError(409, `${key} is the same device as ${entry.covered ?? '?'}: adopting it makes a second Matter device ` +
740
+ '(force: true adopts it anyway, replace: true also disables the twin)', { covered: entry.covered, twins: entry.twins ?? [] });
741
+ }
742
+ await this.applyAdoption(before, devices, new Set([key, ...(replace ? (entry.twins ?? []) : [])]));
743
+ return { ...this.deviceJson(key), entry };
744
+ });
745
+ r.add('GET', '/api/export', (request, response) => {
746
+ const key = request.query.get('device');
747
+ if (key !== null) {
748
+ const raw = this.store.rawDevice(key);
749
+ if (raw === undefined) {
750
+ throw new HttpError(404, `no device ${key}`);
751
+ }
752
+ response.setHeader('content-disposition', `attachment; filename="${key}.json"`);
753
+ return { [key]: raw };
754
+ }
755
+ response.setHeader('content-disposition', 'attachment; filename="mqtt2matter.json"');
756
+ return this.store.raw;
757
+ });
758
+ r.add('POST', '/api/import', async (request) => {
759
+ const b = body(request);
760
+ const devices = isRecord(b.devices)
761
+ ? b.devices
762
+ : isRecord(b.config)
763
+ ? b.config.devices
764
+ : undefined;
765
+ if (!isRecord(devices)) {
766
+ throw new HttpError(400, 'expected {devices: {...}} or {config: {devices: {...}}}');
767
+ }
768
+ // an export of an earlier version imports as it is
769
+ migrateDevices(devices);
770
+ const parsed = new Map();
771
+ for (const [key, raw] of Object.entries(devices)) {
772
+ const result = DeviceSchema.safeParse(raw);
773
+ if (!result.success) {
774
+ throw new HttpError(400, `device ${key} is invalid`, {
775
+ issues: result.error.issues.map((issue) => ({
776
+ level: 'error',
777
+ path: `${key}.${issue.path.map(String).join('.')}`,
778
+ message: issue.message,
779
+ })),
780
+ });
781
+ }
782
+ parsed.set(key, result.data);
783
+ }
784
+ if (b.replace === true) {
785
+ for (const key of Object.keys(this.app.config.devices)) {
786
+ if (!parsed.has(key)) {
787
+ this.unobserve(key);
788
+ await this.app.removeDevice(key);
789
+ }
790
+ }
791
+ }
792
+ let written = 0;
793
+ for (const [key, device] of parsed) {
794
+ await this.saveDevice(key, device);
795
+ written++;
796
+ }
797
+ if (b.replace === true) {
798
+ await this.store.replaceDevices(Object.fromEntries([...parsed].map(([key, device]) => [key, compactDevice(device)])));
799
+ }
800
+ this.hub.broadcast({ type: 'devices' });
801
+ return { imported: written };
802
+ });
803
+ r.add('GET', '/api/log', (request) => {
804
+ const limit = Number(request.query.get('limit') ?? 500);
805
+ const after = Number(request.query.get('after') ?? 0);
806
+ return this.options.logBuffer.list(Number.isFinite(limit) ? limit : 500, Number.isFinite(after) ? after : 0);
807
+ });
808
+ }
809
+ }
810
+ //# sourceMappingURL=server.js.map