gen-tsconfig-paths.mjs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import { readFileSync, writeFileSync } from "node:fs";
  2. import path from "node:path";
  3. import { fileURLToPath } from "node:url";
  4. import { readExtraction, extractionPath } from "./lib/release-metadata.mjs";
  5. import { packageExportEntries } from "./lib/package-exports.mjs";
  6. // The standalone type-check path map is derived from the package scope in
  7. // `release/extraction.json` plus each package's own `exports`, so adding a package
  8. // or an export subpath never requires hand-editing 100+ path entries. Run with
  9. // `--write` after changing package scope or exports; the default check mode fails
  10. // when the committed map has drifted.
  11. const root = fileURLToPath(new URL("../", import.meta.url));
  12. const configPath = "tsconfig.standalone.json";
  13. const { packageRoots } = readExtraction(root);
  14. const paths = {};
  15. for (const { specifier, file } of packageExportEntries(root, packageRoots)) {
  16. if (paths[specifier])
  17. throw new Error(
  18. `Duplicate export specifier ${specifier} in ${paths[specifier][0]} and ./${file}`,
  19. );
  20. paths[specifier] = [`./${file}`];
  21. }
  22. const expected = Object.fromEntries(
  23. Object.keys(paths)
  24. .sort()
  25. .map((specifier) => [specifier, paths[specifier]]),
  26. );
  27. const config = JSON.parse(readFileSync(path.join(root, configPath), "utf8"));
  28. const serialize = (value) => JSON.stringify(value, null, 2) + "\n";
  29. if (process.argv.includes("--write")) {
  30. config.compilerOptions.paths = expected;
  31. writeFileSync(path.join(root, configPath), serialize(config));
  32. console.log(
  33. `Recorded ${Object.keys(expected).length} package paths in ${configPath}.`,
  34. );
  35. } else {
  36. const actual = config.compilerOptions.paths ?? {};
  37. const drift = [
  38. ...Object.keys(expected)
  39. .filter((key) => serialize(actual[key]) !== serialize(expected[key]))
  40. .map((key) => `${key}: expected ${expected[key][0]}, found ${actual[key]?.[0] ?? "nothing"}`),
  41. ...Object.keys(actual)
  42. .filter((key) => !(key in expected))
  43. .map((key) => `${key}: not declared by any package in ${extractionPath}`),
  44. ];
  45. if (drift.length)
  46. throw new Error(
  47. `${configPath} paths are stale; run \`pnpm gen:tsconfig\`:\n${drift.join("\n")}`,
  48. );
  49. console.log(
  50. `${configPath} paths match ${Object.keys(expected).length} package exports.`,
  51. );
  52. }