localgate 0.5.0 → 0.6.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.
@@ -1,11 +1,15 @@
1
1
  import { LocalgateAliasStore } from "../config/localgateAliasStore.ts";
2
2
  import { LocalgateMachineConfig, type LocalgateMachineSettings } from "../config/localgateMachineConfig.ts";
3
+ import { LocalgateNames } from "../config/localgateNames.ts";
4
+ import { LocalgateRunnerControl } from "../run/localgateRunnerControl.ts";
5
+ import { LocalgateShellCommand } from "../run/localgateShellCommand.ts";
3
6
  import { LocalgateAliasRoute } from "./localgateAliasRoute.ts";
4
7
  import { LocalgateUrl } from "./localgateUrl.ts";
5
8
  import { LocalgateControlApi } from "./localgateControlApi.ts";
6
9
  import { LocalgateHealth } from "./localgateHealth.ts";
7
10
  import { LocalgateProxy } from "./localgateProxy.ts";
8
11
  import { LocalgateRegistry, type LocalgateRoute } from "./localgateRegistry.ts";
12
+ import { LocalgateStartPage } from "./localgateStartPage.ts";
9
13
 
10
14
  // Boots the long-lived half of localgate. Started on demand by the first `run` or `alias`, and it exits
11
15
  // once the last route disappears, so nothing is installed and nothing runs when no dev server does.
@@ -18,12 +22,21 @@ export class LocalgateProxyHost
18
22
  const machine = LocalgateMachineConfig.load();
19
23
  const port = LocalgateUrl.proxyPort(machine);
20
24
  const registry = new LocalgateRegistry();
21
- const health = new LocalgateHealth(registry, machine?.autoRestart === true, LocalgateProxyHost.requestRestart);
25
+ const health = new LocalgateHealth(registry, machine?.autoRestart === true,
26
+ route => LocalgateProxyHost.request(route, "restart"));
22
27
 
23
28
  const proxy: LocalgateProxy = new LocalgateProxy(
24
29
  registry,
25
30
  health,
26
31
  new LocalgateControlApi(registry, () => proxy.checkIdle()),
32
+ // The configured port rather than the bound one, because the page writes addresses for a person to
33
+ // click, and those are the names and the port they would have typed themselves.
34
+ new LocalgateStartPage(registry, machine, port, {
35
+ // Read at each render rather than held from boot, so an alias that gains a stop command gets
36
+ // its button without restarting the proxy every dev server on this machine depends on.
37
+ aliasStopCommands: () => LocalgateAliasStore.stopCommands(),
38
+ stop: route => LocalgateProxyHost.stop(route)
39
+ }),
27
40
  {
28
41
  port,
29
42
  lanIp: machine?.lanIp ?? null,
@@ -40,7 +53,8 @@ export class LocalgateProxyHost
40
53
 
41
54
  await proxy.start();
42
55
  process.stdout.write(`localgate proxy listening on 127.0.0.1:${port}`
43
- + `${machine?.lanIp ? ` and ${machine.lanIp}:${port}` : ""}\n`);
56
+ + `${machine?.lanIp ? ` and ${machine.lanIp}:${port}` : ""}\n`
57
+ + `localgate: start page at ${LocalgateStartPage.localUrl(port)}\n`);
44
58
 
45
59
  for (const signal of ["SIGINT", "SIGTERM"] as const)
46
60
  process.on(signal, () => void proxy.stop().then(() => process.exit(0)));
@@ -54,11 +68,31 @@ export class LocalgateProxyHost
54
68
  for (const line of restored) process.stdout.write(`${line}\n`);
55
69
  }
56
70
 
57
- private static async requestRestart(route: LocalgateRoute): Promise<void>
71
+ // Two kinds of route, two ways to end one. An app has a runner, and only the runner can end the child
72
+ // tree, release the port and deregister its own route. An alias has nothing of ours behind it, so all
73
+ // that can be done is to run the line the machine's owner wrote for it.
74
+ static async stop(route: LocalgateRoute): Promise<void>
75
+ {
76
+ if (route.controlUrl) return LocalgateProxyHost.request(route, "stop");
77
+
78
+ const name = LocalgateNames.shortName(route.names[0]!);
79
+ const command = LocalgateAliasStore.stopCommands().get(name);
80
+ if (!command) throw new Error(`${name} is an alias with no stop command in ${LocalgateAliasStore.filePath()}`);
81
+
82
+ await LocalgateShellCommand.run(command);
83
+ }
84
+
85
+ // The proxy never kills anything itself: it asks the runner that owns the process, which is the only
86
+ // one that can end the child tree, release the port and deregister its own route.
87
+ private static async request(route: LocalgateRoute, action: "restart" | "stop"): Promise<void>
58
88
  {
59
89
  if (!route.controlUrl) throw new Error(`route ${route.names[0]} has no control endpoint`);
60
90
 
61
- const response = await fetch(`${route.controlUrl}/restart`, { method: "POST" });
62
- if (!response.ok) throw new Error(`control endpoint answered ${response.status}`);
91
+ const response = await fetch(`${route.controlUrl}/${action}`, { method: "POST" });
92
+ // With the reason the runner wrote, not the status alone: this message is what the start page shows
93
+ // its reader, and a bare `409` there sends them to a terminal to find out what the kill hit.
94
+ if (!response.ok)
95
+ throw new Error(`control endpoint answered ${response.status}`
96
+ + LocalgateRunnerControl.refusalDetail(await response.text().catch(() => "")));
63
97
  }
64
98
  }
@@ -1,5 +1,7 @@
1
1
  import { isAbsolute, relative, resolve, sep } from "node:path";
2
+ import { LocalgateNames } from "../config/localgateNames.ts";
2
3
  import type { LocalgateMode } from "../config/localgateProjectConfig.ts";
4
+ import { LocalgateUrl } from "./localgateUrl.ts";
3
5
 
4
6
  export type LocalgateRouteKind = "app" | "alias";
5
7
 
@@ -70,6 +72,8 @@ export class LocalgateRegistry
70
72
  if (registration.names.length == 0)
71
73
  throw new Error("a route needs at least one name");
72
74
 
75
+ LocalgateRegistry.refuseReserved(registration.names);
76
+
73
77
  // Taking a name away from a live runner used to be silent, which left that runner holding its port
74
78
  // with no route pointing at it - unreachable, and invisible to stop/restart/status. A runner may
75
79
  // still re-register its own names, which is how the heartbeat recovers from a proxy restart.
@@ -119,7 +123,7 @@ export class LocalgateRegistry
119
123
  // `.localhost` name ends up answered on the LAN.
120
124
  byHostname(hostHeader: string, reachedFrom: LocalgateReach): LocalgateRoute | null
121
125
  {
122
- const host = LocalgateRegistry.hostnameOf(hostHeader);
126
+ const host = LocalgateUrl.hostnameOf(hostHeader);
123
127
  if (!host) return null;
124
128
 
125
129
  for (const route of this.routes.values())
@@ -175,6 +179,7 @@ export class LocalgateRegistry
175
179
  if (patch.names)
176
180
  {
177
181
  if (patch.names.length == 0) throw new Error("a route needs at least one name");
182
+ LocalgateRegistry.refuseReserved(patch.names);
178
183
  for (const name of patch.names)
179
184
  {
180
185
  const existing = this.findByName(name);
@@ -186,6 +191,17 @@ export class LocalgateRegistry
186
191
  return route;
187
192
  }
188
193
 
194
+ // The proxy resolves the start page before it looks in this table, so a route under that name would be
195
+ // registered, listed and never reached. Refused here rather than only in the commands, because the
196
+ // table is what every path ends at - the alias command, a runner claiming a name, a rename on restart.
197
+ private static refuseReserved(names: string[]): void
198
+ {
199
+ for (const name of names)
200
+ if (LocalgateNames.isReserved(name))
201
+ throw new Error(`"${LocalgateNames.startNameConst}" is reserved for localgate's start page, `
202
+ + `so ${name} cannot be registered`);
203
+ }
204
+
189
205
  private findByName(name: string): LocalgateRoute | null
190
206
  {
191
207
  for (const route of this.routes.values())
@@ -193,12 +209,6 @@ export class LocalgateRegistry
193
209
  return null;
194
210
  }
195
211
 
196
- private static hostnameOf(hostHeader: string): string | null
197
- {
198
- const host = hostHeader.trim().toLowerCase().split(":")[0];
199
- return host ? host : null;
200
- }
201
-
202
212
  // `.localhost` resolves to the loopback address of whoever looked it up, so off this machine it
203
213
  // names somebody else's computer. Serving it on the LAN listener would hand out every route,
204
214
  // including the local-mode ones whose whole point is that they never leave the machine.
@@ -0,0 +1,491 @@
1
+ import type { IncomingMessage, ServerResponse } from "node:http";
2
+ import { LocalgateNames } from "../config/localgateNames.ts";
3
+ import { LocalgateHealth } from "./localgateHealth.ts";
4
+ import { LocalgatePortProbe } from "./localgatePortProbe.ts";
5
+ import type { LocalgateMachineSettings } from "../config/localgateMachineConfig.ts";
6
+ import type { LocalgateReach, LocalgateRegistry, LocalgateRoute, LocalgateRouteState } from "./localgateRegistry.ts";
7
+ import { LocalgateUrl, type LocalgateAddress } from "./localgateUrl.ts";
8
+
9
+ // How the page ends what a route points at, and how it knows whether it can. One object rather than two
10
+ // callbacks, because the button and the action behind it must not drift apart: a button that appears for
11
+ // something nothing can stop is a click that fails, and the reverse is a verb nobody can find.
12
+ //
13
+ // An app is ended by asking its runner. An alias has no runner, so it can be ended only where the
14
+ // machine's owner wrote down how, which is `stop` in ~/.localgate/aliases.json - hence the names rather
15
+ // than a flag on the route: that file is the only source, and nothing reaching the proxy over a socket
16
+ // can add to it.
17
+ export type LocalgateRouteStopper =
18
+ {
19
+ aliasStopCommands(): ReadonlyMap<string, string>;
20
+ stop(route: LocalgateRoute): Promise<void>;
21
+ };
22
+
23
+ // What the current request asks the page to show on top of the list: one card awaiting confirmation,
24
+ // and the name of whatever was just stopped. Both come from the query string and name a route.
25
+ export type LocalgateStartPageView =
26
+ {
27
+ confirming?: string | null;
28
+ stopped?: string | null;
29
+ // Route id to "something accepts a connection on its port". A route missing from the map was not
30
+ // probed, and then the card falls back to the health the proxy learned from forwarded traffic.
31
+ listening?: ReadonlyMap<string, boolean>;
32
+ };
33
+
34
+ // The one page localgate serves from itself: every route on this machine and the addresses each one
35
+ // answers on, so a person has somewhere to start that does not depend on remembering a name.
36
+ //
37
+ // It is reach-aware for the same reason the route table is. On loopback it shows everything, including
38
+ // the upstream port and the directory a route was started from. On the LAN listener it answers only on
39
+ // the machine's own domain and lists only what a LAN caller can actually open: a route in mode `local`
40
+ // has no address off this machine, so it does not appear at all, and neither do the local paths and
41
+ // ports, which are nobody else's business.
42
+ export class LocalgateStartPage
43
+ {
44
+ private static readonly refreshSecondsConst = 5;
45
+ private static readonly stopPathConst = "/stop";
46
+
47
+ // A hub and three routes, which is what the proxy is. Inline, because the page is served to the LAN
48
+ // and must not fetch anything: a tab icon is not worth a request that could fail or be logged.
49
+ private static readonly faviconConst = "data:image/svg+xml,"
50
+ + "%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E"
51
+ + "%3Crect width='32' height='32' rx='8' fill='%232f6df6'/%3E"
52
+ + "%3Ccircle cx='10' cy='16' r='3.2' fill='white'/%3E"
53
+ + "%3Crect x='17' y='8' width='7' height='4' rx='2' fill='white'/%3E"
54
+ + "%3Crect x='17' y='14' width='7' height='4' rx='2' fill='white'/%3E"
55
+ + "%3Crect x='17' y='20' width='7' height='4' rx='2' fill='white'/%3E%3C/svg%3E";
56
+
57
+ private static readonly styleConst = `
58
+ :root { color-scheme: light dark; --bg: #f4f5f9; --fg: #16161b; --muted: #6b6b78; --card: #ffffff;
59
+ --line: #e3e3ec; --link: #1b52c0; --shadow: 0 1px 2px rgba(16, 16, 32, .06);
60
+ --shadow-lift: 0 8px 24px rgba(16, 16, 32, .13); --mark-l: 42%; --mark-s: 58%;
61
+ --ok: #17914f; --warn: #a37000; --bad: #c03028; }
62
+ @media (prefers-color-scheme: dark) {
63
+ :root { --bg: #131317; --fg: #ededf2; --muted: #9797a4; --card: #1d1d23; --line: #2d2d37;
64
+ --link: #8ab0ff; --shadow: none; --shadow-lift: 0 8px 24px rgba(0, 0, 0, .5);
65
+ --mark-l: 58%; --mark-s: 52%; --ok: #3ecf8e; --warn: #e0a92e; --bad: #ff6f62; } }
66
+ * { box-sizing: border-box; }
67
+ body { margin: 0; padding: 2.25rem 1.25rem 3rem; background: var(--bg); color: var(--fg);
68
+ font: 15px/1.5 ui-sans-serif, system-ui, "Segoe UI", sans-serif; }
69
+ main { max-width: 62rem; margin: 0 auto; }
70
+ header { display: flex; align-items: center; gap: .7rem; margin-bottom: .3rem; }
71
+ .logo { width: 1.9rem; height: 1.9rem; border-radius: .5rem; flex: none; }
72
+ h1 { margin: 0; font-size: 1.3rem; font-weight: 650; letter-spacing: .01em; }
73
+ .sub, footer { color: var(--muted); font-size: .85rem; }
74
+ .sub { margin: 0 0 1.6rem; }
75
+ ul { list-style: none; margin: 0; padding: 0; display: grid; gap: 1rem;
76
+ grid-template-columns: repeat(auto-fill, minmax(19rem, 1fr)); }
77
+ /* A column, so the cards in one row line their footers up however many addresses each one has. */
78
+ .card { position: relative; display: flex; flex-direction: column; background: var(--card);
79
+ border: 1px solid var(--line); border-radius: .9rem; padding: 1rem 1.1rem; box-shadow: var(--shadow);
80
+ transition: transform .12s ease, box-shadow .12s ease, border-color .12s ease; }
81
+ .card:hover { transform: translateY(-2px); box-shadow: var(--shadow-lift); border-color: var(--link); }
82
+ /* Nothing answers on its port. Still listed, because the name exists and an alias comes back at the
83
+ next proxy start, but it should not read like the apps that are actually up. */
84
+ .card.down { opacity: .62; }
85
+ .card.down:hover { opacity: 1; }
86
+ .head { display: flex; align-items: flex-start; gap: .7rem; }
87
+ .mark { flex: none; width: 2.4rem; height: 2.4rem; border-radius: .65rem; display: grid;
88
+ place-items: center; font-size: .78rem; font-weight: 700; letter-spacing: .02em; color: white;
89
+ background: hsl(var(--hue) var(--mark-s) var(--mark-l)); }
90
+ .title { min-width: 0; }
91
+ /* The whole card opens the address this listener can reach, and the stretched overlay is what makes
92
+ the padding clickable too. Every other link sits above it, so they still open their own address.
93
+ The name wraps rather than truncating: it is what the reader is looking for, and real project names
94
+ are long enough (web-myapp-customer-frontend) that an ellipsis would cut the distinguishing half. */
95
+ .name { display: block; font-size: 1.06rem; font-weight: 640; color: var(--fg);
96
+ line-height: 1.25; overflow-wrap: anywhere; }
97
+ .name::after { content: ""; position: absolute; inset: 0; border-radius: .9rem; }
98
+ .card:hover .name { color: var(--link); }
99
+ .primary { display: block; font-size: .82rem; color: var(--link); overflow: hidden;
100
+ text-overflow: ellipsis; white-space: nowrap; }
101
+ .state { margin-left: auto; flex: none; display: flex; align-items: center; gap: .35rem;
102
+ padding-top: .2rem; font-size: .72rem; text-transform: uppercase; letter-spacing: .05em;
103
+ color: var(--muted); }
104
+ .dot { width: .5rem; height: .5rem; border-radius: 50%; background: currentColor; }
105
+ .state.healthy { color: var(--ok); }
106
+ .state.starting { color: var(--warn); }
107
+ .state.unresponsive, .state.dead { color: var(--bad); }
108
+ .chips { display: flex; flex-wrap: wrap; gap: .35rem; margin: .75rem 0 .75rem; }
109
+ .chip { position: relative; z-index: 1; font-size: .76rem; padding: .2rem .55rem; border-radius: 1rem;
110
+ border: 1px solid var(--line); color: var(--muted); background: var(--bg); }
111
+ a.chip { color: var(--link); }
112
+ a.chip:hover { border-color: var(--link); }
113
+ a { text-decoration: none; }
114
+ a:hover { text-decoration: underline; }
115
+ .meta { margin-top: auto; padding-top: .7rem; border-top: 1px solid var(--line); color: var(--muted);
116
+ font-family: ui-monospace, "Cascadia Code", Consolas, monospace; font-size: .76rem;
117
+ overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
118
+ a.chip.danger { color: var(--bad); }
119
+ a.chip.danger:hover { border-color: var(--bad); }
120
+ .confirm { position: relative; z-index: 1; margin: .75rem 0; }
121
+ .confirm p { margin: 0 0 .6rem; font-size: .85rem; }
122
+ .confirm form { display: inline; }
123
+ .kill { font: inherit; font-size: .76rem; padding: .25rem .7rem; margin-right: .35rem; cursor: pointer;
124
+ color: white; background: var(--bad); border: 1px solid var(--bad); border-radius: 1rem; }
125
+ .notice { margin: -.9rem 0 1.4rem; font-size: .85rem; color: var(--muted); }
126
+ .empty { background: var(--card); border: 1px dashed var(--line); border-radius: .9rem;
127
+ padding: 2rem 1.1rem; text-align: center; color: var(--muted); }
128
+ footer { margin-top: 1.9rem; font-family: ui-monospace, "Cascadia Code", Consolas, monospace; }
129
+ `;
130
+
131
+ constructor(
132
+ private readonly registry: LocalgateRegistry,
133
+ private readonly machine: LocalgateMachineSettings | null,
134
+ private readonly proxyPort: number,
135
+ private readonly stopper: LocalgateRouteStopper
136
+ ) {}
137
+
138
+ // What to print in a terminal so the reader can click it. The page is always on `.localhost`, whatever
139
+ // the machine is called, because that name needs no configuration and no DNS.
140
+ static localUrl(proxyPort: number): string
141
+ {
142
+ return LocalgateUrl.forName(LocalgateNames.local(LocalgateNames.startNameConst), proxyPort);
143
+ }
144
+
145
+ handles(hostHeader: string, reachedFrom: LocalgateReach): boolean
146
+ {
147
+ const host = LocalgateUrl.hostnameOf(hostHeader);
148
+ if (!host) return false;
149
+
150
+ if (reachedFrom == "loopback") return host == this.localName() || host == this.lanName();
151
+ else if (reachedFrom == "lan") return host == this.lanName();
152
+ else
153
+ throw new Error(`unknown localgate reach: ${JSON.stringify(reachedFrom)}`);
154
+ }
155
+
156
+ // The page serves two verbs of its own, so the proxy hands it the request rather than a rendering
157
+ // call: a GET draws the list, and the POST behind the confirm button ends a dev server.
158
+ async handle(request: IncomingMessage, response: ServerResponse, reachedFrom: LocalgateReach): Promise<void>
159
+ {
160
+ const url = new URL(request.url ?? "/", "http://localgate.invalid");
161
+
162
+ if (request.method == "POST") return this.handleStop(request, response, url, reachedFrom);
163
+
164
+ LocalgateStartPage.sendHtml(response, 200, this.render(reachedFrom, {
165
+ confirming: url.searchParams.get("confirm"),
166
+ stopped: url.searchParams.get("stopped"),
167
+ listening: await LocalgatePortProbe.listeningRoutes(this.registry.all())
168
+ }));
169
+ }
170
+
171
+ render(reachedFrom: LocalgateReach, view: LocalgateStartPageView = {}): string
172
+ {
173
+ const loopback = reachedFrom == "loopback";
174
+ const entries = this.visible(reachedFrom);
175
+ const confirming = loopback ? view.confirming ?? null : null;
176
+ // Once per render rather than once per card: this reads the alias file, and it is the same answer
177
+ // for every card on the page.
178
+ const aliasStops = this.stopper.aliasStopCommands();
179
+
180
+ return [
181
+ "<!doctype html>",
182
+ "<html lang=\"en\">",
183
+ "<head>",
184
+ "<meta charset=\"utf-8\">",
185
+ "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">",
186
+ // A route appears the moment a dev server registers and its state changes while you look at the
187
+ // page, so a list that only tells the truth at load time is the one thing this page must not be.
188
+ // It reloads the plain list, which is how the "stopped" note clears itself; and it is left out
189
+ // entirely while a card is asking a question, because that question must not expire under the
190
+ // cursor of whoever is reading it.
191
+ confirming ? "" : `<meta http-equiv="refresh" content="${LocalgateStartPage.refreshSecondsConst}; url=/">`,
192
+ "<title>localgate</title>",
193
+ `<link rel="icon" href="${LocalgateStartPage.faviconConst}">`,
194
+ `<style>${LocalgateStartPage.styleConst}</style>`,
195
+ "</head>",
196
+ "<body><main>",
197
+ `<header><img class="logo" alt="" src="${LocalgateStartPage.faviconConst}"><h1>localgate</h1></header>`,
198
+ `<p class="sub">${LocalgateStartPage.escape(this.subtitle(entries.length, loopback))}</p>`,
199
+ loopback && view.stopped ? `<p class="notice">${LocalgateStartPage.escape(view.stopped)} was stopped. `
200
+ + "Start it again from the editor it was launched in.</p>" : "",
201
+ entries.length == 0
202
+ ? `<p class="empty">${LocalgateStartPage.escape(LocalgateStartPage.emptyMessage(loopback))}</p>`
203
+ : `<ul>${entries.map(entry => LocalgateStartPage.card(entry, loopback, confirming,
204
+ view.listening?.get(entry.route.id), LocalgateStartPage.stopsWith(entry.route, aliasStops))).join("")}</ul>`,
205
+ `<footer>${LocalgateStartPage.escape(LocalgateStartPage.footer(loopback, confirming))}</footer>`,
206
+ "</main></body>",
207
+ "</html>",
208
+ ""
209
+ ].join("\n");
210
+ }
211
+
212
+ // Ending a dev server is process control, which belongs to the loopback listener alone - the same
213
+ // boundary the control API sits behind. A POST that arrives on the LAN listener is refused whatever
214
+ // it carries, and the button that makes one is never rendered there in the first place.
215
+ private async handleStop(request: IncomingMessage, response: ServerResponse, url: URL,
216
+ reachedFrom: LocalgateReach): Promise<void>
217
+ {
218
+ if (reachedFrom != "loopback")
219
+ return LocalgateStartPage.sendHtml(response, 404, LocalgateStartPage.refusal("not found here"));
220
+
221
+ if (url.pathname != LocalgateStartPage.stopPathConst)
222
+ return LocalgateStartPage.sendHtml(response, 404, LocalgateStartPage.refusal("no such page"));
223
+
224
+ // The page is reachable by any site the developer happens to be browsing, and a form POST needs no
225
+ // permission to leave one. Without this check a page anywhere could end every dev server on the
226
+ // machine; with it, only a form served from this page can. Browsers always send Origin on a POST.
227
+ if (request.headers.origin != `http://${request.headers.host ?? ""}`)
228
+ return LocalgateStartPage.sendHtml(response, 403,
229
+ LocalgateStartPage.refusal("this request did not come from the start page"));
230
+
231
+ // By name rather than by the route id: ids are handed out per proxy process, so a tab left open
232
+ // across a proxy restart could otherwise confirm r3 and end whatever r3 has become. A name that no
233
+ // longer exists simply stops nothing, which is the state the click was asking for anyway.
234
+ const name = url.searchParams.get("name") ?? "";
235
+ const route = name ? this.registry.byName(name) : null;
236
+
237
+ const stopsWith = route ? LocalgateStartPage.stopsWith(route, this.stopper.aliasStopCommands()) : null;
238
+ if (!route || !stopsWith)
239
+ {
240
+ response.writeHead(303, { location: "/" });
241
+ response.end();
242
+ return;
243
+ }
244
+
245
+ // What a runner or a shell command reports back is the only account of what happened, and swallowing
246
+ // it would leave the reader with a page that quietly still lists the thing they asked to end.
247
+ try
248
+ {
249
+ await this.stopper.stop(route);
250
+ }
251
+ catch (error)
252
+ {
253
+ return LocalgateStartPage.sendHtml(response, 502,
254
+ LocalgateStartPage.refusal(`${name} could not be stopped: ${error instanceof Error ? error.message : String(error)}`));
255
+ }
256
+
257
+ response.writeHead(303, { location: `/?stopped=${encodeURIComponent(name)}` });
258
+ response.end();
259
+ }
260
+
261
+ private localName(): string
262
+ {
263
+ return LocalgateNames.local(LocalgateNames.startNameConst);
264
+ }
265
+
266
+ // null when the machine has no config, and compared against a hostname that is never null, so the page
267
+ // simply has no shared name on a machine that has none either.
268
+ private lanName(): string | null
269
+ {
270
+ return this.machine ? LocalgateNames.lan(LocalgateNames.startNameConst, this.machine) : null;
271
+ }
272
+
273
+ // The routes this listener may show, each with the addresses that listener can reach. A route left
274
+ // with no address - mode `local`, seen from the LAN - is not listed at all, name included.
275
+ private visible(reachedFrom: LocalgateReach): { route: LocalgateRoute; addresses: LocalgateAddress[] }[]
276
+ {
277
+ return this.registry.all()
278
+ .map(route => ({ route, addresses: LocalgateStartPage.addressesOf(route, this.proxyPort, reachedFrom) }))
279
+ .filter(entry => entry.addresses.length > 0)
280
+ .sort((left, right) => LocalgateStartPage.appName(left.route).localeCompare(LocalgateStartPage.appName(right.route)));
281
+ }
282
+
283
+ private static addressesOf(route: LocalgateRoute, proxyPort: number, reachedFrom: LocalgateReach): LocalgateAddress[]
284
+ {
285
+ const addresses = LocalgateUrl.routeAddresses(route, proxyPort);
286
+
287
+ if (reachedFrom == "loopback") return addresses;
288
+ // The `.localhost` address is the local one by construction, and off this machine it names the
289
+ // computer that reads it, so printing it there would be an invitation to a dead link at best.
290
+ else if (reachedFrom == "lan") return addresses.filter(address => address.label != "local");
291
+ else
292
+ throw new Error(`unknown localgate reach: ${JSON.stringify(reachedFrom)}`);
293
+ }
294
+
295
+ // One card per route, opening on a click anywhere in it. The address it opens is the first one this
296
+ // listener can reach - the `.localhost` name on this machine, the shared name off it - because a card
297
+ // that opened the wrong one would be a dead link for exactly the person who clicked it.
298
+ // What ends this route, as a sentence for the person about to click: the runner for an app, and the
299
+ // machine's own line for an alias. null means nothing can, and then there is no button.
300
+ private static stopsWith(route: LocalgateRoute, aliasStops: ReadonlyMap<string, string>): string | null
301
+ {
302
+ if (route.controlUrl) return "its dev server and the terminal it runs in end with it";
303
+
304
+ const command = aliasStops.get(LocalgateStartPage.appName(route));
305
+ return command ? `localgate runs: ${command}` : null;
306
+ }
307
+
308
+ private static card(entry: { route: LocalgateRoute; addresses: LocalgateAddress[] },
309
+ loopback: boolean, confirming: string | null, listening: boolean | undefined,
310
+ stopsWith: string | null): string
311
+ {
312
+ const { route, addresses } = entry;
313
+ const name = LocalgateStartPage.appName(route);
314
+ const [primary, ...rest] = addresses;
315
+ const meta = (reachable: boolean | undefined) => LocalgateStartPage.meta(route, reachable);
316
+ // A card asking the question must not also be one big link to the app, or the click meant for
317
+ // "no, go back" opens the dev server instead.
318
+ const asking = confirming == name;
319
+
320
+ const status = LocalgateStartPage.statusOf(route, listening);
321
+
322
+ const parts = [
323
+ `<li class="card${listening === false ? " down" : ""}">`,
324
+ "<div class=\"head\">",
325
+ `<span class="mark" style="--hue: ${LocalgateStartPage.hueOf(name)}">`
326
+ + `${LocalgateStartPage.escape(LocalgateStartPage.monogram(name))}</span>`,
327
+ "<span class=\"title\">",
328
+ asking
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>`,
332
+ "</span>",
333
+ `<span class="state ${status.shade}"><span class="dot"></span>`
334
+ + `${LocalgateStartPage.escape(status.word)}</span>`,
335
+ "</div>"
336
+ ];
337
+
338
+ if (asking && stopsWith) parts.push(LocalgateStartPage.confirmBlock(name, stopsWith));
339
+ else
340
+ {
341
+ const chips = rest.map(address => `<a class="chip" href="${LocalgateStartPage.escape(address.url)}">`
342
+ + `${LocalgateStartPage.escape(address.label)} · ${LocalgateStartPage.escape(address.hostname)}</a>`);
343
+
344
+ if (route.kind == "alias") chips.push("<span class=\"chip\">alias</span>");
345
+ if (loopback && route.debuggerAttached) chips.push("<span class=\"chip\">debugger</span>");
346
+ // Off this machine there is no stopping at all: that is process control, and it stays on loopback.
347
+ if (loopback && stopsWith)
348
+ chips.push(`<a class="chip danger" href="/?confirm=${encodeURIComponent(name)}">stop</a>`);
349
+
350
+ if (chips.length > 0) parts.push(`<div class="chips">${chips.join("")}</div>`);
351
+ }
352
+
353
+ // The full line in `title` as well as on the card: the directory is the long part, and it is the
354
+ // part a person hovers to read when the card has cut it off.
355
+ if (loopback) parts.push(`<div class="meta" title="${LocalgateStartPage.escape(meta(listening))}">`
356
+ + `${LocalgateStartPage.escape(meta(listening))}</div>`);
357
+
358
+ parts.push("</li>");
359
+ return parts.join("");
360
+ }
361
+
362
+ // The second step of the stop, and the only form on the page. A POST, because it ends a process:
363
+ // a link would be followed by a prefetch, a crawler or a restored tab.
364
+ private static confirmBlock(name: string, stopsWith: string): string
365
+ {
366
+ const safe = LocalgateStartPage.escape(name);
367
+ return "<div class=\"confirm\">"
368
+ + `<p>Stop ${safe}? ${LocalgateStartPage.escape(stopsWith)}.</p>`
369
+ + `<form method="post" action="${LocalgateStartPage.stopPathConst}?name=${encodeURIComponent(name)}">`
370
+ + "<button class=\"kill\" type=\"submit\">yes, stop it</button></form>"
371
+ + "<a class=\"chip\" href=\"/\">cancel</a>"
372
+ + "</div>";
373
+ }
374
+
375
+ private static refusal(reason: string): string
376
+ {
377
+ return `<!doctype html><meta charset="utf-8"><title>localgate</title>`
378
+ + `<p>localgate: ${LocalgateStartPage.escape(reason)}.</p>`;
379
+ }
380
+
381
+ // The first letter of the name plus the start of its last word, because our names share their
382
+ // beginning and differ at the end: web-myapp-admin and web-myapp-app are WAD and WAP, while
383
+ // initials of the leading words would make both of them WM.
384
+ private static monogram(name: string): string
385
+ {
386
+ const words = name.split("-").filter(word => word.length > 0);
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();
390
+ }
391
+
392
+ // A colour the name always gets back, so a card keeps its look across a refresh and a person finds an
393
+ // app by where the colour is rather than by reading every tile.
394
+ private static hueOf(name: string): number
395
+ {
396
+ let hash = 0;
397
+ for (const character of name) hash = (hash * 31 + character.charCodeAt(0)) % 360;
398
+ return hash;
399
+ }
400
+
401
+ private static meta(route: LocalgateRoute, listening: boolean | undefined): string
402
+ {
403
+ const parts = [`127.0.0.1:${route.port}`];
404
+
405
+ // An alias outlives whatever it points at, on purpose, so a dead one is not a fault to report but a
406
+ // row the reader may simply be done with. The way out belongs next to it.
407
+ if (listening === false && route.kind == "alias")
408
+ parts.push(`nothing there · localgate alias --remove ${LocalgateStartPage.appName(route)}`);
409
+
410
+ if (route.command) parts.push(route.command);
411
+ if (route.cwd) parts.push(route.cwd);
412
+ return parts.join(" · ");
413
+ }
414
+
415
+ // What the badge says. The probe answers the question the reader is actually asking - is this thing
416
+ // up - and the traffic-learned state refines it: a port that accepts connections while every request
417
+ // times out is wedged, not running. Without a probe result the state is all there is.
418
+ private static statusOf(route: LocalgateRoute, listening: boolean | undefined): { word: string; shade: string }
419
+ {
420
+ if (listening === undefined)
421
+ return { word: LocalgateStartPage.stateWord(route.state), shade: route.state };
422
+
423
+ if (listening)
424
+ return route.state == "unresponsive"
425
+ ? { word: "not responding", shade: "unresponsive" }
426
+ : { word: "running", shade: "healthy" };
427
+
428
+ // Nothing on the port. For an app just launched that is normal - the dev server binds its port a
429
+ // moment later - and the same grace window the proxy uses for a refused request applies here. An
430
+ // alias starts nothing, so for it there is no such moment.
431
+ const since = Date.parse(route.lastResponseAt ?? route.startedAt);
432
+ const starting = route.kind == "app" && Date.now() - since < LocalgateHealth.startupGraceMs();
433
+ return starting ? { word: "starting", shade: "starting" } : { word: "not running", shade: "dead" };
434
+ }
435
+
436
+ private static stateWord(state: LocalgateRouteState): string
437
+ {
438
+ if (state == "starting") return "starting";
439
+ else if (state == "healthy") return "running";
440
+ else if (state == "unresponsive") return "not responding";
441
+ else if (state == "dead") return "not running";
442
+ else
443
+ throw new Error(`unknown localgate route state: ${JSON.stringify(state)}`);
444
+ }
445
+
446
+ private static appName(route: LocalgateRoute): string
447
+ {
448
+ return LocalgateNames.shortName(route.names[0]!);
449
+ }
450
+
451
+ private subtitle(count: number, loopback: boolean): string
452
+ {
453
+ const routes = count == 1 ? "1 route" : `${count} routes`;
454
+ if (!loopback) return `${routes} on ${this.machine?.label ?? "this machine"}, reachable from this network`;
455
+ return this.machine ? `${routes} on ${this.machine.label}` : `${routes} on this machine`;
456
+ }
457
+
458
+ private static emptyMessage(loopback: boolean): string
459
+ {
460
+ return loopback
461
+ ? "No routes yet. Start one with: localgate run npm run dev"
462
+ : "No shared routes. Everything running here is in mode local.";
463
+ }
464
+
465
+ private static footer(loopback: boolean, confirming: string | null): string
466
+ {
467
+ // The refresh is off while a card is asking, so the footer must not keep promising one.
468
+ if (confirming) return "localgate list";
469
+ return loopback
470
+ ? `localgate list · refreshes every ${LocalgateStartPage.refreshSecondsConst} s`
471
+ : `refreshes every ${LocalgateStartPage.refreshSecondsConst} s`;
472
+ }
473
+
474
+ private static sendHtml(response: ServerResponse, status: number, body: string): void
475
+ {
476
+ response.writeHead(status, { "content-type": "text/html; charset=utf-8", "content-length": Buffer.byteLength(body) });
477
+ response.end(body);
478
+ }
479
+
480
+ // A command line and a working directory are free text from whatever was started, and they are printed
481
+ // into a page, so nothing goes in unescaped - including the values that look safe today.
482
+ private static escape(value: string): string
483
+ {
484
+ return value
485
+ .replace(/&/g, "&amp;")
486
+ .replace(/</g, "&lt;")
487
+ .replace(/>/g, "&gt;")
488
+ .replace(/"/g, "&quot;")
489
+ .replace(/'/g, "&#39;");
490
+ }
491
+ }