relapsesdk 0.0.0-stage → 0.2.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 (49) hide show
  1. package/LICENSE +232 -0
  2. package/README.md +2 -2
  3. package/dist/channel.d.ts +33 -0
  4. package/dist/channel.js +39 -0
  5. package/dist/client.d.ts +28 -0
  6. package/dist/client.js +57 -0
  7. package/dist/configuration.d.ts +38 -0
  8. package/dist/configuration.js +251 -0
  9. package/dist/discovery.d.ts +12 -0
  10. package/dist/discovery.js +79 -0
  11. package/dist/errors.d.ts +5 -0
  12. package/dist/errors.js +9 -0
  13. package/dist/index.d.ts +14 -0
  14. package/dist/index.js +10 -0
  15. package/dist/internal/json.d.ts +5 -0
  16. package/dist/internal/json.js +15 -0
  17. package/dist/internal/operation.d.ts +13 -0
  18. package/dist/internal/operation.js +52 -0
  19. package/dist/internal/profile-name.d.ts +1 -0
  20. package/dist/internal/profile-name.js +4 -0
  21. package/dist/internal/transport.d.ts +25 -0
  22. package/dist/internal/transport.js +203 -0
  23. package/dist/internal/wait-for.d.ts +3 -0
  24. package/dist/internal/wait-for.js +35 -0
  25. package/dist/launcher.d.ts +12 -0
  26. package/dist/launcher.js +34 -0
  27. package/dist/main-channel.d.ts +74 -0
  28. package/dist/main-channel.js +233 -0
  29. package/dist/profiles.d.ts +18 -0
  30. package/dist/profiles.js +65 -0
  31. package/examples/channel.mjs +20 -0
  32. package/examples/consumer.ts +134 -0
  33. package/examples/execute.mjs +22 -0
  34. package/package.json +61 -4
  35. package/src/channel.ts +71 -0
  36. package/src/client.ts +76 -0
  37. package/src/configuration.ts +273 -0
  38. package/src/discovery.ts +80 -0
  39. package/src/errors.ts +25 -0
  40. package/src/index.ts +26 -0
  41. package/src/internal/json.ts +25 -0
  42. package/src/internal/operation.ts +69 -0
  43. package/src/internal/profile-name.ts +5 -0
  44. package/src/internal/transport.ts +213 -0
  45. package/src/internal/wait-for.ts +40 -0
  46. package/src/launcher.ts +43 -0
  47. package/src/main-channel.ts +295 -0
  48. package/src/profiles.ts +83 -0
  49. package/tsconfig.json +20 -0
@@ -0,0 +1,20 @@
1
+ // SPDX-License-Identifier: GPL-3.0-or-later
2
+
3
+ import { Channel } from "relapsesdk";
4
+
5
+ const [socketPath, name] = process.argv.slice(2);
6
+ if (!socketPath || !name) {
7
+ console.log("Usage: node examples/channel.mjs SOCKET CHANNEL");
8
+ } else {
9
+ const channel = await Channel.connect({ socketPath, name });
10
+ channel.on("message", message => console.log(message));
11
+ channel.on("close", info => console.log(info.error?.message ?? `Channel closed (${info.reason}).`));
12
+ const stop = () => channel.close();
13
+ process.once("SIGINT", stop);
14
+ channel.once("close", () => process.off("SIGINT", stop));
15
+ await channel.send({ action: "hello" }).catch(error => {
16
+ console.error(error.message);
17
+ process.exitCode = 1;
18
+ channel.close();
19
+ });
20
+ }
@@ -0,0 +1,134 @@
1
+ // SPDX-License-Identifier: GPL-3.0-or-later
2
+
3
+ import { randomUUID } from "node:crypto";
4
+ import { createInterface } from "node:readline/promises";
5
+ import { setTimeout as sleep } from "node:timers/promises";
6
+ import { Client, RelapseError, listClients, profiles } from "relapsesdk";
7
+ import type { Channel, JsonValue } from "relapsesdk";
8
+
9
+ const input = createInterface({ input: process.stdin, output: process.stdout });
10
+ const shutdown = new AbortController();
11
+ let client: Client | undefined;
12
+ let channel: Channel | undefined;
13
+
14
+ function stop() {
15
+ if (shutdown.signal.aborted) return;
16
+ shutdown.abort();
17
+ channel?.close();
18
+ client?.close();
19
+ input.close();
20
+ }
21
+
22
+ input.on("SIGINT", stop);
23
+ input.on("close", stop);
24
+ process.once("SIGINT", stop);
25
+
26
+ async function main() {
27
+ const savedProfiles = await profiles.list();
28
+ console.log("Profiles:", savedProfiles.map(profile => profile.name).join(", ") || "none");
29
+
30
+ let socketPath = process.argv[2];
31
+ if (!socketPath) {
32
+ const clients = await listClients({ signal: shutdown.signal });
33
+ if (!clients.length) {
34
+ console.log("No Relapse clients found. Launch one, then run this example again.");
35
+ return;
36
+ }
37
+ console.table(clients.map((info, index) => ({
38
+ number: index + 1,
39
+ profile: info.profile ?? "Unnamed",
40
+ ready: info.ready,
41
+ socket: info.socketPath,
42
+ })));
43
+ const choice = clients.length === 1 ? "1" :
44
+ await input.question("Client number: ", { signal: shutdown.signal });
45
+ const selected = clients[Number(choice) - 1];
46
+ if (!selected) throw new Error("Choose a client number from the list.");
47
+ socketPath = selected.socketPath;
48
+ }
49
+
50
+ client = await Client.connect({ socketPath, signal: shutdown.signal });
51
+ const mainChannel = client.mainChannel;
52
+ mainChannel.on("status", status => console.log("Executor:", status.ready ? "ready" : "waiting"));
53
+ mainChannel.on("log", entry => console.log(`[${entry.level}] ${entry.text}`));
54
+ mainChannel.on("close", info => {
55
+ if (!shutdown.signal.aborted) console.log(info.error?.message ?? "Client disconnected.");
56
+ stop();
57
+ });
58
+ if (!mainChannel.ready) {
59
+ await mainChannel.waitFor("status", status => status.ready, { signal: shutdown.signal });
60
+ }
61
+
62
+ const channelName = `sdk-example-${randomUUID()}`;
63
+ await mainChannel.execute(`
64
+ local name = ${JSON.stringify(channelName)}
65
+ local channel = RelapseChannel.new(name)
66
+ getgenv()[name] = channel
67
+ local connected = false
68
+
69
+ local function cleanup()
70
+ channel:Close()
71
+ getgenv()[name] = nil
72
+ end
73
+
74
+ channel.Connected:Connect(function(connection)
75
+ connected = true
76
+ connection.MessageReceived:Connect(function(message)
77
+ if message == "status" then
78
+ connection:Send({
79
+ placeId = tostring(game.PlaceId),
80
+ jobId = game.JobId,
81
+ players = #game:GetService("Players"):GetPlayers(),
82
+ })
83
+ else
84
+ connection:Send(message)
85
+ end
86
+ end)
87
+ connection.Disconnected:Connect(cleanup)
88
+ end)
89
+
90
+ task.delay(30, function()
91
+ if not connected then cleanup() end
92
+ end)
93
+ `, { name: "sdk-example.luau", signal: shutdown.signal });
94
+
95
+ // Submission can be acknowledged before the script has published its channel.
96
+ const deadline = Date.now() + 5000;
97
+ while (!channel) {
98
+ channel = await client.openChannel(channelName, { signal: shutdown.signal })
99
+ .catch(error => {
100
+ if (error instanceof RelapseError && error.code === "channel_rejected" &&
101
+ error.message === "unknown_channel" && Date.now() < deadline) return undefined;
102
+ throw error;
103
+ });
104
+ if (!channel) await sleep(100, undefined, { signal: shutdown.signal });
105
+ }
106
+
107
+ channel.on("message", message => console.dir(message, { depth: null, colors: process.stdout.isTTY }));
108
+ channel.on("close", info => {
109
+ if (!shutdown.signal.aborted) console.log(info.error?.message ?? "Example channel closed.");
110
+ stop();
111
+ });
112
+ console.log('Connected. Enter status, JSON to echo, or quit. Ctrl+C also exits.');
113
+ await channel.send("status");
114
+
115
+ while (!shutdown.signal.aborted) {
116
+ const text = (await input.question("> ", { signal: shutdown.signal })).trim();
117
+ if (text === "quit" || text === "exit") break;
118
+ if (!text) continue;
119
+ let message: JsonValue;
120
+ try {
121
+ message = JSON.parse(text);
122
+ } catch {
123
+ message = text;
124
+ }
125
+ await channel.send(message).catch(error => console.error(error.message));
126
+ }
127
+ }
128
+
129
+ main().catch(error => {
130
+ if (!shutdown.signal.aborted) {
131
+ console.error(error.message);
132
+ process.exitCode = 1;
133
+ }
134
+ }).finally(stop);
@@ -0,0 +1,22 @@
1
+ // SPDX-License-Identifier: GPL-3.0-or-later
2
+
3
+ import { Client, listClients } from "relapsesdk";
4
+
5
+ const [socketPath, file] = process.argv.slice(2);
6
+ if (!socketPath || !file) {
7
+ console.log("Usage: node examples/execute.mjs SOCKET SCRIPT.luau");
8
+ console.table(await listClients());
9
+ } else {
10
+ const client = await Client.connect({ socketPath });
11
+ const main = client.mainChannel;
12
+ main.on("log", entry => console.log(`[${entry.level}] ${entry.text}`));
13
+ const ready = main.ready ? Promise.resolve() : main.waitFor("status", status => status.ready);
14
+ await ready
15
+ .then(() => main.executeFile(file))
16
+ .then(() => console.log("Script submitted."))
17
+ .catch(error => {
18
+ console.error(error.message);
19
+ process.exitCode = 1;
20
+ })
21
+ .finally(() => client.close());
22
+ }
package/package.json CHANGED
@@ -1,6 +1,63 @@
1
1
  {
2
2
  "name": "relapsesdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Node.js SDK for building Relapse tools and frontends.",
5
+ "license": "GPL-3.0-or-later",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/vpu00000/relapse-sdk.git"
9
+ },
10
+ "homepage": "https://github.com/vpu00000/relapse-sdk/tree/typescript#readme",
11
+ "bugs": {
12
+ "url": "https://github.com/vpu00000/relapse-sdk/issues"
13
+ },
14
+ "keywords": [
15
+ "relapse",
16
+ "sdk",
17
+ "typescript",
18
+ "nodejs",
19
+ "luau"
20
+ ],
21
+ "type": "module",
22
+ "main": "./dist/index.js",
23
+ "types": "./dist/index.d.ts",
24
+ "exports": {
25
+ ".": {
26
+ "types": "./dist/index.d.ts",
27
+ "default": "./dist/index.js"
28
+ },
29
+ "./profiles": {
30
+ "types": "./dist/profiles.d.ts",
31
+ "default": "./dist/profiles.js"
32
+ },
33
+ "./configuration": {
34
+ "types": "./dist/configuration.d.ts",
35
+ "default": "./dist/configuration.js"
36
+ }
37
+ },
38
+ "files": [
39
+ "dist",
40
+ "src",
41
+ "examples",
42
+ "tsconfig.json"
43
+ ],
44
+ "publishConfig": {
45
+ "access": "public",
46
+ "registry": "https://registry.npmjs.org/"
47
+ },
48
+ "engines": {
49
+ "node": ">=22"
50
+ },
51
+ "scripts": {
52
+ "build": "tsc -p tsconfig.json",
53
+ "check": "tsc -p tsconfig.json --noEmit",
54
+ "example": "npm run build && node --experimental-strip-types examples/consumer.ts",
55
+ "prepack": "npm run build"
56
+ },
57
+ "devDependencies": {
58
+ "typescript": "^7.0.2"
59
+ },
60
+ "dependencies": {
61
+ "@types/node": ">=22"
62
+ }
63
+ }
package/src/channel.ts ADDED
@@ -0,0 +1,71 @@
1
+ // SPDX-License-Identifier: GPL-3.0-or-later
2
+
3
+ import { EventEmitter } from "node:events";
4
+ import { Transport, type CloseInfo } from "./internal/transport.js";
5
+ import type { JsonValue } from "./internal/json.js";
6
+ import type { WaitOptions } from "./internal/operation.js";
7
+ import { waitForEvent } from "./internal/wait-for.js";
8
+
9
+ export interface ChannelConnection {
10
+ readonly socketPath: string;
11
+ readonly name: string;
12
+ readonly connected: boolean;
13
+ readonly maxMessageBytes: number;
14
+ close(): void;
15
+ }
16
+
17
+ export interface ChannelOptions extends WaitOptions {
18
+ socketPath: string;
19
+ name: string;
20
+ }
21
+
22
+ export interface ChannelEvents {
23
+ message: [message: unknown];
24
+ close: [info: CloseInfo];
25
+ }
26
+
27
+ export class Channel extends EventEmitter<ChannelEvents> implements ChannelConnection {
28
+ readonly #transport: Transport;
29
+
30
+ private constructor(options: ChannelOptions) {
31
+ super();
32
+ const name = options.name;
33
+ if (typeof name !== "string" || name.startsWith("@")) {
34
+ throw new TypeError("Channel names starting with @ are reserved. Use MainChannel for @main.");
35
+ }
36
+ this.#transport = new Transport(options.socketPath, name, {
37
+ message: message => this.emit("message", message),
38
+ close: info => this.emit("close", info),
39
+ });
40
+ }
41
+
42
+ static async connect(options: ChannelOptions): Promise<Channel> {
43
+ const channel = new Channel(options);
44
+ await channel.#transport.open(options);
45
+ setImmediate(() => channel.#transport.resume());
46
+ return channel;
47
+ }
48
+
49
+ get socketPath(): string { return this.#transport.socketPath; }
50
+ get name(): string { return this.#transport.name; }
51
+ get connected(): boolean { return this.#transport.connected; }
52
+ get maxMessageBytes(): number { return this.#transport.maxMessageBytes; }
53
+
54
+ /** Resolves after writing locally, without waiting for a peer acknowledgement. */
55
+ send(value: JsonValue): Promise<void> {
56
+ return this.#transport.send(value);
57
+ }
58
+
59
+ /** Waits for a future matching event. Existing messages are not replayed. */
60
+ waitFor<K extends keyof ChannelEvents>(
61
+ event: K,
62
+ predicate?: (value: ChannelEvents[K][0]) => boolean,
63
+ options: WaitOptions = {},
64
+ ): Promise<ChannelEvents[K][0]> {
65
+ return waitForEvent(this, event, this.connected, predicate, options);
66
+ }
67
+
68
+ close(): void {
69
+ this.#transport.close();
70
+ }
71
+ }
package/src/client.ts ADDED
@@ -0,0 +1,76 @@
1
+ // SPDX-License-Identifier: GPL-3.0-or-later
2
+
3
+ import { basename } from "node:path";
4
+ import { Channel } from "./channel.js";
5
+ import { MainChannel } from "./main-channel.js";
6
+ import { RelapseError } from "./errors.js";
7
+ import { isValidName } from "./profiles.js";
8
+ import type { WaitOptions } from "./internal/operation.js";
9
+
10
+ export interface ClientOptions extends WaitOptions {
11
+ socketPath: string;
12
+ }
13
+
14
+ export interface ClientInfo {
15
+ socketPath: string;
16
+ /** Inferred from the socket filename; null for an unnamed client. */
17
+ profile: string | null;
18
+ pid: number;
19
+ ready: boolean;
20
+ session: number;
21
+ }
22
+
23
+ export class Client {
24
+ readonly mainChannel: MainChannel;
25
+ readonly #channels = new Set<Channel>();
26
+ #closed = false;
27
+
28
+ private constructor(mainChannel: MainChannel) {
29
+ this.mainChannel = mainChannel;
30
+ mainChannel.once("close", () => this.close());
31
+ }
32
+
33
+ static async connect(options: ClientOptions): Promise<Client> {
34
+ return new Client(await MainChannel.connect(options));
35
+ }
36
+
37
+ get socketPath(): string { return this.mainChannel.socketPath; }
38
+ get connected(): boolean { return !this.#closed && this.mainChannel.connected; }
39
+ get pid(): number { return this.mainChannel.hello.pid; }
40
+ get profile(): string | null {
41
+ // Older executors report "default" in hello even when using a named profile.
42
+ const match = /^relapse-(.+)\.sock$/u.exec(basename(this.socketPath));
43
+ return match?.[1] && isValidName(match[1]) ? match[1] : null;
44
+ }
45
+
46
+ get info(): ClientInfo {
47
+ return {
48
+ socketPath: this.socketPath,
49
+ profile: this.profile,
50
+ pid: this.pid,
51
+ ready: this.mainChannel.ready,
52
+ session: this.mainChannel.session,
53
+ };
54
+ }
55
+
56
+ async openChannel(name: string, options: WaitOptions = {}): Promise<Channel> {
57
+ if (!this.connected) throw new RelapseError("disconnected", "Client is disconnected.");
58
+ const channel = await Channel.connect({ ...options, socketPath: this.socketPath, name });
59
+ if (!this.connected) {
60
+ channel.close();
61
+ throw new RelapseError("disconnected", "Client disconnected while opening the channel.");
62
+ }
63
+ this.#channels.add(channel);
64
+ channel.once("close", () => this.#channels.delete(channel));
65
+ return channel;
66
+ }
67
+
68
+ /** Closes @main and any channels opened through this client. */
69
+ close(): void {
70
+ if (this.#closed) return;
71
+ this.#closed = true;
72
+ for (const channel of this.#channels) channel.close();
73
+ this.#channels.clear();
74
+ this.mainChannel.close();
75
+ }
76
+ }
@@ -0,0 +1,273 @@
1
+ // SPDX-License-Identifier: GPL-3.0-or-later
2
+
3
+ import { readFile, mkdir, rename, unlink, writeFile } from "node:fs/promises";
4
+ import { homedir } from "node:os";
5
+ import { dirname, isAbsolute, join } from "node:path";
6
+ import { isValidName } from "./internal/profile-name.js";
7
+ import { isRecord } from "./internal/json.js";
8
+
9
+ export interface ConfigurationOptions {
10
+ homeDirectory?: string;
11
+ configHome?: string;
12
+ dataHome?: string;
13
+ }
14
+
15
+ export type ConfigurationObject = Record<string, unknown>;
16
+
17
+ export interface GlobalConfiguration extends ConfigurationObject {
18
+ defaultProfile?: string;
19
+ workspace?: string;
20
+ autoexec?: string;
21
+ autolaunch?: readonly string[] | null;
22
+ }
23
+
24
+ export interface ConfigurationOverrides extends ConfigurationObject {
25
+ workspace?: string;
26
+ autoexec?: string;
27
+ autolaunch?: readonly string[] | null;
28
+ }
29
+
30
+ export interface ProfileConfiguration extends ConfigurationObject {
31
+ dataDir?: string;
32
+ override?: ConfigurationOverrides;
33
+ }
34
+
35
+ export interface ResolvedConfiguration {
36
+ profile: string;
37
+ dataDir: string;
38
+ workspace: string;
39
+ autoexec: string;
40
+ autolaunch: string[] | null;
41
+ environment: Record<string, string>;
42
+ }
43
+
44
+ export function configDirectory(options: ConfigurationOptions = {}): string {
45
+ const home = options.homeDirectory ?? process.env.HOME ?? homedir();
46
+ if (!isAbsolute(home)) throw new TypeError("homeDirectory must be an absolute path.");
47
+ const configured = options.configHome ?? process.env.XDG_CONFIG_HOME;
48
+ const root = configured ? configured : join(home, ".config");
49
+ if (!isAbsolute(root)) throw new TypeError("configHome must be an absolute path.");
50
+ return join(root, "relapse");
51
+ }
52
+
53
+ export function dataDirectory(options: ConfigurationOptions = {}): string {
54
+ const home = options.homeDirectory ?? process.env.HOME ?? homedir();
55
+ if (!isAbsolute(home)) throw new TypeError("homeDirectory must be an absolute path.");
56
+ const configured = options.dataHome ?? process.env.XDG_DATA_HOME;
57
+ const root = configured ? configured : join(home, ".local", "share");
58
+ if (!isAbsolute(root)) throw new TypeError("dataHome must be an absolute path.");
59
+ return join(root, "relapse");
60
+ }
61
+
62
+ export function globalPath(options: ConfigurationOptions = {}): string {
63
+ return join(configDirectory(options), "config.json");
64
+ }
65
+
66
+ export function profilePath(name: string, options: ConfigurationOptions = {}): string {
67
+ if (!isValidName(name)) throw new TypeError("Invalid profile name.");
68
+ return join(configDirectory(options), "profiles", name, "config.json");
69
+ }
70
+
71
+ function stripComments(text: string): string {
72
+ let result = "";
73
+ let quoted = false;
74
+ let escaped = false;
75
+ let lineComment = false;
76
+ let blockComment = false;
77
+ for (let index = 0; index < text.length; index++) {
78
+ const character = text[index]!;
79
+ const next = text[index + 1];
80
+ if (lineComment) {
81
+ if (character === "\n") {
82
+ result += character;
83
+ lineComment = false;
84
+ } else result += " ";
85
+ } else if (blockComment) {
86
+ if (character === "*" && next === "/") {
87
+ result += " ";
88
+ index++;
89
+ blockComment = false;
90
+ } else result += character === "\n" ? "\n" : " ";
91
+ } else if (quoted) {
92
+ result += character;
93
+ if (escaped) escaped = false;
94
+ else if (character === "\\") escaped = true;
95
+ else if (character === '"') quoted = false;
96
+ } else if (character === '"') {
97
+ result += character;
98
+ quoted = true;
99
+ } else if (character === "/" && next === "/") {
100
+ result += " ";
101
+ index++;
102
+ lineComment = true;
103
+ } else if (character === "/" && next === "*") {
104
+ result += " ";
105
+ index++;
106
+ blockComment = true;
107
+ } else result += character;
108
+ }
109
+ return result;
110
+ }
111
+
112
+ async function readObject(path: string): Promise<ConfigurationObject> {
113
+ const text = await readFile(path, "utf8").catch((error: NodeJS.ErrnoException) => {
114
+ if (error.code === "ENOENT") return undefined;
115
+ throw error;
116
+ });
117
+ if (text === undefined) return {};
118
+ if (Buffer.byteLength(text) > 1024 * 1024 || text.includes("\0")) {
119
+ throw new Error("Configuration must be UTF-8 JSON smaller than 1 MiB.");
120
+ }
121
+ const value: unknown = JSON.parse(stripComments(text));
122
+ if (!isRecord(value)) throw new TypeError("Relapse configuration must be a JSON object.");
123
+ return value as ConfigurationObject;
124
+ }
125
+
126
+ async function writeObject(path: string, value: ConfigurationObject): Promise<void> {
127
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
128
+ const temporary = `${path}.tmp.${process.pid}.${Date.now()}`;
129
+ try {
130
+ await writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, {
131
+ encoding: "utf8", flag: "wx", mode: 0o600,
132
+ });
133
+ await rename(temporary, path);
134
+ } finally {
135
+ await unlink(temporary).catch((error: NodeJS.ErrnoException) => {
136
+ if (error.code !== "ENOENT") throw error;
137
+ });
138
+ }
139
+ }
140
+
141
+ function validatePath(value: unknown, key: string): void {
142
+ if (value !== undefined && (typeof value !== "string" || !value || !isAbsolute(value))) {
143
+ throw new TypeError(`${key} must be an absolute path.`);
144
+ }
145
+ }
146
+
147
+ function validateAutolaunch(value: unknown): asserts value is readonly string[] | null | undefined {
148
+ if (value === undefined || value === null) return;
149
+ if (!Array.isArray(value) || !value.length || value.some(argument => typeof argument !== "string") || !value[0]) {
150
+ throw new TypeError("autolaunch must be null or a nonempty string array.");
151
+ }
152
+ }
153
+
154
+ function validateGlobal(configuration: GlobalConfiguration): void {
155
+ if (configuration.defaultProfile !== undefined && !isValidName(configuration.defaultProfile)) {
156
+ throw new TypeError("defaultProfile must be a valid profile name.");
157
+ }
158
+ validatePath(configuration.workspace, "workspace");
159
+ validatePath(configuration.autoexec, "autoexec");
160
+ validateAutolaunch(configuration.autolaunch);
161
+ }
162
+
163
+ function validateProfile(configuration: ProfileConfiguration): void {
164
+ validatePath(configuration.dataDir, "dataDir");
165
+ if (configuration.override !== undefined) {
166
+ if (!isRecord(configuration.override)) throw new TypeError("Profile override must be an object.");
167
+ validatePath(configuration.override.workspace, "override.workspace");
168
+ validatePath(configuration.override.autoexec, "override.autoexec");
169
+ validateAutolaunch(configuration.override.autolaunch);
170
+ }
171
+ }
172
+
173
+ export async function readGlobal(options: ConfigurationOptions = {}): Promise<GlobalConfiguration> {
174
+ return await readObject(globalPath(options)) as GlobalConfiguration;
175
+ }
176
+
177
+ export async function readProfile(name: string, options: ConfigurationOptions = {}): Promise<ProfileConfiguration> {
178
+ return await readObject(profilePath(name, options)) as ProfileConfiguration;
179
+ }
180
+
181
+ export async function writeGlobal(
182
+ configuration: GlobalConfiguration, options: ConfigurationOptions = {},
183
+ ): Promise<void> {
184
+ if (!isRecord(configuration)) throw new TypeError("Global configuration must be an object.");
185
+ validateGlobal(configuration);
186
+ await writeObject(globalPath(options), configuration);
187
+ }
188
+
189
+ export async function writeProfile(
190
+ name: string, configuration: ProfileConfiguration, options: ConfigurationOptions = {},
191
+ ): Promise<void> {
192
+ if (!isValidName(name)) throw new TypeError("Invalid profile name.");
193
+ if (!isRecord(configuration)) throw new TypeError("Profile configuration must be an object.");
194
+ validateProfile(configuration);
195
+ await writeObject(profilePath(name, options), configuration);
196
+ }
197
+
198
+ function merge(target: ConfigurationObject, overrides: ConfigurationOverrides): ConfigurationObject {
199
+ for (const [key, value] of Object.entries(overrides)) {
200
+ const current = target[key];
201
+ target[key] = isRecord(current) && isRecord(value)
202
+ ? merge({ ...current }, value as ConfigurationOverrides)
203
+ : value;
204
+ }
205
+ return target;
206
+ }
207
+
208
+ function resolvedPath(object: ConfigurationObject, key: string, fallback: string): string {
209
+ const value = object[key];
210
+ if (value === undefined) return fallback;
211
+ validatePath(value, key);
212
+ return value as string;
213
+ }
214
+
215
+ function environmentName(path: string): string {
216
+ let name = "RELAPSE_";
217
+ for (const character of path) {
218
+ if (character === "." || character === "-") name += "_";
219
+ else if (/[a-zA-Z0-9_]/u.test(character)) name += character.toUpperCase();
220
+ else throw new TypeError(`Executor configuration key has unsupported characters: ${path}`);
221
+ }
222
+ return name;
223
+ }
224
+
225
+ function flatten(object: ConfigurationObject, prefix: string, environment: Record<string, string>): void {
226
+ for (const [key, value] of Object.entries(object)) {
227
+ const path = prefix ? `${prefix}.${key}` : key;
228
+ if (isRecord(value)) {
229
+ flatten(value as ConfigurationObject, path, environment);
230
+ continue;
231
+ }
232
+ let encoded: string;
233
+ if (typeof value === "boolean") encoded = value ? "1" : "0";
234
+ else if (typeof value === "string") encoded = value;
235
+ else if (typeof value === "number" && Number.isFinite(value)) encoded = JSON.stringify(value);
236
+ else throw new TypeError(`Executor configuration values must be scalar: ${path}`);
237
+ environment[environmentName(path)] = encoded;
238
+ }
239
+ }
240
+
241
+ export async function resolve(
242
+ requestedProfile?: string, options: ConfigurationOptions = {},
243
+ ): Promise<ResolvedConfiguration> {
244
+ const [global, profileConfiguration] = await Promise.all([readGlobal(options),
245
+ requestedProfile ? readProfile(requestedProfile, options) : undefined]);
246
+ let profile = requestedProfile;
247
+ if (!profile) {
248
+ const selected = global.defaultProfile === undefined ? "Default" : global.defaultProfile;
249
+ if (typeof selected !== "string") throw new TypeError("defaultProfile must be a string.");
250
+ profile = selected;
251
+ }
252
+ if (!isValidName(profile)) throw new TypeError("Invalid profile name.");
253
+ const selectedConfiguration = requestedProfile ? profileConfiguration! : await readProfile(profile, options);
254
+ const overrides = selectedConfiguration.override === undefined ? {} : selectedConfiguration.override;
255
+ if (!isRecord(overrides)) throw new TypeError("Profile override must be an object.");
256
+ const defaultDataDir = join(dataDirectory(options), "profiles", profile);
257
+ const dataDir = selectedConfiguration.dataDir === undefined ? defaultDataDir : selectedConfiguration.dataDir;
258
+ validatePath(dataDir, "dataDir");
259
+ const merged = merge({ ...global }, overrides);
260
+ delete merged.defaultProfile;
261
+ const workspace = resolvedPath(merged, "workspace", join(dataDirectory(options), "workspace"));
262
+ const autoexec = resolvedPath(merged, "autoexec", join(configDirectory(options), "autoexec"));
263
+ const command = merged.autolaunch;
264
+ validateAutolaunch(command);
265
+ const autolaunch = command ? Array.from(command) : null;
266
+ delete merged.workspace;
267
+ delete merged.autoexec;
268
+ delete merged.dataDir;
269
+ delete merged.autolaunch;
270
+ const environment: Record<string, string> = {};
271
+ flatten(merged, "", environment);
272
+ return { profile, dataDir: dataDir as string, workspace, autoexec, autolaunch, environment };
273
+ }