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