forked from codesandbox/codesandbox-client
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdependencies.ts
More file actions
61 lines (51 loc) · 1.36 KB
/
dependencies.ts
File metadata and controls
61 lines (51 loc) · 1.36 KB
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
async function fetchWithRetries(url: string) {
let err: Error;
for (let i = 0; i < 5; i++) {
try {
// eslint-disable-next-line
return await fetch(url).then(x => {
if (x.ok) {
return x.json();
}
throw new Error('Could not fetch ' + url);
});
} catch (e) {
err = e;
}
}
throw err;
}
export async function fetchPackageJSON(dep: string, version: string) {
try {
return fetchWithRetries(
`https://cdn.jsdelivr.net/npm/${dep}@${encodeURIComponent(
version
)}/package.json`
);
} catch (e) {
return fetchWithRetries(
`https://unpkg.com/${dep}@${encodeURIComponent(version)}/package.json`
);
}
}
export function isAbsoluteVersion(version: string) {
const isAbsolute = /^\d+\.\d+\.\d+$/.test(version);
return isAbsolute || /\//.test(version);
}
export async function getAbsoluteDependencies(dependencies: Object) {
const nonAbsoluteDependencies = Object.keys(dependencies).filter(
dep => !isAbsoluteVersion(dependencies[dep])
);
const newDependencies = { ...dependencies };
await Promise.all(
nonAbsoluteDependencies.map(async dep => {
try {
const data = await fetchPackageJSON(dep, dependencies[dep]);
newDependencies[dep] = data.version;
} catch (e) {
/* ignore */
}
})
);
return newDependencies;
}