1 var url = require("url")
3 var log = require("npmlog")
4 , npa = require("npm-package-arg")
6 module.exports = mapToRegistry
8 function mapToRegistry(name, config, cb) {
9 log.silly("mapToRegistry", "name", name)
12 // the name itself takes precedence
15 // the name is definitely scoped, so escape now
16 name = name.replace("/", "%2f")
18 log.silly("mapToRegistry", "scope (from package name)", data.scope)
20 registry = config.get(data.scope + ":registry")
22 log.verbose("mapToRegistry", "no registry URL found in name for scope", data.scope)
26 // ...then --scope=@scope or --scope=scope
27 var scope = config.get("scope")
28 if (!registry && scope) {
29 // I'm an enabler, sorry
30 if (scope.charAt(0) !== "@") scope = "@" + scope
32 log.silly("mapToRegistry", "scope (from config)", scope)
34 registry = config.get(scope + ":registry")
36 log.verbose("mapToRegistry", "no registry URL found in config for scope", scope)
40 // ...and finally use the default registry
42 log.silly("mapToRegistry", "using default registry")
43 registry = config.get("registry")
46 log.silly("mapToRegistry", "registry", registry)
48 var auth = config.getCredentialsByURI(registry)
50 // normalize registry URL so resolution doesn't drop a piece of registry URL
51 var normalized = registry.slice(-1) !== '/' ? registry + '/' : registry
53 log.silly('mapToRegistry', 'data', data)
54 if (data.type === 'remote') {
57 uri = url.resolve(normalized, name)
60 log.silly('mapToRegistry', 'uri', uri)
62 cb(null, uri, scopeAuth(uri, registry, auth), normalized)
65 function scopeAuth (uri, registry, auth) {
69 alwaysAuth: auth.alwaysAuth,
79 if (auth.token || auth.auth || (auth.username && auth.password)) {
80 requestHost = url.parse(uri).hostname
81 registryHost = url.parse(registry).hostname
83 if (requestHost === registryHost) {
84 cleaned.token = auth.token
85 cleaned.auth = auth.auth
86 cleaned.username = auth.username
87 cleaned.password = auth.password
88 } else if (auth.alwaysAuth) {
89 log.verbose('scopeAuth', 'alwaysAuth set for', registry)
90 cleaned.token = auth.token
91 cleaned.auth = auth.auth
92 cleaned.username = auth.username
93 cleaned.password = auth.password
95 log.silly('scopeAuth', uri, "doesn't share host with registry", registry)