Welcome to mirror list, hosted at ThFree Co, Russian Federation.

index.js « map-workspaces « @npmcli « node_modules « npm « deps - github.com/nodejs/node.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: b06662154a83a18698a093cd392ca0a3c1fefc0c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
const { promisify } = require('util')
const path = require('path')

const getName = require('@npmcli/name-from-folder')
const minimatch = require('minimatch')
const rpj = require('read-package-json-fast')
const glob = require('glob')
const pGlob = promisify(glob)

function appendNegatedPatterns (patterns) {
  const results = []
  for (let pattern of patterns) {
    const excl = pattern.match(/^!+/)
    if (excl) {
      pattern = pattern.substr(excl[0].length)
    }

    // strip off any / from the start of the pattern.  /foo => foo
    pattern = pattern.replace(/^\/+/, '')

    // an odd number of ! means a negated pattern.  !!foo ==> foo
    const negate = excl && excl[0].length % 2 === 1
    results.push({ pattern, negate })
  }

  return results
}

function getPatterns (workspaces) {
  const workspacesDeclaration =
    Array.isArray(workspaces.packages)
      ? workspaces.packages
      : workspaces

  if (!Array.isArray(workspacesDeclaration)) {
    throw getError({
      message: 'workspaces config expects an Array',
      code: 'EWORKSPACESCONFIG'
    })
  }

  return [
    ...appendNegatedPatterns(workspacesDeclaration),
    { pattern: '**/node_modules/**', negate: true }
  ]
}

function isEmpty (patterns) {
  return patterns.length < 2
}

function getPackageName (pkg, pathname) {
  const { name } = pkg
  return name || getName(pathname)
}

function pkgPathmame (opts) {
  return (...args) => {
    const cwd = opts.cwd ? opts.cwd : process.cwd()
    return path.join.apply(null, [cwd, ...args])
  }
}

// make sure glob pattern only matches folders
function getGlobPattern (pattern) {
  return pattern.endsWith('/')
    ? pattern
    : `${pattern}/`
}

function getError ({ Type = TypeError, message, code }) {
  return Object.assign(new Type(message), { code })
}

function reverseResultMap (map) {
  return new Map(Array.from(map, item => item.reverse()))
}

async function mapWorkspaces (opts = {}) {
  if (!opts || !opts.pkg) {
    throw getError({
      message: 'mapWorkspaces missing pkg info',
      code: 'EMAPWORKSPACESPKG'
    })
  }

  const { workspaces = [] } = opts.pkg
  const patterns = getPatterns(workspaces)
  const results = new Map()
  const seen = new Map()

  if (isEmpty(patterns)) {
    return results
  }

  const getGlobOpts = () => ({
    ...opts,
    ignore: [
      ...opts.ignore || [],
      ...['**/node_modules/**']
    ]
  })

  const getPackagePathname = pkgPathmame(opts)

  for (const item of patterns) {
    const matches = await pGlob(getGlobPattern(item.pattern), getGlobOpts())

    for (const match of matches) {
      let pkg
      const packageJsonPathname = getPackagePathname(match, 'package.json')
      const packagePathname = path.dirname(packageJsonPathname)

      try {
        pkg = await rpj(packageJsonPathname)
      } catch (err) {
        if (err.code === 'ENOENT') {
          continue
        } else {
          throw err
        }
      }

      const name = getPackageName(pkg, packagePathname)

      if (item.negate) {
        results.delete(packagePathname, name)
      } else {
        if (seen.has(name) && seen.get(name) !== packagePathname) {
          throw getError({
            Type: Error,
            message: 'must not have multiple workspaces with the same name',
            code: 'EDUPLICATEWORKSPACE'
          })
        }

        seen.set(name, packagePathname)
        results.set(packagePathname, name)
      }
    }
  }

  return reverseResultMap(results)
}

mapWorkspaces.virtual = function (opts = {}) {
  if (!opts || !opts.lockfile) {
    throw getError({
      message: 'mapWorkspaces.virtual missing lockfile info',
      code: 'EMAPWORKSPACESLOCKFILE'
    })
  }

  const { packages = {} } = opts.lockfile
  const { workspaces = [] } = packages[''] || {}
  const patterns = getPatterns(workspaces)

  // uses a pathname-keyed map in order to negate the exact items
  const results = new Map()

  if (isEmpty(patterns)) {
    return results
  }

  const getPackagePathname = pkgPathmame(opts)

  for (const packageKey of Object.keys(packages)) {
    if (packageKey === '') {
      continue
    }

    for (const item of patterns) {
      if (minimatch(packageKey, item.pattern)) {
        const packagePathname = getPackagePathname(packageKey)
        const name = getPackageName(packages[packageKey], packagePathname)

        if (item.negate) {
          results.delete(packagePathname)
        } else {
          results.set(packagePathname, name)
        }
      }
    }
  }

  // Invert pathname-keyed to a proper name-to-pathnames Map
  return reverseResultMap(results)
}

module.exports = mapWorkspaces