forked from mjackson/unpkg
/
npm.js
206 lines (164 loc) · 4.83 KB
/
npm.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
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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
import url from 'url';
import {https} from 'follow-redirects';
import gunzip from 'gunzip-maybe';
import LRUCache from 'lru-cache';
import bufferStream from './bufferStream.js';
const npmRegistryURL =
process.env.NPM_REGISTRY_URL || 'https://registry.npmjs.org';
const agent = new https.Agent({
keepAlive: true
});
const oneMegabyte = 1024 * 1024;
const oneSecond = 1000;
const oneMinute = oneSecond * 60;
const cache = new LRUCache({
max: oneMegabyte * 40,
length: Buffer.byteLength,
maxAge: oneSecond
});
const notFound = '';
function get(options) {
return new Promise((accept, reject) => {
https.get(options, accept).on('error', reject);
});
}
function isScopedPackageName(packageName) {
return packageName.startsWith('@');
}
function encodePackageName(packageName) {
return isScopedPackageName(packageName)
? `@${encodeURIComponent(packageName.substring(1))}`
: encodeURIComponent(packageName);
}
async function fetchPackageInfo(packageName, log) {
const name = encodePackageName(packageName);
const infoURL = `${npmRegistryURL}/${name}`;
log.debug('Fetching package info for %s from %s', packageName, infoURL);
const { hostname, pathname } = url.parse(infoURL);
const options = {
agent: agent,
hostname: hostname,
path: pathname,
headers: {
Accept: 'application/json'
}
};
const res = await get(options);
if (res.statusCode === 200) {
return bufferStream(res).then(JSON.parse);
}
if (res.statusCode === 404) {
return null;
}
const content = (await bufferStream(res)).toString('utf-8');
log.error(
'Error fetching info for %s (status: %s)',
packageName,
res.statusCode
);
log.error(content);
return null;
}
async function fetchVersionsAndTags(packageName, log) {
const info = await fetchPackageInfo(packageName, log);
return info && info.versions
? { versions: Object.keys(info.versions), tags: info['dist-tags'] }
: null;
}
/**
* Returns an object of available { versions, tags }.
* Uses a cache to avoid over-fetching from the registry.
*/
export async function getVersionsAndTags(packageName, log) {
const cacheKey = `versions-${packageName}`;
const cacheValue = cache.get(cacheKey);
if (cacheValue != null) {
return cacheValue === notFound ? null : JSON.parse(cacheValue);
}
const value = await fetchVersionsAndTags(packageName, log);
if (value == null) {
cache.set(cacheKey, notFound, 5 * oneMinute);
return null;
}
cache.set(cacheKey, JSON.stringify(value), oneMinute);
return value;
}
// All the keys that sometimes appear in package info
// docs that we don't need. There are probably more.
const packageConfigExcludeKeys = [
'browserify',
'bugs',
'directories',
'engines',
'files',
'homepage',
'keywords',
'maintainers',
'scripts'
];
function cleanPackageConfig(config) {
return Object.keys(config).reduce((memo, key) => {
if (!key.startsWith('_') && !packageConfigExcludeKeys.includes(key)) {
memo[key] = config[key];
}
return memo;
}, {});
}
async function fetchPackageConfig(packageName, version, log) {
const info = await fetchPackageInfo(packageName, log);
return info && info.versions && version in info.versions
? cleanPackageConfig(info.versions[version])
: null;
}
/**
* Returns metadata about a package, mostly the same as package.json.
* Uses a cache to avoid over-fetching from the registry.
*/
export async function getPackageConfig(packageName, version, log) {
const cacheKey = `config-${packageName}-${version}`;
const cacheValue = cache.get(cacheKey);
if (cacheValue != null) {
return cacheValue === notFound ? null : JSON.parse(cacheValue);
}
const value = await fetchPackageConfig(packageName, version, log);
if (value == null) {
cache.set(cacheKey, notFound, 5 * oneMinute);
return null;
}
cache.set(cacheKey, JSON.stringify(value), oneMinute);
return value;
}
/**
* Returns a stream of the tarball'd contents of the given package.
*/
export async function getPackage(packageName, version, log) {
const tarballName = isScopedPackageName(packageName)
? packageName.split('/')[1]
: packageName;
const tarballURL = `${npmRegistryURL}/${packageName}/-/${tarballName}-${version}.tgz`;
log.debug('Fetching package for %s from %s', packageName, tarballURL);
const { hostname, pathname } = url.parse(tarballURL);
const options = {
agent: agent,
hostname: hostname,
path: pathname
};
const res = await get(options);
if (res.statusCode === 200) {
const stream = res.pipe(gunzip());
// stream.pause();
return stream;
}
if (res.statusCode === 404) {
return null;
}
const content = (await bufferStream(res)).toString('utf-8');
log.error(
'Error fetching tarball for %s@%s (status: %s)',
packageName,
version,
res.statusCode
);
log.error(content);
return null;
}