@zuke-build/cli 2.7.0 → 2.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -194,6 +194,9 @@ interface ProjectHost
194
194
  Remove a file.
195
195
  deno(denoArgs: string[], cwd: string): Promise<number>
196
196
  Run `deno <denoArgs>` in `cwd`, returning its exit code.
197
+ npm(npmArgs: string[], cwd: string): Promise<number>
198
+ Run `npm <npmArgs>` in `cwd`, a Node project's root, returning its exit
199
+ code.
197
200
  denoVersion(): string
198
201
  The version of the Deno that runs the command.
199
202
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zuke-build/cli",
3
- "version": "2.7.0",
3
+ "version": "2.8.0",
4
4
  "description": "The zuke command-line tool — scaffold a Zuke project with `zuke setup`, including a starter build, launchers, and tasks.",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/src/cache.d.ts CHANGED
@@ -8,6 +8,10 @@
8
8
  * moved. `--min-dep-age` passes Deno's `--minimum-dependency-age` through,
9
9
  * and only matters for a resolution the lock does not have yet.
10
10
  *
11
+ * In a project whose build runs on Node it runs `npm ci --ignore-scripts`,
12
+ * which installs exactly what `package-lock.json` pins, or `npm install
13
+ * --ignore-scripts` to write the first lock when there is none.
14
+ *
11
15
  * @module
12
16
  */
13
17
  import type { BuildProbe } from "./dispatch.ts";
package/src/cache.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // Copyright (c) 2026 the Zuke contributors
2
2
  // SPDX-License-Identifier: MIT
3
- import { installArgs, parseInstallFlags, projectLocation, } from "./project.js";
3
+ import { installArgs, nodeInstallFlags, parseInstallFlags, projectLocation, } from "./project.js";
4
4
  /**
5
5
  * Run `zuke cache <args>` from `cwd`, reporting through `log`, and return the
6
6
  * exit code.
@@ -10,7 +10,23 @@ import { installArgs, parseInstallFlags, projectLocation, } from "./project.js";
10
10
  */
11
11
  export async function runCache(args, log, host, paint, cwd, probe) {
12
12
  const flags = parseInstallFlags("cache", args);
13
- const { root, build } = await projectLocation(cwd, probe, "cache");
13
+ const { root, build, runtime } = await projectLocation(cwd, probe, "cache");
14
+ if (runtime === "node") {
15
+ nodeInstallFlags("cache", flags);
16
+ const locked = (await host.entry(`${root}/package-lock.json`)) !== "missing";
17
+ const npmArgs = [locked ? "ci" : "install", "--ignore-scripts"];
18
+ if (flags.dryRun) {
19
+ log(`Would cache the build's dependencies: npm ${npmArgs.join(" ")}`);
20
+ return 0;
21
+ }
22
+ const code = await host.npm(npmArgs, root);
23
+ if (code !== 0) {
24
+ log(paint.fail(`zuke cache: npm ${npmArgs[0]} exited ${code}.`));
25
+ return code;
26
+ }
27
+ log(paint.ok("Installed everything the build imports."));
28
+ return 0;
29
+ }
14
30
  const denoArgs = installArgs("cache", flags, host.denoVersion(), build);
15
31
  if (flags.dryRun) {
16
32
  log(`Would cache the build's dependencies: deno ${denoArgs.join(" ")}`);
@@ -43,7 +43,7 @@ export async function runDenoIsolated(denoArgs, prefix) {
43
43
  const cwd = await FileTasks.makeTempDirectory((s) => s.prefix(prefix));
44
44
  try {
45
45
  await FileTasks.writeText(`${cwd}/deno.json`, ISOLATED_DENO_CONFIG);
46
- const child = spawnDeno(denoArgs, {
46
+ const child = await spawnDeno(denoArgs, {
47
47
  cwd,
48
48
  stdin: "null",
49
49
  stdout: "piped",
@@ -112,4 +112,4 @@ export interface DenoSpawnOptions {
112
112
  *
113
113
  * @throws {DenoNotFoundError} when every candidate is missing.
114
114
  */
115
- export declare function spawnDeno(args: string[], options?: DenoSpawnOptions, candidates?: readonly string[]): ChildProcess;
115
+ export declare function spawnDeno(args: string[], options?: DenoSpawnOptions, candidates?: readonly string[]): Promise<ChildProcess>;
package/src/deno_path.js CHANGED
@@ -163,12 +163,12 @@ function cwdUsable(cwd) {
163
163
  *
164
164
  * @throws {DenoNotFoundError} when every candidate is missing.
165
165
  */
166
- export function spawnDeno(args, options = {}, candidates = denoCandidates()) {
166
+ export async function spawnDeno(args, options = {}, candidates = denoCandidates()) {
167
167
  const tried = [];
168
168
  for (const command of candidates) {
169
169
  tried.push(command);
170
170
  try {
171
- return ProcessTasks.spawn(command, (s) => {
171
+ const child = ProcessTasks.spawn(command, (s) => {
172
172
  s.args(...args);
173
173
  if (options.cwd !== undefined)
174
174
  s.cwd(options.cwd);
@@ -187,6 +187,11 @@ export function spawnDeno(args, options = {}, candidates = denoCandidates()) {
187
187
  s.env(name, value);
188
188
  return s;
189
189
  });
190
+ // On Node a command that cannot start throws nothing: the child has no
191
+ // process, and its status rejects with why.
192
+ if (child.pid === -1)
193
+ await child.status;
194
+ return child;
190
195
  }
191
196
  catch (error) {
192
197
  // Not installed here; the next candidate may be. Anything else — a
@@ -11,6 +11,12 @@
11
11
  * `--minimum-dependency-age` flag. Both honour the project's own
12
12
  * `minimumDependencyAge` in `deno.json`, which Deno reads for them.
13
13
  *
14
+ * In a project whose build runs on Node they run `npm install` and
15
+ * `npm uninstall` instead, with `--ignore-scripts`, and change `package.json`:
16
+ * a bare name becomes the alias `@zuke/<name>` for `npm:@zuke-build/<name>@^1`,
17
+ * as `zuke setup --runtime node` writes it, and an `npm:` specifier passes
18
+ * through. A JSR package has no npm install, so it is refused there.
19
+ *
14
20
  * @module
15
21
  */
16
22
  import type { BuildProbe } from "./dispatch.ts";
@@ -27,6 +33,17 @@ export type DependencyCommand = "add" | "remove";
27
33
  * read, or a name no registry accepts — rather than handing it to Deno.
28
34
  */
29
35
  export declare function dependencySpecifier(command: DependencyCommand, name: string): string;
36
+ /**
37
+ * The `npm install` / `npm uninstall` operand for `specifier`, one
38
+ * {@link dependencySpecifier} returned: a Zuke package becomes its
39
+ * `@zuke/<name>` alias (to add) or that alias (to remove), and an `npm:`
40
+ * specifier is npm's own, without the prefix. A removal names the package
41
+ * alone, as `npm uninstall` takes it.
42
+ *
43
+ * @throws {Error} naming `command` on any other JSR package, which npm
44
+ * cannot install.
45
+ */
46
+ export declare function npmOperand(command: DependencyCommand, specifier: string): string;
30
47
  /**
31
48
  * Parse `zuke add`'s or `zuke remove`'s arguments: one or more packages, and
32
49
  * `--dry-run`.
@@ -1,6 +1,7 @@
1
1
  // Copyright (c) 2026 the Zuke contributors
2
2
  // SPDX-License-Identifier: MIT
3
3
  import { projectLocation } from "./project.js";
4
+ import { zukeNpmDependency } from "./starter.js";
4
5
  import { projectConfigText } from "./version_report.js";
5
6
  /** A bare Zuke package name, as `zuke add docker` takes it. */
6
7
  const BARE_NAME = /^[a-z0-9][a-z0-9-]*$/;
@@ -27,6 +28,37 @@ export function dependencySpecifier(command, name) {
27
28
  "(docker), a scoped JSR name (@scope/name), or a jsr: or npm: " +
28
29
  "specifier.");
29
30
  }
31
+ /** The `@zuke/<name>` a Zuke package's specifier names, if it is one. */
32
+ const ZUKE_JSR = /^jsr:@zuke\/([a-z0-9][a-z0-9-]*)$/;
33
+ /**
34
+ * The `npm install` / `npm uninstall` operand for `specifier`, one
35
+ * {@link dependencySpecifier} returned: a Zuke package becomes its
36
+ * `@zuke/<name>` alias (to add) or that alias (to remove), and an `npm:`
37
+ * specifier is npm's own, without the prefix. A removal names the package
38
+ * alone, as `npm uninstall` takes it.
39
+ *
40
+ * @throws {Error} naming `command` on any other JSR package, which npm
41
+ * cannot install.
42
+ */
43
+ export function npmOperand(command, specifier) {
44
+ const zuke = ZUKE_JSR.exec(specifier)?.[1];
45
+ if (zuke !== undefined) {
46
+ return command === "add"
47
+ ? `@zuke/${zuke}@${zukeNpmDependency(zuke)}`
48
+ : `@zuke/${zuke}`;
49
+ }
50
+ if (specifier.startsWith("npm:")) {
51
+ const spec = specifier.slice("npm:".length);
52
+ if (command === "add")
53
+ return spec;
54
+ // `name@range` names `name`; a scoped name's own `@` comes first.
55
+ const at = spec.indexOf("@", 1);
56
+ return at === -1 ? spec : spec.slice(0, at);
57
+ }
58
+ throw new Error(`zuke ${command}: ${specifier} is a JSR package, and this project's build ` +
59
+ "runs on Node, which installs from npm. Pass its npm name as " +
60
+ "npm:<name>.");
61
+ }
30
62
  /**
31
63
  * Parse `zuke add`'s or `zuke remove`'s arguments: one or more packages, and
32
64
  * `--dry-run`.
@@ -55,26 +87,43 @@ export function parseDependencyArgs(command, args) {
55
87
  */
56
88
  export async function runDependencies(command, args, log, host, paint, cwd, probe) {
57
89
  const { specifiers, dryRun } = parseDependencyArgs(command, args);
58
- const { root } = await projectLocation(cwd, probe, command);
59
- const denoArgs = [command, ...specifiers];
90
+ const { root, runtime } = await projectLocation(cwd, probe, command);
91
+ const node = runtime === "node";
92
+ const tool = node ? "npm" : "deno";
93
+ const toolArgs = node
94
+ ? [
95
+ command === "add" ? "install" : "uninstall",
96
+ "--ignore-scripts",
97
+ ...specifiers.map((specifier) => npmOperand(command, specifier)),
98
+ ]
99
+ : [command, ...specifiers];
60
100
  if (dryRun) {
61
- log(`Would run in ${root}: deno ${denoArgs.join(" ")}`);
101
+ log(`Would run in ${root}: ${tool} ${toolArgs.join(" ")}`);
62
102
  return 0;
63
103
  }
64
- const config = () => projectConfigText((path) => host.readText(path), root);
104
+ const manifest = node ? "package.json" : "deno.json";
105
+ // What the report names: the packages as the manifest spells them.
106
+ const named = (node
107
+ ? specifiers.map((specifier) => npmOperand("remove", specifier))
108
+ : specifiers).join(", ");
109
+ const config = node
110
+ ? () => host.readText(`${root}/package.json`).catch(() => undefined)
111
+ : () => projectConfigText((path) => host.readText(path), root);
65
112
  const before = await config();
66
- const code = await host.deno(denoArgs, root);
113
+ const code = node
114
+ ? await host.npm(toolArgs, root)
115
+ : await host.deno(toolArgs, root);
67
116
  if (code !== 0) {
68
- log(paint.fail(`zuke ${command}: deno ${command} exited ${code}.`));
117
+ log(paint.fail(`zuke ${command}: ${tool} ${toolArgs[0]} exited ${code}.`));
69
118
  return code;
70
119
  }
71
- // `deno remove` exits 0 when it finds nothing to remove; an unchanged
72
- // config is how that shows.
120
+ // `deno remove` and `npm uninstall` exit 0 when they find nothing to
121
+ // remove; an unchanged manifest is how that shows.
73
122
  if (command === "remove" && (await config()) === before) {
74
- log(paint.fail(`zuke remove: nothing was removed; this project's deno.json has no ` +
75
- `${specifiers.join(", ")}.`));
123
+ log(paint.fail(`zuke remove: nothing was removed; this project's ${manifest} has no ` +
124
+ `${named}.`));
76
125
  return 1;
77
126
  }
78
- log(paint.ok(`${command === "add" ? "Added" : "Removed"} ${specifiers.join(", ")}.`));
127
+ log(paint.ok(`${command === "add" ? "Added" : "Removed"} ${named}.`));
79
128
  return 0;
80
129
  }
package/src/dispatch.js CHANGED
@@ -518,7 +518,7 @@ function signalPlan(child) {
518
518
  */
519
519
  export const defaultBuildRunner = async (root, args, program, env) => {
520
520
  const child = program === undefined
521
- ? spawnDeno(args, {
521
+ ? await spawnDeno(args, {
522
522
  cwd: root,
523
523
  stdin: "inherit",
524
524
  stdout: "inherit",
@@ -0,0 +1,16 @@
1
+ import { type DenoHost } from "./deno_path.ts";
2
+ /**
3
+ * The npm executables to try, in order: the bare name for `PATH`, then the
4
+ * one beside the pinned Node the launchers cache. That one is left out when
5
+ * the environment names no absolute directory to find it in.
6
+ */
7
+ export declare function npmCandidates(host?: DenoHost): string[];
8
+ /**
9
+ * Run `npm <args>` in `cwd` with the terminal's output, trying each candidate
10
+ * in order and skipping the ones that are not installed, and return its exit
11
+ * code. The cached npm runs with its Node first on `PATH`, which its script
12
+ * needs to start.
13
+ *
14
+ * @throws {Error} naming every candidate tried when none is installed.
15
+ */
16
+ export declare function runNpm(args: string[], cwd: string, candidates?: readonly string[]): Promise<number>;
@@ -0,0 +1,78 @@
1
+ // Copyright (c) 2026 the Zuke contributors
2
+ // SPDX-License-Identifier: MIT
3
+ /**
4
+ * Finding the npm that changes a Node project's dependencies.
5
+ *
6
+ * `zuke add`, `remove`, `cache` and `relock` run npm in a project whose
7
+ * `zuke.json` says `"runtime": "node"`. The order mirrors the project's own
8
+ * launchers: whatever `PATH` resolves first, then the pinned Node they
9
+ * download into `ZUKE_NODE_HOME` (`~/.zuke/node` by default), so a project
10
+ * whose only Node is the one `./zuke` fetched still works. As in
11
+ * `deno_path.ts`, a candidate is tried by spawning it, which leaves `PATHEXT`
12
+ * (`npm.cmd` on Windows) to the OS.
13
+ *
14
+ * @module
15
+ */
16
+ import { absolutePath, FileTasks, ProcessTasks } from "@zuke/core";
17
+ import { defaultDenoHost, firstSet, pathWithDeno, } from "./deno_path.js";
18
+ import { NODE_PIN } from "./node_pin.js";
19
+ /**
20
+ * The npm executables to try, in order: the bare name for `PATH`, then the
21
+ * one beside the pinned Node the launchers cache. That one is left out when
22
+ * the environment names no absolute directory to find it in.
23
+ */
24
+ export function npmCandidates(host = defaultDenoHost) {
25
+ const candidates = ["npm"];
26
+ const explicit = firstSet(host, "ZUKE_NODE_HOME");
27
+ const home = firstSet(host, "HOME", "USERPROFILE");
28
+ try {
29
+ const root = explicit !== undefined
30
+ ? absolutePath(explicit)
31
+ : home !== undefined
32
+ ? absolutePath(home)(".zuke", "node")
33
+ : undefined;
34
+ if (root !== undefined) {
35
+ const release = root(`v${NODE_PIN.version}`);
36
+ candidates.push(host.windows() ? release("npm.cmd").path : release("bin", "npm").path);
37
+ }
38
+ }
39
+ catch {
40
+ // A relative ZUKE_NODE_HOME or HOME names no place to look.
41
+ }
42
+ return candidates;
43
+ }
44
+ /**
45
+ * Run `npm <args>` in `cwd` with the terminal's output, trying each candidate
46
+ * in order and skipping the ones that are not installed, and return its exit
47
+ * code. The cached npm runs with its Node first on `PATH`, which its script
48
+ * needs to start.
49
+ *
50
+ * @throws {Error} naming every candidate tried when none is installed.
51
+ */
52
+ export async function runNpm(args, cwd, candidates = npmCandidates()) {
53
+ for (const command of candidates) {
54
+ // A path that is not there is skipped before spawning: Windows reports
55
+ // spawning one as an error that is not a plain "not found".
56
+ const isPath = command.includes("/") || command.includes("\\");
57
+ if (isPath && !(await FileTasks.exists(command)))
58
+ continue;
59
+ try {
60
+ const out = await ProcessTasks.run(command, (s) => {
61
+ s.args(...args).cwd(cwd).stdin("null").stdout("inherit")
62
+ .stderr("inherit");
63
+ for (const [name, value] of Object.entries(pathWithDeno(command))) {
64
+ s.env(name, value);
65
+ }
66
+ return s;
67
+ });
68
+ return out.code;
69
+ }
70
+ catch (error) {
71
+ if (!FileTasks.isNotFound(error))
72
+ throw error;
73
+ }
74
+ }
75
+ throw new Error(`zuke: this is a Node project, and no npm was found — tried ` +
76
+ `${candidates.join(", ")}. Run the project's ./zuke once, which ` +
77
+ `installs a pinned Node, or put Node ${NODE_PIN.version.split(".")[0]} or newer on PATH.`);
78
+ }
package/src/project.d.ts CHANGED
@@ -18,10 +18,15 @@ export interface ProjectHost {
18
18
  remove(path: string): Promise<void>;
19
19
  /** Run `deno <denoArgs>` in `cwd`, returning its exit code. */
20
20
  deno(denoArgs: string[], cwd: string): Promise<number>;
21
+ /**
22
+ * Run `npm <npmArgs>` in `cwd`, a Node project's root, returning its exit
23
+ * code.
24
+ */
25
+ npm(npmArgs: string[], cwd: string): Promise<number>;
21
26
  /** The version of the Deno that runs the command. */
22
27
  denoVersion(): string;
23
28
  }
24
- /** The real {@link ProjectHost}: the file system, and `deno` in the root. */
29
+ /** The real {@link ProjectHost}: the file system, and `deno` or `npm` in the root. */
25
30
  export declare const defaultProjectHost: ProjectHost;
26
31
  /**
27
32
  * The project at or above `cwd`, through the trust gate: its root, and the
@@ -67,3 +72,11 @@ export declare function parseInstallFlags(command: string, args: readonly string
67
72
  * `denoVersion` does not accept the flag.
68
73
  */
69
74
  export declare function installArgs(command: string, flags: InstallFlags, denoVersion: string, build: string): string[];
75
+ /**
76
+ * Refuse what `flags` asks of npm that it cannot do: a Node project's
77
+ * dependencies are its `package.json`'s, so there are no further entrypoints
78
+ * to resolve, and `--min-dep-age` is Deno's.
79
+ *
80
+ * @throws {Error} naming `command` when either was given.
81
+ */
82
+ export declare function nodeInstallFlags(command: string, flags: InstallFlags): void;
package/src/project.js CHANGED
@@ -2,8 +2,9 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
  /**
4
4
  * What the global CLI's project commands share: `relock`, `cache`, `add` and
5
- * `remove` each run a `deno` command in the project root, so that working on
6
- * a Zuke project needs only `zuke`.
5
+ * `remove` each run a `deno` command in the project root — or an `npm` one,
6
+ * in a project whose build runs on Node — so that working on a Zuke project
7
+ * needs only `zuke`.
7
8
  *
8
9
  * They are the CLI's own rather than the build's because they must work
9
10
  * whatever core the project is on — including one too old, or too broken, to
@@ -14,9 +15,10 @@
14
15
  */
15
16
  import { FileTasks, RuntimeTasks } from "@zuke/core";
16
17
  import { spawnDeno } from "./deno_path.js";
18
+ import { runNpm } from "./npm_path.js";
17
19
  import { locateBuild, } from "./dispatch.js";
18
20
  import { acceptsMinimumDependencyAge } from "./upgrade.js";
19
- /** The real {@link ProjectHost}: the file system, and `deno` in the root. */
21
+ /** The real {@link ProjectHost}: the file system, and `deno` or `npm` in the root. */
20
22
  export const defaultProjectHost = {
21
23
  entry: async (path) => {
22
24
  try {
@@ -34,7 +36,7 @@ export const defaultProjectHost = {
34
36
  await FileTasks.remove(path);
35
37
  },
36
38
  deno: async (denoArgs, cwd) => {
37
- const child = spawnDeno(denoArgs, {
39
+ const child = await spawnDeno(denoArgs, {
38
40
  cwd,
39
41
  stdin: "null",
40
42
  stdout: "inherit",
@@ -42,6 +44,7 @@ export const defaultProjectHost = {
42
44
  });
43
45
  return (await child.status).code;
44
46
  },
47
+ npm: (npmArgs, cwd) => runNpm(npmArgs, cwd),
45
48
  // The cli runs on Deno, so the runtime is the Deno that runs the command.
46
49
  denoVersion: () => RuntimeTasks.facts().version,
47
50
  };
@@ -130,3 +133,17 @@ export function installArgs(command, flags, denoVersion, build) {
130
133
  }
131
134
  return [...args, `--minimum-dependency-age=${flags.minDepAge}`];
132
135
  }
136
+ /**
137
+ * Refuse what `flags` asks of npm that it cannot do: a Node project's
138
+ * dependencies are its `package.json`'s, so there are no further entrypoints
139
+ * to resolve, and `--min-dep-age` is Deno's.
140
+ *
141
+ * @throws {Error} naming `command` when either was given.
142
+ */
143
+ export function nodeInstallFlags(command, flags) {
144
+ if (flags.entrypoints.length > 0 || flags.minDepAge !== undefined) {
145
+ throw new Error(`zuke ${command}: this project's build runs on Node, whose ` +
146
+ "dependencies are package.json's: it takes only --dry-run, not " +
147
+ "entrypoints or --min-dep-age.");
148
+ }
149
+ }
package/src/relock.js CHANGED
@@ -27,10 +27,15 @@
27
27
  * matters on Deno 2.9, which by default skips releases from the last day or
28
28
  * so: `--min-dep-age 0` resolves the newest published versions.
29
29
  *
30
+ * In a project whose build runs on Node it regenerates `package-lock.json`
31
+ * instead, behind the same backup and emptied in place the same way, and
32
+ * `npm install --package-lock-only --ignore-scripts` resolves `package.json`
33
+ * afresh into it, installing nothing.
34
+ *
30
35
  * @module
31
36
  */
32
37
  import { lockedJsrSpecifiers } from "@zuke/core";
33
- import { installArgs, parseInstallFlags, projectLocation, } from "./project.js";
38
+ import { installArgs, nodeInstallFlags, parseInstallFlags, projectLocation, } from "./project.js";
34
39
  import { lockedCoreVersions, projectConfigText, projectLockPath, } from "./version_report.js";
35
40
  /** The suffix of the backup a run keeps while the lock is being rewritten. */
36
41
  const BACKUP_SUFFIX = ".relock-backup";
@@ -54,66 +59,59 @@ function olderThan(a, b) {
54
59
  }
55
60
  return false;
56
61
  }
57
- /** The emptied lock a run resolves into: `before`'s format version, no entries. */
58
- function emptied(before) {
59
- let version = "5";
62
+ /** The lock formats `relock` empties: Deno's `deno.lock`, npm's `package-lock.json`. */
63
+ const LOCK_FORMATS = {
64
+ deno: { key: "version", fallback: "5", entries: {} },
65
+ npm: { key: "lockfileVersion", fallback: 3, entries: { packages: {} } },
66
+ };
67
+ /**
68
+ * The emptied lock a run resolves into: `before`'s format version, no
69
+ * entries. It is written over the lock in place rather than the lock being
70
+ * removed, so a lock that is a symlink to a shared file stays one.
71
+ */
72
+ function emptied(before, kind) {
73
+ const format = LOCK_FORMATS[kind];
74
+ let version = format.fallback;
60
75
  try {
61
76
  const parsed = JSON.parse(before);
62
77
  if (parsed !== null && typeof parsed === "object") {
63
- version = Reflect.get(parsed, "version") ?? version;
78
+ version = Reflect.get(parsed, format.key) ?? version;
64
79
  }
65
80
  }
66
81
  catch {
67
- // An unreadable lock is still replaced; the default format is Deno 2's.
82
+ // An unreadable lock is still replaced, in the current default format.
68
83
  }
69
- return `${JSON.stringify({ version }, null, 2)}\n`;
70
- }
71
- /** The JSR package names `lock` resolves. */
72
- function jsrPackages(lock) {
73
- return new Set(lockedJsrSpecifiers(lock).map((entry) => entry.name));
84
+ return `${JSON.stringify({ [format.key]: version, ...format.entries }, null, 2)}\n`;
74
85
  }
75
86
  /**
76
- * Run `zuke relock <args>` from `cwd`, reporting through `log`, and return
77
- * the exit code.
87
+ * Refuse to start while `backup`, a lock an earlier run set aside, is still
88
+ * there: it is the only copy of the lock as it was.
78
89
  *
79
- * @throws {Error} with a message for the user when the request cannot be
80
- * carried out. `main` prints the message and exits 1.
90
+ * @throws {Error} saying how to restore or drop it.
81
91
  */
82
- export async function runRelock(args, log, host, paint, cwd, probe) {
83
- const flags = parseInstallFlags("relock", args);
84
- const { root, build } = await projectLocation(cwd, probe, "relock");
85
- const lockPath = projectLockPath(root, await projectConfigText((path) => host.readText(path), root));
86
- if (lockPath === null) {
87
- throw new Error("zuke relock: this project's deno.json disables its lock, or could " +
88
- "not be read as JSON, so there is no lock to regenerate.");
89
- }
90
- // Regenerating is the point, so a lock the config freezes is not a reason
91
- // to refuse the write.
92
- const denoArgs = [
93
- ...installArgs("relock", flags, host.denoVersion(), build),
94
- "--frozen=false",
95
- ];
96
- const name = lockPath.startsWith(`${root}/`)
97
- ? lockPath.slice(root.length + 1)
98
- : lockPath;
99
- if (flags.dryRun) {
100
- log(`Would regenerate ${name}: deno ${denoArgs.join(" ")}`);
101
- return 0;
102
- }
103
- const backup = `${lockPath}${BACKUP_SUFFIX}`;
104
- let leftover = true;
92
+ async function refuseLeftover(host, backup, name) {
105
93
  try {
106
94
  await host.readText(backup);
107
95
  }
108
96
  catch {
109
- leftover = false;
110
- }
111
- if (leftover) {
112
- throw new Error(`zuke relock: ${backup} is left from a relock that did not finish. ` +
113
- `It is the lock as it was before that run: move it back over ${name} ` +
114
- "to restore it, or delete it to keep the lock as it is, then run " +
115
- "zuke relock again.");
97
+ return;
116
98
  }
99
+ throw new Error(`zuke relock: ${backup} is left from a relock that did not finish. ` +
100
+ `It is the lock as it was before that run: move it back over ${name} ` +
101
+ "to restore it, or delete it to keep the lock as it is, then run " +
102
+ "zuke relock again.");
103
+ }
104
+ /**
105
+ * Regenerate the lock at `lockPath` behind a backup, the one sequence both
106
+ * runtimes share: refuse to start over a backup an earlier run left, set the
107
+ * lock aside, empty it in place in format `kind` (written through, so a link
108
+ * stays one), and run `regenerate`. Its result is kept only when it exits 0
109
+ * and writes a lock that is not still the emptied one; otherwise the old text
110
+ * goes back the same way. The backup is removed either way, and on a throw.
111
+ */
112
+ async function regenerateLock(host, lockPath, name, kind, log, regenerate) {
113
+ const backup = `${lockPath}${BACKUP_SUFFIX}`;
114
+ await refuseLeftover(host, backup, name);
117
115
  let before;
118
116
  try {
119
117
  before = await host.readText(lockPath);
@@ -123,21 +121,22 @@ export async function runRelock(args, log, host, paint, cwd, probe) {
123
121
  }
124
122
  if (before !== undefined) {
125
123
  await host.writeText(backup, before);
126
- await host.writeText(lockPath, emptied(before));
124
+ await host.writeText(lockPath, emptied(before, kind));
127
125
  }
128
- const restore = async () => {
129
- if (before !== undefined)
126
+ const settle = async (keep) => {
127
+ if (before === undefined)
128
+ return;
129
+ if (!keep)
130
130
  await host.writeText(lockPath, before);
131
+ await host.remove(backup);
131
132
  };
132
133
  log(`Regenerating ${name}…`);
133
134
  let code;
134
135
  try {
135
- code = await host.deno(denoArgs, root);
136
+ code = await regenerate();
136
137
  }
137
138
  catch (error) {
138
- await restore();
139
- if (before !== undefined)
140
- await host.remove(backup);
139
+ await settle(false);
141
140
  throw error;
142
141
  }
143
142
  let after;
@@ -146,21 +145,79 @@ export async function runRelock(args, log, host, paint, cwd, probe) {
146
145
  after = await host.readText(lockPath);
147
146
  }
148
147
  catch {
149
- // Reported below.
148
+ // Reported by the caller, as no lock written.
150
149
  }
151
150
  }
152
- if (code !== 0 || after === undefined || after === emptied(before ?? "")) {
153
- await restore();
154
- if (before !== undefined)
155
- await host.remove(backup);
151
+ const fresh = code === 0 && after !== undefined &&
152
+ after !== emptied(before ?? "", kind);
153
+ await settle(fresh);
154
+ return { code, before, after: fresh ? after : undefined };
155
+ }
156
+ /**
157
+ * Regenerate a Node project's `package-lock.json` in `root`, resolving
158
+ * `package.json` afresh with npm behind {@link regenerateLock}'s backup.
159
+ */
160
+ async function relockNode(flags, root, log, host, paint) {
161
+ nodeInstallFlags("relock", flags);
162
+ const name = "package-lock.json";
163
+ const npmArgs = ["install", "--package-lock-only", "--ignore-scripts"];
164
+ if (flags.dryRun) {
165
+ log(`Would regenerate ${name}: npm ${npmArgs.join(" ")}`);
166
+ return 0;
167
+ }
168
+ const { code, before, after } = await regenerateLock(host, `${root}/${name}`, name, "npm", log, () => host.npm(npmArgs, root));
169
+ if (after === undefined) {
170
+ log(paint.fail(code !== 0
171
+ ? `zuke relock: npm install exited ${code}; ${name} is unchanged.`
172
+ : `zuke relock: npm install wrote no ${name}${before === undefined ? "" : "; the old one is restored"}.`));
173
+ return code !== 0 ? code : 1;
174
+ }
175
+ log(paint.ok(`Regenerated ${name}.`));
176
+ return 0;
177
+ }
178
+ /** The JSR package names `lock` resolves. */
179
+ function jsrPackages(lock) {
180
+ return new Set(lockedJsrSpecifiers(lock).map((entry) => entry.name));
181
+ }
182
+ /**
183
+ * Run `zuke relock <args>` from `cwd`, reporting through `log`, and return
184
+ * the exit code.
185
+ *
186
+ * @throws {Error} with a message for the user when the request cannot be
187
+ * carried out. `main` prints the message and exits 1.
188
+ */
189
+ export async function runRelock(args, log, host, paint, cwd, probe) {
190
+ const flags = parseInstallFlags("relock", args);
191
+ const { root, build, runtime } = await projectLocation(cwd, probe, "relock");
192
+ if (runtime === "node") {
193
+ return await relockNode(flags, root, log, host, paint);
194
+ }
195
+ const lockPath = projectLockPath(root, await projectConfigText((path) => host.readText(path), root));
196
+ if (lockPath === null) {
197
+ throw new Error("zuke relock: this project's deno.json disables its lock, or could " +
198
+ "not be read as JSON, so there is no lock to regenerate.");
199
+ }
200
+ // Regenerating is the point, so a lock the config freezes is not a reason
201
+ // to refuse the write.
202
+ const denoArgs = [
203
+ ...installArgs("relock", flags, host.denoVersion(), build),
204
+ "--frozen=false",
205
+ ];
206
+ const name = lockPath.startsWith(`${root}/`)
207
+ ? lockPath.slice(root.length + 1)
208
+ : lockPath;
209
+ if (flags.dryRun) {
210
+ log(`Would regenerate ${name}: deno ${denoArgs.join(" ")}`);
211
+ return 0;
212
+ }
213
+ const { code, before, after } = await regenerateLock(host, lockPath, name, "deno", log, () => host.deno(denoArgs, root));
214
+ if (after === undefined) {
156
215
  log(paint.fail(code !== 0
157
216
  ? `zuke relock: deno install exited ${code}; ${name} is unchanged.`
158
217
  : `zuke relock: deno install wrote no ${name}${before === undefined ? "" : "; the old one is restored"}. In a workspace member, Deno keeps the lock at the workspace ` +
159
218
  "root: run zuke relock there."));
160
219
  return code !== 0 ? code : 1;
161
220
  }
162
- if (before !== undefined)
163
- await host.remove(backup);
164
221
  const was = lockedCoreVersions(before ?? "");
165
222
  const now = lockedCoreVersions(after);
166
223
  log(paint.ok(`Regenerated ${name}: @zuke/core ${shown(was) === shown(now) ? shown(now) : `${shown(was)} → ${shown(now)}`}`));
package/src/setup.js CHANGED
@@ -191,6 +191,11 @@ export const defaultHost = {
191
191
  // pre-write check. The temporary name is created exclusively, so it cannot
192
192
  // itself be a link someone left waiting.
193
193
  const temp = `${path}.zuke-${crypto.randomUUID().slice(0, 8)}.tmp`;
194
+ // `--dir` may name a directory that is not there yet; every path written
195
+ // is that directory joined with a file name.
196
+ const parent = path.lastIndexOf("/");
197
+ if (parent > 0)
198
+ await FileTasks.createDirectory(path.slice(0, parent));
194
199
  try {
195
200
  await FileTasks.writeText(temp, content, (s) => s.createNew());
196
201
  await FileTasks.move(temp, path);
package/src/version.js CHANGED
@@ -10,4 +10,4 @@
10
10
  * reads it — the annotation is what keeps that from mattering if it is ever
11
11
  * exported.
12
12
  */
13
- export const VERSION = "2.7.0"; // x-release-please-version
13
+ export const VERSION = "2.8.0"; // x-release-please-version