leafrelay 0.1.6 → 0.2.0

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