relapsesdk 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 +232 -0
- package/README.md +150 -2
- package/dist/channel.d.ts +33 -0
- package/dist/channel.js +40 -0
- package/dist/client.d.ts +28 -0
- package/dist/client.js +58 -0
- package/dist/discovery.d.ts +12 -0
- package/dist/discovery.js +80 -0
- package/dist/errors.d.ts +5 -0
- package/dist/errors.js +10 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.js +10 -0
- package/dist/internal/json.d.ts +5 -0
- package/dist/internal/json.js +16 -0
- package/dist/internal/operation.d.ts +13 -0
- package/dist/internal/operation.js +53 -0
- package/dist/internal/transport.d.ts +25 -0
- package/dist/internal/transport.js +204 -0
- package/dist/internal/wait-for.d.ts +3 -0
- package/dist/internal/wait-for.js +36 -0
- package/dist/launcher.d.ts +12 -0
- package/dist/launcher.js +35 -0
- package/dist/main-channel.d.ts +74 -0
- package/dist/main-channel.js +234 -0
- package/dist/profiles.d.ts +20 -0
- package/dist/profiles.js +56 -0
- package/examples/channel.mjs +21 -0
- package/examples/consumer.ts +135 -0
- package/examples/execute.mjs +23 -0
- package/package.json +58 -4
- package/src/channel.ts +72 -0
- package/src/client.ts +77 -0
- package/src/discovery.ts +81 -0
- package/src/errors.ts +26 -0
- package/src/index.ts +22 -0
- package/src/internal/json.ts +26 -0
- package/src/internal/operation.ts +70 -0
- package/src/internal/transport.ts +214 -0
- package/src/internal/wait-for.ts +41 -0
- package/src/launcher.ts +44 -0
- package/src/main-channel.ts +296 -0
- package/src/profiles.ts +75 -0
- package/tsconfig.json +20 -0
package/src/client.ts
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
// Copyright (C) 2026 vpu007
|
|
2
|
+
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
3
|
+
|
|
4
|
+
import { basename } from "node:path";
|
|
5
|
+
import { Channel } from "./channel.js";
|
|
6
|
+
import { MainChannel } from "./main-channel.js";
|
|
7
|
+
import { RelapseError } from "./errors.js";
|
|
8
|
+
import { isValidName } from "./profiles.js";
|
|
9
|
+
import type { WaitOptions } from "./internal/operation.js";
|
|
10
|
+
|
|
11
|
+
export interface ClientOptions extends WaitOptions {
|
|
12
|
+
socketPath: string;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface ClientInfo {
|
|
16
|
+
socketPath: string;
|
|
17
|
+
/** Inferred from the socket filename; null for an unnamed client. */
|
|
18
|
+
profile: string | null;
|
|
19
|
+
pid: number;
|
|
20
|
+
ready: boolean;
|
|
21
|
+
session: number;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export class Client {
|
|
25
|
+
readonly mainChannel: MainChannel;
|
|
26
|
+
readonly #channels = new Set<Channel>();
|
|
27
|
+
#closed = false;
|
|
28
|
+
|
|
29
|
+
private constructor(mainChannel: MainChannel) {
|
|
30
|
+
this.mainChannel = mainChannel;
|
|
31
|
+
mainChannel.once("close", () => this.close());
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
static async connect(options: ClientOptions): Promise<Client> {
|
|
35
|
+
return new Client(await MainChannel.connect(options));
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
get socketPath(): string { return this.mainChannel.socketPath; }
|
|
39
|
+
get connected(): boolean { return !this.#closed && this.mainChannel.connected; }
|
|
40
|
+
get pid(): number { return this.mainChannel.hello.pid; }
|
|
41
|
+
get profile(): string | null {
|
|
42
|
+
// Older executors report "default" in hello even when using a named profile.
|
|
43
|
+
const match = /^relapse-(.+)\.sock$/u.exec(basename(this.socketPath));
|
|
44
|
+
return match?.[1] && isValidName(match[1]) ? match[1] : null;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
get info(): ClientInfo {
|
|
48
|
+
return {
|
|
49
|
+
socketPath: this.socketPath,
|
|
50
|
+
profile: this.profile,
|
|
51
|
+
pid: this.pid,
|
|
52
|
+
ready: this.mainChannel.ready,
|
|
53
|
+
session: this.mainChannel.session,
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
async openChannel(name: string, options: WaitOptions = {}): Promise<Channel> {
|
|
58
|
+
if (!this.connected) throw new RelapseError("disconnected", "Client is disconnected.");
|
|
59
|
+
const channel = await Channel.connect({ ...options, socketPath: this.socketPath, name });
|
|
60
|
+
if (!this.connected) {
|
|
61
|
+
channel.close();
|
|
62
|
+
throw new RelapseError("disconnected", "Client disconnected while opening the channel.");
|
|
63
|
+
}
|
|
64
|
+
this.#channels.add(channel);
|
|
65
|
+
channel.once("close", () => this.#channels.delete(channel));
|
|
66
|
+
return channel;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Closes @main and any channels opened through this client. */
|
|
70
|
+
close(): void {
|
|
71
|
+
if (this.#closed) return;
|
|
72
|
+
this.#closed = true;
|
|
73
|
+
for (const channel of this.#channels) channel.close();
|
|
74
|
+
this.#channels.clear();
|
|
75
|
+
this.mainChannel.close();
|
|
76
|
+
}
|
|
77
|
+
}
|
package/src/discovery.ts
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
// Copyright (C) 2026 vpu007
|
|
2
|
+
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
3
|
+
|
|
4
|
+
import { lstat, readdir } from "node:fs/promises";
|
|
5
|
+
import { isAbsolute, join } from "node:path";
|
|
6
|
+
import { setTimeout as sleep } from "node:timers/promises";
|
|
7
|
+
import { Client, type ClientInfo } from "./client.js";
|
|
8
|
+
import { RelapseError } from "./errors.js";
|
|
9
|
+
import { isValidName } from "./profiles.js";
|
|
10
|
+
import { resolveTimeout, type WaitOptions } from "./internal/operation.js";
|
|
11
|
+
|
|
12
|
+
export interface DiscoveryOptions extends WaitOptions {
|
|
13
|
+
directory?: string;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export interface WatchOptions extends DiscoveryOptions {
|
|
17
|
+
intervalMs?: number;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Finds responsive @main endpoints belonging to the current user. */
|
|
21
|
+
export async function listClients(options: DiscoveryOptions = {}): Promise<ClientInfo[]> {
|
|
22
|
+
if (options.signal?.aborted) throw new RelapseError("aborted", "Discovery aborted.");
|
|
23
|
+
const directory = options.directory ?? "/tmp";
|
|
24
|
+
if (!isAbsolute(directory)) throw new TypeError("Discovery directory must be an absolute path.");
|
|
25
|
+
const timeoutMs = resolveTimeout(options.timeoutMs, 1000);
|
|
26
|
+
const entries = await readdir(directory, { withFileTypes: true }).catch((error: NodeJS.ErrnoException) => {
|
|
27
|
+
if (error.code === "ENOENT") return [];
|
|
28
|
+
throw error;
|
|
29
|
+
});
|
|
30
|
+
const paths = entries.filter(entry => {
|
|
31
|
+
const match = /^relapse-(.+)\.sock$/u.exec(entry.name);
|
|
32
|
+
return entry.isSocket() && (entry.name === "relapse.sock" || (match?.[1] && isValidName(match[1])));
|
|
33
|
+
}).map(entry => join(directory, entry.name)).sort();
|
|
34
|
+
|
|
35
|
+
const result: ClientInfo[] = [];
|
|
36
|
+
for (let offset = 0; offset < paths.length; offset += 4) {
|
|
37
|
+
const batch = await Promise.all(paths.slice(offset, offset + 4).map(async socketPath => {
|
|
38
|
+
let client: Client | undefined;
|
|
39
|
+
try {
|
|
40
|
+
const stat = await lstat(socketPath);
|
|
41
|
+
if (!stat.isSocket() || stat.uid !== process.getuid?.()) return undefined;
|
|
42
|
+
client = await Client.connect({
|
|
43
|
+
socketPath,
|
|
44
|
+
timeoutMs,
|
|
45
|
+
...(options.signal ? { signal: options.signal } : {}),
|
|
46
|
+
});
|
|
47
|
+
return client.info;
|
|
48
|
+
} catch (error) {
|
|
49
|
+
if (options.signal?.aborted) throw new RelapseError("aborted", "Discovery aborted.", { cause: error });
|
|
50
|
+
return undefined;
|
|
51
|
+
} finally {
|
|
52
|
+
client?.close();
|
|
53
|
+
}
|
|
54
|
+
}));
|
|
55
|
+
for (const client of batch) if (client) result.push(client);
|
|
56
|
+
}
|
|
57
|
+
return result;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Yields an initial snapshot, then changed snapshots. Abort or break to stop polling. */
|
|
61
|
+
export async function* watchClients(options: WatchOptions = {}): AsyncGenerator<ClientInfo[]> {
|
|
62
|
+
const interval = options.intervalMs ?? 1000;
|
|
63
|
+
if (!Number.isInteger(interval) || interval < 1 || interval > 2_147_483_647) {
|
|
64
|
+
throw new RangeError("intervalMs must be an integer between 1 and 2147483647.");
|
|
65
|
+
}
|
|
66
|
+
let previous: string | undefined;
|
|
67
|
+
while (!options.signal?.aborted) {
|
|
68
|
+
try {
|
|
69
|
+
const clients = await listClients(options);
|
|
70
|
+
const snapshot = JSON.stringify(clients);
|
|
71
|
+
if (snapshot !== previous) {
|
|
72
|
+
previous = snapshot;
|
|
73
|
+
yield clients;
|
|
74
|
+
}
|
|
75
|
+
await sleep(interval, undefined, options.signal ? { signal: options.signal } : {});
|
|
76
|
+
} catch (error) {
|
|
77
|
+
if (options.signal?.aborted) return;
|
|
78
|
+
throw error;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
}
|
package/src/errors.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
// Copyright (C) 2026 vpu007
|
|
2
|
+
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
3
|
+
|
|
4
|
+
export type ErrorCode =
|
|
5
|
+
| "connection_failed"
|
|
6
|
+
| "disconnected"
|
|
7
|
+
| "protocol_error"
|
|
8
|
+
| "channel_rejected"
|
|
9
|
+
| "message_too_large"
|
|
10
|
+
| "backpressure"
|
|
11
|
+
| "not_ready"
|
|
12
|
+
| "execution_failed"
|
|
13
|
+
| "session_changed"
|
|
14
|
+
| "timeout"
|
|
15
|
+
| "aborted";
|
|
16
|
+
|
|
17
|
+
export class RelapseError extends Error {
|
|
18
|
+
constructor(
|
|
19
|
+
public readonly code: ErrorCode,
|
|
20
|
+
message: string,
|
|
21
|
+
options?: ErrorOptions,
|
|
22
|
+
) {
|
|
23
|
+
super(message, options);
|
|
24
|
+
this.name = "RelapseError";
|
|
25
|
+
}
|
|
26
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// Copyright (C) 2026 vpu007
|
|
2
|
+
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
3
|
+
|
|
4
|
+
/// <reference types="node" preserve="true" />
|
|
5
|
+
|
|
6
|
+
export { Channel, type ChannelOptions, type ChannelEvents, type ChannelConnection } from "./channel.js";
|
|
7
|
+
export {
|
|
8
|
+
Client, type ClientOptions, type ClientInfo,
|
|
9
|
+
} from "./client.js";
|
|
10
|
+
export {
|
|
11
|
+
MainChannel, type MainChannelOptions, type MainChannelEvents,
|
|
12
|
+
type MainRequest, type MainMessage, type MainHello, type MainStatus, type MainError,
|
|
13
|
+
type ExecuteOptions, type ExecutionResult, type LogEntry,
|
|
14
|
+
} from "./main-channel.js";
|
|
15
|
+
export { listClients, watchClients, type DiscoveryOptions, type WatchOptions } from "./discovery.js";
|
|
16
|
+
export { launch, type LaunchOptions } from "./launcher.js";
|
|
17
|
+
export { RelapseError, type ErrorCode } from "./errors.js";
|
|
18
|
+
export * as profiles from "./profiles.js";
|
|
19
|
+
export type { ProfileInfo, ProfileOptions, ProfilePaths } from "./profiles.js";
|
|
20
|
+
export type { JsonValue } from "./internal/json.js";
|
|
21
|
+
export type { WaitOptions } from "./internal/operation.js";
|
|
22
|
+
export type { CloseInfo } from "./internal/transport.js";
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
// Copyright (C) 2026 vpu007
|
|
2
|
+
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
3
|
+
|
|
4
|
+
export type JsonValue =
|
|
5
|
+
| null
|
|
6
|
+
| boolean
|
|
7
|
+
| number
|
|
8
|
+
| string
|
|
9
|
+
| readonly JsonValue[]
|
|
10
|
+
| { readonly [key: string]: JsonValue };
|
|
11
|
+
|
|
12
|
+
export function isRecord(value: unknown): value is Record<string, unknown> {
|
|
13
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function encodeJson(value: JsonValue): Buffer {
|
|
17
|
+
const text = JSON.stringify(value, (_key, item: unknown) => {
|
|
18
|
+
if (typeof item === "undefined" || typeof item === "function" ||
|
|
19
|
+
typeof item === "symbol" || typeof item === "bigint" ||
|
|
20
|
+
(typeof item === "number" && !Number.isFinite(item))) {
|
|
21
|
+
throw new TypeError("Messages must contain only JSON-compatible values.");
|
|
22
|
+
}
|
|
23
|
+
return item;
|
|
24
|
+
});
|
|
25
|
+
return Buffer.from(text, "utf8");
|
|
26
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
// Copyright (C) 2026 vpu007
|
|
2
|
+
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
3
|
+
|
|
4
|
+
import { RelapseError } from "../errors.js";
|
|
5
|
+
|
|
6
|
+
export interface WaitOptions {
|
|
7
|
+
/** Milliseconds to wait. Zero disables the timeout. */
|
|
8
|
+
timeoutMs?: number;
|
|
9
|
+
signal?: AbortSignal;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface Operation<T> {
|
|
13
|
+
promise: Promise<T>;
|
|
14
|
+
readonly settled: boolean;
|
|
15
|
+
resolve(value: T): void;
|
|
16
|
+
reject(error: unknown): void;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function resolveTimeout(timeout: number | undefined, fallback: number): number {
|
|
20
|
+
const value = timeout ?? fallback;
|
|
21
|
+
if (!Number.isInteger(value) || value < 0 || value > 2_147_483_647) {
|
|
22
|
+
throw new RangeError("timeoutMs must be an integer between 0 and 2147483647.");
|
|
23
|
+
}
|
|
24
|
+
return value;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function operation<T>(
|
|
28
|
+
options: WaitOptions,
|
|
29
|
+
defaultTimeout: number,
|
|
30
|
+
): Operation<T> {
|
|
31
|
+
const timeout = resolveTimeout(options.timeoutMs, defaultTimeout);
|
|
32
|
+
const signal = options.signal;
|
|
33
|
+
|
|
34
|
+
let settled = false;
|
|
35
|
+
let timer: NodeJS.Timeout | undefined;
|
|
36
|
+
let resolve!: (value: T) => void;
|
|
37
|
+
let reject!: (error: unknown) => void;
|
|
38
|
+
const promise = new Promise<T>((accept, fail) => {
|
|
39
|
+
resolve = accept;
|
|
40
|
+
reject = fail;
|
|
41
|
+
});
|
|
42
|
+
const cleanup = () => {
|
|
43
|
+
settled = true;
|
|
44
|
+
clearTimeout(timer);
|
|
45
|
+
signal?.removeEventListener("abort", abort);
|
|
46
|
+
};
|
|
47
|
+
const result: Operation<T> = {
|
|
48
|
+
promise,
|
|
49
|
+
get settled() { return settled; },
|
|
50
|
+
resolve(value) {
|
|
51
|
+
if (settled) return;
|
|
52
|
+
cleanup();
|
|
53
|
+
resolve(value);
|
|
54
|
+
},
|
|
55
|
+
reject(error) {
|
|
56
|
+
if (settled) return;
|
|
57
|
+
cleanup();
|
|
58
|
+
reject(error);
|
|
59
|
+
},
|
|
60
|
+
};
|
|
61
|
+
const abort = () => result.reject(new RelapseError("aborted", "Operation aborted.", {
|
|
62
|
+
cause: signal?.reason,
|
|
63
|
+
}));
|
|
64
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
65
|
+
if (signal?.aborted) abort();
|
|
66
|
+
if (!settled && timeout > 0) {
|
|
67
|
+
timer = setTimeout(() => result.reject(new RelapseError("timeout", "Operation timed out.")), timeout);
|
|
68
|
+
}
|
|
69
|
+
return result;
|
|
70
|
+
}
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
// Copyright (C) 2026 vpu007
|
|
2
|
+
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
3
|
+
|
|
4
|
+
import { Socket } from "node:net";
|
|
5
|
+
import { isAbsolute } from "node:path";
|
|
6
|
+
import { RelapseError } from "../errors.js";
|
|
7
|
+
import { encodeJson, isRecord, type JsonValue } from "./json.js";
|
|
8
|
+
import { operation, type Operation, type WaitOptions } from "./operation.js";
|
|
9
|
+
|
|
10
|
+
const MAX_MESSAGE_BYTES = 8 * 1024 * 1024;
|
|
11
|
+
const MAX_QUEUED_BYTES = 16 * 1024 * 1024;
|
|
12
|
+
const MAX_QUEUED_MESSAGES = 256;
|
|
13
|
+
const MAX_OPENING_BYTES = 4096;
|
|
14
|
+
|
|
15
|
+
export interface CloseInfo {
|
|
16
|
+
reason: "local" | "peer" | "error";
|
|
17
|
+
error?: RelapseError;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
interface Handlers {
|
|
21
|
+
message(value: unknown): void;
|
|
22
|
+
close(info: CloseInfo): void;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export class Transport {
|
|
26
|
+
readonly #socket = new Socket();
|
|
27
|
+
readonly #handlers: Handlers;
|
|
28
|
+
readonly #header = Buffer.alloc(4);
|
|
29
|
+
readonly #writes = new Set<(error: RelapseError) => void>();
|
|
30
|
+
#opening: Operation<void> | undefined;
|
|
31
|
+
#opened = false;
|
|
32
|
+
#closed = false;
|
|
33
|
+
#paused = false;
|
|
34
|
+
#headerUsed = 0;
|
|
35
|
+
#body: Buffer | undefined;
|
|
36
|
+
#bodyUsed = 0;
|
|
37
|
+
#rest: Buffer | undefined;
|
|
38
|
+
#queuedBytes = 0;
|
|
39
|
+
#maxMessageBytes = MAX_OPENING_BYTES;
|
|
40
|
+
|
|
41
|
+
constructor(
|
|
42
|
+
readonly socketPath: string,
|
|
43
|
+
readonly name: string,
|
|
44
|
+
handlers: Handlers,
|
|
45
|
+
) {
|
|
46
|
+
if (!isAbsolute(socketPath) || socketPath.includes("\0") || Buffer.byteLength(socketPath) >= 108) {
|
|
47
|
+
throw new TypeError("Expected an absolute Unix socket path shorter than 108 bytes.");
|
|
48
|
+
}
|
|
49
|
+
if (!name || Buffer.byteLength(name) > 255 || /[\x00-\x1f\x7f]/u.test(name) ||
|
|
50
|
+
Buffer.from(name).toString("utf8") !== name) {
|
|
51
|
+
throw new TypeError("Channel names must contain 1–255 UTF-8 bytes without control characters.");
|
|
52
|
+
}
|
|
53
|
+
this.#handlers = handlers;
|
|
54
|
+
this.#socket.on("data", (data: Buffer) => this.#receive(data));
|
|
55
|
+
this.#socket.on("error", error => {
|
|
56
|
+
this.#finish({ reason: "error", error: new RelapseError(
|
|
57
|
+
this.#opened ? "disconnected" : "connection_failed", error.message, { cause: error },
|
|
58
|
+
) });
|
|
59
|
+
});
|
|
60
|
+
this.#socket.on("end", () => {
|
|
61
|
+
if (this.#headerUsed || this.#body) this.#invalid("Connection ended in the middle of a frame.");
|
|
62
|
+
else this.#finish({ reason: "peer" });
|
|
63
|
+
});
|
|
64
|
+
this.#socket.on("close", () => this.#finish({ reason: "peer" }));
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
get connected(): boolean { return this.#opened && !this.#closed; }
|
|
68
|
+
get maxMessageBytes(): number { return this.#maxMessageBytes; }
|
|
69
|
+
|
|
70
|
+
async open(options: WaitOptions): Promise<void> {
|
|
71
|
+
this.#opening = operation<void>(options, 5000);
|
|
72
|
+
try {
|
|
73
|
+
if (!this.#opening.settled) {
|
|
74
|
+
this.#socket.connect(this.socketPath, () => {
|
|
75
|
+
const body = encodeJson({ version: 1, channel: this.name });
|
|
76
|
+
this.#socket.write(this.#frame(body));
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
await this.#opening.promise;
|
|
80
|
+
} catch (error) {
|
|
81
|
+
this.#finish({ reason: "error", error: error instanceof RelapseError ? error :
|
|
82
|
+
new RelapseError("connection_failed", "Could not connect to Relapse.", { cause: error }) });
|
|
83
|
+
throw error;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
pause(): void {
|
|
88
|
+
this.#paused = true;
|
|
89
|
+
this.#socket.pause();
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
resume(): void {
|
|
93
|
+
if (this.#closed) return;
|
|
94
|
+
this.#paused = false;
|
|
95
|
+
const rest = this.#rest;
|
|
96
|
+
this.#rest = undefined;
|
|
97
|
+
if (rest) this.#receive(rest);
|
|
98
|
+
if (!this.#paused && !this.#closed) this.#socket.resume();
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
async send(value: JsonValue): Promise<void> {
|
|
102
|
+
if (!this.connected) throw new RelapseError("disconnected", "Channel is closed.");
|
|
103
|
+
const body = encodeJson(value);
|
|
104
|
+
if (body.length > this.#maxMessageBytes) {
|
|
105
|
+
throw new RelapseError("message_too_large", `Message exceeds ${this.#maxMessageBytes} bytes.`);
|
|
106
|
+
}
|
|
107
|
+
const size = body.length + 4;
|
|
108
|
+
if (this.#writes.size >= MAX_QUEUED_MESSAGES || this.#queuedBytes + size > MAX_QUEUED_BYTES) {
|
|
109
|
+
throw new RelapseError("backpressure", "Channel send queue is full.");
|
|
110
|
+
}
|
|
111
|
+
await new Promise<void>((resolve, reject) => {
|
|
112
|
+
const fail = (error: RelapseError) => reject(error);
|
|
113
|
+
this.#writes.add(fail);
|
|
114
|
+
this.#queuedBytes += size;
|
|
115
|
+
this.#socket.write(this.#frame(body), error => {
|
|
116
|
+
this.#writes.delete(fail);
|
|
117
|
+
this.#queuedBytes -= size;
|
|
118
|
+
if (error) reject(new RelapseError("disconnected", error.message, { cause: error }));
|
|
119
|
+
else resolve();
|
|
120
|
+
});
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
close(error?: RelapseError): void {
|
|
125
|
+
this.#finish(error ? { reason: "error", error } : { reason: "local" });
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
#frame(body: Buffer): Buffer {
|
|
129
|
+
const frame = Buffer.allocUnsafe(body.length + 4);
|
|
130
|
+
frame.writeUInt32BE(body.length);
|
|
131
|
+
body.copy(frame, 4);
|
|
132
|
+
return frame;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
#receive(data: Buffer): void {
|
|
136
|
+
let offset = 0;
|
|
137
|
+
while (offset < data.length && !this.#closed) {
|
|
138
|
+
if (this.#paused) {
|
|
139
|
+
this.#rest = data.subarray(offset);
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
if (this.#headerUsed < 4) {
|
|
143
|
+
const amount = Math.min(4 - this.#headerUsed, data.length - offset);
|
|
144
|
+
data.copy(this.#header, this.#headerUsed, offset, offset + amount);
|
|
145
|
+
offset += amount;
|
|
146
|
+
this.#headerUsed += amount;
|
|
147
|
+
if (this.#headerUsed < 4) return;
|
|
148
|
+
const size = this.#header.readUInt32BE();
|
|
149
|
+
if (size === 0 || size > this.#maxMessageBytes) {
|
|
150
|
+
this.#invalid("Invalid channel frame length.");
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
this.#body = Buffer.allocUnsafe(size);
|
|
154
|
+
}
|
|
155
|
+
const body = this.#body!;
|
|
156
|
+
const amount = Math.min(body.length - this.#bodyUsed, data.length - offset);
|
|
157
|
+
data.copy(body, this.#bodyUsed, offset, offset + amount);
|
|
158
|
+
offset += amount;
|
|
159
|
+
this.#bodyUsed += amount;
|
|
160
|
+
if (this.#bodyUsed < body.length) return;
|
|
161
|
+
this.#headerUsed = this.#bodyUsed = 0;
|
|
162
|
+
this.#body = undefined;
|
|
163
|
+
|
|
164
|
+
let message: unknown;
|
|
165
|
+
try {
|
|
166
|
+
message = JSON.parse(new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(body));
|
|
167
|
+
} catch {
|
|
168
|
+
this.#invalid("Expected a UTF-8 JSON message.");
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
if (!this.#opened) this.#handshake(message);
|
|
172
|
+
else this.#handlers.message(message);
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
#handshake(message: unknown): void {
|
|
177
|
+
if (!isRecord(message) || typeof message.ok !== "boolean") {
|
|
178
|
+
this.#invalid("Expected a channel handshake response.");
|
|
179
|
+
return;
|
|
180
|
+
}
|
|
181
|
+
if (!message.ok) {
|
|
182
|
+
if (typeof message.error !== "string") this.#invalid("Invalid channel rejection.");
|
|
183
|
+
else this.close(new RelapseError("channel_rejected", message.error));
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
if (message.version !== 1 || typeof message.max_message_bytes !== "number" ||
|
|
187
|
+
!Number.isInteger(message.max_message_bytes) || message.max_message_bytes <= 0 ||
|
|
188
|
+
message.max_message_bytes > 0xffff_ffff) {
|
|
189
|
+
this.#invalid("Unsupported channel version or invalid message limit.");
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
this.#maxMessageBytes = Math.min(message.max_message_bytes, MAX_MESSAGE_BYTES);
|
|
193
|
+
this.#opened = true;
|
|
194
|
+
// Let connect() callers attach listeners before delivering coalesced frames.
|
|
195
|
+
this.pause();
|
|
196
|
+
this.#opening?.resolve();
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
#invalid(message: string): void {
|
|
200
|
+
this.close(new RelapseError("protocol_error", message));
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
#finish(info: CloseInfo): void {
|
|
204
|
+
if (this.#closed) return;
|
|
205
|
+
this.#closed = true;
|
|
206
|
+
const error = info.error ?? new RelapseError("disconnected", "Channel closed.");
|
|
207
|
+
this.#opening?.reject(error);
|
|
208
|
+
for (const fail of this.#writes) fail(error);
|
|
209
|
+
this.#writes.clear();
|
|
210
|
+
this.#body = this.#rest = undefined;
|
|
211
|
+
this.#socket.destroy();
|
|
212
|
+
this.#handlers.close(info);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
// Copyright (C) 2026 vpu007
|
|
2
|
+
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
3
|
+
|
|
4
|
+
import type { EventEmitter } from "node:events";
|
|
5
|
+
import { RelapseError } from "../errors.js";
|
|
6
|
+
import { operation, type WaitOptions } from "./operation.js";
|
|
7
|
+
import type { CloseInfo } from "./transport.js";
|
|
8
|
+
|
|
9
|
+
export async function waitForEvent<T>(
|
|
10
|
+
source: EventEmitter,
|
|
11
|
+
event: string,
|
|
12
|
+
connected: boolean,
|
|
13
|
+
predicate: ((value: T) => boolean) | undefined,
|
|
14
|
+
options: WaitOptions,
|
|
15
|
+
): Promise<T> {
|
|
16
|
+
const wait = operation<T>(options, 30_000);
|
|
17
|
+
const receive = (value: T) => {
|
|
18
|
+
if (wait.settled) return;
|
|
19
|
+
try {
|
|
20
|
+
if (!predicate || predicate(value)) wait.resolve(value);
|
|
21
|
+
} catch (error) {
|
|
22
|
+
wait.reject(error);
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
const closed = (info: CloseInfo) => {
|
|
26
|
+
wait.reject(info.error ?? new RelapseError("disconnected", "Channel closed before the event arrived."));
|
|
27
|
+
};
|
|
28
|
+
if (!wait.settled) {
|
|
29
|
+
if (!connected) wait.reject(new RelapseError("disconnected", "Channel is closed."));
|
|
30
|
+
else {
|
|
31
|
+
source.on(event, receive);
|
|
32
|
+
source.on("close", closed);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
try {
|
|
36
|
+
return await wait.promise;
|
|
37
|
+
} finally {
|
|
38
|
+
source.off(event, receive);
|
|
39
|
+
source.off("close", closed);
|
|
40
|
+
}
|
|
41
|
+
}
|
package/src/launcher.ts
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// Copyright (C) 2026 vpu007
|
|
2
|
+
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
3
|
+
|
|
4
|
+
import { spawn, type ChildProcess } from "node:child_process";
|
|
5
|
+
import { once } from "node:events";
|
|
6
|
+
import { isValidName } from "./profiles.js";
|
|
7
|
+
|
|
8
|
+
export interface LaunchOptions {
|
|
9
|
+
profile: string;
|
|
10
|
+
launcherPath?: string;
|
|
11
|
+
placeId?: string;
|
|
12
|
+
jobId?: string;
|
|
13
|
+
env?: NodeJS.ProcessEnv;
|
|
14
|
+
/** Defaults to ignore. Use pipe to consume the launcher's stdout and stderr. */
|
|
15
|
+
stdio?: "ignore" | "inherit" | "pipe";
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Resolves when the launcher process starts, before a client or executor is necessarily ready. */
|
|
19
|
+
export async function launch(options: LaunchOptions): Promise<ChildProcess> {
|
|
20
|
+
if (!isValidName(options.profile)) throw new TypeError("Invalid profile name.");
|
|
21
|
+
const launcher = options.launcherPath ?? "relapse-launcher";
|
|
22
|
+
if (!launcher || launcher.includes("\0")) throw new TypeError("Invalid launcher executable.");
|
|
23
|
+
const args = ["--profile", options.profile, "--no-launch-ui"];
|
|
24
|
+
const place = options.placeId?.trim() ?? "";
|
|
25
|
+
const job = options.jobId?.trim() ?? "";
|
|
26
|
+
if (!place && job) throw new TypeError("A Job ID requires a Place ID.");
|
|
27
|
+
if (place) {
|
|
28
|
+
if (!/^[0-9]+$/u.test(place) || BigInt(place) < 1n || BigInt(place) > 0x7fff_ffff_ffff_ffffn) {
|
|
29
|
+
throw new TypeError("Place ID must be a positive 64-bit integer string.");
|
|
30
|
+
}
|
|
31
|
+
if (job && !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu.test(job)) {
|
|
32
|
+
throw new TypeError("Job ID must be a UUID.");
|
|
33
|
+
}
|
|
34
|
+
const uri = `roblox://placeId=${BigInt(place)}${job ? `&gameInstanceId=${job}` : ""}`;
|
|
35
|
+
args.push("--", uri);
|
|
36
|
+
}
|
|
37
|
+
const env = { ...(options.env ?? process.env) };
|
|
38
|
+
delete env.LD_PRELOAD;
|
|
39
|
+
delete env.LD_AUDIT;
|
|
40
|
+
delete env.LD_LIBRARY_PATH;
|
|
41
|
+
const child = spawn(launcher, args, { env, stdio: options.stdio ?? "ignore" });
|
|
42
|
+
await once(child, "spawn");
|
|
43
|
+
return child;
|
|
44
|
+
}
|