shippedPackage
uses node:module
A package tcm ships, installed with it: its directory and version. Undefined for others, and where tcm has none
beside it. The directory is the package's own, links followed. Run from its codebase, tcm ships what the codebase
installed for it (its package's with), in the cache it runs from: at its name (Vitest, through the cache's link
to it), or else under its alias, as its browser test runner is (all of it, so they're one install: a codebase
given Vitest linked and its browser side installed gets two that don't fit).
import { compareVersions } from "#codebase/tcmts/core/semver"; import { SHIPPED } from "#codebase/tcmts/loader/packages"; import fs from "node:fs"; import { createRequire } from "node:module"; import path from "node:path"; export function shippedPackage(name: string): { dir: string; version: string } | undefined { if (!SHIPPED.has(name)) return undefined; const near = createRequire(import.meta.url); for (const base of near.resolve.paths(name) ?? []) { const file = path.join(base, name, "package.json"); if (!fs.existsSync(file)) continue; const { version } = JSON.parse(fs.readFileSync(file, "utf8")) as { version?: string }; if (version) return { dir: fs.realpathSync(path.dirname(file)), version }; } // (followed by its version: `npm__vitest__` also begins `npm__vitest__browser-playwright__`) const alias = `npm__${name.replace(/^@/, "").replace("/", "__")}__`; for (const base of near.resolve.paths(name) ?? []) { if (!fs.existsSync(base)) continue; const found = fs .readdirSync(base) .filter((d) => d.startsWith(alias) && /^\d/.test(d.slice(alias.length))) .flatMap((d) => { try { const pkg = JSON.parse(fs.readFileSync(path.join(base, d, "package.json"), "utf8")) as { name?: string; version?: string; }; return pkg.name === name && pkg.version ? [{ dir: fs.realpathSync(path.join(base, d)), version: pkg.version }] : []; } catch { return []; } }) .sort((x, y) => compareVersions(y.version, x.version))[0]; if (found) return found; } return undefined; }