@homelib/xiaomi 0.0.0-wip.01265bf1cc90

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 (183) hide show
  1. package/LICENSE +19 -0
  2. package/README.md +26 -0
  3. package/bld/library/backend/client.d.ts +73 -0
  4. package/bld/library/backend/client.js +490 -0
  5. package/bld/library/backend/client.js.map +1 -0
  6. package/bld/library/backend/constants.d.ts +7 -0
  7. package/bld/library/backend/constants.js +11 -0
  8. package/bld/library/backend/constants.js.map +1 -0
  9. package/bld/library/backend/index.d.ts +3 -0
  10. package/bld/library/backend/index.js +4 -0
  11. package/bld/library/backend/index.js.map +1 -0
  12. package/bld/library/backend/oauth.d.ts +24 -0
  13. package/bld/library/backend/oauth.js +121 -0
  14. package/bld/library/backend/oauth.js.map +1 -0
  15. package/bld/library/binding.d.ts +44 -0
  16. package/bld/library/binding.js +212 -0
  17. package/bld/library/binding.js.map +1 -0
  18. package/bld/library/cloud/client.d.ts +27 -0
  19. package/bld/library/cloud/client.js +109 -0
  20. package/bld/library/cloud/client.js.map +1 -0
  21. package/bld/library/cloud/constants.d.ts +9 -0
  22. package/bld/library/cloud/constants.js +11 -0
  23. package/bld/library/cloud/constants.js.map +1 -0
  24. package/bld/library/cloud/device.d.ts +84 -0
  25. package/bld/library/cloud/device.js +686 -0
  26. package/bld/library/cloud/device.js.map +1 -0
  27. package/bld/library/cloud/index.d.ts +5 -0
  28. package/bld/library/cloud/index.js +6 -0
  29. package/bld/library/cloud/index.js.map +1 -0
  30. package/bld/library/cloud/mqtt.d.ts +69 -0
  31. package/bld/library/cloud/mqtt.js +517 -0
  32. package/bld/library/cloud/mqtt.js.map +1 -0
  33. package/bld/library/cloud/transport.d.ts +8 -0
  34. package/bld/library/cloud/transport.js +34 -0
  35. package/bld/library/cloud/transport.js.map +1 -0
  36. package/bld/library/command.d.ts +6 -0
  37. package/bld/library/command.js +6 -0
  38. package/bld/library/command.js.map +1 -0
  39. package/bld/library/configuration.d.ts +62 -0
  40. package/bld/library/configuration.js +303 -0
  41. package/bld/library/configuration.js.map +1 -0
  42. package/bld/library/device.d.ts +69 -0
  43. package/bld/library/device.js +266 -0
  44. package/bld/library/device.js.map +1 -0
  45. package/bld/library/devices/air-conditioner.d.ts +48 -0
  46. package/bld/library/devices/air-conditioner.js +155 -0
  47. package/bld/library/devices/air-conditioner.js.map +1 -0
  48. package/bld/library/devices/command-effect.d.ts +35 -0
  49. package/bld/library/devices/command-effect.js +269 -0
  50. package/bld/library/devices/command-effect.js.map +1 -0
  51. package/bld/library/devices/dehumidifier.d.ts +41 -0
  52. package/bld/library/devices/dehumidifier.js +124 -0
  53. package/bld/library/devices/dehumidifier.js.map +1 -0
  54. package/bld/library/devices/fan.d.ts +37 -0
  55. package/bld/library/devices/fan.js +135 -0
  56. package/bld/library/devices/fan.js.map +1 -0
  57. package/bld/library/devices/index.d.ts +9 -0
  58. package/bld/library/devices/index.js +10 -0
  59. package/bld/library/devices/index.js.map +1 -0
  60. package/bld/library/devices/light.d.ts +22 -0
  61. package/bld/library/devices/light.js +112 -0
  62. package/bld/library/devices/light.js.map +1 -0
  63. package/bld/library/devices/pet-feeder.d.ts +36 -0
  64. package/bld/library/devices/pet-feeder.js +116 -0
  65. package/bld/library/devices/pet-feeder.js.map +1 -0
  66. package/bld/library/devices/placeholder.d.ts +3 -0
  67. package/bld/library/devices/placeholder.js +4 -0
  68. package/bld/library/devices/placeholder.js.map +1 -0
  69. package/bld/library/devices/temperature-humidity-sensor.d.ts +14 -0
  70. package/bld/library/devices/temperature-humidity-sensor.js +56 -0
  71. package/bld/library/devices/temperature-humidity-sensor.js.map +1 -0
  72. package/bld/library/devices/value-range.d.ts +2 -0
  73. package/bld/library/devices/value-range.js +6 -0
  74. package/bld/library/devices/value-range.js.map +1 -0
  75. package/bld/library/endpoint-connection.d.ts +168 -0
  76. package/bld/library/endpoint-connection.js +510 -0
  77. package/bld/library/endpoint-connection.js.map +1 -0
  78. package/bld/library/index.d.ts +26 -0
  79. package/bld/library/index.js +33 -0
  80. package/bld/library/index.js.map +1 -0
  81. package/bld/library/local/certificate.d.ts +31 -0
  82. package/bld/library/local/certificate.js +298 -0
  83. package/bld/library/local/certificate.js.map +1 -0
  84. package/bld/library/local/controller.d.ts +70 -0
  85. package/bld/library/local/controller.js +498 -0
  86. package/bld/library/local/controller.js.map +1 -0
  87. package/bld/library/local/discovery.d.ts +29 -0
  88. package/bld/library/local/discovery.js +321 -0
  89. package/bld/library/local/discovery.js.map +1 -0
  90. package/bld/library/local/index.d.ts +6 -0
  91. package/bld/library/local/index.js +7 -0
  92. package/bld/library/local/index.js.map +1 -0
  93. package/bld/library/local/message.d.ts +11 -0
  94. package/bld/library/local/message.js +128 -0
  95. package/bld/library/local/message.js.map +1 -0
  96. package/bld/library/local/mqtt.d.ts +113 -0
  97. package/bld/library/local/mqtt.js +1074 -0
  98. package/bld/library/local/mqtt.js.map +1 -0
  99. package/bld/library/local/routed-message-client.d.ts +49 -0
  100. package/bld/library/local/routed-message-client.js +326 -0
  101. package/bld/library/local/routed-message-client.js.map +1 -0
  102. package/bld/library/miot/index.d.ts +4 -0
  103. package/bld/library/miot/index.js +5 -0
  104. package/bld/library/miot/index.js.map +1 -0
  105. package/bld/library/miot/matcher.d.ts +84 -0
  106. package/bld/library/miot/matcher.js +326 -0
  107. package/bld/library/miot/matcher.js.map +1 -0
  108. package/bld/library/miot/request.d.ts +33 -0
  109. package/bld/library/miot/request.js +57 -0
  110. package/bld/library/miot/request.js.map +1 -0
  111. package/bld/library/miot/result.d.ts +8 -0
  112. package/bld/library/miot/result.js +5 -0
  113. package/bld/library/miot/result.js.map +1 -0
  114. package/bld/library/miot/spec.d.ts +96 -0
  115. package/bld/library/miot/spec.js +86 -0
  116. package/bld/library/miot/spec.js.map +1 -0
  117. package/bld/library/provider.d.ts +78 -0
  118. package/bld/library/provider.js +600 -0
  119. package/bld/library/provider.js.map +1 -0
  120. package/bld/library/session-manager.d.ts +34 -0
  121. package/bld/library/session-manager.js +177 -0
  122. package/bld/library/session-manager.js.map +1 -0
  123. package/bld/library/session.d.ts +36 -0
  124. package/bld/library/session.js +370 -0
  125. package/bld/library/session.js.map +1 -0
  126. package/bld/library/storage.d.ts +2 -0
  127. package/bld/library/storage.js +66 -0
  128. package/bld/library/storage.js.map +1 -0
  129. package/bld/library/terminal/bindings.d.ts +3 -0
  130. package/bld/library/terminal/bindings.js +306 -0
  131. package/bld/library/terminal/bindings.js.map +1 -0
  132. package/bld/library/terminal/index.d.ts +2 -0
  133. package/bld/library/terminal/index.js +3 -0
  134. package/bld/library/terminal/index.js.map +1 -0
  135. package/bld/library/terminal/provider-details.d.ts +3 -0
  136. package/bld/library/terminal/provider-details.js +477 -0
  137. package/bld/library/terminal/provider-details.js.map +1 -0
  138. package/package.json +29 -0
  139. package/src/library/backend/client.ts +737 -0
  140. package/src/library/backend/constants.ts +17 -0
  141. package/src/library/backend/index.ts +3 -0
  142. package/src/library/backend/oauth.ts +170 -0
  143. package/src/library/binding.ts +387 -0
  144. package/src/library/cloud/client.ts +155 -0
  145. package/src/library/cloud/constants.ts +19 -0
  146. package/src/library/cloud/device.ts +938 -0
  147. package/src/library/cloud/index.ts +5 -0
  148. package/src/library/cloud/mqtt.ts +671 -0
  149. package/src/library/cloud/transport.ts +46 -0
  150. package/src/library/command.ts +7 -0
  151. package/src/library/configuration.ts +480 -0
  152. package/src/library/device.ts +601 -0
  153. package/src/library/devices/air-conditioner.ts +171 -0
  154. package/src/library/devices/command-effect.ts +425 -0
  155. package/src/library/devices/dehumidifier.ts +131 -0
  156. package/src/library/devices/fan.ts +140 -0
  157. package/src/library/devices/index.ts +9 -0
  158. package/src/library/devices/light.ts +119 -0
  159. package/src/library/devices/pet-feeder.ts +129 -0
  160. package/src/library/devices/placeholder.ts +3 -0
  161. package/src/library/devices/temperature-humidity-sensor.ts +49 -0
  162. package/src/library/devices/value-range.ts +14 -0
  163. package/src/library/endpoint-connection.ts +841 -0
  164. package/src/library/index.ts +71 -0
  165. package/src/library/local/certificate.ts +401 -0
  166. package/src/library/local/controller.ts +693 -0
  167. package/src/library/local/discovery.ts +485 -0
  168. package/src/library/local/index.ts +6 -0
  169. package/src/library/local/message.ts +174 -0
  170. package/src/library/local/mqtt.ts +1555 -0
  171. package/src/library/local/routed-message-client.ts +377 -0
  172. package/src/library/miot/index.ts +4 -0
  173. package/src/library/miot/matcher.ts +683 -0
  174. package/src/library/miot/request.ts +70 -0
  175. package/src/library/miot/result.ts +14 -0
  176. package/src/library/miot/spec.ts +114 -0
  177. package/src/library/provider.ts +745 -0
  178. package/src/library/session-manager.ts +224 -0
  179. package/src/library/session.ts +528 -0
  180. package/src/library/storage.ts +83 -0
  181. package/src/library/terminal/bindings.tsx +692 -0
  182. package/src/library/terminal/index.ts +2 -0
  183. package/src/library/terminal/provider-details.tsx +871 -0
@@ -0,0 +1,871 @@
1
+ import {type ProviderDetailsComponentProps} from '@homelib/terminal';
2
+ import {Box, Text, useInput, usePaste} from 'ink';
3
+ import {useCallback, useEffect, useRef, useState} from 'react';
4
+
5
+ import {
6
+ CLOUD_SERVERS,
7
+ type CloudServer,
8
+ DEFAULT_CLOUD_SERVER,
9
+ } from '../backend/index.js';
10
+ import type {
11
+ MiotProviderConfigurationSnapshot,
12
+ MiotProviderHomeItem,
13
+ } from '../configuration.js';
14
+ import type {MiotProvider} from '../provider.js';
15
+
16
+ const DEFAULT_CLOUD_SERVER_INDEX = CLOUD_SERVERS.indexOf(DEFAULT_CLOUD_SERVER);
17
+
18
+ export function MiotProviderDetails({
19
+ provider,
20
+ onBack,
21
+ }: ProviderDetailsComponentProps<MiotProvider>): React.JSX.Element {
22
+ const [state, setState] = useState<DetailsState>({type: 'loading'});
23
+ const operationReference = useRef<Operation | undefined>(undefined);
24
+
25
+ const beginOperation = useCallback((): Operation => {
26
+ const operation = {authorizationCancellationRequested: false};
27
+
28
+ operationReference.current = operation;
29
+ return operation;
30
+ }, []);
31
+
32
+ const isCurrentOperation = useCallback(
33
+ (operation: Operation): boolean => operationReference.current === operation,
34
+ [],
35
+ );
36
+
37
+ const completeOperation = useCallback((operation: Operation): void => {
38
+ if (operationReference.current === operation) {
39
+ operationReference.current = undefined;
40
+ }
41
+ }, []);
42
+
43
+ const clearOperation = useCallback((): void => {
44
+ const operation = operationReference.current;
45
+
46
+ operationReference.current = undefined;
47
+
48
+ if (
49
+ operation !== undefined &&
50
+ !operation.authorizationCancellationRequested
51
+ ) {
52
+ operation.authorizationCancellationRequested = true;
53
+ void operation.cancelAuthorization?.().catch(console.error);
54
+ }
55
+ }, []);
56
+
57
+ const load = useCallback(
58
+ (notice?: ReadyNotice): void => {
59
+ const operation = beginOperation();
60
+
61
+ setState({type: 'loading'});
62
+ void provider.configuration.load().then(
63
+ snapshot => {
64
+ if (!isCurrentOperation(operation)) {
65
+ return;
66
+ }
67
+
68
+ completeOperation(operation);
69
+
70
+ if (snapshot === undefined) {
71
+ setState({
72
+ type: 'authorization-required',
73
+ cloudServerIndex: DEFAULT_CLOUD_SERVER_INDEX,
74
+ });
75
+ } else {
76
+ setState({...createReadyState(snapshot), notice});
77
+ }
78
+ },
79
+ error => {
80
+ if (!isCurrentOperation(operation)) {
81
+ return;
82
+ }
83
+
84
+ completeOperation(operation);
85
+ setState({type: 'load-error', message: getErrorMessage(error)});
86
+ },
87
+ );
88
+ },
89
+ [beginOperation, completeOperation, isCurrentOperation, provider],
90
+ );
91
+
92
+ const authorize = useCallback(
93
+ (cloudServer: CloudServer): void => {
94
+ const operation = beginOperation();
95
+
96
+ setState({type: 'authorizing', cloudServer});
97
+ void (async () => {
98
+ const authorization =
99
+ await provider.configuration.beginAuthorization(cloudServer);
100
+
101
+ if (!isCurrentOperation(operation)) {
102
+ await authorization.cancel();
103
+ return;
104
+ }
105
+
106
+ operation.cancelAuthorization = authorization.cancel;
107
+ operation.submitCallbackUrl = callbackUrl =>
108
+ authorization.submitCallbackUrl(callbackUrl);
109
+
110
+ if (operation.authorizationCancellationRequested) {
111
+ await authorization.cancel();
112
+ } else {
113
+ setState({
114
+ type: 'authorizing',
115
+ cloudServer,
116
+ url: authorization.url,
117
+ });
118
+ }
119
+
120
+ await authorization.wait();
121
+
122
+ if (!isCurrentOperation(operation)) {
123
+ return;
124
+ }
125
+
126
+ completeOperation(operation);
127
+ load();
128
+ })().catch(error => {
129
+ if (!isCurrentOperation(operation)) {
130
+ return;
131
+ }
132
+
133
+ completeOperation(operation);
134
+
135
+ if (operation.authorizationCancellationRequested) {
136
+ load();
137
+ } else {
138
+ setState({
139
+ type: 'authorization-error',
140
+ cloudServer,
141
+ message: getErrorMessage(error),
142
+ });
143
+ }
144
+ });
145
+ },
146
+ [beginOperation, completeOperation, isCurrentOperation, load, provider],
147
+ );
148
+
149
+ const submitCallbackUrl = useCallback(
150
+ (value: string): void => {
151
+ if (
152
+ state.type !== 'authorizing' ||
153
+ state.url === undefined ||
154
+ state.callbackStatus !== undefined
155
+ ) {
156
+ return;
157
+ }
158
+
159
+ const operation = operationReference.current;
160
+ const submit = operation?.submitCallbackUrl;
161
+
162
+ if (operation === undefined || submit === undefined) {
163
+ return;
164
+ }
165
+
166
+ const callbackUrl = value.trim();
167
+
168
+ if (callbackUrl.length === 0) {
169
+ setState({...state, callbackError: 'callback URL is empty.'});
170
+ return;
171
+ }
172
+
173
+ setState({
174
+ ...state,
175
+ callbackStatus: 'submitting',
176
+ callbackError: undefined,
177
+ });
178
+ void submit(callbackUrl).then(
179
+ () => {
180
+ if (
181
+ !isCurrentOperation(operation) ||
182
+ operation.authorizationCancellationRequested
183
+ ) {
184
+ return;
185
+ }
186
+
187
+ setState(currentState => {
188
+ return currentState.type === 'authorizing'
189
+ ? {
190
+ ...currentState,
191
+ callbackStatus: 'accepted',
192
+ callbackError: undefined,
193
+ }
194
+ : currentState;
195
+ });
196
+ },
197
+ error => {
198
+ if (
199
+ !isCurrentOperation(operation) ||
200
+ operation.authorizationCancellationRequested
201
+ ) {
202
+ return;
203
+ }
204
+
205
+ setState(currentState => {
206
+ return currentState.type === 'authorizing'
207
+ ? {
208
+ ...currentState,
209
+ callbackStatus: undefined,
210
+ callbackError: getErrorMessage(error),
211
+ }
212
+ : currentState;
213
+ });
214
+ },
215
+ );
216
+ },
217
+ [isCurrentOperation, state],
218
+ );
219
+
220
+ usePaste(submitCallbackUrl, {
221
+ isActive:
222
+ state.type === 'authorizing' &&
223
+ state.url !== undefined &&
224
+ state.callbackStatus === undefined,
225
+ });
226
+
227
+ const save = useCallback(
228
+ (readyState: ReadyState): void => {
229
+ const operation = beginOperation();
230
+ const includedHomes = readyState.snapshot.homes
231
+ .filter(home => readyState.draftHomeKeys.has(getHomeKey(home)))
232
+ .map(({source, id}) => ({source, id}));
233
+
234
+ setState({
235
+ ...readyState,
236
+ saving: true,
237
+ saveError: undefined,
238
+ notice: undefined,
239
+ });
240
+ void provider.configuration
241
+ .saveIncludedHomes(readyState.snapshot.account, includedHomes)
242
+ .then(
243
+ () => {
244
+ if (!isCurrentOperation(operation)) {
245
+ return;
246
+ }
247
+
248
+ completeOperation(operation);
249
+
250
+ const savedHomeKeys = new Set(readyState.draftHomeKeys);
251
+ const snapshot = {
252
+ ...readyState.snapshot,
253
+ selectionSource: 'saved' as const,
254
+ homes: readyState.snapshot.homes.map(home => ({
255
+ ...home,
256
+ included: savedHomeKeys.has(getHomeKey(home)),
257
+ })),
258
+ };
259
+
260
+ setState({
261
+ ...readyState,
262
+ snapshot,
263
+ savedHomeKeys,
264
+ draftHomeKeys: new Set(savedHomeKeys),
265
+ saving: false,
266
+ saveError: undefined,
267
+ notice: 'saved',
268
+ });
269
+ },
270
+ error => {
271
+ if (!isCurrentOperation(operation)) {
272
+ return;
273
+ }
274
+
275
+ completeOperation(operation);
276
+ setState({
277
+ ...readyState,
278
+ saving: false,
279
+ saveError: getErrorMessage(error),
280
+ notice: undefined,
281
+ });
282
+ },
283
+ );
284
+ },
285
+ [beginOperation, completeOperation, isCurrentOperation, provider],
286
+ );
287
+
288
+ const logOut = useCallback(
289
+ (readyState: ReadyState): void => {
290
+ const operation = beginOperation();
291
+
292
+ setState({type: 'logging-out'});
293
+ void provider.configuration.forgetAuthorization().then(
294
+ () => {
295
+ if (!isCurrentOperation(operation)) {
296
+ return;
297
+ }
298
+
299
+ completeOperation(operation);
300
+ setState({type: 'logged-out'});
301
+ },
302
+ error => {
303
+ if (!isCurrentOperation(operation)) {
304
+ return;
305
+ }
306
+
307
+ completeOperation(operation);
308
+ setState({
309
+ type: 'logout-error',
310
+ readyState,
311
+ message: getErrorMessage(error),
312
+ });
313
+ },
314
+ );
315
+ },
316
+ [beginOperation, completeOperation, isCurrentOperation, provider],
317
+ );
318
+
319
+ useEffect(() => {
320
+ load();
321
+
322
+ return clearOperation;
323
+ }, [clearOperation, load]);
324
+
325
+ useInput((input, key) => {
326
+ if (state.type === 'loading') {
327
+ if (key.escape) {
328
+ clearOperation();
329
+ onBack();
330
+ }
331
+ } else if (state.type === 'authorization-required') {
332
+ if (key.escape) {
333
+ onBack();
334
+ } else if (key.upArrow) {
335
+ setState({
336
+ ...state,
337
+ cloudServerIndex: wrapIndex(
338
+ state.cloudServerIndex - 1,
339
+ CLOUD_SERVERS.length,
340
+ ),
341
+ });
342
+ } else if (key.downArrow) {
343
+ setState({
344
+ ...state,
345
+ cloudServerIndex: wrapIndex(
346
+ state.cloudServerIndex + 1,
347
+ CLOUD_SERVERS.length,
348
+ ),
349
+ });
350
+ } else if (key.return) {
351
+ const cloudServer = CLOUD_SERVERS.at(state.cloudServerIndex);
352
+
353
+ if (cloudServer !== undefined) {
354
+ authorize(cloudServer);
355
+ }
356
+ }
357
+ } else if (state.type === 'authorizing') {
358
+ if (key.escape) {
359
+ const operation = operationReference.current;
360
+
361
+ if (operation !== undefined) {
362
+ operation.authorizationCancellationRequested = true;
363
+ void operation.cancelAuthorization?.().catch(console.error);
364
+ }
365
+
366
+ setState({type: 'cancelling-authorization'});
367
+ }
368
+ } else if (state.type === 'cancelling-authorization') {
369
+ return;
370
+ } else if (state.type === 'load-error') {
371
+ if (key.escape) {
372
+ onBack();
373
+ } else if (key.return || input === 'r') {
374
+ load();
375
+ } else if (input === 'a') {
376
+ setState({
377
+ type: 'authorization-required',
378
+ cloudServerIndex: DEFAULT_CLOUD_SERVER_INDEX,
379
+ });
380
+ }
381
+ } else if (state.type === 'authorization-error') {
382
+ if (key.escape) {
383
+ setState({
384
+ type: 'authorization-required',
385
+ cloudServerIndex: CLOUD_SERVERS.indexOf(state.cloudServer),
386
+ });
387
+ } else if (key.return || input === 'r') {
388
+ authorize(state.cloudServer);
389
+ }
390
+ } else if (state.type === 'logout-confirmation') {
391
+ if (key.escape) {
392
+ setState(state.readyState);
393
+ } else if (input === 'y') {
394
+ logOut(state.readyState);
395
+ }
396
+ } else if (state.type === 'logging-out') {
397
+ return;
398
+ } else if (state.type === 'logged-out') {
399
+ return;
400
+ } else if (state.type === 'logout-error') {
401
+ if (key.escape) {
402
+ setState(state.readyState);
403
+ } else if (key.return || input === 'r') {
404
+ logOut(state.readyState);
405
+ }
406
+ } else if (!state.saving) {
407
+ const homeCount = state.snapshot.homes.length;
408
+ const filteringAvailable = state.snapshot.account.userId !== null;
409
+ const clearedState =
410
+ state.notice === undefined ? state : {...state, notice: undefined};
411
+
412
+ if (key.escape) {
413
+ onBack();
414
+ } else if (key.upArrow && homeCount > 0) {
415
+ setState({
416
+ ...clearedState,
417
+ cursor: wrapIndex(state.cursor - 1, homeCount),
418
+ });
419
+ } else if (key.downArrow && homeCount > 0) {
420
+ setState({
421
+ ...clearedState,
422
+ cursor: wrapIndex(state.cursor + 1, homeCount),
423
+ });
424
+ } else if (input === ' ' && homeCount > 0 && filteringAvailable) {
425
+ const home = state.snapshot.homes.at(state.cursor);
426
+
427
+ if (home !== undefined) {
428
+ const draftHomeKeys = new Set(clearedState.draftHomeKeys);
429
+ const key = getHomeKey(home);
430
+
431
+ if (draftHomeKeys.has(key)) {
432
+ draftHomeKeys.delete(key);
433
+ } else {
434
+ draftHomeKeys.add(key);
435
+ }
436
+
437
+ setState({
438
+ ...clearedState,
439
+ draftHomeKeys,
440
+ saveError: undefined,
441
+ });
442
+ }
443
+ } else if (key.return && filteringAvailable && needsSave(state)) {
444
+ save(clearedState);
445
+ } else if (input === 'r' && !hasDraftChanges(state)) {
446
+ load('reloaded');
447
+ } else if (input === 'o') {
448
+ setState({type: 'logout-confirmation', readyState: clearedState});
449
+ } else if (state.notice !== undefined) {
450
+ setState(clearedState);
451
+ }
452
+ }
453
+ });
454
+
455
+ return <DetailsView state={state} />;
456
+ }
457
+
458
+ type DetailsViewProps = {
459
+ readonly state: DetailsState;
460
+ };
461
+
462
+ function DetailsView({state}: DetailsViewProps): React.JSX.Element {
463
+ if (state.type === 'loading') {
464
+ return (
465
+ <Box flexDirection="column">
466
+ <Text>loading miot configuration…</Text>
467
+ <Hint>esc back</Hint>
468
+ </Box>
469
+ );
470
+ } else if (state.type === 'authorization-required') {
471
+ return <AuthorizationRequiredView state={state} />;
472
+ } else if (state.type === 'authorizing') {
473
+ return <AuthorizingView state={state} />;
474
+ } else if (state.type === 'cancelling-authorization') {
475
+ return (
476
+ <Box flexDirection="column">
477
+ <Text>cancelling authorization…</Text>
478
+ </Box>
479
+ );
480
+ } else if (state.type === 'load-error') {
481
+ return (
482
+ <ErrorView message={state.message}>
483
+ enter/r retry · a authorize again · esc back
484
+ </ErrorView>
485
+ );
486
+ } else if (state.type === 'authorization-error') {
487
+ return (
488
+ <ErrorView message={state.message}>
489
+ enter/r retry · esc choose region
490
+ </ErrorView>
491
+ );
492
+ } else if (state.type === 'logout-confirmation') {
493
+ return <LogoutConfirmationView />;
494
+ } else if (state.type === 'logging-out') {
495
+ return (
496
+ <Box flexDirection="column">
497
+ <Text>logging out…</Text>
498
+ </Box>
499
+ );
500
+ } else if (state.type === 'logged-out') {
501
+ return (
502
+ <Box flexDirection="column">
503
+ <Text>logged out locally. restart the script to continue.</Text>
504
+ </Box>
505
+ );
506
+ } else if (state.type === 'logout-error') {
507
+ return (
508
+ <ErrorView message={state.message}>enter/r retry · esc cancel</ErrorView>
509
+ );
510
+ }
511
+
512
+ return <ReadyView state={state} />;
513
+ }
514
+
515
+ type AuthorizationRequiredViewProps = {
516
+ readonly state: AuthorizationRequiredState;
517
+ };
518
+
519
+ function AuthorizationRequiredView({
520
+ state,
521
+ }: AuthorizationRequiredViewProps): React.JSX.Element {
522
+ return (
523
+ <Box flexDirection="column">
524
+ <Text>
525
+ setup <Text dimColor>○ authorization required</Text>
526
+ </Text>
527
+
528
+ <Box flexDirection="column" marginTop={1}>
529
+ <Text dimColor>cloud region</Text>
530
+ {CLOUD_SERVERS.map((cloudServer, index) => (
531
+ <Text
532
+ key={cloudServer}
533
+ bold={index === state.cloudServerIndex}
534
+ color={index === state.cloudServerIndex ? 'cyan' : undefined}
535
+ >
536
+ {index === state.cloudServerIndex ? '› ' : ' '}
537
+ {cloudServer}
538
+ </Text>
539
+ ))}
540
+ </Box>
541
+
542
+ <Hint>↑↓ select · enter authorize · esc back</Hint>
543
+ </Box>
544
+ );
545
+ }
546
+
547
+ type AuthorizingViewProps = {
548
+ readonly state: AuthorizingState;
549
+ };
550
+
551
+ function AuthorizingView({state}: AuthorizingViewProps): React.JSX.Element {
552
+ return (
553
+ <Box flexDirection="column">
554
+ <Text>
555
+ setup <Text color="yellow">● authorizing</Text> · region{' '}
556
+ {state.cloudServer}
557
+ </Text>
558
+
559
+ {state.url === undefined ? (
560
+ <Text>starting oauth callback…</Text>
561
+ ) : (
562
+ <Box flexDirection="column" marginTop={1}>
563
+ <Text>open this url in a browser:</Text>
564
+ <Text color="cyan" underline wrap="wrap">
565
+ {state.url}
566
+ </Text>
567
+ {state.callbackStatus === 'submitting' ? (
568
+ <Text>processing pasted callback…</Text>
569
+ ) : state.callbackStatus === 'accepted' ? (
570
+ <Text>callback received; completing authorization…</Text>
571
+ ) : (
572
+ <>
573
+ <Text>waiting for browser callback…</Text>
574
+ <Text dimColor>
575
+ if the browser cannot connect, paste the complete callback URL
576
+ here.
577
+ </Text>
578
+ </>
579
+ )}
580
+ {state.callbackError === undefined ? null : (
581
+ <Text color="red">callback rejected: {state.callbackError}</Text>
582
+ )}
583
+ </Box>
584
+ )}
585
+
586
+ <Hint>
587
+ {state.url !== undefined && state.callbackStatus === undefined
588
+ ? 'paste callback URL · esc cancel'
589
+ : 'esc cancel'}
590
+ </Hint>
591
+ </Box>
592
+ );
593
+ }
594
+
595
+ function LogoutConfirmationView(): React.JSX.Element {
596
+ return (
597
+ <Box flexDirection="column">
598
+ <Text>log out of this miot provider?</Text>
599
+ <Text dimColor>
600
+ local oauth credentials will be removed. provider identity and the saved
601
+ home filter will be kept.
602
+ </Text>
603
+ <Hint>y confirm · esc cancel</Hint>
604
+ </Box>
605
+ );
606
+ }
607
+
608
+ type ReadyViewProps = {
609
+ readonly state: ReadyState;
610
+ };
611
+
612
+ function ReadyView({state}: ReadyViewProps): React.JSX.Element {
613
+ const selectedCount = state.draftHomeKeys.size;
614
+ const draftChanged = hasDraftChanges(state);
615
+ const saveRequired = needsSave(state);
616
+ const filteringAvailable = state.snapshot.account.userId !== null;
617
+
618
+ return (
619
+ <Box flexDirection="column">
620
+ <Text>
621
+ setup <Text color="green">● ready</Text> · region{' '}
622
+ {state.snapshot.account.cloudServer}
623
+ </Text>
624
+
625
+ {!filteringAvailable ? (
626
+ <Text color="yellow">
627
+ home filtering is unavailable because this account has no stable id.
628
+ </Text>
629
+ ) : state.snapshot.selectionSource === 'account-mismatch' ? (
630
+ <Text color="yellow">
631
+ saved homes belong to another account; all homes are selected.
632
+ </Text>
633
+ ) : null}
634
+
635
+ <Box flexDirection="column" marginTop={1}>
636
+ <Text>
637
+ homes {selectedCount} / {state.snapshot.homes.length} selected
638
+ </Text>
639
+
640
+ {state.snapshot.homes.length === 0 ? (
641
+ <Text dimColor>no homes discovered.</Text>
642
+ ) : (
643
+ state.snapshot.homes.map((home, index) => (
644
+ <HomeItemView
645
+ key={getHomeKey(home)}
646
+ home={home}
647
+ included={state.draftHomeKeys.has(getHomeKey(home))}
648
+ selected={index === state.cursor}
649
+ />
650
+ ))
651
+ )}
652
+ </Box>
653
+
654
+ {state.saveError === undefined ? null : (
655
+ <Text color="red">save failed: {state.saveError}</Text>
656
+ )}
657
+ {state.notice === 'saved' ? (
658
+ <Text color="green">home selection saved.</Text>
659
+ ) : state.notice === 'reloaded' ? (
660
+ <Text color="green">configuration reloaded.</Text>
661
+ ) : null}
662
+
663
+ {state.saving ? (
664
+ <Hint>saving…</Hint>
665
+ ) : !filteringAvailable ? (
666
+ <Hint>↑↓ select · r reload · o log out · esc back</Hint>
667
+ ) : draftChanged ? (
668
+ <Hint>
669
+ ↑↓ select · space toggle · enter save · o log out · esc discard/back
670
+ </Hint>
671
+ ) : saveRequired ? (
672
+ <Hint>
673
+ ↑↓ select · space toggle · enter save · r reload · o log out · esc
674
+ back
675
+ </Hint>
676
+ ) : (
677
+ <Hint>↑↓ select · space toggle · r reload · o log out · esc back</Hint>
678
+ )}
679
+ </Box>
680
+ );
681
+ }
682
+
683
+ type HomeItemViewProps = {
684
+ readonly home: MiotProviderHomeItem;
685
+ readonly included: boolean;
686
+ readonly selected: boolean;
687
+ };
688
+
689
+ function HomeItemView({
690
+ home,
691
+ included,
692
+ selected,
693
+ }: HomeItemViewProps): React.JSX.Element {
694
+ return (
695
+ <Text bold={selected} color={selected ? 'cyan' : undefined}>
696
+ {selected ? '› ' : ' '}[{included ? 'x' : ' '}] {home.name}{' '}
697
+ <Text dimColor>{getHomeSourceLabel(home.source)}</Text>
698
+ </Text>
699
+ );
700
+ }
701
+
702
+ type ErrorViewProps = {
703
+ readonly children: React.ReactNode;
704
+ readonly message: string;
705
+ };
706
+
707
+ function ErrorView({children, message}: ErrorViewProps): React.JSX.Element {
708
+ return (
709
+ <Box flexDirection="column">
710
+ <Text color="red">error: {message}</Text>
711
+ <Hint>{children}</Hint>
712
+ </Box>
713
+ );
714
+ }
715
+
716
+ type HintProps = {
717
+ readonly children: React.ReactNode;
718
+ };
719
+
720
+ function Hint({children}: HintProps): React.JSX.Element {
721
+ return (
722
+ <Box marginTop={1}>
723
+ <Text dimColor>{children}</Text>
724
+ </Box>
725
+ );
726
+ }
727
+
728
+ type DetailsState =
729
+ | LoadingState
730
+ | AuthorizationRequiredState
731
+ | AuthorizingState
732
+ | CancellingAuthorizationState
733
+ | LoadErrorState
734
+ | AuthorizationErrorState
735
+ | LogoutConfirmationState
736
+ | LoggingOutState
737
+ | LoggedOutState
738
+ | LogoutErrorState
739
+ | ReadyState;
740
+
741
+ type LoadingState = {
742
+ readonly type: 'loading';
743
+ };
744
+
745
+ type AuthorizationRequiredState = {
746
+ readonly type: 'authorization-required';
747
+ readonly cloudServerIndex: number;
748
+ };
749
+
750
+ type AuthorizingState = {
751
+ readonly type: 'authorizing';
752
+ readonly cloudServer: CloudServer;
753
+ readonly url?: string;
754
+ readonly callbackStatus?: 'submitting' | 'accepted';
755
+ readonly callbackError?: string;
756
+ };
757
+
758
+ type CancellingAuthorizationState = {
759
+ readonly type: 'cancelling-authorization';
760
+ };
761
+
762
+ type LoadErrorState = {
763
+ readonly type: 'load-error';
764
+ readonly message: string;
765
+ };
766
+
767
+ type AuthorizationErrorState = {
768
+ readonly type: 'authorization-error';
769
+ readonly cloudServer: CloudServer;
770
+ readonly message: string;
771
+ };
772
+
773
+ type LogoutConfirmationState = {
774
+ readonly type: 'logout-confirmation';
775
+ readonly readyState: ReadyState;
776
+ };
777
+
778
+ type LoggingOutState = {
779
+ readonly type: 'logging-out';
780
+ };
781
+
782
+ type LoggedOutState = {
783
+ readonly type: 'logged-out';
784
+ };
785
+
786
+ type LogoutErrorState = {
787
+ readonly type: 'logout-error';
788
+ readonly readyState: ReadyState;
789
+ readonly message: string;
790
+ };
791
+
792
+ type ReadyState = {
793
+ readonly type: 'ready';
794
+ readonly snapshot: MiotProviderConfigurationSnapshot;
795
+ readonly cursor: number;
796
+ readonly savedHomeKeys: ReadonlySet<string>;
797
+ readonly draftHomeKeys: ReadonlySet<string>;
798
+ readonly saving: boolean;
799
+ readonly saveError?: string;
800
+ readonly notice?: ReadyNotice;
801
+ };
802
+
803
+ type ReadyNotice = 'saved' | 'reloaded';
804
+
805
+ type Operation = {
806
+ authorizationCancellationRequested: boolean;
807
+ cancelAuthorization?: () => Promise<void>;
808
+ submitCallbackUrl?: (callbackUrl: string) => Promise<void>;
809
+ };
810
+
811
+ function createReadyState(
812
+ snapshot: MiotProviderConfigurationSnapshot,
813
+ ): ReadyState {
814
+ const savedHomeKeys = new Set(
815
+ snapshot.homes.filter(home => home.included).map(getHomeKey),
816
+ );
817
+
818
+ return {
819
+ type: 'ready',
820
+ snapshot,
821
+ cursor: 0,
822
+ savedHomeKeys,
823
+ draftHomeKeys: new Set(savedHomeKeys),
824
+ saving: false,
825
+ };
826
+ }
827
+
828
+ function needsSave(state: ReadyState): boolean {
829
+ if (state.snapshot.selectionSource !== 'saved') {
830
+ return true;
831
+ }
832
+
833
+ return hasDraftChanges(state);
834
+ }
835
+
836
+ function hasDraftChanges(state: ReadyState): boolean {
837
+ return !setsEqual(state.savedHomeKeys, state.draftHomeKeys);
838
+ }
839
+
840
+ function setsEqual(
841
+ left: ReadonlySet<string>,
842
+ right: ReadonlySet<string>,
843
+ ): boolean {
844
+ if (left.size !== right.size) {
845
+ return false;
846
+ }
847
+
848
+ return [...left].every(value => right.has(value));
849
+ }
850
+
851
+ function getHomeKey(home: Pick<MiotProviderHomeItem, 'source' | 'id'>): string {
852
+ return JSON.stringify([home.source, home.id]);
853
+ }
854
+
855
+ function getHomeSourceLabel(source: MiotProviderHomeItem['source']): string {
856
+ if (source === 'shared-home') {
857
+ return 'shared home';
858
+ } else if (source === 'shared-device') {
859
+ return 'shared device';
860
+ }
861
+
862
+ return 'owned';
863
+ }
864
+
865
+ function wrapIndex(index: number, length: number): number {
866
+ return (index + length) % length;
867
+ }
868
+
869
+ function getErrorMessage(error: unknown): string {
870
+ return error instanceof Error ? error.message : String(error);
871
+ }