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
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
// Copyright (C) 2026 vpu007
|
|
2
|
+
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
3
|
+
import { EventEmitter } from "node:events";
|
|
4
|
+
import { readFile } from "node:fs/promises";
|
|
5
|
+
import { basename } from "node:path";
|
|
6
|
+
import { RelapseError } from "./errors.js";
|
|
7
|
+
import { isRecord } from "./internal/json.js";
|
|
8
|
+
import { operation } from "./internal/operation.js";
|
|
9
|
+
import { Transport } from "./internal/transport.js";
|
|
10
|
+
import { waitForEvent } from "./internal/wait-for.js";
|
|
11
|
+
export class MainChannel extends EventEmitter {
|
|
12
|
+
#transport;
|
|
13
|
+
#opening;
|
|
14
|
+
#requests = new Map();
|
|
15
|
+
#pending = new Set();
|
|
16
|
+
#hello;
|
|
17
|
+
#ready = false;
|
|
18
|
+
#session = 0;
|
|
19
|
+
#nextId = 1;
|
|
20
|
+
constructor(options, opening) {
|
|
21
|
+
super();
|
|
22
|
+
this.#opening = opening;
|
|
23
|
+
this.#transport = new Transport(options.socketPath, "@main", {
|
|
24
|
+
message: message => this.#receive(message),
|
|
25
|
+
close: info => this.#closed(info),
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
/** Connects to @main and receives its initial hello, which may report ready: false. */
|
|
29
|
+
static async connect(options) {
|
|
30
|
+
const opening = operation(options, 5000);
|
|
31
|
+
let channel;
|
|
32
|
+
try {
|
|
33
|
+
channel = new MainChannel(options, opening);
|
|
34
|
+
}
|
|
35
|
+
catch (error) {
|
|
36
|
+
opening.resolve();
|
|
37
|
+
await opening.promise.catch(() => { });
|
|
38
|
+
throw error;
|
|
39
|
+
}
|
|
40
|
+
try {
|
|
41
|
+
await Promise.all([
|
|
42
|
+
channel.#transport.open(options).then(() => channel.#transport.resume()),
|
|
43
|
+
opening.promise,
|
|
44
|
+
]);
|
|
45
|
+
setImmediate(() => channel.#transport.resume());
|
|
46
|
+
return channel;
|
|
47
|
+
}
|
|
48
|
+
catch (error) {
|
|
49
|
+
channel.close();
|
|
50
|
+
throw error;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
get socketPath() { return this.#transport.socketPath; }
|
|
54
|
+
get name() { return "@main"; }
|
|
55
|
+
get connected() { return this.#transport.connected; }
|
|
56
|
+
get maxMessageBytes() { return this.#transport.maxMessageBytes; }
|
|
57
|
+
get hello() { return this.#hello; }
|
|
58
|
+
get ready() { return this.connected && this.#ready; }
|
|
59
|
+
get session() { return this.#session; }
|
|
60
|
+
/** Validates and writes a request. Execution acknowledgements arrive as exec_result events. */
|
|
61
|
+
async send(value) {
|
|
62
|
+
const request = validateRequest(value);
|
|
63
|
+
if (!this.connected)
|
|
64
|
+
throw new RelapseError("disconnected", "Main channel is closed.");
|
|
65
|
+
if (!this.ready)
|
|
66
|
+
throw new RelapseError("not_ready", "Executor is not ready.");
|
|
67
|
+
if (request.session !== this.#session)
|
|
68
|
+
throw new RelapseError("session_changed", "Request targets a different executor session.");
|
|
69
|
+
if (this.#pending.has(request.script_id))
|
|
70
|
+
throw new TypeError("This execution request ID is already pending.");
|
|
71
|
+
if (this.#pending.size >= 16)
|
|
72
|
+
throw new RelapseError("backpressure", "Too many pending executions.");
|
|
73
|
+
this.#pending.add(request.script_id);
|
|
74
|
+
this.#nextId = Math.max(this.#nextId, request.script_id + 1);
|
|
75
|
+
try {
|
|
76
|
+
await this.#transport.send(request);
|
|
77
|
+
}
|
|
78
|
+
catch (error) {
|
|
79
|
+
this.#pending.delete(request.script_id);
|
|
80
|
+
throw error;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
/** Waits for a future matching event. Check ready before waiting for a readiness transition. */
|
|
84
|
+
waitFor(event, predicate, options = {}) {
|
|
85
|
+
return waitForEvent(this, event, this.connected, predicate, options);
|
|
86
|
+
}
|
|
87
|
+
/** Resolves on submission, not script completion. Timeout/abort cannot undo submission. */
|
|
88
|
+
async execute(source, options = {}) {
|
|
89
|
+
if (this.#nextId > Number.MAX_SAFE_INTEGER)
|
|
90
|
+
throw new RangeError("Execution request IDs exhausted.");
|
|
91
|
+
const request = operation(options, 10_000);
|
|
92
|
+
const id = this.#nextId++;
|
|
93
|
+
if (!request.settled) {
|
|
94
|
+
this.#requests.set(id, request);
|
|
95
|
+
this.send({
|
|
96
|
+
op: "execute", script_id: id, session: this.#session,
|
|
97
|
+
source, name: options.name ?? "relapse",
|
|
98
|
+
}).catch(error => request.reject(error));
|
|
99
|
+
}
|
|
100
|
+
try {
|
|
101
|
+
await request.promise;
|
|
102
|
+
}
|
|
103
|
+
finally {
|
|
104
|
+
this.#requests.delete(id);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
async executeFile(path, options = {}) {
|
|
108
|
+
const source = await readFile(path, {
|
|
109
|
+
encoding: "utf8",
|
|
110
|
+
...(options.signal ? { signal: options.signal } : {}),
|
|
111
|
+
});
|
|
112
|
+
await this.execute(source, { ...options, name: options.name ?? basename(path) });
|
|
113
|
+
}
|
|
114
|
+
close() {
|
|
115
|
+
this.#transport.close();
|
|
116
|
+
}
|
|
117
|
+
#receive(value) {
|
|
118
|
+
let message;
|
|
119
|
+
try {
|
|
120
|
+
message = parseMessage(value);
|
|
121
|
+
if ((!this.#hello && message.type !== "hello") || (this.#hello && message.type === "hello")) {
|
|
122
|
+
throw new TypeError("Expected one initial hello message.");
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
catch (error) {
|
|
126
|
+
this.#transport.close(new RelapseError("protocol_error", "Invalid @main message.", { cause: error }));
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
switch (message.type) {
|
|
130
|
+
case "hello":
|
|
131
|
+
this.#hello = Object.freeze(message);
|
|
132
|
+
this.#ready = message.ready;
|
|
133
|
+
this.#session = message.session;
|
|
134
|
+
this.#transport.pause();
|
|
135
|
+
this.#opening.resolve();
|
|
136
|
+
this.emit("hello", message);
|
|
137
|
+
break;
|
|
138
|
+
case "status":
|
|
139
|
+
if (!message.ready || message.session !== this.#session) {
|
|
140
|
+
for (const pending of this.#requests.values()) {
|
|
141
|
+
pending.reject(new RelapseError("session_changed", "Executor session changed before acknowledgement."));
|
|
142
|
+
}
|
|
143
|
+
this.#requests.clear();
|
|
144
|
+
this.#pending.clear();
|
|
145
|
+
}
|
|
146
|
+
this.#ready = message.ready;
|
|
147
|
+
this.#session = message.session;
|
|
148
|
+
this.emit("status", message);
|
|
149
|
+
break;
|
|
150
|
+
case "exec_result": {
|
|
151
|
+
this.#pending.delete(message.script_id);
|
|
152
|
+
const pending = this.#requests.get(message.script_id);
|
|
153
|
+
this.#requests.delete(message.script_id);
|
|
154
|
+
if (message.phase === "submitted")
|
|
155
|
+
pending?.resolve();
|
|
156
|
+
else
|
|
157
|
+
pending?.reject(new RelapseError("execution_failed", message.detail ?? "Execution rejected."));
|
|
158
|
+
this.emit("exec_result", message);
|
|
159
|
+
break;
|
|
160
|
+
}
|
|
161
|
+
case "log":
|
|
162
|
+
this.emit("log", message);
|
|
163
|
+
break;
|
|
164
|
+
case "error":
|
|
165
|
+
this.emit("message", message);
|
|
166
|
+
this.#transport.close(new RelapseError("protocol_error", message.detail));
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
this.emit("message", message);
|
|
170
|
+
}
|
|
171
|
+
#closed(info) {
|
|
172
|
+
const error = info.error ?? new RelapseError("disconnected", "Main channel closed.");
|
|
173
|
+
this.#opening.reject(error);
|
|
174
|
+
for (const request of this.#requests.values())
|
|
175
|
+
request.reject(error);
|
|
176
|
+
this.#requests.clear();
|
|
177
|
+
this.#pending.clear();
|
|
178
|
+
this.#ready = false;
|
|
179
|
+
this.emit("close", info);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
function integer(value, minimum) {
|
|
183
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= minimum;
|
|
184
|
+
}
|
|
185
|
+
function validateRequest(value) {
|
|
186
|
+
if (!isRecord(value) || Object.keys(value).some(key => !["op", "script_id", "session", "source", "name"].includes(key))) {
|
|
187
|
+
throw new TypeError("Expected a main-channel execution request with only defined fields.");
|
|
188
|
+
}
|
|
189
|
+
const { op, script_id, session, source, name } = value;
|
|
190
|
+
if (op !== "execute" || !integer(script_id, 1) || !integer(session, 0) || typeof source !== "string" ||
|
|
191
|
+
(name !== undefined && (typeof name !== "string" || Buffer.byteLength(name) > 255))) {
|
|
192
|
+
throw new TypeError("Expected execute, a positive script_id, a session, source text, and an optional name of at most 255 bytes.");
|
|
193
|
+
}
|
|
194
|
+
if (Buffer.from(source).toString("utf8") !== source ||
|
|
195
|
+
(name !== undefined && Buffer.from(name).toString("utf8") !== name)) {
|
|
196
|
+
throw new TypeError("Script source and name must contain valid Unicode.");
|
|
197
|
+
}
|
|
198
|
+
// Copy validated fields so serialization cannot use a caller's toJSON implementation.
|
|
199
|
+
return { op, script_id, session, source, ...(name === undefined ? {} : { name }) };
|
|
200
|
+
}
|
|
201
|
+
function parseMessage(value) {
|
|
202
|
+
if (!isRecord(value))
|
|
203
|
+
throw new TypeError("Expected an object.");
|
|
204
|
+
switch (value.type) {
|
|
205
|
+
case "hello":
|
|
206
|
+
case "status": {
|
|
207
|
+
const { ready, session } = value;
|
|
208
|
+
if (typeof ready !== "boolean" || !integer(session, ready ? 1 : 0))
|
|
209
|
+
break;
|
|
210
|
+
if (value.type === "status")
|
|
211
|
+
return { type: "status", ready, session };
|
|
212
|
+
if (!integer(value.pid, 1) || typeof value.profile !== "string")
|
|
213
|
+
break;
|
|
214
|
+
return { type: "hello", ready, session, pid: value.pid, profile: value.profile };
|
|
215
|
+
}
|
|
216
|
+
case "exec_result": {
|
|
217
|
+
const { script_id, phase, detail } = value;
|
|
218
|
+
if (!integer(script_id, 1) || (phase !== "submitted" && phase !== "error") ||
|
|
219
|
+
(detail !== undefined && typeof detail !== "string"))
|
|
220
|
+
break;
|
|
221
|
+
return { type: "exec_result", script_id, phase, ...(detail === undefined ? {} : { detail }) };
|
|
222
|
+
}
|
|
223
|
+
case "log":
|
|
224
|
+
if (typeof value.level === "string" && typeof value.text === "string") {
|
|
225
|
+
return { type: "log", level: value.level, text: value.text };
|
|
226
|
+
}
|
|
227
|
+
break;
|
|
228
|
+
case "error":
|
|
229
|
+
if (typeof value.detail === "string")
|
|
230
|
+
return { type: "error", detail: value.detail };
|
|
231
|
+
break;
|
|
232
|
+
}
|
|
233
|
+
throw new TypeError("Invalid main-channel message.");
|
|
234
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
export interface ProfileOptions {
|
|
2
|
+
homeDirectory?: string;
|
|
3
|
+
}
|
|
4
|
+
export interface ProfileInfo {
|
|
5
|
+
name: string;
|
|
6
|
+
directory: string;
|
|
7
|
+
}
|
|
8
|
+
export interface ProfilePaths {
|
|
9
|
+
directory: string;
|
|
10
|
+
state: string;
|
|
11
|
+
cookies: string;
|
|
12
|
+
}
|
|
13
|
+
export declare function isValidName(name: string): boolean;
|
|
14
|
+
export declare function directory(options?: ProfileOptions): string;
|
|
15
|
+
export declare function path(name: string, options?: ProfileOptions): string;
|
|
16
|
+
export declare function paths(name: string, options?: ProfileOptions): ProfilePaths;
|
|
17
|
+
export declare function get(name: string, options?: ProfileOptions): Promise<ProfileInfo>;
|
|
18
|
+
export declare function list(options?: ProfileOptions): Promise<ProfileInfo[]>;
|
|
19
|
+
/** Creates a fresh profile directory. The launcher initializes its state on first use. */
|
|
20
|
+
export declare function create(name: string, options?: ProfileOptions): Promise<ProfileInfo>;
|
package/dist/profiles.js
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
// Copyright (C) 2026 vpu007
|
|
2
|
+
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
3
|
+
import { lstat, mkdir, readdir } from "node:fs/promises";
|
|
4
|
+
import { homedir } from "node:os";
|
|
5
|
+
import { isAbsolute, join } from "node:path";
|
|
6
|
+
export function isValidName(name) {
|
|
7
|
+
return typeof name === "string" && /^[a-zA-Z0-9._-]{1,64}$/u.test(name) && name !== "." && name !== "..";
|
|
8
|
+
}
|
|
9
|
+
export function directory(options = {}) {
|
|
10
|
+
const home = options.homeDirectory ?? homedir();
|
|
11
|
+
if (!isAbsolute(home))
|
|
12
|
+
throw new TypeError("homeDirectory must be an absolute path.");
|
|
13
|
+
return join(home, ".local", "share", "relapse", "profiles");
|
|
14
|
+
}
|
|
15
|
+
export function path(name, options = {}) {
|
|
16
|
+
if (!isValidName(name)) {
|
|
17
|
+
throw new TypeError("Profile names must contain 1–64 letters, digits, dots, underscores or hyphens, excluding . and ..");
|
|
18
|
+
}
|
|
19
|
+
return join(directory(options), name);
|
|
20
|
+
}
|
|
21
|
+
export function paths(name, options = {}) {
|
|
22
|
+
const profile = path(name, options);
|
|
23
|
+
return {
|
|
24
|
+
directory: profile,
|
|
25
|
+
state: join(profile, "state"),
|
|
26
|
+
cookies: join(profile, "state", "app", "data", "sober", "cookies"),
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
export async function get(name, options = {}) {
|
|
30
|
+
const profile = path(name, options);
|
|
31
|
+
const stat = await lstat(profile);
|
|
32
|
+
if (!stat.isDirectory())
|
|
33
|
+
throw new Error("Profile must be a directory, not a symlink or other file.");
|
|
34
|
+
return { name, directory: profile };
|
|
35
|
+
}
|
|
36
|
+
export async function list(options = {}) {
|
|
37
|
+
const root = directory(options);
|
|
38
|
+
const entries = await readdir(root, { withFileTypes: true }).catch((error) => {
|
|
39
|
+
if (error.code === "ENOENT")
|
|
40
|
+
return [];
|
|
41
|
+
throw error;
|
|
42
|
+
});
|
|
43
|
+
return entries.filter(entry => entry.isDirectory() && isValidName(entry.name))
|
|
44
|
+
.map(entry => ({ name: entry.name, directory: join(root, entry.name) }))
|
|
45
|
+
.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
|
|
46
|
+
}
|
|
47
|
+
/** Creates a fresh profile directory. The launcher initializes its state on first use. */
|
|
48
|
+
export async function create(name, options = {}) {
|
|
49
|
+
const profile = path(name, options);
|
|
50
|
+
const root = directory(options);
|
|
51
|
+
await mkdir(root, { recursive: true, mode: 0o700 });
|
|
52
|
+
if (!(await lstat(root)).isDirectory())
|
|
53
|
+
throw new Error("Profiles directory must not be a symlink.");
|
|
54
|
+
await mkdir(profile, { mode: 0o700 });
|
|
55
|
+
return { name, directory: profile };
|
|
56
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
// Copyright (C) 2026 vpu007
|
|
2
|
+
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
3
|
+
|
|
4
|
+
import { Channel } from "relapsesdk";
|
|
5
|
+
|
|
6
|
+
const [socketPath, name] = process.argv.slice(2);
|
|
7
|
+
if (!socketPath || !name) {
|
|
8
|
+
console.log("Usage: node examples/channel.mjs SOCKET CHANNEL");
|
|
9
|
+
} else {
|
|
10
|
+
const channel = await Channel.connect({ socketPath, name });
|
|
11
|
+
channel.on("message", message => console.log(message));
|
|
12
|
+
channel.on("close", info => console.log(info.error?.message ?? `Channel closed (${info.reason}).`));
|
|
13
|
+
const stop = () => channel.close();
|
|
14
|
+
process.once("SIGINT", stop);
|
|
15
|
+
channel.once("close", () => process.off("SIGINT", stop));
|
|
16
|
+
await channel.send({ action: "hello" }).catch(error => {
|
|
17
|
+
console.error(error.message);
|
|
18
|
+
process.exitCode = 1;
|
|
19
|
+
channel.close();
|
|
20
|
+
});
|
|
21
|
+
}
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
// Copyright (C) 2026 vpu007
|
|
2
|
+
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
3
|
+
|
|
4
|
+
import { randomUUID } from "node:crypto";
|
|
5
|
+
import { createInterface } from "node:readline/promises";
|
|
6
|
+
import { setTimeout as sleep } from "node:timers/promises";
|
|
7
|
+
import { Client, RelapseError, listClients, profiles } from "relapsesdk";
|
|
8
|
+
import type { Channel, JsonValue } from "relapsesdk";
|
|
9
|
+
|
|
10
|
+
const input = createInterface({ input: process.stdin, output: process.stdout });
|
|
11
|
+
const shutdown = new AbortController();
|
|
12
|
+
let client: Client | undefined;
|
|
13
|
+
let channel: Channel | undefined;
|
|
14
|
+
|
|
15
|
+
function stop() {
|
|
16
|
+
if (shutdown.signal.aborted) return;
|
|
17
|
+
shutdown.abort();
|
|
18
|
+
channel?.close();
|
|
19
|
+
client?.close();
|
|
20
|
+
input.close();
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
input.on("SIGINT", stop);
|
|
24
|
+
input.on("close", stop);
|
|
25
|
+
process.once("SIGINT", stop);
|
|
26
|
+
|
|
27
|
+
async function main() {
|
|
28
|
+
const savedProfiles = await profiles.list();
|
|
29
|
+
console.log("Profiles:", savedProfiles.map(profile => profile.name).join(", ") || "none");
|
|
30
|
+
|
|
31
|
+
let socketPath = process.argv[2];
|
|
32
|
+
if (!socketPath) {
|
|
33
|
+
const clients = await listClients({ signal: shutdown.signal });
|
|
34
|
+
if (!clients.length) {
|
|
35
|
+
console.log("No Relapse clients found. Launch one, then run this example again.");
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
console.table(clients.map((info, index) => ({
|
|
39
|
+
number: index + 1,
|
|
40
|
+
profile: info.profile ?? "Unnamed",
|
|
41
|
+
ready: info.ready,
|
|
42
|
+
socket: info.socketPath,
|
|
43
|
+
})));
|
|
44
|
+
const choice = clients.length === 1 ? "1" :
|
|
45
|
+
await input.question("Client number: ", { signal: shutdown.signal });
|
|
46
|
+
const selected = clients[Number(choice) - 1];
|
|
47
|
+
if (!selected) throw new Error("Choose a client number from the list.");
|
|
48
|
+
socketPath = selected.socketPath;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
client = await Client.connect({ socketPath, signal: shutdown.signal });
|
|
52
|
+
const mainChannel = client.mainChannel;
|
|
53
|
+
mainChannel.on("status", status => console.log("Executor:", status.ready ? "ready" : "waiting"));
|
|
54
|
+
mainChannel.on("log", entry => console.log(`[${entry.level}] ${entry.text}`));
|
|
55
|
+
mainChannel.on("close", info => {
|
|
56
|
+
if (!shutdown.signal.aborted) console.log(info.error?.message ?? "Client disconnected.");
|
|
57
|
+
stop();
|
|
58
|
+
});
|
|
59
|
+
if (!mainChannel.ready) {
|
|
60
|
+
await mainChannel.waitFor("status", status => status.ready, { signal: shutdown.signal });
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const channelName = `sdk-example-${randomUUID()}`;
|
|
64
|
+
await mainChannel.execute(`
|
|
65
|
+
local name = ${JSON.stringify(channelName)}
|
|
66
|
+
local channel = RelapseChannel.new(name)
|
|
67
|
+
getgenv()[name] = channel
|
|
68
|
+
local connected = false
|
|
69
|
+
|
|
70
|
+
local function cleanup()
|
|
71
|
+
channel:Close()
|
|
72
|
+
getgenv()[name] = nil
|
|
73
|
+
end
|
|
74
|
+
|
|
75
|
+
channel.Connected:Connect(function(connection)
|
|
76
|
+
connected = true
|
|
77
|
+
connection.MessageReceived:Connect(function(message)
|
|
78
|
+
if message == "status" then
|
|
79
|
+
connection:Send({
|
|
80
|
+
placeId = tostring(game.PlaceId),
|
|
81
|
+
jobId = game.JobId,
|
|
82
|
+
players = #game:GetService("Players"):GetPlayers(),
|
|
83
|
+
})
|
|
84
|
+
else
|
|
85
|
+
connection:Send(message)
|
|
86
|
+
end
|
|
87
|
+
end)
|
|
88
|
+
connection.Disconnected:Connect(cleanup)
|
|
89
|
+
end)
|
|
90
|
+
|
|
91
|
+
task.delay(30, function()
|
|
92
|
+
if not connected then cleanup() end
|
|
93
|
+
end)
|
|
94
|
+
`, { name: "sdk-example.luau", signal: shutdown.signal });
|
|
95
|
+
|
|
96
|
+
// Submission can be acknowledged before the script has published its channel.
|
|
97
|
+
const deadline = Date.now() + 5000;
|
|
98
|
+
while (!channel) {
|
|
99
|
+
channel = await client.openChannel(channelName, { signal: shutdown.signal })
|
|
100
|
+
.catch(error => {
|
|
101
|
+
if (error instanceof RelapseError && error.code === "channel_rejected" &&
|
|
102
|
+
error.message === "unknown_channel" && Date.now() < deadline) return undefined;
|
|
103
|
+
throw error;
|
|
104
|
+
});
|
|
105
|
+
if (!channel) await sleep(100, undefined, { signal: shutdown.signal });
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
channel.on("message", message => console.dir(message, { depth: null, colors: process.stdout.isTTY }));
|
|
109
|
+
channel.on("close", info => {
|
|
110
|
+
if (!shutdown.signal.aborted) console.log(info.error?.message ?? "Example channel closed.");
|
|
111
|
+
stop();
|
|
112
|
+
});
|
|
113
|
+
console.log('Connected. Enter status, JSON to echo, or quit. Ctrl+C also exits.');
|
|
114
|
+
await channel.send("status");
|
|
115
|
+
|
|
116
|
+
while (!shutdown.signal.aborted) {
|
|
117
|
+
const text = (await input.question("> ", { signal: shutdown.signal })).trim();
|
|
118
|
+
if (text === "quit" || text === "exit") break;
|
|
119
|
+
if (!text) continue;
|
|
120
|
+
let message: JsonValue;
|
|
121
|
+
try {
|
|
122
|
+
message = JSON.parse(text);
|
|
123
|
+
} catch {
|
|
124
|
+
message = text;
|
|
125
|
+
}
|
|
126
|
+
await channel.send(message).catch(error => console.error(error.message));
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
main().catch(error => {
|
|
131
|
+
if (!shutdown.signal.aborted) {
|
|
132
|
+
console.error(error.message);
|
|
133
|
+
process.exitCode = 1;
|
|
134
|
+
}
|
|
135
|
+
}).finally(stop);
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
// Copyright (C) 2026 vpu007
|
|
2
|
+
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
3
|
+
|
|
4
|
+
import { Client, listClients } from "relapsesdk";
|
|
5
|
+
|
|
6
|
+
const [socketPath, file] = process.argv.slice(2);
|
|
7
|
+
if (!socketPath || !file) {
|
|
8
|
+
console.log("Usage: node examples/execute.mjs SOCKET SCRIPT.luau");
|
|
9
|
+
console.table(await listClients());
|
|
10
|
+
} else {
|
|
11
|
+
const client = await Client.connect({ socketPath });
|
|
12
|
+
const main = client.mainChannel;
|
|
13
|
+
main.on("log", entry => console.log(`[${entry.level}] ${entry.text}`));
|
|
14
|
+
const ready = main.ready ? Promise.resolve() : main.waitFor("status", status => status.ready);
|
|
15
|
+
await ready
|
|
16
|
+
.then(() => main.executeFile(file))
|
|
17
|
+
.then(() => console.log("Script submitted."))
|
|
18
|
+
.catch(error => {
|
|
19
|
+
console.error(error.message);
|
|
20
|
+
process.exitCode = 1;
|
|
21
|
+
})
|
|
22
|
+
.finally(() => client.close());
|
|
23
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,60 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "relapsesdk",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Node.js SDK for building Relapse tools and frontends.",
|
|
5
|
+
"license": "GPL-3.0-or-later",
|
|
6
|
+
"author": "vpu007",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/vpu00000/relapse-sdk.git"
|
|
10
|
+
},
|
|
11
|
+
"homepage": "https://github.com/vpu00000/relapse-sdk/tree/typescript#readme",
|
|
12
|
+
"bugs": {
|
|
13
|
+
"url": "https://github.com/vpu00000/relapse-sdk/issues"
|
|
14
|
+
},
|
|
15
|
+
"keywords": [
|
|
16
|
+
"relapse",
|
|
17
|
+
"sdk",
|
|
18
|
+
"typescript",
|
|
19
|
+
"nodejs",
|
|
20
|
+
"luau"
|
|
21
|
+
],
|
|
22
|
+
"type": "module",
|
|
23
|
+
"main": "./dist/index.js",
|
|
24
|
+
"types": "./dist/index.d.ts",
|
|
25
|
+
"exports": {
|
|
26
|
+
".": {
|
|
27
|
+
"types": "./dist/index.d.ts",
|
|
28
|
+
"default": "./dist/index.js"
|
|
29
|
+
},
|
|
30
|
+
"./profiles": {
|
|
31
|
+
"types": "./dist/profiles.d.ts",
|
|
32
|
+
"default": "./dist/profiles.js"
|
|
33
|
+
}
|
|
34
|
+
},
|
|
35
|
+
"files": [
|
|
36
|
+
"dist",
|
|
37
|
+
"src",
|
|
38
|
+
"examples",
|
|
39
|
+
"tsconfig.json"
|
|
40
|
+
],
|
|
41
|
+
"publishConfig": {
|
|
42
|
+
"access": "public",
|
|
43
|
+
"registry": "https://registry.npmjs.org/"
|
|
44
|
+
},
|
|
45
|
+
"engines": {
|
|
46
|
+
"node": ">=22"
|
|
47
|
+
},
|
|
48
|
+
"scripts": {
|
|
49
|
+
"build": "tsc -p tsconfig.json",
|
|
50
|
+
"check": "tsc -p tsconfig.json --noEmit",
|
|
51
|
+
"example": "npm run build && node --experimental-strip-types examples/consumer.ts",
|
|
52
|
+
"prepack": "npm run build"
|
|
53
|
+
},
|
|
54
|
+
"devDependencies": {
|
|
55
|
+
"typescript": "^7.0.2"
|
|
56
|
+
},
|
|
57
|
+
"dependencies": {
|
|
58
|
+
"@types/node": ">=22"
|
|
59
|
+
}
|
|
60
|
+
}
|
package/src/channel.ts
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
// Copyright (C) 2026 vpu007
|
|
2
|
+
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
3
|
+
|
|
4
|
+
import { EventEmitter } from "node:events";
|
|
5
|
+
import { Transport, type CloseInfo } from "./internal/transport.js";
|
|
6
|
+
import type { JsonValue } from "./internal/json.js";
|
|
7
|
+
import type { WaitOptions } from "./internal/operation.js";
|
|
8
|
+
import { waitForEvent } from "./internal/wait-for.js";
|
|
9
|
+
|
|
10
|
+
export interface ChannelConnection {
|
|
11
|
+
readonly socketPath: string;
|
|
12
|
+
readonly name: string;
|
|
13
|
+
readonly connected: boolean;
|
|
14
|
+
readonly maxMessageBytes: number;
|
|
15
|
+
close(): void;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface ChannelOptions extends WaitOptions {
|
|
19
|
+
socketPath: string;
|
|
20
|
+
name: string;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface ChannelEvents {
|
|
24
|
+
message: [message: unknown];
|
|
25
|
+
close: [info: CloseInfo];
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export class Channel extends EventEmitter<ChannelEvents> implements ChannelConnection {
|
|
29
|
+
readonly #transport: Transport;
|
|
30
|
+
|
|
31
|
+
private constructor(options: ChannelOptions) {
|
|
32
|
+
super();
|
|
33
|
+
const name = options.name;
|
|
34
|
+
if (typeof name !== "string" || name.startsWith("@")) {
|
|
35
|
+
throw new TypeError("Channel names starting with @ are reserved. Use MainChannel for @main.");
|
|
36
|
+
}
|
|
37
|
+
this.#transport = new Transport(options.socketPath, name, {
|
|
38
|
+
message: message => this.emit("message", message),
|
|
39
|
+
close: info => this.emit("close", info),
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
static async connect(options: ChannelOptions): Promise<Channel> {
|
|
44
|
+
const channel = new Channel(options);
|
|
45
|
+
await channel.#transport.open(options);
|
|
46
|
+
setImmediate(() => channel.#transport.resume());
|
|
47
|
+
return channel;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
get socketPath(): string { return this.#transport.socketPath; }
|
|
51
|
+
get name(): string { return this.#transport.name; }
|
|
52
|
+
get connected(): boolean { return this.#transport.connected; }
|
|
53
|
+
get maxMessageBytes(): number { return this.#transport.maxMessageBytes; }
|
|
54
|
+
|
|
55
|
+
/** Resolves after writing locally, without waiting for a peer acknowledgement. */
|
|
56
|
+
send(value: JsonValue): Promise<void> {
|
|
57
|
+
return this.#transport.send(value);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Waits for a future matching event. Existing messages are not replayed. */
|
|
61
|
+
waitFor<K extends keyof ChannelEvents>(
|
|
62
|
+
event: K,
|
|
63
|
+
predicate?: (value: ChannelEvents[K][0]) => boolean,
|
|
64
|
+
options: WaitOptions = {},
|
|
65
|
+
): Promise<ChannelEvents[K][0]> {
|
|
66
|
+
return waitForEvent(this, event, this.connected, predicate, options);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
close(): void {
|
|
70
|
+
this.#transport.close();
|
|
71
|
+
}
|
|
72
|
+
}
|