forked from renovatebot/renovate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
get.ts
319 lines (284 loc) · 9.33 KB
/
get.ts
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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
import url from 'node:url';
import is from '@sindresorhus/is';
import { DateTime } from 'luxon';
import { z } from 'zod';
import { GlobalConfig } from '../../../config/global';
import { HOST_DISABLED } from '../../../constants/error-messages';
import { logger } from '../../../logger';
import { ExternalHostError } from '../../../types/errors/external-host-error';
import * as packageCache from '../../../util/cache/package';
import type { Http } from '../../../util/http';
import type { HttpOptions } from '../../../util/http/types';
import { regEx } from '../../../util/regex';
import { LooseRecord } from '../../../util/schema-utils';
import { joinUrlParts } from '../../../util/url';
import type { Release, ReleaseResult } from '../types';
import type { CachedReleaseResult } from './types';
const SHORT_REPO_REGEX = regEx(
/^((?<platform>bitbucket|github|gitlab):)?(?<shortRepo>[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+)$/
);
const platformMapping: Record<string, string> = {
bitbucket: 'https://bitbucket.org/',
github: 'https://github.com/',
gitlab: 'https://gitlab.com/',
};
interface PackageSource {
sourceUrl: string | null;
sourceDirectory: string | null;
}
const PackageSource = z
.union([
z
.string()
.nonempty()
.transform((repository): PackageSource => {
let sourceUrl: string | null = null;
const sourceDirectory = null;
const shortMatch = repository.match(SHORT_REPO_REGEX);
if (shortMatch?.groups) {
const { platform = 'github', shortRepo } = shortMatch.groups;
sourceUrl = platformMapping[platform] + shortRepo;
} else {
sourceUrl = repository;
}
return { sourceUrl, sourceDirectory };
}),
z
.object({
url: z.string().nonempty().nullish(),
directory: z.string().nonempty().nullish(),
})
.transform(({ url, directory }) => {
const res: PackageSource = { sourceUrl: null, sourceDirectory: null };
if (url) {
res.sourceUrl = url;
}
if (directory) {
res.sourceDirectory = directory;
}
return res;
}),
])
.catch({ sourceUrl: null, sourceDirectory: null });
const DepResponse = z
.object({
versions: LooseRecord(
z.object({
repository: PackageSource,
homepage: z.string().nullish().catch(null),
deprecated: z.string().nullish().catch('Unknown deprecation reason'),
gitHead: z.string().nullish().catch(null),
dependencies: LooseRecord(z.string()).nullish().catch(null),
devDependencies: LooseRecord(z.string()).nullish().catch(null),
})
).catch({}),
repository: PackageSource,
homepage: z.string().nullish().catch(null),
time: LooseRecord(z.string()).catch({}),
'dist-tags': LooseRecord(z.string()).nullish().catch(null),
})
.transform((body) => {
const { time, versions, 'dist-tags': tags, repository } = body;
const latestTag = tags?.latest;
const latestVersion = latestTag ? versions[latestTag] : undefined;
const homepage = body.homepage ?? latestVersion?.homepage;
const latestVersionRepository = latestVersion?.repository ?? repository;
const sourceUrl = repository.sourceUrl ?? latestVersionRepository.sourceUrl;
const sourceDirectory =
repository.sourceDirectory ?? latestVersionRepository.sourceDirectory;
const deprecationMessage = latestVersion?.deprecated;
return {
time,
versions,
tags,
latestTag,
latestVersion,
homepage,
sourceUrl,
sourceDirectory,
deprecationMessage,
};
})
.transform(
({
homepage,
sourceUrl,
sourceDirectory,
tags,
versions,
time,
deprecationMessage,
}): ReleaseResult | null => {
if (is.emptyObject(versions)) {
return null;
}
const result: ReleaseResult = { releases: [] };
if (homepage) {
result.homepage = homepage;
}
if (sourceUrl) {
result.sourceUrl = sourceUrl;
}
if (sourceDirectory) {
result.sourceDirectory = sourceDirectory;
}
if (tags) {
result.tags = tags;
}
if (deprecationMessage) {
result.deprecationMessage = deprecationMessage;
}
for (const [version, versionInfo] of Object.entries(versions)) {
const {
gitHead: gitRef,
dependencies,
devDependencies,
deprecated,
repository: src,
} = versionInfo;
const release: Release = { version };
if (gitRef) {
release.gitRef = gitRef;
}
if (dependencies) {
release.dependencies = dependencies;
}
if (devDependencies) {
release.devDependencies = devDependencies;
}
if (deprecated) {
release.isDeprecated = true;
}
const releaseTimestamp = time[version];
if (releaseTimestamp) {
release.releaseTimestamp = releaseTimestamp;
}
if (src.sourceUrl && src.sourceUrl !== sourceUrl) {
release.sourceUrl = src.sourceUrl;
}
if (src.sourceDirectory && src.sourceDirectory !== sourceDirectory) {
release.sourceDirectory = src.sourceDirectory;
}
result.releases.push(release);
}
return result;
}
)
.catch(null);
export async function getDependency(
http: Http,
registryUrl: string,
packageName: string
): Promise<ReleaseResult | null> {
logger.trace(`npm.getDependency(${packageName})`);
const packageUrl = joinUrlParts(registryUrl, packageName.replace('/', '%2F'));
// Now check the persistent cache
const cacheNamespace = 'datasource-npm:data';
const cachedResult = await packageCache.get<CachedReleaseResult>(
cacheNamespace,
packageUrl
);
if (cachedResult) {
if (cachedResult.cacheData) {
const softExpireAt = DateTime.fromISO(
cachedResult.cacheData.softExpireAt
);
if (softExpireAt.isValid && softExpireAt > DateTime.local()) {
logger.trace('Cached result is not expired - reusing');
delete cachedResult.cacheData;
return cachedResult;
}
logger.trace('Cached result is soft expired');
} else {
logger.trace('Reusing legacy cached result');
return cachedResult;
}
}
const cacheMinutes = process.env.RENOVATE_CACHE_NPM_MINUTES
? parseInt(process.env.RENOVATE_CACHE_NPM_MINUTES, 10)
: 15;
const softExpireAt = DateTime.local()
.plus({ minutes: cacheMinutes })
.toISO()!;
let { cacheHardTtlMinutes } = GlobalConfig.get();
if (!(is.number(cacheHardTtlMinutes) && cacheHardTtlMinutes > cacheMinutes)) {
cacheHardTtlMinutes = cacheMinutes;
}
try {
const options: HttpOptions = {};
if (cachedResult?.cacheData?.etag) {
logger.trace({ packageName }, 'Using cached etag');
options.headers = { 'If-None-Match': cachedResult.cacheData.etag };
}
const res = await http.getJson(packageUrl, options, DepResponse);
if (cachedResult?.cacheData && res.statusCode === 304) {
logger.trace(`Cached npm result for ${packageName} is revalidated`);
cachedResult.cacheData.softExpireAt = softExpireAt;
await packageCache.set(
cacheNamespace,
packageUrl,
cachedResult,
cacheHardTtlMinutes
);
delete cachedResult.cacheData;
return cachedResult;
}
const etag = res.headers.etag;
const dep = res.body;
if (!dep) {
// Registry returned a 200 OK but with no versions
logger.debug(`No versions returned for npm dependency ${packageName}`);
return null;
}
dep.registryUrl = registryUrl;
if (dep.deprecationMessage) {
dep.deprecationMessage = `On registry \`${registryUrl}\`, the "latest" version of dependency \`${packageName}\` has the following deprecation notice:\n\n\`${dep.deprecationMessage}\`\n\nMarking the latest version of an npm package as deprecated results in the entire package being considered deprecated, so contact the package author you think this is a mistake.`;
}
logger.trace({ dep }, 'dep');
const cacheControl = res.headers?.['cache-control'];
if (
is.nonEmptyString(cacheControl) &&
regEx(/(^|,)\s*public\s*(,|$)/).test(cacheControl)
) {
dep.isPrivate = false;
const cacheData = { softExpireAt, etag };
await packageCache.set(
cacheNamespace,
packageUrl,
{ ...dep, cacheData },
etag ? cacheHardTtlMinutes : cacheMinutes
);
} else {
dep.isPrivate = true;
}
return dep;
} catch (err) {
const ignoredStatusCodes = [401, 402, 403, 404];
const ignoredResponseCodes = ['ENOTFOUND'];
if (
err.message === HOST_DISABLED ||
ignoredStatusCodes.includes(err.statusCode) ||
ignoredResponseCodes.includes(err.code)
) {
return null;
}
const uri = url.parse(packageUrl);
if (uri.host === 'registry.npmjs.org') {
if (cachedResult) {
logger.warn(
{ err },
'npmjs error, reusing expired cached result instead'
);
delete cachedResult.cacheData;
return cachedResult;
}
// istanbul ignore if
if (err.name === 'ParseError' && err.body) {
err.body = 'err.body deleted by Renovate';
}
throw new ExternalHostError(err);
}
logger.debug({ err }, 'Unknown npm lookup error');
return null;
}
}