ShtukbaseStandard
файл пакета→ .shtukbase/packages/lenses/actions/packages.mjs

actions/packages.mjs

108 строк, 5.5 КБ.

Файл как есть в пакете: код и комментарии в нём не переводятся.

  1. // The data of the service lenses "Project packages" and "Project checks": what is installed in the project,
  2. // read from .shtukbase/packages.lock and the package.md of each installed package, plus the norm pages each
  3. // package laid. Written to lib/base/packages.data.js as `window.SHTUK_PACKAGES`; the output has no clock in it,
  4. // so the `check` action can compare it byte for byte.
  5. import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
  6. import { createRequire } from "node:module";
  7. import { basename, dirname, join } from "node:path";
  8. import { OWN_KIT } from "./kit.mjs";
  9. const yaml = createRequire(import.meta.url)(join(OWN_KIT, "vendor", "js-yaml.min.cjs"));
  10. export const DATA_FILE = join("lib", "base", "packages.data.js");
  11. const LOCK = join(".shtukbase", "packages.lock");
  12. /** Page types that are norms; a waiver is not a norm, it is a departure from one. */
  13. const NORM_TYPES = new Set(["Rule", "Principle", "Default", "Value", "Tenet"]);
  14. const load = (text) => { try { return yaml.load(text, { schema: yaml.CORE_SCHEMA }) ?? {}; } catch { return null; } };
  15. const list = (v) => (Array.isArray(v) ? v : v == null || v === "" ? [] : [v]);
  16. const str = (v) => (v == null ? "" : String(v));
  17. /** The front matter of a markdown text, or null. */
  18. function head(text) {
  19. const m = /^---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/.exec(text);
  20. return m ? load(m[1]) : null;
  21. }
  22. /** `{id: range}` from either a map or a list of `{package, version}`. */
  23. function ranges(v) {
  24. if (Array.isArray(v)) return Object.fromEntries(v.filter((x) => x && x.package).map((x) => [String(x.package), str(x.version)]));
  25. return v && typeof v === "object" ? Object.fromEntries(Object.entries(v).map(([k, r]) => [k, str(r)])) : {};
  26. }
  27. function norm(root, rel, state) {
  28. const file = join(root, rel);
  29. if (!existsSync(file)) return null;
  30. const fm = head(readFileSync(file, "utf8"));
  31. if (!fm || !NORM_TYPES.has(str(fm.type))) return null;
  32. return {
  33. path: "/" + rel, type: str(fm.type),
  34. id: str(fm.ruleId || fm.normId || fm.id || basename(rel, ".md")),
  35. title: str(fm.title || fm.requirement), level: str(fm.level), floor: fm.floor === true || fm.floor === "true",
  36. status: str(fm.status), mode: str(fm.mode),
  37. // the field is `enforcers`; `heldBy` is its old name, read while packages move over
  38. enforcers: list(fm.enforcers ?? fm.heldBy).map(str), state,
  39. };
  40. }
  41. /** Everything the lenses show, from the project in `root`; null when the project has no lock. */
  42. export function packagesData(root) {
  43. const lockFile = join(root, LOCK);
  44. if (!existsSync(lockFile)) return null;
  45. const lock = load(readFileSync(lockFile, "utf8")) || {};
  46. const packages = [];
  47. for (const [id, e] of Object.entries(lock.packages || {}).sort(([a], [b]) => (a < b ? -1 : 1))) {
  48. const mfFile = join(root, ".shtukbase", "packages", id, "package.md");
  49. const mf = existsSync(mfFile) ? head(readFileSync(mfFile, "utf8")) || {} : {};
  50. const pages = Object.entries(e.pages || {}).map(([rel, p]) => ({ path: "/" + rel, state: str(p && p.state) || "clean" }))
  51. .sort((a, b) => (a.path < b.path ? -1 : 1));
  52. packages.push({
  53. id, version: str(e.version || mf.version), kind: str(e.kind || "package"),
  54. title: str(mf.title || id), description: str(mf.description),
  55. icon: iconOf(root, id, mf.icon),
  56. source: str(e.source), sha256: str(e.sha256).slice(0, 12), installed: str(e.installed),
  57. manifest: existsSync(mfFile),
  58. requires: ranges(mf.requires ?? e.requires), includes: ranges(mf.includes),
  59. actions: list(mf.actions).filter((a) => a && a.name).map((a) => ({
  60. name: str(a.name), run: str(a.run), check: a.check === true, norm: a.norm ? str(a.norm) : "", title: str(a.title),
  61. })),
  62. pages,
  63. norms: pages.map((p) => norm(root, p.path.slice(1), p.state)).filter(Boolean),
  64. });
  65. }
  66. return { project: str(lock.project), name: str(lock.name || lock.project), lockVersion: str(lock.lockVersion), packages };
  67. }
  68. /** The package's icon as a path from the project root: its `icon:` file (an .svg next to package.md), else "". */
  69. function iconOf(root, id, icon) {
  70. const f = typeof icon === "string" && /^[\w.-]+\.svg$/.test(icon) ? icon : "";
  71. return f && existsSync(join(root, ".shtukbase", "packages", id, f)) ? "/.shtukbase/packages/" + id + "/" + f : "";
  72. }
  73. /** The text of lib/base/packages.data.js for the project, or null when it has no lock. */
  74. export function packagesFile(root) {
  75. const data = packagesData(root);
  76. if (!data) return null;
  77. const json = JSON.stringify(data, null, 1).replace(/<\/(script)/gi, "<\\/$1");
  78. return "// Built by the build action of the lenses package from .shtukbase/packages.lock and the packages' package.md. Do not edit by hand.\n"
  79. + "window.SHTUK_PACKAGES = " + json + ";\n";
  80. }
  81. /** Writes the data file; returns a line for the person, or null when there is nothing to write. */
  82. export function writePackages(root) {
  83. const text = packagesFile(root);
  84. if (text === null) return null;
  85. const file = join(root, DATA_FILE);
  86. mkdirSync(dirname(file), { recursive: true });
  87. const same = existsSync(file) && readFileSync(file, "utf8") === text;
  88. if (!same) writeFileSync(file, text);
  89. return `Project packages → ${DATA_FILE}` + (same ? " (unchanged)" : "");
  90. }
  91. /** Null when the data file is fresh (or the project has no lock), else what is wrong. */
  92. export function stalePackages(root) {
  93. const text = packagesFile(root);
  94. if (text === null) return null;
  95. const file = join(root, DATA_FILE);
  96. if (!existsSync(file)) return `no ${DATA_FILE}`;
  97. return readFileSync(file, "utf8") === text ? null : `${DATA_FILE} is stale`;
  98. }