Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: coerce dependency versions in semver parsing #2045

Merged
merged 1 commit into from
Mar 27, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 31 additions & 1 deletion src/blocks/blockPackageJson.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,7 @@ describe("blockPackageJson", () => {
`);
});

it("preserves an existing dependency when the addon has an older pinned version", () => {
it("preserves an existing dependency when the addon has an invalid version", () => {
const dependency = "test-dependency";
const creation = testBlock(blockPackageJson, {
addons: {
Expand Down Expand Up @@ -318,6 +318,36 @@ describe("blockPackageJson", () => {
`);
});

it("uses the addon's version when the existing equivalent is invalid semver", () => {
const dependency = "test-dependency";
const creation = testBlock(blockPackageJson, {
addons: {
properties: {
dependencies: {
[dependency]: "1.0.0",
},
},
},
options: {
...optionsBase,
packageData: {
dependencies: {
[dependency]: "next",
},
},
},
});

expect(
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion, @typescript-eslint/no-unsafe-member-access
JSON.parse(creation.files!["package.json"] as string).dependencies,
).toMatchInlineSnapshot(`
{
"test-dependency": "1.0.0",
}
`);
});

it("preserves an existing dependency when the addon has an older version minimum", () => {
const dependency = "test-dependency";
const creation = testBlock(blockPackageJson, {
Expand Down
11 changes: 8 additions & 3 deletions src/blocks/blockPackageJson.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,15 +119,20 @@ function collectBinFiles(bin: Record<string, string> | string | undefined) {
}

function removeRangePrefix(version: string) {
return version.replaceAll(/[\^~><=]/gu, "").split(" ")[0];
const raw = version.replaceAll(/[\^~><=]/gu, "").split(" ")[0];

return semver.coerce(raw) ?? raw;
}

function useLargerVersion(existing: string | undefined, replacement: string) {
if (!existing) {
if (!existing || existing === replacement) {
return replacement;
}

return semver.gt(removeRangePrefix(existing), removeRangePrefix(replacement))
const existingCoerced = semver.coerce(removeRangePrefix(existing));

return existingCoerced &&
semver.gt(existingCoerced, removeRangePrefix(replacement))
? existing
: replacement;
}
Expand Down