@wirecat/cli-base 0.97.0 → 0.98.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 (39) hide show
  1. package/CHANGELOG.md +66 -0
  2. package/dist/commands/document.js +1 -1
  3. package/dist/commands/registry.d.ts +2 -1
  4. package/dist/dev/adopt.d.ts +6 -0
  5. package/dist/dev/adopt.js +43 -0
  6. package/dist/dev/audit.js +2 -2
  7. package/dist/dev/conformance.d.ts +5 -0
  8. package/dist/dev/conformance.js +24 -4
  9. package/dist/dev/family.d.ts +10 -0
  10. package/dist/dev/family.js +41 -0
  11. package/dist/dev/lint.d.ts +5 -0
  12. package/dist/dev/lint.js +32 -7
  13. package/dist/dev/main.js +166 -23
  14. package/dist/dev/network.js +10 -2
  15. package/dist/http/index.d.ts +23 -2
  16. package/dist/http/index.js +61 -0
  17. package/dist/release/fragments.d.ts +17 -0
  18. package/dist/release/fragments.js +108 -0
  19. package/dist/release/index.d.ts +2 -0
  20. package/dist/release/index.js +2 -0
  21. package/dist/release/level.d.ts +2 -0
  22. package/dist/release/level.js +52 -0
  23. package/dist/standards/audit.d.ts +2 -0
  24. package/dist/standards/audit.js +2 -0
  25. package/dist/standards/flags-account.d.ts +3 -0
  26. package/dist/standards/flags-account.js +36 -0
  27. package/dist/standards/lint.d.ts +17 -1
  28. package/dist/standards/lint.js +22 -5
  29. package/dist/standards/tables.d.ts +1 -1
  30. package/dist/standards/tables.js +1 -1
  31. package/dist/standards/vocabulary.js +3 -0
  32. package/docs/standards/accounts.md +3 -3
  33. package/docs/standards/layout.md +1 -1
  34. package/docs/standards/lifecycle.md +4 -6
  35. package/docs/standards/output.md +2 -2
  36. package/docs/standards/releases.md +6 -4
  37. package/docs/standards/testing.md +1 -1
  38. package/docs/standards/toolchain.md +7 -3
  39. package/package.json +1 -1
package/dist/dev/main.js CHANGED
@@ -13,18 +13,20 @@ import * as v from "valibot";
13
13
  import { parseCommandsDocument } from "../commands/document.js";
14
14
  import { describeProgram } from "../commands/registry.js";
15
15
  import { taggedSection } from "../release/fold.js";
16
- import { changelogProblems, docsProblems, JOURNAL_IDS, markdownFiles, packageVersion, structureProblems, versionScript, } from "../release/index.js";
16
+ import { CHANGELOG_HEADINGS, changelogProblems, collectFragments, docsProblems, fragmentProblems, JOURNAL_IDS, levelledVersion, markdownFiles, packageVersion, readFragments, structureProblems, versionLevelProblem, versionScript, } from "../release/index.js";
17
17
  import { AUDIT_BLOCKS, defineParityGroups, PARITY_GROUPS, REQUIRED_ROOTS } from "../standards/audit.js";
18
18
  import { defineReasons } from "../standards/errors.js";
19
- import { baselineProblems, baselineSchema, LINT_RULES, OVERRIDE_BUDGET, OVERRIDE_RULE_REVIEW, overrideSchema, overridesProblems, rulesForReview, } from "../standards/lint.js";
19
+ import { baselineProblems, baselineSchema, LINT_RULES, OVERRIDE_BUDGET, OVERRIDE_RULE_REVIEW, overdue, overrideSchema, overridesDueSoon, overridesProblems, rulesForReview, } from "../standards/lint.js";
20
20
  import { issuesOf, RegistryError } from "../standards/registry.js";
21
21
  import { VOCABULARY } from "../standards/vocabulary.js";
22
22
  import { buildManifest, MANIFEST_FILE, ManifestError, manifestText } from "../wcat/manifest.js";
23
+ import { adopt } from "./adopt.js";
23
24
  import { auditClis, scorecardTable, snakeKeys } from "./audit.js";
24
25
  import { readCapabilities } from "./capabilities.js";
25
26
  import { CONFORMANCE_USAGE, conformanceCommand } from "./conformance.js";
27
+ import { familyPackages, installFamily } from "./family.js";
26
28
  import { changelogChange, landChange, landFold, newestTag, processShell, restoreChange } from "./land.js";
27
- import { baselineOf, judge, lintCommands, RUN_LOG_COMMANDS, walk } from "./lint.js";
29
+ import { baselineOf, judge, lintCommands, misfiled, RUN_LOG_COMMANDS, walk } from "./lint.js";
28
30
  import { readSources } from "./network.js";
29
31
  import { nextVersion } from "./next-version.js";
30
32
  import { readDeclarations } from "./result-shape.js";
@@ -49,6 +51,17 @@ const USAGE = `usage: cli-dev <command> [options]
49
51
  the tag; an entry the tag lacks missed that release and moves
50
52
  to the unreleased section. Prints a line when it changed the
51
53
  file. --land lands it on main through a pull request
54
+ adopt <x.y.z> [--package <name>] moves the CLI onto that version of a shared package
55
+ (@wirecat/cli-core): the pin in package.json, pnpm install,
56
+ then pnpm generate and ci:quick when the CLI has them
57
+ changelog fragments [--collect <x.y.z>] [--ids <A,B>] [--file <path>]
58
+ checks the changes/<branch>.md fragments (### headings of the
59
+ changelog, no journal ids); --collect adds them under that
60
+ version's section and deletes them
61
+ changelog level [--next <x.y.z>] [--file <path>]
62
+ fails when the top section's version is a lower level than its
63
+ headings need (Added: minor; a break: major, minor before
64
+ 1.0.0); --next prints the version a release of x.y.z needs
52
65
  docs-check [--rules <module>] [--ids <A,B>] [--pages]
53
66
  links, anchors and the changelog's shape; --pages also
54
67
  docs/ against docs/meta.json, the docs portal's structure
@@ -68,7 +81,7 @@ const USAGE = `usage: cli-dev <command> [options]
68
81
  is a JSON object of the CLI's own JSON Schemas by name
69
82
  audit (--cli <bin> | --commands <file>)... [--schemas <cli>=<file>]... [--reasons <cli>=<file>]...
70
83
  [--lint <cli>=<dir>]... [--capabilities <file>] [--complete] [--groups <file>] [--differences <file>]
71
- [--baseline <dir>] [--for <cli>] [--json] [--write-baseline]
84
+ [--baseline <dir>] [--for <cli>] [--json] [--write-baseline] [--family]
72
85
  several CLIs against every lint rule and against each other:
73
86
  required roots, same path same contract, same flag same
74
87
  meaning, same entity same schema, same failure same reason.
@@ -77,7 +90,12 @@ const USAGE = `usage: cli-dev <command> [options]
77
90
  rules by its own lint/ folder; the rest by --baseline
78
91
  (audit/baseline). --groups replaces PARITY_GROUPS with the
79
92
  JSON list of parity groups in that file; --differences adds
80
- to the groups in use
93
+ to the groups in use. --family takes this CLI's one --cli and
94
+ installs the latest published CLIs of the parity groups beside
95
+ it (npm, without install scripts), runs each in an empty home,
96
+ reads every CLI's commands info (so same-error-reason and
97
+ same-entity-schema are measured), and defaults --for to this
98
+ CLI, --lint to its lint/ and --groups to config/parity-groups.json
81
99
  bundle --bin <dist/bin/name.js> [--external <package>]... [--anchor <package>]... [--harmless <path>]...
82
100
  bundles the compiled bin with esbuild (a devDependency) into
83
101
  dist/bundle/ and turns the bin into its loader. --external keeps
@@ -125,10 +143,53 @@ const docsCheck = async (args, io) => {
125
143
  ...(values.pages ? structureProblems(root) : []),
126
144
  ], "docs: ok");
127
145
  };
146
+ /** `changes/<branch>.md` fragments: checked, or collected into `--collect <version>`'s section and deleted. */
147
+ const fragments = (args, io) => {
148
+ const { values } = parseArgs({
149
+ args,
150
+ options: {
151
+ collect: { type: "string" },
152
+ ids: { type: "string" },
153
+ file: { type: "string", default: "CHANGELOG.md" },
154
+ },
155
+ });
156
+ const rules = {
157
+ headings: CHANGELOG_HEADINGS,
158
+ ids: [...JOURNAL_IDS, ...(values.ids?.split(",").filter(Boolean) ?? [])],
159
+ };
160
+ const found = readFragments(io.cwd);
161
+ const problems = found.flatMap((fragment) => fragmentProblems(fragment, rules));
162
+ if (problems.length > 0 || !values.collect || found.length === 0)
163
+ return report(io, problems, `changes/: ${found.length} fragments, all well formed`);
164
+ const file = isAbsolute(values.file) ? values.file : join(io.cwd, values.file);
165
+ writeFileSync(file, collectFragments(readFileSync(file, "utf8"), values.collect, found, rules));
166
+ for (const fragment of found)
167
+ rmSync(join(io.cwd, "changes", fragment.name));
168
+ io.out(`collected ${found.length} changelog fragments into ${values.collect}`);
169
+ return 0;
170
+ };
171
+ /** The top section's version level: with `--next <x.y.z>`, the version it needs; without, whether it has it. */
172
+ const level = (args, io) => {
173
+ const { values } = parseArgs({
174
+ args,
175
+ options: { next: { type: "string" }, file: { type: "string", default: "CHANGELOG.md" } },
176
+ });
177
+ const text = readFileSync(isAbsolute(values.file) ? values.file : join(io.cwd, values.file), "utf8");
178
+ if (values.next) {
179
+ io.out(levelledVersion(text, values.next));
180
+ return 0;
181
+ }
182
+ const problem = versionLevelProblem(text);
183
+ return report(io, problem ? [problem] : [], `${values.file}: the top section's version fits its headings`);
184
+ };
128
185
  const changelog = (args, io) => {
129
186
  const [action, ...rest] = args;
187
+ if (action === "fragments")
188
+ return fragments(rest, io);
189
+ if (action === "level")
190
+ return level(rest, io);
130
191
  if (action !== "fold" && action !== "restore") {
131
- io.err(`cli-dev changelog: no action "${action ?? ""}" — the ones there are: fold, restore`);
192
+ io.err(`cli-dev changelog: no action "${action ?? ""}" — the ones there are: fold, restore, fragments, level`);
132
193
  return 2;
133
194
  }
134
195
  const { values } = parseArgs({
@@ -295,16 +356,18 @@ const readJson = (path) => {
295
356
  throw new Error(`${path}: ${error.message}`);
296
357
  }
297
358
  };
298
- const commandsJson = (io, cli, file, commandArgs = ["commands", "--json"]) => {
359
+ const commandsJson = (io, cli, file, commandArgs = ["commands", "--json"], isolated = false) => {
299
360
  if (file)
300
361
  return readJson(isAbsolute(file) ? file : join(io.cwd, file));
301
362
  const bin = cli ?? "";
302
363
  const script = /\.[cm]?js$/.test(bin);
303
- const run = spawn.sync(script ? process.execPath : bin, [...(script ? [bin] : []), ...commandArgs], {
304
- cwd: io.cwd,
305
- encoding: "utf8",
306
- maxBuffer: 64 * 1024 * 1024,
307
- });
364
+ const run = isolated
365
+ ? inEmptyHome(io.cwd, bin, process.env, (call) => call(commandArgs))
366
+ : spawn.sync(script ? process.execPath : bin, [...(script ? [bin] : []), ...commandArgs], {
367
+ cwd: io.cwd,
368
+ encoding: "utf8",
369
+ maxBuffer: 64 * 1024 * 1024,
370
+ });
308
371
  if (run.error || run.status !== 0)
309
372
  throw new Error(`${bin} commands --json failed: ${run.error?.message ?? String(run.stderr).trim().split("\n")[0]}`);
310
373
  return JSON.parse(String(run.stdout));
@@ -342,6 +405,8 @@ export const inEmptyHome = (cwd, bin, environment, body) => {
342
405
  APPDATA: join(home, "AppData", "Roaming"),
343
406
  LOCALAPPDATA: join(home, "AppData", "Local"),
344
407
  CI: "true",
408
+ // An empty HOME does not hide the keyring: D-Bus reaches it all the same.
409
+ DBUS_SESSION_BUS_ADDRESS: "disabled:",
345
410
  ...(environment.SystemRoot ? { SystemRoot: environment.SystemRoot } : {}),
346
411
  };
347
412
  const script = /\.[cm]?js$/.test(bin);
@@ -350,7 +415,7 @@ export const inEmptyHome = (cwd, bin, environment, body) => {
350
415
  env,
351
416
  encoding: "utf8",
352
417
  timeout: 60_000,
353
- maxBuffer: 16 * 1024 * 1024,
418
+ maxBuffer: 64 * 1024 * 1024,
354
419
  });
355
420
  try {
356
421
  return body(call);
@@ -480,13 +545,22 @@ const lintRun = (args, io) => {
480
545
  }
481
546
  }
482
547
  const verdict = judge(violations, baseline, ruleOverrides, budget);
548
+ // A low rule is advice: it is printed and never fails, so polishing help text never holds a merge.
549
+ const advice = (rule) => severity.get(rule) === "low";
550
+ const advised = [];
483
551
  for (const id of verdict.unknownRules)
484
552
  problems.push(`no lint rule "${id}" (named in ${values.baseline} or ${values.overrides})`);
485
553
  for (const found of verdict.fresh)
486
- problems.push(`${severity.get(found.rule) ?? "?"} ${found.rule} ${found.target}: ${found.message}`);
487
- const stale = verdict.stale.map((entry) => entry.in === "baseline"
554
+ (advice(found.rule) ? advised : problems).push(`${severity.get(found.rule) ?? "?"} ${found.rule} ${found.target}: ${found.message}`);
555
+ const staleLine = (entry) => entry.in === "baseline"
488
556
  ? `stale baseline entry, fixed or overridden — remove it: ${values.baseline}/${entry.rule}.json "${entry.target}"`
489
- : `stale override, no such violation — remove it: ${entry.rule} "${entry.target}"`);
557
+ : `stale override, no such violation — remove it: ${entry.rule} "${entry.target}"`;
558
+ const stale = verdict.stale.filter((entry) => !advice(entry.rule)).map(staleLine);
559
+ advised.push(...verdict.stale.filter((entry) => advice(entry.rule)).map(staleLine));
560
+ advised.push(...overridesDueSoon(overrides, today(io)).map((line) => `${values.overrides}: ${line}`));
561
+ // Like a stale entry, a misfiled one is the CLI's cleanup when a shared package's CI lints it.
562
+ for (const line of misfiled(parsed.document, baseline, ruleOverrides))
563
+ stale.push(line);
490
564
  if (!values["allow-stale"])
491
565
  problems.push(...stale);
492
566
  const warnings = wcatWarnings(io.cwd, values.cli);
@@ -505,6 +579,8 @@ const lintRun = (args, io) => {
505
579
  if (values["allow-stale"])
506
580
  for (const line of stale)
507
581
  io.err(`warning ${line}`);
582
+ for (const line of advised)
583
+ io.err(`warning ${line}`);
508
584
  if (!existsSync(join(io.cwd, MANIFEST_FILE)))
509
585
  io.err(`undeclared-host: skipped, no ${MANIFEST_FILE}`);
510
586
  if (declarations.files.length === 0)
@@ -547,14 +623,54 @@ const byCli = (pairs, flag) => new Map((pairs ?? []).map((pair) => {
547
623
  }));
548
624
  const audit = (args, io) => {
549
625
  try {
550
- return auditRun(args, io);
626
+ return args.includes("--family") ? auditFamily(args, io) : auditRun(args, io);
551
627
  }
552
628
  catch (error) {
553
629
  io.err(error.message);
554
630
  return 2;
555
631
  }
556
632
  };
557
- const auditRun = (args, io) => {
633
+ /** The built CLI against the latest published one of every other CLI in the parity groups, as `scripts/audit.sh` did. */
634
+ const auditFamily = (args, io) => {
635
+ const { values } = parseArgs({
636
+ args,
637
+ strict: false,
638
+ options: {
639
+ cli: { type: "string", multiple: true },
640
+ commands: { type: "string", multiple: true },
641
+ groups: { type: "string" },
642
+ for: { type: "string" },
643
+ lint: { type: "string", multiple: true },
644
+ },
645
+ });
646
+ const [own, ...more] = (values.cli ?? []);
647
+ if (!own || more.length > 0 || values.commands) {
648
+ io.err("audit --family takes one --cli: this CLI's built bin");
649
+ return 2;
650
+ }
651
+ const name = commandsJson(io, own, undefined, undefined, true).cli;
652
+ if (typeof name !== "string")
653
+ throw new Error(`${own} commands --json names no cli`);
654
+ const local = (path) => (existsSync(join(io.cwd, path)) ? path : undefined);
655
+ const groupsFile = values.groups ?? local("config/parity-groups.json");
656
+ const groups = groupsFile ? defineParityGroups(readJson(join(io.cwd, groupsFile))) : PARITY_GROUPS;
657
+ const lintDir = values.lint ? undefined : local("lint");
658
+ const family = installFamily(familyPackages(groups, name));
659
+ try {
660
+ return auditRun([
661
+ ...args.filter((arg) => arg !== "--family"),
662
+ ...[...family.bins.values()].flatMap((bin) => ["--cli", bin]),
663
+ ...(values.for ? [] : ["--for", name]),
664
+ ...(values.groups || !groupsFile ? [] : ["--groups", groupsFile]),
665
+ ...(lintDir ? ["--lint", `${name}=${lintDir}`] : []),
666
+ ], io, true);
667
+ }
668
+ finally {
669
+ family.close();
670
+ }
671
+ };
672
+ const FAMILY_REPORTS = new Set(["same-entity-schema", "same-error-reason"]);
673
+ const auditRun = (args, io, family = false) => {
558
674
  const started = Date.now();
559
675
  const { values } = parseArgs({
560
676
  args,
@@ -575,7 +691,7 @@ const auditRun = (args, io) => {
575
691
  },
576
692
  });
577
693
  const raws = [
578
- ...(values.cli ?? []).map((bin) => commandsJson(io, bin, undefined)),
694
+ ...(values.cli ?? []).map((bin) => commandsJson(io, bin, undefined, undefined, family)),
579
695
  ...(values.commands ?? []).map((file) => commandsJson(io, undefined, file)),
580
696
  ];
581
697
  if (raws.length < 2) {
@@ -588,10 +704,11 @@ const auditRun = (args, io) => {
588
704
  const lintDirs = byCli(values.lint, "--lint");
589
705
  const problems = [];
590
706
  const evidence = new Map();
591
- if (values.complete) {
707
+ // The family audit reads every CLI's reasons and schemas, so same-error-reason and same-entity-schema are measured.
708
+ if (values.complete || family) {
592
709
  for (const [index, bin] of (values.cli ?? []).entries()) {
593
710
  const raw = raws[index];
594
- const data = commandsJson(io, bin, undefined, ["commands", "info", "--json"]);
711
+ const data = commandsJson(io, bin, undefined, ["commands", "info", "--json"], family);
595
712
  if (typeof raw.cli === "string")
596
713
  evidence.set(raw.cli, data);
597
714
  }
@@ -602,6 +719,8 @@ const auditRun = (args, io) => {
602
719
  throw new Error(`a commands document is not the shape cli-base's commandsDocument() writes: ${parsed.problems[0]}`);
603
720
  const cli = parsed.document.cli;
604
721
  const input = { document: parsed.document, raw, ...evidence.get(cli) };
722
+ if (family && input.reasons)
723
+ input.reasons = defineReasons(input.reasons);
605
724
  const schemaFile = schemas.get(cli);
606
725
  if (schemaFile)
607
726
  input.schemas = readJson(at(schemaFile));
@@ -687,6 +806,7 @@ const auditRun = (args, io) => {
687
806
  absent: v.optional(v.string()),
688
807
  only: v.optional(v.string()),
689
808
  reason: v.string(),
809
+ review_after: v.optional(v.string()),
690
810
  }));
691
811
  const parsed = v.safeParse(schema, readJson(at(values.differences)));
692
812
  if (!parsed.success)
@@ -702,6 +822,11 @@ const auditRun = (args, io) => {
702
822
  ],
703
823
  })));
704
824
  }
825
+ const differences = groups.flatMap((group) => group.differences);
826
+ for (const line of overdue(differences, today(io)))
827
+ problems.push(`parity difference: ${line}`);
828
+ for (const line of overridesDueSoon(differences, today(io), "the audit"))
829
+ io.err(`warning parity difference: ${line}`);
705
830
  const result = auditClis(inputs, {
706
831
  ...(values.capabilities ? { capabilities: readCapabilities(readJson(at(values.capabilities))) } : {}),
707
832
  groups,
@@ -734,8 +859,16 @@ const auditRun = (args, io) => {
734
859
  }));
735
860
  else
736
861
  io.out(scorecardTable(result.rows));
737
- for (const finding of result.blocking)
738
- problems.push(`new ${finding.rule} ${finding.target}: ${finding.message}`);
862
+ for (const finding of result.blocking) {
863
+ const line = `new ${finding.rule} ${finding.target}: ${finding.message}`;
864
+ // Measured for the first time by the family audit, and strict, so no baseline can hold them: shown, not failed.
865
+ if (family && FAMILY_REPORTS.has(finding.rule))
866
+ io.err(`warning ${line}`);
867
+ else
868
+ problems.push(line);
869
+ }
870
+ if (values.for === undefined && result.rows.some((row) => row.fixed > 0))
871
+ io.err(`warning ${values.baseline} holds rows no CLI has any more (the "fixed" column): remove them with --write-baseline`);
739
872
  io.err(`audit: ${inputs.length} CLIs, ${result.findings.length} findings, ${result.blocking.length} new that block${AUDIT_BLOCKS === "never" ? " (cross-CLI divergences do not block)" : ""}`);
740
873
  for (const problem of problems)
741
874
  io.err(problem);
@@ -827,6 +960,16 @@ export const main = async (argv, io) => {
827
960
  return audit(args, io);
828
961
  case "bundle":
829
962
  return bundleCommand(args, io);
963
+ case "adopt": {
964
+ const { values, positionals } = parseArgs({
965
+ args,
966
+ allowPositionals: true,
967
+ options: { package: { type: "string", default: "@wirecat/cli-core" } },
968
+ });
969
+ const [version = ""] = positionals;
970
+ const run = (command, commandArgs) => spawn.sync(command, [...commandArgs], { cwd: io.cwd, stdio: "inherit" }).status ?? 1;
971
+ return adopt(io.cwd, values.package, version, run, io.err);
972
+ }
830
973
  case "help":
831
974
  case "--help":
832
975
  case "-h":
@@ -48,8 +48,16 @@ const opensNothing = (module, clause) => {
48
48
  .filter((binding) => binding !== "" && !binding.startsWith("type "))
49
49
  .every((binding) => allowed.has(binding.split(/\s+as\s+/)[0]));
50
50
  };
51
- // A file that binds its own `fetch` (an injected FetchLike, `const fetch = hostFetch(…)`) calls that one.
52
- const BINDS_FETCH = /\b(?:const|let|var|function)\s+fetch\b|[{,(]\s*fetch\s*[,}):=]/;
51
+ // A file that binds its own `fetch` (an injected FetchLike, `const fetch = hostFetch(…)`) calls that one. Only a
52
+ // declaration binds it: a typed or defaulted parameter, a destructuring pattern, an arrow's own parameter. An object
53
+ // key (`{ fetch: deps.fetch ?? fetch }`) or an argument (`call(fetch)`) hands the global on and binds nothing.
54
+ const BINDS_FETCH = new RegExp([
55
+ String.raw `\b(?:const|let|var|function)\s+fetch\b`,
56
+ String.raw `[(,]\s*fetch\s*\??\s*:\s*(?:typeof\b|[A-Z(])`,
57
+ String.raw `[(,]\s*fetch\s*=(?![=>])`,
58
+ String.raw `\{[^{}]*(?<![\w$.:]\s*)\bfetch\b(?!\s*:)[^{}]*\}\s*(?::|=(?![=>]))`,
59
+ String.raw `(?:\(\s*fetch\s*\)|\bfetch)\s*=>`,
60
+ ].join("|"));
53
61
  const GLOBAL_FETCH = /(?<!\btypeof\s+)\b(?:globalThis|window|self)\s*\.\s*fetch\b/;
54
62
  // A call, or a value handed on to be called later (`options.fetch ?? fetch`); a key (`fetch:`) or a type reaches nothing.
55
63
  const GLOBAL_FETCH_USE = /(?<![\w$.#]|\btypeof\s+)fetch\b(?![\w$]|\s*\??\s*:)/;
@@ -5,8 +5,9 @@
5
5
  * status-code semantics and `Retry-After` parsing. Import `@wirecat/cli-base/http` only when
6
6
  * the thing on the other end is actually HTTP.
7
7
  */
8
- import type { ErrorCode } from "../errors.js";
9
- import type { WallClock } from "../time.js";
8
+ import { type ErrorCode } from "../errors.js";
9
+ import { type RetryConfig } from "../retry.js";
10
+ import { type SleepLike, type WallClock } from "../time.js";
10
11
  /** The one function an HTTP client needs from its environment. A Worker, a browser, a test and Node all satisfy it. */
11
12
  export type FetchLike = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
12
13
  /** `Retry-After` is either a number of seconds or an HTTP date. Both forms occur in the wild. */
@@ -20,3 +21,23 @@ export declare const statusToCode: (status: number) => ErrorCode;
20
21
  export { type JsonResponseOptions, readJsonResponse } from "./body.js";
21
22
  export { HOST_FETCH_TIMEOUT_MS, type HostFetchOptions, hostFetch } from "./fetch.js";
22
23
  export { HOST_PATTERN, hostCovered, hostProblems } from "./hosts.js";
24
+ /** cli-core's `Pacer` fits: one queue for every process of a profile, since a provider's limit is per account. */
25
+ export interface PacerLike {
26
+ /** The epoch milliseconds at which this request may go. */
27
+ reserve(): Promise<number>;
28
+ /** Everyone waits this long, because the provider said so. */
29
+ holdFor(ms: number): Promise<void>;
30
+ }
31
+ export interface RetryingOptions {
32
+ retry?: RetryConfig;
33
+ /** Which requests may be sent again after a failure. A write is sent again only when the provider refused it (429). */
34
+ reads?: (method: string, url: URL) => boolean;
35
+ pacer?: PacerLike;
36
+ /** The most the retries and pacing of one request may wait in all; more ends it with the last answer. */
37
+ budget?: number;
38
+ sleep?: SleepLike;
39
+ now?: WallClock;
40
+ random?: () => number;
41
+ }
42
+ /** `fetch` that waits and sends again: reads on a retryable status or error, writes only on 429. */
43
+ export declare const retrying: (send: FetchLike, options?: RetryingOptions) => FetchLike;
@@ -1,3 +1,13 @@
1
+ /**
2
+ * The HTTP layer, deliberately behind its own entry point.
3
+ *
4
+ * A CLI that speaks a socket, a message bus or a local database has no business depending on
5
+ * status-code semantics and `Retry-After` parsing. Import `@wirecat/cli-base/http` only when
6
+ * the thing on the other end is actually HTTP.
7
+ */
8
+ import { CliError, isCliError } from "../errors.js";
9
+ import { backoffMs, DEFAULT_RETRY } from "../retry.js";
10
+ import { realSleep, wallClock } from "../time.js";
1
11
  /** `Retry-After` is either a number of seconds or an HTTP date. Both forms occur in the wild. */
2
12
  export const parseRetryAfter = (header, now) => {
3
13
  if (!header)
@@ -46,3 +56,54 @@ export const statusToCode = (status) => {
46
56
  export { readJsonResponse } from "./body.js";
47
57
  export { HOST_FETCH_TIMEOUT_MS, hostFetch } from "./fetch.js";
48
58
  export { HOST_PATTERN, hostCovered, hostProblems } from "./hosts.js";
59
+ const SAFE = new Set(["GET", "HEAD", "OPTIONS"]);
60
+ /** `fetch` that waits and sends again: reads on a retryable status or error, writes only on 429. */
61
+ export const retrying = (send, options = {}) => {
62
+ const { retry = DEFAULT_RETRY, reads = (method) => SAFE.has(method), pacer, budget = Number.POSITIVE_INFINITY, sleep = realSleep, now = wallClock, random = Math.random, } = options;
63
+ return async (input, init = {}) => {
64
+ const request = input instanceof Request ? input : undefined;
65
+ const method = (init.method ?? request?.method ?? "GET").toUpperCase();
66
+ const read = reads(method, new URL(request?.url ?? String(input)));
67
+ const signal = init.signal ?? request?.signal ?? undefined;
68
+ const once = init.body instanceof ReadableStream;
69
+ let waited = 0;
70
+ const pause = async (ms) => {
71
+ waited += ms;
72
+ await sleep(ms, signal, "retry");
73
+ };
74
+ for (let attempt = 1;; attempt++) {
75
+ if (pacer) {
76
+ const wait = (await pacer.reserve()) - now().getTime();
77
+ if (wait > 0) {
78
+ if (waited + wait > budget)
79
+ throw new CliError("rate_limited", `the provider's pace needs a ${wait} ms wait, more than this run allows`, {
80
+ retry_after_ms: wait,
81
+ sent: false,
82
+ });
83
+ await pause(wait);
84
+ }
85
+ }
86
+ const last = once || attempt > retry.retries;
87
+ try {
88
+ const response = await send(request && !last ? request.clone() : input, init);
89
+ if (last || !retryableStatus(response.status) || !(read || response.status === 429))
90
+ return response;
91
+ const wait = providerWaitMs(response.headers, now) ?? backoffMs(attempt, retry, random);
92
+ if (wait > retry.maxRetryAfterMs || waited + wait > budget)
93
+ return response;
94
+ await response.body?.cancel().catch(() => { });
95
+ if (response.status === 429)
96
+ await pacer?.holdFor(wait);
97
+ await pause(wait);
98
+ }
99
+ catch (error) {
100
+ if (last || !read || signal?.aborted || !isCliError(error) || error.details.retryable !== true)
101
+ throw error;
102
+ const wait = backoffMs(attempt, retry, random);
103
+ if (waited + wait > budget)
104
+ throw error;
105
+ await pause(wait);
106
+ }
107
+ }
108
+ };
109
+ };
@@ -0,0 +1,17 @@
1
+ export type Fragment = {
2
+ name: string;
3
+ text: string;
4
+ };
5
+ /** The changelog's `###` headings in the WireCat CLIs, in their order. */
6
+ export declare const CHANGELOG_HEADINGS: readonly ["Added", "Changed — may break callers", "Fixed", "Security", "Removed"];
7
+ export type FragmentRules = {
8
+ headings: readonly string[];
9
+ ids: readonly string[];
10
+ };
11
+ export declare const readFragments: (root: string) => Fragment[];
12
+ export declare const fragmentProblems: ({ name, text }: Fragment, { headings, ids }: FragmentRules) => string[];
13
+ /**
14
+ * Adds every fragment's entries under the same-named heading of `## <version> — `, after the entries already there,
15
+ * fragments in name order. A fragment links from `changes/`, so `../` is dropped for CHANGELOG.md at the root.
16
+ */
17
+ export declare const collectFragments: (changelog: string, version: string, fragments: Fragment[], { headings }: Pick<FragmentRules, "headings">) => string;
@@ -0,0 +1,108 @@
1
+ /**
2
+ * Changelog fragments: each pull request adds `changes/<branch>.md` instead of editing `## Unreleased`, so open
3
+ * pull requests do not conflict in CHANGELOG.md. A release collects them into the version's section and deletes
4
+ * them in the release commit (`cli-dev changelog fragments`). Moved here from b24 and cli-core, which kept copies.
5
+ */
6
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
7
+ import { join } from "node:path";
8
+ import { idPattern } from "./markdown.js";
9
+ /** The changelog's `###` headings in the WireCat CLIs, in their order. */
10
+ export const CHANGELOG_HEADINGS = ["Added", "Changed — may break callers", "Fixed", "Security", "Removed"];
11
+ const NAME = /^[a-z0-9][a-z0-9._-]*\.md$/;
12
+ export const readFragments = (root) => {
13
+ const directory = join(root, "changes");
14
+ if (!existsSync(directory))
15
+ return [];
16
+ return readdirSync(directory, { withFileTypes: true })
17
+ .filter((entry) => entry.isFile() && entry.name.endsWith(".md") && entry.name !== "README.md")
18
+ .map((entry) => ({ name: entry.name, text: readFileSync(join(directory, entry.name), "utf8") }))
19
+ .sort((a, b) => (a.name < b.name ? -1 : 1));
20
+ };
21
+ export const fragmentProblems = ({ name, text }, { headings, ids }) => {
22
+ const file = `changes/${name}`;
23
+ const id = idPattern(ids);
24
+ const problems = [];
25
+ if (!NAME.test(name))
26
+ problems.push(`${file}: name it changes/<branch>.md in lower case, "/" as "-"`);
27
+ const entries = new Map();
28
+ let heading;
29
+ text.split("\n").forEach((line, index) => {
30
+ const where = `${file}:${index + 1}`;
31
+ if (line.startsWith("### ")) {
32
+ heading = line.slice(4).trim();
33
+ if (!headings.includes(heading))
34
+ problems.push(`${where}: "${heading}" is not one of: ${headings.join(", ")}`);
35
+ if (entries.has(heading))
36
+ problems.push(`${where}: "${heading}" twice`);
37
+ entries.set(heading, 0);
38
+ return;
39
+ }
40
+ if (line.startsWith("#"))
41
+ problems.push(`${where}: only "### <heading>" headings; the release adds the version`);
42
+ if (!line.trim())
43
+ return;
44
+ if (heading === undefined)
45
+ problems.push(`${where}: text before the first ### heading`);
46
+ else
47
+ entries.set(heading, (entries.get(heading) ?? 0) + 1);
48
+ for (const found of line.match(id) ?? [])
49
+ problems.push(`${where}: internal id ${found} — say what changed instead`);
50
+ });
51
+ if (entries.size === 0)
52
+ problems.push(`${file}: no "### <heading>" with an entry under it`);
53
+ for (const [found, count] of entries)
54
+ if (count === 0)
55
+ problems.push(`${file}: "${found}" has no entry`);
56
+ return problems;
57
+ };
58
+ const trimBlank = (lines) => {
59
+ let start = 0;
60
+ let end = lines.length;
61
+ while (start < end && !lines[start]?.trim())
62
+ start++;
63
+ while (end > start && !lines[end - 1]?.trim())
64
+ end--;
65
+ return lines.slice(start, end);
66
+ };
67
+ const byHeading = (lines, where) => {
68
+ const found = new Map();
69
+ let current;
70
+ for (const line of lines) {
71
+ if (line.startsWith("### ")) {
72
+ const heading = line.slice(4).trim();
73
+ current = found.get(heading) ?? [];
74
+ found.set(heading, current);
75
+ }
76
+ else if (current)
77
+ current.push(line);
78
+ else if (line.trim())
79
+ throw new Error(`${where} has text before its first ### heading: "${line}"`);
80
+ }
81
+ return new Map([...found].map(([heading, body]) => [heading, trimBlank(body)]));
82
+ };
83
+ /**
84
+ * Adds every fragment's entries under the same-named heading of `## <version> — `, after the entries already there,
85
+ * fragments in name order. A fragment links from `changes/`, so `../` is dropped for CHANGELOG.md at the root.
86
+ */
87
+ export const collectFragments = (changelog, version, fragments, { headings }) => {
88
+ const parts = changelog.split(/\n(?=## )/);
89
+ const index = parts.findIndex((part) => part.startsWith(`## ${version} — `));
90
+ const section = parts[index];
91
+ if (section === undefined)
92
+ throw new Error(`CHANGELOG.md has no "## ${version} — " section to collect changes/ into`);
93
+ const [title = "", ...lines] = section.split("\n");
94
+ const merged = byHeading(lines, title);
95
+ for (const fragment of fragments) {
96
+ const text = fragment.text.replace(/\]\(\.\.\//g, "](");
97
+ for (const [heading, body] of byHeading(text.split("\n"), `changes/${fragment.name}`))
98
+ merged.set(heading, [...(merged.get(heading) ?? []), ...body]);
99
+ }
100
+ const rank = (heading) => (headings.includes(heading) ? headings.indexOf(heading) : headings.length);
101
+ const body = [...merged]
102
+ .filter(([, entries]) => entries.length > 0)
103
+ .sort(([a], [b]) => rank(a) - rank(b))
104
+ .map(([heading, entries]) => `### ${heading}\n\n${entries.join("\n")}\n`)
105
+ .join("\n");
106
+ parts[index] = `${title}\n\n${body}`;
107
+ return parts.join("\n");
108
+ };
@@ -1,4 +1,6 @@
1
1
  export { foldUnreleased, mergeRepeatedHeadings, restoreReleased } from "./fold.js";
2
+ export { CHANGELOG_HEADINGS, collectFragments, type Fragment, type FragmentRules, fragmentProblems, readFragments, } from "./fragments.js";
3
+ export { levelledVersion, versionLevelProblem } from "./level.js";
2
4
  export { type ChangelogRules, changelogProblems, type DocsRules, docsProblems, idPattern, JOURNAL_IDS, markdownFiles, slug, } from "./markdown.js";
3
5
  export { REQUIRED_PAGES, type StructureRules, structureProblems } from "./structure.js";
4
6
  export type Check = {
@@ -7,6 +7,8 @@ import { spawnSync } from "node:child_process";
7
7
  import { readFileSync, writeFileSync } from "node:fs";
8
8
  import { join } from "node:path";
9
9
  export { foldUnreleased, mergeRepeatedHeadings, restoreReleased } from "./fold.js";
10
+ export { CHANGELOG_HEADINGS, collectFragments, fragmentProblems, readFragments, } from "./fragments.js";
11
+ export { levelledVersion, versionLevelProblem } from "./level.js";
10
12
  export { changelogProblems, docsProblems, idPattern, JOURNAL_IDS, markdownFiles, slug, } from "./markdown.js";
11
13
  export { REQUIRED_PAGES, structureProblems } from "./structure.js";
12
14
  /**
@@ -0,0 +1,2 @@
1
+ export declare const levelledVersion: (changelog: string, next: string) => string;
2
+ export declare const versionLevelProblem: (changelog: string) => string | undefined;