@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/src/setup.js ADDED
@@ -0,0 +1,601 @@
1
+ // Copyright (c) 2026 the Zuke contributors
2
+ // SPDX-License-Identifier: MIT
3
+ /**
4
+ * The scaffolding engine behind `zuke setup`. It writes a starter `zuke.ts`,
5
+ * the `./zuke` launchers (see {@link "./launcher.ts"} for the two variants),
6
+ * and a `deno.json` task into a target directory.
7
+ *
8
+ * All filesystem and console effects go through an injectable {@link SetupHost}
9
+ * so the logic stays pure and unit-testable; {@link defaultHost} is the real
10
+ * `Deno`-backed implementation used in production.
11
+ */
12
+ import { binaryMcpEntry, MCP_CONFIG_FILE, mcpServerEntry, mergeMcpConfig, parseMcpConfig, } from "./mcp_config.js";
13
+ import { FileTasks } from "@zuke/core";
14
+ import { isRecord } from "./records.js";
15
+ import { assertBuildFileName, BUILD_FILE, buildFileNamed, NEW_BUILD_FILE, } from "./build_file.js";
16
+ import { launcherBash, launcherPwsh } from "./launcher.js";
17
+ import { binaryLauncherBash, binaryLauncherPwsh } from "./binary_launcher.js";
18
+ import { lstatOrNull } from "./fs.js";
19
+ import { output } from "./output.js";
20
+ import { PYTHON_BUILD_FILE, STARTER_IMPORTS, starterBuild, starterConfig, starterPythonBuild, starterSdkConfig, } from "./starter.js";
21
+ // Re-exported so the merge guard keeps its historical home for importers.
22
+ export { isRecord };
23
+ /**
24
+ * The task names `setup` writes into `deno.json`, with their commands, for a
25
+ * build whose file is `buildFile`.
26
+ *
27
+ * The `zuke` task deliberately omits `--frozen`, unlike the launchers: a task
28
+ * command runs in `deno task`'s own shell, which has no conditionals, so it
29
+ * cannot skip the flag on the first run when no `deno.lock` exists yet — and
30
+ * hard-coding it would make a fresh scaffold fail before it could ever write
31
+ * one. The launcher (`./zuke`, the advertised entry point) does the lockfile
32
+ * check and enforces `--frozen` from the second run onward.
33
+ */
34
+ function defaultTasks(buildFile) {
35
+ return [
36
+ ["zuke", `deno run -A ${buildFile}`],
37
+ ["fmt", "deno fmt"],
38
+ ["lint", "deno lint"],
39
+ ["test", "deno test -A"],
40
+ ];
41
+ }
42
+ /** The `zuke` task as setup itself writes it, for any build file. */
43
+ const SCAFFOLDED_ZUKE_TASK = /^deno run -A [A-Za-z0-9_.][A-Za-z0-9_.-]*\.ts$/;
44
+ /**
45
+ * Whether `tasks.zuke` is a task setup wrote for another build file than
46
+ * `buildFile`: the one thing in `tasks` a re-run replaces, so that a project
47
+ * whose `zuke.json` was pointed at a new build file does not keep a task
48
+ * running the old one. A task the project wrote itself is never touched.
49
+ */
50
+ function staleZukeTask(tasks, buildFile) {
51
+ if (!isRecord(tasks) || typeof tasks.zuke !== "string")
52
+ return false;
53
+ return SCAFFOLDED_ZUKE_TASK.test(tasks.zuke) &&
54
+ tasks.zuke !== `deno run -A ${buildFile}`;
55
+ }
56
+ /**
57
+ * Add every entry of `defaults` that `root[key]` does not already declare,
58
+ * leaving the ones it does exactly as they are.
59
+ *
60
+ * Shared by the `imports` and `tasks` merges, which differ only in the
61
+ * collection they draw from: one implementation, so the "never overwrite what
62
+ * the project already declared" rule cannot come to mean two things.
63
+ */
64
+ function mergeMissing(root, key, defaults) {
65
+ const existing = root[key];
66
+ const merged = isRecord(existing)
67
+ ? { ...existing }
68
+ : {};
69
+ for (const [name, value] of defaults) {
70
+ if (!(name in merged))
71
+ merged[name] = value;
72
+ }
73
+ root[key] = merged;
74
+ }
75
+ /**
76
+ * Whether a `deno.json` document delegates its import map to a separate file
77
+ * and would be broken by growing an `imports` block.
78
+ *
79
+ * Deno ignores the `importMap` field the moment `imports` or `scopes` appears
80
+ * in the config, so writing `imports` beside a lone `importMap` silently
81
+ * disables the project's entire module resolution. A document that already has
82
+ * `imports` or `scopes` is not delegating — Deno is ignoring `importMap` there
83
+ * already — so merging into it changes nothing.
84
+ */
85
+ export function delegatesImportMap(root) {
86
+ return typeof root.importMap === "string" &&
87
+ !isRecord(root.imports) && !isRecord(root.scopes);
88
+ }
89
+ /**
90
+ * Merge the default Zuke tasks and `imports` into a `deno.json` document,
91
+ * preserving the existing content. `existing` is the file text, or `null` to
92
+ * start fresh; `imports` are the bare-specifier mappings the scaffolded build
93
+ * resolves through, and `buildFile` is the file the `zuke` task runs.
94
+ *
95
+ * Merging is additive per key: a task or import the document already declares
96
+ * is left exactly as it is (but for a `zuke` task setup wrote for another
97
+ * build file, which follows the build file), so a project that has pinned `@zuke/core` to a
98
+ * specific version keeps that pin. A document that delegates to an external
99
+ * `importMap` keeps that delegation and grows no `imports` block — see
100
+ * {@link delegatesImportMap}; the caller reports the entry as a manual step
101
+ * instead.
102
+ */
103
+ export function mergeDenoJson(existing, imports, buildFile) {
104
+ const root = {};
105
+ if (existing !== null) {
106
+ const parsed = JSON.parse(existing);
107
+ if (isRecord(parsed))
108
+ Object.assign(root, parsed);
109
+ }
110
+ // Seed `imports` before `tasks` so a file created from scratch lists the
111
+ // dependencies first, the order deno.json conventionally uses. On a file that
112
+ // already has either key, assigning it keeps its original position.
113
+ if (!delegatesImportMap(root)) {
114
+ mergeMissing(root, "imports", Object.entries(imports));
115
+ }
116
+ if (staleZukeTask(root.tasks, buildFile) && isRecord(root.tasks)) {
117
+ root.tasks = { ...root.tasks, zuke: `deno run -A ${buildFile}` };
118
+ }
119
+ mergeMissing(root, "tasks", defaultTasks(buildFile));
120
+ return `${JSON.stringify(root, null, 2)}\n`;
121
+ }
122
+ /**
123
+ * Classify a `deno.json` text by whether the scaffold has anything to add to
124
+ * it: the `zuke` task, or any of `imports`.
125
+ *
126
+ * The imports are part of the question because the build file is written by the
127
+ * same run and imports them by bare specifier. Treating the `zuke` task alone
128
+ * as "already set up" — as this did before the imports existed — would skip the
129
+ * file on a project being re-scaffolded and leave a `zuke.ts` whose specifiers
130
+ * nothing resolves.
131
+ */
132
+ export function denoJsonState(text, imports, buildFile) {
133
+ let parsed;
134
+ try {
135
+ parsed = JSON.parse(text);
136
+ }
137
+ catch {
138
+ return "unparseable";
139
+ }
140
+ if (!isRecord(parsed))
141
+ return "absent";
142
+ const hasTask = isRecord(parsed.tasks) && "zuke" in parsed.tasks &&
143
+ !staleZukeTask(parsed.tasks, buildFile);
144
+ // A document delegating to an external `importMap` will not grow an
145
+ // `imports` block (it would disable the delegation), so the imports are not
146
+ // something this file is still missing — they are reported as a manual step.
147
+ const declared = isRecord(parsed.imports) ? parsed.imports : {};
148
+ const hasImports = delegatesImportMap(parsed) ||
149
+ Object.keys(imports).every((s) => s in declared);
150
+ return hasTask && hasImports ? "present" : "absent";
151
+ }
152
+ /**
153
+ * The scaffold specifiers `root` maps somewhere other than their `jsr:@zuke/…`
154
+ * dependency, in declaration order.
155
+ *
156
+ * Keeping a mapping the project already declared is the right default — it is
157
+ * how a deliberate version pin, or a link to a local checkout, survives. But
158
+ * the run should not go on to report the dependency as simply "present", so the
159
+ * caller names what it found and leaves the decision to the reader.
160
+ */
161
+ export function remappedImports(root, imports) {
162
+ const declared = isRecord(root.imports) ? root.imports : {};
163
+ return Object.keys(imports).filter((specifier) => {
164
+ const value = declared[specifier];
165
+ return typeof value === "string" &&
166
+ !value.startsWith(`jsr:${specifier}@`);
167
+ });
168
+ }
169
+ /**
170
+ * The real, `Deno`-backed {@link SetupHost}. Every probe reads the link itself
171
+ * rather than its target (see {@link lstatOrNull}), so a symlink is reported
172
+ * as a symlink instead of as whatever it points at.
173
+ */
174
+ export const defaultHost = {
175
+ exists: (path) => FileTasks.exists(path),
176
+ async isDirectory(path) {
177
+ return (await lstatOrNull(path))?.isDirectory === true;
178
+ },
179
+ async isSymlink(path) {
180
+ return (await lstatOrNull(path))?.isSymlink === true;
181
+ },
182
+ readText(path) {
183
+ return FileTasks.readText(path);
184
+ },
185
+ async writeText(path, content) {
186
+ // Write beside the destination and rename into place, rather than writing
187
+ // to the destination directly. Renaming replaces a symbolic link sitting at
188
+ // the destination instead of following it, so the bytes cannot be
189
+ // redirected outside this directory even by a link planted after the
190
+ // pre-write check. The temporary name is created exclusively, so it cannot
191
+ // itself be a link someone left waiting.
192
+ const temp = `${path}.zuke-${crypto.randomUUID().slice(0, 8)}.tmp`;
193
+ try {
194
+ await FileTasks.writeText(temp, content, (s) => s.createNew());
195
+ await FileTasks.move(temp, path);
196
+ }
197
+ catch (error) {
198
+ // Best effort: a failed write may not have created the file at all.
199
+ await FileTasks.remove(temp).catch(() => { });
200
+ throw error;
201
+ }
202
+ },
203
+ chmod(path, mode) {
204
+ return FileTasks.chmod(path, mode);
205
+ },
206
+ log(message) {
207
+ output.info(message);
208
+ },
209
+ };
210
+ /** Join a directory and file name without pulling in path utilities. */
211
+ export function joinPath(dir, name) {
212
+ return dir === "." ? name : `${dir}/${name}`;
213
+ }
214
+ /** The default launcher base name. */
215
+ export const DEFAULT_LAUNCHER = "zuke";
216
+ /**
217
+ * Scaffold file names a launcher must not shadow (the config, and the Python
218
+ * build file; the TypeScript one is named per project).
219
+ */
220
+ const RESERVED_NON_LAUNCHER = new Set([
221
+ PYTHON_BUILD_FILE,
222
+ "zuke.json",
223
+ "deno.json",
224
+ ".gitignore",
225
+ MCP_CONFIG_FILE,
226
+ ]);
227
+ /**
228
+ * Validate a `--launcher-name`: a single path segment (so the launcher can't be
229
+ * written outside the target directory) that doesn't shadow another file setup
230
+ * writes, `buildFile` among them. Throws a friendly error otherwise.
231
+ */
232
+ function assertLauncherName(name, buildFile) {
233
+ // Reject path separators and a colon (a Windows drive/ADS separator), so the
234
+ // launcher can only be a plain file in the target directory.
235
+ if (name === "" || /[\\/:]/.test(name) || name === "." || name === "..") {
236
+ throw new Error(`zuke setup: invalid --launcher-name "${name}" — it must be a plain file ` +
237
+ `name (no path separators or ":").`);
238
+ }
239
+ // Compare case-insensitively: a case-insensitive filesystem (macOS, Windows)
240
+ // would let `Zuke.ts` shadow the `zuke.ts` setup writes.
241
+ const lower = name.toLowerCase();
242
+ if (RESERVED_NON_LAUNCHER.has(lower) || lower === buildFile.toLowerCase()) {
243
+ throw new Error(`zuke setup: --launcher-name "${name}" would overwrite a file setup ` +
244
+ `writes (the build file or config) — choose a different name.`);
245
+ }
246
+ }
247
+ /**
248
+ * The build file the TypeScript project in `dir` already has: the one its
249
+ * `zuke.json` names, `zuke.ts` when it names none, and `zuke.ts` too for a
250
+ * directory that holds one with no `zuke.json` yet. `undefined` for a
251
+ * directory with neither, which is a new project. A `zuke.json` that is a
252
+ * link is not read: scaffolding refuses it.
253
+ *
254
+ * @throws {Error} when `zuke.json` names a build file that is not a valid name.
255
+ */
256
+ export async function existingBuildFile(dir, host) {
257
+ const config = joinPath(dir, "zuke.json");
258
+ if (await host.exists(config) && !(await host.isSymlink(config))) {
259
+ return buildFileNamed(await host.readText(config));
260
+ }
261
+ return await host.exists(joinPath(dir, BUILD_FILE)) ? BUILD_FILE : undefined;
262
+ }
263
+ /**
264
+ * Whether `name` in `dir` is a file of the project's own that is not a Zuke
265
+ * build: it exists and does not import `@zuke/core`. A new project must not
266
+ * take such a name, because its `zuke.json` would point at an unrelated
267
+ * script, and `--force` would overwrite it.
268
+ */
269
+ export async function unrelatedBuildFile(dir, name, host) {
270
+ const path = joinPath(dir, name);
271
+ // A link or a directory there is refused by the collision check instead.
272
+ if (!(await host.exists(path)) || await host.isSymlink(path) ||
273
+ await host.isDirectory(path)) {
274
+ return false;
275
+ }
276
+ return !(await host.readText(path)).includes("@zuke/core");
277
+ }
278
+ /**
279
+ * The build file a TypeScript scaffold writes: the one asked for, else the
280
+ * project's own, else `build.ts`.
281
+ *
282
+ * @throws {Error} when the name asked for is not valid, differs from the one
283
+ * an existing project has, or would take over an unrelated file in a new
284
+ * project.
285
+ */
286
+ async function scaffoldBuildFile(options, host) {
287
+ const existing = await existingBuildFile(options.dir, host);
288
+ const asked = options.buildFile === undefined
289
+ ? undefined
290
+ : assertBuildFileName(options.buildFile);
291
+ if (existing !== undefined) {
292
+ // Setup does not move a build: it would have to overwrite whatever has
293
+ // the new name. The person renames the file, and setup follows zuke.json.
294
+ if (asked !== undefined && asked !== existing) {
295
+ throw new Error(`zuke setup: this project's build file is ${existing}, not ${asked}. ` +
296
+ `To rename it, rename the file, set "build": "${asked}" in ` +
297
+ "zuke.json, and re-run zuke setup --force to rewrite the launchers.");
298
+ }
299
+ return existing;
300
+ }
301
+ const name = asked ?? NEW_BUILD_FILE;
302
+ if (await unrelatedBuildFile(options.dir, name, host)) {
303
+ throw new Error(`zuke setup: ${joinPath(options.dir, name)} already exists and is not ` +
304
+ "a Zuke build, so it was left alone. Pass --build-file <name> to " +
305
+ "give the build another name.");
306
+ }
307
+ return name;
308
+ }
309
+ /**
310
+ * Scaffold Zuke into `options.dir`: a starter build file, the launcher scripts,
311
+ * and a `deno.json` task block. Existing files are skipped unless
312
+ * `options.force` is set; `deno.json` is always merged (never clobbered). Fails
313
+ * up front if a target name is occupied by a directory (see
314
+ * {@link SetupOptions.launcherName}).
315
+ */
316
+ export async function runSetup(options, host = defaultHost) {
317
+ const files = [];
318
+ const manualSteps = [];
319
+ const notes = [];
320
+ const launcher = options.launcherName ?? DEFAULT_LAUNCHER;
321
+ const sdk = options.sdk;
322
+ if (sdk !== undefined && options.buildFile !== undefined) {
323
+ throw new Error("zuke setup: --build-file names a TypeScript build file; a Python " +
324
+ `build is always ${PYTHON_BUILD_FILE}.`);
325
+ }
326
+ // The build file, the launchers, the task, the MCP entry and zuke.json all
327
+ // carry the one name. An SDK build has no TypeScript file to name.
328
+ const buildFile = sdk === undefined
329
+ ? await scaffoldBuildFile(options, host)
330
+ : BUILD_FILE;
331
+ assertLauncherName(launcher, buildFile);
332
+ const variant = { bootstrapDeno: options.bootstrapDeno ?? true, buildFile };
333
+ const scaffold = [
334
+ sdk === undefined
335
+ ? {
336
+ name: buildFile,
337
+ content: options.buildContent ?? starterBuild(options.name),
338
+ }
339
+ : {
340
+ name: PYTHON_BUILD_FILE,
341
+ content: options.buildContent ?? starterPythonBuild(options.name),
342
+ },
343
+ {
344
+ name: launcher,
345
+ content: sdk === undefined
346
+ ? launcherBash(variant)
347
+ : binaryLauncherBash({ download: variant.bootstrapDeno }, sdk.pin),
348
+ mode: 0o755,
349
+ launcher: true,
350
+ },
351
+ {
352
+ name: `${launcher}.ps1`,
353
+ content: sdk === undefined
354
+ ? launcherPwsh(variant)
355
+ : binaryLauncherPwsh({ download: variant.bootstrapDeno }, sdk.pin),
356
+ launcher: true,
357
+ },
358
+ {
359
+ name: "zuke.json",
360
+ content: sdk === undefined
361
+ ? starterConfig(options.name, buildFile)
362
+ : starterSdkConfig(options.name, sdk.pin.engine),
363
+ },
364
+ ];
365
+ // Fail before writing anything if a target name is occupied by a directory —
366
+ // a scaffolded file can't be written over a directory, and silently skipping
367
+ // it (the old behaviour) produced a launcher-less setup. Covers every name
368
+ // setup writes, including the separately-written deno.json and .gitignore.
369
+ const collisionTargets = [
370
+ ...scaffold.map((s) => ({ name: s.name, launcher: s.launcher === true })),
371
+ ...(sdk === undefined ? [{ name: "deno.json", launcher: false }] : []),
372
+ { name: ".gitignore", launcher: false },
373
+ ...(options.mcp ? [{ name: MCP_CONFIG_FILE, launcher: false }] : []),
374
+ ];
375
+ for (const item of collisionTargets) {
376
+ const path = joinPath(options.dir, item.name);
377
+ // A symlink at a scaffold name is refused for the same reason a directory
378
+ // is — nothing can be written there safely — but the stakes differ. Writing
379
+ // follows the link, so a repository that ships one (setup is precisely what
380
+ // a developer runs inside a freshly cloned project) would redirect the
381
+ // write to whatever it names, outside this directory entirely. Checked
382
+ // before any write, so a refusal leaves the tree untouched.
383
+ if (await host.isSymlink(path)) {
384
+ throw new Error(`zuke setup: refusing to write "${item.name}" — ${path} is a symbolic ` +
385
+ `link, and writing through it would modify the file it points at, ` +
386
+ `outside this directory. Replace the link with a regular file (or ` +
387
+ `remove it), then re-run setup.`);
388
+ }
389
+ if (await host.isDirectory(path)) {
390
+ throw new Error(`zuke setup: cannot write "${item.name}" — a directory exists at ` +
391
+ `${path}. ` +
392
+ (item.launcher
393
+ ? `Pass --launcher-name <name> to write the launcher under a ` +
394
+ `different name`
395
+ : `Move or rename that directory (${item.name} is reserved by ` +
396
+ `Zuke)`) +
397
+ `, then re-run setup.`);
398
+ }
399
+ }
400
+ for (const item of scaffold) {
401
+ const path = joinPath(options.dir, item.name);
402
+ const existed = await host.exists(path);
403
+ if (existed && !options.force) {
404
+ host.log(` skip ${item.name} (already exists)`);
405
+ files.push({ path: item.name, status: "skipped" });
406
+ continue;
407
+ }
408
+ await host.writeText(path, item.content);
409
+ if (item.mode !== undefined) {
410
+ try {
411
+ await host.chmod(path, item.mode);
412
+ }
413
+ catch {
414
+ // chmod is a no-op / unsupported on some platforms (e.g. Windows).
415
+ }
416
+ }
417
+ const status = existed ? "overwritten" : "created";
418
+ host.log(` ${existed ? "update" : "create"} ${item.name}`);
419
+ files.push({ path: item.name, status });
420
+ }
421
+ if (sdk === undefined) {
422
+ files.push(await setupDenoJson(options.dir, options.imports ?? STARTER_IMPORTS, buildFile, host, manualSteps, notes));
423
+ }
424
+ files.push(await setupGitignore(options.dir, host));
425
+ if (options.mcp) {
426
+ files.push(await setupMcpConfig(options.dir, options.force, host, notes,
427
+ // A hosted build is served by the zuke binary, whichever CLI
428
+ // registered it: its project needs nothing from Deno's stack. A
429
+ // TypeScript build stays on Deno.
430
+ sdk === undefined
431
+ ? mcpServerEntry(options.mcp.allowRun, buildFile)
432
+ : binaryMcpEntry(options.mcp.allowRun)));
433
+ }
434
+ return { files, manualSteps, notes };
435
+ }
436
+ /**
437
+ * Create or merge `.mcp.json` so the build's MCP server is registered as
438
+ * `entry`. An
439
+ * existing `zuke` entry is left alone unless `force` is set (it may carry a
440
+ * deliberate `--allow-run` choice); every other server in the file survives
441
+ * either way. An unparseable file is skipped, recorded in `notes` so the
442
+ * caller can report that `--mcp` did not take effect.
443
+ */
444
+ async function setupMcpConfig(dir, force, host, notes, entry) {
445
+ const name = MCP_CONFIG_FILE;
446
+ const path = joinPath(dir, name);
447
+ if (!(await host.exists(path))) {
448
+ await host.writeText(path, mergeMcpConfig({}, entry));
449
+ host.log(` create ${name}`);
450
+ return { path: name, status: "created" };
451
+ }
452
+ const config = parseMcpConfig(await host.readText(path));
453
+ if (config.state === "unparseable") {
454
+ host.log(` skip ${name} (unparseable, edit by hand)`);
455
+ // `--mcp` asked for the server to be registered and it was not, so say so
456
+ // in the result rather than only in a line of progress output. A note, not
457
+ // a manual step: the build itself runs regardless, only an agent client
458
+ // will not find it.
459
+ notes.push(`${path} could not be parsed, so the zuke MCP server was not ` +
460
+ `registered. Fix the file and re-run with --mcp to add it.`);
461
+ return { path: name, status: "skipped" };
462
+ }
463
+ if (config.state === "present" && !force) {
464
+ host.log(` skip ${name} (zuke server already registered)`);
465
+ return { path: name, status: "skipped" };
466
+ }
467
+ await host.writeText(path, mergeMcpConfig(config.document, entry));
468
+ host.log(` update ${name}`);
469
+ return { path: name, status: "overwritten" };
470
+ }
471
+ /** The line `setup` ensures is present in `.gitignore` for generated output. */
472
+ const GITIGNORE_ENTRY = ".zuke/";
473
+ /** Create or update `.gitignore` so the generated `.zuke/` folder is ignored. */
474
+ async function setupGitignore(dir, host) {
475
+ const name = ".gitignore";
476
+ const path = joinPath(dir, name);
477
+ if (!(await host.exists(path))) {
478
+ await host.writeText(path, `${GITIGNORE_ENTRY}\n`);
479
+ host.log(` create ${name}`);
480
+ return { path: name, status: "created" };
481
+ }
482
+ const before = await host.readText(path);
483
+ if (before.split(/\r?\n/).some((line) => line.trim() === GITIGNORE_ENTRY)) {
484
+ host.log(` skip ${name} (${GITIGNORE_ENTRY} already ignored)`);
485
+ return { path: name, status: "skipped" };
486
+ }
487
+ const separator = before === "" || before.endsWith("\n") ? "" : "\n";
488
+ await host.writeText(path, `${before}${separator}${GITIGNORE_ENTRY}\n`);
489
+ host.log(` update ${name}`);
490
+ return { path: name, status: "overwritten" };
491
+ }
492
+ /** The `imports` entries `steps` tells the reader to add, as JSON lines. */
493
+ function importLines(imports) {
494
+ return Object.entries(imports)
495
+ .map(([specifier, dependency]) => `"${specifier}": "${dependency}"`)
496
+ .join(", ");
497
+ }
498
+ /**
499
+ * Where an `importMap` field points, as a path inside the setup directory, or
500
+ * `null` when it points anywhere else.
501
+ *
502
+ * Only a plain relative path is resolved. An absolute path, a URL, or one
503
+ * climbing out with `..` names a file this directory does not own, and setup
504
+ * has no business reading it just to decide what to print — those report as
505
+ * unverified instead.
506
+ */
507
+ function delegatedMapPath(dir, importMap) {
508
+ const rel = importMap.replace(/^\.[\\/]/, "");
509
+ const escapes = rel === "" || rel.startsWith("/") || rel.startsWith("\\") ||
510
+ /^[a-z][a-z0-9+.-]*:/i.test(rel) || rel.split(/[\\/]/).includes("..");
511
+ return escapes ? null : joinPath(dir, rel);
512
+ }
513
+ /**
514
+ * Whether the import map at `path` already declares every scaffold specifier.
515
+ *
516
+ * Setup cannot write into a delegated import map — it is the project's file,
517
+ * in a shape setup did not choose — but it can read it, and must: without this
518
+ * a project that has already added the entry would be told to add it again on
519
+ * every run, and `setup` would never exit 0 on a correctly configured project.
520
+ * Anything unreadable or unparseable answers `false`, so an unverifiable map
521
+ * still gets the manual step rather than a silent pass.
522
+ */
523
+ async function delegatedMapDeclares(path, imports, host) {
524
+ try {
525
+ if (!(await host.exists(path)))
526
+ return false;
527
+ const parsed = JSON.parse(await host.readText(path));
528
+ if (!isRecord(parsed) || !isRecord(parsed.imports))
529
+ return false;
530
+ const declared = parsed.imports;
531
+ return Object.keys(imports).every((specifier) => specifier in declared);
532
+ }
533
+ catch {
534
+ return false;
535
+ }
536
+ }
537
+ /**
538
+ * Create or merge `deno.json`, returning what happened to it. `imports` are the
539
+ * bare specifiers the `buildFile` written alongside it resolves through, so the
540
+ * file is completed whenever any of them is missing — not only when the `zuke`
541
+ * task is.
542
+ *
543
+ * Two shapes cannot be completed automatically, and both are fatal to the
544
+ * scaffold now that the build resolves through this file rather than carrying
545
+ * its own `jsr:` specifier. They go into `steps` so the run reports an
546
+ * incomplete scaffold instead of pointing at a `./zuke` that cannot start:
547
+ *
548
+ * - **Unparseable.** `deno.json` is JSONC — Deno accepts `//` comments and
549
+ * trailing commas that `JSON.parse` rejects. Such a file is perfectly valid
550
+ * and must not be rewritten: doing so would strip the reader's comments.
551
+ * - **Delegated.** The document points `importMap` at a separate file, and
552
+ * `imports` belongs in *that* file (see {@link delegatesImportMap}).
553
+ */
554
+ async function setupDenoJson(dir, imports, buildFile, host, steps, notes) {
555
+ const name = "deno.json";
556
+ const path = joinPath(dir, name);
557
+ if (!(await host.exists(path))) {
558
+ await host.writeText(path, mergeDenoJson(null, imports, buildFile));
559
+ host.log(` create ${name}`);
560
+ return { path: name, status: "created" };
561
+ }
562
+ const before = await host.readText(path);
563
+ const state = denoJsonState(before, imports, buildFile);
564
+ if (state === "unparseable") {
565
+ host.log(` skip ${name} (not plain JSON, edit by hand)`);
566
+ steps.push(`${path} has comments or a trailing comma, so it could not be edited ` +
567
+ `without discarding them. Add to its "imports": ` +
568
+ `${importLines(imports)} — the scaffolded ${buildFile} will not run until ` +
569
+ `you do.`);
570
+ return { path: name, status: "skipped" };
571
+ }
572
+ const parsed = JSON.parse(before);
573
+ const root = isRecord(parsed) ? parsed : {};
574
+ if (delegatesImportMap(root)) {
575
+ // Writing `imports` here would make Deno ignore `importMap` and take the
576
+ // project's whole module resolution down with it. Ask for the entry only
577
+ // when the delegated map does not already carry it — otherwise a project
578
+ // that has done exactly this would be nagged on every run.
579
+ const delegated = String(root.importMap);
580
+ const target = delegatedMapPath(dir, delegated);
581
+ const already = target !== null &&
582
+ await delegatedMapDeclares(target, imports, host);
583
+ if (!already) {
584
+ steps.push(`${path} delegates its import map to ${delegated}, which Deno ignores ` +
585
+ `as soon as "imports" appears beside it. Add to that file's ` +
586
+ `"imports" instead: ${importLines(imports)} — the scaffolded ` +
587
+ `${buildFile} will not run until you do.`);
588
+ }
589
+ }
590
+ for (const specifier of remappedImports(root, imports)) {
591
+ notes.push(`${path} already maps "${specifier}" to something other than its JSR ` +
592
+ `package; setup kept that mapping. Check it is what you intend.`);
593
+ }
594
+ if (state === "present") {
595
+ host.log(` skip ${name} (zuke task and imports already declared)`);
596
+ return { path: name, status: "skipped" };
597
+ }
598
+ await host.writeText(path, mergeDenoJson(before, imports, buildFile));
599
+ host.log(` update ${name}`);
600
+ return { path: name, status: "overwritten" };
601
+ }
package/src/star.d.ts ADDED
@@ -0,0 +1,44 @@
1
+ /**
2
+ * The end-of-`setup` "star the repo" prompt: ask once, then help with the
3
+ * answer — star directly through an authenticated `gh`, fall back to opening
4
+ * the repository page in the browser, and fall back again to printing the URL.
5
+ * Every side effect sits behind {@link StarActions} so the flow is testable
6
+ * without a network, a `gh` install, or a browser.
7
+ *
8
+ * @module
9
+ */
10
+ import { BrowserTasks } from "@zuke/core";
11
+ import { GhTasks } from "@zuke/gh";
12
+ import type { SetupHost } from "./setup.ts";
13
+ import type { Prompter } from "../mod.ts";
14
+ /** The Zuke repository's home page. */
15
+ export declare const ZUKE_REPO_URL = "https://github.com/zuke-build/zuke";
16
+ /**
17
+ * The side effects behind {@link promptStar}, injectable so tests never spawn
18
+ * `gh` or a browser.
19
+ */
20
+ export interface StarActions {
21
+ /** Whether the `gh` CLI is installed and holds a login. */
22
+ ghAuthenticated(): Promise<boolean>;
23
+ /** Star the Zuke repository through `gh api`. */
24
+ starWithGh(): Promise<void>;
25
+ /** Open `url` in the default browser; `false` when it could not launch. */
26
+ openBrowser(url: string): Promise<boolean>;
27
+ }
28
+ /**
29
+ * Build the real {@link StarActions} over the given task functions. The
30
+ * parameters exist as seams — production uses the defaults ({@link GhTasks}
31
+ * and {@link BrowserTasks}); tests substitute fakes so no process is spawned.
32
+ */
33
+ export declare function realStarActions(runGh?: typeof GhTasks.run, apiGh?: typeof GhTasks.api, openUrl?: typeof BrowserTasks.open): StarActions;
34
+ /** The real {@link StarActions}, backed by `GhTasks` and `BrowserTasks`. */
35
+ export declare const defaultStarActions: StarActions;
36
+ /**
37
+ * Ask the user to star the Zuke repository and help with a yes. The `gh` login
38
+ * is probed *before* asking, so the question says what a yes will do: with an
39
+ * authenticated `gh`, that the star is placed on their behalf through it;
40
+ * without one, that the repository page opens in the browser (falling back to
41
+ * printing its URL). A "no" is respected silently, and no failure here ever
42
+ * fails the setup that just succeeded.
43
+ */
44
+ export declare function promptStar(host: SetupHost, prompter: Prompter, actions: StarActions): Promise<void>;