/
index.ts
67 lines (59 loc) · 1.84 KB
/
index.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
import { logger } from '../../logger';
import { ExternalHostError } from '../../types/error';
import { Http } from '../../util/http';
import { CachePromise, cacheAble } from '../cache';
import { GetReleasesConfig, ReleaseResult } from '../common';
export const id = 'cdnjs';
const http = new Http(id);
interface CdnjsAsset {
version: string;
files: string[];
sri?: Record<string, string>;
}
interface CdnjsResponse {
homepage?: string;
repository?: {
type: 'git' | unknown;
url?: string;
};
assets?: CdnjsAsset[];
}
async function downloadLibrary(library: string): CachePromise<CdnjsResponse> {
const url = `https://api.cdnjs.com/libraries/${library}?fields=homepage,repository,assets`;
return { data: (await http.getJson<CdnjsResponse>(url)).body };
}
export async function getReleases({
lookupName,
}: GetReleasesConfig): Promise<ReleaseResult | null> {
// Each library contains multiple assets, so we cache at the library level instead of per-asset
const library = lookupName.split('/')[0];
try {
const { assets, homepage, repository } = await cacheAble({
id,
lookup: library,
cb: downloadLibrary,
});
if (!assets) {
return null;
}
const assetName = lookupName.replace(`${library}/`, '');
const releases = assets
.filter(({ files }) => files.includes(assetName))
.map(({ version, sri }) => ({ version, newDigest: sri[assetName] }));
const result: ReleaseResult = { releases };
if (homepage) {
result.homepage = homepage;
}
if (repository?.url) {
result.sourceUrl = repository.url;
}
return result;
} catch (err) {
if (err.statusCode === 404) {
logger.debug({ library }, 'cdnjs library not found');
return null;
}
// Throw an ExternalHostError for all other types of errors
throw new ExternalHostError(err);
}
}