screen-relay 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/Makefile +165 -0
- package/README.md +113 -2
- package/THIRD-PARTY-NOTICES.md +75 -0
- package/dist/cli/client.d.ts +28 -0
- package/dist/cli/commands.d.ts +52 -0
- package/dist/cli/config.d.ts +32 -0
- package/dist/cli/format.d.ts +15 -0
- package/dist/cli/help.d.ts +5 -0
- package/dist/cli/host/common.d.ts +23 -0
- package/dist/cli/host/doctor.d.ts +2 -0
- package/dist/cli/host/packages.d.ts +13 -0
- package/dist/cli/host/session_commands.d.ts +8 -0
- package/dist/cli/host/setup.d.ts +22 -0
- package/dist/cli/host/state.d.ts +23 -0
- package/dist/cli/host/supervisor.d.ts +91 -0
- package/dist/cli/host/watcher.d.ts +4 -0
- package/dist/cli/main.d.ts +3 -0
- package/dist/cli/mode.d.ts +14 -0
- package/dist/cli/output.d.ts +24 -0
- package/dist/cli/parser.d.ts +6 -0
- package/dist/cli/relay.mjs +12247 -0
- package/dist/cli/skills.d.ts +21 -0
- package/dist/cli/theme.d.ts +14 -0
- package/dist/protocol/errors.d.ts +155 -0
- package/dist/protocol/index.d.ts +119 -0
- package/dist/protocol/index.js +418 -0
- package/dist/sdk/index.d.ts +77 -0
- package/dist/sdk/index.js +724 -0
- package/dist/viewer/index.html +96 -0
- package/dist/viewer/viewer.js +1052 -0
- package/package.json +50 -4
- package/packages.tsv +38 -0
- package/skills/core/SKILL.md +169 -0
- package/skills/core/references/cli.md +119 -0
- package/skills/core/references/config.md +48 -0
- package/skills/core/references/macos.md +50 -0
- package/skills/core/references/sdk.md +69 -0
- package/skills/core/references/troubleshooting.md +33 -0
- package/skills/core/references/wayland.md +47 -0
- package/skills/screen-relay/SKILL.md +24 -0
- package/skills/vercel-sandbox/SKILL.md +68 -0
- package/src/engine/backends/linux/keycodes.hpp +35 -0
- package/src/engine/backends/linux/wayland/capture.cpp +298 -0
- package/src/engine/backends/linux/wayland/input.cpp +559 -0
- package/src/engine/backends/linux/wayland/keymap.cpp +118 -0
- package/src/engine/backends/linux/wayland/keymap.hpp +54 -0
- package/src/engine/backends/linux/wayland/protocols/virtual-keyboard-unstable-v1.xml +112 -0
- package/src/engine/backends/linux/wayland/protocols/wlr-screencopy-unstable-v1.xml +234 -0
- package/src/engine/backends/linux/wayland/protocols/wlr-virtual-pointer-unstable-v1.xml +152 -0
- package/src/engine/backends/linux/wayland/wayland.cpp +166 -0
- package/src/engine/backends/linux/wayland/wayland.hpp +60 -0
- package/src/engine/backends/linux/x11/capture.cpp +206 -0
- package/src/engine/backends/linux/x11/input.cpp +266 -0
- package/src/engine/backends/macos/capture.mm +367 -0
- package/src/engine/backends/macos/display.hpp +20 -0
- package/src/engine/backends/macos/display.mm +84 -0
- package/src/engine/backends/macos/input.mm +287 -0
- package/src/engine/backends/macos/keys.hpp +34 -0
- package/src/engine/backends/windows/capture.cpp +393 -0
- package/src/engine/backends/windows/input.cpp +274 -0
- package/src/engine/backends/windows/output.cpp +65 -0
- package/src/engine/backends/windows/output.hpp +26 -0
- package/src/engine/core/capture-bucket.hpp +40 -0
- package/src/engine/core/capture-source.hpp +59 -0
- package/src/engine/core/capture.cpp +565 -0
- package/src/engine/core/capture.hpp +58 -0
- package/src/engine/core/color.cpp +176 -0
- package/src/engine/core/color.hpp +16 -0
- package/src/engine/core/cpu-budget.hpp +196 -0
- package/src/engine/core/flow.hpp +317 -0
- package/src/engine/core/input.cpp +98 -0
- package/src/engine/core/input.hpp +115 -0
- package/src/engine/core/wait.cpp +125 -0
- package/src/engine/core/wait.hpp +41 -0
- package/src/engine/server/backend.cpp +65 -0
- package/src/engine/server/backend.hpp +18 -0
- package/src/engine/server/config.cpp +257 -0
- package/src/engine/server/config.hpp +24 -0
- package/src/engine/server/main.cpp +82 -0
- package/src/engine/server/metrics.cpp +47 -0
- package/src/engine/server/metrics.hpp +10 -0
- package/src/engine/server/screenshot.cpp +108 -0
- package/src/engine/server/screenshot.hpp +31 -0
- package/src/engine/server/server.cpp +531 -0
- package/src/engine/server/server.hpp +88 -0
- package/src/engine/server/wire.cpp +65 -0
- package/src/engine/server/wire.hpp +27 -0
|
@@ -0,0 +1,724 @@
|
|
|
1
|
+
import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
|
|
2
|
+
|
|
3
|
+
// src/sdk/index.ts
|
|
4
|
+
import { readFileSync } from "node:fs";
|
|
5
|
+
import { writeFile } from "node:fs/promises";
|
|
6
|
+
import { request as httpRequest } from "node:http";
|
|
7
|
+
import { request as httpsRequest } from "node:https";
|
|
8
|
+
|
|
9
|
+
// src/protocol/errors.ts
|
|
10
|
+
var ERROR_REASONS = {
|
|
11
|
+
invalid_input: { class: "usage", code: "INVALID_ARGUMENT", exitCode: 2 },
|
|
12
|
+
invalid_option: { class: "usage", code: "INVALID_ARGUMENT", exitCode: 2 },
|
|
13
|
+
unknown_command: { class: "usage", code: "INVALID_ARGUMENT", exitCode: 2 },
|
|
14
|
+
missing_input: { class: "missing_input", code: "INVALID_ARGUMENT", exitCode: 2 },
|
|
15
|
+
missing_command: { class: "missing_input", code: "INVALID_ARGUMENT", exitCode: 2 },
|
|
16
|
+
not_found: { class: "not_found", code: "NOT_FOUND", exitCode: 1 },
|
|
17
|
+
not_running: { class: "not_found", code: "NOT_FOUND", exitCode: 1 },
|
|
18
|
+
already_running: { class: "conflict", code: "BUSY", exitCode: 1 },
|
|
19
|
+
port_in_use: { class: "conflict", code: "BUSY", exitCode: 1 },
|
|
20
|
+
busy: { class: "conflict", code: "BUSY", exitCode: 1 },
|
|
21
|
+
unreachable: { class: "network", code: "NETWORK_ERROR", exitCode: 1 },
|
|
22
|
+
timeout: { class: "network", code: "TIMEOUT", exitCode: 1 },
|
|
23
|
+
disconnected: { class: "network", code: "DISCONNECTED", exitCode: 1 },
|
|
24
|
+
unauthorized: { class: "permission", code: "UNAUTHORIZED", exitCode: 1 },
|
|
25
|
+
forbidden: { class: "permission", code: "UNAUTHORIZED", exitCode: 1 },
|
|
26
|
+
unsupported_input: { class: "platform", code: "UNSUPPORTED", exitCode: 1 },
|
|
27
|
+
unsupported_platform: { class: "platform", code: "UNSUPPORTED", exitCode: 1 },
|
|
28
|
+
missing_dependency: { class: "platform", code: "UNSUPPORTED", exitCode: 1 },
|
|
29
|
+
component_failed: { class: "platform", code: "HTTP_ERROR", exitCode: 1 },
|
|
30
|
+
spawn_failed: { class: "platform", code: "IO_ERROR", exitCode: 1 },
|
|
31
|
+
io_error: { class: "platform", code: "IO_ERROR", exitCode: 1 },
|
|
32
|
+
protocol_error: { class: "platform", code: "PROTOCOL_ERROR", exitCode: 1 },
|
|
33
|
+
invalid_config: { class: "config", code: "CONFIG_ERROR", exitCode: 1 },
|
|
34
|
+
internal: { class: "bug", code: "INTERNAL", exitCode: 1 },
|
|
35
|
+
canceled: { class: "canceled", code: "CANCELED", exitCode: 130 }
|
|
36
|
+
};
|
|
37
|
+
var LEGACY_REASONS = {
|
|
38
|
+
INVALID_ARGUMENT: "invalid_input",
|
|
39
|
+
NOT_FOUND: "not_found",
|
|
40
|
+
BUSY: "busy",
|
|
41
|
+
NETWORK_ERROR: "unreachable",
|
|
42
|
+
TIMEOUT: "timeout",
|
|
43
|
+
DISCONNECTED: "disconnected",
|
|
44
|
+
UNAUTHORIZED: "unauthorized",
|
|
45
|
+
UNSUPPORTED: "unsupported_input",
|
|
46
|
+
HTTP_ERROR: "component_failed",
|
|
47
|
+
IO_ERROR: "io_error",
|
|
48
|
+
PROTOCOL_ERROR: "protocol_error",
|
|
49
|
+
CONFIG_ERROR: "invalid_config",
|
|
50
|
+
INTERNAL: "internal",
|
|
51
|
+
CANCELED: "canceled"
|
|
52
|
+
};
|
|
53
|
+
var RelayError = class extends Error {
|
|
54
|
+
code;
|
|
55
|
+
reason;
|
|
56
|
+
class;
|
|
57
|
+
exitCode;
|
|
58
|
+
hint;
|
|
59
|
+
data;
|
|
60
|
+
next;
|
|
61
|
+
status;
|
|
62
|
+
label;
|
|
63
|
+
constructor(reason, message, options = {}) {
|
|
64
|
+
super(message);
|
|
65
|
+
this.name = "RelayError";
|
|
66
|
+
this.reason = Object.hasOwn(ERROR_REASONS, reason) ? reason : Object.hasOwn(LEGACY_REASONS, reason) ? LEGACY_REASONS[reason] : "internal";
|
|
67
|
+
const definition = ERROR_REASONS[this.reason];
|
|
68
|
+
this.code = definition.code;
|
|
69
|
+
this.class = definition.class;
|
|
70
|
+
this.exitCode = definition.exitCode;
|
|
71
|
+
const details = typeof options === "string" ? { hint: options } : options;
|
|
72
|
+
this.hint = details.hint;
|
|
73
|
+
this.data = details.data;
|
|
74
|
+
this.next = details.next;
|
|
75
|
+
this.label = details.label;
|
|
76
|
+
this.status = details.status ?? "error";
|
|
77
|
+
}
|
|
78
|
+
};
|
|
79
|
+
function errorCodes(error, seen = /* @__PURE__ */ new Set()) {
|
|
80
|
+
if (!error || typeof error !== "object" || seen.has(error)) return [];
|
|
81
|
+
seen.add(error);
|
|
82
|
+
const record = error;
|
|
83
|
+
const codes = [];
|
|
84
|
+
if (typeof record.code === "string") codes.push(record.code);
|
|
85
|
+
if (Array.isArray(record.errors)) for (const inner of record.errors) codes.push(...errorCodes(inner, seen));
|
|
86
|
+
if (record.cause !== void 0) codes.push(...errorCodes(record.cause, seen));
|
|
87
|
+
return codes;
|
|
88
|
+
}
|
|
89
|
+
function errorText(error, seen = /* @__PURE__ */ new Set()) {
|
|
90
|
+
if (!error || typeof error !== "object" || seen.has(error)) return "";
|
|
91
|
+
seen.add(error);
|
|
92
|
+
const record = error;
|
|
93
|
+
const parts = [];
|
|
94
|
+
if (typeof record.message === "string") parts.push(record.message);
|
|
95
|
+
if (Array.isArray(record.errors)) for (const inner of record.errors) parts.push(errorText(inner, seen));
|
|
96
|
+
if (record.cause !== void 0) parts.push(errorText(record.cause, seen));
|
|
97
|
+
return parts.join(" ");
|
|
98
|
+
}
|
|
99
|
+
var CAUSES = {
|
|
100
|
+
ECONNREFUSED: "Connection refused.",
|
|
101
|
+
ENOTFOUND: "The host name did not resolve.",
|
|
102
|
+
EAI_AGAIN: "The host name did not resolve.",
|
|
103
|
+
ETIMEDOUT: "The request timed out.",
|
|
104
|
+
ESOCKETTIMEDOUT: "The request timed out.",
|
|
105
|
+
UND_ERR_CONNECT_TIMEOUT: "The request timed out.",
|
|
106
|
+
UND_ERR_HEADERS_TIMEOUT: "The request timed out.",
|
|
107
|
+
UND_ERR_BODY_TIMEOUT: "The request timed out.",
|
|
108
|
+
ABORT_ERR: "The request timed out.",
|
|
109
|
+
ECONNRESET: "The connection was reset.",
|
|
110
|
+
EPIPE: "The connection was closed.",
|
|
111
|
+
EHOSTUNREACH: "The host was unreachable.",
|
|
112
|
+
ENETUNREACH: "The network was unreachable."
|
|
113
|
+
};
|
|
114
|
+
var TLS_CODES = /TLS|SSL|CERT/;
|
|
115
|
+
var TIMEOUT_CODES = /* @__PURE__ */ new Set(["ETIMEDOUT", "ESOCKETTIMEDOUT", "UND_ERR_CONNECT_TIMEOUT", "UND_ERR_HEADERS_TIMEOUT", "UND_ERR_BODY_TIMEOUT", "ABORT_ERR", "TimeoutError"]);
|
|
116
|
+
function networkError(error) {
|
|
117
|
+
const codes = errorCodes(error);
|
|
118
|
+
const text = errorText(error);
|
|
119
|
+
if (codes.some((code) => TLS_CODES.test(code)) || /certificate/i.test(text)) return new RelayError("unreachable", "The TLS certificate was rejected.");
|
|
120
|
+
const timedOut = codes.some((code) => TIMEOUT_CODES.has(code)) || typeof error === "object" && error !== null && error.name === "AbortError" || /timed? ?out/i.test(text);
|
|
121
|
+
const blocked = /bad port/i.test(text);
|
|
122
|
+
const message = blocked ? "Connection refused." : codes.map((code) => CAUSES[code]).find(Boolean) ?? (timedOut ? "The request timed out." : "The connection failed.");
|
|
123
|
+
return new RelayError(timedOut ? "timeout" : "unreachable", message);
|
|
124
|
+
}
|
|
125
|
+
function responseError(status2, detail) {
|
|
126
|
+
const body = detail && typeof detail === "object" ? detail : {};
|
|
127
|
+
const reason = status2 === 401 ? "unauthorized" : status2 === 403 ? "forbidden" : status2 === 404 ? "not_found" : status2 === 409 || status2 === 429 || status2 === 503 && body.error === "busy" || body.error === "busy" ? "busy" : status2 === 422 || body.error === "unsupported_input" ? "unsupported_input" : status2 === 400 || status2 === 413 || body.error === "invalid_input" ? "invalid_input" : "component_failed";
|
|
128
|
+
const messages = {
|
|
129
|
+
unauthorized: "The engine rejected the token.",
|
|
130
|
+
forbidden: "The engine rejected the connection origin.",
|
|
131
|
+
not_found: "The engine endpoint was not found.",
|
|
132
|
+
busy: "Another controller holds control of the desktop.",
|
|
133
|
+
unsupported_input: "The engine does not support this input.",
|
|
134
|
+
invalid_input: "The engine rejected the input."
|
|
135
|
+
};
|
|
136
|
+
const index = Number.isInteger(body.index) && Number(body.index) >= 0 ? Number(body.index) : void 0;
|
|
137
|
+
const applied = Number.isInteger(body.applied) && Number(body.applied) >= 0 ? Number(body.applied) : void 0;
|
|
138
|
+
const message = body.error === "screenshot_unavailable" ? "The engine could not take a screenshot. Read the engine log with screen-relay logs engine." : messages[reason] ?? "The engine could not complete the request.";
|
|
139
|
+
return new RelayError(reason, message, {
|
|
140
|
+
data: { httpStatus: status2, ...index === void 0 ? {} : { index }, ...applied === void 0 ? {} : { applied } }
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// src/protocol/index.ts
|
|
145
|
+
var MAGIC = 1314081841;
|
|
146
|
+
var VERSION = 1;
|
|
147
|
+
var HEADER_SIZE = 20;
|
|
148
|
+
var INPUT_SIZE = 16;
|
|
149
|
+
var MAX_INPUT_BATCH = 256;
|
|
150
|
+
var MAX_INPUT_PENDING = 32;
|
|
151
|
+
var MAX_BYTES_IN_FLIGHT = 8388608;
|
|
152
|
+
var SUBPROTOCOL = "nsl1";
|
|
153
|
+
var MESSAGE_TYPES = { frame: 1, ack: 2, input: 3, controlReady: 4, inputResponse: 5, cursor: 6 };
|
|
154
|
+
var INPUT_TYPES = { keyDown: 1, keyUp: 2, pointerMove: 3, buttonDown: 4, buttonUp: 5, wheel: 6, releaseAll: 7, text: 8 };
|
|
155
|
+
function integer(value, min, max, name) {
|
|
156
|
+
if (!Number.isInteger(value) || value < min || value > max) throw new RelayError("invalid_input", `Invalid ${name}`);
|
|
157
|
+
return value;
|
|
158
|
+
}
|
|
159
|
+
function coordinate(value, name) {
|
|
160
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value < 0 || value > 1) throw new RelayError("invalid_input", `Invalid ${name}`);
|
|
161
|
+
return Math.round(value * 65535);
|
|
162
|
+
}
|
|
163
|
+
function encodeInputRecord(event) {
|
|
164
|
+
if (!event || typeof event !== "object" || !Object.hasOwn(INPUT_TYPES, event.type)) throw new RelayError("invalid_input", "Unknown input type");
|
|
165
|
+
const bytes = new Uint8Array(INPUT_SIZE);
|
|
166
|
+
const view = new DataView(bytes.buffer);
|
|
167
|
+
view.setUint8(0, INPUT_TYPES[event.type]);
|
|
168
|
+
const buttons = integer(event.buttons ?? 0, 0, 31, "buttons");
|
|
169
|
+
const modifiers = integer(event.modifiers ?? 0, 0, 255, "modifiers");
|
|
170
|
+
if ((event.type === "releaseAll" || event.type === "text") && (buttons || modifiers)) throw new RelayError("invalid_input", "Release and text events require zero masks");
|
|
171
|
+
view.setUint16(12, buttons);
|
|
172
|
+
view.setUint16(14, modifiers);
|
|
173
|
+
if (event.type === "pointerMove" || event.type === "buttonDown" || event.type === "buttonUp" || event.type === "wheel") {
|
|
174
|
+
view.setUint16(8, coordinate(event.x, "x"));
|
|
175
|
+
view.setUint16(10, coordinate(event.y, "y"));
|
|
176
|
+
}
|
|
177
|
+
if (event.type === "keyDown" || event.type === "keyUp") view.setUint16(2, integer(event.key, 0, 231, "key"));
|
|
178
|
+
if (event.type === "buttonDown" || event.type === "buttonUp") view.setUint16(2, integer(event.button, 1, 3, "button"));
|
|
179
|
+
if (event.type === "wheel") {
|
|
180
|
+
if (event.axis !== "vertical" && event.axis !== "horizontal") throw new RelayError("invalid_input", "Invalid wheel axis");
|
|
181
|
+
const delta = integer(event.delta, -1200, 1200, "wheel delta");
|
|
182
|
+
if (delta % 120) throw new RelayError("invalid_input", "Wheel delta must be a multiple of 120");
|
|
183
|
+
view.setUint16(2, event.axis === "horizontal" ? 1 : 0);
|
|
184
|
+
view.setInt32(4, delta);
|
|
185
|
+
}
|
|
186
|
+
if (event.type === "text") {
|
|
187
|
+
const codepoint = integer(event.codepoint, 1, 1114111, "Unicode scalar");
|
|
188
|
+
if (codepoint >= 55296 && codepoint <= 57343) throw new RelayError("invalid_input", "Invalid Unicode scalar");
|
|
189
|
+
view.setInt32(4, codepoint);
|
|
190
|
+
view.setUint16(8, 0);
|
|
191
|
+
view.setUint16(10, 0);
|
|
192
|
+
}
|
|
193
|
+
return bytes;
|
|
194
|
+
}
|
|
195
|
+
function encodeInputBatch(events) {
|
|
196
|
+
if (!Array.isArray(events)) throw new RelayError("invalid_input", "Input must be an array");
|
|
197
|
+
integer(events.length, 1, MAX_INPUT_BATCH, "input batch length");
|
|
198
|
+
const bytes = new Uint8Array(events.length * INPUT_SIZE);
|
|
199
|
+
for (let index = 0; index < events.length; index++) bytes.set(encodeInputRecord(events[index]), index * INPUT_SIZE);
|
|
200
|
+
return bytes;
|
|
201
|
+
}
|
|
202
|
+
function batches(groups, limit = MAX_INPUT_BATCH) {
|
|
203
|
+
integer(limit, 1, MAX_INPUT_BATCH, "input batch limit");
|
|
204
|
+
const result = [];
|
|
205
|
+
let batch = [];
|
|
206
|
+
for (const group of groups) {
|
|
207
|
+
if (group.length > limit) throw new RelayError("invalid_input", `An input group has more than ${limit} events`);
|
|
208
|
+
if (batch.length + group.length > limit) {
|
|
209
|
+
result.push(batch);
|
|
210
|
+
batch = [];
|
|
211
|
+
}
|
|
212
|
+
batch.push(...group);
|
|
213
|
+
}
|
|
214
|
+
if (batch.length) result.push(batch);
|
|
215
|
+
return result;
|
|
216
|
+
}
|
|
217
|
+
function header(type, generation, sequence, size) {
|
|
218
|
+
integer(type, 1, 6, "message type");
|
|
219
|
+
integer(generation, 1, 4294967295, "generation");
|
|
220
|
+
integer(sequence, 0, 4294967295, "sequence");
|
|
221
|
+
integer(size, 0, 8388620, "payload length");
|
|
222
|
+
const bytes = new Uint8Array(HEADER_SIZE + size);
|
|
223
|
+
const view = new DataView(bytes.buffer);
|
|
224
|
+
view.setUint32(0, MAGIC);
|
|
225
|
+
view.setUint8(4, VERSION);
|
|
226
|
+
view.setUint8(5, type);
|
|
227
|
+
view.setUint32(8, generation);
|
|
228
|
+
view.setUint32(12, sequence);
|
|
229
|
+
view.setUint32(16, size);
|
|
230
|
+
return bytes;
|
|
231
|
+
}
|
|
232
|
+
function encodeInput(event, generation, sequence) {
|
|
233
|
+
const bytes = header(MESSAGE_TYPES.input, generation, sequence, INPUT_SIZE);
|
|
234
|
+
bytes.set(encodeInputRecord(event), HEADER_SIZE);
|
|
235
|
+
return bytes;
|
|
236
|
+
}
|
|
237
|
+
function parseHeader(bytes) {
|
|
238
|
+
const data = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
|
|
239
|
+
if (data.byteLength < HEADER_SIZE || data.byteLength > HEADER_SIZE + 12 + MAX_BYTES_IN_FLIGHT) throw new RelayError("protocol_error", "Invalid message length");
|
|
240
|
+
const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
|
|
241
|
+
const type = view.getUint8(5), flags = view.getUint16(6), generation = view.getUint32(8);
|
|
242
|
+
if (view.getUint32(0) !== MAGIC || view.getUint8(4) !== VERSION || type < 1 || type > 6 || flags > (type === MESSAGE_TYPES.frame ? 1 : 0) || !generation || view.getUint32(16) !== data.byteLength - HEADER_SIZE) {
|
|
243
|
+
throw new RelayError("protocol_error", "Invalid message envelope");
|
|
244
|
+
}
|
|
245
|
+
return { type, flags, generation, sequence: view.getUint32(12), payloadLength: view.getUint32(16) };
|
|
246
|
+
}
|
|
247
|
+
function parseMessage(bytes) {
|
|
248
|
+
const data = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
|
|
249
|
+
const { type, flags, generation, sequence, payloadLength: size } = parseHeader(data);
|
|
250
|
+
const view = new DataView(data.buffer, data.byteOffset + HEADER_SIZE, size);
|
|
251
|
+
const invalid = (what) => new RelayError("protocol_error", `Invalid ${what}`);
|
|
252
|
+
if (type === MESSAGE_TYPES.frame) {
|
|
253
|
+
if (size < 13 || !sequence) throw invalid("frame header");
|
|
254
|
+
const width = view.getUint16(0), height = view.getUint16(2), timestamp = view.getBigUint64(4);
|
|
255
|
+
if (!width || !height || timestamp > BigInt(Number.MAX_SAFE_INTEGER)) throw invalid("frame header");
|
|
256
|
+
return { type: "frame", generation, sequence, keyframe: flags === 1, width, height, timestamp: Number(timestamp), data: data.subarray(HEADER_SIZE + 12) };
|
|
257
|
+
}
|
|
258
|
+
if (type === MESSAGE_TYPES.cursor) {
|
|
259
|
+
if (size < 8 || sequence) throw invalid("cursor envelope");
|
|
260
|
+
const width = view.getUint16(0), height = view.getUint16(2), hotX = view.getUint16(4), hotY = view.getUint16(6);
|
|
261
|
+
if (width > 256 || height > 256 || size !== 8 + width * height * 4 || (width && height ? hotX >= width || hotY >= height : width || height || hotX || hotY)) throw invalid("cursor image");
|
|
262
|
+
return { type: "cursor", generation, width, height, hotX, hotY, pixels: new Uint8ClampedArray(data.buffer, data.byteOffset + HEADER_SIZE + 8, size - 8) };
|
|
263
|
+
}
|
|
264
|
+
if (type === MESSAGE_TYPES.controlReady) {
|
|
265
|
+
if (size !== 4 || sequence || !view.getUint16(0) || !view.getUint16(2)) throw invalid("ready message");
|
|
266
|
+
return { type: "controlReady", generation, width: view.getUint16(0), height: view.getUint16(2) };
|
|
267
|
+
}
|
|
268
|
+
if (type === MESSAGE_TYPES.inputResponse) {
|
|
269
|
+
if (size !== 1 || !sequence || view.getUint8(0) > 2) throw invalid("input response");
|
|
270
|
+
return { type: "inputResponse", generation, sequence, status: view.getUint8(0) };
|
|
271
|
+
}
|
|
272
|
+
throw invalid("message type");
|
|
273
|
+
}
|
|
274
|
+
function socketTarget(origin, path, token) {
|
|
275
|
+
const url = new URL(path, origin);
|
|
276
|
+
url.protocol = origin.protocol === "https:" ? "wss:" : "ws:";
|
|
277
|
+
return { url, protocols: token ? [SUBPROTOCOL, `bearer.${token}`] : [SUBPROTOCOL] };
|
|
278
|
+
}
|
|
279
|
+
var HID_KEYS = {};
|
|
280
|
+
function assignKeys(first, names) {
|
|
281
|
+
names.forEach((name, index) => {
|
|
282
|
+
HID_KEYS[name] = first + index;
|
|
283
|
+
});
|
|
284
|
+
}
|
|
285
|
+
assignKeys(4, Array.from({ length: 26 }, (_, index) => `Key${String.fromCharCode(65 + index)}`));
|
|
286
|
+
assignKeys(30, "Digit1 Digit2 Digit3 Digit4 Digit5 Digit6 Digit7 Digit8 Digit9 Digit0".split(" "));
|
|
287
|
+
assignKeys(40, "Enter Escape Backspace Tab Space Minus Equal BracketLeft BracketRight Backslash".split(" "));
|
|
288
|
+
assignKeys(51, "Semicolon Quote Backquote Comma Period Slash CapsLock".split(" "));
|
|
289
|
+
assignKeys(58, Array.from({ length: 12 }, (_, index) => `F${index + 1}`));
|
|
290
|
+
assignKeys(70, "PrintScreen ScrollLock Pause Insert Home PageUp Delete End PageDown ArrowRight ArrowLeft ArrowDown ArrowUp NumLock".split(" "));
|
|
291
|
+
assignKeys(84, "NumpadDivide NumpadMultiply NumpadSubtract NumpadAdd NumpadEnter Numpad1 Numpad2 Numpad3 Numpad4 Numpad5 Numpad6 Numpad7 Numpad8 Numpad9 Numpad0 NumpadDecimal".split(" "));
|
|
292
|
+
HID_KEYS.IntlBackslash = 100;
|
|
293
|
+
HID_KEYS.ContextMenu = 101;
|
|
294
|
+
assignKeys(104, Array.from({ length: 12 }, (_, index) => `F${index + 13}`));
|
|
295
|
+
assignKeys(224, "ControlLeft ShiftLeft AltLeft MetaLeft ControlRight ShiftRight AltRight MetaRight".split(" "));
|
|
296
|
+
Object.freeze(HID_KEYS);
|
|
297
|
+
var MODIFIERS = Object.freeze({ ctrl: 224, control: 224, shift: 225, alt: 226, super: 227, meta: 227, cmd: 227, win: 227 });
|
|
298
|
+
var NAMED_KEYS = Object.freeze({
|
|
299
|
+
...Object.fromEntries(Object.entries(HID_KEYS).filter(([name]) => !name.startsWith("Key") && !name.startsWith("Digit")).map(([name, code]) => [name.toLowerCase(), code])),
|
|
300
|
+
return: 40,
|
|
301
|
+
esc: 41,
|
|
302
|
+
right: 79,
|
|
303
|
+
left: 80,
|
|
304
|
+
down: 81,
|
|
305
|
+
up: 82,
|
|
306
|
+
menu: 101
|
|
307
|
+
});
|
|
308
|
+
var characters = "abcdefghijklmnopqrstuvwxyz1234567890";
|
|
309
|
+
var punctuation = "-=[]\\";
|
|
310
|
+
var punctuationTail = ";'`,./";
|
|
311
|
+
var shifted = '!@#$%^&*()_+{}|:"~<>?';
|
|
312
|
+
var unshifted = "1234567890-=[]\\;'`,./";
|
|
313
|
+
function comboEvents(spec) {
|
|
314
|
+
if (typeof spec !== "string" || !spec) throw new RelayError("invalid_input", "Invalid key combo");
|
|
315
|
+
const split = spec === "+" || spec.endsWith("++") ? spec.length - 2 : spec.lastIndexOf("+");
|
|
316
|
+
if (split === 0 && spec !== "+") throw new RelayError("invalid_input", `Invalid key combo "${spec}"`);
|
|
317
|
+
const held = split > 0 ? spec.slice(0, split).split("+") : [];
|
|
318
|
+
const key = spec === "+" || spec.endsWith("++") ? "+" : spec.slice(split + 1);
|
|
319
|
+
const modifiers = [];
|
|
320
|
+
for (const name of held) {
|
|
321
|
+
if (!Object.hasOwn(MODIFIERS, name.toLowerCase())) throw new RelayError("invalid_input", `Invalid key combo "${spec}"`);
|
|
322
|
+
const code2 = MODIFIERS[name.toLowerCase()];
|
|
323
|
+
if (!modifiers.includes(code2)) modifiers.push(code2);
|
|
324
|
+
}
|
|
325
|
+
const lower = key.toLowerCase();
|
|
326
|
+
let code = Object.hasOwn(NAMED_KEYS, lower) ? NAMED_KEYS[lower] : Object.hasOwn(MODIFIERS, lower) ? MODIFIERS[lower] : void 0;
|
|
327
|
+
if (code === void 0 && key.length === 1) {
|
|
328
|
+
const shiftedIndex = shifted.indexOf(key);
|
|
329
|
+
const plain = shiftedIndex >= 0 ? unshifted[shiftedIndex] : lower;
|
|
330
|
+
const index = characters.indexOf(plain);
|
|
331
|
+
if (index >= 0) code = index + 4;
|
|
332
|
+
else if (punctuation.includes(plain)) code = punctuation.indexOf(plain) + 45;
|
|
333
|
+
else if (punctuationTail.includes(plain)) code = punctuationTail.indexOf(plain) + 51;
|
|
334
|
+
else code = { "\n": 40, " ": 43, " ": 44 }[plain];
|
|
335
|
+
if ((shiftedIndex >= 0 || /[A-Z]/.test(key)) && !modifiers.includes(225)) modifiers.push(225);
|
|
336
|
+
}
|
|
337
|
+
if (code === void 0 || !key) throw new RelayError("invalid_input", `Unknown key "${key}"`);
|
|
338
|
+
const keys = [...modifiers.filter((modifier) => modifier !== code), code];
|
|
339
|
+
return [...keys.map((key2) => ({ type: "keyDown", key: key2 })), ...keys.reverse().map((key2) => ({ type: "keyUp", key: key2 }))];
|
|
340
|
+
}
|
|
341
|
+
function textEvents(text) {
|
|
342
|
+
if (typeof text !== "string") throw new RelayError("invalid_input", "Text must be a string");
|
|
343
|
+
return Array.from(text, (character) => {
|
|
344
|
+
const codepoint = character.codePointAt(0);
|
|
345
|
+
if (!codepoint || codepoint >= 55296 && codepoint <= 57343) throw new RelayError("invalid_input", "Invalid Unicode scalar");
|
|
346
|
+
return { type: "text", codepoint };
|
|
347
|
+
});
|
|
348
|
+
}
|
|
349
|
+
function isLoopback(hostname) {
|
|
350
|
+
return hostname === "localhost" || hostname === "127.0.0.1";
|
|
351
|
+
}
|
|
352
|
+
function validToken(token) {
|
|
353
|
+
return typeof token === "string" && /^[0-9a-f]{64}$/.test(token);
|
|
354
|
+
}
|
|
355
|
+
function baseUrl(url, token) {
|
|
356
|
+
let parsed;
|
|
357
|
+
try {
|
|
358
|
+
parsed = new URL(url);
|
|
359
|
+
} catch {
|
|
360
|
+
throw new RelayError("invalid_input", "Invalid server URL");
|
|
361
|
+
}
|
|
362
|
+
const local = isLoopback(parsed.hostname);
|
|
363
|
+
if (!["http:", "https:"].includes(parsed.protocol) || !local && parsed.protocol !== "https:" || parsed.username || parsed.password || parsed.pathname !== "/" || parsed.search || parsed.hash) {
|
|
364
|
+
throw new RelayError("invalid_input", "Server URL must be an HTTPS origin or loopback HTTP origin");
|
|
365
|
+
}
|
|
366
|
+
if (token !== void 0 && !validToken(token) || !local && !token) throw new RelayError("invalid_input", "Remote connections require a 64-character hexadecimal token");
|
|
367
|
+
return parsed;
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
// src/sdk/index.ts
|
|
371
|
+
function target({ url = "http://127.0.0.1:8080", timeout = 1e4, token, ca, connect: connect2, signal }) {
|
|
372
|
+
return { base: baseUrl(url, token), timeout: integer(timeout, 1, 2147483647, "timeout"), token, ca, connect: connect2, signal };
|
|
373
|
+
}
|
|
374
|
+
function headers(server, body) {
|
|
375
|
+
const result = server.token ? { Authorization: `Bearer ${server.token}` } : {};
|
|
376
|
+
if (body !== void 0) result["Content-Type"] = "application/octet-stream";
|
|
377
|
+
return result;
|
|
378
|
+
}
|
|
379
|
+
function decode(data, binary) {
|
|
380
|
+
if (binary) return data;
|
|
381
|
+
try {
|
|
382
|
+
return JSON.parse(data.toString("utf8"));
|
|
383
|
+
} catch {
|
|
384
|
+
throw new RelayError("protocol_error", "Invalid JSON response");
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
function nodeRequest(server, path, binary, body) {
|
|
388
|
+
const base = server.base;
|
|
389
|
+
let ca;
|
|
390
|
+
if (server.ca) {
|
|
391
|
+
try {
|
|
392
|
+
ca = readFileSync(server.ca);
|
|
393
|
+
} catch (error) {
|
|
394
|
+
return Promise.reject(new RelayError("io_error", `Cannot read certificate ${server.ca}: ${error instanceof Error ? error.message : String(error)}`));
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
const hostname = server.connect ?? base.hostname.replace(/^\[|\]$/g, "");
|
|
398
|
+
const requestHeaders = headers(server, body);
|
|
399
|
+
if (body !== void 0) requestHeaders["Content-Length"] = String(body.length);
|
|
400
|
+
if (server.connect) requestHeaders.Host = base.host;
|
|
401
|
+
const options = {
|
|
402
|
+
protocol: base.protocol,
|
|
403
|
+
hostname,
|
|
404
|
+
port: Number(base.port || (base.protocol === "https:" ? 443 : 80)),
|
|
405
|
+
path: `${base.pathname === "/" ? "" : base.pathname}${path}`,
|
|
406
|
+
method: body === void 0 ? "GET" : "POST",
|
|
407
|
+
headers: requestHeaders,
|
|
408
|
+
timeout: server.timeout,
|
|
409
|
+
signal: server.signal
|
|
410
|
+
};
|
|
411
|
+
if (ca) {
|
|
412
|
+
options.ca = ca;
|
|
413
|
+
options.checkServerIdentity = () => void 0;
|
|
414
|
+
}
|
|
415
|
+
return new Promise((resolve, reject) => {
|
|
416
|
+
const transport = base.protocol === "https:" ? httpsRequest : httpRequest;
|
|
417
|
+
const sent = transport(options, (response) => {
|
|
418
|
+
const chunks = [];
|
|
419
|
+
let size = 0;
|
|
420
|
+
response.on("data", (chunk) => {
|
|
421
|
+
size += chunk.length;
|
|
422
|
+
if (size > 8 * 1024 * 1024) sent.destroy(new RelayError("protocol_error", "Response exceeds 8 MiB"));
|
|
423
|
+
else chunks.push(chunk);
|
|
424
|
+
});
|
|
425
|
+
response.once("end", () => {
|
|
426
|
+
clearTimeout(timer);
|
|
427
|
+
const status2 = response.statusCode ?? 0;
|
|
428
|
+
const data = Buffer.concat(chunks);
|
|
429
|
+
if (status2 >= 400) {
|
|
430
|
+
let detail = null;
|
|
431
|
+
try {
|
|
432
|
+
detail = JSON.parse(data.toString("utf8"));
|
|
433
|
+
} catch {
|
|
434
|
+
}
|
|
435
|
+
reject(responseError(status2, detail));
|
|
436
|
+
return;
|
|
437
|
+
}
|
|
438
|
+
if (status2 >= 300) {
|
|
439
|
+
reject(new RelayError("component_failed", "Server answered with a redirect; refusing to follow it"));
|
|
440
|
+
return;
|
|
441
|
+
}
|
|
442
|
+
try {
|
|
443
|
+
resolve(decode(data, binary));
|
|
444
|
+
} catch (error) {
|
|
445
|
+
reject(error);
|
|
446
|
+
}
|
|
447
|
+
});
|
|
448
|
+
});
|
|
449
|
+
const timer = setTimeout(() => sent.destroy(new RelayError("timeout", "The request timed out.")), server.timeout);
|
|
450
|
+
sent.once("timeout", () => sent.destroy(new RelayError("timeout", "The request timed out.")));
|
|
451
|
+
sent.once("error", (error) => {
|
|
452
|
+
clearTimeout(timer);
|
|
453
|
+
if (server.signal?.aborted) reject(new RelayError("canceled", "Request canceled."));
|
|
454
|
+
else if (error instanceof RelayError) reject(error);
|
|
455
|
+
else reject(networkError(error));
|
|
456
|
+
});
|
|
457
|
+
if (body !== void 0) sent.write(Buffer.from(body));
|
|
458
|
+
sent.end();
|
|
459
|
+
});
|
|
460
|
+
}
|
|
461
|
+
async function request(server, path, binary = false, body) {
|
|
462
|
+
if (server.signal?.aborted) throw new RelayError("canceled", "Request canceled.");
|
|
463
|
+
if (server.ca || server.connect) return nodeRequest(server, path, binary, body);
|
|
464
|
+
const controller = new AbortController();
|
|
465
|
+
let timer;
|
|
466
|
+
const deadline = new Promise((_, reject) => {
|
|
467
|
+
timer = setTimeout(() => {
|
|
468
|
+
controller.abort();
|
|
469
|
+
reject(new RelayError("timeout", "The request timed out."));
|
|
470
|
+
}, server.timeout);
|
|
471
|
+
});
|
|
472
|
+
const operation = (async () => {
|
|
473
|
+
try {
|
|
474
|
+
const response = await fetch(new URL(path, server.base), {
|
|
475
|
+
signal: server.signal ? AbortSignal.any([controller.signal, server.signal]) : controller.signal,
|
|
476
|
+
redirect: "error",
|
|
477
|
+
headers: headers(server, body),
|
|
478
|
+
method: body === void 0 ? "GET" : "POST",
|
|
479
|
+
body: body === void 0 ? void 0 : Buffer.from(body)
|
|
480
|
+
});
|
|
481
|
+
if (!response.ok) {
|
|
482
|
+
let detail = null;
|
|
483
|
+
try {
|
|
484
|
+
detail = await response.json();
|
|
485
|
+
} catch (error) {
|
|
486
|
+
if (!(error instanceof SyntaxError)) throw error;
|
|
487
|
+
}
|
|
488
|
+
throw responseError(response.status, detail);
|
|
489
|
+
}
|
|
490
|
+
if (!binary) {
|
|
491
|
+
try {
|
|
492
|
+
return await response.json();
|
|
493
|
+
} catch (error) {
|
|
494
|
+
if (error instanceof SyntaxError) throw new RelayError("protocol_error", "Invalid JSON response");
|
|
495
|
+
throw error;
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
if (!response.body) throw new RelayError("protocol_error", "Missing screenshot body");
|
|
499
|
+
const chunks = [];
|
|
500
|
+
let size = 0;
|
|
501
|
+
const reader = response.body.getReader();
|
|
502
|
+
try {
|
|
503
|
+
for (; ; ) {
|
|
504
|
+
const chunk = await reader.read();
|
|
505
|
+
if (chunk.done) break;
|
|
506
|
+
size += chunk.value.length;
|
|
507
|
+
if (size > 8 * 1024 * 1024) {
|
|
508
|
+
controller.abort();
|
|
509
|
+
throw new RelayError("protocol_error", "Screenshot exceeds 8 MiB");
|
|
510
|
+
}
|
|
511
|
+
chunks.push(chunk.value);
|
|
512
|
+
}
|
|
513
|
+
} finally {
|
|
514
|
+
reader.releaseLock();
|
|
515
|
+
}
|
|
516
|
+
return Buffer.concat(chunks, size);
|
|
517
|
+
} catch (error) {
|
|
518
|
+
if (error instanceof RelayError) throw error;
|
|
519
|
+
if (server.signal?.aborted) throw new RelayError("canceled", "Request canceled.");
|
|
520
|
+
if (controller.signal.aborted) throw new RelayError("timeout", "The request timed out.");
|
|
521
|
+
throw networkError(error);
|
|
522
|
+
}
|
|
523
|
+
})();
|
|
524
|
+
try {
|
|
525
|
+
return await Promise.race([operation, deadline]);
|
|
526
|
+
} finally {
|
|
527
|
+
clearTimeout(timer);
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
async function capabilities(options = {}) {
|
|
531
|
+
return request(target(options), "/capabilities");
|
|
532
|
+
}
|
|
533
|
+
async function status(options = {}) {
|
|
534
|
+
return request(target(options), "/metrics");
|
|
535
|
+
}
|
|
536
|
+
async function screenshot(options = {}, path) {
|
|
537
|
+
const bytes = await request(target(options), "/screenshot.png", true);
|
|
538
|
+
if (path !== void 0) {
|
|
539
|
+
try {
|
|
540
|
+
await writeFile(path, bytes);
|
|
541
|
+
} catch (error) {
|
|
542
|
+
throw new RelayError("io_error", `Screenshot write failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
return bytes;
|
|
546
|
+
}
|
|
547
|
+
function createClient(options = {}) {
|
|
548
|
+
const server = target(options);
|
|
549
|
+
const send = async (groups) => {
|
|
550
|
+
if (!groups.length) return { events: 0 };
|
|
551
|
+
const capabilities2 = await request(server, "/capabilities");
|
|
552
|
+
const limit = integer(capabilities2.max_input_batch, 1, MAX_INPUT_BATCH, "max_input_batch");
|
|
553
|
+
const payloads = batches(groups, limit).map((events2) => ({ count: events2.length, body: encodeInputBatch(events2) }));
|
|
554
|
+
let events = 0;
|
|
555
|
+
for (const payload of payloads) {
|
|
556
|
+
let result;
|
|
557
|
+
try {
|
|
558
|
+
result = await request(server, "/input", false, payload.body);
|
|
559
|
+
} catch (error) {
|
|
560
|
+
if (error instanceof RelayError) {
|
|
561
|
+
const partial = Math.min(payload.count, typeof error.data?.applied === "number" ? error.data.applied : typeof error.data?.index === "number" ? error.data.index : 0);
|
|
562
|
+
const applied = events + partial;
|
|
563
|
+
Object.assign(error, { applied, data: { ...error.data, applied } });
|
|
564
|
+
}
|
|
565
|
+
throw error;
|
|
566
|
+
}
|
|
567
|
+
if (!result || result.applied !== payload.count) throw new RelayError("protocol_error", "Invalid input result");
|
|
568
|
+
events += result.applied;
|
|
569
|
+
}
|
|
570
|
+
return { events };
|
|
571
|
+
};
|
|
572
|
+
return {
|
|
573
|
+
capabilities: () => request(server, "/capabilities"),
|
|
574
|
+
status: () => request(server, "/metrics"),
|
|
575
|
+
screenshot: () => request(server, "/screenshot.png", true),
|
|
576
|
+
async click(x, y, { button = "left" } = {}) {
|
|
577
|
+
const buttons = { left: 1, middle: 2, right: 3 };
|
|
578
|
+
if (!Object.hasOwn(buttons, button)) throw new RelayError("invalid_input", "Invalid button");
|
|
579
|
+
const code = buttons[button];
|
|
580
|
+
return send([[{ type: "buttonDown", button: code, x, y }, { type: "buttonUp", button: code, x, y }]]);
|
|
581
|
+
},
|
|
582
|
+
async move(x, y) {
|
|
583
|
+
return send([[{ type: "pointerMove", x, y }]]);
|
|
584
|
+
},
|
|
585
|
+
async scroll(x, y, { dx = 0, dy = 0 } = {}) {
|
|
586
|
+
integer(dx, -Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER, "dx");
|
|
587
|
+
integer(dy, -Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER, "dy");
|
|
588
|
+
if (!dx && !dy) throw new RelayError("invalid_input", "Nothing to scroll");
|
|
589
|
+
integer(1 + Math.ceil(Math.abs(dx) / 10) + Math.ceil(Math.abs(dy) / 10), 1, MAX_INPUT_BATCH, "scroll event count");
|
|
590
|
+
const events = [{ type: "pointerMove", x, y }];
|
|
591
|
+
for (const [axis, notches] of [["vertical", dy], ["horizontal", dx]]) {
|
|
592
|
+
let remaining = notches;
|
|
593
|
+
while (remaining) {
|
|
594
|
+
const step = Math.max(-10, Math.min(10, remaining));
|
|
595
|
+
events.push({ type: "wheel", axis, delta: step * 120, x, y });
|
|
596
|
+
remaining -= step;
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
return send([events]);
|
|
600
|
+
},
|
|
601
|
+
async key(...combos) {
|
|
602
|
+
if (!combos.length) throw new RelayError("invalid_input", "At least one key combo is required");
|
|
603
|
+
return send(combos.map(comboEvents));
|
|
604
|
+
},
|
|
605
|
+
async type(text) {
|
|
606
|
+
return send(textEvents(text).map((event) => [event]));
|
|
607
|
+
},
|
|
608
|
+
async input(events) {
|
|
609
|
+
if (!Array.isArray(events) || !events.length) throw new RelayError("invalid_input", "Input must be a nonempty array");
|
|
610
|
+
return send(events.map((event) => [event]));
|
|
611
|
+
}
|
|
612
|
+
};
|
|
613
|
+
}
|
|
614
|
+
async function connect(options = {}) {
|
|
615
|
+
const server = target(options);
|
|
616
|
+
if (server.ca || server.connect) throw new RelayError("invalid_option", "Control connections do not support ca or connect options.");
|
|
617
|
+
if (server.signal?.aborted) throw new RelayError("canceled", "Control connection canceled.");
|
|
618
|
+
if (typeof WebSocket === "undefined") throw new RelayError("unsupported_platform", "Control sessions require Node 22 or newer");
|
|
619
|
+
const { url, protocols } = socketTarget(server.base, "/control", server.token);
|
|
620
|
+
const socket = new WebSocket(url, protocols);
|
|
621
|
+
socket.binaryType = "arraybuffer";
|
|
622
|
+
let generation = 0, sequence = 0, closed = false, ready = false;
|
|
623
|
+
const pending = /* @__PURE__ */ new Map();
|
|
624
|
+
let resolveReady;
|
|
625
|
+
let rejectReady;
|
|
626
|
+
const initial = new Promise((resolve, reject) => {
|
|
627
|
+
resolveReady = resolve;
|
|
628
|
+
rejectReady = reject;
|
|
629
|
+
});
|
|
630
|
+
const finish = (error) => {
|
|
631
|
+
if (closed) return;
|
|
632
|
+
closed = true;
|
|
633
|
+
server.signal?.removeEventListener("abort", cancel);
|
|
634
|
+
if (!ready) rejectReady(error);
|
|
635
|
+
for (const item of pending.values()) {
|
|
636
|
+
clearTimeout(item.timer);
|
|
637
|
+
item.reject(error);
|
|
638
|
+
}
|
|
639
|
+
pending.clear();
|
|
640
|
+
if (socket.readyState < WebSocket.CLOSING) socket.close();
|
|
641
|
+
};
|
|
642
|
+
const cancel = () => finish(new RelayError("canceled", "Control connection canceled."));
|
|
643
|
+
server.signal?.addEventListener("abort", cancel, { once: true });
|
|
644
|
+
socket.addEventListener("error", () => finish(new RelayError("unreachable", "The connection failed.")));
|
|
645
|
+
socket.addEventListener("close", () => finish(new RelayError("disconnected", "Control connection closed")));
|
|
646
|
+
socket.addEventListener("message", ({ data }) => {
|
|
647
|
+
try {
|
|
648
|
+
if (!(data instanceof ArrayBuffer)) throw new Error("Non-binary message");
|
|
649
|
+
const message = parseMessage(data);
|
|
650
|
+
if (!ready) {
|
|
651
|
+
if (message.type !== "controlReady") throw new Error("Invalid ready message");
|
|
652
|
+
generation = message.generation;
|
|
653
|
+
ready = true;
|
|
654
|
+
resolveReady({ width: message.width, height: message.height });
|
|
655
|
+
return;
|
|
656
|
+
}
|
|
657
|
+
if (message.type !== "inputResponse" || message.generation !== generation || !pending.has(message.sequence)) throw new Error("Invalid input response");
|
|
658
|
+
const item = pending.get(message.sequence);
|
|
659
|
+
pending.delete(message.sequence);
|
|
660
|
+
clearTimeout(item.timer);
|
|
661
|
+
if (message.status) item.reject(new RelayError(message.status === 1 ? "invalid_input" : "unsupported_input", "Input rejected by server"));
|
|
662
|
+
else item.resolve();
|
|
663
|
+
} catch (error) {
|
|
664
|
+
finish(new RelayError("protocol_error", error instanceof Error ? error.message : String(error)));
|
|
665
|
+
}
|
|
666
|
+
});
|
|
667
|
+
const timer = setTimeout(() => finish(new RelayError("timeout", "Control connection timed out")), server.timeout);
|
|
668
|
+
let surface;
|
|
669
|
+
try {
|
|
670
|
+
surface = await initial;
|
|
671
|
+
} finally {
|
|
672
|
+
clearTimeout(timer);
|
|
673
|
+
}
|
|
674
|
+
return {
|
|
675
|
+
surface,
|
|
676
|
+
capabilities: () => request(server, "/capabilities"),
|
|
677
|
+
status: () => request(server, "/metrics"),
|
|
678
|
+
async screenshot(path) {
|
|
679
|
+
if (closed) throw new RelayError("disconnected", "Control connection closed");
|
|
680
|
+
return screenshot({ ...options, url: server.base.href, timeout: server.timeout, token: server.token }, path);
|
|
681
|
+
},
|
|
682
|
+
input(event) {
|
|
683
|
+
if (closed) return Promise.reject(new RelayError("disconnected", "Control connection closed"));
|
|
684
|
+
if (pending.size >= MAX_INPUT_PENDING) return Promise.reject(new RelayError("busy", "Too many pending input requests"));
|
|
685
|
+
if (sequence === 4294967295) return Promise.reject(new RelayError("protocol_error", "Input sequence exhausted; reconnect"));
|
|
686
|
+
let message;
|
|
687
|
+
try {
|
|
688
|
+
message = encodeInput(event, generation, sequence + 1);
|
|
689
|
+
} catch (error) {
|
|
690
|
+
return Promise.reject(error);
|
|
691
|
+
}
|
|
692
|
+
sequence++;
|
|
693
|
+
return new Promise((resolve, reject) => {
|
|
694
|
+
const requestSequence = sequence;
|
|
695
|
+
const timer2 = setTimeout(() => {
|
|
696
|
+
pending.delete(requestSequence);
|
|
697
|
+
reject(new RelayError("timeout", "Input acknowledgement timed out"));
|
|
698
|
+
finish(new RelayError("disconnected", "Control connection timed out"));
|
|
699
|
+
}, server.timeout);
|
|
700
|
+
pending.set(requestSequence, { resolve, reject, timer: timer2 });
|
|
701
|
+
try {
|
|
702
|
+
socket.send(Buffer.from(message));
|
|
703
|
+
} catch (error) {
|
|
704
|
+
clearTimeout(timer2);
|
|
705
|
+
pending.delete(requestSequence);
|
|
706
|
+
reject(networkError(error));
|
|
707
|
+
finish(new RelayError("disconnected", "Control connection failed"));
|
|
708
|
+
}
|
|
709
|
+
});
|
|
710
|
+
},
|
|
711
|
+
close() {
|
|
712
|
+
finish(new RelayError("disconnected", "Control connection closed"));
|
|
713
|
+
}
|
|
714
|
+
};
|
|
715
|
+
}
|
|
716
|
+
export {
|
|
717
|
+
ERROR_REASONS,
|
|
718
|
+
RelayError,
|
|
719
|
+
capabilities,
|
|
720
|
+
connect,
|
|
721
|
+
createClient,
|
|
722
|
+
screenshot,
|
|
723
|
+
status
|
|
724
|
+
};
|