@zuke-build/cli 0.0.0-stage → 2.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.
Files changed (68) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +343 -2
  3. package/mod.d.ts +99 -0
  4. package/mod.js +893 -0
  5. package/package.json +35 -4
  6. package/src/binary_launcher.d.ts +49 -0
  7. package/src/binary_launcher.js +327 -0
  8. package/src/binary_pin.d.ts +47 -0
  9. package/src/binary_pin.js +117 -0
  10. package/src/build_file.d.ts +25 -0
  11. package/src/build_file.js +65 -0
  12. package/src/cache.d.ts +23 -0
  13. package/src/cache.js +26 -0
  14. package/src/deno_isolated.d.ts +14 -0
  15. package/src/deno_isolated.js +70 -0
  16. package/src/deno_path.d.ts +115 -0
  17. package/src/deno_path.js +205 -0
  18. package/src/deno_pin.d.ts +37 -0
  19. package/src/deno_pin.js +32 -0
  20. package/src/dependencies.d.ts +48 -0
  21. package/src/dependencies.js +80 -0
  22. package/src/dispatch.d.ts +220 -0
  23. package/src/dispatch.js +538 -0
  24. package/src/embedded_engine.d.ts +28 -0
  25. package/src/embedded_engine.js +21 -0
  26. package/src/engine_pin.d.ts +56 -0
  27. package/src/engine_pin.js +196 -0
  28. package/src/fs.d.ts +14 -0
  29. package/src/fs.js +25 -0
  30. package/src/import.d.ts +132 -0
  31. package/src/import.js +289 -0
  32. package/src/install_source.d.ts +79 -0
  33. package/src/install_source.js +104 -0
  34. package/src/launcher.d.ts +37 -0
  35. package/src/launcher.js +464 -0
  36. package/src/mcp_config.d.ts +63 -0
  37. package/src/mcp_config.js +86 -0
  38. package/src/output.d.ts +38 -0
  39. package/src/output.js +43 -0
  40. package/src/paint.d.ts +42 -0
  41. package/src/paint.js +38 -0
  42. package/src/project.d.ts +69 -0
  43. package/src/project.js +132 -0
  44. package/src/pyproject.d.ts +30 -0
  45. package/src/pyproject.js +156 -0
  46. package/src/python_build.d.ts +27 -0
  47. package/src/python_build.js +197 -0
  48. package/src/records.d.ts +9 -0
  49. package/src/records.js +13 -0
  50. package/src/relock.d.ts +11 -0
  51. package/src/relock.js +182 -0
  52. package/src/setup.d.ts +251 -0
  53. package/src/setup.js +601 -0
  54. package/src/star.d.ts +44 -0
  55. package/src/star.js +100 -0
  56. package/src/starter.d.ts +55 -0
  57. package/src/starter.js +126 -0
  58. package/src/toml.d.ts +32 -0
  59. package/src/toml.js +354 -0
  60. package/src/translate.d.ts +69 -0
  61. package/src/translate.js +198 -0
  62. package/src/upgrade.d.ts +113 -0
  63. package/src/upgrade.js +344 -0
  64. package/src/version.d.ts +11 -0
  65. package/src/version.js +13 -0
  66. package/src/version_report.d.ts +55 -0
  67. package/src/version_report.js +187 -0
  68. package/zuke.js +8 -0
package/mod.js ADDED
@@ -0,0 +1,893 @@
1
+ // Copyright (c) 2026 the Zuke contributors
2
+ // SPDX-License-Identifier: MIT
3
+ /**
4
+ * `@zuke/cli` — the `zuke` command. Install it globally with
5
+ *
6
+ * ```sh
7
+ * deno install -A -g -n zuke jsr:@zuke/cli
8
+ * ```
9
+ *
10
+ * scaffold Zuke into any project with `zuke setup`, then run its build from
11
+ * anywhere inside the project with `zuke <target>`: every command that is not
12
+ * the CLI's own (`setup`, `import`, `doc`, `upgrade`, and the project
13
+ * commands `add`, `remove`, `cache` and `relock`) is forwarded to the
14
+ * nearest `zuke.ts`, exactly as the `./zuke` launcher would run it. Update the
15
+ * installed CLI itself with `zuke upgrade`, and manage a project's
16
+ * dependencies and lock with `zuke add`, `remove`, `cache` and `relock`.
17
+ *
18
+ * @module
19
+ */
20
+ import { ConsoleTasks } from "@zuke/console";
21
+ import { assertBuildFileName, NEW_BUILD_FILE } from "./src/build_file.js";
22
+ import { defaultHost, existingBuildFile, runSetup, unrelatedBuildFile, } from "./src/setup.js";
23
+ import { runImport } from "./src/import.js";
24
+ import { defaultStarActions, promptStar, } from "./src/star.js";
25
+ import { VERSION } from "./src/version.js";
26
+ import { installLabel, installSource, } from "./src/install_source.js";
27
+ import { DENO_PIN } from "./src/deno_pin.js";
28
+ import { buildLabel, defaultBuildProbe, defaultBuildRunner, embeddedEngineNotice, locateBuild, NO_LOCK_NOTICE, runBuild, runningNotice, servingEngine, } from "./src/dispatch.js";
29
+ import { absolutePath, logoLines, resolveDocSpec, RuntimeTasks, } from "@zuke/core";
30
+ import { runDenoIsolated } from "./src/deno_isolated.js";
31
+ import { defaultDenoHost, firstSet } from "./src/deno_path.js";
32
+ import { defaultUpgradeHost, runUpgrade, } from "./src/upgrade.js";
33
+ import { runEnginePin } from "./src/engine_pin.js";
34
+ import { neutralise, output } from "./src/output.js";
35
+ import { runRelock } from "./src/relock.js";
36
+ import { runCache } from "./src/cache.js";
37
+ import { runDependencies } from "./src/dependencies.js";
38
+ import { defaultProjectHost } from "./src/project.js";
39
+ import { invocationPaint } from "./src/paint.js";
40
+ import { versionPanel } from "@zuke/core/render";
41
+ import { homeRelative, lockedCoreVersions, projectConfigText, projectLockPath, VERSION_PATTERN, } from "./src/version_report.js";
42
+ export { EMBEDDED_ENGINE_ENV, } from "./src/embedded_engine.js";
43
+ export { FORWARDED_ENV } from "./src/dispatch.js";
44
+ /** The real {@link Prompter}, backed by Deno's `prompt`/`confirm`. */
45
+ export const defaultPrompter = {
46
+ interactive() {
47
+ return RuntimeTasks.isTerminal("stdin");
48
+ },
49
+ ask(question, fallback) {
50
+ // The default is shown in the question rather than prefilled: `prompt`
51
+ // writes its text to the terminal itself, past the package's sink, and the
52
+ // default is what the user typed on the command line (`--name`). Shown
53
+ // neutralised, so the line cannot open a workflow command on a runner;
54
+ // the value itself stays what was typed.
55
+ const answer = prompt(neutralise(`${question} [${fallback}]`));
56
+ return answer === null || answer === "" ? fallback : answer;
57
+ },
58
+ confirm(question) {
59
+ return confirm(question);
60
+ },
61
+ };
62
+ /** Parse the argument list following `zuke setup`. */
63
+ export function parseSetupFlags(args) {
64
+ const flags = {
65
+ force: false,
66
+ yes: false,
67
+ mcp: false,
68
+ allowRun: false,
69
+ };
70
+ for (let i = 0; i < args.length; i++) {
71
+ const arg = args[i];
72
+ if (arg === "--force" || arg === "-f") {
73
+ flags.force = true;
74
+ }
75
+ else if (arg === "--yes" || arg === "-y") {
76
+ flags.yes = true;
77
+ }
78
+ else if (arg === "--mcp") {
79
+ flags.mcp = true;
80
+ }
81
+ else if (arg === "--allow-run") {
82
+ // Execution only makes sense for a registered server, so the flag
83
+ // implies --mcp rather than being silently ignored without it.
84
+ flags.mcp = true;
85
+ flags.allowRun = true;
86
+ }
87
+ else if (arg === "--bootstrap" || arg === "--bootstrap-deno") {
88
+ // `--bootstrap-deno` is the older spelling, from before a launcher
89
+ // could bootstrap anything but Deno.
90
+ flags.bootstrapDeno = true;
91
+ }
92
+ else if (arg === "--no-bootstrap" || arg === "--no-bootstrap-deno") {
93
+ flags.bootstrapDeno = false;
94
+ }
95
+ else if (arg === "--name") {
96
+ if (i + 1 < args.length) {
97
+ i++;
98
+ flags.name = args[i];
99
+ }
100
+ }
101
+ else if (arg.startsWith("--name=")) {
102
+ flags.name = arg.slice("--name=".length);
103
+ }
104
+ else if (arg === "--build-file") {
105
+ if (i + 1 < args.length) {
106
+ i++;
107
+ flags.buildFile = args[i];
108
+ }
109
+ }
110
+ else if (arg.startsWith("--build-file=")) {
111
+ flags.buildFile = arg.slice("--build-file=".length);
112
+ }
113
+ else if (arg === "--dir") {
114
+ if (i + 1 < args.length) {
115
+ i++;
116
+ flags.dir = args[i];
117
+ }
118
+ }
119
+ else if (arg.startsWith("--dir=")) {
120
+ flags.dir = arg.slice("--dir=".length);
121
+ }
122
+ else if (arg === "--launcher-name") {
123
+ if (i + 1 < args.length) {
124
+ i++;
125
+ flags.launcherName = args[i];
126
+ }
127
+ }
128
+ else if (arg.startsWith("--launcher-name=")) {
129
+ flags.launcherName = arg.slice("--launcher-name=".length);
130
+ }
131
+ else if (arg === "--sdk") {
132
+ if (i + 1 < args.length) {
133
+ i++;
134
+ flags.sdk = args[i];
135
+ }
136
+ }
137
+ else if (arg.startsWith("--sdk=")) {
138
+ flags.sdk = arg.slice("--sdk=".length);
139
+ }
140
+ else if (arg === "--zuke") {
141
+ if (i + 1 < args.length) {
142
+ i++;
143
+ flags.zuke = args[i];
144
+ }
145
+ }
146
+ else if (arg.startsWith("--zuke=")) {
147
+ flags.zuke = arg.slice("--zuke=".length);
148
+ }
149
+ }
150
+ return flags;
151
+ }
152
+ /** The SDKs `--sdk` accepts: the ones whose build `@zuke/engine` can host. */
153
+ const SDKS = new Set(["python"]);
154
+ /**
155
+ * What `--sdk` asks `setup` to scaffold against: the pin of the `zuke`
156
+ * release the launchers run. `undefined` without `--sdk`, for a TypeScript
157
+ * build.
158
+ *
159
+ * @throws {Error} naming an SDK the engine cannot host, or a release whose
160
+ * pin cannot be read.
161
+ */
162
+ async function sdkOption(flags, upgradeHost) {
163
+ if (flags.sdk === undefined)
164
+ return undefined;
165
+ if (!SDKS.has(flags.sdk)) {
166
+ throw new Error(`zuke setup: unknown --sdk "${flags.sdk}" — the engine hosts a build ` +
167
+ `in: ${[...SDKS].join(", ")}.`);
168
+ }
169
+ return { pin: await binaryPin(flags, upgradeHost, "zuke setup") };
170
+ }
171
+ /**
172
+ * The pin of the `zuke` release an SDK build's launchers run: `--zuke`, or
173
+ * this zuke's own release. `command` names the caller in its errors.
174
+ *
175
+ * @throws {Error} naming a `--zuke` that is not an exact version, or a
176
+ * release whose binaries or engine cannot be read.
177
+ */
178
+ async function binaryPin(flags, upgradeHost, command) {
179
+ const version = flags.zuke ?? VERSION;
180
+ if (!VERSION_PATTERN.test(version)) {
181
+ throw new Error(`${command}: --zuke "${version}" is not an exact version — name a ` +
182
+ "zuke release such as 2.4.0.");
183
+ }
184
+ try {
185
+ return await upgradeHost.binaryPin(version);
186
+ }
187
+ catch (error) {
188
+ throw new Error(`${command}: ${error instanceof Error ? error.message : String(error)}` +
189
+ ". Name a published release with --zuke <version>.");
190
+ }
191
+ }
192
+ /** The `.mcp.json` request the flags make, or `undefined` for none. */
193
+ function mcpOption(flags) {
194
+ return flags.mcp ? { allowRun: flags.allowRun } : undefined;
195
+ }
196
+ /** The launcher question for a TypeScript build, naming the Deno a yes pins. */
197
+ const BOOTSTRAP_QUESTION = `Launchers: bootstrap a pinned, checksum-verified Deno v${DENO_PIN.version} ` +
198
+ "when none is on PATH? [y/n]";
199
+ /** The launcher question for a build another SDK hosts, which needs no Deno. */
200
+ const SDK_BOOTSTRAP_QUESTION = "Launchers: download the pinned, checksum-verified zuke release on first " +
201
+ "use, rather than require zuke on PATH? [y/n]";
202
+ /** The launcher question when the build's kind is not known yet (`import`). */
203
+ const ANY_BOOTSTRAP_QUESTION = "Launchers: download their pinned, checksum-verified runtime (Deno for a " +
204
+ "TypeScript build, zuke for a Python one) when it is missing? [y/n]";
205
+ /**
206
+ * Which launchers to scaffold. A flag decides outright; otherwise the wizard
207
+ * asks `question` when it is interactive, and the default — bootstrap —
208
+ * stands under `--yes` or a non-TTY. Only an explicit "n…" opts out, so
209
+ * Enter keeps the default the question shows.
210
+ */
211
+ function resolveBootstrapDeno(flags, prompter, interactive, question) {
212
+ if (flags.bootstrapDeno !== undefined)
213
+ return flags.bootstrapDeno;
214
+ if (!interactive)
215
+ return true;
216
+ return !/^n/i.test(prompter.ask(question, "y").trim());
217
+ }
218
+ /** The flag that asks for plain output, read here for the CLI's own commands. */
219
+ const PLAIN_FLAG = "--plain";
220
+ /** The `upgrade` flag that moves a project's engine pin instead of the CLI. */
221
+ const ENGINE_FLAG = "--engine";
222
+ /**
223
+ * The arguments `zuke upgrade --engine` parses when `args` carries the flag,
224
+ * as a bare `--engine` or as `--engine=<version>`, with the flag taken out
225
+ * and an inline version left as its own argument; `null` when the command is
226
+ * the CLI's own reinstall. An exact token match: nothing else is read as the
227
+ * flag.
228
+ */
229
+ function enginePinArgs(args) {
230
+ const inline = `${ENGINE_FLAG}=`;
231
+ if (!args.some((arg) => arg === ENGINE_FLAG || arg.startsWith(inline))) {
232
+ return null;
233
+ }
234
+ return args.flatMap((arg) => arg === ENGINE_FLAG
235
+ ? []
236
+ : arg.startsWith(inline)
237
+ ? [arg.slice(inline.length)]
238
+ : [arg]);
239
+ }
240
+ /** The environment that asks a spawned build for plain output. */
241
+ const PLAIN_ENV = { ZUKE_PLAIN: "1" };
242
+ /** The one-line identity printed under the logo and atop `--help`. */
243
+ const TAGLINE = `zuke ${VERSION} — code-first build automation`;
244
+ /**
245
+ * Print the Zuke logo through `host`, so scaffolding opens with the brand.
246
+ * Colour and log-level detection are `ConsoleTasks`'s (a TTY with `NO_COLOR`
247
+ * unset paints the art; a pipe gets it plain; `ZUKE_LOG_LEVEL=silent` skips
248
+ * it), while the lines themselves flow through the injectable host.
249
+ */
250
+ function printBanner(host) {
251
+ ConsoleTasks.configure({
252
+ sink: { out: (line) => host.log(line), err: (line) => host.log(line) },
253
+ });
254
+ ConsoleTasks.logo({ tagline: TAGLINE });
255
+ // Point the process-global sink back at the console so nothing else in this
256
+ // process (or a test's next case) keeps writing into this command's host.
257
+ ConsoleTasks.reset();
258
+ host.log("");
259
+ }
260
+ /**
261
+ * The CLI's own half of the help: the commands that work anywhere, with no
262
+ * project needed.
263
+ *
264
+ * Headed so a reader can tell it apart from the build's half, which is printed
265
+ * after it when there is a project here. The two are different surfaces — this
266
+ * one is the installed `zuke`, that one is whatever `zuke.ts` declares — and
267
+ * showing them unlabelled under one heading was what made them look like one
268
+ * inconsistent command.
269
+ */
270
+ const HELP = `${TAGLINE}
271
+
272
+ Usage:
273
+ zuke <command> [options] A zuke command, anywhere (below)
274
+ zuke <target> A target of the build in this directory
275
+ zuke -- <args> Pass args straight to the build, unread
276
+
277
+ Zuke commands (available anywhere):
278
+ setup [options] Scaffold Zuke into a directory
279
+ import [options] Generate a build from package.json scripts, a Makefile or pyproject.toml tasks
280
+ doc <package> Show a @zuke/* package's API docs (isolated resolution)
281
+ upgrade [<version>] Reinstall this CLI at the latest (or given) JSR release
282
+ (Homebrew installs: brew upgrade zuke)
283
+ upgrade --engine [<v>] Move a Python project's launchers to the latest (or given) zuke release
284
+ add <package...> Add packages to this project's deno.json (docker = @zuke/docker)
285
+ remove <package...> Remove packages from this project's deno.json
286
+ cache [<entry>...] Fetch everything the build imports, keeping the lock
287
+ relock [<entry>...] Regenerate this project's lock from scratch
288
+ --help Show this help
289
+ --version Show the CLI's version, and this project's build's
290
+
291
+ Setup options:
292
+ --dir <path> Directory to scaffold into (default: .)
293
+ --name <Class> Build class name (default: MyBuild)
294
+ --build-file <name> TypeScript build file name (default: build.ts, or the project's own)
295
+ --launcher-name <name> Launcher base name when a zuke/ directory is in the way
296
+ --sdk python Scaffold a build.py and launchers that run the zuke binary (no Deno)
297
+ --zuke <version> The zuke release those launchers run (default: this one)
298
+ --mcp Also write .mcp.json registering the build's MCP server
299
+ --allow-run …with --allow-run, so an agent may execute targets (implies --mcp)
300
+ --bootstrap Launchers download their pinned, checksum-verified runtime when missing (default):
301
+ Deno for a zuke.ts build, the zuke binary for a Python one
302
+ --no-bootstrap Launchers require that runtime on PATH and fail closed without it
303
+ --force, -f Overwrite existing files
304
+ --yes, -y Accept defaults without prompting
305
+
306
+ Import options:
307
+ --dir <path> Directory to read from and scaffold into (default: .)
308
+ --name <Class> Build class name (default: MyBuild)
309
+ --from <source> Force a source: package.json, makefile or pyproject (default: auto-detect)
310
+ --zuke <version> The zuke release a pyproject.toml import's launchers run (default: this one)
311
+ --mcp Also write .mcp.json registering the build's MCP server
312
+ --allow-run …with --allow-run, so an agent may execute targets (implies --mcp)
313
+ --bootstrap Launchers download their pinned, checksum-verified runtime when missing (default):
314
+ Deno for a zuke.ts build, the zuke binary for a Python one
315
+ --no-bootstrap Launchers require that runtime on PATH and fail closed without it
316
+ --force, -f Overwrite existing files
317
+ --yes, -y Accept defaults without prompting
318
+
319
+ Upgrade options:
320
+ --dry-run Say what would be installed, and install nothing
321
+ --force, -f Reinstall even when already on that version
322
+ --engine Move a Python project's launchers and engine pin instead (takes --dry-run)
323
+
324
+ Cache and relock options:
325
+ --min-dep-age <age> Only resolve releases at least this old (0 for the newest)
326
+ --dry-run Say what would run, and change nothing
327
+
328
+ Doc:
329
+ zuke doc core API of @zuke/core
330
+ zuke doc @scope/pkg API of a scoped package (or pass jsr:/npm:/https: as-is)`;
331
+ /**
332
+ * {@link HELP} as `paint` renders it: headings marked, each row's command or
333
+ * flag painted, every word in place. Plain paint returns it unchanged.
334
+ */
335
+ function helpText(paint) {
336
+ if (!paint.rich)
337
+ return HELP;
338
+ return HELP.split("\n").map((line) => {
339
+ if (line === TAGLINE)
340
+ return paint.target(line);
341
+ if (/^\S.*:$/.test(line))
342
+ return paint.heading(line);
343
+ const row = /^( {2})(\S.*?)( {2,})(.*)$/.exec(line);
344
+ if (row === null)
345
+ return line;
346
+ const [, indent, label, gap, description] = row;
347
+ return `${indent}${paint.command(label)}${gap}${description}`;
348
+ }).join("\n");
349
+ }
350
+ /**
351
+ * The heading that introduces the build's own half of the merged help: a rule,
352
+ * then a line naming the build. Painted as a section heading when output is
353
+ * rich; plain output is the text it always was.
354
+ */
355
+ function buildHelpHeading(location, paint, engine) {
356
+ const title = `This project's build (${buildLabel(location, engine)}) — ` +
357
+ `run as \`zuke <target>\` or \`./zuke <target>\`:`;
358
+ return `\n${paint.muted("─".repeat(72))}\n${paint.heading(title)}\n`;
359
+ }
360
+ /**
361
+ * What to say where the build's half should have been, when the build was
362
+ * found but did not describe itself — it failed to spawn, or its own `--help`
363
+ * exited non-zero. The heading is already printed by then (the build inherits
364
+ * stdio, so there is nothing to buffer and inspect first), which would
365
+ * otherwise leave a heading over an empty section with only Deno's own error
366
+ * to explain it. Named on stderr so stdout stays the help.
367
+ */
368
+ const BUILD_HELP_FAILED = "The build was found but could not describe itself, so the section above " +
369
+ "is empty. The CLI's own commands are unaffected.";
370
+ /** What to say when the build was found but could not report its version. */
371
+ const BUILD_VERSION_FAILED = "The build was found but could not report its version: a build on " +
372
+ "@zuke/core older than 1.60.0 cannot answer --version, and this project " +
373
+ "has no deno.lock naming its core to read instead. The CLI's own version " +
374
+ "above is unaffected.";
375
+ /** What to say where the build's half would be, when there is no project. */
376
+ const NO_BUILD_NOTICE = `\n${"─".repeat(72)}\nNo zuke.json in this directory or any parent, so ` +
377
+ `there is no build to describe here.\nRun \`zuke setup\` to scaffold one, ` +
378
+ `then \`zuke --help\` also lists its targets.`;
379
+ /** How many answers the build file question takes before setup gives up. */
380
+ const BUILD_FILE_ATTEMPTS = 3;
381
+ /**
382
+ * Ask a new project's build file name until the answer is a valid name that
383
+ * no unrelated file in `dir` already has. `suggested` is what `--build-file`
384
+ * gave, shown as the default in place of `build.ts`.
385
+ *
386
+ * @throws {Error} after {@link BUILD_FILE_ATTEMPTS} refused answers, saying
387
+ * why the last one was refused: a closed stdin answers the default forever.
388
+ */
389
+ async function askBuildFile(dir, suggested, host, prompter) {
390
+ let refusal = "";
391
+ for (let attempt = 0; attempt < BUILD_FILE_ATTEMPTS; attempt++) {
392
+ const answer = prompter.ask("Build file", suggested ?? NEW_BUILD_FILE)
393
+ .trim();
394
+ try {
395
+ assertBuildFileName(answer);
396
+ if (!(await unrelatedBuildFile(dir, answer, host)))
397
+ return answer;
398
+ refusal = `zuke setup: ${answer} already exists here and is not a ` +
399
+ "Zuke build. Choose another name.";
400
+ }
401
+ catch (error) {
402
+ refusal = error instanceof Error ? error.message : String(error);
403
+ }
404
+ host.log(refusal);
405
+ }
406
+ throw new Error(refusal);
407
+ }
408
+ /** Run the `setup` subcommand. */
409
+ async function commandSetup(args, host, prompter, starActions, paint, upgradeHost) {
410
+ const flags = parseSetupFlags(args);
411
+ // Resolved before any question is asked, so an unknown SDK or an
412
+ // unreachable registry stops the run before the wizard starts.
413
+ const sdk = await sdkOption(flags, upgradeHost);
414
+ let name = flags.name ?? "MyBuild";
415
+ let force = flags.force;
416
+ const dir = flags.dir ?? ".";
417
+ if (paint.banner)
418
+ printBanner(host);
419
+ const interactive = !flags.yes && prompter.interactive();
420
+ let buildFile = flags.buildFile;
421
+ if (interactive) {
422
+ // Only a new TypeScript project is asked: an existing one has its name,
423
+ // and a Python build is always build.py.
424
+ if (sdk === undefined && await existingBuildFile(dir, host) === undefined) {
425
+ buildFile = await askBuildFile(dir, buildFile, host, prompter);
426
+ }
427
+ name = prompter.ask("Build class name", name);
428
+ if (!force) {
429
+ force = prompter.confirm("Overwrite existing files if present?");
430
+ }
431
+ }
432
+ const bootstrapDeno = resolveBootstrapDeno(flags, prompter, interactive, sdk === undefined ? BOOTSTRAP_QUESTION : SDK_BOOTSTRAP_QUESTION);
433
+ const where = dir === "." ? "the current directory" : dir;
434
+ host.log(`Scaffolding Zuke into ${where}:`);
435
+ const launcherName = flags.launcherName;
436
+ const result = await runSetup({
437
+ dir,
438
+ force,
439
+ name,
440
+ buildFile,
441
+ launcherName,
442
+ mcp: mcpOption(flags),
443
+ bootstrapDeno,
444
+ sdk,
445
+ }, host);
446
+ const written = result.files.filter((f) => f.status !== "skipped").length;
447
+ reportNotes(host, result);
448
+ if (result.manualSteps.length > 0) {
449
+ reportManualSteps(host, result, `${written} file(s) written`, paint);
450
+ return 1;
451
+ }
452
+ host.log(paint.ok(`Done — ${written} file(s) written. Next: zuke`));
453
+ if (interactive) {
454
+ await promptStar(host, prompter, starActions);
455
+ }
456
+ return 0;
457
+ }
458
+ /** Print the advisory notes a scaffold run collected, if any. */
459
+ function reportNotes(host, result) {
460
+ for (const note of result.notes)
461
+ host.log(` note ${note}`);
462
+ }
463
+ /**
464
+ * Report a scaffold that could not be finished automatically.
465
+ *
466
+ * The files are on disk, but the build cannot run until the reader acts, so
467
+ * this never prints `Next: ./zuke` — the caller returns a non-zero exit code.
468
+ * A scaffold that claims success over a build that errors on its first import
469
+ * is worse than one that says plainly what is left to do.
470
+ */
471
+ function reportManualSteps(host, result, written, paint) {
472
+ host.log(paint.fail(`Incomplete — ${written}, but ${result.manualSteps.length} step(s) ` +
473
+ `need you:`));
474
+ for (const step of result.manualSteps)
475
+ host.log(` - ${step}`);
476
+ }
477
+ /** Map a `--from` value to a source, or `undefined` when unrecognised. */
478
+ function parseSource(value) {
479
+ const lower = value.toLowerCase();
480
+ if (lower === "package.json" || lower === "package")
481
+ return "package.json";
482
+ if (lower === "makefile")
483
+ return "Makefile";
484
+ if (lower === "pyproject.toml" || lower === "pyproject") {
485
+ return "pyproject.toml";
486
+ }
487
+ return undefined;
488
+ }
489
+ /** Parse the argument list following `zuke import`. */
490
+ export function parseImportFlags(args) {
491
+ const flags = parseSetupFlags(args);
492
+ for (let i = 0; i < args.length; i++) {
493
+ const arg = args[i];
494
+ if (arg === "--from" && i + 1 < args.length) {
495
+ flags.from = parseSource(args[++i]);
496
+ }
497
+ else if (arg.startsWith("--from=")) {
498
+ flags.from = parseSource(arg.slice("--from=".length));
499
+ }
500
+ }
501
+ return flags;
502
+ }
503
+ /** Run the `import` subcommand. */
504
+ async function commandImport(args, host, prompter, paint, upgradeHost) {
505
+ const flags = parseImportFlags(args);
506
+ let name = flags.name ?? "MyBuild";
507
+ let force = flags.force;
508
+ const dir = flags.dir ?? ".";
509
+ if (paint.banner)
510
+ printBanner(host);
511
+ const interactive = !flags.yes && prompter.interactive();
512
+ if (interactive) {
513
+ name = prompter.ask("Build class name", name);
514
+ if (!force) {
515
+ force = prompter.confirm("Overwrite existing files if present?");
516
+ }
517
+ }
518
+ const bootstrapDeno = resolveBootstrapDeno(flags, prompter, interactive, ANY_BOOTSTRAP_QUESTION);
519
+ const result = await runImport({
520
+ dir,
521
+ force,
522
+ name,
523
+ buildFile: flags.buildFile,
524
+ from: flags.from,
525
+ mcp: mcpOption(flags),
526
+ bootstrapDeno,
527
+ pin: () => binaryPin(flags, upgradeHost, "zuke import"),
528
+ }, host);
529
+ if (result.source === null) {
530
+ host.log(paint.fail("Nothing to import: no package.json, Makefile or pyproject.toml found" +
531
+ (flags.from ? ` for --from ${flags.from}` : "") + "."));
532
+ return 1;
533
+ }
534
+ const written = result.files.filter((f) => f.status !== "skipped").length;
535
+ reportNotes(host, result);
536
+ if (result.manualSteps.length > 0) {
537
+ reportManualSteps(host, result, `imported ${result.taskCount} task(s) from ${result.source}, ` +
538
+ `${written} file(s) written`, paint);
539
+ return 1;
540
+ }
541
+ host.log(paint.ok(`Done — imported ${result.taskCount} task(s) from ${result.source}; ` +
542
+ `${written} file(s) written. Next: zuke`));
543
+ return 0;
544
+ }
545
+ /**
546
+ * The default {@link DocRunner}: `deno doc …` in an isolated temp dir, so the
547
+ * surrounding repo's deno.json / node_modules / tsconfig don't drag
548
+ * @types/node resolution noise into the output — the whole point of
549
+ * `zuke doc` inside a Node project.
550
+ */
551
+ const defaultDocRunner = (denoArgs) => runDenoIsolated(denoArgs, "zuke-doc-");
552
+ /** Run the `doc` subcommand: `deno doc <spec>` in an isolated directory. */
553
+ async function commandDoc(args, host, runner) {
554
+ const [pkg, ...extra] = args;
555
+ if (pkg === undefined || pkg === "" || pkg.startsWith("-")) {
556
+ host.log("zuke doc: name a package, e.g. `zuke doc core` or `zuke doc @scope/pkg`.");
557
+ return 1;
558
+ }
559
+ // A path would resolve against the runner's throwaway cwd — the resolver
560
+ // pins it to the user's directory now, while cwd is still theirs. (Absolute
561
+ // paths and `jsr:`/`npm:`/`https:` specifiers are location-independent.)
562
+ return await runner([
563
+ "doc",
564
+ ...extra,
565
+ resolveDocSpec(pkg, RuntimeTasks.cwd()),
566
+ ]);
567
+ }
568
+ /**
569
+ * Forward `args` to the project's build: locate the nearest `zuke.json` above
570
+ * the working directory (through `probe`, which also enforces the trust gate)
571
+ * and run `zuke.ts` beside it through `runner`. Returns `null` when the
572
+ * caller is not inside a project, so `main` can report the unknown command
573
+ * instead. A refusal or a failed spawn is reported on **stderr** — stdout is
574
+ * the build's, and under `zuke mcp` it is the JSON-RPC stream — and is exit 1.
575
+ * Both reports bypass the log level: they are never the build's to silence.
576
+ */
577
+ async function forwardToBuild(args, probe, runner, engine) {
578
+ // The CLI's own stderr sink, not `ConsoleTasks`: `ZUKE_LOG_LEVEL` is a knob
579
+ // for the build's output, and neither a security refusal nor the launchers'
580
+ // unverified-lockfile notice may be silenced by it. The sink neutralises the
581
+ // line on an Actions runner — the root and the error message below carry
582
+ // text from the filesystem and from a failed spawn, not from Zuke.
583
+ try {
584
+ const cwd = RuntimeTasks.cwd();
585
+ const location = await locateBuild(cwd, probe);
586
+ if (location === null)
587
+ return null;
588
+ // Discovery ran something the caller never named: say which, unless it
589
+ // is the build right here, where `./zuke` would have been the same act.
590
+ if (location.root !== absolutePath(cwd).path) {
591
+ output.error(runningNotice(location, engine));
592
+ }
593
+ const fallback = embeddedEngineNotice(location, engine);
594
+ if (fallback !== undefined)
595
+ output.error(fallback);
596
+ // A launcher has its own lockfile story to tell; only the bare `deno run`
597
+ // it stands in for is this notice's to report.
598
+ // A hosted build has no Deno config for Deno to write a lock into, so
599
+ // the launchers say nothing there, and neither does this.
600
+ if (location.launcher === null && !location.frozen &&
601
+ location.engine === null) {
602
+ output.error(NO_LOCK_NOTICE);
603
+ }
604
+ return await runBuild(runner, location, args, undefined, engine);
605
+ }
606
+ catch (error) {
607
+ output.error(error instanceof Error ? error.message : String(error));
608
+ return 1;
609
+ }
610
+ }
611
+ /**
612
+ * `zuke --help`: this CLI's own commands, then — inside a project — the
613
+ * build's.
614
+ *
615
+ * The two halves were separate programs' help, and from inside a project the
616
+ * distinction was invisible: `zuke --help` and `./zuke --help` disagreed for
617
+ * no reason a reader could see, and the build's surface was reachable only by
618
+ * knowing to type `zuke -- --help`. Both are shown here, under headings that
619
+ * say which is which.
620
+ *
621
+ * The build's half is produced by running the build's own `--help` rather than
622
+ * rendered here. The CLI has no business knowing how a build describes itself,
623
+ * and a second renderer is a second thing to drift.
624
+ *
625
+ * A build that fails to describe itself is not an error for this command:
626
+ * the CLI's own help is still correct and still useful, so both shapes of
627
+ * failure — a spawn that throws and a `--help` that exits non-zero — are
628
+ * named on stderr and the exit stays 0. Help is what someone reaches for when
629
+ * a project is already broken; refusing to print it then would be backwards.
630
+ */
631
+ async function commandHelp(host, probe, runner, paint, childEnv, engine) {
632
+ // The wordmark opens the help only where the rest of it is rich: a pipe, CI
633
+ // or plain output reads help as text, where six lines of art are noise.
634
+ if (paint.rich && paint.banner) {
635
+ host.log(`${logoLines(paint.color).join("\n")}\n`);
636
+ }
637
+ host.log(helpText(paint));
638
+ let location = null;
639
+ try {
640
+ location = await locateBuild(RuntimeTasks.cwd(), probe);
641
+ }
642
+ catch (error) {
643
+ // A refusal is not the same as an absence, and must not be reported as
644
+ // one: the trust gate rejecting a `zuke.json` is exactly what someone
645
+ // needs to be told, and "there is no build here" would hide it. Reported
646
+ // on stderr, as the forwarding path reports it, because stdout is the
647
+ // help. The CLI's own half is still correct, so this is not an error.
648
+ output.error(error instanceof Error ? error.message : String(error));
649
+ host.log(NO_BUILD_NOTICE);
650
+ return 0;
651
+ }
652
+ if (location === null) {
653
+ host.log(NO_BUILD_NOTICE);
654
+ return 0;
655
+ }
656
+ host.log(buildHelpHeading(location, paint, engine));
657
+ try {
658
+ // The runner *returns* the build's exit code rather than throwing on one,
659
+ // so a build whose `--help` runs and fails is reported here too — not
660
+ // only one that fails to spawn. Left unread, that outcome was the one
661
+ // path this command passed over without a word of its own.
662
+ const code = await runBuild(runner, location, ["--help"], childEnv, engine);
663
+ if (code !== 0)
664
+ output.error(BUILD_HELP_FAILED);
665
+ }
666
+ catch (error) {
667
+ output.error(error instanceof Error ? error.message : String(error));
668
+ output.error(BUILD_HELP_FAILED);
669
+ }
670
+ return 0;
671
+ }
672
+ /**
673
+ * `zuke --version`: this CLI's version, then — inside a project — the build's.
674
+ *
675
+ * Both numbers, because they differ for a real reason: `@zuke/cli` and
676
+ * `@zuke/core` are separate packages on separate cadences, and a project pins
677
+ * core through its own import map and lock. Reporting only one of them made
678
+ * `zuke --version` and `./zuke --version` disagree with nothing to say which
679
+ * had answered.
680
+ *
681
+ * In plain output the first line is the installed CLI's version, bare, so
682
+ * anything reading `zuke --version` keeps working, and the build's follows
683
+ * under a heading. On a terminal the same facts are one panel, which also
684
+ * names how this CLI was installed (JSR, Homebrew, a standalone binary, or
685
+ * source): one machine can hold more than one `zuke`, and the panel says which
686
+ * answered. Plain output leaves it out, keeping its lines as they were.
687
+ *
688
+ * The build's version is read from its lockfile — what the project
689
+ * actually resolves, which the CLI's own linked core need not be — so nothing
690
+ * is spawned, and a build on any core is answered. Only a project with no
691
+ * lock, or a lock naming no core, has its build asked instead, plainly; a
692
+ * build that cannot answer is reported and does not fail the command, since
693
+ * the CLI's own version is still correct.
694
+ *
695
+ * Outside a project there is no second line and no notice. A version query is
696
+ * not the place to explain what a project is, and `--help` already does.
697
+ */
698
+ async function commandVersion(host, probe, runner, paint, installHost, engine) {
699
+ let location = null;
700
+ let refusal;
701
+ try {
702
+ location = await locateBuild(RuntimeTasks.cwd(), probe);
703
+ }
704
+ catch (error) {
705
+ // A refused build is worth saying out loud even here: silence would read
706
+ // as "no project", which is a different fact. On stderr, so the version
707
+ // on stdout stays the one line a script reads.
708
+ refusal = error instanceof Error ? error.message : String(error);
709
+ }
710
+ // A build the binary's own engine runs is on the binary's core, not the
711
+ // one the project's lock names: it is asked, below, like a lockless one.
712
+ const core = location === null || servingEngine(location, engine) !== undefined
713
+ ? []
714
+ : await projectCoreVersions(host, location.root);
715
+ if (paint.rich) {
716
+ const home = firstSet(defaultDenoHost, "HOME", "USERPROFILE");
717
+ // An executable path comes from the OS, with backslashes on Windows;
718
+ // homeRelative compares forward-slash paths, as absolutePath writes them.
719
+ const display = (path) => {
720
+ let normal = path;
721
+ try {
722
+ normal = absolutePath(path).path;
723
+ }
724
+ catch {
725
+ // Not absolute: shown as it is.
726
+ }
727
+ return homeRelative(normal, home, defaultDenoHost.windows());
728
+ };
729
+ const rows = [
730
+ ["cli", VERSION],
731
+ ["install", installLabel(await installSource(installHost), display)],
732
+ ];
733
+ if (location !== null) {
734
+ if (core.length > 0)
735
+ rows.push(["core", core.join(", ")]);
736
+ if (location.engine !== null)
737
+ rows.push(["engine", location.engine]);
738
+ rows.push(["project", display(location.root)]);
739
+ }
740
+ if (engine !== undefined) {
741
+ rows.push(["built-in", `@zuke/engine ${engine.version}`]);
742
+ }
743
+ // The binary's runtime is compiled in, not a Deno its user has or needs.
744
+ const runtime = RuntimeTasks.facts();
745
+ if (!runtime.standalone)
746
+ rows.push([runtime.name, runtime.version]);
747
+ rows.push(["platform", `${RuntimeTasks.os()}-${RuntimeTasks.arch()}`]);
748
+ host.log(versionPanel(rows, paint));
749
+ }
750
+ else {
751
+ host.log(VERSION);
752
+ }
753
+ if (refusal !== undefined)
754
+ output.error(refusal);
755
+ if (location === null)
756
+ return 0;
757
+ if (core.length > 0) {
758
+ // The panel already named it; plain output keeps the two-part shape it
759
+ // always had, so a script reading the second line still finds it.
760
+ if (!paint.rich) {
761
+ host.log(`\nThis project's build (${buildLabel(location, engine)}) runs on Zuke:`);
762
+ host.log(core.join(", "));
763
+ }
764
+ return 0;
765
+ }
766
+ // No lock to read, or none naming core: ask the build itself, as before.
767
+ host.log(`\nThis project's build (${buildLabel(location, engine)}) runs on Zuke:`);
768
+ try {
769
+ // Asked plainly whatever this invocation is, so the answer is the bare
770
+ // version under the heading — never a second panel under the first.
771
+ const code = await runBuild(runner, location, ["--version"], PLAIN_ENV, engine);
772
+ if (code !== 0)
773
+ output.error(BUILD_VERSION_FAILED);
774
+ }
775
+ catch (error) {
776
+ output.error(error instanceof Error ? error.message : String(error));
777
+ output.error(BUILD_VERSION_FAILED);
778
+ }
779
+ return 0;
780
+ }
781
+ /**
782
+ * The `@zuke/core` versions the project at `root` resolves, read from the
783
+ * lockfile its config points Deno at (`deno.lock` unless it names another);
784
+ * empty when it has none, disables its lock, or names no core. Reading the
785
+ * lock answers for a build on any core — asking the build only works from
786
+ * core 1.60.0, where `--version` was added — and spawns nothing.
787
+ */
788
+ async function projectCoreVersions(host, root) {
789
+ const lock = projectLockPath(root, await projectConfigText((path) => host.readText(path), root));
790
+ if (lock === null)
791
+ return [];
792
+ let text;
793
+ try {
794
+ text = await host.readText(lock);
795
+ }
796
+ catch {
797
+ return [];
798
+ }
799
+ return lockedCoreVersions(text);
800
+ }
801
+ /**
802
+ * The CLI entry point. Returns a process exit code; `host`, `prompter`,
803
+ * `docRunner`, `starActions`, `buildRunner`, `buildProbe`, `upgradeHost` and
804
+ * `projectHost` are injectable for testing. `engine` is the engine the
805
+ * compiled binary carries, absent under `deno run`: see {@link binaryMain}.
806
+ */
807
+ export async function main(args, host = defaultHost, prompter = defaultPrompter, docRunner = defaultDocRunner, starActions = defaultStarActions, buildRunner = defaultBuildRunner, buildProbe = defaultBuildProbe, upgradeHost = defaultUpgradeHost, projectHost = defaultProjectHost, engine) {
808
+ // `--plain` belongs to whichever CLI answers. For the commands answered
809
+ // here it is read and set aside; a command forwarded to the build keeps it
810
+ // in its argv, where the build's own CLI reads it.
811
+ const own = args.filter((arg) => arg !== PLAIN_FLAG);
812
+ const plainFlag = own.length !== args.length;
813
+ const paint = invocationPaint(plainFlag ? true : undefined, host.isTerminal?.bind(host));
814
+ if (own[0] === "--help" || own[0] === "-h") {
815
+ // The build's half answers to the same request: an explicit --plain
816
+ // reaches it as ZUKE_PLAIN, which a build on any core accepts, where the
817
+ // flag would be refused by one older than core 1.67.0.
818
+ const childEnv = plainFlag ? PLAIN_ENV : undefined;
819
+ return await commandHelp(host, buildProbe, buildRunner, paint, childEnv, engine);
820
+ }
821
+ const command = own[0];
822
+ const rest = own.slice(1);
823
+ if (command === "--version" || command === "-V") {
824
+ return await commandVersion(host, buildProbe, buildRunner, paint, upgradeHost, engine);
825
+ }
826
+ try {
827
+ if (command === "setup") {
828
+ return await commandSetup(rest, host, prompter, starActions, paint, upgradeHost);
829
+ }
830
+ if (command === "import") {
831
+ return await commandImport(rest, host, prompter, paint, upgradeHost);
832
+ }
833
+ if (command === "doc") {
834
+ return await commandDoc(rest, host, docRunner);
835
+ }
836
+ if (command === "upgrade") {
837
+ const engineArgs = enginePinArgs(rest);
838
+ if (engineArgs !== null) {
839
+ return await runEnginePin(engineArgs, (line) => host.log(line), {
840
+ entry: (path) => projectHost.entry(path),
841
+ readText: (path) => projectHost.readText(path),
842
+ writeText: (path, text) => projectHost.writeText(path, text),
843
+ cliMeta: () => upgradeHost.meta(),
844
+ binaryPin: (version) => upgradeHost.binaryPin(version),
845
+ }, paint, RuntimeTasks.cwd(), buildProbe);
846
+ }
847
+ return await runUpgrade(rest, (line) => host.log(line), upgradeHost, paint);
848
+ }
849
+ const log = (line) => host.log(line);
850
+ if (command === "relock") {
851
+ return await runRelock(rest, log, projectHost, paint, RuntimeTasks.cwd(), buildProbe);
852
+ }
853
+ if (command === "cache") {
854
+ return await runCache(rest, log, projectHost, paint, RuntimeTasks.cwd(), buildProbe);
855
+ }
856
+ if (command === "add" || command === "remove") {
857
+ return await runDependencies(command, rest, log, projectHost, paint, RuntimeTasks.cwd(), buildProbe);
858
+ }
859
+ }
860
+ catch (error) {
861
+ // Surface a command's own friendly error (e.g. a setup directory collision)
862
+ // as a clean message and non-zero exit, not an uncaught stack trace.
863
+ host.log(paint.fail(error instanceof Error ? error.message : String(error)));
864
+ return 1;
865
+ }
866
+ // Not one of ours: inside a project it is the build's — `zuke ci`,
867
+ // `zuke --list`, `zuke mcp`, and a bare `zuke` for the default target, as
868
+ // `./zuke` — and the build's own CLI answers for it, unknown-target message
869
+ // included. Outside any project a bare `zuke` has no build to run: it is
870
+ // the usage.
871
+ const forwarded = await forwardToBuild(args, buildProbe, buildRunner, engine);
872
+ if (forwarded !== null)
873
+ return forwarded;
874
+ if (own.length === 0) {
875
+ host.log(helpText(paint));
876
+ return 0;
877
+ }
878
+ host.log(`Unknown command: ${command} — and no zuke.json was found in the current ` +
879
+ `directory or any parent to forward it to.\n`);
880
+ host.log(helpText(paint));
881
+ return 1;
882
+ }
883
+ /**
884
+ * The compiled `zuke` binary's entry point: {@link main} with every default
885
+ * and the `engine` the binary carries, so a project with no `zuke.ts` runs on
886
+ * it with no Deno installed.
887
+ */
888
+ export function binaryMain(args, engine) {
889
+ return main(args, defaultHost, defaultPrompter, defaultDocRunner, defaultStarActions, defaultBuildRunner, defaultBuildProbe, defaultUpgradeHost, defaultProjectHost, engine);
890
+ }
891
+ if (import.meta.main) {
892
+ RuntimeTasks.exit(await main(RuntimeTasks.args()));
893
+ }