import { readFileSync } from "node:fs"; import path from "node:path"; import type { Plugin } from "vite"; type ModuleInventoryChunk = Readonly<{ fileName: string; modules: readonly string[]; }>; /** * Rollup knows the exact source-module set for every emitted chunk. Persisting * that graph makes optional-runtime exclusion verifiable without relying on * minified names, error strings, or source maps. */ export function viteModuleInventoryPlugin( repositoryRoot = process.cwd(), ): Plugin { return { name: "frontend-module-inventory", generateBundle(_options, bundle) { const chunks: ModuleInventoryChunk[] = Object.values(bundle) .filter((output) => output.type === "chunk") .map((chunk) => ({ fileName: chunk.fileName, modules: Object.freeze( [...new Set( Object.keys(chunk.modules).map((moduleId) => normalizeModuleId(moduleId, repositoryRoot), ), )].sort(), ), })) .sort((left, right) => left.fileName.localeCompare(right.fileName)); this.emitFile({ type: "asset", fileName: ".vite/module-inventory.json", source: `${JSON.stringify( { schemaVersion: 1, chunks, packages: bundledPackages(chunks), }, null, 2, )}\n`, }); }, }; } /** * 13-12. The `name@version` of every package with at least one module in the * emitted bundle: what the public release actually ships, as opposed to the * SBOM, which lists the whole installed graph. */ export function bundledPackages(chunks: readonly ModuleInventoryChunk[]): string[] { const packages = new Set(); for (const chunk of chunks) { for (const module of chunk.modules) { const match = /^npm:((?:@[^/]+\/)?[^/@]+@[^/]+)\//u.exec(module); if (match?.[1]) packages.add(match[1]); } } return [...packages].sort(); } const packageManifests = new Map>(); function installedPackage(directory: string): Readonly<{ name: string; version: string }> { let manifest = packageManifests.get(directory); if (!manifest) { const parsed = JSON.parse(readFileSync(path.join(directory, "package.json"), "utf8")) as { name?: unknown; version?: unknown; }; if (typeof parsed.name !== "string" || typeof parsed.version !== "string") { throw new TypeError(`bundled package has no name/version: ${directory}`); } manifest = Object.freeze({ name: parsed.name, version: parsed.version }); packageManifests.set(directory, manifest); } return manifest; } export function normalizeModuleId( moduleId: string, repositoryRoot: string, ): string { const withoutQuery = moduleId.replace(/^\0/u, "").split("?", 1)[0] ?? ""; if (!path.isAbsolute(withoutQuery)) { return withoutQuery.replaceAll("\\", "/"); } // 13-12: a dependency module keeps its package identity, read from the // package.json of the directory it was resolved into. const file = withoutQuery.replaceAll("\\", "/"); const marker = "/node_modules/"; const at = file.lastIndexOf(marker); if (at >= 0) { const segments = file.slice(at + marker.length).split("/"); const nameLength = segments[0]?.startsWith("@") ? 2 : 1; const directory = file.slice(0, at + marker.length) + segments.slice(0, nameLength).join("/"); const { name, version } = installedPackage(directory); return `npm:${name}@${version}/${segments.slice(nameLength).join("/")}`; } const relative = path.relative(repositoryRoot, withoutQuery); return relative.startsWith("..") ? `external:${path.basename(withoutQuery)}` : relative.replaceAll("\\", "/"); }