localgate 0.6.1 → 0.6.3

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/README.md CHANGED
@@ -237,6 +237,12 @@ The takeover above is the one place this matters for safety. **With no terminal
237
237
  the developer's session by accident; `localgate run --force` takes over deliberately. To pick up a
238
238
  change, use `localgate restart`, which keeps the runner, the terminal and the debugger.
239
239
 
240
+ A dev server lives as long as the terminal that started it. When an agent's command ends and takes its
241
+ console along, the runner notices within 10 s and stops the dev server the way Ctrl+C does, instead of
242
+ leaving it running on a console that no longer exists. On Windows such a server could start no child
243
+ process, and a Next.js dev server then restarted its worker processes in a loop. See
244
+ [docs/architecture/terminal-loss.md](docs/architecture/terminal-loss.md).
245
+
240
246
  ## Names, and who can reach them
241
247
 
242
248
  A project gets its name from `package.json`, and nothing else is needed to work locally:
@@ -315,6 +321,9 @@ get a readable page instead of a browser error, and it says what to do next:
315
321
  | `dead` | 503, "nothing is listening" plus the `prune` hint - the route outlived its dev server |
316
322
  | `unresponsive` | 504, after three requests in a row went unanswered, with the exact `localgate restart` line to run |
317
323
 
324
+ A reset on a kept-alive connection is not one of these states: the proxy sends a `GET`, `HEAD` or
325
+ `OPTIONS` request once more on a fresh connection first ([upstream keep-alive](docs/architecture/upstream-keep-alive.md)).
326
+
318
327
  Acting on it is the risky half, so it is opt-in: `"autoRestart": true` in `~/.localgate/config.json`
319
328
  lets the proxy restart an unresponsive app by itself, bounded by two attempts and a five-minute
320
329
  cooldown. **It never fires while a debugger is attached** - a process paused at a breakpoint is
@@ -363,7 +372,7 @@ switch back from `internet` when you are done. There is no TLS - it is plain htt
363
372
  ## Development
364
373
 
365
374
  ```bash
366
- pnpm run verify # type-check + lint + tests
375
+ pnpm run check # lint + typecheck + tests
367
376
  pnpm test # vitest
368
377
  ```
369
378
 
@@ -100,15 +100,21 @@ export class LocalgateProxyClient
100
100
  return ((await response.json()) as { route: LocalgateRoute | null }).route;
101
101
  }
102
102
 
103
- // Two levels of spawn on Windows, deliberately: `cmd` exits immediately, so the proxy's recorded
104
- // parent is already gone and the tree kill VSCode performs when a terminal closes cannot reach it.
105
- // Otherwise closing one project's terminal would take the routing of every other project with it.
103
+ // Two levels of spawn on Windows, deliberately: the intermediate exits immediately, so the proxy's
104
+ // recorded parent is already gone and the tree kill VSCode performs when a terminal closes cannot
105
+ // reach it. Otherwise closing one project's terminal would take the routing of every other project
106
+ // with it. The intermediate is node, not `cmd /c start /b`: a detached child gets DETACHED_PROCESS,
107
+ // so cmd had no console and Windows allocated a new one for the proxy - a visible window when
108
+ // Windows Terminal is the default terminal. A detached child of a detached node has no console.
109
+ private static readonly windowsLauncherConst = "require('node:child_process').spawn(process.execPath, "
110
+ + "process.argv.slice(1), { detached: true, stdio: 'ignore', windowsHide: true }).unref()";
111
+
106
112
  private static spawnDetached(): void
107
113
  {
108
114
  const entry = join(fileURLToPath(new URL("../../", import.meta.url)), "bin", "localgate.mjs");
109
115
 
110
116
  const child = process.platform == "win32"
111
- ? spawn("cmd", ["/c", "start", "\"\"", "/b", process.execPath, entry, "__proxy"],
117
+ ? spawn(process.execPath, ["-e", LocalgateProxyClient.windowsLauncherConst, entry, "__proxy"],
112
118
  { detached: true, stdio: "ignore", windowsHide: true })
113
119
  : spawn(process.execPath, [entry, "__proxy"], { detached: true, stdio: "ignore" });
114
120
 
@@ -37,6 +37,6 @@ export class LocalgatePortProbe
37
37
  static async listeningRoutes(routes: Pick<LocalgateRoute, "id" | "port">[]): Promise<Map<string, boolean>>
38
38
  {
39
39
  const answers = await Promise.all(routes.map(route => LocalgatePortProbe.listening(route.port)));
40
- return new Map(routes.map((route, index) => [route.id, answers[index]!]));
40
+ return new Map(routes.map((route, index) => [route.id, answers[index]]));
41
41
  }
42
42
  }
@@ -1,4 +1,5 @@
1
- import { createServer, request as httpRequest, type IncomingMessage, type Server, type ServerResponse } from "node:http";
1
+ import { Agent, createServer, request as httpRequest, type IncomingMessage, type OutgoingHttpHeaders, type Server,
2
+ type ServerResponse } from "node:http";
2
3
  import type { Duplex } from "node:stream";
3
4
  import { LocalgateControlApi } from "./localgateControlApi.ts";
4
5
  import { LocalgateHeaderRewrite } from "./localgateHeaderRewrite.ts";
@@ -17,7 +18,13 @@ export type LocalgateProxyOptions =
17
18
 
18
19
  export class LocalgateProxy
19
20
  {
21
+ // Node servers, Next included, close a kept-alive socket after 5 s without a request. Dropping ours after
22
+ // 1 s keeps a page load on warm sockets while leaving the dev server's timer far behind.
23
+ private static readonly idleSocketMsConst = 1_000;
24
+ private static readonly replayableMethodsConst = ["GET", "HEAD", "OPTIONS"];
25
+
20
26
  private readonly servers: Server[] = [];
27
+ private readonly upstreamAgent = new Agent({ keepAlive: true, timeout: LocalgateProxy.idleSocketMsConst });
21
28
  // An upgraded socket is handed to us and stops being tracked by the http server, so
22
29
  // closeAllConnections cannot reach it. The proxy keeps its own set, or a single open browser tab
23
30
  // holding an HMR websocket would keep it alive forever and defeat the self-exit.
@@ -66,6 +73,7 @@ export class LocalgateProxy
66
73
 
67
74
  await Promise.all(this.servers.map(server => new Promise<void>(resolve => server.close(() => resolve()))));
68
75
  this.servers.length = 0;
76
+ this.upstreamAgent.destroy();
69
77
  }
70
78
 
71
79
  // Called after every control-API mutation: the proxy exists to serve routes, so when the last one goes
@@ -93,7 +101,7 @@ export class LocalgateProxy
93
101
  {
94
102
  const reachedFrom: LocalgateReach = loopback ? "loopback" : "lan";
95
103
  const server = createServer((request, response) => void this.handleRequest(request, response, loopback, reachedFrom));
96
- server.on("upgrade", (request, socket, head) => this.handleUpgrade(request, socket as Duplex, head, reachedFrom));
104
+ server.on("upgrade", (request, socket, head) => this.handleUpgrade(request, socket, head, reachedFrom));
97
105
 
98
106
  return new Promise<void>((resolve, reject) =>
99
107
  {
@@ -144,14 +152,27 @@ export class LocalgateProxy
144
152
  + "service actually listens on.\n");
145
153
 
146
154
  const headers = { ...request.headers };
147
- LocalgateHeaderRewrite.apply(request.url ?? "/", headers, request.headers.host ?? "", route.names[0]!);
155
+ LocalgateHeaderRewrite.apply(request.url ?? "/", headers, request.headers.host ?? "", route.names[0]);
156
+
157
+ // Only a request that may be sent twice takes a kept-alive socket: a body is streamed through once, and
158
+ // a method that changes state must not run again because the first attempt might have reached the server.
159
+ const replayable = LocalgateProxy.replayableMethodsConst.includes(request.method ?? "")
160
+ && request.headers["content-length"] === undefined && request.headers["transfer-encoding"] === undefined;
161
+ if (replayable) request.resume();
162
+ this.dial(route, request, response, headers, replayable, false);
163
+ }
148
164
 
165
+ private dial(route: LocalgateRoute, request: IncomingMessage, response: ServerResponse, headers: OutgoingHttpHeaders,
166
+ replayable: boolean, retry: boolean): void
167
+ {
168
+ const reuse = replayable && !retry;
149
169
  const upstream = httpRequest({
150
170
  host: "127.0.0.1",
151
171
  port: route.port,
152
172
  method: request.method,
153
173
  path: request.url,
154
- headers
174
+ headers,
175
+ agent: reuse ? this.upstreamAgent : false
155
176
  });
156
177
 
157
178
  upstream.setTimeout(LocalgateHealth.requestTimeoutMs(), () =>
@@ -192,6 +213,13 @@ export class LocalgateProxy
192
213
  return;
193
214
  }
194
215
 
216
+ // The dev server closed a kept-alive socket while this request was on its way. A server whose event
217
+ // loop is blocked (a debugger, a long compile) runs its idle timer late, so the close can come seconds
218
+ // after the request arrived. The reset says nothing about the route, so the request goes once more on
219
+ // a fresh connection before the route is judged.
220
+ if (reuse && upstream.reusedSocket && error.code == "ECONNRESET")
221
+ return this.dial(route, request, response, headers, replayable, true);
222
+
195
223
  if (error.code == "ECONNREFUSED" || error.code == "ECONNRESET")
196
224
  {
197
225
  this.health.noteConnectionRefused(route);
@@ -203,7 +231,9 @@ export class LocalgateProxy
203
231
  LocalgateProxy.sendText(response, 502, `localgate: upstream error for ${route.names[0]}: ${error.message}\n`);
204
232
  });
205
233
 
206
- request.pipe(upstream);
234
+ // A replayable request has already ended by the time of a retry, so piping it would never end the new one.
235
+ if (replayable) upstream.end();
236
+ else request.pipe(upstream);
207
237
  }
208
238
 
209
239
  // Hot module reload runs over a websocket, so the upgrade has to be proxied or every edit needs a
@@ -220,7 +250,7 @@ export class LocalgateProxy
220
250
  }
221
251
 
222
252
  const headers = { ...request.headers };
223
- LocalgateHeaderRewrite.apply(request.url ?? "/", headers, request.headers.host ?? "", route.names[0]!);
253
+ LocalgateHeaderRewrite.apply(request.url ?? "/", headers, request.headers.host ?? "", route.names[0]);
224
254
 
225
255
  const upstream = httpRequest({
226
256
  host: "127.0.0.1",
@@ -291,7 +321,7 @@ export class LocalgateProxy
291
321
 
292
322
  // The port this request arrived on, not the configured one: the two differ when the proxy was asked
293
323
  // for an ephemeral port, and a hint pointing at a port nothing listens on is worse than no hint.
294
- lines.push("", `Every route, with its addresses: ${LocalgateStartPage.localUrl(this.boundPorts()[0]!)}`, "");
324
+ lines.push("", `Every route, with its addresses: ${LocalgateStartPage.localUrl(this.boundPorts()[0])}`, "");
295
325
  return lines.join("\n");
296
326
  }
297
327
 
@@ -75,7 +75,7 @@ export class LocalgateProxyHost
75
75
  {
76
76
  if (route.controlUrl) return LocalgateProxyHost.request(route, "stop");
77
77
 
78
- const name = LocalgateNames.shortName(route.names[0]!);
78
+ const name = LocalgateNames.shortName(route.names[0]);
79
79
  const command = LocalgateAliasStore.stopCommands().get(name);
80
80
  if (!command) throw new Error(`${name} is an alias with no stop command in ${LocalgateAliasStore.filePath()}`);
81
81
 
@@ -327,8 +327,8 @@ export class LocalgateStartPage
327
327
  "<span class=\"title\">",
328
328
  asking
329
329
  ? `<span class="name">${LocalgateStartPage.escape(name)}</span>`
330
- : `<a class="name" href="${LocalgateStartPage.escape(primary!.url)}">${LocalgateStartPage.escape(name)}</a>`,
331
- `<span class="primary">${LocalgateStartPage.escape(primary!.hostname)}</span>`,
330
+ : `<a class="name" href="${LocalgateStartPage.escape(primary.url)}">${LocalgateStartPage.escape(name)}</a>`,
331
+ `<span class="primary">${LocalgateStartPage.escape(primary.hostname)}</span>`,
332
332
  "</span>",
333
333
  `<span class="state ${status.shade}"><span class="dot"></span>`
334
334
  + `${LocalgateStartPage.escape(status.word)}</span>`,
@@ -385,8 +385,8 @@ export class LocalgateStartPage
385
385
  {
386
386
  const words = name.split("-").filter(word => word.length > 0);
387
387
  if (words.length == 0) return "?";
388
- if (words.length == 1) return words[0]!.slice(0, 2).toUpperCase();
389
- return `${words[0]![0]!}${words[words.length - 1]!.slice(0, 2)}`.toUpperCase();
388
+ if (words.length == 1) return words[0].slice(0, 2).toUpperCase();
389
+ return `${words[0][0]}${words[words.length - 1].slice(0, 2)}`.toUpperCase();
390
390
  }
391
391
 
392
392
  // A colour the name always gets back, so a card keeps its look across a refresh and a person finds an
@@ -445,7 +445,7 @@ export class LocalgateStartPage
445
445
 
446
446
  private static appName(route: LocalgateRoute): string
447
447
  {
448
- return LocalgateNames.shortName(route.names[0]!);
448
+ return LocalgateNames.shortName(route.names[0]);
449
449
  }
450
450
 
451
451
  private subtitle(count: number, loopback: boolean): string
@@ -0,0 +1,55 @@
1
+ import { closeSync, openSync } from "node:fs";
2
+
3
+ // Whether the Windows console this process is attached to still exists. The runner and its dev tree
4
+ // share the console of whoever started `localgate run`. When an agent's command ends, its console host
5
+ // can go without any event reaching the processes attached to it, and from then on every child spawned
6
+ // without its own console fails to start with 0xC0000142 - Next's worker pool restarts such a child
7
+ // forever. Opening the console device is the cheapest question that tells: about 0.1 ms, no process.
8
+ export class LocalgateConsole
9
+ {
10
+ // `CONOUT$` alone resolves against the working directory; only the device path reaches the console.
11
+ static readonly devicePathConst = "\\\\.\\CONOUT$";
12
+
13
+ private readonly platform: NodeJS.Platform;
14
+ private readonly open: (path: string) => void;
15
+ private readonly watched: boolean;
16
+
17
+ constructor(platform: NodeJS.Platform = process.platform, open: (path: string) => void = LocalgateConsole.openDevice)
18
+ {
19
+ this.platform = platform;
20
+ this.open = open;
21
+ // A runner started without a console, or on a console this probe cannot read, keeps working the way
22
+ // it always did; only a console that was there and went is the loss this class reports.
23
+ try { this.watched = this.attached(); }
24
+ catch { this.watched = false; }
25
+ }
26
+
27
+ // POSIX reports a lost terminal as SIGHUP, which the runner handles, so only Windows needs the probe.
28
+ attached(): boolean
29
+ {
30
+ if (this.platform != "win32") return true;
31
+
32
+ try
33
+ {
34
+ this.open(LocalgateConsole.devicePathConst);
35
+ return true;
36
+ }
37
+ catch (error)
38
+ {
39
+ const code = (error as NodeJS.ErrnoException).code;
40
+ // EPIPE: the console host is gone. EBADF: this process has no console at all.
41
+ if (code == "EPIPE" || code == "EBADF") return false;
42
+ throw error;
43
+ }
44
+ }
45
+
46
+ lost(): boolean
47
+ {
48
+ return this.watched && !this.attached();
49
+ }
50
+
51
+ private static openDevice(path: string): void
52
+ {
53
+ closeSync(openSync(path, "r+"));
54
+ }
55
+ }
@@ -224,7 +224,7 @@ export class LocalgateProcessTree
224
224
  catch (error)
225
225
  {
226
226
  throw new Error(`${file} ${JSON.stringify(args)} [shell=false timeout=${timeout}ms]: `
227
- + LocalgateProcessTree.describeFailure(error));
227
+ + LocalgateProcessTree.describeFailure(error), { cause: error });
228
228
  }
229
229
  }
230
230
 
@@ -9,6 +9,7 @@ import { LocalgateNames } from "../config/localgateNames.ts";
9
9
  import { LocalgateProjectConfig, type LocalgateProjectSettings } from "../config/localgateProjectConfig.ts";
10
10
  import { LocalgateRouteConflictError } from "../proxy/localgateRegistry.ts";
11
11
  import type { LocalgateRoute, LocalgateRouteRegistration } from "../proxy/localgateRegistry.ts";
12
+ import { LocalgateConsole } from "./localgateConsole.ts";
12
13
  import { LocalgateEnvRewrite } from "./localgateEnvRewrite.ts";
13
14
  import { LocalgateNodeOptions } from "./localgateNodeOptions.ts";
14
15
  import { LocalgateProcessTree, type LocalgateKillOutcome } from "./localgateProcessTree.ts";
@@ -40,6 +41,7 @@ export class LocalgateRunner
40
41
  private stopping = false;
41
42
  private restarting = false;
42
43
  private reportedLostRoute = false;
44
+ private reportedConsoleProbe = false;
43
45
  private exitCode = 0;
44
46
 
45
47
  constructor(
@@ -511,14 +513,25 @@ export class LocalgateRunner
511
513
  // The proxy holds the route table in memory, so if it dies the route dies with it. Another runner may
512
514
  // start the proxy before this heartbeat, so a successful ping is not enough: this runner verifies that
513
515
  // its own route is present and re-registers when it is missing.
516
+ //
517
+ // The same beat notices a terminal that went without a signal: an agent's command ending takes its
518
+ // console host along, nothing tells the processes attached to it, and the dev tree is left unable to
519
+ // start any child. That is the operator leaving, so it ends the way Ctrl+C does.
514
520
  private startHeartbeat(): NodeJS.Timeout
515
521
  {
522
+ const terminal = new LocalgateConsole();
516
523
  const timer = setInterval(() =>
517
524
  {
518
525
  void (async () =>
519
526
  {
520
527
  if (this.stopping || !this.route) return;
521
528
 
529
+ if (this.terminalLost(terminal))
530
+ {
531
+ await this.shutdown(0);
532
+ return;
533
+ }
534
+
522
535
  const registered = await LocalgateProxyClient.resolve({ name: this.route.names[0] }).catch(() => null);
523
536
  if (LocalgateRunner.routeRegistrationMatches(this.route, registered, process.pid))
524
537
  {
@@ -567,15 +580,38 @@ export class LocalgateRunner
567
580
  return timer;
568
581
  }
569
582
 
583
+ private terminalLost(terminal: LocalgateConsole): boolean
584
+ {
585
+ try
586
+ {
587
+ return terminal.lost();
588
+ }
589
+ catch (error)
590
+ {
591
+ // Said once: an error this probe does not know repeats on every beat, and the runner keeps working.
592
+ if (!this.reportedConsoleProbe)
593
+ process.stderr.write(`localgate: could not check the terminal: ${String(error)}\n`);
594
+ this.reportedConsoleProbe = true;
595
+ return false;
596
+ }
597
+ }
598
+
599
+ // SIGHUP is the terminal window closing (on Windows the console close event). Without a handler Node
600
+ // exits at once and skips the kill, the port check and the route release.
570
601
  private installSignalHandlers(): void
571
602
  {
572
- for (const signal of ["SIGINT", "SIGTERM"] as const)
603
+ for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"] as const)
573
604
  process.on(signal, () => void this.shutdown(0));
605
+ // A terminal that is gone answers every write with EPIPE. Unhandled, that error would end the runner
606
+ // in the middle of its shutdown, before the route is released; the output is lost either way.
607
+ for (const stream of [process.stdout, process.stderr])
608
+ stream.on("error", () => {});
574
609
  }
575
610
 
576
- // Ctrl+C and the terminal going away, which is the operator leaving: the runner ends whatever the kill
577
- // achieved, and a port that outlived the child is a line on the way out. `/stop` is the other way in,
578
- // and it is the opposite - there somebody is waiting for the answer, so a refused kill is refused.
611
+ // Ctrl+C and the terminal going away (SIGHUP, or a console the heartbeat finds gone), which is the
612
+ // operator leaving: the runner ends whatever the kill achieved, and a port that outlived the child is
613
+ // a line on the way out. `/stop` is the other way in, and it is the opposite - there somebody is
614
+ // waiting for the answer, so a refused kill is refused.
579
615
  private async shutdown(code: number): Promise<void>
580
616
  {
581
617
  if (this.stopping) return;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "localgate",
3
- "version": "0.6.1",
3
+ "version": "0.6.3",
4
4
  "description": "Stable names for local dev servers: one port 80 multiplexed by Host, plus an API that can restart a dev server owned by your editor.",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
@@ -24,7 +24,7 @@
24
24
  "engines": {
25
25
  "node": ">=24"
26
26
  },
27
- "packageManager": "pnpm@11.17.0",
27
+ "packageManager": "pnpm@12.8.1",
28
28
  "bin": {
29
29
  "localgate": "bin/localgate.mjs"
30
30
  },
@@ -36,18 +36,18 @@
36
36
  "scripts": {
37
37
  "test": "vitest run --passWithNoTests",
38
38
  "test:watch": "vitest",
39
- "lint": "eslint .",
40
- "type-check": "tsc --noEmit",
41
- "verify": "pnpm run type-check && pnpm run lint && pnpm run test"
39
+ "lint": "oxlint --type-aware",
40
+ "typecheck": "tsc --noEmit",
41
+ "check": "pnpm run lint && pnpm run typecheck && pnpm test"
42
42
  },
43
43
  "dependencies": {
44
44
  "tsx": "4.21.0"
45
45
  },
46
46
  "devDependencies": {
47
47
  "@types/node": "25.5.0",
48
- "eslint": "9.22.0",
48
+ "oxlint": "1.95.0",
49
+ "oxlint-tsgolint": "7.0.2008",
49
50
  "typescript": "5.8.3",
50
- "typescript-eslint": "8.27.0",
51
- "vitest": "4.1.9"
51
+ "vitest": "5.1.1"
52
52
  }
53
53
  }