@evandu/super-pi 0.1.178 → 0.1.179

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.
Files changed (34) hide show
  1. package/bin/super-pi.js +1 -1
  2. package/dist/client/.super-pi-client-sources.json +3 -3
  3. package/dist/client/assets/{CodeMirrorEditor-BenB0qCl.js → CodeMirrorEditor-BdY_vez9.js} +2 -2
  4. package/dist/client/assets/{dist-Bqa4C7ia.js → dist-1AZAH0Vw.js} +1 -1
  5. package/dist/client/assets/{dist-BBqymG_O.js → dist-BPaSHEMs.js} +1 -1
  6. package/dist/client/assets/{dist-BEhZCgAe.js → dist-BXJ0FVm3.js} +1 -1
  7. package/dist/client/assets/{dist-DsYkcVVD.js → dist-BXrWZekq.js} +1 -1
  8. package/dist/client/assets/{dist-Dy29IXwY.js → dist-B_v-qVKZ.js} +1 -1
  9. package/dist/client/assets/{dist-C-XFV2Lh.js → dist-BiQDCO0Z.js} +1 -1
  10. package/dist/client/assets/{dist-fJbqoI_z.js → dist-Bxp6Lr31.js} +1 -1
  11. package/dist/client/assets/{dist-BondndXn.js → dist-BzicsMSL.js} +1 -1
  12. package/dist/client/assets/{dist-BWYKkV9J.js → dist-CE4F-GnZ.js} +1 -1
  13. package/dist/client/assets/{dist-BTbcZiCW.js → dist-C_5fMTu2.js} +1 -1
  14. package/dist/client/assets/{dist-DRcKCYFV.js → dist-CcVJlndc.js} +1 -1
  15. package/dist/client/assets/{dist-DynAZB38.js → dist-CxZY8nws.js} +1 -1
  16. package/dist/client/assets/{dist-Bm5z1I13.js → dist-D-AKDchV.js} +1 -1
  17. package/dist/client/assets/{dist-CP2zo9EH.js → dist-D7S0Q68i.js} +1 -1
  18. package/dist/client/assets/{dist-9SgjXHKI.js → dist-DVYPDnbh.js} +1 -1
  19. package/dist/client/assets/{dist-BphpuegD.js → dist-DfY4zXbE.js} +1 -1
  20. package/dist/client/assets/{dist-B7qg204Z.js → dist-DjsQFuR8.js} +1 -1
  21. package/dist/client/assets/{dist-D1W6DFkl.js → dist-Dl22kIFG.js} +1 -1
  22. package/dist/client/assets/{dist-BgVPFmiW.js → dist-RxPniecV.js} +1 -1
  23. package/dist/client/assets/{dist-CAqvv7Ol.js → dist-XnsZBWBb.js} +1 -1
  24. package/dist/client/assets/{dist-BfRyxOfA.js → dist-tD_cG-sA.js} +1 -1
  25. package/dist/client/assets/{dist-D754rN4L.js → dist-zNY48I29.js} +1 -1
  26. package/dist/client/assets/{index-D5fhfow-.js → index-Cy4Cb9zB.js} +4 -4
  27. package/dist/client/index.html +1 -1
  28. package/dist/server/http-server.d.ts +10 -0
  29. package/dist/server/http-server.js +47 -9
  30. package/dist/server/index.js +1 -1
  31. package/dist/server/update.d.ts +1 -1
  32. package/dist/server/update.js +7 -3
  33. package/package.json +3 -1
  34. package/scripts/restart-server.mjs +24 -3
@@ -8,7 +8,7 @@
8
8
  <link rel="alternate icon" href="/favicon.ico" />
9
9
  <link rel="apple-touch-icon" href="/favicon.svg" />
10
10
  <title>Super Pi</title>
11
- <script type="module" crossorigin src="/assets/index-D5fhfow-.js"></script>
11
+ <script type="module" crossorigin src="/assets/index-Cy4Cb9zB.js"></script>
12
12
  <link rel="stylesheet" crossorigin href="/assets/index-DAKtgLA9.css">
13
13
  </head>
14
14
  <body>
@@ -29,5 +29,15 @@ export declare function isAuthorized(request: {
29
29
  export interface HttpServerOptions {
30
30
  context: ServerContext;
31
31
  onShutdown: (reason: string) => Promise<void>;
32
+ /**
33
+ * THE PORT AND HOST THIS SERVER LISTENS ON.
34
+ *
35
+ * The update endpoint hands them to the restart script, which has to find the running server
36
+ * by port - it cannot know the port on its own, because the CLI passes the port as a command
37
+ * line argument. They are the values the server resolved at startup, so the server that comes
38
+ * back listens on exactly the same address as the one that went away.
39
+ */
40
+ port?: number;
41
+ host?: string;
32
42
  }
33
43
  export declare function createHttpServer(options: HttpServerOptions): NodeHttpServer;
@@ -277,7 +277,7 @@ async function readRequestText(request, limitBytes) {
277
277
  return { text: text + decoder.decode(), tooLarge: false };
278
278
  }
279
279
  export function createHttpServer(options) {
280
- const { context, onShutdown } = options;
280
+ const { context, onShutdown, port, host } = options;
281
281
  const { store, paths, accessToken, broadcaster, runService, catalogService, execService, toolRegistry, toolRunner } = context;
282
282
  const { uploadsDir, clientDir, rootDir } = paths;
283
283
  return createServer(async (request, response) => {
@@ -989,6 +989,25 @@ export function createHttpServer(options) {
989
989
  response.writeHead(403).end("Update requires a loopback or private network POST");
990
990
  return;
991
991
  }
992
+ // THE BODY IS OPTIONAL. An old client sends nothing; that still has to work.
993
+ let body = {};
994
+ try {
995
+ const reader = textBodyReader();
996
+ let raw = "";
997
+ for await (const chunk of request) {
998
+ const piece = chunk;
999
+ raw = reader.push(piece);
1000
+ if (raw.length > 4096)
1001
+ break;
1002
+ }
1003
+ raw = reader.finish();
1004
+ body = raw.trim() ? JSON.parse(raw) : {};
1005
+ }
1006
+ catch {
1007
+ body = {};
1008
+ }
1009
+ const wantedVersion = typeof body?.version === "string" && body.version ? body.version : undefined;
1010
+ const restartOnly = body?.restartOnly === true;
992
1011
  // ONE UPDATE AT A TIME. The client disables its button during an update, but a second tab
993
1012
  // (or a UI that failed to disable) can still reach this endpoint, and two npm installs against
994
1013
  // one global prefix corrupt each other. The slot is claimed BEFORE the 202 so a refused
@@ -998,11 +1017,6 @@ export function createHttpServer(options) {
998
1017
  return;
999
1018
  }
1000
1019
  response.writeHead(202, { "content-type": "application/json; charset=utf-8" }).end(JSON.stringify({ status: "updating" }));
1001
- // Use npm directly instead of `pi update` to avoid Windows detached+shell exit timing issues.
1002
- // npm's exit code correctly reflects whether the update succeeded.
1003
- const npmCmd = process.platform === "win32" ? "npm.cmd" : "npm";
1004
- const update = packageUpdateArgs(rootDir);
1005
- const child = spawn(npmCmd, update.args, { stdio: "ignore", shell: process.platform === "win32", env: process.env });
1006
1020
  // EXACTLY ONE RELEASE PER CHILD. A spawn that fails to start emits "error" AND THEN "close",
1007
1021
  // so a plain release in both handlers would free the slot a second time - and if a new
1008
1022
  // update had already claimed it in between, that second release would hand the slot away
@@ -1010,13 +1024,37 @@ export function createHttpServer(options) {
1010
1024
  let released = false;
1011
1025
  const release = () => { if (released)
1012
1026
  return; released = true; releaseUpdateSlot(); };
1027
+ // THE PORT AND HOST THE SERVER IS REALLY ON. The restart script has to find this very
1028
+ // server by port to replace it, and it cannot work the port out on its own: the CLI starts
1029
+ // the server with `--port=N` as an argument. Without them the script looked at the default
1030
+ // port, found nothing there, and started a second server next to the running one.
1031
+ const listenPort = port ?? request.socket.localPort;
1032
+ const restartEnv = { ...process.env, SUPER_PI_PORT: String(listenPort) };
1033
+ if (host)
1034
+ restartEnv.SUPER_PI_HOST = host;
1035
+ const restartNow = () => {
1036
+ console.log("Super Pi: restart triggered.");
1037
+ const restart = spawn(process.execPath, [join(rootDir, "scripts", "restart-server.mjs")], { cwd: rootDir, detached: true, stdio: "ignore", env: restartEnv });
1038
+ restart.on("error", (restartError) => console.error(`Super Pi: restart after update failed: ${restartError instanceof Error ? restartError.message : String(restartError)}`));
1039
+ restart.unref();
1040
+ };
1041
+ // RESTART ONLY: the code on disk is already new, the running server is not. Re-downloading
1042
+ // 32.8 MB to restart a process is waste; the second button asks for exactly this.
1043
+ if (restartOnly) {
1044
+ release();
1045
+ restartNow();
1046
+ return;
1047
+ }
1048
+ // Use npm directly instead of `pi update` to avoid Windows detached+shell exit timing issues.
1049
+ // npm's exit code correctly reflects whether the update succeeded.
1050
+ const npmCmd = process.platform === "win32" ? "npm.cmd" : "npm";
1051
+ const update = packageUpdateArgs(rootDir, wantedVersion);
1052
+ const child = spawn(npmCmd, update.args, { stdio: "ignore", shell: process.platform === "win32", env: process.env });
1013
1053
  child.on("close", (code) => {
1014
1054
  release();
1015
1055
  if (code === 0 || code === null) {
1016
1056
  console.log("Super Pi: npm install completed, triggering restart.");
1017
- const restart = spawn(process.execPath, [join(rootDir, "scripts", "restart-server.mjs")], { cwd: rootDir, detached: true, stdio: "ignore", env: process.env });
1018
- restart.on("error", (restartError) => console.error(`Super Pi: restart after update failed: ${restartError instanceof Error ? restartError.message : String(restartError)}`));
1019
- restart.unref();
1057
+ restartNow();
1020
1058
  }
1021
1059
  else {
1022
1060
  console.error(`Super Pi: npm install failed with code ${code}`);
@@ -409,7 +409,7 @@ async function shutdown(reason) {
409
409
  process.on("SIGINT", () => { void shutdown("SIGINT").finally(() => process.exit(0)); });
410
410
  process.on("SIGTERM", () => { void shutdown("SIGTERM").finally(() => process.exit(0)); });
411
411
  // ------------------------------------------------------------- Transports & startup
412
- const httpServer = createHttpServer({ context: serverContext, onShutdown: shutdown });
412
+ const httpServer = createHttpServer({ context: serverContext, onShutdown: shutdown, port, host });
413
413
  const wsServer = new WsServer({
414
414
  httpServer,
415
415
  broadcaster,
@@ -17,7 +17,7 @@
17
17
  * The fetch options are there because the tarball is ~32 MB: npm's default
18
18
  * 5 minute timeout fails on a slow line and the update looks broken.
19
19
  */
20
- export declare function packageUpdateArgs(rootDir: string): {
20
+ export declare function packageUpdateArgs(rootDir: string, version?: string): {
21
21
  args: string[];
22
22
  prefix?: string;
23
23
  };
@@ -18,15 +18,19 @@ import { sep } from "node:path";
18
18
  * The fetch options are there because the tarball is ~32 MB: npm's default
19
19
  * 5 minute timeout fails on a slow line and the update looks broken.
20
20
  */
21
- export function packageUpdateArgs(rootDir) {
21
+ export function packageUpdateArgs(rootDir, version) {
22
22
  const marker = `${sep}node_modules${sep}`;
23
23
  const lower = rootDir.toLowerCase();
24
24
  const index = lower.lastIndexOf(marker);
25
+ // THE VERSION THE USER CONFIRMED. The check reads the registry directly while npm resolves
26
+ // "latest" from its own cache, so the two can disagree: the dialog promises vX and the
27
+ // install silently lands on vY. Pinning the version the dialog showed removes that gap.
28
+ const target = version ? `@evandu/super-pi@${version}` : "@evandu/super-pi";
25
29
  if (index >= 0) {
26
30
  const prefix = rootDir.slice(0, index);
27
- return { prefix, args: ["install", "-g", "--prefix", prefix, "--fetch-timeout=900000", "--fetch-retries=8", "--fetch-retry-maxtimeout=120000", "@evandu/super-pi"] };
31
+ return { prefix, args: ["install", "-g", "--prefix", prefix, "--fetch-timeout=900000", "--fetch-retries=8", "--fetch-retry-maxtimeout=120000", target] };
28
32
  }
29
- return { args: ["install", "-g", "--fetch-timeout=900000", "--fetch-retries=8", "--fetch-retry-maxtimeout=120000", "@evandu/super-pi"] };
33
+ return { args: ["install", "-g", "--fetch-timeout=900000", "--fetch-retries=8", "--fetch-retry-maxtimeout=120000", target] };
30
34
  }
31
35
  /**
32
36
  * ONE UPDATE AT A TIME.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@evandu/super-pi",
3
- "version": "0.1.178",
3
+ "version": "0.1.179",
4
4
  "description": "Web control plane and companion for Pi",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -44,6 +44,8 @@
44
44
  },
45
45
  "check:logic": [
46
46
  "scripts/update-args.test.mjs",
47
+ "scripts/update-restart.test.mjs",
48
+ "scripts/update-version-pinning.test.mjs",
47
49
  "scripts/test-runner.test.mjs",
48
50
  "scripts/stream-checkpoint.test.mjs",
49
51
  "scripts/stream-transport.test.mjs",
@@ -1,12 +1,33 @@
1
1
  import { spawn, execFile } from "node:child_process";
2
2
  import { openSync, readFileSync } from "node:fs";
3
- import { platform } from "node:os";
3
+ import { homedir, platform } from "node:os";
4
+ import { join, resolve } from "node:path";
4
5
  import { promisify } from "node:util";
5
6
 
6
7
  const execFileAsync = promisify(execFile);
7
- const port = Number(process.env.SUPER_PI_PORT ?? 3080);
8
+
9
+ /** The saved port, from the same settings file the CLI reads. Returns undefined when there is
10
+ * no usable value, so the caller can fall through to the default. */
11
+ function savedPort() {
12
+ try {
13
+ const dir = process.env.SUPER_PI_DATA_DIR ? resolve(process.env.SUPER_PI_DATA_DIR) : join(homedir(), ".super-pi");
14
+ const saved = JSON.parse(readFileSync(join(dir, "config.json"), "utf8"));
15
+ const value = Number(saved?.port);
16
+ return Number.isInteger(value) && value > 0 ? value : undefined;
17
+ } catch { return undefined; }
18
+ }
19
+
20
+ // THE PORT THE SERVER IS REALLY ON. The environment wins, then the saved settings, then the
21
+ // default. Reading the environment ALONE was the bug: the CLI starts the server with `--port=N`
22
+ // as an argument and never sets this variable, so the script looked at 3080 and never found the
23
+ // running server it was supposed to replace.
24
+ const port = Number(process.env.SUPER_PI_PORT ?? savedPort() ?? 3080);
8
25
  const entry = "dist/server/index.js";
9
26
  const allowedEntries = [entry, "src/server/index.ts"];
27
+ /** Compare paths the way Windows reports them. A command line on Windows contains BACKSLASHES
28
+ * (`dist\server\index.js`) while the entries above use forward slashes, so a plain
29
+ * `cmd.includes(candidate)` never matched and the script refused to kill its own server. */
30
+ const normalisePath = (value) => value.replace(/[\\/]+/g, "/").toLowerCase();
10
31
  const waitMs = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
11
32
  async function pidsOnPort() {
12
33
  if (platform() === "win32") {
@@ -39,7 +60,7 @@ async function forceKill(pid) {
39
60
  }
40
61
  async function stopConflicts() {
41
62
  const pids = await pidsOnPort(); if (!pids.length) { console.log(`Port ${port} is free.`); return true; }
42
- for (const pid of pids) { const cmd = await commandLine(pid); console.log(`Port ${port} is occupied by PID ${pid}: ${cmd}`); if (!allowedEntries.some((candidate) => cmd.includes(candidate))) { console.error(`Refusing to kill non-super-pi process on port ${port}: ${cmd}`); process.exitCode = 2; return false; } }
63
+ for (const pid of pids) { const cmd = await commandLine(pid); console.log(`Port ${port} is occupied by PID ${pid}: ${cmd}`); if (!allowedEntries.some((candidate) => normalisePath(cmd).includes(normalisePath(candidate)))) { console.error(`Refusing to kill non-super-pi process on port ${port}: ${cmd}`); process.exitCode = 2; return false; } }
43
64
  const status = await requestShutdown();
44
65
  if (status !== null && status >= 200 && status < 300) {
45
66
  console.log(`Graceful shutdown accepted (HTTP ${status}); waiting for port ${port} to release...`);