@attraccess/plugin-shelly 0.2.0 → 0.3.0-nightly.1200.1

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.
@@ -15,10 +15,20 @@ var PluginApiError = class extends Error {
15
15
  this.name = "PluginApiError";
16
16
  }
17
17
  };
18
+ /**
19
+ * Joins validation messages into one text. Messages that already end a sentence are separated by a space, so
20
+ * "The URL is too long." and "The token is short." never become "long., token".
21
+ */
22
+ function joinErrorMessages(parts) {
23
+ return parts.map((part) => part.trim()).filter(Boolean).reduce((joined, part) => {
24
+ if (joined === "") return part;
25
+ return /[.!?]$/.test(joined) ? `${joined} ${part}` : `${joined}, ${part}`;
26
+ }, "");
27
+ }
18
28
  async function toError(res) {
19
29
  try {
20
30
  const body = await res.json();
21
- const message = Array.isArray(body.message) ? body.message.join(", ") : body.message;
31
+ const message = Array.isArray(body.message) ? joinErrorMessages(body.message) : body.message;
22
32
  if (message) return new PluginApiError(message, res.status);
23
33
  } catch {}
24
34
  return new PluginApiError(`Request failed (HTTP ${res.status}).`, res.status);
@@ -61,7 +71,7 @@ function createPluginApiClient(basePath = "") {
61
71
  };
62
72
  }
63
73
  // ../../../libs/plugins-frontend-sdk/src/lib/frontend.license.ts
64
- var { useCallback: useCallback$7, useEffect: useEffect$5, useState: useState$6 } = await importShared("react");
74
+ var { useCallback: useCallback$11, useEffect: useEffect$7, useState: useState$9 } = await importShared("react");
65
75
  // ../../../node_modules/.pnpm/react@19.3.1/node_modules/react/cjs/react-jsx-runtime.production.js
66
76
  /**
67
77
  * @license React
@@ -74,6 +84,7 @@ var { useCallback: useCallback$7, useEffect: useEffect$5, useState: useState$6 }
74
84
  */
75
85
  var require_react_jsx_runtime_production = /* @__PURE__ */ __commonJSMin(((exports) => {
76
86
  var REACT_ELEMENT_TYPE = Symbol.for("react.transitional.element");
87
+ var REACT_FRAGMENT_TYPE = Symbol.for("react.fragment");
77
88
  function jsxProd(type, config, maybeKey) {
78
89
  var key = null;
79
90
  void 0 !== maybeKey && (key = "" + maybeKey);
@@ -91,6 +102,7 @@ var require_react_jsx_runtime_production = /* @__PURE__ */ __commonJSMin(((expor
91
102
  props: maybeKey
92
103
  };
93
104
  }
105
+ exports.Fragment = REACT_FRAGMENT_TYPE;
94
106
  exports.jsx = jsxProd;
95
107
  exports.jsxs = jsxProd;
96
108
  }));
@@ -98,7 +110,7 @@ var require_react_jsx_runtime_production = /* @__PURE__ */ __commonJSMin(((expor
98
110
  var import_jsx_runtime = (/* @__PURE__ */ __commonJSMin(((exports, module) => {
99
111
  module.exports = require_react_jsx_runtime_production();
100
112
  })))();
101
- var { createContext, useCallback: useCallback$6, useContext, useEffect: useEffect$4, useRef: useRef$3 } = await importShared("react");
113
+ var { createContext, useCallback: useCallback$10, useContext, useEffect: useEffect$6, useRef: useRef$5 } = await importShared("react");
102
114
  var contextKey = Symbol.for("attraccess.plugin.live-updates.context");
103
115
  var contexts = globalThis;
104
116
  var LiveContext = contexts[contextKey] ??= createContext(null);
@@ -108,7 +120,7 @@ var IdentityContext = identities[identityKey] ??= createContext(null);
108
120
  function usePluginLiveUpdates(props) {
109
121
  const client = useContext(LiveContext);
110
122
  const plugin = useContext(IdentityContext) ?? props.plugin;
111
- const latest = useRef$3({
123
+ const latest = useRef$5({
112
124
  props,
113
125
  client,
114
126
  plugin
@@ -118,9 +130,9 @@ function usePluginLiveUpdates(props) {
118
130
  client,
119
131
  plugin
120
132
  };
121
- const unsubscribe = useRef$3(null);
133
+ const unsubscribe = useRef$5(null);
122
134
  const { topic, identifier, enabled = true } = props;
123
- useEffect$4(() => {
135
+ useEffect$6(() => {
124
136
  if (!client || !enabled) return;
125
137
  let active = true;
126
138
  const matches = () => active && latest.current.client === client && latest.current.props.enabled !== false && latest.current.plugin === plugin && latest.current.props.topic === topic && latest.current.props.identifier === identifier;
@@ -151,7 +163,7 @@ function usePluginLiveUpdates(props) {
151
163
  identifier,
152
164
  enabled
153
165
  ]);
154
- return { abort: useCallback$6(() => unsubscribe.current?.(), []) };
166
+ return { abort: useCallback$10(() => unsubscribe.current?.(), []) };
155
167
  }
156
168
  // ../../../libs/plugins-frontend-sdk/src/lib/frontend.standard-drawer.tsx
157
169
  var { StandardDrawer: SharedStandardDrawer } = await importShared("@attraccess/plugins-frontend-ui");
@@ -174,7 +186,7 @@ function reprobeDevice(id) {
174
186
  function deleteDevice(id) {
175
187
  return api.request(`/devices/${id}`, { method: "DELETE" });
176
188
  }
177
- function getDeviceInfo(id, input) {
189
+ function getDeviceInfo$1(id, input) {
178
190
  return api.request(`/devices/${id}/info`, {
179
191
  method: "POST",
180
192
  body: input ?? {}
@@ -197,7 +209,7 @@ function startFirmwareUpdate(id, input) {
197
209
  body: input
198
210
  });
199
211
  }
200
- function setAdminPassword(id, input) {
212
+ function setAdminPassword$1(id, input) {
201
213
  return api.request(`/devices/${id}/auth`, {
202
214
  method: "POST",
203
215
  body: input
@@ -215,14 +227,14 @@ function discoverDevices(input = {}) {
215
227
  });
216
228
  }
217
229
  // frontend/src/shared/TextFieldRow.tsx
218
- var { Input, Label, TextField } = await importShared("@heroui/react");
230
+ var { Input, Label: Label$2, TextField } = await importShared("@heroui/react");
219
231
  function TextFieldRow({ label, value, onChange, placeholder, required, description, dataCy }) {
220
232
  return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(TextField, {
221
233
  value,
222
234
  onChange,
223
235
  isRequired: required,
224
236
  children: [
225
- /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Label, { children: label }),
237
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Label$2, { children: label }),
226
238
  /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Input, {
227
239
  placeholder,
228
240
  autoComplete: "off",
@@ -258,7 +270,8 @@ var en_default = {
258
270
  "password": "Set admin password",
259
271
  "reprobe": "Re-probe device",
260
272
  "delete": "Delete device",
261
- "deleteDescription": "Remove {{name}} ({{address}}) from the registry? The device itself is not changed."
273
+ "deleteDescription": "Remove {{name}} ({{address}}) from the registry? The device itself is not changed.",
274
+ "bluetooth": "Set up over Bluetooth"
262
275
  },
263
276
  auth: {
264
277
  "none": "No auth",
@@ -360,6 +373,117 @@ var en_default = {
360
373
  "delete": "Delete",
361
374
  "done": "Done",
362
375
  "refresh": "Refresh"
376
+ },
377
+ ble: {
378
+ "title": "Set up over Bluetooth",
379
+ "description": "Connect to a factory-reset Shelly from this browser, give it Wi-Fi and an admin password, and add it to Attraccess.",
380
+ "unsupported": {
381
+ "title": "Bluetooth is not available here",
382
+ "noApi": "This browser cannot use Web Bluetooth. Open Attraccess in Chrome or Edge on a desktop or Android device.",
383
+ "insecure": "Web Bluetooth only works on HTTPS pages or on localhost. Open Attraccess over HTTPS.",
384
+ "alternatives": "You can still add the device with “Add device” if you know its IP address, or use “Discover” once it is on your network."
385
+ },
386
+ "start": {
387
+ "intro": "Stand next to the Shelly and make sure it is powered and factory reset. Works with Shelly Gen2, Gen3 and Gen4 devices. Gen1 devices cannot be set up over Bluetooth.",
388
+ "select": "Select device",
389
+ "connecting": "Connecting to the device…",
390
+ "hint": "Your browser opens a list of nearby Bluetooth devices. Pick the Shelly (its name starts with “Shelly”)."
391
+ },
392
+ "connect": {
393
+ "title": "Could not connect",
394
+ "noRpcService": "This device does not offer Shelly's Bluetooth RPC service. Gen1 devices never do. On some Gen2 firmware, enable “RPC over Bluetooth” in the device's web interface. Otherwise join it to Wi-Fi through its own access point, then use “Add device” or “Discover”.",
395
+ "adapterOff": "Bluetooth is switched off or missing on this computer. Switch it on and try again.",
396
+ "linkLost": "The Bluetooth connection could not be established. Move closer to the device and try again.",
397
+ "generic": "Could not talk to the device over Bluetooth."
398
+ },
399
+ "device": {
400
+ "model": "Model",
401
+ "generation": "Generation",
402
+ "id": "Device ID",
403
+ "mac": "MAC address",
404
+ "firmware": "Firmware"
405
+ },
406
+ "wifi": {
407
+ "title": "Wi-Fi network",
408
+ "description": "Pick the 2.4 GHz network the device should join.",
409
+ "scanning": "Scanning for networks — this can take several seconds…",
410
+ "scanFailed": "The device could not scan for networks. Enter the network name yourself.",
411
+ "scanFailedProtected": "The device could not scan for networks. If it already has an admin password, enter it below and press “Scan again”, or enter the network name yourself.",
412
+ "rescan": "Scan again",
413
+ "networks": "Networks seen by the device",
414
+ "other": "Other network (enter name)",
415
+ "ssid": "Network name (SSID)",
416
+ "password": "Wi-Fi password",
417
+ "passwordManualDescription": "Leave empty for an open network.",
418
+ "secured": "secured",
419
+ "open": "open",
420
+ "signal": "{{rssi}} dBm",
421
+ "none": "The device did not see any networks."
422
+ },
423
+ "admin": {
424
+ "new": "New admin password",
425
+ "newDescription": "Required. It protects the device before it joins the network. The username is “admin”.",
426
+ "current": "Current admin password",
427
+ "currentDescription": "This device already has an admin password. It is used to authenticate over Bluetooth and is not changed.",
428
+ "confirm": "Confirm admin password",
429
+ "mismatch": "The passwords do not match."
430
+ },
431
+ "name": {
432
+ "label": "Name (optional)",
433
+ "description": "Shown in Attraccess. Defaults to the Bluetooth name of the device."
434
+ },
435
+ "disable": {
436
+ "label": "Switch off Bluetooth on the device after setup",
437
+ "description": "Keep it on only if you use the device as a BLU or BTHome gateway. While Bluetooth is on, anyone nearby can try to connect."
438
+ },
439
+ "begin": "Start setup",
440
+ "validation": {
441
+ "ssid": "Choose or enter a Wi-Fi network.",
442
+ "wifiPassword": "Enter the Wi-Fi password.",
443
+ "adminPassword": "An admin password is required."
444
+ },
445
+ "secretsNote": "Wi-Fi and admin passwords go from this browser straight to the device over Bluetooth. They are not sent to Attraccess and not stored.",
446
+ "steps": {
447
+ "password": "Set the admin password",
448
+ "passwordCheck": "Check the admin password",
449
+ "wifi": "Configure Wi-Fi",
450
+ "join": "Wait for the device to join the network",
451
+ "register": "Add to Attraccess",
452
+ "bluetooth": "Switch off Bluetooth"
453
+ },
454
+ "stepStatus": {
455
+ "pending": "Not started",
456
+ "running": "In progress",
457
+ "done": "Done",
458
+ "skipped": "Skipped",
459
+ "failed": "Failed"
460
+ },
461
+ "failure": {
462
+ "title": "Setup failed at “{{step}}”",
463
+ "titleGeneric": "Setup failed",
464
+ "wrongPassword": "The device rejected the admin password. Check it and try again.",
465
+ "linkLost": "The Bluetooth connection was lost. Move closer to the device and start over. If the device already joined Wi-Fi, use “Discover” to add it.",
466
+ "joinTimeout": "The device did not get an IP address within 60 seconds (last status: {{status}}). Check the password, and that the network is 2.4 GHz — Shelly devices cannot join 5 GHz networks.",
467
+ "timeout": "The device did not answer over Bluetooth in time. Move closer and try again.",
468
+ "rpc": "The device refused the request: {{method}} returned “{{message}}” (code {{code}}).",
469
+ "registerFailed": "The device is on the network, but Attraccess could not add it ({{message}}). Use “Discover” or “Add device” to add it.",
470
+ "registerFailedNoDetail": "The device is on the network, but Attraccess could not add it. Use “Discover” or “Add device” to add it.",
471
+ "generic": "Something went wrong while talking to the device.",
472
+ "retry": "Start over"
473
+ },
474
+ "result": {
475
+ "title": "Device set up",
476
+ "name": "Name",
477
+ "ip": "IP address",
478
+ "passwordSet": "Admin password set",
479
+ "bluetoothOff": "Bluetooth switched off",
480
+ "bluetoothOn": "Bluetooth left on",
481
+ "bluetoothRefused": "The device refused to switch Bluetooth off. It is set up and registered; switch Bluetooth off in the device's web interface if you want to.",
482
+ "bluetoothUnknown": "The device did not confirm that Bluetooth is off. It is set up and registered; check Bluetooth in the device's web interface.",
483
+ "alreadyRegistered": "A device with the IP {{ip}} is already registered in Attraccess, so nothing was added.",
484
+ "restartTitle": "The device is restarting",
485
+ "restart": "Wi-Fi is set and the device is restarting. Once it is online, use “Discover” (or “Add device”) to add it. Bluetooth is left on."
486
+ }
363
487
  }
364
488
  };
365
489
  var de_default = {
@@ -385,7 +509,8 @@ var de_default = {
385
509
  "password": "Admin-Passwort festlegen",
386
510
  "reprobe": "Gerät erneut prüfen",
387
511
  "delete": "Gerät löschen",
388
- "deleteDescription": "{{name}} ({{address}}) aus der Registrierung entfernen? Das Gerät selbst wird nicht verändert."
512
+ "deleteDescription": "{{name}} ({{address}}) aus der Registrierung entfernen? Das Gerät selbst wird nicht verändert.",
513
+ "bluetooth": "Über Bluetooth einrichten"
389
514
  },
390
515
  auth: {
391
516
  "none": "Keine Authentifizierung",
@@ -487,6 +612,117 @@ var de_default = {
487
612
  "delete": "Löschen",
488
613
  "done": "Fertig",
489
614
  "refresh": "Aktualisieren"
615
+ },
616
+ ble: {
617
+ "title": "Über Bluetooth einrichten",
618
+ "description": "Verbinde dich von diesem Browser aus mit einem zurückgesetzten Shelly, richte WLAN und ein Admin-Passwort ein und füge ihn zu Attraccess hinzu.",
619
+ "unsupported": {
620
+ "title": "Bluetooth ist hier nicht verfügbar",
621
+ "noApi": "Dieser Browser unterstützt kein Web Bluetooth. Öffne Attraccess in Chrome oder Edge auf einem Desktop- oder Android-Gerät.",
622
+ "insecure": "Web Bluetooth funktioniert nur auf HTTPS-Seiten oder auf localhost. Öffne Attraccess über HTTPS.",
623
+ "alternatives": "Du kannst das Gerät trotzdem über „Gerät hinzufügen“ hinzufügen, wenn du seine IP-Adresse kennst, oder „Suchen“ nutzen, sobald es im Netzwerk ist."
624
+ },
625
+ "start": {
626
+ "intro": "Geh zum Shelly und stell sicher, dass er Strom hat und auf Werkseinstellungen zurückgesetzt ist. Funktioniert mit Shelly Gen2, Gen3 und Gen4. Gen1-Geräte lassen sich nicht über Bluetooth einrichten.",
627
+ "select": "Gerät auswählen",
628
+ "connecting": "Verbindung zum Gerät wird hergestellt…",
629
+ "hint": "Dein Browser zeigt eine Liste von Bluetooth-Geräten in der Nähe. Wähle den Shelly aus (sein Name beginnt mit „Shelly“)."
630
+ },
631
+ "connect": {
632
+ "title": "Verbindung fehlgeschlagen",
633
+ "noRpcService": "Dieses Gerät bietet Shellys Bluetooth-RPC-Dienst nicht an. Gen1-Geräte tun das nie. Aktiviere bei manchen Gen2-Firmwares „RPC über Bluetooth“ in der Weboberfläche des Geräts. Andernfalls verbinde es über seinen eigenen Access Point mit dem WLAN und nutze dann „Gerät hinzufügen“ oder „Suchen“.",
634
+ "adapterOff": "Bluetooth ist an diesem Computer ausgeschaltet oder nicht vorhanden. Schalte es ein und versuche es erneut.",
635
+ "linkLost": "Die Bluetooth-Verbindung konnte nicht hergestellt werden. Gehe näher an das Gerät heran und versuche es erneut.",
636
+ "generic": "Die Kommunikation mit dem Gerät über Bluetooth ist fehlgeschlagen."
637
+ },
638
+ "device": {
639
+ "model": "Modell",
640
+ "generation": "Generation",
641
+ "id": "Geräte-ID",
642
+ "mac": "MAC-Adresse",
643
+ "firmware": "Firmware"
644
+ },
645
+ "wifi": {
646
+ "title": "WLAN-Netzwerk",
647
+ "description": "Wähle das 2,4-GHz-Netzwerk, dem das Gerät beitreten soll.",
648
+ "scanning": "Suche nach Netzwerken – das kann einige Sekunden dauern…",
649
+ "scanFailed": "Das Gerät konnte nicht nach Netzwerken suchen. Gib den Netzwerknamen selbst ein.",
650
+ "scanFailedProtected": "Das Gerät konnte nicht nach Netzwerken suchen. Falls es schon ein Admin-Passwort hat, gib es unten ein und wähle „Erneut suchen“, oder gib den Netzwerknamen selbst ein.",
651
+ "rescan": "Erneut suchen",
652
+ "networks": "Vom Gerät gefundene Netzwerke",
653
+ "other": "Anderes Netzwerk (Name eingeben)",
654
+ "ssid": "Netzwerkname (SSID)",
655
+ "password": "WLAN-Passwort",
656
+ "passwordManualDescription": "Leer lassen für ein offenes Netzwerk.",
657
+ "secured": "gesichert",
658
+ "open": "offen",
659
+ "signal": "{{rssi}} dBm",
660
+ "none": "Das Gerät hat keine Netzwerke gefunden."
661
+ },
662
+ "admin": {
663
+ "new": "Neues Admin-Passwort",
664
+ "newDescription": "Erforderlich. Es schützt das Gerät, bevor es dem Netzwerk beitritt. Der Benutzername ist „admin“.",
665
+ "current": "Aktuelles Admin-Passwort",
666
+ "currentDescription": "Dieses Gerät hat bereits ein Admin-Passwort. Es wird zur Authentifizierung über Bluetooth verwendet und nicht geändert.",
667
+ "confirm": "Admin-Passwort bestätigen",
668
+ "mismatch": "Die Passwörter stimmen nicht überein."
669
+ },
670
+ "name": {
671
+ "label": "Name (optional)",
672
+ "description": "Wird in Attraccess angezeigt. Standard ist der Bluetooth-Name des Geräts."
673
+ },
674
+ "disable": {
675
+ "label": "Bluetooth am Gerät nach der Einrichtung ausschalten",
676
+ "description": "Lass es nur eingeschaltet, wenn du das Gerät als BLU- oder BTHome-Gateway nutzt. Solange Bluetooth an ist, kann jeder in der Nähe versuchen, sich zu verbinden."
677
+ },
678
+ "begin": "Einrichtung starten",
679
+ "validation": {
680
+ "ssid": "Wähle ein WLAN-Netzwerk oder gib eines ein.",
681
+ "wifiPassword": "Gib das WLAN-Passwort ein.",
682
+ "adminPassword": "Ein Admin-Passwort ist erforderlich."
683
+ },
684
+ "secretsNote": "WLAN- und Admin-Passwort gehen direkt von diesem Browser über Bluetooth an das Gerät. Sie werden nicht an Attraccess gesendet und nicht gespeichert.",
685
+ "steps": {
686
+ "password": "Admin-Passwort festlegen",
687
+ "passwordCheck": "Admin-Passwort prüfen",
688
+ "wifi": "WLAN konfigurieren",
689
+ "join": "Warten, bis das Gerät dem Netzwerk beigetreten ist",
690
+ "register": "Zu Attraccess hinzufügen",
691
+ "bluetooth": "Bluetooth ausschalten"
692
+ },
693
+ "stepStatus": {
694
+ "pending": "Nicht begonnen",
695
+ "running": "Läuft",
696
+ "done": "Erledigt",
697
+ "skipped": "Übersprungen",
698
+ "failed": "Fehlgeschlagen"
699
+ },
700
+ "failure": {
701
+ "title": "Einrichtung bei „{{step}}“ fehlgeschlagen",
702
+ "titleGeneric": "Einrichtung fehlgeschlagen",
703
+ "wrongPassword": "Das Gerät hat das Admin-Passwort abgelehnt. Prüfe es und versuche es erneut.",
704
+ "linkLost": "Die Bluetooth-Verbindung wurde unterbrochen. Gehe näher an das Gerät heran und beginne von vorn. Wenn das Gerät schon im WLAN ist, füge es über „Suchen“ hinzu.",
705
+ "joinTimeout": "Das Gerät hat innerhalb von 60 Sekunden keine IP-Adresse erhalten (letzter Status: {{status}}). Prüfe das Passwort und ob das Netzwerk 2,4 GHz nutzt – Shelly-Geräte können keinem 5-GHz-Netzwerk beitreten.",
706
+ "timeout": "Das Gerät hat nicht rechtzeitig über Bluetooth geantwortet. Gehe näher heran und versuche es erneut.",
707
+ "rpc": "Das Gerät hat die Anfrage abgelehnt: {{method}} lieferte „{{message}}“ (Code {{code}}).",
708
+ "registerFailed": "Das Gerät ist im Netzwerk, aber Attraccess konnte es nicht hinzufügen ({{message}}). Füge es über „Suchen“ oder „Gerät hinzufügen“ hinzu.",
709
+ "registerFailedNoDetail": "Das Gerät ist im Netzwerk, aber Attraccess konnte es nicht hinzufügen. Füge es über „Suchen“ oder „Gerät hinzufügen“ hinzu.",
710
+ "generic": "Bei der Kommunikation mit dem Gerät ist etwas schiefgelaufen.",
711
+ "retry": "Von vorn beginnen"
712
+ },
713
+ "result": {
714
+ "title": "Gerät eingerichtet",
715
+ "name": "Name",
716
+ "ip": "IP-Adresse",
717
+ "passwordSet": "Admin-Passwort festgelegt",
718
+ "bluetoothOff": "Bluetooth ausgeschaltet",
719
+ "bluetoothOn": "Bluetooth bleibt eingeschaltet",
720
+ "bluetoothRefused": "Das Gerät hat das Ausschalten von Bluetooth abgelehnt. Es ist eingerichtet und registriert; schalte Bluetooth bei Bedarf in der Weboberfläche des Geräts aus.",
721
+ "bluetoothUnknown": "Das Gerät hat nicht bestätigt, dass Bluetooth aus ist. Es ist eingerichtet und registriert; prüfe Bluetooth in der Weboberfläche des Geräts.",
722
+ "alreadyRegistered": "Ein Gerät mit der IP {{ip}} ist in Attraccess bereits registriert, daher wurde nichts hinzugefügt.",
723
+ "restartTitle": "Das Gerät startet neu",
724
+ "restart": "Das WLAN ist eingestellt und das Gerät startet neu. Sobald es online ist, füge es über „Suchen“ (oder „Gerät hinzufügen“) hinzu. Bluetooth bleibt eingeschaltet."
725
+ }
490
726
  }
491
727
  };
492
728
  // frontend/src/i18n.ts
@@ -496,19 +732,19 @@ var useShellyTranslations = () => useTranslations({
496
732
  de: de_default
497
733
  }, { escapeValues: false });
498
734
  // frontend/src/devices/AddDeviceDrawer.tsx
499
- var { DrawerBody: DrawerBody$4, DrawerHeader: DrawerHeader$4, DrawerHeading: DrawerHeading$4, Form: Form$3 } = await importShared("@heroui/react");
500
- var { PlusIcon: PlusIcon$2, XIcon: XIcon$4 } = await importShared("lucide-react");
501
- var { useCallback: useCallback$5, useRef: useRef$2, useState: useState$5 } = await importShared("react");
502
- var { Button: Button$8, StandardDrawer: StandardDrawer$4, StatusAlert: StatusAlert$5 } = await importShared("@attraccess/plugins-frontend-ui");
735
+ var { DrawerBody: DrawerBody$5, DrawerHeader: DrawerHeader$5, DrawerHeading: DrawerHeading$5, Form: Form$4 } = await importShared("@heroui/react");
736
+ var { PlusIcon: PlusIcon$2, XIcon: XIcon$5 } = await importShared("lucide-react");
737
+ var { useCallback: useCallback$9, useRef: useRef$4, useState: useState$8 } = await importShared("react");
738
+ var { Button: Button$11, StandardDrawer: StandardDrawer$5, StatusAlert: StatusAlert$11 } = await importShared("@attraccess/plugins-frontend-ui");
503
739
  function AddDeviceDrawer({ isOpen, onOpenChange, onAdded }) {
504
740
  const { t, tMessage } = useShellyTranslations();
505
- const [ipAddress, setIpAddress] = useState$5("");
506
- const [name, setName] = useState$5("");
507
- const [submitting, setSubmitting] = useState$5(false);
508
- const [error, setError] = useState$5(null);
509
- const close = useCallback$5(() => onOpenChange(false), [onOpenChange]);
510
- const inFlight = useRef$2(false);
511
- const submit = useCallback$5(async () => {
741
+ const [ipAddress, setIpAddress] = useState$8("");
742
+ const [name, setName] = useState$8("");
743
+ const [submitting, setSubmitting] = useState$8(false);
744
+ const [error, setError] = useState$8(null);
745
+ const close = useCallback$9(() => onOpenChange(false), [onOpenChange]);
746
+ const inFlight = useRef$4(false);
747
+ const submit = useCallback$9(async () => {
512
748
  if (inFlight.current) return;
513
749
  const ip = ipAddress.trim();
514
750
  if (!ip) {
@@ -539,28 +775,28 @@ function AddDeviceDrawer({ isOpen, onOpenChange, onAdded }) {
539
775
  onAdded,
540
776
  close
541
777
  ]);
542
- return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(StandardDrawer$4, {
778
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(StandardDrawer$5, {
543
779
  isOpen,
544
780
  onOpenChange,
545
- children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(DrawerHeader$4, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
781
+ children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(DrawerHeader$5, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
546
782
  className: "sh:flex sh:w-full sh:items-start sh:justify-between sh:gap-3",
547
783
  children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
548
784
  className: "sh:flex sh:flex-col sh:gap-1",
549
- children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(DrawerHeading$4, {
785
+ children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(DrawerHeading$5, {
550
786
  className: "sh:text-lg sh:font-semibold",
551
787
  children: t("add.title")
552
788
  }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", {
553
789
  className: "sh:text-sm sh:text-muted",
554
790
  children: t("add.description")
555
791
  })]
556
- }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button$8, {
792
+ }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button$11, {
557
793
  isIconOnly: true,
558
794
  variant: "ghost",
559
795
  "aria-label": t("common.close"),
560
796
  onPress: close,
561
- children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(XIcon$4, { size: 16 })
797
+ children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(XIcon$5, { size: 16 })
562
798
  })]
563
- }) }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DrawerBody$4, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Form$3, {
799
+ }) }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DrawerBody$5, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Form$4, {
564
800
  onSubmit: submit,
565
801
  className: "sh:flex sh:flex-col sh:gap-4",
566
802
  children: [
@@ -579,7 +815,7 @@ function AddDeviceDrawer({ isOpen, onOpenChange, onAdded }) {
579
815
  placeholder: t("add.placeholder"),
580
816
  dataCy: "shelly-add-name"
581
817
  }),
582
- error && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(StatusAlert$5, {
818
+ error && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(StatusAlert$11, {
583
819
  status: "danger",
584
820
  title: t("add.error"),
585
821
  "data-cy": "shelly-add-error",
@@ -587,11 +823,11 @@ function AddDeviceDrawer({ isOpen, onOpenChange, onAdded }) {
587
823
  }),
588
824
  /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
589
825
  className: "sh:flex sh:justify-end sh:gap-2 sh:pt-2",
590
- children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button$8, {
826
+ children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button$11, {
591
827
  variant: "secondary",
592
828
  onPress: close,
593
829
  children: t("common.cancel")
594
- }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Button$8, {
830
+ }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Button$11, {
595
831
  variant: "primary",
596
832
  type: "submit",
597
833
  isPending: submitting,
@@ -613,25 +849,25 @@ function AddDeviceDrawer({ isOpen, onOpenChange, onAdded }) {
613
849
  });
614
850
  }
615
851
  // frontend/src/AdminPasswordDrawer.tsx
616
- var { DrawerBody: DrawerBody$3, DrawerFooter: DrawerFooter$2, DrawerHeader: DrawerHeader$3, DrawerHeading: DrawerHeading$3, Form: Form$2 } = await importShared("@heroui/react");
617
- var { KeyRoundIcon: KeyRoundIcon$1, XIcon: XIcon$3 } = await importShared("lucide-react");
618
- var { useCallback: useCallback$4, useEffect: useEffect$3, useState: useState$4 } = await importShared("react");
619
- var { Button: Button$7, PasswordInput: PasswordInput$2, StandardDrawer: StandardDrawer$3, StatusAlert: StatusAlert$4 } = await importShared("@attraccess/plugins-frontend-ui");
852
+ var { DrawerBody: DrawerBody$4, DrawerFooter: DrawerFooter$3, DrawerHeader: DrawerHeader$4, DrawerHeading: DrawerHeading$4, Form: Form$3 } = await importShared("@heroui/react");
853
+ var { KeyRoundIcon: KeyRoundIcon$1, XIcon: XIcon$4 } = await importShared("lucide-react");
854
+ var { useCallback: useCallback$8, useEffect: useEffect$5, useState: useState$7 } = await importShared("react");
855
+ var { Button: Button$10, PasswordInput: PasswordInput$3, StandardDrawer: StandardDrawer$4, StatusAlert: StatusAlert$10 } = await importShared("@attraccess/plugins-frontend-ui");
620
856
  function AdminPasswordDrawer({ device, onOpenChange, onSaved }) {
621
857
  const { t, tMessage } = useShellyTranslations();
622
- const [currentPassword, setCurrentPassword] = useState$4("");
623
- const [password, setPassword] = useState$4("");
624
- const [submitting, setSubmitting] = useState$4(false);
625
- const [error, setError] = useState$4(null);
626
- useEffect$3(() => {
858
+ const [currentPassword, setCurrentPassword] = useState$7("");
859
+ const [password, setPassword] = useState$7("");
860
+ const [submitting, setSubmitting] = useState$7(false);
861
+ const [error, setError] = useState$7(null);
862
+ useEffect$5(() => {
627
863
  if (device) {
628
864
  setCurrentPassword("");
629
865
  setPassword("");
630
866
  setError(null);
631
867
  }
632
868
  }, [device]);
633
- const close = useCallback$4(() => onOpenChange(false), [onOpenChange]);
634
- const submit = useCallback$4(async () => {
869
+ const close = useCallback$8(() => onOpenChange(false), [onOpenChange]);
870
+ const submit = useCallback$8(async () => {
635
871
  if (!device) return;
636
872
  const nextPassword = password.trim();
637
873
  if (!nextPassword) {
@@ -641,7 +877,7 @@ function AdminPasswordDrawer({ device, onOpenChange, onSaved }) {
641
877
  setSubmitting(true);
642
878
  setError(null);
643
879
  try {
644
- await setAdminPassword(device.id, {
880
+ await setAdminPassword$1(device.id, {
645
881
  currentPassword: currentPassword || void 0,
646
882
  password: nextPassword
647
883
  });
@@ -659,21 +895,21 @@ function AdminPasswordDrawer({ device, onOpenChange, onSaved }) {
659
895
  onSaved,
660
896
  password
661
897
  ]);
662
- const onSubmit = useCallback$4((event) => {
898
+ const onSubmit = useCallback$8((event) => {
663
899
  event.preventDefault();
664
900
  submit();
665
901
  }, [submit]);
666
- return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(StandardDrawer$3, {
902
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(StandardDrawer$4, {
667
903
  isOpen: !!device,
668
904
  onOpenChange,
669
905
  children: [
670
- /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DrawerHeader$3, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
906
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DrawerHeader$4, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
671
907
  className: "sh:flex sh:w-full sh:items-start sh:justify-between sh:gap-3",
672
908
  children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
673
909
  className: "sh:flex sh:min-w-0 sh:flex-col sh:gap-1",
674
910
  children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
675
911
  className: "sh:flex sh:items-center sh:gap-2",
676
- children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(KeyRoundIcon$1, { className: "sh:h-5 sh:w-5 sh:shrink-0 sh:text-accent-soft-foreground" }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DrawerHeading$3, {
912
+ children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(KeyRoundIcon$1, { className: "sh:h-5 sh:w-5 sh:shrink-0 sh:text-accent-soft-foreground" }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DrawerHeading$4, {
677
913
  className: "sh:text-lg sh:font-semibold",
678
914
  children: t("password.title")
679
915
  })]
@@ -684,19 +920,19 @@ function AdminPasswordDrawer({ device, onOpenChange, onSaved }) {
684
920
  address: device.ipAddress
685
921
  })
686
922
  })]
687
- }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button$7, {
923
+ }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button$10, {
688
924
  isIconOnly: true,
689
925
  variant: "ghost",
690
926
  "aria-label": t("common.close"),
691
927
  onPress: close,
692
- children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(XIcon$3, { size: 16 })
928
+ children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(XIcon$4, { size: 16 })
693
929
  })]
694
930
  }) }),
695
- /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DrawerBody$3, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Form$2, {
931
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DrawerBody$4, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Form$3, {
696
932
  onSubmit,
697
933
  className: "sh:flex sh:flex-col sh:gap-4",
698
934
  children: [
699
- device?.authState === "required" && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(PasswordInput$2, {
935
+ device?.authState === "required" && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(PasswordInput$3, {
700
936
  label: t("password.current"),
701
937
  value: currentPassword,
702
938
  onChange: setCurrentPassword,
@@ -704,7 +940,7 @@ function AdminPasswordDrawer({ device, onOpenChange, onSaved }) {
704
940
  autoComplete: "current-password",
705
941
  "data-cy": "shelly-auth-current-password"
706
942
  }),
707
- /* @__PURE__ */ (0, import_jsx_runtime.jsx)(PasswordInput$2, {
943
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(PasswordInput$3, {
708
944
  label: t("password.new"),
709
945
  value: password,
710
946
  onChange: setPassword,
@@ -713,7 +949,7 @@ function AdminPasswordDrawer({ device, onOpenChange, onSaved }) {
713
949
  autoComplete: "new-password",
714
950
  "data-cy": "shelly-auth-password"
715
951
  }),
716
- error && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(StatusAlert$4, {
952
+ error && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(StatusAlert$10, {
717
953
  status: "danger",
718
954
  title: t("password.error"),
719
955
  "data-cy": "shelly-auth-error",
@@ -725,11 +961,11 @@ function AdminPasswordDrawer({ device, onOpenChange, onSaved }) {
725
961
  })
726
962
  ]
727
963
  }) }),
728
- /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DrawerFooter$2, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button$7, {
964
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DrawerFooter$3, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button$10, {
729
965
  variant: "secondary",
730
966
  onPress: close,
731
967
  children: t("common.cancel")
732
- }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Button$7, {
968
+ }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Button$10, {
733
969
  variant: "primary",
734
970
  isPending: submitting,
735
971
  onPress: () => void submit(),
@@ -743,6 +979,1204 @@ function AdminPasswordDrawer({ device, onOpenChange, onSaved }) {
743
979
  ]
744
980
  });
745
981
  }
982
+ // frontend/src/bluetooth/errors.ts
983
+ var ShellyBleError = class extends Error {
984
+ constructor(kind, message, data = {}) {
985
+ super(message);
986
+ this.kind = kind;
987
+ this.data = data;
988
+ this.name = "ShellyBleError";
989
+ }
990
+ };
991
+ /** Device messages are shown to the operator; a misbehaving device could send anything. */
992
+ var MAX_DEVICE_MESSAGE = 200;
993
+ function clip(message) {
994
+ return message.length > MAX_DEVICE_MESSAGE ? `${message.slice(0, MAX_DEVICE_MESSAGE)}…` : message;
995
+ }
996
+ /** The device answered an RPC call with an error object. */
997
+ var RpcError = class extends ShellyBleError {
998
+ constructor(method, code, deviceMessage) {
999
+ super("rpc", `${method} failed: ${clip(deviceMessage)} (code ${code ?? "?"})`, {
1000
+ method,
1001
+ code: code ?? 0,
1002
+ message: clip(deviceMessage)
1003
+ });
1004
+ this.method = method;
1005
+ this.code = code;
1006
+ this.name = "RpcError";
1007
+ this.deviceMessage = clip(deviceMessage);
1008
+ }
1009
+ };
1010
+ /** The device did not report an IP address in time; `lastStatus` is its last Wi-Fi status. */
1011
+ var JoinTimeoutError = class extends Error {
1012
+ constructor(lastStatus) {
1013
+ super(`The device did not get an IP address (last status: ${lastStatus})`);
1014
+ this.lastStatus = lastStatus;
1015
+ this.name = "JoinTimeoutError";
1016
+ }
1017
+ };
1018
+ /** A setup step failed; `cause` is the underlying (secret-free) error. */
1019
+ var SetupStepError = class extends Error {
1020
+ constructor(step, cause) {
1021
+ super(`Setup step "${step}" failed`);
1022
+ this.step = step;
1023
+ this.cause = cause;
1024
+ this.name = "SetupStepError";
1025
+ }
1026
+ };
1027
+ // frontend/src/bluetooth/gatt.ts
1028
+ var SHELLY_RPC_SERVICE = "5f6d4f53-5f52-5043-5f53-56435f49445f";
1029
+ var SHELLY_RPC_DATA = "5f6d4f53-5f52-5043-5f64-6174615f5f5f";
1030
+ var SHELLY_RPC_TX_CONTROL = "5f6d4f53-5f52-5043-5f74-785f63746c5f";
1031
+ var SHELLY_RPC_RX_CONTROL = "5f6d4f53-5f52-5043-5f72-785f63746c5f";
1032
+ function writeChunk(characteristic, value) {
1033
+ return characteristic.writeValueWithResponse ? characteristic.writeValueWithResponse(value) : characteristic.writeValue(value);
1034
+ }
1035
+ // frontend/src/bluetooth/digest.ts
1036
+ async function sha256Hex(value) {
1037
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(value));
1038
+ return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
1039
+ }
1040
+ /** `ha1` as stored by `Shelly.SetAuth`: sha256("<user>:<realm>:<password>"). */
1041
+ function computeHa1(username, realm, password) {
1042
+ return sha256Hex(`${username}:${realm}:${password}`);
1043
+ }
1044
+ /** A fresh client nonce per auth object, from the platform CSPRNG. */
1045
+ function randomCnonce() {
1046
+ return crypto.getRandomValues(/* @__PURE__ */ new Uint32Array(1))[0] & 2147483647;
1047
+ }
1048
+ async function buildRpcAuth(challenge, username, password, cnonce = randomCnonce(), nc = 1) {
1049
+ const ha1 = await computeHa1(username, challenge.realm, password);
1050
+ const ha2 = await sha256Hex("dummy_method:dummy_uri");
1051
+ const response = await sha256Hex(`${ha1}:${challenge.nonce}:${nc}:${cnonce}:auth:${ha2}`);
1052
+ return {
1053
+ realm: challenge.realm,
1054
+ username,
1055
+ nonce: challenge.nonce,
1056
+ cnonce,
1057
+ nc,
1058
+ algorithm: "SHA-256",
1059
+ response
1060
+ };
1061
+ }
1062
+ /** Reads the digest challenge out of a 401 error's message, or undefined when it is not one. */
1063
+ function parseChallenge(message) {
1064
+ if (!message) return void 0;
1065
+ try {
1066
+ const parsed = JSON.parse(message);
1067
+ if (parsed && typeof parsed.realm === "string" && parsed.nonce !== void 0) return {
1068
+ realm: parsed.realm,
1069
+ nonce: parsed.nonce,
1070
+ nc: parsed.nc,
1071
+ algorithm: parsed.algorithm
1072
+ };
1073
+ } catch {}
1074
+ }
1075
+ // frontend/src/bluetooth/rpc.ts
1076
+ var MAX_RESPONSE_BYTES = 1048576;
1077
+ var defaultSleep$1 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
1078
+ function uint32BE(value) {
1079
+ const bytes = /* @__PURE__ */ new Uint8Array(4);
1080
+ new DataView(bytes.buffer).setUint32(0, value, false);
1081
+ return bytes;
1082
+ }
1083
+ /** Maps any transport-level failure to a link-lost error, never echoing request data. */
1084
+ async function transport(action) {
1085
+ try {
1086
+ return await action();
1087
+ } catch (err) {
1088
+ if (err instanceof ShellyBleError) throw err;
1089
+ throw new ShellyBleError("linkLost", "The Bluetooth connection to the device was lost");
1090
+ }
1091
+ }
1092
+ function timeoutError() {
1093
+ return new ShellyBleError("timeout", "Timed out waiting for the device to answer over Bluetooth");
1094
+ }
1095
+ var ShellyBleRpc = class {
1096
+ constructor(channel, options = {}) {
1097
+ this.channel = channel;
1098
+ this.nextId = 1;
1099
+ this.nc = 0;
1100
+ this.outOfStep = false;
1101
+ this.queue = Promise.resolve();
1102
+ this.chunkSize = options.chunkSize ?? 20;
1103
+ this.pollIntervalMs = options.pollIntervalMs ?? 100;
1104
+ this.timeoutMs = options.timeoutMs ?? 15e3;
1105
+ this.sleep = options.sleep ?? defaultSleep$1;
1106
+ this.now = options.now ?? Date.now;
1107
+ }
1108
+ /** Authenticate later calls with digest auth. Held in memory only. */
1109
+ setCredentials(username, password) {
1110
+ this.credentials = {
1111
+ username,
1112
+ password
1113
+ };
1114
+ this.challenge = void 0;
1115
+ }
1116
+ /** Calls run one after another, in the order they were made. */
1117
+ call(method, params, options = {}) {
1118
+ const result = this.queue.then(() => this.callNow(method, params, options));
1119
+ this.queue = result.catch(() => void 0);
1120
+ return result;
1121
+ }
1122
+ async callNow(method, params, options) {
1123
+ if (this.outOfStep) throw new ShellyBleError("linkLost", "The Bluetooth link is out of step; reconnect to the device");
1124
+ const timeoutMs = options.timeoutMs ?? this.timeoutMs;
1125
+ const creds = this.credentials;
1126
+ let auth = creds && this.challenge ? await this.authFor(this.challenge, creds) : void 0;
1127
+ let usedFreshChallenge = false;
1128
+ for (let tries = 0; tries < 3; tries++) {
1129
+ const envelope = await this.exchange(method, params, auth, timeoutMs);
1130
+ if (!envelope.error) return envelope.result;
1131
+ if (envelope.error.code !== 401) throw new RpcError(method, envelope.error.code, envelope.error.message ?? "unknown error");
1132
+ if (!creds) throw new ShellyBleError("authRequired", `${method}: the device requires its admin password`);
1133
+ const challenge = parseChallenge(envelope.error.message);
1134
+ if (auth && (usedFreshChallenge || !challenge)) throw new ShellyBleError("wrongPassword", `${method}: the admin password was rejected`);
1135
+ if (!challenge) throw new RpcError(method, 401, "unreadable authentication challenge");
1136
+ usedFreshChallenge = true;
1137
+ this.challenge = challenge;
1138
+ this.nc = 0;
1139
+ auth = await this.authFor(challenge, creds);
1140
+ }
1141
+ throw new ShellyBleError("wrongPassword", `${method}: the admin password was rejected`);
1142
+ }
1143
+ authFor(challenge, creds) {
1144
+ this.nc += 1;
1145
+ return buildRpcAuth(challenge, creds.username, creds.password, void 0, this.nc);
1146
+ }
1147
+ /**
1148
+ * One request and its reply. The deadline covers waiting for the reply; once
1149
+ * its length is known, reading it out gets the same time again, because a
1150
+ * half-read reply would stay on the device and garble the next one.
1151
+ */
1152
+ async exchange(method, params, auth, timeoutMs) {
1153
+ const id = this.nextId++;
1154
+ const frame = new TextEncoder().encode(JSON.stringify({
1155
+ id,
1156
+ src: "attraccess",
1157
+ method,
1158
+ ...params ? { params } : {},
1159
+ ...auth ? { auth } : {}
1160
+ }));
1161
+ await transport(async () => {
1162
+ await writeChunk(this.channel.txControl, uint32BE(frame.length));
1163
+ for (let offset = 0; offset < frame.length; offset += this.chunkSize) await writeChunk(this.channel.data, frame.subarray(offset, offset + this.chunkSize));
1164
+ });
1165
+ const deadline = this.now() + timeoutMs;
1166
+ for (;;) {
1167
+ const raw = new TextDecoder().decode(await this.readResponse(deadline, timeoutMs));
1168
+ let envelope;
1169
+ try {
1170
+ envelope = JSON.parse(raw);
1171
+ } catch {
1172
+ throw new ShellyBleError("malformedResponse", `${method}: the device sent a malformed response`);
1173
+ }
1174
+ if (envelope.id == null || envelope.id === id) return envelope;
1175
+ }
1176
+ }
1177
+ async readResponse(deadline, timeoutMs) {
1178
+ const length = await this.awaitResponseLength(deadline);
1179
+ const readDeadline = Math.max(deadline, this.now()) + timeoutMs;
1180
+ if (length > MAX_RESPONSE_BYTES) throw new ShellyBleError("responseTooLarge", `Bluetooth response is too large (${length} bytes)`);
1181
+ const out = new Uint8Array(length);
1182
+ let filled = 0;
1183
+ while (filled < length) {
1184
+ if (this.now() >= readDeadline) {
1185
+ this.outOfStep = true;
1186
+ throw timeoutError();
1187
+ }
1188
+ const view = await transport(() => this.channel.data.readValue());
1189
+ if (view.byteLength === 0) throw new ShellyBleError("linkLost", "The device stopped sending its response");
1190
+ const chunk = new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
1191
+ const take = Math.min(chunk.length, length - filled);
1192
+ out.set(chunk.subarray(0, take), filled);
1193
+ filled += take;
1194
+ }
1195
+ return out;
1196
+ }
1197
+ async awaitResponseLength(deadline) {
1198
+ for (;;) {
1199
+ const view = await transport(() => this.channel.rxControl.readValue());
1200
+ const length = view.byteLength >= 4 ? view.getUint32(0, false) : 0;
1201
+ if (length > 0) return length;
1202
+ if (this.now() >= deadline) throw timeoutError();
1203
+ await this.sleep(this.pollIntervalMs);
1204
+ }
1205
+ }
1206
+ };
1207
+ // frontend/src/bluetooth/webBluetooth.ts
1208
+ /** `navigator.bluetooth`, or undefined on Firefox/Safari and outside a secure context. */
1209
+ function getBluetooth() {
1210
+ if (typeof window === "undefined" || !window.isSecureContext) return void 0;
1211
+ return navigator.bluetooth;
1212
+ }
1213
+ function isWebBluetoothAvailable() {
1214
+ return getBluetooth() !== void 0;
1215
+ }
1216
+ /**
1217
+ * The operator closed the browser chooser without a pick. Chrome uses
1218
+ * `NotFoundError` both for that ("User cancelled the requestDevice() chooser")
1219
+ * and for a missing or switched-off adapter, so the message tells them apart.
1220
+ */
1221
+ function isChooserCancelled(err) {
1222
+ return err instanceof Error && err.name === "NotFoundError" && /cancel/i.test(err.message);
1223
+ }
1224
+ /** `requestDevice` failed because this computer's Bluetooth is off or missing. */
1225
+ function isAdapterUnavailable(err) {
1226
+ return err instanceof Error && err.name === "NotFoundError" && !isChooserCancelled(err);
1227
+ }
1228
+ async function connectShellyOverBle(bluetooth = getBluetooth()) {
1229
+ if (!bluetooth) throw new ShellyBleError("unsupported", "Web Bluetooth is not available");
1230
+ const device = await bluetooth.requestDevice({
1231
+ filters: [{ services: [SHELLY_RPC_SERVICE] }, { namePrefix: "Shelly" }],
1232
+ optionalServices: [SHELLY_RPC_SERVICE]
1233
+ });
1234
+ const gatt = device.gatt;
1235
+ if (!gatt) throw new ShellyBleError("noRpcService", "The selected device does not expose a GATT server");
1236
+ let server;
1237
+ try {
1238
+ server = await gatt.connect();
1239
+ } catch {
1240
+ throw new ShellyBleError("linkLost", "Could not connect to the device over Bluetooth");
1241
+ }
1242
+ try {
1243
+ const service = await server.getPrimaryService(SHELLY_RPC_SERVICE);
1244
+ const [data, txControl, rxControl] = await Promise.all([
1245
+ service.getCharacteristic(SHELLY_RPC_DATA),
1246
+ service.getCharacteristic(SHELLY_RPC_TX_CONTROL),
1247
+ service.getCharacteristic(SHELLY_RPC_RX_CONTROL)
1248
+ ]);
1249
+ return {
1250
+ advertisedName: device.name ?? "Shelly",
1251
+ rpc: new ShellyBleRpc({
1252
+ data,
1253
+ txControl,
1254
+ rxControl
1255
+ }),
1256
+ disconnect: () => gatt.disconnect()
1257
+ };
1258
+ } catch {
1259
+ gatt.disconnect();
1260
+ throw new ShellyBleError("noRpcService", "The device does not expose the Shelly RPC Bluetooth service");
1261
+ }
1262
+ }
1263
+ // frontend/src/bluetooth/provisioning.ts
1264
+ var ADMIN_USERNAME = "admin";
1265
+ var defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
1266
+ function getDeviceInfo(rpc) {
1267
+ return rpc.call("Shelly.GetDeviceInfo");
1268
+ }
1269
+ /** Networks the device sees, strongest first, one entry per SSID, hidden ones dropped. */
1270
+ async function scanWifi(rpc) {
1271
+ const reply = await rpc.call("WiFi.Scan", void 0, { timeoutMs: 45e3 });
1272
+ const best = /* @__PURE__ */ new Map();
1273
+ for (const entry of reply?.results ?? []) {
1274
+ if (!entry.ssid) continue;
1275
+ const network = {
1276
+ ssid: entry.ssid,
1277
+ rssi: entry.rssi ?? -100,
1278
+ secured: (entry.auth ?? 0) !== 0
1279
+ };
1280
+ const known = best.get(network.ssid);
1281
+ if (!known || known.rssi < network.rssi) best.set(network.ssid, network);
1282
+ }
1283
+ return [...best.values()].sort((a, b) => b.rssi - a.rssi);
1284
+ }
1285
+ /** Sets the admin password with the ha1 computed here; the plain password never leaves the browser. */
1286
+ async function setAdminPassword(rpc, info, password) {
1287
+ const ha1 = await computeHa1(ADMIN_USERNAME, info.id, password);
1288
+ await rpc.call("Shelly.SetAuth", {
1289
+ user: ADMIN_USERNAME,
1290
+ realm: info.id,
1291
+ ha1
1292
+ });
1293
+ rpc.setCredentials(ADMIN_USERNAME, password);
1294
+ }
1295
+ /** Returns true when the device wants a reboot before the config applies. */
1296
+ async function configureWifi(rpc, wifi) {
1297
+ const sta = wifi.password ? {
1298
+ ssid: wifi.ssid,
1299
+ pass: wifi.password,
1300
+ is_open: false,
1301
+ enable: true
1302
+ } : {
1303
+ ssid: wifi.ssid,
1304
+ is_open: true,
1305
+ enable: true
1306
+ };
1307
+ const result = await rpc.call("WiFi.SetConfig", { config: { sta } });
1308
+ return Boolean(result?.restart_required);
1309
+ }
1310
+ async function waitForIp(rpc, options = {}) {
1311
+ const { timeoutMs = 6e4, pollIntervalMs = 2e3, sleep = defaultSleep, now = Date.now } = options;
1312
+ const deadline = now() + timeoutMs;
1313
+ for (;;) {
1314
+ const wifi = await rpc.call("WiFi.GetStatus");
1315
+ const lastStatus = wifi?.status ?? "unknown";
1316
+ if (lastStatus === "got ip" && wifi?.sta_ip) return wifi.sta_ip;
1317
+ if (now() >= deadline) throw new JoinTimeoutError(lastStatus);
1318
+ await sleep(pollIntervalMs);
1319
+ }
1320
+ }
1321
+ /** The device may reboot before it answers, so a lost reply is success. */
1322
+ async function reboot(rpc) {
1323
+ await rpc.call("Shelly.Reboot", void 0, { timeoutMs: 3e3 }).catch(() => void 0);
1324
+ }
1325
+ /**
1326
+ * Switches the radio off. Failures are reported, not thrown: the device is
1327
+ * registered already. `refused` means the device said no; `unknown` means the
1328
+ * reply never came (link lost, timeout), so the change may or may not have applied.
1329
+ */
1330
+ async function disableBluetooth(rpc) {
1331
+ try {
1332
+ if ((await rpc.call("BLE.SetConfig", { config: { enable: false } }))?.restart_required) await reboot(rpc);
1333
+ return "off";
1334
+ } catch (err) {
1335
+ return err instanceof RpcError ? "refused" : "unknown";
1336
+ }
1337
+ }
1338
+ async function step(name, callbacks, action) {
1339
+ callbacks.onStep?.(name, "running");
1340
+ try {
1341
+ const result = await action();
1342
+ callbacks.onStep?.(name, "done");
1343
+ return result;
1344
+ } catch (err) {
1345
+ throw new SetupStepError(name, err);
1346
+ }
1347
+ }
1348
+ async function runSetup(rpc, params, callbacks = {}) {
1349
+ const { info, wifi } = params;
1350
+ if (info.auth_en) {
1351
+ rpc.setCredentials(ADMIN_USERNAME, params.adminPassword);
1352
+ await step("password", callbacks, () => rpc.call("WiFi.GetStatus"));
1353
+ } else await step("password", callbacks, () => setAdminPassword(rpc, info, params.adminPassword));
1354
+ if (await step("wifi", callbacks, () => configureWifi(rpc, wifi))) {
1355
+ await reboot(rpc);
1356
+ return {
1357
+ restartRequired: true,
1358
+ alreadyRegistered: false,
1359
+ bluetooth: "left-on"
1360
+ };
1361
+ }
1362
+ const ipAddress = await step("join", callbacks, () => waitForIp(rpc, callbacks.join));
1363
+ const alreadyRegistered = await step("register", callbacks, () => params.register({
1364
+ ipAddress,
1365
+ name: params.name
1366
+ })) === "alreadyRegistered";
1367
+ let bluetooth = "left-on";
1368
+ if (params.disableBluetooth) bluetooth = await step("bluetooth", callbacks, () => disableBluetooth(rpc));
1369
+ else callbacks.onStep?.("bluetooth", "skipped");
1370
+ return {
1371
+ restartRequired: false,
1372
+ ipAddress,
1373
+ alreadyRegistered,
1374
+ bluetooth
1375
+ };
1376
+ }
1377
+ // frontend/src/devices/bluetooth/useWifiScan.ts
1378
+ var { useCallback: useCallback$7, useEffect: useEffect$4, useRef: useRef$3, useState: useState$6 } = await importShared("react");
1379
+ /** Scans once when mounted and again on demand. A failure only means "enter the SSID yourself". */
1380
+ function useWifiScan(rpc) {
1381
+ const [state, setState] = useState$6({ status: "scanning" });
1382
+ const [run, setRun] = useState$6(0);
1383
+ const inflight = useRef$3(null);
1384
+ useEffect$4(() => {
1385
+ let cancelled = false;
1386
+ setState({ status: "scanning" });
1387
+ const current = inflight.current;
1388
+ const scan = current?.rpc === rpc && current.run === run ? current.scan : scanWifi(rpc);
1389
+ inflight.current = {
1390
+ rpc,
1391
+ run,
1392
+ scan
1393
+ };
1394
+ scan.then((networks) => !cancelled && setState({
1395
+ status: "done",
1396
+ networks
1397
+ }), () => !cancelled && setState({ status: "failed" }));
1398
+ return () => {
1399
+ cancelled = true;
1400
+ };
1401
+ }, [rpc, run]);
1402
+ return {
1403
+ state,
1404
+ rescan: useCallback$7((adminPassword) => {
1405
+ if (adminPassword) rpc.setCredentials(ADMIN_USERNAME, adminPassword);
1406
+ setRun((n) => n + 1);
1407
+ }, [rpc])
1408
+ };
1409
+ }
1410
+ // frontend/src/devices/bluetooth/WifiNetworkPicker.tsx
1411
+ var { Label: Label$1, Radio, RadioGroup, Spinner: Spinner$4 } = await importShared("@heroui/react");
1412
+ var { RefreshCwIcon: RefreshCwIcon$3 } = await importShared("lucide-react");
1413
+ var { Button: Button$9, StatusAlert: StatusAlert$9 } = await importShared("@attraccess/plugins-frontend-ui");
1414
+ var MANUAL = "__manual__";
1415
+ function WifiNetworkPicker({ rpc, selection, onChange, protectedDevice = false, adminPassword }) {
1416
+ const { t } = useShellyTranslations();
1417
+ const { state, rescan } = useWifiScan(rpc);
1418
+ const networks = state.status === "done" ? state.networks : [];
1419
+ const manual = selection.choice === "__manual__" || state.status === "failed";
1420
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
1421
+ className: "sh:flex sh:flex-col sh:gap-3",
1422
+ "data-cy": "shelly-ble-wifi",
1423
+ children: [
1424
+ state.status === "scanning" && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
1425
+ className: "sh:flex sh:items-center sh:gap-3 sh:text-sm sh:text-muted",
1426
+ children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Spinner$4, {
1427
+ color: "accent",
1428
+ size: "sm"
1429
+ }), t("ble.wifi.scanning")]
1430
+ }),
1431
+ state.status === "failed" && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(StatusAlert$9, {
1432
+ status: "warning",
1433
+ title: t(protectedDevice ? "ble.wifi.scanFailedProtected" : "ble.wifi.scanFailed")
1434
+ }),
1435
+ state.status === "done" && networks.length === 0 && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", {
1436
+ className: "sh:text-sm sh:text-muted",
1437
+ children: t("ble.wifi.none")
1438
+ }),
1439
+ state.status === "done" && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(RadioGroup, {
1440
+ value: selection.choice,
1441
+ onChange: (choice) => {
1442
+ const network = networks.find((n) => n.ssid === choice);
1443
+ onChange({
1444
+ ...selection,
1445
+ choice,
1446
+ secured: network?.secured ?? false
1447
+ });
1448
+ },
1449
+ "data-cy": "shelly-ble-networks",
1450
+ children: [
1451
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Label$1, {
1452
+ className: "sh:sr-only",
1453
+ children: t("ble.wifi.networks")
1454
+ }),
1455
+ networks.map((network) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Radio, {
1456
+ value: network.ssid,
1457
+ children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Radio.Content, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Radio.Control, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Radio.Indicator, {}) }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Label$1, { children: [
1458
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", {
1459
+ className: "sh:break-all",
1460
+ children: network.ssid
1461
+ }),
1462
+ " ",
1463
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", {
1464
+ className: "sh:text-xs sh:text-muted",
1465
+ children: [
1466
+ t(network.secured ? "ble.wifi.secured" : "ble.wifi.open"),
1467
+ " ·",
1468
+ " ",
1469
+ t("ble.wifi.signal", { rssi: network.rssi })
1470
+ ]
1471
+ })
1472
+ ] })] })
1473
+ }, network.ssid)),
1474
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Radio, {
1475
+ value: "__manual__",
1476
+ children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Radio.Content, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Radio.Control, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Radio.Indicator, {}) }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Label$1, { children: t("ble.wifi.other") })] })
1477
+ })
1478
+ ]
1479
+ }),
1480
+ manual && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(TextFieldRow, {
1481
+ label: t("ble.wifi.ssid"),
1482
+ value: selection.manualSsid,
1483
+ onChange: (manualSsid) => onChange({
1484
+ ...selection,
1485
+ choice: "__manual__",
1486
+ manualSsid,
1487
+ secured: false
1488
+ }),
1489
+ required: true,
1490
+ dataCy: "shelly-ble-ssid"
1491
+ }),
1492
+ state.status !== "scanning" && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Button$9, {
1493
+ variant: "ghost",
1494
+ size: "sm",
1495
+ onPress: () => rescan(protectedDevice ? adminPassword : void 0),
1496
+ "data-cy": "shelly-ble-rescan",
1497
+ children: [
1498
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(RefreshCwIcon$3, { className: "sh:h-4 sh:w-4" }),
1499
+ " ",
1500
+ t("ble.wifi.rescan")
1501
+ ]
1502
+ }) })
1503
+ ]
1504
+ });
1505
+ }
1506
+ // frontend/src/devices/bluetooth/SetupForm.tsx
1507
+ var { Checkbox, Description, Form: Form$2, Label } = await importShared("@heroui/react");
1508
+ var { useCallback: useCallback$6, useState: useState$5 } = await importShared("react");
1509
+ var { PasswordInput: PasswordInput$2, StatusAlert: StatusAlert$8 } = await importShared("@attraccess/plugins-frontend-ui");
1510
+ var SETUP_FORM_ID = "shelly-ble-form";
1511
+ function SetupForm({ rpc, info, advertisedName, onSubmit }) {
1512
+ const { t } = useShellyTranslations();
1513
+ const protectedDevice = Boolean(info.auth_en);
1514
+ const [selection, setSelection] = useState$5({
1515
+ choice: "",
1516
+ manualSsid: "",
1517
+ secured: false
1518
+ });
1519
+ const [wifiPassword, setWifiPassword] = useState$5("");
1520
+ const [adminPassword, setAdminPassword] = useState$5("");
1521
+ const [confirm, setConfirm] = useState$5("");
1522
+ const [name, setName] = useState$5(advertisedName);
1523
+ const [disableBluetooth, setDisableBluetooth] = useState$5(true);
1524
+ const [error, setError] = useState$5(null);
1525
+ const [submitted, setSubmitted] = useState$5(false);
1526
+ const manual = selection.choice === MANUAL;
1527
+ const ssid = manual ? selection.manualSsid.trim() : selection.choice;
1528
+ const needsWifiPassword = manual || selection.secured;
1529
+ const admin = protectedDevice ? adminPassword : adminPassword.trim();
1530
+ const confirmMismatch = !protectedDevice && admin !== confirm.trim();
1531
+ const showMismatch = submitted && confirmMismatch && admin !== "";
1532
+ const submit = useCallback$6(() => {
1533
+ setSubmitted(true);
1534
+ if (!ssid) return setError(t("ble.validation.ssid"));
1535
+ if (selection.secured && !manual && !wifiPassword) return setError(t("ble.validation.wifiPassword"));
1536
+ if (!admin.trim()) return setError(t("ble.validation.adminPassword"));
1537
+ setError(null);
1538
+ if (confirmMismatch) return;
1539
+ onSubmit({
1540
+ wifi: {
1541
+ ssid,
1542
+ password: needsWifiPassword && wifiPassword ? wifiPassword : void 0
1543
+ },
1544
+ adminPassword: admin,
1545
+ name: name.trim() || advertisedName,
1546
+ disableBluetooth
1547
+ });
1548
+ }, [
1549
+ admin,
1550
+ advertisedName,
1551
+ confirmMismatch,
1552
+ disableBluetooth,
1553
+ manual,
1554
+ name,
1555
+ needsWifiPassword,
1556
+ onSubmit,
1557
+ selection.secured,
1558
+ ssid,
1559
+ t,
1560
+ wifiPassword
1561
+ ]);
1562
+ const handleSubmit = useCallback$6((event) => {
1563
+ event.preventDefault();
1564
+ submit();
1565
+ }, [submit]);
1566
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Form$2, {
1567
+ id: SETUP_FORM_ID,
1568
+ onSubmit: handleSubmit,
1569
+ className: "sh:flex sh:flex-col sh:gap-5",
1570
+ "data-cy": "shelly-ble-form",
1571
+ children: [
1572
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("section", {
1573
+ className: "sh:flex sh:w-full sh:flex-col sh:gap-3",
1574
+ children: [
1575
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
1576
+ className: "sh:flex sh:flex-col sh:gap-1",
1577
+ children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("h3", {
1578
+ className: "sh:text-sm sh:font-semibold",
1579
+ children: t("ble.wifi.title")
1580
+ }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", {
1581
+ className: "sh:text-xs sh:text-muted",
1582
+ children: t("ble.wifi.description")
1583
+ })]
1584
+ }),
1585
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(WifiNetworkPicker, {
1586
+ rpc,
1587
+ selection,
1588
+ onChange: setSelection,
1589
+ protectedDevice,
1590
+ adminPassword: admin || void 0
1591
+ }),
1592
+ needsWifiPassword && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(PasswordInput$2, {
1593
+ label: t("ble.wifi.password"),
1594
+ value: wifiPassword,
1595
+ onChange: setWifiPassword,
1596
+ description: manual ? t("ble.wifi.passwordManualDescription") : void 0,
1597
+ autoComplete: "off",
1598
+ "data-cy": "shelly-ble-wifi-password"
1599
+ })
1600
+ ]
1601
+ }),
1602
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("section", {
1603
+ className: "sh:flex sh:w-full sh:flex-col sh:gap-3",
1604
+ children: protectedDevice ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(PasswordInput$2, {
1605
+ label: t("ble.admin.current"),
1606
+ value: adminPassword,
1607
+ onChange: setAdminPassword,
1608
+ description: t("ble.admin.currentDescription"),
1609
+ autoComplete: "current-password",
1610
+ isRequired: true,
1611
+ "data-cy": "shelly-ble-admin-password"
1612
+ }) : /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(PasswordInput$2, {
1613
+ label: t("ble.admin.new"),
1614
+ value: adminPassword,
1615
+ onChange: setAdminPassword,
1616
+ description: t("ble.admin.newDescription"),
1617
+ autoComplete: "new-password",
1618
+ isRequired: true,
1619
+ "data-cy": "shelly-ble-admin-password"
1620
+ }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(PasswordInput$2, {
1621
+ label: t("ble.admin.confirm"),
1622
+ value: confirm,
1623
+ onChange: setConfirm,
1624
+ autoComplete: "new-password",
1625
+ isRequired: true,
1626
+ isInvalid: showMismatch,
1627
+ errorMessage: showMismatch ? t("ble.admin.mismatch") : void 0,
1628
+ "data-cy": "shelly-ble-admin-confirm"
1629
+ })] })
1630
+ }),
1631
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(TextFieldRow, {
1632
+ label: t("ble.name.label"),
1633
+ value: name,
1634
+ onChange: setName,
1635
+ description: t("ble.name.description"),
1636
+ dataCy: "shelly-ble-name"
1637
+ }),
1638
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Checkbox, {
1639
+ isSelected: disableBluetooth,
1640
+ onChange: setDisableBluetooth,
1641
+ "data-cy": "shelly-ble-disable",
1642
+ children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Checkbox.Content, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Checkbox.Control, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Checkbox.Indicator, {}) }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Label, { children: t("ble.disable.label") })] }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Description, { children: t("ble.disable.description") })]
1643
+ }),
1644
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", {
1645
+ className: "sh:text-xs sh:text-muted",
1646
+ children: t("ble.secretsNote")
1647
+ }),
1648
+ error && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(StatusAlert$8, {
1649
+ status: "danger",
1650
+ "data-cy": "shelly-ble-form-error",
1651
+ children: error
1652
+ })
1653
+ ]
1654
+ });
1655
+ }
1656
+ // frontend/src/devices/bluetooth/SetupFooter.tsx
1657
+ var { BluetoothIcon: BluetoothIcon$2 } = await importShared("lucide-react");
1658
+ var { Button: Button$8 } = await importShared("@attraccess/plugins-frontend-ui");
1659
+ function dismissLabel(kind, supported) {
1660
+ if (kind === "done") return "common.done";
1661
+ if (kind === "failed" || !supported) return "common.close";
1662
+ return "common.cancel";
1663
+ }
1664
+ function SetupFooter({ phase, supported, busy, onSelect, onRetry, onClose }) {
1665
+ const { t } = useShellyTranslations();
1666
+ const canSelect = supported && (phase.kind === "start" || phase.kind === "connecting");
1667
+ const done = phase.kind === "done";
1668
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [
1669
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button$8, {
1670
+ variant: done ? "primary" : "secondary",
1671
+ isDisabled: busy,
1672
+ onPress: onClose,
1673
+ "data-cy": "shelly-ble-close",
1674
+ children: t(dismissLabel(phase.kind, supported))
1675
+ }),
1676
+ canSelect && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Button$8, {
1677
+ variant: "primary",
1678
+ isPending: phase.kind === "connecting",
1679
+ onPress: onSelect,
1680
+ "data-cy": "shelly-ble-select",
1681
+ children: [
1682
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(BluetoothIcon$2, { className: "sh:h-4 sh:w-4" }),
1683
+ " ",
1684
+ t("ble.start.select")
1685
+ ]
1686
+ }),
1687
+ phase.kind === "form" && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Button$8, {
1688
+ variant: "primary",
1689
+ type: "submit",
1690
+ form: "shelly-ble-form",
1691
+ "data-cy": "shelly-ble-start",
1692
+ children: [
1693
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(BluetoothIcon$2, { className: "sh:h-4 sh:w-4" }),
1694
+ " ",
1695
+ t("ble.begin")
1696
+ ]
1697
+ }),
1698
+ phase.kind === "running" && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button$8, {
1699
+ variant: "primary",
1700
+ isPending: true,
1701
+ "data-cy": "shelly-ble-start",
1702
+ children: t("ble.begin")
1703
+ }),
1704
+ phase.kind === "failed" && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button$8, {
1705
+ variant: "primary",
1706
+ onPress: onRetry,
1707
+ "data-cy": "shelly-ble-retry",
1708
+ children: t("ble.failure.retry")
1709
+ })
1710
+ ] });
1711
+ }
1712
+ // frontend/src/devices/bluetooth/DeviceSummary.tsx
1713
+ function DeviceSummary({ info, advertisedName }) {
1714
+ const { t } = useShellyTranslations();
1715
+ const rows = [
1716
+ [t("ble.device.model"), info.model ?? advertisedName],
1717
+ [t("ble.device.generation"), info.gen ? t("devices.generation", { generation: info.gen }) : t("devices.unknown")],
1718
+ [t("ble.device.id"), info.id],
1719
+ [t("ble.device.mac"), info.mac ?? t("devices.unknown")],
1720
+ [t("ble.device.firmware"), info.ver ?? t("devices.unknown")]
1721
+ ];
1722
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("dl", {
1723
+ className: "sh:grid sh:grid-cols-[auto_1fr] sh:gap-x-4 sh:gap-y-1 sh:text-sm",
1724
+ "data-cy": "shelly-ble-device",
1725
+ children: rows.map(([label, value]) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
1726
+ className: "sh:contents",
1727
+ children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("dt", {
1728
+ className: "sh:text-muted",
1729
+ children: label
1730
+ }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("dd", {
1731
+ className: "sh:break-all",
1732
+ children: value
1733
+ })]
1734
+ }, label))
1735
+ });
1736
+ }
1737
+ // frontend/src/devices/bluetooth/SetupStepIcon.tsx
1738
+ var { Spinner: Spinner$3 } = await importShared("@heroui/react");
1739
+ var { CheckCircle2Icon, CircleDashedIcon, MinusCircleIcon, XCircleIcon } = await importShared("lucide-react");
1740
+ var ICON_CLASS = "sh:h-5 sh:w-5 sh:shrink-0";
1741
+ /** A step's status as an icon, labelled for assistive tech. */
1742
+ function SetupStepIcon({ status }) {
1743
+ const { t } = useShellyTranslations();
1744
+ const label = t(`ble.stepStatus.${status}`);
1745
+ if (status === "running") return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Spinner$3, {
1746
+ color: "accent",
1747
+ size: "sm",
1748
+ "aria-label": label
1749
+ });
1750
+ const a11y = {
1751
+ role: "img",
1752
+ "aria-label": label
1753
+ };
1754
+ if (status === "done") return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(CheckCircle2Icon, {
1755
+ ...a11y,
1756
+ className: `${ICON_CLASS} sh:text-success`
1757
+ });
1758
+ if (status === "failed") return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(XCircleIcon, {
1759
+ ...a11y,
1760
+ className: `${ICON_CLASS} sh:text-danger`
1761
+ });
1762
+ if (status === "skipped") return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(MinusCircleIcon, {
1763
+ ...a11y,
1764
+ className: `${ICON_CLASS} sh:text-muted`
1765
+ });
1766
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(CircleDashedIcon, {
1767
+ ...a11y,
1768
+ className: `${ICON_CLASS} sh:text-muted`
1769
+ });
1770
+ }
1771
+ // frontend/src/devices/bluetooth/SetupProgress.tsx
1772
+ var ORDER = [
1773
+ "password",
1774
+ "wifi",
1775
+ "join",
1776
+ "register",
1777
+ "bluetooth"
1778
+ ];
1779
+ function SetupProgress({ statuses, protectedDevice, disableBluetooth }) {
1780
+ const { t } = useShellyTranslations();
1781
+ const steps = disableBluetooth ? ORDER : ORDER.filter((step) => step !== "bluetooth");
1782
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("ol", {
1783
+ className: "sh:flex sh:flex-col sh:gap-2",
1784
+ "aria-live": "polite",
1785
+ "data-cy": "shelly-ble-steps",
1786
+ children: steps.map((step) => {
1787
+ const status = statuses[step] ?? "pending";
1788
+ const label = step === "password" && protectedDevice ? t("ble.steps.passwordCheck") : t(`ble.steps.${step}`);
1789
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("li", {
1790
+ className: "sh:flex sh:items-center sh:gap-3 sh:text-sm",
1791
+ "aria-current": status === "running" ? "step" : void 0,
1792
+ "data-cy": `shelly-ble-step-${step}`,
1793
+ "data-status": status,
1794
+ children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(SetupStepIcon, { status }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", {
1795
+ className: status === "pending" ? "sh:text-muted" : void 0,
1796
+ children: label
1797
+ })]
1798
+ }, step);
1799
+ })
1800
+ });
1801
+ }
1802
+ // frontend/src/devices/bluetooth/SetupResult.tsx
1803
+ var { StatusAlert: StatusAlert$7 } = await importShared("@attraccess/plugins-frontend-ui");
1804
+ var BLUETOOTH_LINE = {
1805
+ off: "ble.result.bluetoothOff",
1806
+ "left-on": "ble.result.bluetoothOn"
1807
+ };
1808
+ var BLUETOOTH_WARNING = {
1809
+ refused: "ble.result.bluetoothRefused",
1810
+ unknown: "ble.result.bluetoothUnknown"
1811
+ };
1812
+ function SetupResult({ outcome, name, passwordSet }) {
1813
+ const { t } = useShellyTranslations();
1814
+ if (outcome.restartRequired) return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(StatusAlert$7, {
1815
+ status: "accent",
1816
+ title: t("ble.result.restartTitle"),
1817
+ "data-cy": "shelly-ble-restart",
1818
+ children: t("ble.result.restart")
1819
+ });
1820
+ const bluetoothLine = BLUETOOTH_LINE[outcome.bluetooth];
1821
+ const bluetoothWarning = BLUETOOTH_WARNING[outcome.bluetooth];
1822
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
1823
+ className: "sh:flex sh:flex-col sh:gap-4",
1824
+ "data-cy": "shelly-ble-result",
1825
+ children: [
1826
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(StatusAlert$7, {
1827
+ status: "success",
1828
+ title: t("ble.result.title")
1829
+ }),
1830
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("dl", {
1831
+ className: "sh:grid sh:grid-cols-[auto_1fr] sh:gap-x-4 sh:gap-y-1 sh:text-sm",
1832
+ children: [
1833
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("dt", {
1834
+ className: "sh:text-muted",
1835
+ children: t("ble.result.name")
1836
+ }),
1837
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("dd", {
1838
+ className: "sh:break-all",
1839
+ children: name
1840
+ }),
1841
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("dt", {
1842
+ className: "sh:text-muted",
1843
+ children: t("ble.result.ip")
1844
+ }),
1845
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("dd", {
1846
+ className: "sh:break-all",
1847
+ children: outcome.ipAddress
1848
+ })
1849
+ ]
1850
+ }),
1851
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("ul", {
1852
+ className: "sh:flex sh:list-inside sh:list-disc sh:flex-col sh:gap-1 sh:text-sm",
1853
+ children: [passwordSet && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("li", { children: t("ble.result.passwordSet") }), bluetoothLine && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("li", { children: t(bluetoothLine) })]
1854
+ }),
1855
+ outcome.alreadyRegistered && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(StatusAlert$7, {
1856
+ status: "warning",
1857
+ "data-cy": "shelly-ble-already-registered",
1858
+ children: t("ble.result.alreadyRegistered", { ip: outcome.ipAddress ?? "" })
1859
+ }),
1860
+ bluetoothWarning && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(StatusAlert$7, {
1861
+ status: "warning",
1862
+ "data-cy": "shelly-ble-bluetooth-warning",
1863
+ children: t(bluetoothWarning)
1864
+ })
1865
+ ]
1866
+ });
1867
+ }
1868
+ // frontend/src/devices/bluetooth/SetupStartView.tsx
1869
+ var { Spinner: Spinner$2 } = await importShared("@heroui/react");
1870
+ var { StatusAlert: StatusAlert$6 } = await importShared("@attraccess/plugins-frontend-ui");
1871
+ /** Before a device is chosen: what to do, the connect error if any, or the connecting spinner. */
1872
+ function SetupStartView({ connecting, error }) {
1873
+ const { t } = useShellyTranslations();
1874
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
1875
+ className: "sh:flex sh:flex-col sh:gap-3",
1876
+ children: [
1877
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", {
1878
+ className: "sh:text-sm",
1879
+ children: t("ble.start.intro")
1880
+ }),
1881
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", {
1882
+ className: "sh:text-sm sh:text-muted",
1883
+ children: t("ble.start.hint")
1884
+ }),
1885
+ error && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(StatusAlert$6, {
1886
+ status: "danger",
1887
+ title: t("ble.connect.title"),
1888
+ "data-cy": "shelly-ble-connect-error",
1889
+ children: error
1890
+ }),
1891
+ connecting && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
1892
+ className: "sh:flex sh:items-center sh:gap-3 sh:text-sm sh:text-muted",
1893
+ children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Spinner$2, {
1894
+ color: "accent",
1895
+ size: "sm"
1896
+ }), t("ble.start.connecting")]
1897
+ })
1898
+ ]
1899
+ });
1900
+ }
1901
+ // frontend/src/devices/bluetooth/SetupPhaseView.tsx
1902
+ var { StatusAlert: StatusAlert$5 } = await importShared("@attraccess/plugins-frontend-ui");
1903
+ function SetupPhaseView({ phase, onSubmit }) {
1904
+ switch (phase.kind) {
1905
+ case "start": return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SetupStartView, {
1906
+ connecting: false,
1907
+ error: phase.error
1908
+ });
1909
+ case "connecting": return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SetupStartView, { connecting: true });
1910
+ case "form": return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(DeviceSummary, {
1911
+ info: phase.info,
1912
+ advertisedName: phase.advertisedName
1913
+ }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SetupForm, {
1914
+ rpc: phase.rpc,
1915
+ info: phase.info,
1916
+ advertisedName: phase.advertisedName,
1917
+ onSubmit: (values) => onSubmit(phase.info, values)
1918
+ })] });
1919
+ case "running":
1920
+ case "failed": return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(SetupProgress, {
1921
+ statuses: phase.statuses,
1922
+ protectedDevice: Boolean(phase.info.auth_en),
1923
+ disableBluetooth: phase.disableBluetooth
1924
+ }), phase.kind === "failed" && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(StatusAlert$5, {
1925
+ status: "danger",
1926
+ title: phase.failure.title,
1927
+ "data-cy": "shelly-ble-failure",
1928
+ children: phase.failure.detail
1929
+ })] });
1930
+ case "done": return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SetupResult, {
1931
+ outcome: phase.outcome,
1932
+ name: phase.name,
1933
+ passwordSet: !phase.info.auth_en
1934
+ });
1935
+ }
1936
+ }
1937
+ // frontend/src/devices/bluetooth/UnsupportedBrowser.tsx
1938
+ var { StatusAlert: StatusAlert$4 } = await importShared("@attraccess/plugins-frontend-ui");
1939
+ function UnsupportedBrowser() {
1940
+ const { t } = useShellyTranslations();
1941
+ const insecure = typeof window !== "undefined" && !window.isSecureContext;
1942
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
1943
+ className: "sh:flex sh:flex-col sh:gap-3",
1944
+ "data-cy": "shelly-ble-unsupported",
1945
+ children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(StatusAlert$4, {
1946
+ status: "warning",
1947
+ title: t("ble.unsupported.title"),
1948
+ children: t(insecure ? "ble.unsupported.insecure" : "ble.unsupported.noApi")
1949
+ }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", {
1950
+ className: "sh:text-sm sh:text-muted",
1951
+ children: t("ble.unsupported.alternatives")
1952
+ })]
1953
+ });
1954
+ }
1955
+ // frontend/src/devices/bluetooth/describeSetupError.ts
1956
+ function describeSetupError(err, t, options = {}) {
1957
+ if (!(err instanceof SetupStepError)) return {
1958
+ title: t("ble.failure.titleGeneric"),
1959
+ detail: describeCause(err, t)
1960
+ };
1961
+ const title = t("ble.failure.title", { step: t(`ble.steps.${err.step === "password" && options.protectedDevice ? "passwordCheck" : err.step}`) });
1962
+ const cause = err.cause;
1963
+ if (cause instanceof JoinTimeoutError) return {
1964
+ title,
1965
+ detail: t("ble.failure.joinTimeout", { status: cause.lastStatus })
1966
+ };
1967
+ if (err.step === "register") {
1968
+ const message = cause instanceof Error ? cause.message.trim().replace(/[.\s]+$/, "") : "";
1969
+ return {
1970
+ title,
1971
+ detail: t(message ? "ble.failure.registerFailed" : "ble.failure.registerFailedNoDetail", { message })
1972
+ };
1973
+ }
1974
+ return {
1975
+ title,
1976
+ detail: describeCause(cause, t)
1977
+ };
1978
+ }
1979
+ function describeCause(cause, t) {
1980
+ if (cause instanceof ShellyBleError) switch (cause.kind) {
1981
+ case "wrongPassword":
1982
+ case "authRequired": return t("ble.failure.wrongPassword");
1983
+ case "linkLost": return t("ble.failure.linkLost");
1984
+ case "timeout": return t("ble.failure.timeout");
1985
+ case "rpc": return t("ble.failure.rpc", cause.data);
1986
+ default: return t("ble.failure.generic");
1987
+ }
1988
+ return t("ble.failure.generic");
1989
+ }
1990
+ /** Message for a failure before the setup starts (chooser, connect, device info). */
1991
+ function describeConnectError(err, t) {
1992
+ if (isAdapterUnavailable(err)) return t("ble.connect.adapterOff");
1993
+ if (err instanceof ShellyBleError) {
1994
+ if (err.kind === "noRpcService") return t("ble.connect.noRpcService");
1995
+ if (err.kind === "linkLost" || err.kind === "timeout") return t("ble.connect.linkLost");
1996
+ }
1997
+ return t("ble.connect.generic");
1998
+ }
1999
+ // frontend/src/devices/bluetooth/useSetupSession.ts
2000
+ var { useCallback: useCallback$5, useEffect: useEffect$3, useRef: useRef$2, useState: useState$4 } = await importShared("react");
2001
+ /** Adds the device; an address that is in the registry already is reported, not thrown. */
2002
+ async function register(input) {
2003
+ try {
2004
+ await addDevice(input);
2005
+ return "added";
2006
+ } catch (err) {
2007
+ if (err instanceof PluginApiError && err.status === 409) return "alreadyRegistered";
2008
+ throw err;
2009
+ }
2010
+ }
2011
+ function useSetupSession(onRegistered) {
2012
+ const { t } = useShellyTranslations();
2013
+ const [phase, setPhase] = useState$4({ kind: "start" });
2014
+ const connection = useRef$2(null);
2015
+ const mounted = useRef$2(true);
2016
+ const disconnect = useCallback$5(() => {
2017
+ connection.current?.disconnect();
2018
+ connection.current = null;
2019
+ }, []);
2020
+ useEffect$3(() => {
2021
+ mounted.current = true;
2022
+ return () => {
2023
+ mounted.current = false;
2024
+ disconnect();
2025
+ };
2026
+ }, [disconnect]);
2027
+ const reset = useCallback$5(() => {
2028
+ disconnect();
2029
+ setPhase({ kind: "start" });
2030
+ }, [disconnect]);
2031
+ return {
2032
+ phase,
2033
+ connect: useCallback$5(async () => {
2034
+ setPhase({ kind: "connecting" });
2035
+ try {
2036
+ const conn = await connectShellyOverBle();
2037
+ if (!mounted.current) return conn.disconnect();
2038
+ connection.current = conn;
2039
+ const info = await getDeviceInfo(conn.rpc);
2040
+ setPhase({
2041
+ kind: "form",
2042
+ info,
2043
+ advertisedName: conn.advertisedName,
2044
+ rpc: conn.rpc
2045
+ });
2046
+ } catch (err) {
2047
+ disconnect();
2048
+ setPhase(isChooserCancelled(err) ? { kind: "start" } : {
2049
+ kind: "start",
2050
+ error: describeConnectError(err, t)
2051
+ });
2052
+ }
2053
+ }, [disconnect, t]),
2054
+ run: useCallback$5(async (info, values) => {
2055
+ const conn = connection.current;
2056
+ if (!conn) return setPhase({ kind: "start" });
2057
+ const statuses = {};
2058
+ const base = {
2059
+ info,
2060
+ disableBluetooth: values.disableBluetooth
2061
+ };
2062
+ setPhase({
2063
+ kind: "running",
2064
+ ...base,
2065
+ statuses: {}
2066
+ });
2067
+ let registered = false;
2068
+ try {
2069
+ const outcome = await runSetup(conn.rpc, {
2070
+ info,
2071
+ adminPassword: values.adminPassword,
2072
+ wifi: values.wifi,
2073
+ name: values.name,
2074
+ disableBluetooth: values.disableBluetooth,
2075
+ register
2076
+ }, { onStep: (step, status) => {
2077
+ statuses[step] = status;
2078
+ if (step === "register" && status === "done") registered = true;
2079
+ setPhase({
2080
+ kind: "running",
2081
+ ...base,
2082
+ statuses: { ...statuses }
2083
+ });
2084
+ } });
2085
+ setPhase({
2086
+ kind: "done",
2087
+ info,
2088
+ outcome,
2089
+ name: values.name
2090
+ });
2091
+ } catch (err) {
2092
+ if (err instanceof SetupStepError) statuses[err.step] = "failed";
2093
+ setPhase({
2094
+ kind: "failed",
2095
+ ...base,
2096
+ statuses: { ...statuses },
2097
+ failure: describeSetupError(err, t, { protectedDevice: Boolean(info.auth_en) })
2098
+ });
2099
+ } finally {
2100
+ disconnect();
2101
+ if (registered) onRegistered();
2102
+ }
2103
+ }, [
2104
+ disconnect,
2105
+ onRegistered,
2106
+ t
2107
+ ]),
2108
+ reset
2109
+ };
2110
+ }
2111
+ // frontend/src/devices/bluetooth/BluetoothSetupDrawer.tsx
2112
+ var { DrawerBody: DrawerBody$3, DrawerFooter: DrawerFooter$2, DrawerHeader: DrawerHeader$3, DrawerHeading: DrawerHeading$3 } = await importShared("@heroui/react");
2113
+ var { BluetoothIcon: BluetoothIcon$1, XIcon: XIcon$3 } = await importShared("lucide-react");
2114
+ var { useCallback: useCallback$4 } = await importShared("react");
2115
+ var { Button: Button$7, StandardDrawer: StandardDrawer$3 } = await importShared("@attraccess/plugins-frontend-ui");
2116
+ function BluetoothSetupDrawer({ isOpen, onOpenChange, onRegistered }) {
2117
+ const { t } = useShellyTranslations();
2118
+ const { phase, connect, run, reset } = useSetupSession(onRegistered);
2119
+ const supported = isWebBluetoothAvailable();
2120
+ const busy = phase.kind === "connecting" || phase.kind === "running";
2121
+ const handleOpenChange = useCallback$4((open) => {
2122
+ if (!open && busy) return;
2123
+ if (!open) reset();
2124
+ onOpenChange(open);
2125
+ }, [
2126
+ busy,
2127
+ onOpenChange,
2128
+ reset
2129
+ ]);
2130
+ const close = useCallback$4(() => handleOpenChange(false), [handleOpenChange]);
2131
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(StandardDrawer$3, {
2132
+ isOpen,
2133
+ onOpenChange: handleOpenChange,
2134
+ backdropProps: {
2135
+ isDismissable: !busy,
2136
+ isKeyboardDismissDisabled: busy
2137
+ },
2138
+ children: [
2139
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DrawerHeader$3, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
2140
+ className: "sh:flex sh:w-full sh:items-start sh:justify-between sh:gap-3",
2141
+ children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
2142
+ className: "sh:flex sh:min-w-0 sh:flex-col sh:gap-1",
2143
+ children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
2144
+ className: "sh:flex sh:items-center sh:gap-2",
2145
+ children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(BluetoothIcon$1, { className: "sh:h-5 sh:w-5 sh:shrink-0 sh:text-accent-soft-foreground" }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DrawerHeading$3, {
2146
+ className: "sh:text-lg sh:font-semibold",
2147
+ children: t("ble.title")
2148
+ })]
2149
+ }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", {
2150
+ className: "sh:text-sm sh:text-muted",
2151
+ children: t("ble.description")
2152
+ })]
2153
+ }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button$7, {
2154
+ isIconOnly: true,
2155
+ variant: "ghost",
2156
+ "aria-label": t("common.close"),
2157
+ isDisabled: busy,
2158
+ onPress: close,
2159
+ children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(XIcon$3, { size: 16 })
2160
+ })]
2161
+ }) }),
2162
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DrawerBody$3, { children: supported ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", {
2163
+ className: "sh:flex sh:flex-col sh:gap-5",
2164
+ children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SetupPhaseView, {
2165
+ phase,
2166
+ onSubmit: (info, values) => void run(info, values)
2167
+ })
2168
+ }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(UnsupportedBrowser, {}) }),
2169
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DrawerFooter$2, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SetupFooter, {
2170
+ phase,
2171
+ supported,
2172
+ busy,
2173
+ onSelect: () => void connect(),
2174
+ onRetry: reset,
2175
+ onClose: close
2176
+ }) })
2177
+ ]
2178
+ });
2179
+ }
746
2180
  // frontend/src/devices/info/AuthProtectedForm.tsx
747
2181
  var { Button: Button$6, PasswordInput: PasswordInput$1 } = await importShared("@attraccess/plugins-frontend-ui");
748
2182
  var { Form: Form$1 } = await importShared("@heroui/react");
@@ -964,7 +2398,7 @@ function DeviceInfoDrawer({ device, onOpenChange }) {
964
2398
  setLoading(true);
965
2399
  setError(null);
966
2400
  try {
967
- setInfo(await getDeviceInfo(device.id, { currentPassword: currentPassword || void 0 }));
2401
+ setInfo(await getDeviceInfo$1(device.id, { currentPassword: currentPassword || void 0 }));
968
2402
  } catch (err) {
969
2403
  setError(err instanceof Error ? err.message : String(err));
970
2404
  } finally {
@@ -1734,7 +3168,7 @@ function DevicesTable({ devices, onAdd, ...rowProps }) {
1734
3168
  // frontend/src/devices/DevicesPage.tsx
1735
3169
  var { PageHeader, StatusAlert, TableDataLoadingIndicator } = await importShared("@attraccess/plugins-frontend-ui");
1736
3170
  var { useOverlayState } = await importShared("@heroui/react");
1737
- var { PlusIcon, SearchIcon, WifiIcon: WifiIcon$1 } = await importShared("lucide-react");
3171
+ var { BluetoothIcon, PlusIcon, SearchIcon, WifiIcon: WifiIcon$1 } = await importShared("lucide-react");
1738
3172
  var { useCallback, useEffect, useState } = await importShared("react");
1739
3173
  function DevicesPage() {
1740
3174
  const { t } = useShellyTranslations();
@@ -1748,6 +3182,7 @@ function DevicesPage() {
1748
3182
  const [firmware, setFirmware] = useState({});
1749
3183
  const addDrawer = useOverlayState();
1750
3184
  const discoverDrawer = useOverlayState();
3185
+ const bluetoothDrawer = useOverlayState();
1751
3186
  const refreshFirmware = useCallback(async (known = []) => {
1752
3187
  try {
1753
3188
  const entries = await listFirmware();
@@ -1803,21 +3238,32 @@ function DevicesPage() {
1803
3238
  icon: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(WifiIcon$1, { className: "sh:h-6 sh:w-6 sh:text-accent-soft-foreground" }),
1804
3239
  title: t("devices.title"),
1805
3240
  subtitle: t("devices.description"),
1806
- actions: [{
1807
- key: "discover",
1808
- label: t("devices.discover"),
1809
- icon: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SearchIcon, { className: "sh:h-4 sh:w-4" }),
1810
- variant: "secondary",
1811
- onPress: discoverDrawer.open,
1812
- dataCy: "shelly-discover-open"
1813
- }, {
1814
- key: "add",
1815
- label: t("devices.add"),
1816
- icon: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(PlusIcon, { className: "sh:h-4 sh:w-4" }),
1817
- variant: "primary",
1818
- onPress: addDrawer.open,
1819
- dataCy: "shelly-add-open"
1820
- }]
3241
+ actions: [
3242
+ {
3243
+ key: "bluetooth",
3244
+ label: t("devices.bluetooth"),
3245
+ icon: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(BluetoothIcon, { className: "sh:h-4 sh:w-4" }),
3246
+ variant: "secondary",
3247
+ onPress: bluetoothDrawer.open,
3248
+ dataCy: "shelly-ble-open"
3249
+ },
3250
+ {
3251
+ key: "discover",
3252
+ label: t("devices.discover"),
3253
+ icon: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SearchIcon, { className: "sh:h-4 sh:w-4" }),
3254
+ variant: "secondary",
3255
+ onPress: discoverDrawer.open,
3256
+ dataCy: "shelly-discover-open"
3257
+ },
3258
+ {
3259
+ key: "add",
3260
+ label: t("devices.add"),
3261
+ icon: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(PlusIcon, { className: "sh:h-4 sh:w-4" }),
3262
+ variant: "primary",
3263
+ onPress: addDrawer.open,
3264
+ dataCy: "shelly-add-open"
3265
+ }
3266
+ ]
1821
3267
  }),
1822
3268
  pageError && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(StatusAlert, {
1823
3269
  status: "danger",
@@ -1840,6 +3286,11 @@ function DevicesPage() {
1840
3286
  onOpenChange: addDrawer.setOpen,
1841
3287
  onAdded: refresh
1842
3288
  }),
3289
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(BluetoothSetupDrawer, {
3290
+ isOpen: bluetoothDrawer.isOpen,
3291
+ onOpenChange: bluetoothDrawer.setOpen,
3292
+ onRegistered: refresh
3293
+ }),
1843
3294
  /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DiscoverDrawer, {
1844
3295
  isOpen: discoverDrawer.isOpen,
1845
3296
  onOpenChange: discoverDrawer.setOpen,
@@ -1866,7 +3317,7 @@ function DevicesPage() {
1866
3317
  var { WifiIcon } = await importShared("lucide-react");
1867
3318
  var ShellyPlugin = class {
1868
3319
  getPluginName() {
1869
- return "shelly-plugin@0.2.0";
3320
+ return "shelly-plugin@0.3.0";
1870
3321
  }
1871
3322
  getDependencies() {
1872
3323
  return [];