licenses.mjs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import { readFile, readdir, writeFile } from "node:fs/promises";
  2. import { dirname, join, resolve } from "node:path";
  3. /**
  4. * Collect licences from the modules that actually end up in the bundles, including transitive
  5. * dependencies. A package without a licence file falls back to its declared SPDX licence and
  6. * repository so the notice still names it; packages without either fail the build.
  7. */
  8. export async function writeNotices(metafiles, destination) {
  9. const packages = new Map();
  10. for (const input of metafiles.flatMap((meta) => Object.keys(meta.inputs))) {
  11. if (!input.includes("node_modules/")) continue;
  12. let directory = dirname(resolve(input));
  13. while (directory.includes("node_modules")) {
  14. try {
  15. const pkg = JSON.parse(await readFile(join(directory, "package.json"), "utf8"));
  16. if (pkg.name) {
  17. packages.set(directory, pkg);
  18. break;
  19. }
  20. } catch (error) {
  21. if (error.code !== "ENOENT") throw error;
  22. }
  23. directory = dirname(directory);
  24. }
  25. }
  26. const notices = [];
  27. const seen = new Set();
  28. for (const [directory, pkg] of [...packages].sort((a, b) => a[1].name.localeCompare(b[1].name))) {
  29. const key = `${pkg.name}@${pkg.version}`;
  30. if (seen.has(key)) continue;
  31. seen.add(key);
  32. const files = (await readdir(directory)).filter((name) =>
  33. /^(license|licence|copying|notice)([.-]|$)/i.test(name),
  34. );
  35. const texts = await Promise.all(files.map((file) => readFile(join(directory, file), "utf8")));
  36. const license =
  37. typeof pkg.license === "string" ? pkg.license : JSON.stringify(pkg.license ?? null);
  38. if (!texts.length) {
  39. if (!pkg.license) throw new Error(`Missing license for bundled dependency ${key}`);
  40. const repository = typeof pkg.repository === "string" ? pkg.repository : pkg.repository?.url;
  41. texts.push(`Licensed under ${license}.${repository ? ` Source: ${repository}` : ""}`);
  42. }
  43. notices.push(`${key} — ${license}\n${texts.join("\n\n")}`);
  44. }
  45. await writeFile(destination, notices.join("\n\n----------------------------------------\n\n"));
  46. }