pi-pocket 0.25.0 → 0.26.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.
Files changed (85) hide show
  1. package/AGENTS.md +2 -0
  2. package/README.md +5 -3
  3. package/docs/architecture.md +21 -0
  4. package/docs/design/design-mode.md +108 -0
  5. package/docs/design/notes-a.md +106 -0
  6. package/docs/design/notes-b.md +123 -0
  7. package/docs/design/notes-c.md +92 -0
  8. package/docs/design/notes-d.md +78 -0
  9. package/docs/design/release-notes-design.md +46 -0
  10. package/docs/extensions/browser-modules.md +2 -0
  11. package/docs/extensions/policies/api-stability.md +2 -0
  12. package/docs/extensions/reference/api-versions.md +1 -0
  13. package/docs/extensions/reference/host.md +1 -1
  14. package/docs/extensions/reference/limits.md +4 -0
  15. package/docs/extensions/reference/names.md +2 -2
  16. package/docs/extensions/reference/pocket.md +38 -0
  17. package/docs/features.md +19 -5
  18. package/docs/map.md +75 -54
  19. package/docs/release-notes.md +1 -1
  20. package/docs/self-editing.md +1 -1
  21. package/docs/systemd.md +1 -1
  22. package/npm-shrinkwrap.json +2 -2
  23. package/package.json +1 -1
  24. package/src/launcher/main.ts +20 -9
  25. package/src/server/app.ts +113 -4
  26. package/src/server/background.ts +3 -3
  27. package/src/server/cache-keeper.ts +605 -0
  28. package/src/server/compaction.ts +68 -15
  29. package/src/server/design/bundle.ts +65 -0
  30. package/src/server/design/export.ts +118 -0
  31. package/src/server/design/files.ts +49 -0
  32. package/src/server/design/guide.ts +56 -0
  33. package/src/server/design/index.ts +232 -0
  34. package/src/server/design/pptx.ts +304 -0
  35. package/src/server/design/render.ts +593 -0
  36. package/src/server/design/system.ts +248 -0
  37. package/src/server/docs.ts +55 -0
  38. package/src/server/extensions/artifacts.ts +202 -18
  39. package/src/server/extensions/design/canvas.js +304 -0
  40. package/src/server/extensions/design/comments.js +15 -0
  41. package/src/server/extensions/design/data.js +263 -0
  42. package/src/server/extensions/design/devices.js +70 -0
  43. package/src/server/extensions/design/docks.js +647 -0
  44. package/src/server/extensions/design/edits.js +37 -0
  45. package/src/server/extensions/design/index.js +326 -0
  46. package/src/server/extensions/design/messages.js +92 -0
  47. package/src/server/extensions/design/parts.js +160 -0
  48. package/src/server/extensions/design/state.js +146 -0
  49. package/src/server/extensions/design/style.css +1332 -0
  50. package/src/server/extensions/design/tweaks.js +161 -0
  51. package/src/server/extensions/design/views.js +375 -0
  52. package/src/server/extensions/design/workspace.js +723 -0
  53. package/src/server/extensions/design.ts +620 -0
  54. package/src/server/extensions/plan.ts +11 -9
  55. package/src/server/extensions/prompt.ts +11 -3
  56. package/src/server/extensions/subagents.ts +7 -1
  57. package/src/server/extensions/updates/index.js +16 -6
  58. package/src/server/extensions/updates.ts +2 -2
  59. package/src/server/http/artifact-assets.ts +216 -0
  60. package/src/server/http/artifact-inspect.ts +1281 -0
  61. package/src/server/http/artifacts.ts +89 -14
  62. package/src/server/http/conversation-routes.ts +46 -1
  63. package/src/server/http.ts +12 -4
  64. package/src/server/main.ts +4 -0
  65. package/src/server/npm-install.ts +82 -0
  66. package/src/server/npm-update.ts +100 -0
  67. package/src/server/reload.ts +5 -0
  68. package/src/server/room.ts +2 -0
  69. package/src/server/spend.ts +73 -9
  70. package/src/server/update-state.ts +257 -8
  71. package/src/server/updates.ts +268 -33
  72. package/src/server/zip.ts +163 -0
  73. package/types/pocket.d.ts +32 -0
  74. package/web/activity-fold.js +28 -0
  75. package/web/artifact-bridge.js +506 -82
  76. package/web/extension-ui.js +21 -1
  77. package/web/pip.js +46 -9
  78. package/web/sessions.js +1 -1
  79. package/web/sheets/appearance.js +10 -0
  80. package/web/sheets/viewers.js +26 -1
  81. package/web/style.css +11 -0
  82. package/web/taps.js +26 -0
  83. package/web/theme.js +6 -0
  84. package/web/transcript.js +19 -10
  85. package/src/server/http/public.ts +0 -30
@@ -7,16 +7,24 @@
7
7
  * when its lock file differs), notes the update in `.pocket-update/pending.json` (`update-state.ts`), puts the packages
8
8
  * in place, moves the checkout forward to the release's commit (never over a change of its own), and restarts. When
9
9
  * the new version starts, `recover` notes that it did; when it does not, the launcher goes back to the version before.
10
+ * Global npm installs use the registry's latest version with GitHub's notes. They stage a complete package beside the
11
+ * live one, then swap the package folders. Local installs and npx caches require their own npm command instead.
10
12
  * The `updates` extension module shows it to the owner, and checks and installs on a timer.
11
13
  */
12
14
  import { execFile } from "node:child_process";
13
- import { constants, existsSync, lstatSync, readFileSync } from "node:fs";
15
+ import { constants, lstatSync, readFileSync } from "node:fs";
14
16
  import { access, mkdir, realpath, rm, writeFile } from "node:fs/promises";
15
- import { dirname, isAbsolute, join, resolve, sep } from "node:path";
17
+ import { isAbsolute, join, resolve } from "node:path";
18
+ import { npmCommand, npmInstallKind, npmWritable, type InstallKind } from "./npm-install.ts";
16
19
  import { describe, HttpError } from "./errors.ts";
20
+ import { stageNpmUpdate } from "./npm-update.ts";
17
21
  import { git, GitError } from "./git.ts";
18
22
  import {
23
+ clearPending,
19
24
  finishPending,
25
+ finishNpmPending,
26
+ restorePackage,
27
+ swapInPackage,
20
28
  type PendingUpdate,
21
29
  readOutcome,
22
30
  readPending,
@@ -46,6 +54,8 @@ export type Release = {
46
54
  * could not read. An update to it is treated as one with a warning: the owner's word first, and no going back.
47
55
  */
48
56
  unread?: boolean;
57
+ /** The npm release's Node.js requirement, checked before staging. */
58
+ node?: string;
49
59
  };
50
60
 
51
61
  /** The release may need care: its notes warn, or Pi Pocket could not read them to know. */
@@ -56,6 +66,7 @@ export function needsCare(release: Release): boolean {
56
66
  export type UpdateStatus = {
57
67
  /** The running version, and the checkout's commit and branch (null when detached). */
58
68
  version: string;
69
+ installKind: InstallKind;
59
70
  commit?: string;
60
71
  branch?: string | null;
61
72
  /** Where releases come from. */
@@ -89,6 +100,8 @@ export interface UpdatesOptions {
89
100
  supervised: boolean;
90
101
  /** The launcher goes back to the version before when a new one does not start. */
91
102
  rollback: boolean;
103
+ /** An older launcher can undo git updates but does not know the sibling npm update state. */
104
+ npmRollback?: boolean;
92
105
  restart: () => void;
93
106
  /**
94
107
  * Stop reloading what changes on disk (web files, extension modules) just before git moves the checkout, so the
@@ -192,10 +205,11 @@ function releaseOf(tag: string, fields: Partial<Release>): Release | undefined {
192
205
  async function githubRelease(
193
206
  repository: { owner: string; name: string },
194
207
  signal?: AbortSignal,
208
+ tag?: string,
195
209
  ): Promise<Release | undefined> {
196
210
  const timeout = AbortSignal.timeout(20_000);
197
211
  const response = await fetch(
198
- `https://api.github.com/repos/${repository.owner}/${repository.name}/releases/latest`,
212
+ `https://api.github.com/repos/${repository.owner}/${repository.name}/releases/${tag === undefined ? "latest" : `tags/${encodeURIComponent(tag)}`}`,
199
213
  {
200
214
  headers: {
201
215
  accept: "application/vnd.github+json",
@@ -215,20 +229,84 @@ async function githubRelease(
215
229
  }
216
230
 
217
231
  const body = (await response.json()) as Record<string, unknown>;
218
- const tag = typeof body.tag_name === "string" ? body.tag_name : "";
219
- const page = `https://github.com/${repository.owner}/${repository.name}/releases/tag/${tag}`;
220
- const release = releaseOf(tag, {
221
- name: typeof body.name === "string" && body.name.trim() !== "" ? body.name.trim() : tag,
222
- notes: typeof body.body === "string" ? body.body.slice(0, MAX_NOTES) : "",
232
+ const notes = typeof body.body === "string" ? body.body : "";
233
+ const foundTag = typeof body.tag_name === "string" ? body.tag_name : "";
234
+ const page = `https://github.com/${repository.owner}/${repository.name}/releases/tag/${foundTag}`;
235
+ const release = releaseOf(foundTag, {
236
+ name:
237
+ typeof body.name === "string" && body.name.trim() !== "" ? body.name.trim() : foundTag,
238
+ notes: notes.slice(0, MAX_NOTES),
223
239
  url: page,
224
240
  ...(typeof body.published_at === "string" ? { publishedAt: body.published_at } : {}),
225
241
  });
226
242
 
227
243
  if (release === undefined) {
228
- throw new Error(`The newest release's tag is not a version: ${tag.slice(0, 40)}`);
244
+ throw new Error(`The release's tag is not a version: ${foundTag.slice(0, 40)}`);
229
245
  }
230
246
 
231
- return release;
247
+ // Read all notes for safety, even when only the first part is displayed.
248
+ return { ...release, warning: notesWarn(notes) };
249
+ }
250
+
251
+ /** npm's published latest version, with the notes for that exact version from GitHub. */
252
+ export async function npmRelease(
253
+ repository: { owner: string; name: string } | undefined,
254
+ signal?: AbortSignal,
255
+ ): Promise<Release> {
256
+ const timeout = AbortSignal.timeout(20_000);
257
+ const response = await fetch("https://registry.npmjs.org/pi-pocket", {
258
+ headers: {
259
+ accept: "application/vnd.npm.install-v1+json",
260
+ "user-agent": "pi-pocket-updates",
261
+ },
262
+ signal: signal === undefined ? timeout : AbortSignal.any([signal, timeout]),
263
+ });
264
+
265
+ if (!response.ok) {
266
+ throw new Error(`npm answered ${response.status} for the newest release`);
267
+ }
268
+
269
+ const body = (await response.json()) as {
270
+ "dist-tags"?: { latest?: unknown };
271
+ versions?: Record<string, { engines?: { node?: unknown } }>;
272
+ };
273
+ const version = body["dist-tags"]?.latest;
274
+
275
+ if (typeof version !== "string" || !TAG.test(version) || version.startsWith("v")) {
276
+ throw new Error("npm's latest dist-tag is not a release version.");
277
+ }
278
+
279
+ const manifest = body.versions?.[version];
280
+
281
+ if (manifest === undefined) {
282
+ throw new Error("npm's latest dist-tag has no published package metadata.");
283
+ }
284
+
285
+ const tag = `v${version}`;
286
+ const node = manifest.engines?.node;
287
+ const fields = typeof node === "string" ? { node } : {};
288
+
289
+ if (repository !== undefined) {
290
+ const notes = await githubRelease(repository, signal, tag).catch(() => undefined);
291
+
292
+ if (notes?.version === version) {
293
+ return { ...notes, ...fields };
294
+ }
295
+ }
296
+
297
+ return {
298
+ tag,
299
+ version,
300
+ name: tag,
301
+ warning: false,
302
+ unread: true,
303
+ ...(repository === undefined
304
+ ? {}
305
+ : {
306
+ url: `https://github.com/${repository.owner}/${repository.name}/releases/tag/${tag}`,
307
+ }),
308
+ ...fields,
309
+ };
232
310
  }
233
311
 
234
312
  /** The newest version tag of a repository anywhere git reaches, without notes. */
@@ -274,14 +352,6 @@ export function changedFiles(status: string): string[] {
274
352
  /** The oldest git updates work with: `--pathspec-from-file` came in 2.26. */
275
353
  const MIN_GIT = "2.26.0";
276
354
 
277
- /** The npm beside the Node.js that runs the server, else the one on `PATH`. */
278
- function npm(): { file: string; shell: boolean } {
279
- const windows = process.platform === "win32";
280
- const beside = join(dirname(process.execPath), windows ? "npm.cmd" : "npm");
281
-
282
- return { file: existsSync(beside) ? beside : windows ? "npm.cmd" : "npm", shell: windows };
283
- }
284
-
285
355
  /**
286
356
  * What a failed program said, in its last lines; npm's help for the command, which it prints after the error itself
287
357
  * (from the command's summary, the line before `Usage:`, on), is left out, so the cause shows.
@@ -346,12 +416,22 @@ export class Updates {
346
416
  readonly repository: string;
347
417
  readonly #listeners = new Set<(status: UpdateStatus) => void>();
348
418
  #latest: Release | undefined;
419
+ /** The last check asked npm, not GitHub. */
420
+ #fromNpm = false;
349
421
  #checkedAt: number | undefined;
350
422
  #error: string | undefined;
351
423
  #target: Target | undefined;
352
424
  #targetError: string | undefined;
353
425
  #checking: Promise<void> | undefined;
354
426
  #step: string | undefined;
427
+ #npmKind: Promise<InstallKind> | undefined;
428
+ #knownKind: InstallKind = "unknown";
429
+
430
+ async #installKind(local: Local): Promise<InstallKind> {
431
+ this.#knownKind = local.git ? "git" : await (this.#npmKind ??= npmInstallKind(this.#root));
432
+
433
+ return this.#knownKind;
434
+ }
355
435
 
356
436
  constructor(options: UpdatesOptions) {
357
437
  this.#options = options;
@@ -363,6 +443,12 @@ export class Updates {
363
443
  return (this.#options.now ?? Date.now)();
364
444
  }
365
445
 
446
+ #canRollBack(kind: InstallKind): boolean {
447
+ return (
448
+ this.#options.rollback && (kind !== "npm-global" || this.#options.npmRollback === true)
449
+ );
450
+ }
451
+
366
452
  /** Hear each change: a check, and each step of an update. Returns how to stop. */
367
453
  subscribe(listener: (status: UpdateStatus) => void): () => void {
368
454
  this.#listeners.add(listener);
@@ -548,6 +634,7 @@ export class Updates {
548
634
  if (this.#step !== undefined && this.#step !== "Checking") {
549
635
  return {
550
636
  version: this.#options.version,
637
+ installKind: this.#knownKind,
551
638
  repository: this.repository,
552
639
  ...(this.#latest === undefined ? {} : { latest: this.#latest }),
553
640
  ...(this.#checkedAt === undefined ? {} : { checkedAt: this.#checkedAt }),
@@ -558,11 +645,12 @@ export class Updates {
558
645
  busy: this.#options.busy(),
559
646
  step: this.#step,
560
647
  supervised: this.#options.supervised,
561
- rollback: this.#options.rollback,
648
+ rollback: this.#canRollBack(this.#knownKind),
562
649
  };
563
650
  }
564
651
 
565
652
  const local = await this.#local().catch((): Local => ({ git: false }));
653
+ const installKind = await this.#installKind(local);
566
654
  const latest = this.#latest;
567
655
  const busy = this.#options.busy();
568
656
  let available = latest !== undefined && newer(latest.version, this.#options.version);
@@ -577,13 +665,35 @@ export class Updates {
577
665
  );
578
666
  }
579
667
 
580
- const gitVersion = await this.#gitVersion();
668
+ const gitVersion = local.git ? await this.#gitVersion() : undefined;
669
+
670
+ if (installKind === "npm-global") {
671
+ packages = true;
672
+
673
+ if (!this.#canRollBack(installKind)) {
674
+ blockers.push(
675
+ "This launcher cannot recover npm updates. Quit Pi Pocket and start it again before updating from the app.",
676
+ );
677
+ }
678
+
679
+ if (!(await npmWritable(this.#root))) {
680
+ blockers.push(
681
+ `The server's user cannot write to ${this.#root} and its global node_modules folder. Update it as the user who owns it with \`npm install -g pi-pocket@latest\` (a system install may need sudo).`,
682
+ );
683
+ }
581
684
 
582
- if (!local.git) {
685
+ if (!nodeMeets(latest.node, process.versions.node)) {
686
+ blockers.push(
687
+ `${latest.tag} needs Node.js ${latest.node}, and this server runs ${process.versions.node}. Update Node.js first.`,
688
+ );
689
+ }
690
+ } else if (!local.git) {
583
691
  blockers.push(
584
- this.#root.split(sep).includes("node_modules")
585
- ? `This copy of Pi Pocket came from npm. When ${latest.tag} is on npm, update it with \`npm install -g pi-pocket@latest\` (or run \`npx pi-pocket@latest\`), then start it again.`
586
- : "This copy of Pi Pocket is not a git checkout. Update it the way you installed it.",
692
+ installKind === "npm-local"
693
+ ? "This is a local npm install. Update it with `npm install pi-pocket@latest` in that project, then start it again."
694
+ : installKind === "npx"
695
+ ? "This copy runs with npx. Stop it, then run `npx pi-pocket@latest`."
696
+ : "This copy of Pi Pocket is not a git checkout. Update it the way you installed it.",
587
697
  );
588
698
  } else if (gitVersion !== undefined && !atLeast(gitVersion, MIN_GIT)) {
589
699
  blockers.push(
@@ -641,7 +751,7 @@ export class Updates {
641
751
  }
642
752
  }
643
753
 
644
- if (readPending(this.#root) !== undefined && this.#step === undefined) {
754
+ if (readPending(this.#root) !== undefined) {
645
755
  blockers.push("An update is under way. Restart the server to finish it.");
646
756
  }
647
757
  }
@@ -663,7 +773,9 @@ export class Updates {
663
773
 
664
774
  if (packages) {
665
775
  cautions.push(
666
- "The update installs new packages (`npm ci`): this can take a few minutes.",
776
+ installKind === "npm-global"
777
+ ? "The update stages a complete npm install before switching versions: this can take a few minutes."
778
+ : "The update installs new packages (`npm ci`): this can take a few minutes.",
667
779
  );
668
780
  }
669
781
 
@@ -684,6 +796,7 @@ export class Updates {
684
796
 
685
797
  return {
686
798
  version: this.#options.version,
799
+ installKind,
687
800
  ...(local.git ? { commit: local.commit, branch: local.branch } : {}),
688
801
  repository: this.repository,
689
802
  ...(latest === undefined ? {} : { latest }),
@@ -701,7 +814,7 @@ export class Updates {
701
814
  return last === undefined ? {} : { last };
702
815
  })(),
703
816
  supervised: this.#options.supervised,
704
- rollback: this.#options.rollback,
817
+ rollback: this.#canRollBack(installKind),
705
818
  };
706
819
  }
707
820
 
@@ -728,6 +841,11 @@ export class Updates {
728
841
  }
729
842
  } catch (error) {
730
843
  this.#error = describe(error);
844
+
845
+ // npm is the only word on what an npm install can get: a version it no longer confirms is not offered.
846
+ if (this.#fromNpm) {
847
+ this.#latest = undefined;
848
+ }
731
849
  } finally {
732
850
  this.#checkedAt = this.#now;
733
851
  }
@@ -740,11 +858,20 @@ export class Updates {
740
858
  throw new Error(problem);
741
859
  }
742
860
 
861
+ const kind = await this.#installKind(await this.#local());
862
+
863
+ this.#fromNpm = kind === "npm-global" || kind === "npm-local" || kind === "npx";
864
+
743
865
  if (this.#options.releases !== undefined) {
744
866
  return this.#options.releases(signal);
745
867
  }
746
868
 
747
869
  const github = githubRepository(this.repository);
870
+
871
+ if (this.#fromNpm) {
872
+ return npmRelease(github, signal);
873
+ }
874
+
748
875
  let failed: unknown;
749
876
 
750
877
  if (github !== undefined) {
@@ -852,6 +979,10 @@ export class Updates {
852
979
  throw new HttpError(409, `An update is under way: ${this.#step.toLowerCase()}.`);
853
980
  }
854
981
 
982
+ if (readPending(this.#root) !== undefined) {
983
+ throw new HttpError(409, "An update is under way. Restart the server to finish it.");
984
+ }
985
+
855
986
  this.#setStep("Checking");
856
987
 
857
988
  try {
@@ -880,6 +1011,16 @@ export class Updates {
880
1011
  throw new HttpError(409, "Pi works in a session now: update when it is done.");
881
1012
  }
882
1013
 
1014
+ const stillWanted = () =>
1015
+ options.stillWanted?.() ??
1016
+ (this.#options.busy() > 0 && options.allowBusy !== true
1017
+ ? "Pi started to work in a session: update when it is done."
1018
+ : undefined);
1019
+
1020
+ if (status.installKind === "npm-global") {
1021
+ return await this.#applyNpm(latest, stillWanted, options.by);
1022
+ }
1023
+
883
1024
  if (
884
1025
  target === undefined ||
885
1026
  status.commit === undefined ||
@@ -914,11 +1055,7 @@ export class Updates {
914
1055
  }
915
1056
  }
916
1057
 
917
- const reason =
918
- options.stillWanted?.() ??
919
- (this.#options.busy() > 0 && options.allowBusy !== true
920
- ? "Pi started to work in a session: update when it is done."
921
- : undefined);
1058
+ const reason = stillWanted();
922
1059
 
923
1060
  if (reason !== undefined) {
924
1061
  throw new HttpError(409, reason);
@@ -1047,6 +1184,91 @@ export class Updates {
1047
1184
  }
1048
1185
  }
1049
1186
 
1187
+ /** Stage a self-contained global package, then move it into the unchanged global bin link's target. */
1188
+ async #applyNpm(
1189
+ latest: Release,
1190
+ stillWanted: () => string | undefined,
1191
+ by?: string,
1192
+ ): Promise<{ restarting: true; version: string }> {
1193
+ const pending: PendingUpdate = {
1194
+ v: 1,
1195
+ kind: "npm-global",
1196
+ tag: latest.tag,
1197
+ fromVersion: this.#options.version,
1198
+ toVersion: latest.version,
1199
+ from: this.#options.version,
1200
+ to: latest.version,
1201
+ branch: null,
1202
+ modules: false,
1203
+ oneWay: needsCare(latest),
1204
+ phase: "packages",
1205
+ at: this.#now,
1206
+ };
1207
+
1208
+ this.#options.log(
1209
+ `Updating Pi Pocket from ${pending.fromVersion} to ${pending.toVersion}${by === undefined ? "" : ` (${by})`}.`,
1210
+ );
1211
+ // Someone started to work while npm staged the package: nothing failed, so no outcome is noted (as for git),
1212
+ // and an install by itself tries this release again once the sessions are quiet.
1213
+ let declined = false;
1214
+
1215
+ writePending(this.#root, pending);
1216
+
1217
+ try {
1218
+ this.#setStep("Installing packages");
1219
+ await stageNpmUpdate(this.#root, latest.version);
1220
+ const reason = stillWanted();
1221
+
1222
+ if (reason !== undefined) {
1223
+ declined = true;
1224
+
1225
+ throw new HttpError(409, reason);
1226
+ }
1227
+
1228
+ this.#setStep(`Switching to ${latest.tag}`);
1229
+ this.#options.quiesce?.(true);
1230
+ swapInPackage(this.#root);
1231
+ } catch (error) {
1232
+ // No new server ran yet, so even a warning release can safely restore the package here.
1233
+ // If restoration fails, keep the pending state and stopped watchers for launcher recovery.
1234
+ try {
1235
+ if (!restorePackage(this.#root)) {
1236
+ throw new Error("The previous npm package is missing.");
1237
+ }
1238
+
1239
+ if (declined) {
1240
+ clearPending(this.#root);
1241
+ } else {
1242
+ finishPending(
1243
+ this.#root,
1244
+ pending,
1245
+ false,
1246
+ `The update to ${latest.version} failed, so Pi Pocket stays at ${pending.fromVersion}: ${describe(error)}`,
1247
+ this.#now,
1248
+ );
1249
+ }
1250
+
1251
+ this.#options.quiesce?.(false);
1252
+ } catch (restoreError) {
1253
+ throw new HttpError(
1254
+ 500,
1255
+ `The update stopped part way (${describe(error)}), and restoring the package failed (${describe(restoreError)}). Restart the server to recover the previous version.`,
1256
+ );
1257
+ }
1258
+
1259
+ if (error instanceof HttpError) {
1260
+ throw error;
1261
+ }
1262
+
1263
+ throw new HttpError(500, `The npm update failed: ${describe(error)}`);
1264
+ }
1265
+
1266
+ this.#setStep("Restarting");
1267
+ setTimeout(() => this.#options.restart(), 500);
1268
+
1269
+ return { restarting: true, version: latest.version };
1270
+ }
1271
+
1050
1272
  /** The release's packages, installed in `staging/` from its lock file, while the checkout stays as it is. */
1051
1273
  async #install(commit: string): Promise<void> {
1052
1274
  const { staging } = updatePaths(this.#root);
@@ -1061,7 +1283,7 @@ export class Updates {
1061
1283
  );
1062
1284
  }
1063
1285
 
1064
- const { file, shell } = npm();
1286
+ const { file, shell } = npmCommand();
1065
1287
 
1066
1288
  try {
1067
1289
  // Through a shell (Windows' npm.cmd), a path with spaces needs its quotes.
@@ -1096,6 +1318,19 @@ export class Updates {
1096
1318
  return undefined;
1097
1319
  }
1098
1320
 
1321
+ if (pending.kind === "npm-global") {
1322
+ const outcome = finishNpmPending(this.#root, pending, this.#now);
1323
+
1324
+ if (outcome.ok) {
1325
+ await rm(paths.previous, { recursive: true, force: true }).catch(() => {});
1326
+ }
1327
+
1328
+ await rm(paths.staging, { recursive: true, force: true });
1329
+ this.#options.log(outcome.message);
1330
+
1331
+ return outcome;
1332
+ }
1333
+
1099
1334
  const head = (await git(this.#root, ["rev-parse", "HEAD"]).catch(() => "")).trim();
1100
1335
  let outcome: UpdateOutcome;
1101
1336
  let restart = false;
@@ -0,0 +1,163 @@
1
+ // Minimal ZIP writer: builds an uncompressed-or-deflated ZIP32 archive in memory, with no dependencies.
2
+ import { deflateRawSync } from "node:zlib";
3
+
4
+ export interface ZipEntry {
5
+ name: string;
6
+ bytes: Buffer;
7
+ }
8
+
9
+ const MAX_ENTRIES = 65535;
10
+ const MAX_NAME_BYTES = 65535;
11
+ const UINT32_MAX = 0xffffffff;
12
+
13
+ function crc32(bytes: Buffer): number {
14
+ let crc = 0xffffffff;
15
+
16
+ for (let i = 0; i < bytes.length; i++) {
17
+ crc ^= bytes[i]!;
18
+
19
+ for (let bit = 0; bit < 8; bit++) {
20
+ crc = (crc >>> 1) ^ (0xedb88320 & -(crc & 1));
21
+ }
22
+ }
23
+
24
+ return ~crc >>> 0;
25
+ }
26
+
27
+ function validateName(name: string): void {
28
+ // The name length field counts UTF-8 bytes, and a NUL could hide a suffix from other tools.
29
+ const nameBytes = Buffer.byteLength(name, "utf8");
30
+
31
+ if (name.length === 0 || name.includes("\0")) {
32
+ throw new Error("zip: entry name is empty or has a NUL character");
33
+ }
34
+
35
+ if (nameBytes > MAX_NAME_BYTES) {
36
+ throw new Error(`zip: entry name too long in UTF-8 bytes: ${nameBytes}`);
37
+ }
38
+
39
+ if (name.startsWith("/") || name.startsWith("\\")) {
40
+ throw new Error(`zip: entry name is absolute: ${name}`);
41
+ }
42
+
43
+ if (/^[a-zA-Z]:/.test(name)) {
44
+ throw new Error(`zip: entry name has a drive letter: ${name}`);
45
+ }
46
+
47
+ const segments = name.split(/[/\\]/);
48
+
49
+ for (const segment of segments) {
50
+ if (segment === ".." || segment === ".") {
51
+ throw new Error(`zip: entry name has an unsafe path segment: ${name}`);
52
+ }
53
+ }
54
+ }
55
+
56
+ /**
57
+ * Builds a ZIP32 archive from the given entries. Names are UTF-8, paths are validated,
58
+ * duplicate names are rejected, and data is deflated when that is smaller than stored.
59
+ */
60
+ export function zip(entries: ZipEntry[]): Buffer {
61
+ if (entries.length > MAX_ENTRIES) {
62
+ throw new Error(`zip: too many entries: ${entries.length}`);
63
+ }
64
+
65
+ const seen = new Set<string>();
66
+
67
+ for (const entry of entries) {
68
+ validateName(entry.name);
69
+
70
+ if (seen.has(entry.name)) {
71
+ throw new Error(`zip: duplicate entry name: ${entry.name}`);
72
+ }
73
+
74
+ seen.add(entry.name);
75
+
76
+ if (entry.bytes.length > UINT32_MAX) {
77
+ throw new Error(`zip: entry too large for ZIP32: ${entry.name}`);
78
+ }
79
+ }
80
+
81
+ // Fixed DOS timestamp (1980-01-01 00:00:00) keeps output deterministic.
82
+ const dosTime = 0;
83
+ const dosDate = (1 << 5) | 1;
84
+
85
+ const localParts: Buffer[] = [];
86
+ const centralParts: Buffer[] = [];
87
+ let offset = 0;
88
+
89
+ for (const entry of entries) {
90
+ const nameBytes = Buffer.from(entry.name, "utf8");
91
+ const crc = crc32(entry.bytes);
92
+ const deflated = deflateRawSync(entry.bytes);
93
+ const useDeflate = deflated.length < entry.bytes.length;
94
+ const data = useDeflate ? deflated : entry.bytes;
95
+ const method = useDeflate ? 8 : 0;
96
+
97
+ if (offset + data.length > UINT32_MAX) {
98
+ throw new Error(`zip: archive exceeds ZIP32 bounds at entry: ${entry.name}`);
99
+ }
100
+
101
+ const local = Buffer.alloc(30);
102
+
103
+ local.writeUInt32LE(0x04034b50, 0);
104
+ local.writeUInt16LE(20, 4);
105
+ local.writeUInt16LE(0x0800, 6);
106
+ local.writeUInt16LE(method, 8);
107
+ local.writeUInt16LE(dosTime, 10);
108
+ local.writeUInt16LE(dosDate, 12);
109
+ local.writeUInt32LE(crc, 14);
110
+ local.writeUInt32LE(data.length, 18);
111
+ local.writeUInt32LE(entry.bytes.length, 22);
112
+ local.writeUInt16LE(nameBytes.length, 26);
113
+ local.writeUInt16LE(0, 28);
114
+
115
+ const central = Buffer.alloc(46);
116
+
117
+ central.writeUInt32LE(0x02014b50, 0);
118
+ central.writeUInt16LE(20, 4);
119
+ central.writeUInt16LE(20, 6);
120
+ central.writeUInt16LE(0x0800, 8);
121
+ central.writeUInt16LE(method, 10);
122
+ central.writeUInt16LE(dosTime, 12);
123
+ central.writeUInt16LE(dosDate, 14);
124
+ central.writeUInt32LE(crc, 16);
125
+ central.writeUInt32LE(data.length, 20);
126
+ central.writeUInt32LE(entry.bytes.length, 24);
127
+ central.writeUInt16LE(nameBytes.length, 28);
128
+ central.writeUInt16LE(0, 30);
129
+ central.writeUInt16LE(0, 32);
130
+ central.writeUInt16LE(0, 34);
131
+ central.writeUInt16LE(0, 36);
132
+ central.writeUInt32LE(0, 38);
133
+ central.writeUInt32LE(offset, 42);
134
+
135
+ localParts.push(local, nameBytes, data);
136
+ centralParts.push(central, nameBytes);
137
+ offset += local.length + nameBytes.length + data.length;
138
+ }
139
+
140
+ const centralStart = offset;
141
+ let centralSize = 0;
142
+
143
+ for (const part of centralParts) {
144
+ centralSize += part.length;
145
+ }
146
+
147
+ if (centralStart + centralSize > UINT32_MAX) {
148
+ throw new Error("zip: archive exceeds ZIP32 bounds in central directory");
149
+ }
150
+
151
+ const eocd = Buffer.alloc(22);
152
+
153
+ eocd.writeUInt32LE(0x06054b50, 0);
154
+ eocd.writeUInt16LE(0, 4);
155
+ eocd.writeUInt16LE(0, 6);
156
+ eocd.writeUInt16LE(entries.length, 8);
157
+ eocd.writeUInt16LE(entries.length, 10);
158
+ eocd.writeUInt32LE(centralSize, 12);
159
+ eocd.writeUInt32LE(centralStart, 16);
160
+ eocd.writeUInt16LE(0, 20);
161
+
162
+ return Buffer.concat([...localParts, ...centralParts, eocd]);
163
+ }