diff --git a/advisory_test.go b/advisory_test.go index dc81986..2a0069a 100644 --- a/advisory_test.go +++ b/advisory_test.go @@ -13,11 +13,6 @@ type npmAdvisoryRange struct { Native string `json:"npm_native"` } -// Advisory ranges that list exact versions with spaces, which npm intersects. -var unsatisfiableNPMAdvisoryRanges = map[string]bool{ - "1.1.2 1.2.2": true, -} - func TestNPMAdvisoryRangesParse(t *testing.T) { filename := filepath.Join("testdata", "local", "data", "npm_advisory.json") data, err := os.ReadFile(filename) @@ -33,14 +28,7 @@ func TestNPMAdvisoryRangesParse(t *testing.T) { } for _, advisoryRange := range ranges { t.Run(fmt.Sprintf("%04d", advisoryRange.TestIndex), func(t *testing.T) { - _, err := ParseNative(advisoryRange.Native, schemeNPM) - if unsatisfiableNPMAdvisoryRanges[advisoryRange.Native] { - if err == nil { - t.Errorf("ParseNative(%q, npm) succeeded, want unsatisfiable range error", advisoryRange.Native) - } - return - } - if err != nil { + if _, err := ParseNative(advisoryRange.Native, schemeNPM); err != nil { t.Errorf("ParseNative(%q, npm): %v", advisoryRange.Native, err) } }) diff --git a/parser.go b/parser.go index adf45e0..ea5d169 100644 --- a/parser.go +++ b/parser.go @@ -210,6 +210,10 @@ func (p *Parser) ToVersString(r *Range, scheme string) string { } // Check if empty but has raw constraints (preserve them for output) if r.isEmptyFor(scheme) && len(r.RawConstraints) == 0 { + if scheme == schemeNPM { + // VERS has no empty range; this bound is below the lowest semver version. + return "vers:npm/<0.0.0-0" + } return fmt.Sprintf("vers:%s/", scheme) } @@ -439,6 +443,9 @@ func (p *Parser) parseNpmRange(s string) (*Range, error) { if err != nil { return nil, err } + if r.IsEmpty() { + continue + } allIntervals = append(allIntervals, r.Intervals...) allExclusions = append(allExclusions, r.Exclusions...) if len(r.RawConstraints) > 0 { @@ -447,6 +454,9 @@ func (p *Parser) parseNpmRange(s string) (*Range, error) { allRaw = append(allRaw, r.Intervals...) } } + if len(allIntervals) == 0 { + return &Range{}, nil + } return &Range{ Intervals: mergeIntervals(allIntervals, CompareVersions), Exclusions: allExclusions, @@ -455,96 +465,30 @@ func (p *Parser) parseNpmRange(s string) (*Range, error) { } // Handle space-separated AND constraints - if strings.ContainsAny(s, " \t\r\n") && !strings.Contains(s, " - ") { - parts := tokenizeNpmConstraints(s) - ranges := make([]*Range, 0, len(parts)) + if parts := tokenizeNpmConstraints(s); len(parts) > 1 { var result *Range - for i, part := range parts { + for _, part := range parts { r, err := p.parseNpmSingleRange(part) if err != nil { return nil, err } - ranges = append(ranges, r) if result == nil { result = r continue } result = result.Intersect(r) - if result.IsEmpty() { - return nil, npmUnsatisfiableError(parts, ranges, i) - } } - if len(ranges) > 1 { - result.RawConstraints = npmIntersectedRaw(ranges) + if result.IsEmpty() { + return &Range{}, nil } + // Per-comparator constraints would serialize as a union. + result.RawConstraints = nil return result, nil } return p.parseNpmSingleRange(s) } -// npmIntersectedRaw returns the raw constraints of the comparators that set -// the tightest lower and upper bound, since listing every comparator would -// serialize as a union. It returns nil when the merged intervals should be -// serialized instead. -func npmIntersectedRaw(ranges []*Range) []Interval { - var out Interval - lower, upper := -1, -1 - for i, r := range ranges { - raw := r.RawConstraints - if len(raw) == 0 { - raw = r.Intervals - } - if len(r.Intervals) != 1 || len(raw) != 1 { - return nil - } - bound := r.Intervals[0] - if bound.Min != "" && (lower < 0 || tighterLower(bound, ranges[lower].Intervals[0])) { - lower = i - out.Min, out.MinInclusive = raw[0].Min, raw[0].MinInclusive - } - if bound.Max != "" && (upper < 0 || tighterUpper(bound, ranges[upper].Intervals[0])) { - upper = i - out.Max, out.MaxInclusive = raw[0].Max, raw[0].MaxInclusive - } - } - if lower < 0 && upper < 0 { - return nil - } - return []Interval{out} -} - -func tighterLower(a, b Interval) bool { - c := CompareVersions(a.Min, b.Min) - return c > 0 || (c == 0 && !a.MinInclusive && b.MinInclusive) -} - -func tighterUpper(a, b Interval) bool { - c := CompareVersions(a.Max, b.Max) - return c < 0 || (c == 0 && !a.MaxInclusive && b.MaxInclusive) -} - -// npmUnsatisfiableError names the comparator at index last and an earlier one -// it cannot be satisfied together with. -func npmUnsatisfiableError(parts []string, ranges []*Range, last int) error { - conflict := 0 - for i := range last { - if ranges[i].Intersect(ranges[last]).IsEmpty() { - conflict = i - break - } - } - return fmt.Errorf("space-separated npm comparators are intersected: %s and %s match no version", - npmComparatorString(parts[conflict]), npmComparatorString(parts[last])) -} - -func npmComparatorString(part string) string { - if strings.ContainsAny(part[:1], "<>=!~^") { - return part - } - return "=" + part -} - // tokenizeNpmConstraints splits an npm constraint string into individual constraints, // properly handling operators followed by spaces (e.g., ">= 1.0.0" stays as one token). func tokenizeNpmConstraints(s string) []string { @@ -558,6 +502,11 @@ func tokenizeNpmConstraints(s string) []string { i := 0 for i < len(tokens) { token := tokens[i] + if i+2 < len(tokens) && tokens[i+1] == "-" { + result = append(result, token+" - "+tokens[i+2]) + i += 3 + continue + } // Check if this token is just an operator if isOperatorOnly(token) && i+1 < len(tokens) { // Merge with next token @@ -593,6 +542,9 @@ func extractOperator(s string) (string, string) { func (p *Parser) parseNpmSingleRange(s string) (*Range, error) { s = strings.TrimSpace(s) + if s == "-" { + return nil, fmt.Errorf("invalid npm range: hyphen without a version on both sides") + } // Caret range: ^1.2.3 if strings.HasPrefix(s, "^") { return p.parseCaretRange(s[1:]) diff --git a/parser_test.go b/parser_test.go index 81fc2c2..568cf75 100644 --- a/parser_test.go +++ b/parser_test.go @@ -194,7 +194,7 @@ func TestParseNpmRange(t *testing.T) { } func TestParseNpmRangeErrors(t *testing.T) { - for _, constraint := range []string{"1.x.2", "1.2.3.x"} { + for _, constraint := range []string{"1.x.2", "1.2.3.x", "-", "1.0.0 -", "- 1.0.0", "1.0.0 - 2.0.0 - 3.0.0", "1.0.0 || -"} { if _, err := ParseNative(constraint, schemeNPM); err == nil { t.Errorf("ParseNative(%q, npm) succeeded", constraint) } @@ -203,16 +203,28 @@ func TestParseNpmRangeErrors(t *testing.T) { func TestParseNpmIntersectionToVers(t *testing.T) { tests := []struct { - input string - want string + input string + want string + contains []string + excludes []string }{ - {">=5.0.3 >=4.2.1", "vers:npm/>=5.0.3"}, - {">=4.2.1 >=5.0.3 <6.0.0 <7.0.0", "vers:npm/>=5.0.3|<6.0.0"}, - {">1.0.0 >=1.0.0", "vers:npm/>1.0.0"}, - {"<=2.1 >=1.1 >=1.0", "vers:npm/>=1.1.0|<=2.1.0"}, - {"<=2.1 <2.1.5", "vers:npm/<2.1.5"}, - {"^1.2.3 >=1.5.0", "vers:npm/>=1.5.0|<2.0.0"}, - {">=1.0.0 <2.0.0 || >=3.0.0 >=3.1.0", "vers:npm/>=1.0.0|<2.0.0|>=3.1.0"}, + {">=5.0.3 >=4.2.1", "vers:npm/>=5.0.3", []string{"5.0.3"}, []string{"4.2.1"}}, + {">=4.2.1 >=5.0.3 <6.0.0 <7.0.0", "vers:npm/>=5.0.3|<6.0.0", []string{"5.5.0"}, []string{"6.0.0"}}, + {">1.0.0 >=1.0.0", "vers:npm/>1.0.0", []string{"1.0.1"}, []string{"1.0.0"}}, + {"<=2.1 >=1.1 >=1.0", "vers:npm/>=1.1.0|<2.2.0", []string{"2.1.9"}, []string{"1.0.5", "2.2.0"}}, + {"<=2.1 <2.2.0", "vers:npm/<2.2.0", []string{"2.1.9"}, []string{"2.2.0"}}, + {"<2.2.0 <=2.1", "vers:npm/<2.2.0", []string{"2.1.9"}, []string{"2.2.0"}}, + {">1.2 <2.0.0", "vers:npm/>=1.3.0|<2.0.0", []string{"1.3.0"}, []string{"1.2.8"}}, + {"1.2 >=1.2.3", "vers:npm/>=1.2.3|<1.3.0", []string{"1.2.5"}, []string{"1.2.0", "9.0.0"}}, + {"<2.x >=1.0.0", "vers:npm/>=1.0.0|<2.0.0", []string{"1.9.0"}, []string{"2.5.0"}}, + {"^1.2.3 >=1.5.0", "vers:npm/>=1.5.0|<2.0.0", []string{"1.5.0"}, []string{"1.4.0", "2.0.0"}}, + {">=1.0.0 <2.0.0 || >=3.0.0 >=3.1.0", "vers:npm/>=1.0.0|<2.0.0|>=3.1.0", []string{"1.5.0", "3.1.0"}, []string{"3.0.0"}}, + {"1.2.3 - 2.0.0 <1.5.0", "vers:npm/>=1.2.3|<1.5.0", []string{"1.4.0"}, []string{"1.7.0"}}, + {">=1.4.0 1.2.3 - 2.0.0", "vers:npm/>=1.4.0|<=2.0.0", []string{"2.0.0"}, []string{"1.3.0", "2.0.1"}}, + {"1.0.0 || >=2.0.0 <1.0.0", "vers:npm/1.0.0", []string{"1.0.0"}, []string{"2.0.0"}}, + {"1.1.2 1.2.2", "vers:npm/<0.0.0-0", nil, []string{"1.1.2", "1.2.2", "999.0.0"}}, + {">=1.0.0 ^1.2.3 <1.1.0", "vers:npm/<0.0.0-0", nil, []string{"1.0.5", "1.2.3"}}, + {">=2.0.0 <1.0.0 || 1.1.2 1.2.2", "vers:npm/<0.0.0-0", nil, []string{"1.1.2", "2.0.0"}}, } for _, tt := range tests { r, err := ParseNative(tt.input, schemeNPM) @@ -220,30 +232,64 @@ func TestParseNpmIntersectionToVers(t *testing.T) { t.Errorf("ParseNative(%q, npm): %v", tt.input, err) continue } - if got := ToVersString(r, schemeNPM); got != tt.want { + got := ToVersString(r, schemeNPM) + if got != tt.want { t.Errorf("ParseNative(%q, npm) = %q, want %q", tt.input, got, tt.want) } + reparsed, err := Parse(got) + if err != nil { + t.Errorf("Parse(%q): %v", got, err) + continue + } + for _, v := range tt.contains { + if !r.Contains(v) || !reparsed.Contains(v) { + t.Errorf("%q: Contains(%q) = %v, reparsed %v, want true", tt.input, v, r.Contains(v), reparsed.Contains(v)) + } + } + for _, v := range tt.excludes { + if r.Contains(v) || reparsed.Contains(v) { + t.Errorf("%q: Contains(%q) = %v, reparsed %v, want false", tt.input, v, r.Contains(v), reparsed.Contains(v)) + } + } } } func TestParseNpmUnsatisfiableIntersection(t *testing.T) { - tests := []struct { - input string - want string - }{ - {"1.1.2 1.2.2", "space-separated npm comparators are intersected: =1.1.2 and =1.2.2 match no version"}, - {">=2.0.0 <1.0.0", "space-separated npm comparators are intersected: >=2.0.0 and <1.0.0 match no version"}, - {">=1.0.0 ^1.2.3 <1.1.0", "space-separated npm comparators are intersected: ^1.2.3 and <1.1.0 match no version"}, - {"1.0.0 || >=2.0.0 <1.0.0", "space-separated npm comparators are intersected: >=2.0.0 and <1.0.0 match no version"}, - } - for _, tt := range tests { - _, err := ParseNative(tt.input, schemeNPM) - if err == nil { - t.Errorf("ParseNative(%q, npm) succeeded", tt.input) + for _, input := range []string{"1.1.2 1.2.2", ">=2.0.0 <1.0.0", ">=2.0.0 <1.0.0 || 1.1.2 1.2.2"} { + r, err := ParseNative(input, schemeNPM) + if err != nil { + t.Errorf("ParseNative(%q, npm): %v", input, err) continue } - if err.Error() != tt.want { - t.Errorf("ParseNative(%q, npm) error = %q, want %q", tt.input, err, tt.want) + if !r.IsEmpty() { + t.Errorf("ParseNative(%q, npm) is not empty", input) + } + } + if _, err := ParseNative("1.1.2 1.2.2 1.x.2", schemeNPM); err == nil { + t.Error("malformed comparator after a contradiction parsed without error") + } +} + +func TestIntersectEmptyNpmRangeToVers(t *testing.T) { + empty, err := ParseNative("1.1.2 1.2.2", schemeNPM) + if err != nil { + t.Fatal(err) + } + other, err := ParseNative(">=1.0.0", schemeNPM) + if err != nil { + t.Fatal(err) + } + for _, r := range []*Range{empty.Intersect(other), other.Intersect(empty)} { + got := ToVersString(r, schemeNPM) + if got != "vers:npm/<0.0.0-0" { + t.Errorf("ToVersString = %q, want vers:npm/<0.0.0-0", got) + } + reparsed, err := Parse(got) + if err != nil { + t.Fatalf("Parse(%q): %v", got, err) + } + if r.Contains("1.5.0") || reparsed.Contains("1.5.0") { + t.Errorf("Contains(1.5.0) = %v, reparsed %v, want false", r.Contains("1.5.0"), reparsed.Contains("1.5.0")) } } } @@ -617,7 +663,7 @@ func TestToVersString(t *testing.T) { want string }{ {"unbounded", Unbounded(), "npm", "vers:npm/*"}, - {"empty", Empty(), "npm", "vers:npm/"}, + {"empty", Empty(), "npm", "vers:npm/<0.0.0-0"}, {"exact", Exact("1.0.0"), "npm", "vers:npm/1.0.0"}, {"greater than", GreaterThan("1.0.0", true), "npm", "vers:npm/>=1.0.0"}, {"less than", LessThan("2.0.0", false), "npm", "vers:npm/<2.0.0"}, diff --git a/range.go b/range.go index a48127e..44ce3ec 100644 --- a/range.go +++ b/range.go @@ -339,6 +339,11 @@ func (r *Range) UnionChecked(other *Range) (*Range, error) { func (r *Range) Intersect(other *Range) *Range { left, right := rangesWithCommonScheme(r, other) + // The other side's constraints alone would serialize as a non-empty range. + if (left.IsEmpty() && len(left.RawConstraints) == 0) || (right.IsEmpty() && len(right.RawConstraints) == 0) { + return &Range{Scheme: left.Scheme} + } + // Combine raw constraints for VERS output (preserved even if result is empty) rawConstraints := make([]Interval, 0, len(left.RawConstraints)+len(right.RawConstraints)) if len(left.RawConstraints) > 0 { diff --git a/testdata/local/skip.json b/testdata/local/skip.json index 3dbaea1..105977a 100644 --- a/testdata/local/skip.json +++ b/testdata/local/skip.json @@ -9,6 +9,25 @@ }, "expected_output": false, "reason": "VERS constraints cannot encode Conan's per-branch prerelease opt-in." + }, + { + "file": "vers-spec/tests/npm_range_from_native_test.json", + "test_type": "from_native", + "input": { + "native_range": "1.1.2 1.2.2", + "scheme": "npm" + }, + "reason": "ParseNative returns an empty range for unsatisfiable npm comparators instead of an error." + }, + { + "file": "vers-spec/tests/npm_range_from_native_test.json", + "test_type": "from_native", + "input": { + "native_range": "<=2.1 >=1.1", + "scheme": "npm" + }, + "expected_output": "vers:npm/>=1.1.0|<=2.1.0", + "reason": "npm <=2.1 admits every 2.1.x, so the upper bound is <2.2.0." } ] }