import { readFileSync, writeFileSync } from "node:fs"; import { join, relative } from "node:path"; import { applyWorkspaceRangeEdit, captureFiles, createPackageFilter, describeMajorChange, describeSkippedClusterFix, diffDuplicates, outstandingOverrides, partitionUnconditionalOverrides, planClusterApply, renderApplyPlan, restoreFiles, reuseKeys, selectClusterFixes, shouldColorize, } from "pm-dedup-core"; import type { ApplyPlanFileChange, ClusterFix, DuplicateSnapshot, FileSnapshot, IdentifyLockstepClusterFixesOptions, OverrideTargetState, PackageFilterOptions, PlannedManifestEdit, PlannedOverride, SelectedClusterFixes, VersionsSnapshot, } from "pm-dedup-core"; import { buildYarnPackagesMap } from "./helpers/buildYarnPackagesMap.ts"; import { collectWorkspaces, createManifestReader, } from "./helpers/collectWorkspaces.ts"; import { readDuplicateSnapshot } from "./helpers/duplicateSnapshot.ts"; import { addResolutions } from "./helpers/packageJsonResolutions.ts"; import { parseYarnLockPackages } from "./helpers/parseYarnLockPackages.ts"; import { lockPathOf } from "./helpers/projectDir.ts"; import { runYarn } from "./helpers/runYarn.ts"; import { readVersionsSnapshot } from "./helpers/versionsSnapshot.ts"; import { identifyClusterFixes } from "./identifyClusterFixes.ts"; import { readAndParseYarnLock } from "./readYarnLock.ts"; const issuesUrl = "https://github.com/christophehurpeau/pm-tools/issues"; export type ClusterApplyStatus = | "applied" | "dry-run" | "nothing-to-do" | "reverted"; export interface ClusterApplyOutcome { status: ClusterApplyStatus; before: DuplicateSnapshot; after: DuplicateSnapshot; // resolutions the duplicates came back without: reported, never left behind stickyOverrides: PlannedOverride[]; // how many edits the plan holds, so `--check` gates without re-planning plannedChangeCount: number; } export interface ApplyClusterFixesOptions { projectDir: string; dryRun?: boolean; log?: (message?: string) => void; // seams for tests: everything else runs against the real files resolve?: () => number | null; verifyFrozen?: () => number | null; readFixes?: (projectDir: string) => ClusterFix[]; readDuplicates?: (lockPath: string) => DuplicateSnapshot; readVersions?: (lockPath: string) => VersionsSnapshot; // restricts which packages may be touched, for deduplicating a large lockfile // a family at a time filter?: PackageFilterOptions; // lets a cluster fix upgrade a range the user declares to another major dedupeByDirectMajorBump?: boolean; // what `yarn install` itself would still change, for the dry-run report. Only // the caller runs that probe, so only it can say. packageManagerResiduals?: string; // decided by the caller, because a caller that passes `log` is not writing to // `process.stdout` and cannot be read off it color?: boolean; } const defaultReadFixes = ( projectDir: string, options: IdentifyLockstepClusterFixesOptions, ): ClusterFix[] => { const entries = readAndParseYarnLock(lockPathOf(projectDir)); const packages = parseYarnLockPackages(entries); return identifyClusterFixes( buildYarnPackagesMap(packages), packages, collectWorkspaces(packages, createManifestReader(projectDir)), options, ); }; // the root workspace is keyed "", which `join` already treats as the project // directory itself const manifestPathOf = (projectDir: string, importerPath: string): string => join(projectDir, importerPath, "package.json"); const describeOverride = (override: PlannedOverride): string => `"${override.packageName}": "${override.version}"`; /** * A yarn resolution is matched against the package a descriptor resolves to, so * an edge declared through an npm alias * (`"psc-pinned": "npm:printable-shell-command@~5.0.0"`) is repointed by a * resolution on the *target* name. The resolution is still written, because an * in-cluster requester declaring the package directly is repointed by it too, * but naming the alias-only requesters keeps a revert from saying nothing. */ const aliasOnlyRequesters = ( fixes: ClusterFix[], packageName: string, ): string[] => { const constraints = fixes .flatMap((fix) => fix.externalConstraints) .filter((constraint) => constraint.packageName === packageName); return constraints.length > 0 && constraints.every((c) => c.isAlias === true) ? constraints.map((constraint) => constraint.requester) : []; }; type ApplyState = OverrideTargetState; export const applyClusterFixes = ({ projectDir, dryRun = false, log = console.log, // `yarn install` is the only way to reach a version whose manifest the // lockfile does not carry, and the only thing that cascades a family's // internal pins resolve = () => runYarn(["install"], { cwd: projectDir }).status, // the result has to be what CI would install from the manifests alone verifyFrozen = () => runYarn(["install", "--immutable"], { cwd: projectDir }).status, dedupeByDirectMajorBump = false, readFixes = (dir: string) => defaultReadFixes(dir, { dedupeByDirectMajorBump }), readDuplicates = readDuplicateSnapshot, readVersions = readVersionsSnapshot, filter, packageManagerResiduals, color = shouldColorize(), }: ApplyClusterFixesOptions): ClusterApplyOutcome => { const packageFilter = createPackageFilter(filter); const readSelectedFixes = (dir: string): SelectedClusterFixes => selectClusterFixes(readFixes(dir), packageFilter); const lockPath = lockPathOf(projectDir); const rootManifestPath = join(projectDir, "package.json"); const before = readDuplicates(lockPath); const unchanged = ( status: ClusterApplyStatus, plannedChangeCount = 0, ): ClusterApplyOutcome => ({ status, before, after: before, stickyOverrides: [], plannedChangeCount, }); const { selected: fixes, skipped: filteredOut } = readSelectedFixes(projectDir); const plan = planClusterApply(fixes); // a yarn resolution applies to every requester of the package, so one a // third-party range rejects would force that dependent too const { safe: plannedOverrides, rejected } = partitionUnconditionalOverrides( fixes, plan.overrides, ); const skipped = [ ...filteredOut.map(describeSkippedClusterFix), ...plan.majorChanges.map(describeMajorChange), ...plan.unresolvableChanges.map( (unresolvable) => `${unresolvable}: no workspace file recorded for it`, ), ...plan.conflicts.map( (conflict) => `${conflict.packageName}: keeping ${conflict.kept}, ignoring ${conflict.dropped} asked by another cluster`, ), ...rejected.flatMap(({ override, rejectedBy }) => rejectedBy.map( (constraint) => `resolution ${describeOverride(override)}: ${constraint.requesterName ?? "workspace"} requires "${constraint.range}", and a yarn resolution would force it too`, ), ), ]; const changeCount = plan.manifestEdits.length + plannedOverrides.length; const relativeManifestPath = (importerPath: string): string => relative(projectDir, manifestPathOf(projectDir, importerPath)); const planFileChanges = (): ApplyPlanFileChange[] => [ ...[ ...new Set( plan.manifestEdits.map((edit) => relativeManifestPath(edit.importerPath), ), ), ].map((path) => ({ path, changes: plan.manifestEdits .filter((edit) => relativeManifestPath(edit.importerPath) === path) .map( (edit) => `"${edit.packageName}": "${edit.range}" -> "${edit.to}" (${edit.depType})`, ), })), { path: `${relative(projectDir, rootManifestPath)} resolutions`, transient: "removed once the result is verified", changes: plannedOverrides.map( (override) => `${describeOverride(override)} (${override.reason})`, ), }, ]; // A dry run prints the plan through the shared renderer and stops. const reportPlan = (): ClusterApplyOutcome => { renderApplyPlan({ fileChanges: changeCount === 0 ? [] : planFileChanges(), skipped, packageManagerResiduals, dedupeCommand: "yarn-berry-deduplicate", log, color, }); return unchanged("dry-run", changeCount); }; if (!dryRun) { for (const entry of skipped) { log(` Skipped ${entry}`); } } if (changeCount === 0) { return dryRun ? reportPlan() : unchanged("nothing-to-do"); } if (dryRun) { return reportPlan(); } const touchedPaths = [ ...new Set([ ...plan.manifestEdits.map((edit) => manifestPathOf(projectDir, edit.importerPath), ), rootManifestPath, ]), lockPath, ]; const originalSnapshot = captureFiles(touchedPaths); const revertTo = (snapshot: FileSnapshot[]): void => { restoreFiles(snapshot); resolve(); }; const editManifests = (edits: PlannedManifestEdit[]): boolean => edits.every((edit) => { const path = manifestPathOf(projectDir, edit.importerPath); const updated = applyWorkspaceRangeEdit(readFileSync(path, "utf8"), edit); if (updated === undefined) { log( ` ${path} no longer declares "${edit.packageName}": "${edit.range}" — the lockfile is out of date`, ); return false; } log( ` ${path}: "${edit.packageName}" ${edit.range} -> ${edit.to} in ${edit.depType}`, ); writeFileSync(path, updated); return true; }); // A reuse fix removes no duplicate — both copies keep their dependents — so // the duplicate set cannot tell whether it took. The detector can: the fix is // gone from its output once the edge points at the anchored version. const readState = (): ApplyState => ({ duplicates: readDuplicates(lockPath), versions: readVersions(lockPath), reuses: reuseKeys(readSelectedFixes(projectDir).selected), }); // A step keeps its edits as long as it broke nothing: a widened range often // deduplicates nothing on its own and only makes the resolutions applicable. const resolveAndCheck = (label: string): ApplyState | null => { if (resolve() !== 0) { log(` \`yarn install\` failed after ${label} — reverting`); return null; } const state = readState(); const { added } = diffDuplicates(before, state.duplicates); if (added.length > 0) { log(` ${label} introduced ${added.length} new duplicate(s) — reverting`); return null; } return state; }; if (plan.manifestEdits.length > 0) { log("Editing workspace ranges:"); if (!editManifests(plan.manifestEdits)) { revertTo(originalSnapshot); return unchanged("reverted", changeCount); } if (resolveAndCheck("the workspace range edits") === null) { revertTo(originalSnapshot); return unchanged("reverted", changeCount); } } const withoutOverridesSnapshot = captureFiles(touchedPaths); const rootManifestBefore = withoutOverridesSnapshot.find( (snapshot) => snapshot.path === rootManifestPath, )!; const remaining = readState(); const outstanding = outstandingOverrides(plannedOverrides, remaining); // The result is only a fix if CI can install it from the manifests as they // stand, resolutions removed and all. const frozenFailure = (): ClusterApplyOutcome | null => { if (verifyFrozen() === 0) return null; log( " `yarn install --immutable` rejects the result — reverting, the lockfile it produced is not one CI can reuse", ); revertTo(withoutOverridesSnapshot); return { status: "reverted", before, after: readDuplicates(lockPath), stickyOverrides: [], plannedChangeCount: changeCount, }; }; if (outstanding.length === 0) { return ( frozenFailure() ?? { status: "applied", before, after: remaining.duplicates, stickyOverrides: [], plannedChangeCount: changeCount, } ); } log(`Adding resolutions to ${rootManifestPath}:`); for (const override of outstanding) { log(` ${describeOverride(override)} (${override.reason})`); const aliased = aliasOnlyRequesters(fixes, override.packageName); if (aliased.length > 0) { log( ` every requester of ${override.packageName} declares it through an alias (${aliased.join(", ")}); a yarn resolution repoints the target, not those keys`, ); } } writeFileSync( rootManifestPath, addResolutions( rootManifestBefore.content ?? "{}", new Map( outstanding.map((override) => [override.packageName, override.version]), ), ), ); const withOverrides = resolveAndCheck("the resolutions"); if (withOverrides === null) { revertTo(withoutOverridesSnapshot); return unchanged("reverted", changeCount); } // The resolutions are scaffolding: yarn has to hold the deduplicated result // on its own, or the fix is not one we can ship. log("Removing the resolutions and re-resolving to check the result holds:"); restoreFiles([rootManifestBefore]); if (resolve() !== 0) { log(" `yarn install` failed without the resolutions — reverting"); revertTo(withoutOverridesSnapshot); return unchanged("reverted", changeCount); } const after = readState(); const returnedDuplicates = diffDuplicates( withOverrides.duplicates, after.duplicates, ).added; const returnedReuses = [...after.reuses].filter( (key) => !withOverrides.reuses.has(key), ); if (returnedDuplicates.length > 0 || returnedReuses.length > 0) { log( " The resolutions were the only thing holding the result: yarn resolves back without them. A fix that needs a standing resolution is not one this tool applies.", ); log(` Please report this cluster at ${issuesUrl}:`); for (const override of outstanding) { log(` ${describeOverride(override)}`); } revertTo(withoutOverridesSnapshot); return { status: "reverted", before, after: readDuplicates(lockPath), stickyOverrides: outstanding, plannedChangeCount: changeCount, }; } return ( frozenFailure() ?? { status: "applied", before, after: after.duplicates, stickyOverrides: [], plannedChangeCount: changeCount, } ); };