leafrelay 0.2.7 → 0.2.9

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/dist/daemon.js CHANGED
@@ -1,976 +1,909 @@
1
- import {
2
- ExtendedBaseAPI,
3
- HttpRequestScheduler,
4
- RemoteProject,
5
- SocketIOAPI,
6
- getServerSession,
7
- normalizeServerUrl,
8
- readConfig,
9
- readProjectSettings,
10
- removeKnownServer,
11
- removeServerSession,
12
- saveKnownServer,
13
- saveServerSession,
14
- serverKey,
15
- setLogSink,
16
- startServe
17
- } from "./chunk-3TTRDNHP.js";
18
-
19
- // ../daemon/src/server.ts
20
- import { randomBytes, randomUUID as randomUUID2 } from "crypto";
21
- import { appendFile, chmod, mkdir, readFile, rm, writeFile } from "fs/promises";
22
- import { createServer } from "net";
23
- import { formatWithOptions } from "util";
24
-
1
+ import { c as readConfig, d as removeServerSession, f as saveKnownServer, g as startServe, h as setLogSink, i as SocketIOAPI, l as readProjectSettings, m as serverKey, n as HttpRequestScheduler, o as getServerSession, p as saveServerSession, r as RemoteProject, s as normalizeServerUrl, t as ExtendedBaseAPI, u as removeKnownServer } from "./dist-JyfvbgjD.js";
2
+ import { formatWithOptions } from "node:util";
3
+ import { appendFile, chmod, mkdir, realpath, rm, writeFile } from "node:fs/promises";
4
+ import { homedir } from "node:os";
5
+ import { join, resolve } from "node:path";
6
+ import { createHash, randomBytes, randomUUID } from "node:crypto";
7
+ import { createServer } from "node:net";
8
+ import { ResponseError, SocketMessageReader, SocketMessageWriter, createMessageConnection } from "vscode-jsonrpc/node";
25
9
  // ../protocol/dist/index.js
26
- var LEAFRELAY_PROTOCOL_VERSION = 1;
27
- var RPC_METHOD = {
28
- initialize: "leafrelay/initialize",
29
- daemonStatus: "leafrelay/daemon/status",
30
- daemonShutdown: "leafrelay/daemon/shutdown",
31
- replicaAttach: "leafrelay/replica/attach",
32
- replicaDetach: "leafrelay/replica/detach",
33
- replicaResolveConflict: "leafrelay/replica/resolveConflict",
34
- replicaRetry: "leafrelay/replica/retry",
35
- sessionImport: "leafrelay/session/import",
36
- sessionLogin: "leafrelay/session/login",
37
- sessionLogout: "leafrelay/session/logout",
38
- serverList: "leafrelay/server/list",
39
- serverAdd: "leafrelay/server/add",
40
- serverRemove: "leafrelay/server/remove",
41
- serverCall: "leafrelay/server/call",
42
- projectOpen: "leafrelay/project/open",
43
- projectClose: "leafrelay/project/close",
44
- projectCall: "leafrelay/project/call"
10
+ const RPC_METHOD = {
11
+ initialize: "leafrelay/initialize",
12
+ daemonStatus: "leafrelay/daemon/status",
13
+ daemonShutdown: "leafrelay/daemon/shutdown",
14
+ replicaAttach: "leafrelay/replica/attach",
15
+ replicaDetach: "leafrelay/replica/detach",
16
+ replicaResolveConflict: "leafrelay/replica/resolveConflict",
17
+ replicaRetry: "leafrelay/replica/retry",
18
+ sessionImport: "leafrelay/session/import",
19
+ sessionLogin: "leafrelay/session/login",
20
+ sessionLogout: "leafrelay/session/logout",
21
+ serverList: "leafrelay/server/list",
22
+ serverAdd: "leafrelay/server/add",
23
+ serverRemove: "leafrelay/server/remove",
24
+ serverCall: "leafrelay/server/call",
25
+ projectOpen: "leafrelay/project/open",
26
+ projectClose: "leafrelay/project/close",
27
+ projectCall: "leafrelay/project/call"
45
28
  };
46
- var RPC_NOTIFICATION = {
47
- log: "leafrelay/log",
48
- replicaStatus: "leafrelay/replica/status",
49
- replicaConflict: "leafrelay/replica/conflict",
50
- projectEvent: "leafrelay/project/event"
29
+ const RPC_NOTIFICATION = {
30
+ log: "leafrelay/log",
31
+ replicaStatus: "leafrelay/replica/status",
32
+ replicaConflict: "leafrelay/replica/conflict",
33
+ projectEvent: "leafrelay/project/event"
51
34
  };
52
-
53
- // ../daemon/src/server.ts
54
- import { ResponseError } from "vscode-jsonrpc/node";
55
-
56
35
  // ../daemon/src/paths.ts
57
- import { createHash } from "crypto";
58
- import { homedir } from "os";
59
- import { join, resolve } from "path";
60
36
  function daemonPaths(environment = process.env) {
61
- const home = environment.LEAFRELAY_HOME ? resolve(environment.LEAFRELAY_HOME) : join(homedir(), ".leafrelay");
62
- const socketPath = process.platform === "win32" ? `\\\\.\\pipe\\leafrelay-${createHash("sha256").update(home).digest("hex").slice(0, 16)}` : join(home, "daemon.sock");
63
- return {
64
- home,
65
- socketPath,
66
- metadataPath: join(home, "daemon.json"),
67
- logPath: join(home, "daemon.log"),
68
- startupLockPath: join(home, "daemon.starting")
69
- };
37
+ const home = environment.LEAFRELAY_HOME ? resolve(environment.LEAFRELAY_HOME) : join(homedir(), ".leafrelay");
38
+ return {
39
+ home,
40
+ socketPath: process.platform === "win32" ? `\\\\.\\pipe\\leafrelay-${createHash("sha256").update(home).digest("hex").slice(0, 16)}` : join(home, "daemon.sock"),
41
+ metadataPath: join(home, "daemon.json"),
42
+ logPath: join(home, "daemon.log"),
43
+ startupLockPath: join(home, "daemon.starting")
44
+ };
70
45
  }
71
-
72
46
  // ../daemon/src/codec.ts
73
47
  function isEncodedBinary(value) {
74
- return typeof value === "object" && value !== null && value.$leafrelay === "bytes" && typeof value.base64 === "string";
48
+ return typeof value === "object" && value !== null && value.$leafrelay === "bytes" && typeof value.base64 === "string";
75
49
  }
76
50
  function encodeRpcValue(value) {
77
- if (value instanceof Uint8Array) {
78
- return { $leafrelay: "bytes", base64: Buffer.from(value).toString("base64") };
79
- }
80
- if (Array.isArray(value)) {
81
- return value.map(encodeRpcValue);
82
- }
83
- if (typeof value === "object" && value !== null) {
84
- return Object.fromEntries(Object.entries(value).map(([key, child]) => [key, encodeRpcValue(child)]));
85
- }
86
- return value;
51
+ if (value instanceof Uint8Array) return {
52
+ $leafrelay: "bytes",
53
+ base64: Buffer.from(value).toString("base64")
54
+ };
55
+ if (Array.isArray(value)) return value.map(encodeRpcValue);
56
+ if (typeof value === "object" && value !== null) return Object.fromEntries(Object.entries(value).map(([key, child]) => [key, encodeRpcValue(child)]));
57
+ return value;
87
58
  }
88
59
  function decodeRpcValue(value) {
89
- if (isEncodedBinary(value)) {
90
- return Uint8Array.from(Buffer.from(value.base64, "base64"));
91
- }
92
- if (Array.isArray(value)) {
93
- return value.map(decodeRpcValue);
94
- }
95
- if (typeof value === "object" && value !== null) {
96
- return Object.fromEntries(Object.entries(value).map(([key, child]) => [key, decodeRpcValue(child)]));
97
- }
98
- return value;
60
+ if (isEncodedBinary(value)) return Uint8Array.from(Buffer.from(value.base64, "base64"));
61
+ if (Array.isArray(value)) return value.map(decodeRpcValue);
62
+ if (typeof value === "object" && value !== null) return Object.fromEntries(Object.entries(value).map(([key, child]) => [key, decodeRpcValue(child)]));
63
+ return value;
99
64
  }
100
-
101
65
  // ../daemon/src/networkRuntime.ts
102
- var SERVER_OPERATIONS = /* @__PURE__ */ new Set([
103
- "userProjectsJson",
104
- "getProjectsJson",
105
- "projectEntitiesJson",
106
- "newProject",
107
- "cloneProject",
108
- "renameProject",
109
- "deleteProject",
110
- "archiveProject",
111
- "unarchiveProject",
112
- "trashProject",
113
- "untrashProject",
114
- "getFile",
115
- "addDoc",
116
- "uploadFile",
117
- "uploadProject",
118
- "addFolder",
119
- "deleteEntity",
120
- "deleteAuxFiles",
121
- "renameEntity",
122
- "moveEntity",
123
- "compile",
124
- "stopCompile",
125
- "indexAll",
126
- "getMetadata",
127
- "proxyRequestToSpellingApi",
128
- "spellingControllerLearn",
129
- "spellingControllerUnlearn",
130
- "getProjectSettings",
131
- "updateProjectSettings",
132
- "getFileFromClsi",
133
- "proxySyncPdf",
134
- "proxySyncCode",
135
- "getAllTags",
136
- "createTag",
137
- "renameTag",
138
- "deleteTag",
139
- "addProjectToTag",
140
- "removeProjectFromTag",
141
- "proxyToHistoryApiAndGetUpdates",
142
- "proxyToHistoryApiAndGetFileDiff",
143
- "proxyToHistoryApiAndGetFileTreeDiff",
144
- "downloadZipOfVersion",
145
- "getLabels",
146
- "createLabel",
147
- "deleteLabel",
148
- "getMessages",
149
- "sendMessage",
150
- "refreshLinkedFile",
151
- "createLinkedFile"
66
+ const SERVER_OPERATIONS = /* @__PURE__ */ new Set([
67
+ "userProjectsJson",
68
+ "getProjectsJson",
69
+ "projectEntitiesJson",
70
+ "newProject",
71
+ "cloneProject",
72
+ "renameProject",
73
+ "deleteProject",
74
+ "archiveProject",
75
+ "unarchiveProject",
76
+ "trashProject",
77
+ "untrashProject",
78
+ "getFile",
79
+ "addDoc",
80
+ "uploadFile",
81
+ "uploadProject",
82
+ "addFolder",
83
+ "deleteEntity",
84
+ "deleteAuxFiles",
85
+ "renameEntity",
86
+ "moveEntity",
87
+ "compile",
88
+ "stopCompile",
89
+ "indexAll",
90
+ "getMetadata",
91
+ "proxyRequestToSpellingApi",
92
+ "spellingControllerLearn",
93
+ "spellingControllerUnlearn",
94
+ "getProjectSettings",
95
+ "updateProjectSettings",
96
+ "getFileFromClsi",
97
+ "proxySyncPdf",
98
+ "proxySyncCode",
99
+ "getAllTags",
100
+ "createTag",
101
+ "renameTag",
102
+ "deleteTag",
103
+ "addProjectToTag",
104
+ "removeProjectFromTag",
105
+ "proxyToHistoryApiAndGetUpdates",
106
+ "proxyToHistoryApiAndGetFileDiff",
107
+ "proxyToHistoryApiAndGetFileTreeDiff",
108
+ "downloadZipOfVersion",
109
+ "getLabels",
110
+ "createLabel",
111
+ "deleteLabel",
112
+ "getMessages",
113
+ "sendMessage",
114
+ "refreshLinkedFile",
115
+ "createLinkedFile"
152
116
  ]);
153
- var PROJECT_OPERATIONS = /* @__PURE__ */ new Set([
154
- "init",
155
- "joinProject",
156
- "joinDoc",
157
- "leaveDoc",
158
- "applyOtUpdate",
159
- "getConnectedUsers",
160
- "updatePosition",
161
- "syncFileChanges"
117
+ const PROJECT_OPERATIONS = /* @__PURE__ */ new Set([
118
+ "init",
119
+ "joinProject",
120
+ "joinDoc",
121
+ "leaveDoc",
122
+ "applyOtUpdate",
123
+ "getConnectedUsers",
124
+ "updatePosition",
125
+ "syncFileChanges"
162
126
  ]);
163
- var REMOTE_PROJECT_OPERATIONS = /* @__PURE__ */ new Set([
164
- "entry",
165
- "listEntries",
166
- "read",
167
- "write",
168
- "mkdir",
169
- "remove",
170
- "getCurrentVersion",
171
- "getFileTreeDiff"
127
+ const REMOTE_PROJECT_OPERATIONS = /* @__PURE__ */ new Set([
128
+ "entry",
129
+ "listEntries",
130
+ "read",
131
+ "write",
132
+ "mkdir",
133
+ "remove",
134
+ "getCurrentVersion",
135
+ "getFileTreeDiff"
172
136
  ]);
173
137
  var NetworkRuntimeRegistry = class {
174
- constructor(events) {
175
- this.events = events;
176
- }
177
- events;
178
- servers = /* @__PURE__ */ new Map();
179
- projects = /* @__PURE__ */ new Map();
180
- get projectCount() {
181
- return this.projects.size;
182
- }
183
- async listServers() {
184
- const config = await readConfig();
185
- const keys = /* @__PURE__ */ new Set([...Object.keys(config.knownServers ?? {}), ...Object.keys(config.servers)]);
186
- if (keys.size === 0) {
187
- keys.add("www.overleaf.com");
188
- }
189
- return [...keys].sort().map((key) => {
190
- const session = config.servers[key];
191
- const known = config.knownServers?.[key];
192
- return {
193
- name: known?.name ?? key,
194
- url: known?.url ?? session?.url ?? normalizeServerUrl(key),
195
- loggedIn: Boolean(session),
196
- userId: session?.userId,
197
- userEmail: session?.userEmail
198
- };
199
- });
200
- }
201
- async addServer(name, url) {
202
- await saveKnownServer(name, url);
203
- }
204
- async removeServer(server2) {
205
- const key = serverKey(server2);
206
- for (const project of this.projects.values()) {
207
- if (project.server.key === key) {
208
- await this.stopProject(project);
209
- }
210
- }
211
- this.servers.delete(key);
212
- await removeKnownServer(server2);
213
- }
214
- async login(params) {
215
- const url = normalizeServerUrl(params.server);
216
- const scheduler = new HttpRequestScheduler({
217
- onRateLimit: (until) => this.events.log("warn", `${serverKey(url)} is rate limited until ${new Date(until).toISOString()}.`)
218
- });
219
- const api = new ExtendedBaseAPI(url, scheduler);
220
- const response = params.cookie ? await api.cookiesLogin(params.cookie) : await api.passportLogin(params.email ?? "", params.password ?? "");
221
- if (response.type !== "success" || !response.identity || !response.userInfo) {
222
- throw new Error(response.message || `Login to ${url} failed.`);
223
- }
224
- const session = {
225
- url,
226
- userId: response.userInfo.userId,
227
- userEmail: response.userInfo.userEmail || params.email || "",
228
- identity: response.identity,
229
- updatedAt: (/* @__PURE__ */ new Date()).toISOString()
230
- };
231
- await saveServerSession(session);
232
- this.servers.set(serverKey(url), { key: serverKey(url), session, scheduler, api });
233
- return { userId: session.userId, userEmail: session.userEmail };
234
- }
235
- async importSession(params) {
236
- const result = await this.login({ server: params.url, cookie: params.identity.cookies });
237
- await saveKnownServer(params.name, params.url);
238
- return result;
239
- }
240
- async logout(server2) {
241
- const runtime = await this.requireServer(server2);
242
- await runtime.api.logout(runtime.session.identity);
243
- await removeServerSession(server2);
244
- this.servers.delete(runtime.key);
245
- }
246
- async callServer(server2, operation, args) {
247
- if (!SERVER_OPERATIONS.has(operation)) {
248
- throw new Error(`Unsupported server operation: ${operation}.`);
249
- }
250
- const runtime = await this.requireServer(server2);
251
- const method = runtime.api[operation];
252
- if (typeof method !== "function") {
253
- throw new Error(`Server operation ${operation} is unavailable.`);
254
- }
255
- return method.call(runtime.api, runtime.session.identity, ...args);
256
- }
257
- async openProject(clientId, server2, projectId) {
258
- const runtime = await this.getOrCreateProject(server2, projectId);
259
- const shared = runtime.owners.size !== 0 || runtime.replicaReferences !== 0;
260
- runtime.owners.add(clientId);
261
- await runtime.ready;
262
- return { projectKey: runtime.key, shared };
263
- }
264
- closeProject(clientId, projectKey) {
265
- const runtime = this.requireProject(projectKey);
266
- runtime.owners.delete(clientId);
267
- this.scheduleProjectStop(runtime);
268
- }
269
- async callProject(projectKey, operation, args) {
270
- const runtime = this.requireProject(projectKey);
271
- await runtime.ready;
272
- if (operation.startsWith("remote.")) {
273
- const remoteOperation = operation.slice("remote.".length);
274
- if (!REMOTE_PROJECT_OPERATIONS.has(remoteOperation)) {
275
- throw new Error(`Unsupported remote project operation: ${remoteOperation}.`);
276
- }
277
- const method2 = runtime.remote[remoteOperation];
278
- if (typeof method2 !== "function") {
279
- throw new Error(`Remote project operation ${remoteOperation} is unavailable.`);
280
- }
281
- return this.enqueueProjectOperation(runtime, () => method2.apply(runtime.remote, args));
282
- }
283
- if (!PROJECT_OPERATIONS.has(operation)) {
284
- throw new Error(`Unsupported project operation: ${operation}.`);
285
- }
286
- const method = runtime.socket[operation];
287
- if (typeof method !== "function") {
288
- throw new Error(`Project operation ${operation} is unavailable.`);
289
- }
290
- return method.apply(runtime.socket, args);
291
- }
292
- async acquireReplica(server2, projectId) {
293
- const runtime = await this.getOrCreateProject(server2, projectId);
294
- runtime.replicaReferences += 1;
295
- await runtime.ready;
296
- let released = false;
297
- return {
298
- remote: this.replicaRemote(runtime),
299
- release: () => {
300
- if (released) {
301
- return;
302
- }
303
- released = true;
304
- runtime.replicaReferences -= 1;
305
- this.scheduleProjectStop(runtime);
306
- }
307
- };
308
- }
309
- detachClient(clientId) {
310
- for (const runtime of this.projects.values()) {
311
- if (runtime.owners.delete(clientId)) {
312
- this.scheduleProjectStop(runtime);
313
- }
314
- }
315
- }
316
- async stopAll() {
317
- await Promise.all([...this.projects.values()].map((runtime) => this.stopProject(runtime)));
318
- this.servers.clear();
319
- }
320
- async requireServer(server2) {
321
- const key = serverKey(server2);
322
- const existing = this.servers.get(key);
323
- if (existing) {
324
- return existing;
325
- }
326
- const session = await getServerSession(server2);
327
- if (!session) {
328
- throw new Error(`Not logged in to ${key}.`);
329
- }
330
- const scheduler = new HttpRequestScheduler({
331
- onRateLimit: (until) => this.events.log("warn", `${key} is rate limited until ${new Date(until).toISOString()}.`)
332
- });
333
- const runtime = { key, session, scheduler, api: new ExtendedBaseAPI(session.url, scheduler) };
334
- this.servers.set(key, runtime);
335
- return runtime;
336
- }
337
- async getOrCreateProject(server2, projectId) {
338
- const serverRuntime = await this.requireServer(server2);
339
- const key = `${serverRuntime.key}:${projectId}`;
340
- const existing = this.projects.get(key);
341
- if (existing) {
342
- return existing;
343
- }
344
- const socket = new SocketIOAPI(serverRuntime.session.url, serverRuntime.api, serverRuntime.session.identity, projectId);
345
- const remote = new RemoteProject(
346
- serverRuntime.session.url,
347
- projectId,
348
- serverRuntime.session.identity.cookies,
349
- { api: serverRuntime.api, identity: serverRuntime.session.identity, socket }
350
- );
351
- const runtime = {
352
- key,
353
- server: serverRuntime,
354
- projectId,
355
- socket,
356
- remote,
357
- ready: Promise.resolve(),
358
- owners: /* @__PURE__ */ new Set(),
359
- replicaReferences: 0,
360
- operationQueue: Promise.resolve()
361
- };
362
- runtime.ready = remote.connect().then(() => this.registerProjectEvents(runtime)).catch((error) => {
363
- this.projects.delete(key);
364
- socket.disconnect();
365
- throw error;
366
- });
367
- this.projects.set(key, runtime);
368
- return runtime;
369
- }
370
- registerProjectEvents(runtime) {
371
- const emit = (event, ...args) => this.events.projectEvent(runtime.owners, {
372
- projectKey: runtime.key,
373
- event,
374
- args
375
- });
376
- runtime.socket.updateEventHandlers({
377
- onFileCreated: (...args) => emit("onFileCreated", ...args),
378
- onFileRenamed: (...args) => emit("onFileRenamed", ...args),
379
- onFileRemoved: (...args) => emit("onFileRemoved", ...args),
380
- onFileMoved: (...args) => emit("onFileMoved", ...args),
381
- onFileChanged: (...args) => emit("onFileChanged", ...args),
382
- onDisconnected: (reason) => emit("onDisconnected", reason),
383
- onConnectionAccepted: (...args) => emit("onConnectionAccepted", ...args),
384
- onClientUpdated: (...args) => emit("onClientUpdated", ...args),
385
- onClientDisconnected: (...args) => emit("onClientDisconnected", ...args),
386
- onReceivedMessage: (...args) => emit("onReceivedMessage", ...args),
387
- onSpellCheckLanguageUpdated: (...args) => emit("onSpellCheckLanguageUpdated", ...args),
388
- onCompilerUpdated: (...args) => emit("onCompilerUpdated", ...args),
389
- onRootDocUpdated: (...args) => emit("onRootDocUpdated", ...args)
390
- });
391
- }
392
- requireProject(projectKey) {
393
- const runtime = this.projects.get(projectKey);
394
- if (!runtime) {
395
- throw new Error(`Unknown project runtime ${projectKey}.`);
396
- }
397
- return runtime;
398
- }
399
- replicaRemote(runtime) {
400
- return {
401
- connect: async () => {
402
- },
403
- disconnect: () => {
404
- },
405
- listEntries: () => runtime.remote.listEntries(),
406
- entry: (path) => runtime.remote.entry(path),
407
- read: (path) => this.enqueueProjectOperation(runtime, () => runtime.remote.read(path)),
408
- write: (path, content) => this.enqueueProjectOperation(runtime, () => runtime.remote.write(path, content)),
409
- remove: (path) => this.enqueueProjectOperation(runtime, () => runtime.remote.remove(path)),
410
- getCurrentVersion: () => this.enqueueProjectOperation(runtime, () => runtime.remote.getCurrentVersion()),
411
- getFileTreeDiff: (from, to) => this.enqueueProjectOperation(runtime, () => runtime.remote.getFileTreeDiff(from, to)),
412
- onChange: (handler) => runtime.remote.onChange(handler),
413
- onReconnect: (handler) => runtime.remote.onReconnect(handler)
414
- };
415
- }
416
- enqueueProjectOperation(runtime, operation) {
417
- const result = runtime.operationQueue.then(operation);
418
- runtime.operationQueue = result.then(() => void 0, () => void 0);
419
- return result;
420
- }
421
- scheduleProjectStop(runtime) {
422
- if (runtime.owners.size !== 0 || runtime.replicaReferences !== 0) {
423
- return;
424
- }
425
- void this.stopProject(runtime);
426
- }
427
- async stopProject(runtime) {
428
- if (!this.projects.delete(runtime.key)) {
429
- return;
430
- }
431
- runtime.socket.disconnect();
432
- }
138
+ events;
139
+ servers = /* @__PURE__ */ new Map();
140
+ projects = /* @__PURE__ */ new Map();
141
+ constructor(events) {
142
+ this.events = events;
143
+ }
144
+ get projectCount() {
145
+ return this.projects.size;
146
+ }
147
+ async listServers() {
148
+ const config = await readConfig();
149
+ const keys = /* @__PURE__ */ new Set([...Object.keys(config.knownServers ?? {}), ...Object.keys(config.servers)]);
150
+ if (keys.size === 0) keys.add("www.overleaf.com");
151
+ return [...keys].sort().map((key) => {
152
+ const session = config.servers[key];
153
+ const known = config.knownServers?.[key];
154
+ return {
155
+ name: known?.name ?? key,
156
+ url: known?.url ?? session?.url ?? normalizeServerUrl(key),
157
+ loggedIn: Boolean(session),
158
+ userId: session?.userId,
159
+ userEmail: session?.userEmail
160
+ };
161
+ });
162
+ }
163
+ async addServer(name, url) {
164
+ await saveKnownServer(name, url);
165
+ }
166
+ async removeServer(server) {
167
+ const key = serverKey(server);
168
+ for (const project of this.projects.values()) if (project.server.key === key) await this.stopProject(project);
169
+ this.servers.delete(key);
170
+ await removeKnownServer(server);
171
+ }
172
+ async login(params) {
173
+ const url = normalizeServerUrl(params.server);
174
+ const scheduler = new HttpRequestScheduler({ onRateLimit: (until) => this.events.log("warn", `${serverKey(url)} is rate limited until ${new Date(until).toISOString()}.`) });
175
+ const api = new ExtendedBaseAPI(url, scheduler);
176
+ const response = params.cookie ? await api.cookiesLogin(params.cookie) : await api.passportLogin(params.email ?? "", params.password ?? "");
177
+ if (response.type !== "success" || !response.identity || !response.userInfo) throw new Error(response.message || `Login to ${url} failed.`);
178
+ const session = {
179
+ url,
180
+ userId: response.userInfo.userId,
181
+ userEmail: response.userInfo.userEmail || params.email || "",
182
+ identity: response.identity,
183
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
184
+ };
185
+ await saveServerSession(session);
186
+ this.servers.set(serverKey(url), {
187
+ key: serverKey(url),
188
+ session,
189
+ scheduler,
190
+ api
191
+ });
192
+ return {
193
+ userId: session.userId,
194
+ userEmail: session.userEmail
195
+ };
196
+ }
197
+ async importSession(params) {
198
+ const result = await this.login({
199
+ server: params.url,
200
+ cookie: params.identity.cookies
201
+ });
202
+ await saveKnownServer(params.name, params.url);
203
+ return result;
204
+ }
205
+ async logout(server) {
206
+ const runtime = await this.requireServer(server);
207
+ await runtime.api.logout(runtime.session.identity);
208
+ await removeServerSession(server);
209
+ this.servers.delete(runtime.key);
210
+ }
211
+ async callServer(server, operation, args) {
212
+ if (!SERVER_OPERATIONS.has(operation)) throw new Error(`Unsupported server operation: ${operation}.`);
213
+ const runtime = await this.requireServer(server);
214
+ const method = runtime.api[operation];
215
+ if (typeof method !== "function") throw new Error(`Server operation ${operation} is unavailable.`);
216
+ return method.call(runtime.api, runtime.session.identity, ...args);
217
+ }
218
+ async openProject(clientId, server, projectId) {
219
+ const runtime = await this.getOrCreateProject(server, projectId);
220
+ const shared = runtime.owners.size !== 0 || runtime.replicaReferences !== 0;
221
+ runtime.owners.add(clientId);
222
+ await runtime.ready;
223
+ return {
224
+ projectKey: runtime.key,
225
+ shared
226
+ };
227
+ }
228
+ closeProject(clientId, projectKey) {
229
+ const runtime = this.requireProject(projectKey);
230
+ runtime.owners.delete(clientId);
231
+ this.scheduleProjectStop(runtime);
232
+ }
233
+ async callProject(projectKey, operation, args) {
234
+ const runtime = this.requireProject(projectKey);
235
+ await runtime.ready;
236
+ if (operation.startsWith("remote.")) {
237
+ const remoteOperation = operation.slice(7);
238
+ if (!REMOTE_PROJECT_OPERATIONS.has(remoteOperation)) throw new Error(`Unsupported remote project operation: ${remoteOperation}.`);
239
+ const method = runtime.remote[remoteOperation];
240
+ if (typeof method !== "function") throw new Error(`Remote project operation ${remoteOperation} is unavailable.`);
241
+ return this.enqueueProjectOperation(runtime, () => method.apply(runtime.remote, args));
242
+ }
243
+ if (!PROJECT_OPERATIONS.has(operation)) throw new Error(`Unsupported project operation: ${operation}.`);
244
+ const method = runtime.socket[operation];
245
+ if (typeof method !== "function") throw new Error(`Project operation ${operation} is unavailable.`);
246
+ return method.apply(runtime.socket, args);
247
+ }
248
+ async acquireReplica(server, projectId) {
249
+ const runtime = await this.getOrCreateProject(server, projectId);
250
+ runtime.replicaReferences += 1;
251
+ await runtime.ready;
252
+ let released = false;
253
+ return {
254
+ remote: this.replicaRemote(runtime),
255
+ release: () => {
256
+ if (released) return;
257
+ released = true;
258
+ runtime.replicaReferences -= 1;
259
+ this.scheduleProjectStop(runtime);
260
+ }
261
+ };
262
+ }
263
+ detachClient(clientId) {
264
+ for (const runtime of this.projects.values()) if (runtime.owners.delete(clientId)) this.scheduleProjectStop(runtime);
265
+ }
266
+ async stopAll() {
267
+ await Promise.all([...this.projects.values()].map((runtime) => this.stopProject(runtime)));
268
+ this.servers.clear();
269
+ }
270
+ async requireServer(server) {
271
+ const key = serverKey(server);
272
+ const existing = this.servers.get(key);
273
+ if (existing) return existing;
274
+ const session = await getServerSession(server);
275
+ if (!session) throw new Error(`Not logged in to ${key}.`);
276
+ const scheduler = new HttpRequestScheduler({ onRateLimit: (until) => this.events.log("warn", `${key} is rate limited until ${new Date(until).toISOString()}.`) });
277
+ const runtime = {
278
+ key,
279
+ session,
280
+ scheduler,
281
+ api: new ExtendedBaseAPI(session.url, scheduler)
282
+ };
283
+ this.servers.set(key, runtime);
284
+ return runtime;
285
+ }
286
+ async getOrCreateProject(server, projectId) {
287
+ const serverRuntime = await this.requireServer(server);
288
+ const key = `${serverRuntime.key}:${projectId}`;
289
+ const existing = this.projects.get(key);
290
+ if (existing) return existing;
291
+ const socket = new SocketIOAPI(serverRuntime.session.url, serverRuntime.api, serverRuntime.session.identity, projectId);
292
+ const remote = new RemoteProject(serverRuntime.session.url, projectId, serverRuntime.session.identity.cookies, {
293
+ api: serverRuntime.api,
294
+ identity: serverRuntime.session.identity,
295
+ socket
296
+ });
297
+ const runtime = {
298
+ key,
299
+ server: serverRuntime,
300
+ projectId,
301
+ socket,
302
+ remote,
303
+ ready: Promise.resolve(),
304
+ owners: /* @__PURE__ */ new Set(),
305
+ replicaReferences: 0,
306
+ operationQueue: Promise.resolve()
307
+ };
308
+ runtime.ready = remote.connect().then(() => this.registerProjectEvents(runtime)).catch((error) => {
309
+ this.projects.delete(key);
310
+ socket.disconnect();
311
+ throw error;
312
+ });
313
+ this.projects.set(key, runtime);
314
+ return runtime;
315
+ }
316
+ registerProjectEvents(runtime) {
317
+ const emit = (event, ...args) => this.events.projectEvent(runtime.owners, {
318
+ projectKey: runtime.key,
319
+ event,
320
+ args
321
+ });
322
+ runtime.socket.updateEventHandlers({
323
+ onFileCreated: (...args) => emit("onFileCreated", ...args),
324
+ onFileRenamed: (...args) => emit("onFileRenamed", ...args),
325
+ onFileRemoved: (...args) => emit("onFileRemoved", ...args),
326
+ onFileMoved: (...args) => emit("onFileMoved", ...args),
327
+ onFileChanged: (...args) => emit("onFileChanged", ...args),
328
+ onDisconnected: (reason) => emit("onDisconnected", reason),
329
+ onConnectionAccepted: (...args) => emit("onConnectionAccepted", ...args),
330
+ onClientUpdated: (...args) => emit("onClientUpdated", ...args),
331
+ onClientDisconnected: (...args) => emit("onClientDisconnected", ...args),
332
+ onReceivedMessage: (...args) => emit("onReceivedMessage", ...args),
333
+ onSpellCheckLanguageUpdated: (...args) => emit("onSpellCheckLanguageUpdated", ...args),
334
+ onCompilerUpdated: (...args) => emit("onCompilerUpdated", ...args),
335
+ onRootDocUpdated: (...args) => emit("onRootDocUpdated", ...args)
336
+ });
337
+ }
338
+ requireProject(projectKey) {
339
+ const runtime = this.projects.get(projectKey);
340
+ if (!runtime) throw new Error(`Unknown project runtime ${projectKey}.`);
341
+ return runtime;
342
+ }
343
+ replicaRemote(runtime) {
344
+ return {
345
+ connect: async () => {},
346
+ disconnect: () => {},
347
+ listEntries: () => runtime.remote.listEntries(),
348
+ entry: (path) => runtime.remote.entry(path),
349
+ read: (path) => this.enqueueProjectOperation(runtime, () => runtime.remote.read(path)),
350
+ write: (path, content) => this.enqueueProjectOperation(runtime, () => runtime.remote.write(path, content)),
351
+ remove: (path) => this.enqueueProjectOperation(runtime, () => runtime.remote.remove(path)),
352
+ getCurrentVersion: () => this.enqueueProjectOperation(runtime, () => runtime.remote.getCurrentVersion()),
353
+ getFileTreeDiff: (from, to) => this.enqueueProjectOperation(runtime, () => runtime.remote.getFileTreeDiff(from, to)),
354
+ onChange: (handler) => runtime.remote.onChange(handler),
355
+ onReconnect: (handler) => runtime.remote.onReconnect(handler)
356
+ };
357
+ }
358
+ enqueueProjectOperation(runtime, operation) {
359
+ const result = runtime.operationQueue.then(operation);
360
+ runtime.operationQueue = result.then(() => void 0, () => void 0);
361
+ return result;
362
+ }
363
+ scheduleProjectStop(runtime) {
364
+ if (runtime.owners.size !== 0 || runtime.replicaReferences !== 0) return;
365
+ this.stopProject(runtime);
366
+ }
367
+ async stopProject(runtime) {
368
+ if (!this.projects.delete(runtime.key)) return;
369
+ runtime.socket.disconnect();
370
+ }
433
371
  };
434
-
435
372
  // ../daemon/src/replicaRegistry.ts
436
- import { randomUUID } from "crypto";
437
- import { realpath } from "fs/promises";
438
- import { resolve as resolve2 } from "path";
439
373
  var ReplicaAlreadyActiveError = class extends Error {
440
- constructor(projectId, activeRoot, requestedRoot) {
441
- super(`Overleaf project ${projectId} is already synchronized by ${activeRoot}; ${requestedRoot} cannot become a second writable replica.`);
442
- this.projectId = projectId;
443
- this.activeRoot = activeRoot;
444
- this.requestedRoot = requestedRoot;
445
- }
446
- projectId;
447
- activeRoot;
448
- requestedRoot;
449
- code = "ReplicaAlreadyActive";
374
+ projectId;
375
+ activeRoot;
376
+ requestedRoot;
377
+ code = "ReplicaAlreadyActive";
378
+ constructor(projectId, activeRoot, requestedRoot) {
379
+ super(`Overleaf project ${projectId} is already synchronized by ${activeRoot}; ${requestedRoot} cannot become a second writable replica.`);
380
+ this.projectId = projectId;
381
+ this.activeRoot = activeRoot;
382
+ this.requestedRoot = requestedRoot;
383
+ }
450
384
  };
451
385
  var ReplicaRegistry = class {
452
- constructor(events, start = startServe) {
453
- this.events = events;
454
- this.start = start;
455
- }
456
- events;
457
- start;
458
- byId = /* @__PURE__ */ new Map();
459
- byRoot = /* @__PURE__ */ new Map();
460
- byProject = /* @__PURE__ */ new Map();
461
- projectOperations = /* @__PURE__ */ new Map();
462
- clients = /* @__PURE__ */ new Set();
463
- get size() {
464
- return this.byId.size;
465
- }
466
- registerClient(clientId) {
467
- this.clients.add(clientId);
468
- }
469
- async attach(clientId, params) {
470
- const root = await realpath(resolve2(params.directory));
471
- const settings = await readProjectSettings(root);
472
- const projectKey = `${settings.serverName}\0${settings.projectId}`;
473
- return this.withProjectLock(projectKey, () => this.attachResolved(clientId, params, root, settings, projectKey));
474
- }
475
- async attachResolved(clientId, params, root, settings, projectKey) {
476
- if (!this.clients.has(clientId)) {
477
- throw new Error("The replica client disconnected before attachment started.");
478
- }
479
- const rootEntry = this.byRoot.get(root);
480
- if (rootEntry) {
481
- if (rootEntry.projectKey !== projectKey) {
482
- throw new Error(`${root} is already registered for another Overleaf project.`);
483
- }
484
- this.addOwner(rootEntry, clientId);
485
- return this.result(rootEntry, true);
486
- }
487
- const projectEntry = this.byProject.get(projectKey);
488
- if (projectEntry) {
489
- throw new ReplicaAlreadyActiveError(settings.projectId, projectEntry.root, root);
490
- }
491
- const id = randomUUID();
492
- const owners = /* @__PURE__ */ new Set([clientId]);
493
- const status = { state: "starting" };
494
- let entry;
495
- this.events.status(owners, { replicaId: id, status });
496
- this.events.log(`[${settings.projectName}] Starting synchronization for ${root}.`);
497
- try {
498
- const running = await this.start(root, {
499
- cookie: params.cookie,
500
- onSyncError: (message) => {
501
- if (!entry) {
502
- return;
503
- }
504
- entry.status = message ? { state: "error", message } : entry.running.conflicts().length ? { state: "paused" } : { state: "active" };
505
- this.events.status(entry.owners, { replicaId: id, status: entry.status });
506
- },
507
- log: (message) => this.events.log(`[${settings.projectName}] ${message}`),
508
- onConflict: (path, reason) => {
509
- if (!entry) {
510
- return;
511
- }
512
- entry.status = { state: "paused", message: `Conflict in ${path}` };
513
- this.events.conflict(entry.owners, {
514
- replicaId: entry.id,
515
- path,
516
- reason,
517
- conflicts: entry.running.conflicts()
518
- });
519
- this.events.status(entry.owners, { replicaId: entry.id, status: entry.status });
520
- }
521
- });
522
- if (!this.clients.has(clientId)) {
523
- await running.stop();
524
- this.events.empty();
525
- throw new Error("The replica client disconnected before attachment completed.");
526
- }
527
- entry = {
528
- id,
529
- root,
530
- projectKey,
531
- serverName: settings.serverName,
532
- projectId: settings.projectId,
533
- projectName: settings.projectName,
534
- owners,
535
- running,
536
- status: running.syncError() ? { state: "error", message: running.syncError() } : running.conflicts().length === 0 ? { state: "active" } : { state: "paused" }
537
- };
538
- this.byId.set(id, entry);
539
- this.byRoot.set(root, entry);
540
- this.byProject.set(projectKey, entry);
541
- this.events.status(owners, { replicaId: id, status: entry.status });
542
- return this.result(entry, false);
543
- } catch (error) {
544
- const failed = { state: "error", message: error instanceof Error ? error.message : String(error) };
545
- this.events.status(owners, { replicaId: id, status: failed });
546
- throw error;
547
- }
548
- }
549
- async detach(clientId, replicaId) {
550
- const entry = this.require(replicaId);
551
- await this.withProjectLock(entry.projectKey, async () => {
552
- entry.owners.delete(clientId);
553
- if (entry.owners.size === 0) {
554
- await this.stop(entry);
555
- }
556
- });
557
- }
558
- async detachClient(clientId) {
559
- this.clients.delete(clientId);
560
- const owned = [...this.byId.values()].filter((entry) => entry.owners.has(clientId));
561
- await Promise.all(owned.map((entry) => this.withProjectLock(entry.projectKey, async () => {
562
- entry.owners.delete(clientId);
563
- if (entry.owners.size === 0) {
564
- await this.stop(entry);
565
- }
566
- })));
567
- }
568
- async resolveConflict(replicaId, path, winner) {
569
- const entry = this.require(replicaId);
570
- await entry.running.resolveConflict(path, winner);
571
- entry.status = entry.running.syncError() ? { state: "error", message: entry.running.syncError() } : entry.running.conflicts().length === 0 ? { state: "active" } : { state: "paused" };
572
- this.events.status(entry.owners, { replicaId, status: entry.status });
573
- }
574
- async retry(replicaId, path) {
575
- const entry = this.require(replicaId);
576
- await entry.running.retry(path);
577
- entry.status = entry.running.syncError() ? { state: "error", message: entry.running.syncError() } : entry.running.conflicts().length === 0 ? { state: "active" } : { state: "paused" };
578
- this.events.status(entry.owners, { replicaId, status: entry.status });
579
- }
580
- list() {
581
- return [...this.byId.values()].map((entry) => ({
582
- id: entry.id,
583
- root: entry.root,
584
- serverName: entry.serverName,
585
- projectId: entry.projectId,
586
- projectName: entry.projectName,
587
- clients: entry.owners.size,
588
- status: entry.status,
589
- conflicts: entry.running.conflicts()
590
- }));
591
- }
592
- async stopAll() {
593
- await Promise.all([...this.byId.values()].map((entry) => this.stop(entry)));
594
- }
595
- addOwner(entry, clientId) {
596
- entry.owners.add(clientId);
597
- }
598
- async stop(entry) {
599
- if (!this.byId.delete(entry.id)) {
600
- return;
601
- }
602
- this.byRoot.delete(entry.root);
603
- this.byProject.delete(entry.projectKey);
604
- entry.status = { state: "stopping" };
605
- this.events.status(entry.owners, { replicaId: entry.id, status: entry.status });
606
- await entry.running.stop();
607
- this.events.empty();
608
- }
609
- require(replicaId) {
610
- const entry = this.byId.get(replicaId);
611
- if (!entry) {
612
- throw new Error(`Unknown replica ${replicaId}.`);
613
- }
614
- return entry;
615
- }
616
- result(entry, shared) {
617
- return {
618
- replicaId: entry.id,
619
- root: entry.root,
620
- serverName: entry.serverName,
621
- projectId: entry.projectId,
622
- projectName: entry.projectName,
623
- shared,
624
- status: entry.status,
625
- conflicts: entry.running.conflicts()
626
- };
627
- }
628
- async withProjectLock(projectKey, operation) {
629
- const previous = this.projectOperations.get(projectKey) ?? Promise.resolve();
630
- let release;
631
- const current = new Promise((resolveOperation) => {
632
- release = resolveOperation;
633
- });
634
- this.projectOperations.set(projectKey, current);
635
- await previous;
636
- try {
637
- return await operation();
638
- } finally {
639
- release();
640
- if (this.projectOperations.get(projectKey) === current) {
641
- this.projectOperations.delete(projectKey);
642
- }
643
- }
644
- }
386
+ events;
387
+ start;
388
+ byId = /* @__PURE__ */ new Map();
389
+ byRoot = /* @__PURE__ */ new Map();
390
+ byProject = /* @__PURE__ */ new Map();
391
+ projectOperations = /* @__PURE__ */ new Map();
392
+ clients = /* @__PURE__ */ new Set();
393
+ constructor(events, start = startServe) {
394
+ this.events = events;
395
+ this.start = start;
396
+ }
397
+ get size() {
398
+ return this.byId.size;
399
+ }
400
+ registerClient(clientId) {
401
+ this.clients.add(clientId);
402
+ }
403
+ async attach(clientId, params) {
404
+ const root = await realpath(resolve(params.directory));
405
+ const settings = await readProjectSettings(root);
406
+ const projectKey = `${settings.serverName}\0${settings.projectId}`;
407
+ return this.withProjectLock(projectKey, () => this.attachResolved(clientId, params, root, settings, projectKey));
408
+ }
409
+ async attachResolved(clientId, params, root, settings, projectKey) {
410
+ if (!this.clients.has(clientId)) throw new Error("The replica client disconnected before attachment started.");
411
+ const rootEntry = this.byRoot.get(root);
412
+ if (rootEntry) {
413
+ if (rootEntry.projectKey !== projectKey) throw new Error(`${root} is already registered for another Overleaf project.`);
414
+ this.addOwner(rootEntry, clientId);
415
+ return this.result(rootEntry, true);
416
+ }
417
+ const projectEntry = this.byProject.get(projectKey);
418
+ if (projectEntry) throw new ReplicaAlreadyActiveError(settings.projectId, projectEntry.root, root);
419
+ const id = randomUUID();
420
+ const owners = /* @__PURE__ */ new Set([clientId]);
421
+ const status = { state: "starting" };
422
+ let entry;
423
+ this.events.status(owners, {
424
+ replicaId: id,
425
+ status
426
+ });
427
+ this.events.log(`[${settings.projectName}] Starting synchronization for ${root}.`);
428
+ try {
429
+ const running = await this.start(root, {
430
+ cookie: params.cookie,
431
+ onSyncError: (message) => {
432
+ if (!entry) return;
433
+ entry.status = message ? {
434
+ state: "error",
435
+ message
436
+ } : entry.running.conflicts().length ? { state: "paused" } : { state: "active" };
437
+ this.events.status(entry.owners, {
438
+ replicaId: id,
439
+ status: entry.status
440
+ });
441
+ },
442
+ log: (message) => this.events.log(`[${settings.projectName}] ${message}`),
443
+ onConflict: (path, reason) => {
444
+ if (!entry) return;
445
+ entry.status = {
446
+ state: "paused",
447
+ message: `Conflict in ${path}`
448
+ };
449
+ this.events.conflict(entry.owners, {
450
+ replicaId: entry.id,
451
+ path,
452
+ reason,
453
+ conflicts: entry.running.conflicts()
454
+ });
455
+ this.events.status(entry.owners, {
456
+ replicaId: entry.id,
457
+ status: entry.status
458
+ });
459
+ }
460
+ });
461
+ if (!this.clients.has(clientId)) {
462
+ await running.stop();
463
+ this.events.empty();
464
+ throw new Error("The replica client disconnected before attachment completed.");
465
+ }
466
+ entry = {
467
+ id,
468
+ root,
469
+ projectKey,
470
+ serverName: settings.serverName,
471
+ projectId: settings.projectId,
472
+ projectName: settings.projectName,
473
+ owners,
474
+ running,
475
+ status: running.syncError() ? {
476
+ state: "error",
477
+ message: running.syncError()
478
+ } : running.conflicts().length === 0 ? { state: "active" } : { state: "paused" }
479
+ };
480
+ this.byId.set(id, entry);
481
+ this.byRoot.set(root, entry);
482
+ this.byProject.set(projectKey, entry);
483
+ this.events.status(owners, {
484
+ replicaId: id,
485
+ status: entry.status
486
+ });
487
+ return this.result(entry, false);
488
+ } catch (error) {
489
+ const failed = {
490
+ state: "error",
491
+ message: error instanceof Error ? error.message : String(error)
492
+ };
493
+ this.events.status(owners, {
494
+ replicaId: id,
495
+ status: failed
496
+ });
497
+ throw error;
498
+ }
499
+ }
500
+ async detach(clientId, replicaId) {
501
+ const entry = this.require(replicaId);
502
+ await this.withProjectLock(entry.projectKey, async () => {
503
+ entry.owners.delete(clientId);
504
+ if (entry.owners.size === 0) await this.stop(entry);
505
+ });
506
+ }
507
+ async detachClient(clientId) {
508
+ this.clients.delete(clientId);
509
+ const owned = [...this.byId.values()].filter((entry) => entry.owners.has(clientId));
510
+ await Promise.all(owned.map((entry) => this.withProjectLock(entry.projectKey, async () => {
511
+ entry.owners.delete(clientId);
512
+ if (entry.owners.size === 0) await this.stop(entry);
513
+ })));
514
+ }
515
+ async resolveConflict(replicaId, path, winner) {
516
+ const entry = this.require(replicaId);
517
+ await entry.running.resolveConflict(path, winner);
518
+ entry.status = entry.running.syncError() ? {
519
+ state: "error",
520
+ message: entry.running.syncError()
521
+ } : entry.running.conflicts().length === 0 ? { state: "active" } : { state: "paused" };
522
+ this.events.status(entry.owners, {
523
+ replicaId,
524
+ status: entry.status
525
+ });
526
+ }
527
+ async retry(replicaId, path) {
528
+ const entry = this.require(replicaId);
529
+ await entry.running.retry(path);
530
+ entry.status = entry.running.syncError() ? {
531
+ state: "error",
532
+ message: entry.running.syncError()
533
+ } : entry.running.conflicts().length === 0 ? { state: "active" } : { state: "paused" };
534
+ this.events.status(entry.owners, {
535
+ replicaId,
536
+ status: entry.status
537
+ });
538
+ }
539
+ list() {
540
+ return [...this.byId.values()].map((entry) => ({
541
+ id: entry.id,
542
+ root: entry.root,
543
+ serverName: entry.serverName,
544
+ projectId: entry.projectId,
545
+ projectName: entry.projectName,
546
+ clients: entry.owners.size,
547
+ status: entry.status,
548
+ conflicts: entry.running.conflicts()
549
+ }));
550
+ }
551
+ async stopAll() {
552
+ await Promise.all([...this.byId.values()].map((entry) => this.stop(entry)));
553
+ }
554
+ addOwner(entry, clientId) {
555
+ entry.owners.add(clientId);
556
+ }
557
+ async stop(entry) {
558
+ if (!this.byId.delete(entry.id)) return;
559
+ this.byRoot.delete(entry.root);
560
+ this.byProject.delete(entry.projectKey);
561
+ entry.status = { state: "stopping" };
562
+ this.events.status(entry.owners, {
563
+ replicaId: entry.id,
564
+ status: entry.status
565
+ });
566
+ await entry.running.stop();
567
+ this.events.empty();
568
+ }
569
+ require(replicaId) {
570
+ const entry = this.byId.get(replicaId);
571
+ if (!entry) throw new Error(`Unknown replica ${replicaId}.`);
572
+ return entry;
573
+ }
574
+ result(entry, shared) {
575
+ return {
576
+ replicaId: entry.id,
577
+ root: entry.root,
578
+ serverName: entry.serverName,
579
+ projectId: entry.projectId,
580
+ projectName: entry.projectName,
581
+ shared,
582
+ status: entry.status,
583
+ conflicts: entry.running.conflicts()
584
+ };
585
+ }
586
+ async withProjectLock(projectKey, operation) {
587
+ const previous = this.projectOperations.get(projectKey) ?? Promise.resolve();
588
+ let release;
589
+ const current = new Promise((resolveOperation) => {
590
+ release = resolveOperation;
591
+ });
592
+ this.projectOperations.set(projectKey, current);
593
+ await previous;
594
+ try {
595
+ return await operation();
596
+ } finally {
597
+ release();
598
+ if (this.projectOperations.get(projectKey) === current) this.projectOperations.delete(projectKey);
599
+ }
600
+ }
645
601
  };
646
-
647
602
  // ../daemon/src/transport.ts
648
- import {
649
- createMessageConnection,
650
- SocketMessageReader,
651
- SocketMessageWriter
652
- } from "vscode-jsonrpc/node";
653
- var CLOSED_SOCKET_ERRORS = /* @__PURE__ */ new Set([
654
- "EPIPE",
655
- "ECONNRESET",
656
- "ERR_SOCKET_CLOSED",
657
- "ERR_STREAM_DESTROYED",
658
- "ERR_STREAM_WRITE_AFTER_END"
603
+ const CLOSED_SOCKET_ERRORS = /* @__PURE__ */ new Set([
604
+ "EPIPE",
605
+ "ECONNRESET",
606
+ "ERR_SOCKET_CLOSED",
607
+ "ERR_STREAM_DESTROYED",
608
+ "ERR_STREAM_WRITE_AFTER_END"
659
609
  ]);
660
610
  var LeafRelaySocketWriter = class extends SocketMessageWriter {
661
- constructor(transportSocket) {
662
- super(transportSocket);
663
- this.transportSocket = transportSocket;
664
- }
665
- transportSocket;
666
- async write(message) {
667
- try {
668
- await super.write(message);
669
- } catch (error) {
670
- const code = error.code;
671
- if (this.transportSocket.destroyed || this.transportSocket.writableEnded || code && CLOSED_SOCKET_ERRORS.has(code)) {
672
- return;
673
- }
674
- throw error;
675
- }
676
- }
611
+ transportSocket;
612
+ constructor(transportSocket) {
613
+ super(transportSocket);
614
+ this.transportSocket = transportSocket;
615
+ }
616
+ async write(message) {
617
+ try {
618
+ await super.write(message);
619
+ } catch (error) {
620
+ const code = error.code;
621
+ if (this.transportSocket.destroyed || this.transportSocket.writableEnded || code && CLOSED_SOCKET_ERRORS.has(code)) return;
622
+ throw error;
623
+ }
624
+ }
677
625
  };
678
626
  function createSocketRpcConnection(socket) {
679
- return createMessageConnection(new SocketMessageReader(socket), new LeafRelaySocketWriter(socket));
627
+ return createMessageConnection(new SocketMessageReader(socket), new LeafRelaySocketWriter(socket));
680
628
  }
681
-
682
629
  // ../daemon/src/server.ts
683
- var IDLE_EXIT_MS = 6e4;
684
- var REPLICA_ALREADY_ACTIVE = -32010;
685
- var daemonVersion = true ? "0.2.7" : "development";
630
+ const IDLE_EXIT_MS = 6e4;
631
+ const REPLICA_ALREADY_ACTIVE = -32010;
632
+ const daemonVersion = "0.2.9";
686
633
  var LeafRelayDaemonServer = class {
687
- constructor(options = {}) {
688
- this.options = options;
689
- this.paths = options.paths ?? daemonPaths();
690
- this.token = options.token ?? randomBytes(32).toString("hex");
691
- this.network = new NetworkRuntimeRegistry({
692
- projectEvent: (owners, notification) => this.notifyOwners(owners, RPC_NOTIFICATION.projectEvent, notification),
693
- log: (level, message) => void this.log(level, message)
694
- });
695
- this.replicas = new ReplicaRegistry({
696
- status: (owners, notification) => this.notifyOwners(owners, RPC_NOTIFICATION.replicaStatus, notification),
697
- conflict: (owners, notification) => this.notifyOwners(owners, RPC_NOTIFICATION.replicaConflict, notification),
698
- empty: () => this.scheduleIdleExit(),
699
- log: (message) => void this.log("info", message)
700
- }, async (directory, startOptions) => {
701
- const settings = await readProjectSettings(directory);
702
- const lease = await this.network.acquireReplica(settings.serverName, settings.projectId);
703
- try {
704
- const running = await startServe(directory, { ...startOptions, remote: lease.remote });
705
- return {
706
- ...running,
707
- stop: async () => {
708
- await running.stop();
709
- lease.release();
710
- }
711
- };
712
- } catch (error) {
713
- lease.release();
714
- throw error;
715
- }
716
- });
717
- }
718
- options;
719
- paths;
720
- token;
721
- startedAt = (/* @__PURE__ */ new Date()).toISOString();
722
- clients = /* @__PURE__ */ new Set();
723
- network;
724
- replicas;
725
- server;
726
- idleTimer;
727
- stopping;
728
- async start() {
729
- await mkdir(this.paths.home, { recursive: true, mode: 448 });
730
- setLogSink((level, args) => void this.log(level, formatWithOptions({ depth: 5, breakLength: Infinity }, ...args)));
731
- if (process.platform !== "win32") {
732
- await rm(this.paths.socketPath, { force: true });
733
- }
734
- this.server = createServer((socket) => this.accept(socket));
735
- await new Promise((resolveListen, reject) => {
736
- this.server.once("error", reject);
737
- this.server.listen(this.paths.socketPath, () => {
738
- this.server.off("error", reject);
739
- resolveListen();
740
- });
741
- });
742
- if (process.platform !== "win32") {
743
- await chmod(this.paths.socketPath, 384);
744
- }
745
- const metadata = {
746
- pid: process.pid,
747
- socketPath: this.paths.socketPath,
748
- token: this.token,
749
- protocolVersion: LEAFRELAY_PROTOCOL_VERSION,
750
- version: daemonVersion,
751
- startedAt: this.startedAt
752
- };
753
- await writeFile(this.paths.metadataPath, `${JSON.stringify(metadata, null, 2)}
754
- `, { encoding: "utf8", mode: 384 });
755
- await chmod(this.paths.metadataPath, 384);
756
- await this.log("info", `Daemon ${daemonVersion} listening on ${this.paths.socketPath}.`);
757
- this.scheduleIdleExit();
758
- return metadata;
759
- }
760
- async stop() {
761
- if (this.stopping) {
762
- return this.stopping;
763
- }
764
- this.stopping = this.performStop();
765
- return this.stopping;
766
- }
767
- status() {
768
- return {
769
- pid: process.pid,
770
- version: daemonVersion,
771
- protocolVersion: LEAFRELAY_PROTOCOL_VERSION,
772
- startedAt: this.startedAt,
773
- clients: this.clients.size,
774
- projects: this.network.projectCount,
775
- replicas: this.replicas.list()
776
- };
777
- }
778
- accept(socket) {
779
- this.cancelIdleExit();
780
- const rpc = createSocketRpcConnection(socket);
781
- const client = { leaseId: randomUUID2(), socket, rpc, initialized: false };
782
- this.clients.add(client);
783
- rpc.onRequest(RPC_METHOD.initialize, (params) => this.initialize(client, params));
784
- rpc.onRequest(RPC_METHOD.daemonStatus, () => this.authorized(client, () => this.status()));
785
- rpc.onRequest(RPC_METHOD.daemonShutdown, () => this.authorized(client, async () => {
786
- setTimeout(() => void this.stop(), 25);
787
- return null;
788
- }));
789
- rpc.onRequest(RPC_METHOD.replicaAttach, (params) => this.authorized(client, async () => {
790
- try {
791
- return await this.replicas.attach(client.leaseId, params);
792
- } catch (error) {
793
- if (error instanceof ReplicaAlreadyActiveError) {
794
- throw new ResponseError(REPLICA_ALREADY_ACTIVE, error.message, {
795
- code: error.code,
796
- projectId: error.projectId,
797
- activeRoot: error.activeRoot,
798
- requestedRoot: error.requestedRoot
799
- });
800
- }
801
- throw error;
802
- }
803
- }));
804
- rpc.onRequest(RPC_METHOD.replicaDetach, (params) => this.authorized(client, async () => {
805
- await this.replicas.detach(client.leaseId, params.replicaId);
806
- return null;
807
- }));
808
- rpc.onRequest(RPC_METHOD.replicaResolveConflict, (params) => this.authorized(client, async () => {
809
- await this.replicas.resolveConflict(params.replicaId, params.path, params.winner);
810
- return null;
811
- }));
812
- rpc.onRequest(RPC_METHOD.replicaRetry, (params) => this.authorized(client, async () => {
813
- await this.replicas.retry(params.replicaId, params.path);
814
- return null;
815
- }));
816
- rpc.onRequest(RPC_METHOD.serverList, () => this.authorized(client, () => this.network.listServers()));
817
- rpc.onRequest(RPC_METHOD.serverAdd, (params) => this.authorized(client, async () => {
818
- await this.network.addServer(params.name, params.url);
819
- return null;
820
- }));
821
- rpc.onRequest(RPC_METHOD.serverRemove, (params) => this.authorized(client, async () => {
822
- await this.network.removeServer(params.server);
823
- return null;
824
- }));
825
- rpc.onRequest(RPC_METHOD.sessionLogin, (params) => this.authorized(client, () => this.network.login(params)));
826
- rpc.onRequest(RPC_METHOD.sessionImport, (params) => this.authorized(client, () => this.network.importSession(params)));
827
- rpc.onRequest(RPC_METHOD.sessionLogout, (params) => this.authorized(client, async () => {
828
- await this.network.logout(params.server);
829
- return null;
830
- }));
831
- rpc.onRequest(RPC_METHOD.serverCall, (params) => this.authorized(client, async () => {
832
- const result = await this.network.callServer(params.server, params.operation, decodeRpcValue(params.args));
833
- return encodeRpcValue(result);
834
- }));
835
- rpc.onRequest(RPC_METHOD.projectOpen, (params) => this.authorized(client, () => this.network.openProject(client.leaseId, params.server, params.projectId)));
836
- rpc.onRequest(RPC_METHOD.projectClose, (params) => this.authorized(client, () => {
837
- this.network.closeProject(client.leaseId, params.projectKey);
838
- return null;
839
- }));
840
- rpc.onRequest(RPC_METHOD.projectCall, (params) => this.authorized(client, async () => {
841
- const result = await this.network.callProject(params.projectKey, params.operation, decodeRpcValue(params.args));
842
- return encodeRpcValue(await result);
843
- }));
844
- rpc.onClose(() => void this.closeClient(client));
845
- rpc.onError((error) => void this.log("error", `JSON-RPC connection error: ${String(error[0])}`));
846
- rpc.listen();
847
- }
848
- initialize(client, params) {
849
- if (params.token !== this.token) {
850
- throw new ResponseError(-32001, "Daemon authentication failed.");
851
- }
852
- if (params.protocolVersion !== LEAFRELAY_PROTOCOL_VERSION) {
853
- throw new ResponseError(-32002, `Protocol ${params.protocolVersion} is incompatible with daemon protocol ${LEAFRELAY_PROTOCOL_VERSION}.`);
854
- }
855
- if (!params.clientId) {
856
- throw new ResponseError(-32602, "clientId is required.");
857
- }
858
- client.clientId = params.clientId;
859
- client.initialized = true;
860
- this.replicas.registerClient(client.leaseId);
861
- void this.log("info", `${params.clientName} ${params.clientVersion} connected (${params.clientId}).`);
862
- return {
863
- daemonVersion,
864
- protocolVersion: LEAFRELAY_PROTOCOL_VERSION,
865
- pid: process.pid,
866
- startedAt: this.startedAt
867
- };
868
- }
869
- async authorized(client, operation) {
870
- if (!client.initialized) {
871
- throw new ResponseError(-32001, "Initialize the daemon connection first.");
872
- }
873
- try {
874
- return await operation();
875
- } catch (error) {
876
- if (error instanceof ResponseError) {
877
- throw error;
878
- }
879
- const message = error instanceof Error ? error.message : String(error);
880
- await this.log("error", `RPC operation failed: ${formatWithOptions({ depth: 5, breakLength: Infinity }, error)}`);
881
- throw new ResponseError(-32603, message);
882
- }
883
- }
884
- async closeClient(client) {
885
- if (!this.clients.delete(client)) {
886
- return;
887
- }
888
- if (client.clientId) {
889
- try {
890
- await this.replicas.detachClient(client.leaseId);
891
- } catch (error) {
892
- await this.log("error", `Failed to stop replicas for a disconnected client: ${error instanceof Error ? error.message : String(error)}`);
893
- } finally {
894
- this.network.detachClient(client.leaseId);
895
- }
896
- }
897
- this.scheduleIdleExit();
898
- }
899
- notifyOwners(owners, method, notification) {
900
- for (const client of this.clients) {
901
- if (owners.has(client.leaseId)) {
902
- this.notifyClient(client, method, notification);
903
- }
904
- }
905
- }
906
- async log(level, message) {
907
- const notification = { timestamp: (/* @__PURE__ */ new Date()).toISOString(), level, message };
908
- await appendFile(this.paths.logPath, `${notification.timestamp} [${level}] ${message}
909
- `, { encoding: "utf8", mode: 384 });
910
- for (const client of this.clients) {
911
- if (client.initialized) {
912
- this.notifyClient(client, RPC_NOTIFICATION.log, notification);
913
- }
914
- }
915
- }
916
- notifyClient(client, method, notification) {
917
- if (!this.clients.has(client) || client.socket.destroyed) {
918
- return;
919
- }
920
- void client.rpc.sendNotification(method, notification).catch(() => this.closeClient(client));
921
- }
922
- scheduleIdleExit() {
923
- if (this.options.exitOnIdle === false || this.clients.size !== 0 || this.replicas.size !== 0 || this.idleTimer) {
924
- return;
925
- }
926
- this.idleTimer = setTimeout(() => void this.stop(), IDLE_EXIT_MS);
927
- this.idleTimer.unref();
928
- }
929
- cancelIdleExit() {
930
- if (this.idleTimer) {
931
- clearTimeout(this.idleTimer);
932
- this.idleTimer = void 0;
933
- }
934
- }
935
- async performStop() {
936
- this.cancelIdleExit();
937
- await this.replicas.stopAll();
938
- await this.network.stopAll();
939
- setLogSink(void 0);
940
- for (const client of this.clients) {
941
- client.rpc.dispose();
942
- client.socket.destroy();
943
- }
944
- this.clients.clear();
945
- if (this.server) {
946
- await new Promise((resolveClose) => this.server.close(() => resolveClose()));
947
- }
948
- await rm(this.paths.metadataPath, { force: true });
949
- if (process.platform !== "win32") {
950
- await rm(this.paths.socketPath, { force: true });
951
- }
952
- }
634
+ options;
635
+ paths;
636
+ token;
637
+ startedAt = (/* @__PURE__ */ new Date()).toISOString();
638
+ clients = /* @__PURE__ */ new Set();
639
+ network;
640
+ replicas;
641
+ server;
642
+ idleTimer;
643
+ stopping;
644
+ constructor(options = {}) {
645
+ this.options = options;
646
+ this.paths = options.paths ?? daemonPaths();
647
+ this.token = options.token ?? randomBytes(32).toString("hex");
648
+ this.network = new NetworkRuntimeRegistry({
649
+ projectEvent: (owners, notification) => this.notifyOwners(owners, RPC_NOTIFICATION.projectEvent, notification),
650
+ log: (level, message) => void this.log(level, message)
651
+ });
652
+ this.replicas = new ReplicaRegistry({
653
+ status: (owners, notification) => this.notifyOwners(owners, RPC_NOTIFICATION.replicaStatus, notification),
654
+ conflict: (owners, notification) => this.notifyOwners(owners, RPC_NOTIFICATION.replicaConflict, notification),
655
+ empty: () => this.scheduleIdleExit(),
656
+ log: (message) => void this.log("info", message)
657
+ }, async (directory, startOptions) => {
658
+ const settings = await readProjectSettings(directory);
659
+ const lease = await this.network.acquireReplica(settings.serverName, settings.projectId);
660
+ try {
661
+ const running = await startServe(directory, {
662
+ ...startOptions,
663
+ remote: lease.remote
664
+ });
665
+ return {
666
+ ...running,
667
+ stop: async () => {
668
+ await running.stop();
669
+ lease.release();
670
+ }
671
+ };
672
+ } catch (error) {
673
+ lease.release();
674
+ throw error;
675
+ }
676
+ });
677
+ }
678
+ async start() {
679
+ await mkdir(this.paths.home, {
680
+ recursive: true,
681
+ mode: 448
682
+ });
683
+ setLogSink((level, args) => void this.log(level, formatWithOptions({
684
+ depth: 5,
685
+ breakLength: Infinity
686
+ }, ...args)));
687
+ if (process.platform !== "win32") await rm(this.paths.socketPath, { force: true });
688
+ this.server = createServer((socket) => this.accept(socket));
689
+ await new Promise((resolveListen, reject) => {
690
+ this.server.once("error", reject);
691
+ this.server.listen(this.paths.socketPath, () => {
692
+ this.server.off("error", reject);
693
+ resolveListen();
694
+ });
695
+ });
696
+ if (process.platform !== "win32") await chmod(this.paths.socketPath, 384);
697
+ const metadata = {
698
+ pid: process.pid,
699
+ socketPath: this.paths.socketPath,
700
+ token: this.token,
701
+ protocolVersion: 1,
702
+ version: daemonVersion,
703
+ startedAt: this.startedAt
704
+ };
705
+ await writeFile(this.paths.metadataPath, `${JSON.stringify(metadata, null, 2)}\n`, {
706
+ encoding: "utf8",
707
+ mode: 384
708
+ });
709
+ await chmod(this.paths.metadataPath, 384);
710
+ await this.log("info", `Daemon ${daemonVersion} listening on ${this.paths.socketPath}.`);
711
+ this.scheduleIdleExit();
712
+ return metadata;
713
+ }
714
+ async stop() {
715
+ if (this.stopping) return this.stopping;
716
+ this.stopping = this.performStop();
717
+ return this.stopping;
718
+ }
719
+ status() {
720
+ return {
721
+ pid: process.pid,
722
+ version: daemonVersion,
723
+ protocolVersion: 1,
724
+ startedAt: this.startedAt,
725
+ clients: this.clients.size,
726
+ projects: this.network.projectCount,
727
+ replicas: this.replicas.list()
728
+ };
729
+ }
730
+ accept(socket) {
731
+ this.cancelIdleExit();
732
+ const rpc = createSocketRpcConnection(socket);
733
+ const client = {
734
+ leaseId: randomUUID(),
735
+ socket,
736
+ rpc,
737
+ initialized: false
738
+ };
739
+ this.clients.add(client);
740
+ rpc.onRequest(RPC_METHOD.initialize, (params) => this.initialize(client, params));
741
+ rpc.onRequest(RPC_METHOD.daemonStatus, () => this.authorized(client, () => this.status()));
742
+ rpc.onRequest(RPC_METHOD.daemonShutdown, () => this.authorized(client, async () => {
743
+ setTimeout(() => void this.stop(), 25);
744
+ return null;
745
+ }));
746
+ rpc.onRequest(RPC_METHOD.replicaAttach, (params) => this.authorized(client, async () => {
747
+ try {
748
+ return await this.replicas.attach(client.leaseId, params);
749
+ } catch (error) {
750
+ if (error instanceof ReplicaAlreadyActiveError) throw new ResponseError(REPLICA_ALREADY_ACTIVE, error.message, {
751
+ code: error.code,
752
+ projectId: error.projectId,
753
+ activeRoot: error.activeRoot,
754
+ requestedRoot: error.requestedRoot
755
+ });
756
+ throw error;
757
+ }
758
+ }));
759
+ rpc.onRequest(RPC_METHOD.replicaDetach, (params) => this.authorized(client, async () => {
760
+ await this.replicas.detach(client.leaseId, params.replicaId);
761
+ return null;
762
+ }));
763
+ rpc.onRequest(RPC_METHOD.replicaResolveConflict, (params) => this.authorized(client, async () => {
764
+ await this.replicas.resolveConflict(params.replicaId, params.path, params.winner);
765
+ return null;
766
+ }));
767
+ rpc.onRequest(RPC_METHOD.replicaRetry, (params) => this.authorized(client, async () => {
768
+ await this.replicas.retry(params.replicaId, params.path);
769
+ return null;
770
+ }));
771
+ rpc.onRequest(RPC_METHOD.serverList, () => this.authorized(client, () => this.network.listServers()));
772
+ rpc.onRequest(RPC_METHOD.serverAdd, (params) => this.authorized(client, async () => {
773
+ await this.network.addServer(params.name, params.url);
774
+ return null;
775
+ }));
776
+ rpc.onRequest(RPC_METHOD.serverRemove, (params) => this.authorized(client, async () => {
777
+ await this.network.removeServer(params.server);
778
+ return null;
779
+ }));
780
+ rpc.onRequest(RPC_METHOD.sessionLogin, (params) => this.authorized(client, () => this.network.login(params)));
781
+ rpc.onRequest(RPC_METHOD.sessionImport, (params) => this.authorized(client, () => this.network.importSession(params)));
782
+ rpc.onRequest(RPC_METHOD.sessionLogout, (params) => this.authorized(client, async () => {
783
+ await this.network.logout(params.server);
784
+ return null;
785
+ }));
786
+ rpc.onRequest(RPC_METHOD.serverCall, (params) => this.authorized(client, async () => {
787
+ return encodeRpcValue(await this.network.callServer(params.server, params.operation, decodeRpcValue(params.args)));
788
+ }));
789
+ rpc.onRequest(RPC_METHOD.projectOpen, (params) => this.authorized(client, () => this.network.openProject(client.leaseId, params.server, params.projectId)));
790
+ rpc.onRequest(RPC_METHOD.projectClose, (params) => this.authorized(client, () => {
791
+ this.network.closeProject(client.leaseId, params.projectKey);
792
+ return null;
793
+ }));
794
+ rpc.onRequest(RPC_METHOD.projectCall, (params) => this.authorized(client, async () => {
795
+ return encodeRpcValue(await await this.network.callProject(params.projectKey, params.operation, decodeRpcValue(params.args)));
796
+ }));
797
+ rpc.onClose(() => void this.closeClient(client));
798
+ rpc.onError((error) => void this.log("error", `JSON-RPC connection error: ${String(error[0])}`));
799
+ rpc.listen();
800
+ }
801
+ initialize(client, params) {
802
+ if (params.token !== this.token) throw new ResponseError(-32001, "Daemon authentication failed.");
803
+ if (params.protocolVersion !== 1) throw new ResponseError(-32002, `Protocol ${params.protocolVersion} is incompatible with daemon protocol 1.`);
804
+ if (!params.clientId) throw new ResponseError(-32602, "clientId is required.");
805
+ client.clientId = params.clientId;
806
+ client.initialized = true;
807
+ this.replicas.registerClient(client.leaseId);
808
+ this.log("info", `${params.clientName} ${params.clientVersion} connected (${params.clientId}).`);
809
+ return {
810
+ daemonVersion,
811
+ protocolVersion: 1,
812
+ pid: process.pid,
813
+ startedAt: this.startedAt
814
+ };
815
+ }
816
+ async authorized(client, operation) {
817
+ if (!client.initialized) throw new ResponseError(-32001, "Initialize the daemon connection first.");
818
+ try {
819
+ return await operation();
820
+ } catch (error) {
821
+ if (error instanceof ResponseError) throw error;
822
+ const message = error instanceof Error ? error.message : String(error);
823
+ await this.log("error", `RPC operation failed: ${formatWithOptions({
824
+ depth: 5,
825
+ breakLength: Infinity
826
+ }, error)}`);
827
+ throw new ResponseError(-32603, message);
828
+ }
829
+ }
830
+ async closeClient(client) {
831
+ if (!this.clients.delete(client)) return;
832
+ if (client.clientId) try {
833
+ await this.replicas.detachClient(client.leaseId);
834
+ } catch (error) {
835
+ await this.log("error", `Failed to stop replicas for a disconnected client: ${error instanceof Error ? error.message : String(error)}`);
836
+ } finally {
837
+ this.network.detachClient(client.leaseId);
838
+ }
839
+ this.scheduleIdleExit();
840
+ }
841
+ notifyOwners(owners, method, notification) {
842
+ for (const client of this.clients) if (owners.has(client.leaseId)) this.notifyClient(client, method, notification);
843
+ }
844
+ async log(level, message) {
845
+ const notification = {
846
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
847
+ level,
848
+ message
849
+ };
850
+ await appendFile(this.paths.logPath, `${notification.timestamp} [${level}] ${message}\n`, {
851
+ encoding: "utf8",
852
+ mode: 384
853
+ });
854
+ for (const client of this.clients) if (client.initialized) this.notifyClient(client, RPC_NOTIFICATION.log, notification);
855
+ }
856
+ notifyClient(client, method, notification) {
857
+ if (!this.clients.has(client) || client.socket.destroyed) return;
858
+ client.rpc.sendNotification(method, notification).catch(() => this.closeClient(client));
859
+ }
860
+ scheduleIdleExit() {
861
+ if (this.options.exitOnIdle === false || this.clients.size !== 0 || this.replicas.size !== 0 || this.idleTimer) return;
862
+ this.idleTimer = setTimeout(() => void this.stop(), IDLE_EXIT_MS);
863
+ this.idleTimer.unref();
864
+ }
865
+ cancelIdleExit() {
866
+ if (this.idleTimer) {
867
+ clearTimeout(this.idleTimer);
868
+ this.idleTimer = void 0;
869
+ }
870
+ }
871
+ async performStop() {
872
+ this.cancelIdleExit();
873
+ await this.replicas.stopAll();
874
+ await this.network.stopAll();
875
+ setLogSink(void 0);
876
+ for (const client of this.clients) {
877
+ client.rpc.dispose();
878
+ client.socket.destroy();
879
+ }
880
+ this.clients.clear();
881
+ if (this.server) await new Promise((resolveClose) => this.server.close(() => resolveClose()));
882
+ await rm(this.paths.metadataPath, { force: true });
883
+ if (process.platform !== "win32") await rm(this.paths.socketPath, { force: true });
884
+ }
953
885
  };
954
-
955
886
  // ../daemon/src/main.ts
956
- var server = new LeafRelayDaemonServer();
957
- var stop = () => {
958
- process.off("SIGINT", stop);
959
- process.off("SIGTERM", stop);
960
- void server.stop().finally(() => process.exit(0));
887
+ const server = new LeafRelayDaemonServer();
888
+ const stop = () => {
889
+ process.off("SIGINT", stop);
890
+ process.off("SIGTERM", stop);
891
+ server.stop().finally(() => process.exit(0));
961
892
  };
962
893
  process.on("SIGINT", stop);
963
894
  process.on("SIGTERM", stop);
964
895
  process.on("uncaughtException", (error) => {
965
- console.error(error);
966
- void server.stop().finally(() => process.exit(1));
896
+ console.error(error);
897
+ server.stop().finally(() => process.exit(1));
967
898
  });
968
899
  process.on("unhandledRejection", (error) => {
969
- console.error(error);
970
- void server.stop().finally(() => process.exit(1));
900
+ console.error(error);
901
+ server.stop().finally(() => process.exit(1));
971
902
  });
972
- void server.start().catch((error) => {
973
- console.error(error);
974
- process.exit(1);
903
+ server.start().catch((error) => {
904
+ console.error(error);
905
+ process.exit(1);
975
906
  });
907
+ export {};
908
+
976
909
  //# sourceMappingURL=daemon.js.map