@decohere/ci-tools 0.0.1-dev.20261122.343 → 0.0.1-dev.20261122.349

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@decohere/ci-tools",
3
- "version": "0.0.1-dev.20261122.343",
3
+ "version": "0.0.1-dev.20261122.349",
4
4
  "description": "CI utility scripts for badge generation, coverage reporting, pages artifact assembly, and GitHub API tooling",
5
5
  "keywords": [
6
6
  "typescript",
@@ -1,5 +1,5 @@
1
1
  import { existsSync, readFileSync } from "node:fs";
2
- import { upsertIssue } from "../lib/github-issue.mjs";
2
+ import { resolveIssue, upsertIssue } from "../lib/github-issue.mjs";
3
3
  import { formatMarkdown, parseAudit } from "./format.mjs";
4
4
 
5
5
  const auditFilePath = process.argv[2] ?? "npm-audit.json";
@@ -23,7 +23,15 @@ if (!existsSync(auditFilePath)) {
23
23
 
24
24
  const parsed = parseAudit(JSON.parse(readFileSync(auditFilePath, "utf8")));
25
25
  if (parsed.total === 0) {
26
- console.log("No vulnerabilities found; skipping issue create/update.");
26
+ const closed = resolveIssue({
27
+ title: ISSUE_TITLE,
28
+ comment: `The audit finds nothing now (${runUrl()}), so this closes. It reopens if a finding comes back.`,
29
+ });
30
+ console.log(
31
+ closed == null
32
+ ? "No vulnerabilities found; no issue open."
33
+ : `No vulnerabilities found; closed issue #${closed}.`,
34
+ );
27
35
  process.exit(0);
28
36
  }
29
37
 
@@ -5,20 +5,26 @@
5
5
  * already done, so with nothing to do it changes nothing.
6
6
  *
7
7
  * npm login
8
- * pnpm npm:bootstrap --otp <code> [--dry-run] [--channel dev] [<package-name>...]
8
+ * pnpm npm:bootstrap --otp <code> [--dry-run] [<package-name>...]
9
9
  *
10
- * Without names: every publishable package. Everything is read first, in parallel, and then only
11
- * the missing steps run, so one OTP code (about 30 seconds) can cover them. npm wants the code even
12
- * to read a package's Trusted Publishers, so it is required, also for `--dry-run`.
10
+ * Without names: every publishable package in this checkout. A named package needn't be in it, so a
11
+ * new package's PR can be set up from `main`; one that isn't on npm yet must be in a package.json on
12
+ * some branch of the repo, so a typo can't claim a name. Everything is read first, in parallel, and
13
+ * then only the missing steps run, so one OTP code (about 30 seconds) can cover them. npm wants the
14
+ * code even to read a package's Trusted Publishers, so it is required, also for `--dry-run`.
13
15
  *
14
- * The first publish and the `publish.yml` publisher go through npm's CLI. The `promote-latest.yml`
16
+ * The first publish only claims the name: a stub with a package.json and a README, version
17
+ * `0.0.0-bootstrap.0`, so nothing from the checkout is shipped. CI publishes the package built.
18
+ * It and the `publish.yml` publisher go through npm's CLI. The `promote-latest.yml`
15
19
  * publisher is copied from a package that has it, through the registry endpoint `npm trust` uses,
16
20
  * because `npm trust` has no flag for the dist-tag permission (`manageDistTags`). npm doesn't
17
21
  * document that endpoint. The calls use the npm login in the user's npmrc, which is never printed.
18
22
  */
19
23
  import { spawnSync } from "node:child_process";
20
- import { readFileSync } from "node:fs";
21
- import { resolve } from "node:path";
24
+ import { randomUUID } from "node:crypto";
25
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
26
+ import { tmpdir } from "node:os";
27
+ import { join, resolve } from "node:path";
22
28
  import { parseArgs } from "node:util";
23
29
  import { pathToFileURL } from "node:url";
24
30
  import { listPublishablePackages } from "./publish-verify.mjs";
@@ -40,21 +46,68 @@ export const PROMOTE_WORKFLOW = "promote-latest.yml";
40
46
  * @typedef {(args: string[], options?: NpmOptions) => { status: number, output: string }} Npm
41
47
  */
42
48
 
43
- /** @param {string | undefined} version */
44
- export function needsPrereleaseTag(version) {
45
- return String(version ?? "").includes("-");
49
+ /** The stub's version: below any version CI publishes, and a prerelease, so it needs a tag. */
50
+ export const STUB_VERSION = "0.0.0-bootstrap.0";
51
+
52
+ /**
53
+ * npm arguments for the first publish, of the stub in `dir`. Scoped names default to restricted,
54
+ * so `--access public`; a prerelease needs a tag other than `latest`.
55
+ *
56
+ * @param {string} dir an absolute path, so npm doesn't read it as a GitHub `owner/repo`
57
+ */
58
+ export function publishArgs(dir) {
59
+ return ["publish", dir, "--access", "public", "--tag", "bootstrap"];
46
60
  }
47
61
 
48
62
  /**
49
- * npm arguments for a name-only first publish. Scoped names default to restricted,
50
- * so `--access public`. `./` stops npm reading the path as a GitHub `owner/repo`.
63
+ * Write the stub that claims a name: a package.json and a README, in a new temporary folder.
51
64
  *
52
- * @param {Package} pkg
53
- * @param {string} channel
65
+ * @param {string} name
66
+ * @returns {string} the folder
54
67
  */
55
- export function publishArgs(pkg, channel) {
56
- const tag = needsPrereleaseTag(pkg.version) ? ["--tag", channel] : [];
57
- return ["publish", `./projects/${pkg.dir}`, "--access", "public", ...tag];
68
+ export function writeStub(name) {
69
+ const dir = join(tmpdir(), `npm-bootstrap-${randomUUID()}`);
70
+ mkdirSync(dir, { recursive: true });
71
+ const manifest = {
72
+ name,
73
+ version: STUB_VERSION,
74
+ description: `Reserves ${name}. Its releases are published from CI.`,
75
+ license: "ISC",
76
+ repository: { type: "git", url: `git+https://github.com/${REPOSITORY}.git` },
77
+ };
78
+ writeFileSync(join(dir, "package.json"), `${JSON.stringify(manifest, null, 2)}\n`);
79
+ writeFileSync(
80
+ join(dir, "README.md"),
81
+ `# ${name}\n\nThis version only reserves the name. Install a release: see https://github.com/${REPOSITORY}.\n`,
82
+ );
83
+ return dir;
84
+ }
85
+
86
+ /**
87
+ * Whether a package of this name is in a package.json under projects/ on any branch of the repo,
88
+ * after fetching them.
89
+ *
90
+ * @param {string} name
91
+ * @param {string} root
92
+ */
93
+ async function isOnBranch(name, root) {
94
+ const git = (/** @type {string[]} */ args) =>
95
+ spawnSync("git", args, { cwd: root, encoding: "utf8" });
96
+ const fetched = git(["fetch", "--quiet", "origin"]);
97
+ if (fetched.status !== 0) throw new Error(`git fetch origin failed: ${fetched.stderr}`);
98
+ const refs = git(["for-each-ref", "--format=%(refname)", "refs/remotes/origin"])
99
+ .stdout.split("\n")
100
+ .filter((ref) => ref !== "" && !ref.endsWith("/HEAD"));
101
+ const found = git([
102
+ "grep",
103
+ "--fixed-strings",
104
+ "--files-with-matches",
105
+ `"name": "${name}"`,
106
+ ...refs,
107
+ "--",
108
+ "projects/**/package.json",
109
+ ]);
110
+ return found.status === 0;
58
111
  }
59
112
 
60
113
  /** @param {string} name */
@@ -167,6 +220,8 @@ function readLoginToken(npm) {
167
220
  * fetch?: typeof globalThis.fetch,
168
221
  * token?: () => string | undefined,
169
222
  * log?: (line: string) => void,
223
+ * isOnBranch?: (name: string) => Promise<boolean>,
224
+ * writeStub?: (name: string) => string,
170
225
  * },
171
226
  * }} [options]
172
227
  * @returns {Promise<number>} exit code
@@ -177,7 +232,6 @@ export async function runBootstrap(options = {}) {
177
232
  options: {
178
233
  otp: { type: "string" },
179
234
  "dry-run": { type: "boolean", default: false },
180
- channel: { type: "string", default: "dev" },
181
235
  },
182
236
  allowPositionals: true,
183
237
  });
@@ -203,12 +257,14 @@ export async function runBootstrap(options = {}) {
203
257
  return 1;
204
258
  }
205
259
 
206
- const publishable = listPublishablePackages(options.root ?? process.cwd());
207
- const unknown = positionals.filter((name) => !publishable.some((pkg) => pkg.name === name));
208
- if (unknown.length > 0) {
209
- log(`Not a publishable package in projects/: ${unknown.join(", ")}`);
210
- return 1;
211
- }
260
+ const root = options.root ?? process.cwd();
261
+ const inCheckout = listPublishablePackages(root);
262
+ // Named packages this checkout doesn't have, such as a new one whose PR isn't merged.
263
+ /** @type {Package[]} */
264
+ const elsewhere = positionals
265
+ .filter((name) => !inCheckout.some((pkg) => pkg.name === name))
266
+ .map((name) => ({ name, dir: "" }));
267
+ const publishable = [...inCheckout, ...elsewhere];
212
268
  const chosen =
213
269
  positionals.length > 0
214
270
  ? publishable.filter((pkg) => positionals.includes(pkg.name))
@@ -224,6 +280,20 @@ export async function runBootstrap(options = {}) {
224
280
  return { pkg, exists, trust: exists ? await npmRegistry.trust(pkg.name) : [] };
225
281
  }),
226
282
  );
283
+ // A name to claim must be a package somewhere in the repo, so a typo can't take one.
284
+ const checkBranch = io.isOnBranch ?? ((name) => isOnBranch(name, root));
285
+ const unknown = [];
286
+ for (const { pkg, exists } of state) {
287
+ if (elsewhere.includes(pkg) && !exists && !(await checkBranch(pkg.name))) {
288
+ unknown.push(pkg.name);
289
+ }
290
+ }
291
+ if (unknown.length > 0) {
292
+ log(
293
+ `Not a package on any branch of ${REPOSITORY}: ${unknown.join(", ")}. Nothing changed.`,
294
+ );
295
+ return 1;
296
+ }
227
297
  } catch (error) {
228
298
  log(`Nothing changed. ${String(error)}`);
229
299
  return 1;
@@ -267,11 +337,13 @@ export async function runBootstrap(options = {}) {
267
337
 
268
338
  for (const plan of plans) {
269
339
  const { pkg } = plan;
270
- log(`\n${pkg.name} (projects/${pkg.dir}, ${pkg.version})`);
340
+ log(
341
+ pkg.dir ? `\n${pkg.name} (projects/${pkg.dir})` : `\n${pkg.name} (not in this checkout)`,
342
+ );
271
343
 
272
344
  if (!plan.publish) {
273
345
  log(" name is on npm: skip the first publish");
274
- } else if (!runChange(publishArgs(pkg, values.channel))) {
346
+ } else if (!runChange(publishArgs((io.writeStub ?? writeStub)(pkg.name)))) {
275
347
  log(" first publish failed: stopping");
276
348
  return 1;
277
349
  }
@@ -37,25 +37,8 @@ export function pickIssue(issues, title) {
37
37
  export function upsertIssue(options, run = gh) {
38
38
  const { title, body, assignees = [] } = options;
39
39
  const repo = options.repo ? ["--repo", options.repo] : [];
40
- const issues = JSON.parse(
41
- run([
42
- "issue",
43
- "list",
44
- ...repo,
45
- "--state",
46
- "all",
47
- "--limit",
48
- "200",
49
- "--search",
50
- // Quoted: GitHub's search can't match a title like `security(ci): …` unquoted.
51
- // The exact-title match in pickIssue still decides.
52
- `"${title.replaceAll('"', "")}" in:title`,
53
- "--json",
54
- "number,title,state,url",
55
- ]),
56
- );
57
40
  const assign = assignees.flatMap((login) => ["--add-assignee", login]);
58
- const existing = pickIssue(issues, title);
41
+ const existing = pickIssue(listIssues(title, repo, run), title);
59
42
  if (existing != null) {
60
43
  if (existing.state !== "OPEN") {
61
44
  run(["issue", "reopen", String(existing.number), ...repo]);
@@ -73,3 +56,46 @@ export function upsertIssue(options, run = gh) {
73
56
  const number = Number(url.split("/").pop());
74
57
  return { number, url, created: true };
75
58
  }
59
+
60
+ /**
61
+ * Close the open issue titled `title`, saying why, once its subject is gone: the next upsert
62
+ * reopens it if it comes back.
63
+ *
64
+ * @param {{ title: string, comment: string, repo?: string }} options
65
+ * @param {typeof gh} [run]
66
+ * @returns {number | null} the issue closed, if one was open
67
+ */
68
+ export function resolveIssue(options, run = gh) {
69
+ const { title, comment } = options;
70
+ const repo = options.repo ? ["--repo", options.repo] : [];
71
+ const open = pickIssue(listIssues(title, repo, run), title);
72
+ if (open == null || open.state !== "OPEN") return null;
73
+ run(["issue", "close", String(open.number), ...repo, "--comment", comment]);
74
+ return open.number;
75
+ }
76
+
77
+ /**
78
+ * @param {string} title
79
+ * @param {string[]} repo
80
+ * @param {typeof gh} run
81
+ * @returns {{ number: number, title: string, state: string, url: string }[]}
82
+ */
83
+ function listIssues(title, repo, run) {
84
+ return JSON.parse(
85
+ run([
86
+ "issue",
87
+ "list",
88
+ ...repo,
89
+ "--state",
90
+ "all",
91
+ "--limit",
92
+ "200",
93
+ "--search",
94
+ // Quoted: GitHub's search can't match a title like `security(ci): …` unquoted.
95
+ // The exact-title match in pickIssue still decides.
96
+ `"${title.replaceAll('"', "")}" in:title`,
97
+ "--json",
98
+ "number,title,state,url",
99
+ ]),
100
+ );
101
+ }
@@ -1,3 +1,4 @@
1
+ import { readdirSync, readFileSync } from "node:fs";
1
2
  import { vol } from "memfs";
2
3
  import { afterEach, describe, expect, it } from "vitest";
3
4
  import { runBootstrap } from "../../src/github/npm-bootstrap.mjs";
@@ -46,11 +47,16 @@ const FULL = [PUBLISH, PROMOTE];
46
47
  function fakeNpm({ packages = {}, loggedIn = true, failPosting = [] } = {}) {
47
48
  const calls = [];
48
49
  const posts = [];
50
+ const published = [];
49
51
  const npm = (args, { otp } = {}) => {
50
52
  calls.push(`${args.join(" ")}${otp ? ` [otp ${otp}]` : ""}`);
51
53
  if (args[0] === "whoami") return { status: loggedIn ? 0 : 1, output: "" };
52
54
  // A first publish creates the name, with no Trusted Publishers yet.
53
- if (args[0] === "publish") packages[`@decohere/${args[1].split("/").at(-1)}`] = [];
55
+ if (args[0] === "publish") {
56
+ const stub = JSON.parse(readFileSync(`${args[1]}/package.json`, "utf8"));
57
+ published.push({ manifest: stub, files: readdirSync(args[1]).sort() });
58
+ packages[stub.name] = [];
59
+ }
54
60
  return { status: 0, output: "" };
55
61
  };
56
62
  const fetch = async (url, init = {}) => {
@@ -76,10 +82,14 @@ function fakeNpm({ packages = {}, loggedIn = true, failPosting = [] } = {}) {
76
82
  }
77
83
  return new Response(JSON.stringify(packages[name]));
78
84
  };
79
- return { npm, fetch, calls, posts };
85
+ return { npm, fetch, calls, posts, published };
80
86
  }
81
87
 
82
- async function run(argv, registry) {
88
+ /** Anything printed that names the stub's temporary folder, with the folder taken out. */
89
+ const STUB = /publish \/\S+ /g;
90
+ const plain = (lines) => lines.map((line) => line.replace(STUB, "publish <stub> "));
91
+
92
+ async function run(argv, registry, { onBranches = [] } = {}) {
83
93
  const lines = [];
84
94
  const code = await runBootstrap({
85
95
  argv,
@@ -89,9 +99,11 @@ async function run(argv, registry) {
89
99
  fetch: registry.fetch,
90
100
  token: () => LOGIN,
91
101
  log: (line) => lines.push(line),
102
+ isOnBranch: async (name) => onBranches.includes(name),
92
103
  },
93
104
  });
94
- return { code, output: lines.join("\n") };
105
+ registry.calls.splice(0, registry.calls.length, ...plain(registry.calls));
106
+ return { code, output: plain(lines).join("\n") };
95
107
  }
96
108
 
97
109
  afterEach(() => {
@@ -110,9 +122,19 @@ describe("npm-bootstrap", () => {
110
122
  expect(code).toBe(0);
111
123
  expect(registry.calls).toEqual([
112
124
  "whoami",
113
- "publish ./projects/scribe/scribe-console --access public --tag dev [otp 123456]",
125
+ "publish <stub> --access public --tag bootstrap [otp 123456]",
114
126
  "trust github @decohere/scribe-console --file publish.yml --repo typesmiths/decohere --env npm-publish --allow-publish --yes [otp 123456]",
115
127
  ]);
128
+ // Only a stub claims the name: none of the package's source, which CI publishes built.
129
+ expect(registry.published).toEqual([
130
+ {
131
+ manifest: expect.objectContaining({
132
+ name: "@decohere/scribe-console",
133
+ version: "0.0.0-bootstrap.0",
134
+ }),
135
+ files: ["README.md", "package.json"],
136
+ },
137
+ ]);
116
138
  expect(registry.posts).toEqual([
117
139
  {
118
140
  name: "@decohere/scribe-console",
@@ -257,9 +279,7 @@ describe("npm-bootstrap", () => {
257
279
  expect(code).toBe(0);
258
280
  expect(registry.calls).toEqual(["whoami"]);
259
281
  expect(registry.posts).toEqual([]);
260
- expect(output).toContain(
261
- "[dry run] npm publish ./projects/scribe/scribe-console --access public --tag dev",
262
- );
282
+ expect(output).toContain("[dry run] npm publish <stub> --access public --tag bootstrap");
263
283
  expect(output).toContain(
264
284
  "[dry run] copy the Trusted Publisher for promote-latest.yml to @decohere/http-fastify",
265
285
  );
@@ -271,10 +291,49 @@ describe("npm-bootstrap", () => {
271
291
  expect((await run(["--otp", "1"], loggedOut)).code).toBe(1);
272
292
  expect(loggedOut.calls).toEqual(["whoami"]);
273
293
 
274
- const typo = fakeNpm();
294
+ const typo = fakeNpm({ packages: { "@decohere/cli": FULL } });
275
295
  const { code, output } = await run(["--otp", "1", "@decohere/scribe-consol"], typo);
276
296
  expect(code).toBe(1);
277
- expect(output).toBe("Not a publishable package in projects/: @decohere/scribe-consol");
297
+ expect(output).toBe(
298
+ "Not a package on any branch of typesmiths/decohere: @decohere/scribe-consol. Nothing changed.",
299
+ );
300
+ expect(typo.calls).toEqual(["whoami"]);
301
+ });
302
+
303
+ it("sets up a new package named from a checkout that doesn't have it, such as main", async () => {
304
+ seedWorkspace();
305
+ const registry = fakeNpm({
306
+ packages: {
307
+ "@decohere/cli": FULL,
308
+ "@decohere/http-fastify": FULL,
309
+ "@decohere/scribe-console": FULL,
310
+ },
311
+ });
312
+
313
+ const { code } = await run(["--otp", "7", "@decohere/data-memory"], registry, {
314
+ onBranches: ["@decohere/data-memory"],
315
+ });
316
+
317
+ expect(code).toBe(0);
318
+ expect(registry.calls).toEqual([
319
+ "whoami",
320
+ "publish <stub> --access public --tag bootstrap [otp 7]",
321
+ "trust github @decohere/data-memory --file publish.yml --repo typesmiths/decohere --env npm-publish --allow-publish --yes [otp 7]",
322
+ ]);
323
+ expect(registry.published[0].manifest.name).toBe("@decohere/data-memory");
324
+ expect(registry.posts.map((p) => p.name)).toEqual(["@decohere/data-memory"]);
325
+ });
326
+
327
+ it("repairs a package on npm that this checkout doesn't have, with no branch to look it up on", async () => {
328
+ seedWorkspace();
329
+ const registry = fakeNpm({
330
+ packages: { "@decohere/cli": FULL, "@decohere/data-memory": [PUBLISH] },
331
+ });
332
+
333
+ const { code } = await run(["--otp", "7", "@decohere/data-memory"], registry);
334
+
335
+ expect(code).toBe(0);
336
+ expect(registry.posts.map((p) => p.name)).toEqual(["@decohere/data-memory"]);
278
337
  });
279
338
 
280
339
  it("never prints the login", async () => {
@@ -1,5 +1,5 @@
1
1
  import { describe, expect, it } from "vitest";
2
- import { pickIssue, upsertIssue } from "../../src/lib/github-issue.mjs";
2
+ import { pickIssue, resolveIssue, upsertIssue } from "../../src/lib/github-issue.mjs";
3
3
 
4
4
  const TITLE = "security(ci): high or critical npm audit findings";
5
5
 
@@ -82,4 +82,23 @@ describe("github-issue", () => {
82
82
  ["issue", "edit", "7"],
83
83
  ]);
84
84
  });
85
+
86
+ // The audit's issue stayed open, listing an advisory GitHub had withdrawn, because a clean
87
+ // run only skipped it.
88
+ it("closes the open issue with a comment once there is nothing to report", () => {
89
+ const { run, calls } = fakeGh([
90
+ { number: 85, title: TITLE, state: "OPEN", url: "u85" },
91
+ { number: 9, title: TITLE, state: "CLOSED", url: "u9" },
92
+ ]);
93
+ expect(resolveIssue({ title: TITLE, comment: "Clean now." }, run)).toBe(85);
94
+ expect(calls.slice(1)).toEqual([
95
+ { args: ["issue", "close", "85", "--comment", "Clean now."], input: undefined },
96
+ ]);
97
+ });
98
+
99
+ it("does nothing when no open issue has the title", () => {
100
+ const { run, calls } = fakeGh([{ number: 9, title: TITLE, state: "CLOSED", url: "u9" }]);
101
+ expect(resolveIssue({ title: TITLE, comment: "Clean now." }, run)).toBeNull();
102
+ expect(calls).toHaveLength(1);
103
+ });
85
104
  });