Class: Bibliothecary::Parsers::NPM

Inherits:
Object
  • Object
show all
Includes:
Analyser
Defined in:
lib/bibliothecary/parsers/npm.rb

Class Method Summary collapse

Methods included from Analyser

create_analysis, create_error_analysis, included

Class Method Details

.mappingObject



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/bibliothecary/parsers/npm.rb', line 8

def self.mapping
  {
    match_filename("package.json") => {
      kind: 'manifest',
      parser: :parse_manifest
    },
    match_filename("npm-shrinkwrap.json") => {
      kind: 'lockfile',
      parser: :parse_shrinkwrap
    },
    match_filename("yarn.lock") => {
      kind: 'lockfile',
      parser: :parse_yarn_lock
    },
    match_filename("package-lock.json") => {
      kind: 'lockfile',
      parser: :parse_package_lock
    }
  }
end

.parse_manifest(file_contents) ⇒ Object



56
57
58
59
60
61
# File 'lib/bibliothecary/parsers/npm.rb', line 56

def self.parse_manifest(file_contents)
  manifest = JSON.parse(file_contents)
  raise "appears to be a lockfile rather than manifest format" if manifest.key?('lockfileVersion')
  map_dependencies(manifest, 'dependencies', 'runtime') +
  map_dependencies(manifest, 'devDependencies', 'development')
end

.parse_package_lock(file_contents) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/bibliothecary/parsers/npm.rb', line 40

def self.parse_package_lock(file_contents)
  manifest = JSON.parse(file_contents)
  manifest.fetch('dependencies',[]).map do |name, requirement|
    if requirement.fetch("dev", false)
      type = 'development'
    else
      type = 'runtime'
    end
    {
      name: name,
      requirement: requirement["version"],
      type: type
    }
  end
end

.parse_shrinkwrap(file_contents) ⇒ Object



29
30
31
32
33
34
35
36
37
38
# File 'lib/bibliothecary/parsers/npm.rb', line 29

def self.parse_shrinkwrap(file_contents)
  manifest = JSON.parse(file_contents)
  manifest.fetch('dependencies',[]).map do |name, requirement|
    {
      name: name,
      requirement: requirement["version"],
      type: 'runtime'
    }
  end
end

.parse_yarn_lock(file_contents) ⇒ Object



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/bibliothecary/parsers/npm.rb', line 63

def self.parse_yarn_lock(file_contents)
  response = Typhoeus.post("#{Bibliothecary.configuration.yarn_parser_host}/parse", body: file_contents)

  raise Bibliothecary::RemoteParsingError.new("Http Error #{response.response_code} when contacting: #{Bibliothecary.configuration.yarn_parser_host}/parse", response.response_code) unless response.success?

  json = JSON.parse(response.body, symbolize_names: true)
  json.uniq.map do |dep|
    {
      name: dep[:name],
      requirement: dep[:version],
      lockfile_requirement: dep[:requirement],
      type: dep[:type]
    }
  end
end