@antelopejs/tooling-configs 0.7.1 → 0.7.3

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.
@@ -1,10 +1,11 @@
1
1
  import { t as CEILINGS_FILE } from "./ceilings-B7KayYIG.mjs";
2
2
  import { l as serializeManifest, o as packageManager, s as parseManifest } from "./package-DDG3YH7W.mjs";
3
- import { f as parseJson } from "./json-CG2L7YFl.mjs";
3
+ import { a as isString, f as parseJson, i as isObject, u as optStr } from "./json-CG2L7YFl.mjs";
4
4
  import { a as gitFiles, u as trackedManifests } from "./files-C-JJhExM.mjs";
5
- import { n as workspaceDirectories } from "./docs-compat-CSljVi3O.mjs";
5
+ import { i as DMS_PACKAGES, n as workspaceDirectories } from "./docs-compat-BAZiPLZt.mjs";
6
6
  import { n as shimInvocation, t as runCommand } from "./run-command-BlFRPORx.mjs";
7
7
  import { n as tagVersion } from "./npm-CIIqL5SG.mjs";
8
+ import { n as packTarball } from "./pack-tarball-Cn4zGKn7.mjs";
8
9
  import { t as accepting } from "./ports-DAeEJsYh.mjs";
9
10
  import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, statSync, writeFileSync } from "node:fs";
10
11
  import { basename, dirname, join, posix, relative, resolve, sep } from "node:path";
@@ -13,8 +14,8 @@ import { isMap, isScalar, isSeq, parseAllDocuments, parseDocument, stringify } f
13
14
  import ts from "@typescript/typescript6";
14
15
  import { createHash } from "node:crypto";
15
16
  import { tmpdir } from "node:os";
17
+ import { Range, gtr, minVersion, prerelease, satisfies, valid, validRange } from "semver";
16
18
  import { gunzipSync } from "node:zlib";
17
- import { validRange } from "semver";
18
19
  import { minimatch } from "minimatch";
19
20
  //#region src/guardrails/run-pnpm.ts
20
21
  /** Runs pnpm, the only manager the pack's CI installs with, with `args` quietly; returns its output only when it failed. */
@@ -43,6 +44,7 @@ function runPnpm(root, args) {
43
44
  * next patch release.
44
45
  */
45
46
  const ANTELOPEJS_SCOPE$1 = "@antelopejs/";
47
+ const INTERFACE_PREFIX = `${ANTELOPEJS_SCOPE$1}interface-`;
46
48
  /** A linked folder is the copy the dependent builds against, not a release it resolves. */
47
49
  const LINK_SPEC_PREFIXES = ["file:", "link:"];
48
50
  /** pnpm replaces a `workspace:` spec with a range on the sibling's version when it publishes the package. */
@@ -224,11 +226,95 @@ function checkDependencyRanges(manifest, localVersions = /* @__PURE__ */ new Map
224
226
  }
225
227
  return violations;
226
228
  }
229
+ /**
230
+ * The `@antelopejs/interface-*` ranges of `manifest` that resolve from the registry: neither a linked folder nor a
231
+ * `workspace:` sibling.
232
+ */
233
+ function interfaceRanges(manifest) {
234
+ return CHECKED_FIELDS.flatMap((field) => Object.entries(manifest[field] ?? {}).filter(([name, spec]) => name.startsWith(INTERFACE_PREFIX) && !isLinkSpec(spec) && !spec.startsWith(WORKSPACE_PREFIX)).map(([name, spec]) => ({
235
+ field,
236
+ name,
237
+ spec
238
+ })));
239
+ }
227
240
  function describeViolation(violation) {
228
241
  const { field, name, spec, local, expected } = violation;
229
242
  return `${field}["${name}"] is "${spec}": AntelopeJS packages ship breaking changes in minor releases, so it must stop below the next minor${local === void 0 ? "" : ` and admit ${local}, the version in this repository`}; ${expected ? `use "${expected}"` : "declare it as >=<floor> <next minor> on 0.x or ~<floor> from 1.0"}`;
230
243
  }
231
244
  //#endregion
245
+ //#region src/guardrails/registry.ts
246
+ const DEFAULT_REGISTRY = "https://registry.npmjs.org/";
247
+ /** How long one registry read may take before it counts as failed. */
248
+ const REGISTRY_TIMEOUT_MS = 3e3;
249
+ /** How many times a read that failed or timed out is made before the document counts as unreadable. */
250
+ const REGISTRY_ATTEMPTS = 2;
251
+ /** The dependency fields a release resolves an interface it implements from. */
252
+ const RELEASE_FIELDS = [
253
+ "dependencies",
254
+ "peerDependencies",
255
+ "optionalDependencies"
256
+ ];
257
+ /** The registry npm is configured with, ending in `/`. */
258
+ function registry() {
259
+ const configured = process.env.npm_config_registry || process.env.NPM_CONFIG_REGISTRY;
260
+ if (!configured) return DEFAULT_REGISTRY;
261
+ return configured.endsWith("/") ? configured : `${configured}/`;
262
+ }
263
+ /** What {@link readRegistry} returns when the registry answers that nothing is published at a path. */
264
+ const UNPUBLISHED = "unpublished";
265
+ /** The document at `path` under the {@link registry}, {@link UNPUBLISHED} when the registry answers 404, or `undefined` when it cannot be read within {@link REGISTRY_ATTEMPTS} reads of {@link REGISTRY_TIMEOUT_MS} each. */
266
+ async function readRegistry(path, accept) {
267
+ for (let attempt = 0; attempt < REGISTRY_ATTEMPTS; attempt++) try {
268
+ const response = await fetch(new URL(path, registry()), {
269
+ headers: { accept },
270
+ signal: AbortSignal.timeout(REGISTRY_TIMEOUT_MS)
271
+ });
272
+ if (response.status === 404) return UNPUBLISHED;
273
+ if (!response.ok) return void 0;
274
+ return { document: parseJson(await response.text()) };
275
+ } catch {
276
+ continue;
277
+ }
278
+ }
279
+ const encodedName = (name) => name.replace("/", "%2f");
280
+ /** The `latest` dist-tag of `name` on the {@link registry}, or `undefined` when it cannot be read. */
281
+ async function publishedVersion(name) {
282
+ const packument = await readRegistry(encodedName(name), "application/vnd.npm.install-v1+json");
283
+ return packument === void 0 || packument === UNPUBLISHED ? void 0 : tagVersion(packument.document, "latest");
284
+ }
285
+ function declaredRange(release, name) {
286
+ for (const field of RELEASE_FIELDS) {
287
+ const dependencies = Object.hasOwn(release, field) ? release[field] : void 0;
288
+ const range = dependencies !== void 0 && isObject(dependencies) ? optStr(dependencies, name) : void 0;
289
+ if (range !== void 0) return range;
290
+ }
291
+ }
292
+ function implementedNames(release) {
293
+ const config = Object.hasOwn(release, "antelopeJs") ? release.antelopeJs : void 0;
294
+ if (config === void 0 || !isObject(config)) return [];
295
+ const names = Object.hasOwn(config, "implements") ? config.implements : void 0;
296
+ return Array.isArray(names) ? names.filter(isString) : [];
297
+ }
298
+ /** The release the `latest` dist-tag of `name` points at, `"unpublished"` when the registry has none, or `undefined` when it cannot be read. */
299
+ async function implementingRelease(name) {
300
+ const read = await readRegistry(`${encodedName(name)}/latest`, "application/json");
301
+ if (read === UNPUBLISHED) return UNPUBLISHED;
302
+ const release = read?.document;
303
+ if (release === void 0 || !isObject(release)) return void 0;
304
+ const version = optStr(release, "version");
305
+ if (version === void 0) return void 0;
306
+ const implemented = /* @__PURE__ */ new Map();
307
+ for (const interfaceName of implementedNames(release)) {
308
+ const range = declaredRange(release, interfaceName);
309
+ if (range !== void 0) implemented.set(interfaceName, range);
310
+ }
311
+ return {
312
+ name,
313
+ version,
314
+ implements: implemented
315
+ };
316
+ }
317
+ //#endregion
232
318
  //#region src/guardrails/dependency-ranges-sync.ts
233
319
  /** Each tracked manifest that parses; a fixture that is not JSON is not a package this repository releases. */
234
320
  function tracked(root) {
@@ -300,11 +386,93 @@ function moveDependencyRanges(root, check) {
300
386
  function hasDependencyRanges(root) {
301
387
  return tracked(root).some(({ manifest }) => declaresAntelopePackage(manifest));
302
388
  }
303
- /** Each `@antelopejs/*` range in a tracked manifest that does not stop below the next minor, one line each; empty when every range does. */
304
- function checkRepositoryRanges(root) {
389
+ function belowNewest(spec, version) {
390
+ if (version === void 0 || valid(version) === null || prerelease(version) !== null || !gtr(version, spec)) return void 0;
391
+ const expected = cappedReplacement(spec, version);
392
+ return expected === void 0 ? void 0 : {
393
+ reason: `which stops below ${version}, its newest published version`,
394
+ expected
395
+ };
396
+ }
397
+ /** The lowest release `range` admits, without the prerelease suffix a floor such as `^0.10.0-rc.1` carries. */
398
+ function stableFloor(range) {
399
+ const floor = minVersion(range);
400
+ return floor === null ? void 0 : `${floor.major}.${floor.minor}.${floor.patch}`;
401
+ }
402
+ /** Whether one release admitted by `a` is also admitted by `b`, counting releases only, as an install resolves them. */
403
+ function sharesRelease(a, b) {
404
+ return new Range(a).set.some((left) => new Range(b).set.some((right) => {
405
+ const both = [...left, ...right].join(" ");
406
+ const floor = stableFloor(both);
407
+ return floor !== void 0 && satisfies(floor, both);
408
+ }));
409
+ }
410
+ /** The implementation of `name` in each of `releases` that is not a prerelease and declares a range semver reads. */
411
+ function implementations(name, releases) {
412
+ return releases.flatMap((release) => {
413
+ const range = release.implements.get(name);
414
+ return range === void 0 || prerelease(release.version) !== null || validRange(range) === null ? [] : [{
415
+ release,
416
+ range
417
+ }];
418
+ });
419
+ }
420
+ function outsideImplemented(spec, { release, range }) {
421
+ if (sharesRelease(spec, range)) return void 0;
422
+ const floor = stableFloor(range);
423
+ const expected = floor === void 0 ? void 0 : cappedReplacement(spec, floor);
424
+ return expected === void 0 ? void 0 : {
425
+ reason: `which excludes "${range}", the range ${release.name} ${release.version}, its newest release, implements it on`,
426
+ expected
427
+ };
428
+ }
429
+ /** The newest release of each DMS package outside this repository that could be read, and whether every published one could. */
430
+ async function dmsReleases(local) {
431
+ const reads = await Promise.all(DMS_PACKAGES.filter((name) => !local.has(name)).map(implementingRelease));
432
+ return {
433
+ releases: reads.filter((read) => read !== void 0 && read !== "unpublished"),
434
+ complete: !reads.includes(void 0)
435
+ };
436
+ }
437
+ /**
438
+ * One line per range among `ranges` that shares no release with the range the newest release of a DMS package outside
439
+ * `local` implements its interface on, since a project loads the interface version that release is built against. An
440
+ * interface no such release implements is held instead to the `latest` dist-tag of its package: one line when every
441
+ * release the range admits sits below it, and only when every published DMS release could be read, since an unread one
442
+ * may implement it. A line that gives the fix an earlier one gave is skipped. A package whose release cannot be read,
443
+ * or whose `latest` is a prerelease, is skipped, so a registry outage leaves only the cap rule deciding the step.
444
+ */
445
+ async function staleRanges(ranges, local) {
446
+ if (!ranges.length) return [];
447
+ const names = [...new Set(ranges.map(({ name }) => name))];
448
+ const [newest, { releases, complete }] = await Promise.all([Promise.all(names.map(async (name) => [name, await publishedVersion(name)])).then((entries) => new Map(entries)), dmsReleases(local)]);
449
+ return ranges.flatMap(({ path, field, name, spec }) => {
450
+ if (validRange(spec) === null) return [];
451
+ const implemented = implementations(name, releases);
452
+ const findings = (implemented.length ? implemented.map((implementation) => outsideImplemented(spec, implementation)) : complete ? [belowNewest(spec, newest.get(name))] : []).filter((finding) => finding !== void 0);
453
+ return findings.filter(({ expected }, index) => findings.findIndex((finding) => finding.expected === expected) === index).map(({ reason, expected }) => `${path}: ${field}["${name}"] is "${spec}", ${reason}, and @antelopejs/core loads one copy of each interface; use "${expected}"\n`);
454
+ });
455
+ }
456
+ /**
457
+ * Each `@antelopejs/*` range in a tracked manifest that does not stop below the next minor, and each capped
458
+ * `@antelopejs/interface-*` range on a package outside this repository that the newest DMS release implementing it, or
459
+ * else its newest published release, does not admit, one line each; empty when every range passes.
460
+ */
461
+ async function checkRepositoryRanges(root) {
305
462
  const manifests = tracked(root);
306
463
  const versions = localVersions(manifests.map(({ manifest }) => manifest));
307
- return manifests.flatMap(({ path, manifest }) => checkDependencyRanges(manifest, versions).map((violation) => `${path}: ${describeViolation(violation)}\n`)).join("");
464
+ const capped = [];
465
+ const published = [];
466
+ for (const { path, manifest } of manifests) {
467
+ const violations = checkDependencyRanges(manifest, versions);
468
+ capped.push(...violations.map((violation) => `${path}: ${describeViolation(violation)}\n`));
469
+ published.push(...interfaceRanges(manifest).filter(({ field, name }) => !versions.has(name) && !violations.some((violation) => violation.field === field && violation.name === name)).map((range) => ({
470
+ path,
471
+ ...range
472
+ })));
473
+ }
474
+ const local = new Set(manifests.flatMap(({ manifest: { name } }) => name ? [name] : []));
475
+ return [...capped, ...await staleRanges(published, local)].join("");
308
476
  }
309
477
  //#endregion
310
478
  //#region src/guardrails/git-identity.ts
@@ -430,39 +598,130 @@ function entrySpecifiers(name, exports, files, consumer) {
430
598
  };
431
599
  }
432
600
  //#endregion
433
- //#region src/guardrails/pack-tarball.ts
434
- /** The flag that stops `pack` from running lifecycle scripts, by package manager. */
435
- const IGNORE_SCRIPTS = {
436
- pnpm: "--config.ignore-scripts=true",
437
- npm: "--ignore-scripts"
438
- };
601
+ //#region src/guardrails/known-failures.ts
602
+ /** The file at the repository root that declares the errors `published:types` reports in a dependency's own declarations. */
603
+ const KNOWN_FAILURES_FILE = "guardrails.published-types.json";
604
+ const ENTRY_KEYS = /* @__PURE__ */ new Set([
605
+ "dependency",
606
+ "file",
607
+ "code"
608
+ ]);
609
+ const CODE = /^TS\d+$/;
610
+ const INSIDE_PACKAGE = /^(?!\.\/|\/)[^\\]+$/;
611
+ const PACKAGE_NAME = /^(?:@[^/\s]+\/)?[^/@\s][^/\s]*$/;
612
+ /** What is wrong with `entry`, or the {@link KnownFailure} it declares. */
613
+ function parseEntry(entry) {
614
+ if (!isObject(entry)) return { problem: "is not an object" };
615
+ const extra = Object.keys(entry).filter((key) => !ENTRY_KEYS.has(key));
616
+ if (extra.length) return { problem: `has unknown key ${extra.join(", ")}` };
617
+ const dependency = optStr(entry, "dependency") ?? "";
618
+ const file = optStr(entry, "file") ?? "";
619
+ const code = optStr(entry, "code") ?? "";
620
+ if (!PACKAGE_NAME.test(dependency)) return { problem: "needs dependency as a package name" };
621
+ if (!INSIDE_PACKAGE.test(file) || file.split("/").includes("..")) return { problem: "needs file as a path inside the package" };
622
+ if (!CODE.test(code)) return { problem: "needs code such as TS2416" };
623
+ return {
624
+ problem: "",
625
+ failure: {
626
+ dependency,
627
+ file,
628
+ code
629
+ }
630
+ };
631
+ }
632
+ const EXPECTED = `expected { "knownFailures": [{ "dependency", "file", "code" }] }`;
633
+ /** The entries `KNOWN_FAILURES_FILE` declares at `root`, none when the file is missing, or what is wrong with it. An entry may not name a package of `ownPackages`, the repository's own, whose declarations the repository fixes instead. */
634
+ function readKnownFailures(root, ownPackages) {
635
+ const path = join(root, KNOWN_FAILURES_FILE);
636
+ if (!existsSync(path)) return {
637
+ failure: "",
638
+ entries: []
639
+ };
640
+ let parsed;
641
+ try {
642
+ parsed = parseJson(readFileSync(path, "utf8"));
643
+ } catch (error) {
644
+ return { failure: `${KNOWN_FAILURES_FILE}: ${String(error)}\n` };
645
+ }
646
+ const list = isObject(parsed) && Object.keys(parsed).length === 1 && Object.hasOwn(parsed, "knownFailures") ? parsed.knownFailures : void 0;
647
+ if (!Array.isArray(list)) return { failure: `${KNOWN_FAILURES_FILE}: ${EXPECTED}.\n` };
648
+ const entries = [];
649
+ let problems = "";
650
+ for (const [index, value] of list.entries()) {
651
+ const parsedEntry = parseEntry(value);
652
+ if ("failure" in parsedEntry && entries.some((entry) => describeEntry(entry) === describeEntry(parsedEntry.failure))) problems += `${KNOWN_FAILURES_FILE}: knownFailures[${index}] repeats an earlier entry.\n`;
653
+ else if ("failure" in parsedEntry && ownPackages.has(parsedEntry.failure.dependency)) problems += `${KNOWN_FAILURES_FILE}: knownFailures[${index}] names ${parsedEntry.failure.dependency}, a package of this repository. Fix its declarations instead.\n`;
654
+ else if ("failure" in parsedEntry) entries.push(parsedEntry.failure);
655
+ else problems += `${KNOWN_FAILURES_FILE}: knownFailures[${index}] ${parsedEntry.problem}.\n`;
656
+ }
657
+ return problems ? { failure: problems } : {
658
+ failure: "",
659
+ entries
660
+ };
661
+ }
662
+ /** The diagnostics of tsc's `--pretty false` output, each its first line and the indented lines that continue it. */
663
+ function diagnosticBlocks(output) {
664
+ const blocks = [];
665
+ for (const line of output.split(/\r?\n/)) {
666
+ if (!line) continue;
667
+ if (/^\s/.test(line) && blocks.length) blocks[blocks.length - 1] += `\n${line}`;
668
+ else blocks.push(line);
669
+ }
670
+ return blocks;
671
+ }
672
+ const LOCATED = /^(.*?)\(\d+,\d+\): error (TS\d+): /;
673
+ const INSTALLED = /^((?:@[^/]+\/)?[^/]+)\/(.+)$/;
674
+ const NODE_MODULES = "node_modules/";
675
+ /** Where `block` is reported, undefined when it names no file under `node_modules`. */
676
+ function installedDiagnostic(block) {
677
+ const [, path = "", code = ""] = LOCATED.exec(block) ?? [];
678
+ const marker = path.lastIndexOf(NODE_MODULES);
679
+ if (marker < 0) return void 0;
680
+ const installed = path.slice(marker + 13);
681
+ const [, dependency = "", file = ""] = INSTALLED.exec(installed) ?? [];
682
+ if (!dependency) return void 0;
683
+ return {
684
+ dependency,
685
+ file,
686
+ code,
687
+ text: `${installed}${block.slice(path.length)}`
688
+ };
689
+ }
690
+ /** `entry` written as tsc names its file, `<dependency>/<file> <code>`. */
691
+ function describeEntry(entry) {
692
+ return `${entry.dependency}/${entry.file} ${entry.code}`;
693
+ }
439
694
  /**
440
- * Packs the package in `cwd` into `destination`: runs its `prepack` through `<manager> run`, which uses the configured
441
- * script shell, then `<manager> pack` with lifecycle scripts off, since `pnpm pack` runs them through cmd.exe on Windows
442
- * whatever the script shell, so a POSIX `prepare` fails there. Returns the first failed command, else the pack.
695
+ * Splits tsc's `--pretty false` `output` into the diagnostics an entry of `entries` declares and the rest. A diagnostic
696
+ * is declared when it lies in a package's installed declarations and an entry names that package, the file inside it
697
+ * and the code. Each entry that declares one is added to `matched`. A diagnostic in a
698
+ * file under `node_modules` names it as `<package>/<file>`.
443
699
  */
444
- async function packTarball(manager, cwd, destination, signal) {
445
- const prepack = await runCommand(manager, [
446
- "run",
447
- "--if-present",
448
- "prepack"
449
- ], {
450
- cwd,
451
- signal
452
- });
453
- if (prepack.status !== 0) return prepack;
454
- return runCommand(manager, [
455
- "pack",
456
- IGNORE_SCRIPTS[manager],
457
- "--pack-destination",
458
- destination
459
- ], {
460
- cwd,
461
- signal
462
- });
700
+ function splitDiagnostics(output, entries, matched) {
701
+ const known = [];
702
+ const unknown = [];
703
+ for (const block of diagnosticBlocks(output)) {
704
+ const diagnostic = installedDiagnostic(block);
705
+ const entry = diagnostic ? entries.find(({ dependency, file, code }) => dependency === diagnostic.dependency && file === diagnostic.file && code === diagnostic.code) : void 0;
706
+ if (entry && diagnostic) {
707
+ matched.add(entry);
708
+ known.push(diagnostic.text);
709
+ } else unknown.push(diagnostic?.text ?? block);
710
+ }
711
+ return {
712
+ known,
713
+ unknown
714
+ };
463
715
  }
464
716
  //#endregion
465
717
  //#region src/guardrails/published-types.ts
718
+ function unchecked(failure) {
719
+ return {
720
+ failure,
721
+ known: [],
722
+ compiled: false
723
+ };
724
+ }
466
725
  const DECLARATION_FILE = /\.d\.[cm]?ts$/;
467
726
  /** An `exports` map that names declarations: a `types` condition or a `.d.ts`, `.d.mts` or `.d.cts` target. */
468
727
  const TYPED_EXPORTS = /"types"\s*:|\.d\.[cm]?ts"/;
@@ -631,13 +890,23 @@ async function typecheck(run, consumer, typed, manifest) {
631
890
  signal: run.signal,
632
891
  shell: false
633
892
  });
634
- return tsc.status === 0 ? "" : readable(tsc.output, consumer, typed.name);
893
+ if (tsc.status === 0) return {
894
+ failure: "",
895
+ known: [],
896
+ compiled: true
897
+ };
898
+ const { known, unknown } = splitDiagnostics(tsc.output, run.declared, run.matched);
899
+ return {
900
+ failure: unknown.length || !known.length ? readable(unknown.length ? `${unknown.join("\n")}\n` : `tsc exited with status ${String(tsc.status)}.\n`, consumer, typed.name) : "",
901
+ known,
902
+ compiled: true
903
+ };
635
904
  }
636
905
  async function consumerErrors(run, typed, slot) {
637
906
  const packed = await pack(run, typed.name);
638
- if (!("tarball" in packed)) return packed.failure;
907
+ if (!("tarball" in packed)) return unchecked(packed.failure);
639
908
  const siblings = await siblingTarballs(run, typed.name, packed.manifest);
640
- if (siblings.failure) return siblings.failure;
909
+ if (siblings.failure) return unchecked(siblings.failure);
641
910
  const consumer = join(run.scratch, `consumer-${slot}`);
642
911
  mkdirSync(consumer);
643
912
  const overrides = {
@@ -654,38 +923,59 @@ async function consumerErrors(run, typed, slot) {
654
923
  cwd: consumer,
655
924
  signal: run.signal
656
925
  });
657
- if (install.status !== 0) return `Installing the tarball failed:\n${install.output}`;
926
+ if (install.status !== 0) return unchecked(`Installing the tarball failed:\n${install.output}`);
658
927
  return typecheck(run, consumer, typed, packed.manifest);
659
928
  }
660
929
  function packsWithPnpmOrNpm(manager) {
661
930
  return manager === "pnpm" || manager === "npm";
662
931
  }
932
+ /** The line that fails each entry of `run` no error matched, once tsc ran over every package. */
933
+ function staleEntries(run) {
934
+ return run.declared.filter((entry) => !run.matched.has(entry)).map((entry) => `${KNOWN_FAILURES_FILE}: ${describeEntry(entry)} no longer occurs. Remove the entry.\n`).join("");
935
+ }
663
936
  /**
664
937
  * Packs each package `typedPackages` finds, running its `prepack`, and installs the tarball alone in a scratch
665
938
  * directory with its peers, optional ones included, `typescript` and `@types/node` at the latest version unless it
666
939
  * names them as peers, and the tarball of each package of the repository it depends on in place of the registry's.
667
940
  * Then runs `tsc` with `skipLibCheck` off over a consumer file importing each entry its `exports` names, or, without
668
- * `exports`, the package itself and every declaration file it ships. Returns what failed, each package's errors under
669
- * its `package.json`, empty when every package passed.
941
+ * `exports`, the package itself and every declaration file it ships. An error in a dependency's declarations that
942
+ * `guardrails.published-types.json` declares is reported under `notes` instead of failing; an entry no error matched
943
+ * fails once tsc ran over every package. Each package's errors are listed under its `package.json`.
670
944
  */
671
945
  async function checkPublishedTypes(root, signal) {
672
946
  const manager = packageManager(parseManifest(readFileSync(join(root, "package.json"), "utf8")));
673
- if (!packsWithPnpmOrNpm(manager)) return `This check packs with pnpm or npm, not ${manager}.\n`;
947
+ if (!packsWithPnpmOrNpm(manager)) return {
948
+ failure: `This check packs with pnpm or npm, not ${manager}.\n`,
949
+ notes: ""
950
+ };
951
+ const members = new Map(publicPackages(root).map(({ name, directory }) => [name, directory]));
952
+ const declared = readKnownFailures(root, new Set(members.keys()));
953
+ if (!("entries" in declared)) return {
954
+ failure: declared.failure,
955
+ notes: ""
956
+ };
674
957
  const scratch = realpathSync.native(mkdtempSync(join(tmpdir(), "published-types-")));
675
958
  const run = {
676
959
  root,
677
960
  manager,
678
961
  scratch,
679
962
  signal,
680
- members: new Map(publicPackages(root).map(({ name, directory }) => [name, directory])),
681
- packs: /* @__PURE__ */ new Map()
963
+ members,
964
+ packs: /* @__PURE__ */ new Map(),
965
+ declared: declared.entries,
966
+ matched: /* @__PURE__ */ new Set()
682
967
  };
683
- let failures = "";
968
+ let failure = "";
969
+ let notes = "";
970
+ let complete = true;
684
971
  try {
685
972
  for (const [slot, typed] of typedPackages(root).entries()) {
686
973
  if (signal?.aborted) break;
687
- const failure = await consumerErrors(run, typed, slot);
688
- if (failure) failures += `${join(typed.directory, "package.json")}: ${typed.name} as a consumer installs it, checked by tsc with skipLibCheck off:\n${failure}`;
974
+ const checked = await consumerErrors(run, typed, slot);
975
+ complete &&= checked.compiled;
976
+ const header = `${join(typed.directory, "package.json")}: ${typed.name} as a consumer installs it, checked by tsc with skipLibCheck off`;
977
+ if (checked.failure) failure += `${header}:\n${checked.failure}`;
978
+ if (checked.known.length) notes += `${header}, errors ${KNOWN_FAILURES_FILE} declares as known:\n${checked.known.join("\n")}\n`;
689
979
  }
690
980
  } finally {
691
981
  rmSync(scratch, {
@@ -693,18 +983,17 @@ async function checkPublishedTypes(root, signal) {
693
983
  force: true
694
984
  });
695
985
  }
696
- return failures;
986
+ if (complete && !signal?.aborted) failure += staleEntries(run);
987
+ return {
988
+ failure,
989
+ notes
990
+ };
697
991
  }
698
992
  //#endregion
699
993
  //#region src/guardrails/readme-version.ts
700
994
  /** An object literal holding no other, such as a config example's `source: { package, version }`. */
701
995
  const FLAT_OBJECT = /\{[^{}]*\}/g;
702
996
  const ANTELOPEJS_SCOPE = "@antelopejs/";
703
- const DEFAULT_REGISTRY = "https://registry.npmjs.org/";
704
- /** How long one read of a package's dist-tags may take before it counts as failed. */
705
- const REGISTRY_TIMEOUT_MS = 3e3;
706
- /** How many times a read that failed or timed out is made before the version counts as unreadable. */
707
- const REGISTRY_ATTEMPTS = 2;
708
997
  function stringField(body, key) {
709
998
  return new RegExp(String.raw`(?<![\w$-])["']?${key}["']?\s*:\s*["']([^"'\n]+)["']`).exec(body);
710
999
  }
@@ -749,23 +1038,6 @@ function readmeExamples(root) {
749
1038
  const packages = ownPackages(root);
750
1039
  return readmes.flatMap((readme) => examplesIn(readme, readFileSync(join(root, readme), "utf8"), packages));
751
1040
  }
752
- function registry() {
753
- const configured = process.env.npm_config_registry || process.env.NPM_CONFIG_REGISTRY;
754
- if (!configured) return DEFAULT_REGISTRY;
755
- return configured.endsWith("/") ? configured : `${configured}/`;
756
- }
757
- /** The `latest` dist-tag of `name` on the registry npm is configured with, or `undefined` when it cannot be read within {@link REGISTRY_ATTEMPTS} reads of {@link REGISTRY_TIMEOUT_MS} each. */
758
- async function publishedVersion(name) {
759
- for (let attempt = 0; attempt < REGISTRY_ATTEMPTS; attempt++) try {
760
- const response = await fetch(new URL(name.replace("/", "%2f"), registry()), {
761
- headers: { accept: "application/vnd.npm.install-v1+json" },
762
- signal: AbortSignal.timeout(REGISTRY_TIMEOUT_MS)
763
- });
764
- return response.ok ? tagVersion(parseJson(await response.text()), "latest") : void 0;
765
- } catch {
766
- continue;
767
- }
768
- }
769
1041
  async function newestVersions(examples) {
770
1042
  const names = [...new Set(examples.map(({ name }) => name))];
771
1043
  const entries = await Promise.all(names.map(async (name) => {
@@ -1214,21 +1486,38 @@ function declaresWorkspaces(path) {
1214
1486
  throw error;
1215
1487
  }
1216
1488
  }
1489
+ /** Whether a `pnpm-workspace.yaml` lists `packages`, or cannot be read and so might; an empty one, or one without them, holds its own folder only. */
1490
+ function declaresPackages(path) {
1491
+ if (!existsSync(path)) return false;
1492
+ const document = parseDocument(readFileSync(path, "utf8"));
1493
+ if (document.errors.length > 0) return true;
1494
+ const { contents } = document;
1495
+ if (contents === null || isScalar(contents) && contents.value === null) return false;
1496
+ return !isMap(contents) || contents.has("packages");
1497
+ }
1217
1498
  /**
1218
- * Whether a folder above `folder` holds a workspace that may list it, a `pnpm-workspace.yaml` or a `package.json` with
1219
- * `workspaces`: its membership then follows patterns this check does not evaluate, and that workspace's lockfile may hold it.
1499
+ * Whether a folder above `folder` holds a workspace that may list it, a `pnpm-workspace.yaml` with `packages` or a
1500
+ * `package.json` with `workspaces`: its membership then follows patterns this check does not evaluate, and that workspace's
1501
+ * lockfile may hold it.
1220
1502
  */
1221
1503
  function inWorkspace(root, folder) {
1222
- return ancestors(folder).some((above) => existsSync(join(root, above, PNPM_WORKSPACE)) || declaresWorkspaces(join(root, above, MANIFEST)));
1504
+ return ancestors(folder).some((above) => declaresPackages(join(root, above, PNPM_WORKSPACE)) || declaresWorkspaces(join(root, above, MANIFEST)));
1223
1505
  }
1224
1506
  function fixCommand(root, folder, lockfile) {
1225
1507
  if (lockfile === NPM_LOCK) return `npm install --package-lock-only --prefix ${folder}`;
1226
1508
  return existsSync(join(root, folder, PNPM_WORKSPACE)) ? `pnpm install --dir ${folder} --lockfile-only` : `pnpm install --dir ${folder} --ignore-workspace --lockfile-only`;
1227
1509
  }
1510
+ /** The lockfile an install writes in a folder that holds none: `package-lock.json` when a folder above holds one, `pnpm-lock.yaml` otherwise. */
1511
+ function unlockedLockfile(root, folder) {
1512
+ return ancestors(folder).some((above) => existsSync(join(root, above, NPM_LOCK))) ? NPM_LOCK : PNPM_LOCK$1;
1513
+ }
1514
+ /** Whether pnpm installs `folder`: it holds a `pnpm-lock.yaml`, or no lockfile and no folder above it holds a `package-lock.json`. */
1515
+ function installsWithPnpm(root, folder) {
1516
+ return (lockfileIn(join(root, folder)) ?? unlockedLockfile(root, folder)) === PNPM_LOCK$1;
1517
+ }
1228
1518
  function unlocked(root, folder) {
1229
1519
  if (inWorkspace(root, folder)) return "";
1230
- const manager = ancestors(folder).some((above) => existsSync(join(root, above, NPM_LOCK))) ? NPM_LOCK : PNPM_LOCK$1;
1231
- return `${folder}/${MANIFEST} has dependencies and no lockfile: run \`${fixCommand(root, folder, manager)}\`.\n`;
1520
+ return `${folder}/${MANIFEST} has dependencies and no lockfile: run \`${fixCommand(root, folder, unlockedLockfile(root, folder))}\`.\n`;
1232
1521
  }
1233
1522
  function checkFolder(root, { folder, lockfile }) {
1234
1523
  if (lockfile === "other") return "";
@@ -1697,14 +1986,20 @@ const CHECK_STEPS = [
1697
1986
  "readme:version",
1698
1987
  "published:types"
1699
1988
  ];
1700
- /** Steps `antelopejs-checks` runs itself, no package.json script behind them: each returns what failed, empty when it passed. */
1989
+ function failureOnly(check) {
1990
+ return async (root, signal) => ({
1991
+ failure: await check(root, signal),
1992
+ notes: ""
1993
+ });
1994
+ }
1995
+ /** Steps `antelopejs-checks` runs itself, no package.json script behind them. */
1701
1996
  const OWN_STEPS = /* @__PURE__ */ new Map([
1702
- ["verify:types", typecheckLayers],
1703
- ["verify:lockfiles", (root) => Promise.resolve(checkLockfiles(root))],
1704
- ["lockfile:singletons", (root) => Promise.resolve(checkSingletonPackages(root))],
1705
- ["dependency:ranges", (root) => Promise.resolve(checkRepositoryRanges(root))],
1706
- ["git:identity", checkGitIdentity],
1707
- ["readme:version", checkReadmeVersion],
1997
+ ["verify:types", failureOnly(typecheckLayers)],
1998
+ ["verify:lockfiles", failureOnly((root) => Promise.resolve(checkLockfiles(root)))],
1999
+ ["lockfile:singletons", failureOnly((root) => Promise.resolve(checkSingletonPackages(root)))],
2000
+ ["dependency:ranges", failureOnly(checkRepositoryRanges)],
2001
+ ["git:identity", failureOnly(checkGitIdentity)],
2002
+ ["readme:version", failureOnly(checkReadmeVersion)],
1708
2003
  ["published:types", checkPublishedTypes]
1709
2004
  ]);
1710
2005
  function hasWork(root, step) {
@@ -1770,13 +2065,22 @@ function skippedNames(setting) {
1770
2065
  async function runSteps(root, manifest, steps, signal) {
1771
2066
  const manager = packageManager(manifest);
1772
2067
  const runStep = async (step) => {
1773
- if (signal?.aborted) return [];
2068
+ if (signal?.aborted) return {
2069
+ failure: "",
2070
+ notes: ""
2071
+ };
1774
2072
  const own = OWN_STEPS.get(step);
1775
2073
  if (own) {
1776
- const failure = await own(root, signal);
1777
- return failure ? [`[${step}]\n${failure}`] : [];
2074
+ const { failure, notes } = await own(root, signal);
2075
+ return {
2076
+ failure: failure && `[${step}]\n${failure}`,
2077
+ notes: notes && `[${step}]\n${notes}`
2078
+ };
1778
2079
  }
1779
- if (!manifest.scripts?.[step]) return [`[${step}] Missing package.json script "${step}". Run antelopejs-sync.\n`];
2080
+ if (!manifest.scripts?.[step]) return {
2081
+ failure: `[${step}] Missing package.json script "${step}". Run antelopejs-sync.\n`,
2082
+ notes: ""
2083
+ };
1780
2084
  const result = await runCommand(manager, ["run", step], {
1781
2085
  cwd: root,
1782
2086
  env: {
@@ -1785,11 +2089,18 @@ async function runSteps(root, manifest, steps, signal) {
1785
2089
  },
1786
2090
  signal
1787
2091
  });
1788
- return result.status === 0 ? [] : [`[${step}]\n${result.output}`];
2092
+ return {
2093
+ failure: result.status === 0 ? "" : `[${step}]\n${result.output}`,
2094
+ notes: ""
2095
+ };
2096
+ };
2097
+ const reports = /* @__PURE__ */ new Map();
2098
+ for (const phase of phases(root, steps)) await Promise.all(phase.map(async (step) => reports.set(step, await runStep(step))));
2099
+ const listed = (field) => steps.flatMap((step) => reports.get(step)?.[field] || []);
2100
+ return {
2101
+ failures: listed("failure"),
2102
+ notes: listed("notes")
1789
2103
  };
1790
- const failures = /* @__PURE__ */ new Map();
1791
- for (const phase of phases(root, steps)) await Promise.all(phase.map(async (step) => failures.set(step, await runStep(step))));
1792
- return steps.flatMap((step) => failures.get(step) ?? []);
1793
2104
  }
1794
2105
  /** The optional package script run once before the steps, to build what several steps read, such as a workspace package's `dist`. */
1795
2106
  const PREPARE = "checks:prepare";
@@ -1816,8 +2127,8 @@ async function prepare(root, manifest, signal) {
1816
2127
  output: `${failure}Checks: 0 passed, 1 failed.\n`
1817
2128
  };
1818
2129
  }
1819
- function summary(failures, passed, skipped) {
1820
- return `${failures.join("\n")}Checks: ${passed} passed, ${failures.length} failed${skipped ? `, ${skipped} skipped` : ""}.\n`;
2130
+ function summary(reported, failed, passed, skipped) {
2131
+ return `${reported}Checks: ${passed} passed, ${failed} failed${skipped ? `, ${skipped} skipped` : ""}.\n`;
1821
2132
  }
1822
2133
  /**
1823
2134
  * Runs the `checks:prepare` package script first when it exists and a step will run, and stops there if it fails.
@@ -1855,20 +2166,23 @@ async function runChecks(root, options = {}) {
1855
2166
  owned: false
1856
2167
  };
1857
2168
  let failures = [];
2169
+ let notes = [];
1858
2170
  let stopped = "";
1859
2171
  try {
1860
- failures = started.failure ? [`[services]\n${started.failure}`] : await runSteps(root, manifest, steps, signal);
2172
+ if (started.failure) failures = [`[services]\n${started.failure}`];
2173
+ else ({failures, notes} = await runSteps(root, manifest, steps, signal));
1861
2174
  } finally {
1862
2175
  if (started.owned) stopped = await stopServices(root);
1863
2176
  }
1864
2177
  const passed = started.failure ? 0 : steps.length - failures.length;
1865
2178
  if (stopped) failures.push(`[services]\n${stopped}`);
1866
2179
  const interrupted = signal?.aborted ?? false;
2180
+ const reported = [...notes, ...failures].join("\n");
1867
2181
  return {
1868
2182
  failed: failures.length,
1869
2183
  interrupted,
1870
- output: interrupted ? `${failures.join("\n")}Checks interrupted by ${String(signal?.reason)}.\n` : summary(failures, passed, skipped)
2184
+ output: interrupted ? `${reported}Checks interrupted by ${String(signal?.reason)}.\n` : summary(reported, failures.length, passed, skipped)
1871
2185
  };
1872
2186
  }
1873
2187
  //#endregion
1874
- export { stepsOf as a, matchingScripts as i, droppedChecksSteps as n, moveDependencyRanges as o, runChecks as r, runPnpm as s, CHECKS_SKIP_ENV as t };
2188
+ export { stepsOf as a, installsWithPnpm as c, runPnpm as d, matchingScripts as i, verifyLayers as l, droppedChecksSteps as n, pnpmLockfiles as o, runChecks as r, inWorkspace as s, CHECKS_SKIP_ENV as t, moveDependencyRanges as u };