-
Notifications
You must be signed in to change notification settings - Fork 3
/
override.js
73 lines (57 loc) · 1.96 KB
/
override.js
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
var semver = require('semver')
/*
if opts.override is non null, then resolve modules that match from there.
{
//either pass in the package.json you want for that package.
foo: foo_package_json
//or pass in another valid range...
bar: {verison: '1.0.1', to: '~2.0.0'}
//this will replace any bar that can use 1.0.1 with something that matches ~2.0.0
}
*/
function isPackage(pkg) {
return pkg.name && pkg.version && (pkg.dependencies || pkg.devDependencies)
}
module.exports = function (fallback) {
return function (module, vrange, opts, cb) {
if('string' === typeof opts.override) {
var or = {}
opts.override.split(',').map(function (e) {
var parts = e.split(/@|:/)
var module = parts.shift()
var to = parts.pop()
var version = parts.shift()
or[module] = {version: version || '*', target: to}
})
opts.override = or
}
//falback if there is no override for this module.
if(!opts.override || !opts.override[module])
return fallback(module, vrange, opts, cb)
//check if we can resolve this module with our override.
var r = opts.override[module]
if(semver.validRange(vrange, true) && semver.satisfies(r.version, vrange, true)) {
//if the entire package.json was passed in...
//that is all that we need to resolve this.
if(isPackage(r)) {
r.shasum = r.shasum || (r.dist && r.dist.shasum)
return cb(null, r)
}
else {
fallback(r.name || module, r.target, opts, function (err, pkg) {
if(!err) return cb(null, pkg)
err.message = 'Override failed. could not replace '
+ module + '@' + r.version
+ ' => ' + (r.name ? r.name + '@' : '') + r.target
+ '\n'
+ err.message
cb(err)
})
}
}
else
//if the override version does not satisfy this version
//fallback to the default resolution.
fallback(module, vrange, opts, cb)
}
}