oneCopyEach

tcmts.loader.packages.oneCopyEach · #uwy3ckqo · term · runs on the server

uses node:path

One copy of each package version in the cache. npm installs a package a peer asks for (React, for React Aria's own packages) at its name, beside the alias tcm installed it under: two copies of one version, which React can't be (two Reacts break hooks). A package at its name that's a locked version becomes a link to that version's alias. Run after each install (npm puts its copy back).

import type { Layout } from "#codebase/tcmts/loader";
import { installDir } from "#codebase/tcmts/loader/packages";
import fs from "node:fs";
import path from "node:path";

export function oneCopyEach(
  lay: Layout,
  locked: { name: string; range: string; version: string }[],
) {
  for (const l of locked) {
    const alias = installDir(lay, l.name, l.range);
    const named = path.join(lay.cacheDir, "node_modules", l.name);
    if (alias === named) continue;
    try {
      const real = fs.realpathSync(alias);
      if (fs.realpathSync(named) === real) continue;
      const version = (
        JSON.parse(fs.readFileSync(path.join(named, "package.json"), "utf8")) as {
          version?: string;
        }
      ).version;
      if (version !== l.version) continue;
      fs.rmSync(named, { recursive: true, force: true });
      fs.mkdirSync(path.dirname(named), { recursive: true });
      // (relative, as the package manager's own links are: a codebase moved or copied keeps working)
      fs.symlinkSync(path.relative(fs.realpathSync(path.dirname(named)), real), named, "dir");
    } catch {
      // (not installed at its name, or not at all: nothing to make one)
    }
  }
}

uses

used by