-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapi.ts
More file actions
177 lines (164 loc) · 5.49 KB
/
Copy pathapi.ts
File metadata and controls
177 lines (164 loc) · 5.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
import { CephableApi } from '@cephable/cephable-web';
import { CEPHABLE_LOCALE } from './config';
// Re-export the model types we use across the app under a single namespace
// so consumers don't reach into the SDK's private @shared paths.
export type UserDevice = Awaited<ReturnType<typeof CephableApi.getUserDevices>>['data'] extends
| infer A
| undefined
? A extends Array<infer E>
? E
: never
: never;
export type CustomControls = Awaited<
ReturnType<typeof CephableApi.getDeviceCustomControls>
>['data'];
export type CustomControl = NonNullable<CustomControls>['controls'][number];
export type DeviceToken = Awaited<
ReturnType<typeof CephableApi.generateCommandToken>
>['data'];
/**
* SDK calls return an IResult discriminated by `resultType`. This shape is
* what we care about for the refresh/retry path.
*/
interface ApiResult<T> {
resultType: string;
data?: T | null;
errors?: string[];
}
/**
* Run an SDK API call and throw if it didn't return Ok. We don't auto-
* refresh tokens here — the SDK's own `autoRefresh: true` schedules a
* background refresh after each successful exchange, and the initial
* load already calls `refreshTokenIfAuthenticated()` to seed sessionStorage.
*
* Worth noting: the SDK maps HTTP **403 → resultType 'Unauthorized'** and
* HTTP 401 → 'Unexpected'. Don't retry on 'Unauthorized' here — it almost
* always means the user lacks permission for that endpoint, not that
* their token expired.
*/
async function callApi<T>(
run: () => Promise<ApiResult<T>>,
failureMessage: string,
): Promise<T> {
const result = await run();
if (
(result.resultType !== 'Ok' && result.resultType !== 'OkWithWarnings') ||
result.data == null
) {
throw new Error(
result.errors?.join(', ') ?? `${failureMessage} (${result.resultType}).`,
);
}
return result.data;
}
export async function listUserDevices(): Promise<UserDevice[]> {
return callApi(
() => CephableApi.getUserDevices() as unknown as Promise<ApiResult<UserDevice[]>>,
'Failed to load user devices',
);
}
export async function listVerifiedDevices(): Promise<UserDevice[]> {
const devices = await listUserDevices();
return devices.filter((d) => d.isVerified);
}
export async function fetchDeviceCustomControls(
userDeviceId: string,
locale: string = CEPHABLE_LOCALE,
): Promise<CustomControl[]> {
const data = await callApi(
() =>
CephableApi.getDeviceCustomControls(userDeviceId, locale) as unknown as Promise<
ApiResult<NonNullable<CustomControls>>
>,
`Failed to load controls for device ${userDeviceId}`,
);
return data.controls ?? [];
}
export async function generateCommandToken(userDeviceId: string): Promise<string> {
const data = await callApi(
() =>
CephableApi.generateCommandToken(userDeviceId) as unknown as Promise<
ApiResult<NonNullable<DeviceToken>>
>,
'Failed to generate command token',
);
return data.token;
}
export type CommandSessionResult =
| { ok: true; token: string }
| { ok: false; reason: 'forbidden'; error: string }
| { ok: false; reason: 'other'; error: string };
/**
* Mint a command token for a play session. Unlike the plain
* `generateCommandToken`, this returns a discriminated result so the UI
* can distinguish the 403 "this connection isn't allowed to use custom
* controllers" case from generic errors.
*/
export async function startCommandSession(
userDeviceId: string,
): Promise<CommandSessionResult> {
try {
const r = (await CephableApi.generateCommandToken(userDeviceId)) as ApiResult<
NonNullable<DeviceToken>
>;
if ((r.resultType === 'Ok' || r.resultType === 'OkWithWarnings') && r.data) {
return { ok: true, token: r.data.token };
}
if (r.resultType === 'Unauthorized') {
// The SDK uses 'Unauthorized' for HTTP 403. For the command-token
// endpoint specifically, that means the device or connection does
// not have permission to mint a command token — i.e. custom
// controllers aren't enabled for it.
return {
ok: false,
reason: 'forbidden',
error:
"This Cephable connection doesn't allow custom controllers yet. " +
'Enable command access on the device in your Cephable account, ' +
'or pick a different device.',
};
}
return {
ok: false,
reason: 'other',
error:
r.errors?.join(', ') ??
`Couldn't start a command session (${r.resultType}).`,
};
} catch (err) {
return {
ok: false,
reason: 'other',
error: err instanceof Error ? err.message : String(err),
};
}
}
/**
* Send a device command. The optional `macro` body lets us drive arbitrary
* key-press / typing / multi-step sequences via the SDK's MacroModel, in
* addition to (or instead of) the named `command` phrase.
*/
export async function sendDeviceCommand(
userDeviceId: string,
command: string,
token: string,
macro?: unknown,
): Promise<void> {
await callApi(
async () => {
const r = (await CephableApi.sendDeviceCommand(
userDeviceId,
command,
token,
// The SDK types `macro` as MacroModel; we accept `unknown` here
// to avoid pulling private @shared paths into our types.
macro as Parameters<typeof CephableApi.sendDeviceCommand>[3],
)) as ApiResult<unknown>;
if (r.resultType === 'Ok' || r.resultType === 'OkWithWarnings') {
return { ...r, data: r.data ?? true };
}
return r;
},
'Failed to send command',
);
}