@g33ks/foundryvtt-mcp 0.0.0-stage → 2.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 +22 -0
- package/README.md +457 -2
- package/dist/character/manager.js +208 -0
- package/dist/cli/checks.js +307 -0
- package/dist/cli/config-file.js +120 -0
- package/dist/cli/init.js +414 -0
- package/dist/cli/prompt.js +117 -0
- package/dist/cli/snippets.js +64 -0
- package/dist/combat/manager.js +371 -0
- package/dist/config/env-layers.js +49 -0
- package/dist/config/index.js +298 -0
- package/dist/config/sources.js +201 -0
- package/dist/core.js +481 -0
- package/dist/diagnostics/client.js +291 -0
- package/dist/diagnostics/types.js +94 -0
- package/dist/foundry/auth.js +224 -0
- package/dist/foundry/browser-detect.js +170 -0
- package/dist/foundry/client.js +5874 -0
- package/dist/foundry/dice-formula.js +154 -0
- package/dist/foundry/event-log.js +298 -0
- package/dist/foundry/headless-gm-session.js +857 -0
- package/dist/foundry/journal-conflicts.js +141 -0
- package/dist/foundry/journal-history.js +90 -0
- package/dist/foundry/journal-integrity.js +322 -0
- package/dist/foundry/message-author.js +19 -0
- package/dist/foundry/module-bridge.js +441 -0
- package/dist/foundry/types.js +52 -0
- package/dist/foundry/world-cache.js +386 -0
- package/dist/index.js +107 -0
- package/dist/mcp-server.js +65 -0
- package/dist/server.js +159 -0
- package/dist/shared/build-order.js +134 -0
- package/dist/shared/config-hash.js +62 -0
- package/dist/shared/config-notice.js +55 -0
- package/dist/shared/control.js +291 -0
- package/dist/shared/daemon-link.js +135 -0
- package/dist/shared/daemon.js +311 -0
- package/dist/shared/ipc-client.js +200 -0
- package/dist/shared/ipc-server.js +316 -0
- package/dist/shared/paths.js +79 -0
- package/dist/shared/protocol.js +230 -0
- package/dist/shared/relay-config.js +65 -0
- package/dist/shared/relay.js +120 -0
- package/dist/shared/rotating-log.js +57 -0
- package/dist/shared/spawn.js +39 -0
- package/dist/shared/state-file.js +33 -0
- package/dist/shared/token.js +62 -0
- package/dist/shared/version.js +57 -0
- package/dist/tools/base.js +74 -0
- package/dist/tools/definitions.js +3109 -0
- package/dist/tools/handlers/actor-mutations.js +128 -0
- package/dist/tools/handlers/actors.js +114 -0
- package/dist/tools/handlers/chat-mutations.js +49 -0
- package/dist/tools/handlers/chat.js +38 -0
- package/dist/tools/handlers/combat-mutations.js +215 -0
- package/dist/tools/handlers/combat-order.js +94 -0
- package/dist/tools/handlers/combat.js +51 -0
- package/dist/tools/handlers/compendium.js +83 -0
- package/dist/tools/handlers/diagnostics.js +450 -0
- package/dist/tools/handlers/dice.js +54 -0
- package/dist/tools/handlers/effects.js +103 -0
- package/dist/tools/handlers/events.js +50 -0
- package/dist/tools/handlers/generation.js +258 -0
- package/dist/tools/handlers/item-mutations.js +132 -0
- package/dist/tools/handlers/items.js +53 -0
- package/dist/tools/handlers/journal-mutations.js +230 -0
- package/dist/tools/handlers/journals.js +80 -0
- package/dist/tools/handlers/module-bridge.js +421 -0
- package/dist/tools/handlers/placeable-mutations.js +272 -0
- package/dist/tools/handlers/resources.js +203 -0
- package/dist/tools/handlers/roll-tables.js +97 -0
- package/dist/tools/handlers/scene-mutations.js +159 -0
- package/dist/tools/handlers/scenes.js +355 -0
- package/dist/tools/handlers/settings.js +53 -0
- package/dist/tools/handlers/tile-mutations.js +56 -0
- package/dist/tools/handlers/token-mutations.js +356 -0
- package/dist/tools/handlers/users.js +59 -0
- package/dist/tools/handlers/utils.js +48 -0
- package/dist/tools/handlers/wall-mutations.js +98 -0
- package/dist/tools/handlers/world-documents.js +222 -0
- package/dist/tools/handlers/world.js +92 -0
- package/dist/tools/index.js +25 -0
- package/dist/tools/new-router.js +97 -0
- package/dist/tools/registry.js +79 -0
- package/dist/tools/resources.js +63 -0
- package/dist/tools/router.js +688 -0
- package/dist/tools/tool-dependencies.js +194 -0
- package/dist/tools/write-tools.js +97 -0
- package/dist/utils/cache-instance.js +30 -0
- package/dist/utils/cache.js +205 -0
- package/dist/utils/diagnostics.js +332 -0
- package/dist/utils/guards.js +17 -0
- package/dist/utils/image-size.js +160 -0
- package/dist/utils/log-args.js +47 -0
- package/dist/utils/logger.js +203 -0
- package/dist/utils/mcp-errors.js +47 -0
- package/dist/utils/refusal.js +30 -0
- package/dist/utils/sanitize.js +22 -0
- package/dist/utils/serial-queue.js +22 -0
- package/package.json +124 -4
|
@@ -0,0 +1,311 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview `foundryvtt-mcp daemon`: the shared process.
|
|
3
|
+
*
|
|
4
|
+
* Owns the single FoundryVTT connection, module bridge and headless GM
|
|
5
|
+
* session ({@link FoundryCore}) and serves tool calls forwarded by relays.
|
|
6
|
+
* It outlives the relays MCP clients start and stop, and exits on `stop`,
|
|
7
|
+
* after a relay from a newer build knocks, after one whose settings match a
|
|
8
|
+
* changed configuration file knocks (see {@link mismatchDecision}), or once
|
|
9
|
+
* no relay has been connected for the idle timeout. When the
|
|
10
|
+
* FoundryVTT connection cannot be established (FoundryVTT not started yet,
|
|
11
|
+
* wrong URL…) it stays up and retries on the next call.
|
|
12
|
+
*/
|
|
13
|
+
import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';
|
|
14
|
+
import { configFromSettings, getConfig } from '../config/index.js';
|
|
15
|
+
import { displayValue, KNOWN_SETTINGS, resolveSettings } from '../config/sources.js';
|
|
16
|
+
import { logger } from '../utils/logger.js';
|
|
17
|
+
import { bareMessage } from '../utils/mcp-errors.js';
|
|
18
|
+
import { isRefusal } from '../utils/refusal.js';
|
|
19
|
+
import { compareBuilds } from './build-order.js';
|
|
20
|
+
import { configDigests, configFingerprint } from './config-hash.js';
|
|
21
|
+
import { IpcServer } from './ipc-server.js';
|
|
22
|
+
import { resolveSharedPaths } from './paths.js';
|
|
23
|
+
import { RotatingLog } from './rotating-log.js';
|
|
24
|
+
import { removeStateFile, writeStateFile } from './state-file.js';
|
|
25
|
+
import { loadOrCreateToken } from './token.js';
|
|
26
|
+
import { buildVersion } from './version.js';
|
|
27
|
+
/** Sends the bare text of an McpError: the relay rebuilds the McpError. */
|
|
28
|
+
export function toIpcError(error) {
|
|
29
|
+
if (error instanceof McpError) {
|
|
30
|
+
return {
|
|
31
|
+
code: error.code,
|
|
32
|
+
message: bareMessage(error),
|
|
33
|
+
...(error.data !== undefined ? { data: error.data } : {}),
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
return {
|
|
37
|
+
code: ErrorCode.InternalError,
|
|
38
|
+
message: error instanceof Error ? error.message : String(error),
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Whether a relay running another build or configuration restarts this
|
|
43
|
+
* process ("the file is authoritative"):
|
|
44
|
+
*
|
|
45
|
+
* - a strictly newer build restarts it (see build-order.ts); an older or
|
|
46
|
+
* unorderable one is served as it is;
|
|
47
|
+
* - another configuration restarts it only when the relay's settings are
|
|
48
|
+
* those of the configuration file as it is on disk now: the file changed,
|
|
49
|
+
* or this process was started by a client whose `env` block overrides it;
|
|
50
|
+
* - any other difference (a client's `env` block) is served with this
|
|
51
|
+
* process's settings, and the relay is told which of its own are ignored;
|
|
52
|
+
* - with the file unreadable or invalid, nothing restarts.
|
|
53
|
+
*
|
|
54
|
+
* @param fileHash - fingerprint of the file alone, `null` when unreadable or invalid
|
|
55
|
+
*/
|
|
56
|
+
export function mismatchDecision(reason, relayVersion, ownVersion, config = {}) {
|
|
57
|
+
if (reason === 'version') {
|
|
58
|
+
return compareBuilds(relayVersion, ownVersion) === 'newer' ? 'restart' : 'accept';
|
|
59
|
+
}
|
|
60
|
+
const { relayHash, ownHash, fileHash } = config;
|
|
61
|
+
if (!fileHash || relayHash === undefined) {
|
|
62
|
+
return 'accept';
|
|
63
|
+
}
|
|
64
|
+
return relayHash === fileHash && fileHash !== ownHash ? 'restart' : 'accept';
|
|
65
|
+
}
|
|
66
|
+
function sleep(ms) {
|
|
67
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
68
|
+
}
|
|
69
|
+
function errorText(error) {
|
|
70
|
+
return error instanceof Error ? error.message : String(error);
|
|
71
|
+
}
|
|
72
|
+
export class SharedProcess {
|
|
73
|
+
options;
|
|
74
|
+
ipc;
|
|
75
|
+
startedAt = new Date();
|
|
76
|
+
core = null;
|
|
77
|
+
startup = null;
|
|
78
|
+
startupError = null;
|
|
79
|
+
shuttingDown = null;
|
|
80
|
+
idleTimer = null;
|
|
81
|
+
constructor(options) {
|
|
82
|
+
this.options = options;
|
|
83
|
+
this.ipc = new IpcServer({
|
|
84
|
+
endpoint: options.paths.endpoint,
|
|
85
|
+
token: options.token,
|
|
86
|
+
version: options.version,
|
|
87
|
+
configHash: options.configHash,
|
|
88
|
+
...(options.configDigests ? { configDigests: options.configDigests } : {}),
|
|
89
|
+
...(options.configStatus ? { configFile: options.configStatus.file.path } : {}),
|
|
90
|
+
toIpcError,
|
|
91
|
+
log: (level, message) => logger[level](message),
|
|
92
|
+
onRelayCountChange: (count) => this.updateIdleTimer(count),
|
|
93
|
+
onMismatch: (reason, relayVersion, relayHash) => {
|
|
94
|
+
const decision = mismatchDecision(reason, relayVersion, options.version, {
|
|
95
|
+
relayHash,
|
|
96
|
+
ownHash: options.configHash,
|
|
97
|
+
// Re-read now: the file may have changed since this process started.
|
|
98
|
+
fileHash: reason === 'config' ? (options.fileConfigHash?.() ?? null) : null,
|
|
99
|
+
});
|
|
100
|
+
if (decision === 'restart') {
|
|
101
|
+
void this.drainAndExit(reason === 'version'
|
|
102
|
+
? `a relay from a newer build (v${relayVersion}) connected`
|
|
103
|
+
: "a relay with the configuration file's settings connected (the file changed, or this process was started with a client's own settings)");
|
|
104
|
+
}
|
|
105
|
+
return decision;
|
|
106
|
+
},
|
|
107
|
+
handler: async (op, name, args) => {
|
|
108
|
+
switch (op) {
|
|
109
|
+
case 'tool':
|
|
110
|
+
return (await this.ready()).callTool(name ?? '', args);
|
|
111
|
+
case 'resource':
|
|
112
|
+
return (await this.ready()).readResource(name ?? '');
|
|
113
|
+
case 'status':
|
|
114
|
+
return this.status();
|
|
115
|
+
case 'stop':
|
|
116
|
+
setImmediate(() => void this.drainAndExit('stop requested'));
|
|
117
|
+
return { stopping: true, pid: process.pid };
|
|
118
|
+
}
|
|
119
|
+
},
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* Takes the single-instance lock, then builds and starts the core. A
|
|
124
|
+
* process that loses the race returns `in-use` without touching FoundryVTT.
|
|
125
|
+
*/
|
|
126
|
+
async start() {
|
|
127
|
+
const { paths, version } = this.options;
|
|
128
|
+
if ((await this.ipc.listen()) === 'in-use') {
|
|
129
|
+
return 'in-use';
|
|
130
|
+
}
|
|
131
|
+
writeStateFile(paths.stateFile, {
|
|
132
|
+
pid: process.pid,
|
|
133
|
+
version,
|
|
134
|
+
startedAt: this.startedAt.toISOString(),
|
|
135
|
+
endpoint: paths.endpoint,
|
|
136
|
+
logFile: paths.daemonLog,
|
|
137
|
+
});
|
|
138
|
+
logger.info(`Shared process ${process.pid} (v${version}) listening on ${paths.endpoint}`);
|
|
139
|
+
this.startup = this.bootCore();
|
|
140
|
+
this.updateIdleTimer(0);
|
|
141
|
+
return 'listening';
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Arms the idle timer while no relay is connected, disarms it otherwise.
|
|
145
|
+
* Hours without a call do not count as idle as long as a relay is there.
|
|
146
|
+
*/
|
|
147
|
+
updateIdleTimer(relays) {
|
|
148
|
+
const idleTimeoutMs = this.options.idleTimeoutMs ?? 0;
|
|
149
|
+
if (this.idleTimer) {
|
|
150
|
+
clearTimeout(this.idleTimer);
|
|
151
|
+
this.idleTimer = null;
|
|
152
|
+
}
|
|
153
|
+
if (relays === 0 && idleTimeoutMs > 0 && !this.shuttingDown) {
|
|
154
|
+
this.idleTimer = setTimeout(() => void this.drainAndExit(`no relay connected for ${Number((idleTimeoutMs / 60_000).toFixed(2))} min`), idleTimeoutMs);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
/** Builds and starts a core, replacing one whose start failed. */
|
|
158
|
+
bootCore() {
|
|
159
|
+
return (async () => {
|
|
160
|
+
if (this.core) {
|
|
161
|
+
await this.core.shutdown();
|
|
162
|
+
}
|
|
163
|
+
this.core = await this.options.createCore();
|
|
164
|
+
await this.core.start();
|
|
165
|
+
})().catch((error) => {
|
|
166
|
+
this.startupError = error;
|
|
167
|
+
if (isRefusal(error)) {
|
|
168
|
+
// Expected (no world launched yet): the core already logged one line.
|
|
169
|
+
logger.info('Shared process waits for FoundryVTT; the next call retries');
|
|
170
|
+
}
|
|
171
|
+
else {
|
|
172
|
+
logger.error('Shared process could not connect to FoundryVTT; the next call retries', error);
|
|
173
|
+
}
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* Stops accepting work, lets started calls finish (a write is never cut
|
|
178
|
+
* in half), tears the core down, releases the endpoint and exits.
|
|
179
|
+
*/
|
|
180
|
+
drainAndExit(reason, code = 0) {
|
|
181
|
+
this.shuttingDown ??= (async () => {
|
|
182
|
+
const { drainMaxMs = 120_000, shutdownGraceMs = 5000, paths, exit } = this.options;
|
|
183
|
+
logger.info(`Shared process shutting down: ${reason}`);
|
|
184
|
+
if (this.idleTimer) {
|
|
185
|
+
clearTimeout(this.idleTimer);
|
|
186
|
+
}
|
|
187
|
+
this.ipc.setDraining();
|
|
188
|
+
await Promise.race([this.ipc.waitForIdle(), sleep(drainMaxMs)]);
|
|
189
|
+
const force = setTimeout(() => exit(1), shutdownGraceMs);
|
|
190
|
+
force.unref();
|
|
191
|
+
await this.core?.shutdown();
|
|
192
|
+
await this.ipc.close();
|
|
193
|
+
clearTimeout(force);
|
|
194
|
+
removeStateFile(paths.stateFile, process.pid);
|
|
195
|
+
exit(code);
|
|
196
|
+
})();
|
|
197
|
+
return this.shuttingDown;
|
|
198
|
+
}
|
|
199
|
+
/** Connected relays, and the builds of those older than this process. */
|
|
200
|
+
relays() {
|
|
201
|
+
return { connected: this.ipc.relayCount, outdated: this.ipc.outdatedRelayVersions };
|
|
202
|
+
}
|
|
203
|
+
status() {
|
|
204
|
+
const coreStatus = this.core?.status() ?? {};
|
|
205
|
+
return {
|
|
206
|
+
pid: process.pid,
|
|
207
|
+
version: this.options.version,
|
|
208
|
+
startedAt: this.startedAt.toISOString(),
|
|
209
|
+
uptimeSeconds: Math.round((Date.now() - this.startedAt.getTime()) / 1000),
|
|
210
|
+
endpoint: this.options.paths.endpoint,
|
|
211
|
+
logFile: this.options.paths.daemonLog,
|
|
212
|
+
relays: this.ipc.relayCount,
|
|
213
|
+
outdatedRelays: this.ipc.outdatedRelayVersions,
|
|
214
|
+
// Excludes this status request itself.
|
|
215
|
+
inFlight: this.ipc.inFlightCount - 1,
|
|
216
|
+
...(this.options.configStatus ? { config: this.options.configStatus } : {}),
|
|
217
|
+
relayConfigs: this.ipc.relayConfigList,
|
|
218
|
+
startupError: this.startupError ? errorText(this.startupError) : null,
|
|
219
|
+
...coreStatus,
|
|
220
|
+
};
|
|
221
|
+
}
|
|
222
|
+
/** Waits (bounded) for the FoundryVTT connection attempt, then hands out the core. */
|
|
223
|
+
async ready() {
|
|
224
|
+
if (this.startupError !== null && !this.shuttingDown) {
|
|
225
|
+
// The last attempt failed: this call retries (concurrent calls share the attempt).
|
|
226
|
+
this.startupError = null;
|
|
227
|
+
this.startup = this.bootCore();
|
|
228
|
+
}
|
|
229
|
+
if (this.startup) {
|
|
230
|
+
await Promise.race([this.startup, sleep(this.options.startupWaitMs ?? 30_000)]);
|
|
231
|
+
}
|
|
232
|
+
if (this.startupError) {
|
|
233
|
+
throw new McpError(ErrorCode.InternalError, `The shared process could not connect to FoundryVTT: ${errorText(this.startupError).replace(/\.$/, '')}. The next call retries. Log: ${this.options.paths.daemonLog}`);
|
|
234
|
+
}
|
|
235
|
+
if (!this.core) {
|
|
236
|
+
throw new McpError(ErrorCode.InternalError, `The shared process is still starting. Log: ${this.options.paths.daemonLog}`);
|
|
237
|
+
}
|
|
238
|
+
return this.core;
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
/** Entry point of `foundryvtt-mcp daemon`. */
|
|
242
|
+
export async function runDaemon(paths = resolveSharedPaths()) {
|
|
243
|
+
// Started detached with stdio ignored: the log file is the only output.
|
|
244
|
+
const log = new RotatingLog(paths.daemonLog);
|
|
245
|
+
logger.addSink((line) => log.write(line));
|
|
246
|
+
logger.info(`Shared process ${process.pid} starting (node ${process.version}, cwd ${process.cwd()})`);
|
|
247
|
+
const token = loadOrCreateToken(paths.tokenFile);
|
|
248
|
+
let config;
|
|
249
|
+
try {
|
|
250
|
+
config = getConfig();
|
|
251
|
+
}
|
|
252
|
+
catch (error) {
|
|
253
|
+
// A relay only starts this process with a usable configuration; the
|
|
254
|
+
// environment or the file changed in between. Nothing to serve.
|
|
255
|
+
logger.error(`Shared process cannot start: ${error instanceof Error ? error.message : error}`);
|
|
256
|
+
process.exit(1);
|
|
257
|
+
}
|
|
258
|
+
const settings = resolveSettings();
|
|
259
|
+
if (settings.file.warning) {
|
|
260
|
+
logger.warn(settings.file.warning);
|
|
261
|
+
}
|
|
262
|
+
const shared = new SharedProcess({
|
|
263
|
+
paths,
|
|
264
|
+
version: buildVersion(),
|
|
265
|
+
token,
|
|
266
|
+
configHash: configFingerprint(config, token),
|
|
267
|
+
configDigests: configDigests(config, token),
|
|
268
|
+
fileConfigHash: () => {
|
|
269
|
+
const fileOnly = resolveSettings({ fileOnly: true });
|
|
270
|
+
if (!fileOnly.file.found || fileOnly.file.error) {
|
|
271
|
+
return null;
|
|
272
|
+
}
|
|
273
|
+
try {
|
|
274
|
+
return configFingerprint(configFromSettings(fileOnly), token);
|
|
275
|
+
}
|
|
276
|
+
catch {
|
|
277
|
+
return null;
|
|
278
|
+
}
|
|
279
|
+
},
|
|
280
|
+
configStatus: {
|
|
281
|
+
file: settings.file,
|
|
282
|
+
settings: KNOWN_SETTINGS.filter((name) => settings.values[name] !== undefined).map((name) => ({
|
|
283
|
+
name,
|
|
284
|
+
value: displayValue(name, settings.values[name]),
|
|
285
|
+
source: settings.sources[name],
|
|
286
|
+
})),
|
|
287
|
+
},
|
|
288
|
+
idleTimeoutMs: config.shared.idleTimeoutMinutes * 60_000,
|
|
289
|
+
// Loaded lazily: Socket.IO, Playwright & co. are not needed to lose the race.
|
|
290
|
+
createCore: async () => new (await import('../core.js')).FoundryCore({ relays: () => shared.relays() }),
|
|
291
|
+
exit: (code) => process.exit(code),
|
|
292
|
+
});
|
|
293
|
+
for (const signal of ['SIGINT', 'SIGTERM', 'SIGBREAK', 'SIGHUP']) {
|
|
294
|
+
process.on(signal, () => void shared.drainAndExit(`received ${signal}`));
|
|
295
|
+
}
|
|
296
|
+
process.on('uncaughtException', (error) => {
|
|
297
|
+
logger.error('Uncaught exception in the shared process:', error);
|
|
298
|
+
removeStateFile(paths.stateFile, process.pid);
|
|
299
|
+
process.exit(1);
|
|
300
|
+
});
|
|
301
|
+
process.on('unhandledRejection', (reason) => {
|
|
302
|
+
logger.error('Unhandled rejection in the shared process:', { reason: String(reason) });
|
|
303
|
+
removeStateFile(paths.stateFile, process.pid);
|
|
304
|
+
process.exit(1);
|
|
305
|
+
});
|
|
306
|
+
if ((await shared.start()) === 'in-use') {
|
|
307
|
+
logger.info('Another shared process already listens on the endpoint; exiting');
|
|
308
|
+
process.exit(0);
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
//# sourceMappingURL=daemon.js.map
|
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Client side of the relay ↔ shared-process channel.
|
|
3
|
+
*/
|
|
4
|
+
import net from 'node:net';
|
|
5
|
+
import { encodeLine, HelloReplySchema, LineDecoder, ResponseSchema, } from './protocol.js';
|
|
6
|
+
/** Nothing listens on the endpoint (no shared process, or it just exited). */
|
|
7
|
+
export class EndpointUnavailableError extends Error {
|
|
8
|
+
endpoint;
|
|
9
|
+
constructor(endpoint, cause) {
|
|
10
|
+
super(`No shared process listening on ${endpoint}`, { cause });
|
|
11
|
+
this.endpoint = endpoint;
|
|
12
|
+
this.name = 'EndpointUnavailableError';
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
/** The shared process answered the handshake with a refusal. */
|
|
16
|
+
export class HandshakeRejectedError extends Error {
|
|
17
|
+
reason;
|
|
18
|
+
constructor(reason, message) {
|
|
19
|
+
super(message);
|
|
20
|
+
this.reason = reason;
|
|
21
|
+
this.name = 'HandshakeRejectedError';
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
/** The connection closed while a request was pending. */
|
|
25
|
+
export class ConnectionLostError extends Error {
|
|
26
|
+
constructor() {
|
|
27
|
+
super('Connection to the shared process was lost');
|
|
28
|
+
this.name = 'ConnectionLostError';
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
/** The shared process answered a request with an error. */
|
|
32
|
+
export class RemoteError extends Error {
|
|
33
|
+
code;
|
|
34
|
+
data;
|
|
35
|
+
constructor(error) {
|
|
36
|
+
super(error.message);
|
|
37
|
+
this.name = 'RemoteError';
|
|
38
|
+
this.code = error.code;
|
|
39
|
+
this.data = error.data;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
/** How long the shared process may take to answer the handshake. */
|
|
43
|
+
const HELLO_TIMEOUT_MS = 5000;
|
|
44
|
+
export class IpcConnection {
|
|
45
|
+
socket;
|
|
46
|
+
pending = new Map();
|
|
47
|
+
nextId = 1;
|
|
48
|
+
closed = false;
|
|
49
|
+
closeListeners = [];
|
|
50
|
+
/** pid reported by the shared process at the handshake. */
|
|
51
|
+
serverPid;
|
|
52
|
+
/** Build the shared process reported at the handshake. */
|
|
53
|
+
serverVersion;
|
|
54
|
+
/**
|
|
55
|
+
* This relay's settings the shared process does not apply (it serves its
|
|
56
|
+
* own), with the file it reads; `null` when none are ignored.
|
|
57
|
+
*/
|
|
58
|
+
ignoredConfig;
|
|
59
|
+
constructor(socket, reply) {
|
|
60
|
+
this.socket = socket;
|
|
61
|
+
this.serverPid = reply.pid;
|
|
62
|
+
this.serverVersion = reply.version;
|
|
63
|
+
this.ignoredConfig = reply.ignoredConfig
|
|
64
|
+
? { settings: reply.ignoredConfig, configFile: reply.configFile ?? null }
|
|
65
|
+
: null;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Connects and performs the handshake.
|
|
69
|
+
*
|
|
70
|
+
* @throws {EndpointUnavailableError} nothing listens on `endpoint`
|
|
71
|
+
* @throws {HandshakeRejectedError} the shared process refused the hello
|
|
72
|
+
*/
|
|
73
|
+
static connect(endpoint, hello) {
|
|
74
|
+
return new Promise((resolve, reject) => {
|
|
75
|
+
const socket = net.connect(endpoint);
|
|
76
|
+
const decoder = new LineDecoder();
|
|
77
|
+
let connection = null;
|
|
78
|
+
let settled = false;
|
|
79
|
+
const fail = (error) => {
|
|
80
|
+
if (!settled) {
|
|
81
|
+
settled = true;
|
|
82
|
+
clearTimeout(timer);
|
|
83
|
+
socket.destroy();
|
|
84
|
+
reject(error);
|
|
85
|
+
}
|
|
86
|
+
};
|
|
87
|
+
const timer = setTimeout(() => fail(new Error(`Shared process did not answer the handshake on ${endpoint}`)), HELLO_TIMEOUT_MS);
|
|
88
|
+
socket.once('connect', () => socket.write(encodeLine(hello)));
|
|
89
|
+
socket.on('error', (error) => {
|
|
90
|
+
if (!settled) {
|
|
91
|
+
fail(new EndpointUnavailableError(endpoint, error));
|
|
92
|
+
}
|
|
93
|
+
});
|
|
94
|
+
socket.on('close', () => {
|
|
95
|
+
if (connection) {
|
|
96
|
+
connection.handleClose();
|
|
97
|
+
}
|
|
98
|
+
else {
|
|
99
|
+
fail(new ConnectionLostError());
|
|
100
|
+
}
|
|
101
|
+
});
|
|
102
|
+
socket.on('data', (chunk) => {
|
|
103
|
+
let messages;
|
|
104
|
+
try {
|
|
105
|
+
messages = decoder.push(chunk);
|
|
106
|
+
}
|
|
107
|
+
catch (error) {
|
|
108
|
+
fail(error instanceof Error ? error : new Error(String(error)));
|
|
109
|
+
connection?.socket.destroy();
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
for (const message of messages) {
|
|
113
|
+
if (connection) {
|
|
114
|
+
connection.handleMessage(message);
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
const reply = HelloReplySchema.safeParse(message);
|
|
118
|
+
if (!reply.success) {
|
|
119
|
+
fail(new Error('Invalid handshake reply from the shared process'));
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
if (!reply.data.ok) {
|
|
123
|
+
fail(new HandshakeRejectedError(reply.data.reason, reply.data.message));
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
settled = true;
|
|
127
|
+
clearTimeout(timer);
|
|
128
|
+
connection = new IpcConnection(socket, reply.data);
|
|
129
|
+
resolve(connection);
|
|
130
|
+
}
|
|
131
|
+
});
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
get isClosed() {
|
|
135
|
+
return this.closed;
|
|
136
|
+
}
|
|
137
|
+
/** Registers a callback for when the connection closes. */
|
|
138
|
+
onClose(listener) {
|
|
139
|
+
this.closeListeners.push(listener);
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* Sends one request. No client-side timeout: the shared process bounds
|
|
143
|
+
* every operation itself, and a relay must never give up earlier than it.
|
|
144
|
+
*
|
|
145
|
+
* @throws {RemoteError} the shared process answered with an error
|
|
146
|
+
* @throws {ConnectionLostError} the connection closed first
|
|
147
|
+
*/
|
|
148
|
+
request(op, name, args) {
|
|
149
|
+
if (this.closed) {
|
|
150
|
+
return Promise.reject(new ConnectionLostError());
|
|
151
|
+
}
|
|
152
|
+
const id = this.nextId++;
|
|
153
|
+
return new Promise((resolve, reject) => {
|
|
154
|
+
this.pending.set(id, { resolve, reject });
|
|
155
|
+
this.socket.write(encodeLine({
|
|
156
|
+
type: 'request',
|
|
157
|
+
id,
|
|
158
|
+
op,
|
|
159
|
+
...(name !== undefined ? { name } : {}),
|
|
160
|
+
...(args !== undefined ? { args } : {}),
|
|
161
|
+
}));
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
close() {
|
|
165
|
+
this.socket.end();
|
|
166
|
+
this.socket.destroy();
|
|
167
|
+
}
|
|
168
|
+
handleMessage(message) {
|
|
169
|
+
const parsed = ResponseSchema.safeParse(message);
|
|
170
|
+
if (!parsed.success) {
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
const response = parsed.data;
|
|
174
|
+
const pending = this.pending.get(response.id);
|
|
175
|
+
if (!pending) {
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
this.pending.delete(response.id);
|
|
179
|
+
if ('error' in response) {
|
|
180
|
+
pending.reject(new RemoteError(response.error));
|
|
181
|
+
}
|
|
182
|
+
else {
|
|
183
|
+
pending.resolve(response.result);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
handleClose() {
|
|
187
|
+
if (this.closed) {
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
this.closed = true;
|
|
191
|
+
for (const [, pending] of this.pending) {
|
|
192
|
+
pending.reject(new ConnectionLostError());
|
|
193
|
+
}
|
|
194
|
+
this.pending.clear();
|
|
195
|
+
for (const listener of this.closeListeners) {
|
|
196
|
+
listener();
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
//# sourceMappingURL=ipc-client.js.map
|