generated from YieldRay/nodejs-purejs-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathregistry.mjs
81 lines (76 loc) · 2.21 KB
/
registry.mjs
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
import { createInterface } from 'node:readline'
/**
* @type {Record<string,string>}
*/
export const REGISTRIES = {
npm: 'https://registry.npmjs.org/',
yarn: 'https://registry.yarnpkg.com/',
github: 'https://npm.pkg.github.com/',
taobao: 'https://registry.npmmirror.com/',
npmMirror: 'https://skimdb.npmjs.com/registry/',
tencent: 'https://mirrors.cloud.tencent.com/npm/',
}
/**
* Returns undefined when line does not contain registry, or registry as string
* @param {string} line
*/
function checkLine(line) {
let currLine = line.trim()
const keyName = 'registry'
if (!currLine.startsWith(keyName)) return
currLine = currLine.slice(keyName.length).trimStart()
if (!currLine.startsWith('=')) return
return currLine.slice(1).trimStart()
}
/**
* @param {NodeJS.ReadableStream} stream
* @returns {Promise<string|undefined>}
* @see https://docs.npmjs.com/cli/configuring-npm/npmrc
*/
export async function getRegistryFromStream(stream) {
const rl = createInterface(stream)
for await (const line of rl) {
const r = checkLine(line)
if (r) return r
}
}
/**
* Returns the proceed rc content
* @param {NodeJS.ReadableStream} stream
* @param {string} registryUrl
* @returns {Promise<string>}
*/
export async function setRegistryFromStream(stream, registryUrl) {
const rl = createInterface(stream)
const lines = []
for await (const line of rl) {
const r = checkLine(line)
if (r) {
lines.push(`registry=${registryUrl}`)
} else {
lines.push(line)
}
}
return lines.join('\n')
}
/**
* Returns `Infinity` when exceed timeout, and `null` when network error
* @param {string} url
* @param {number} timeoutLimit - in milliseconds
*/
export async function speedTest(url, timeoutLimit) {
try {
const beginTime = Date.now()
await fetch(url, {
method: 'HEAD',
signal: AbortSignal.timeout(timeoutLimit),
})
const timeSpent = Date.now() - beginTime
return timeSpent > timeoutLimit ? Infinity : timeSpent
} catch (e) {
if (e instanceof DOMException) {
return Infinity
}
return null // Network Error
}
}