Repository navigation
Expand file tree
/
Copy pathares.ts
More file actions
152 lines (139 loc) · 5.6 KB
/
Copy pathares.ts
File metadata and controls
152 lines (139 loc) · 5.6 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
import path from 'node:path';
import { runCmd, runCmdBackground } from '@agent-device/host-kit/command';
import { Deadline, pollUntilSettled } from '@agent-device/host-kit/retry';
import { AppError, asAppError, errorMessage } from '@agent-device/kernel/errors';
import { listTargets, type PageTunnel } from '@agent-device/tv-cdp';
export type AresDevice = Readonly<{
name: string;
isDefault: boolean;
}>;
type AresSetupEntry = {
profile: string;
name: string;
default: boolean;
};
export type HostEnv = Readonly<Record<string, string | undefined>>;
export function createAres(bin: string | undefined, hostEnv: HostEnv) {
const command = (name: string) => (bin ? path.resolve(bin, name) : name);
const env = bin
? { ...hostEnv, PATH: [bin, hostEnv.PATH].filter(Boolean).join(path.delimiter) }
: hostEnv;
const ares = async (name: string, args: string[], signal?: AbortSignal) => {
try {
return (await runCmd(command(name), args, { env, timeoutMs: 60_000, signal })).stdout;
} catch (error) {
throw aresError(name, error);
}
};
const forDevice = (device: string) => ({
async launch(appId: string, signal?: AbortSignal) {
await ares('ares-launch', ['-d', device, appId], signal);
},
async close(appId: string, signal?: AbortSignal) {
await ares('ares-launch', ['-d', device, '--close', appId], signal);
},
async listApps(): Promise<{ id: string; name: string }[]> {
return parseAppList(await ares('ares-install', ['-d', device, '--listfull']));
},
// ares-inspect is a long-lived ssh tunnel that prints its local inspector port once it is up.
// The page target only appears once the app has loaded, so the port alone is not enough.
async inspect(appId: string, signal?: AbortSignal, timeoutMs = 30_000): Promise<PageTunnel> {
// The tunnel outlives this request, so the signal only cancels the wait for the page.
const { child, wait } = runCmdBackground(
command('ares-inspect'),
['-d', device, '-a', appId],
{
env,
captureOutput: false,
},
);
let output = '';
let collecting = true;
let spawnError: unknown;
let inspectorError: unknown;
const collect = (chunk: Buffer) => {
if (collecting) output += chunk;
};
wait.catch((error: unknown) => {
if (child.pid === undefined) spawnError = error;
});
child.stdout?.on('data', collect);
child.stderr?.on('data', collect);
const close = () => child.kill();
const appTarget = async (port: number) => {
try {
const targets = await listTargets(port);
return targets.find((target) => target.url.includes(`/${appId}/`));
} catch (error) {
inspectorError = error;
return undefined;
}
};
const { value: target } = await pollUntilSettled({
deadline: Deadline.fromTimeoutMs(timeoutMs),
intervalMs: 500,
signal,
settled: (found) => found !== undefined,
probe: async () => {
if (spawnError) throw aresError('ares-inspect', spawnError);
if (child.exitCode !== null || child.signalCode !== null) {
throw new AppError('COMMAND_FAILED', `ares-inspect exited: ${output.trim()}`, {
hint: `Check that ${device} is reachable with ares-setup-device and in Developer Mode.`,
});
}
const port = Number(output.match(/localhost:(\d+)/)?.[1]);
return port ? await appTarget(port) : undefined;
},
}).catch((error: unknown) => {
close();
throw error;
});
if (target) {
collecting = false;
return { target, close, onClose: (listener) => child.once('exit', listener) };
}
close();
const lastError = inspectorError
? `; the inspector last failed with: ${errorMessage(inspectorError)}`
: '';
throw new AppError(
'COMMAND_FAILED',
`ares-inspect found no page for ${appId} on ${device} within ${timeoutMs}ms${lastError}`,
{ output: output.trim(), hint: `Check that ${appId} is installed and starts on the TV.` },
);
},
});
return {
async listDevices(): Promise<AresDevice[]> {
const devices: AresSetupEntry[] = JSON.parse(await ares('ares-setup-device', ['--listfull']));
return devices
.filter((device) => device.profile === 'tv')
.map((device) => ({
name: device.name,
isDefault: device.default,
}));
},
forDevice,
};
}
function aresError(name: string, error: unknown): AppError {
const failure = asAppError(error, 'COMMAND_FAILED');
if (failure.code === 'TOOL_MISSING') {
return new AppError('TOOL_MISSING', `${name} is not installed or not on PATH`, {
hint: 'Install the webOS CLI (npm install -g @webos-tools/cli), or set the plugin option aresBin to the directory that holds it.',
});
}
if (failure.details?.processExitError !== true) return failure;
const stderr = typeof failure.details?.stderr === 'string' ? failure.details.stderr.trim() : '';
return new AppError('COMMAND_FAILED', `${name} failed${stderr ? `: ${stderr}` : ''}`, {
hint: 'Check that the TV is on, in Developer Mode, and registered with ares-setup-device.',
});
}
// `ares-install --listfull` prints one `key : value` block per app, separated by blank lines.
function parseAppList(output: string) {
return output.split(/\n\s*\n/).flatMap((block) => {
const id = block.match(/^id : (.+)$/m)?.[1]?.trim();
const title = block.match(/^title : (.+)$/m)?.[1]?.trim();
return id ? [{ id, name: title ?? id }] : [];
});
}