testPackagesArePureByTheirCode

tcmts.cli.test.e2e.effects.testPackagesArePureByTheirCode · #6zm6sk67 · term

An npm package's code is read as the codebase's own is: a constant computed with an export that, through everything it uses, reaches nothing and holds no state (ms, read from its code) is kept as a pure constant is; one computed with an export that reaches the clock (date-fns's startOfToday) isn't

import { npmFacts } from "#codebase/tcmts/cli/npm";
import { okIn, tempDir } from "#codebase/tcmts/cli/test/e2e/harness";
import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";

export const testPackagesArePureByTheirCode = () => {
  const dir = tempDir("pure packages");
  const ok = (...args: string[]) => okIn(dir, ...args);
  ok("init");
  fs.writeFileSync(
    path.join(dir, "scratch.ts"),
    [
      "// tcm: namespace lib",
      'import ms from "ms";',
      'import { startOfToday } from "date-fns";',
      'export const day = ms("1d");',
      "export const today = startOfToday().getTime();",
      "export const main = (): number => (console.log(day, today > 0), 0);",
      "",
    ].join("\n"),
  );
  ok("add");
  assert.match(ok("run", "lib.main"), /86400000 true/);
  const cache = path.join(dir, ".tcm", "cache");
  const modules = fs
    .readdirSync(cache)
    .filter((f) => /^[a-z2-7]{52}\.ts$/.test(f))
    .map((f) => fs.readFileSync(path.join(cache, f), "utf8"))
    .join("\n");
  const msDir = fs
    .readdirSync(path.join(cache, "node_modules"))
    .find((d) => d.startsWith("npm__ms__"))!;
  const facts = npmFacts(
    cache,
    { module: `npm:ms@${msDir.slice("npm__ms__".length)}`, subpath: "", export: "default" },
    "server",
  );
  assert.match(
    modules,
    /const day = __tcm_kept\(\(\) => \(ms\("1d"\)\), 86400000\)/,
    `ms is pure: kept (${JSON.stringify(facts)}, ${msDir})\n${modules
      .split("\n")
      .filter((l) => /day/.test(l))
      .join("\n")}`,
  );
  assert.match(
    modules,
    /const today(: [^=]+)? = (?!__tcm_kept)/,
    "startOfToday reads the clock: computed as written",
  );
}

uses