-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
373 lines (333 loc) · 9.87 KB
/
server.js
File metadata and controls
373 lines (333 loc) · 9.87 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
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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
import http from 'node:http'
import { readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { dirname, join } from 'node:path'
import { makeBadge, ValidationError } from 'badge-maker'
const __dirname = dirname(fileURLToPath(import.meta.url))
const LOGO_TEMPLATE = readFileSync(join(__dirname, 'logo-mark.svg'), 'utf8')
const INDEX_PATH = join(__dirname, 'public', 'index.html')
function readIndexHtml() {
return readFileSync(INDEX_PATH, 'utf8')
}
const STYLES = new Set([
'plastic',
'flat',
'flat-square',
'for-the-badge',
'social',
])
const DEFAULT_LINK = 'https://npmx.dev/'
const LABEL = 'npmx'
const MAX_MESSAGE_LEN = 64
const MAX_PKG_LEN = 214
const DEFAULT_FETCH_TIMEOUT_MS = Number(process.env.NPM_REGISTRY_TIMEOUT_MS) || 5000
const DEFAULT_VERSION_CACHE_TTL_MS = Number(process.env.NPM_VERSION_CACHE_TTL_MS) || 120000
function npmxPackageUrl(pkgName) {
if (
pkgName.includes('..') ||
pkgName.startsWith('/') ||
pkgName.includes('\\') ||
pkgName.includes('?') ||
pkgName.includes('#')
) {
throw new Error('Invalid package name')
}
return `https://npmx.dev/package/${pkgName}`
}
function parseHex(value, fallback) {
if (value == null || value === '') return fallback
const raw = String(value).trim()
const withHash = raw.startsWith('#') ? raw : `#${raw}`
if (!/^#[0-9a-f]{3}$|^#[0-9a-f]{6}$/i.test(withHash)) {
throw new Error(`Invalid hex color: ${value}`)
}
return withHash.toLowerCase()
}
function wantsIcon(q) {
const v = (q.get('icon') ?? '1').trim().toLowerCase()
if (v === '0' || v === 'false' || v === 'off' || v === 'no') {
return false
}
if (
v === '1' ||
v === 'true' ||
v === 'on' ||
v === 'yes' ||
v === ''
) {
return true
}
throw new Error('Invalid icon (use 1 or 0)')
}
function logoDataUrl(color) {
const svg = LOGO_TEMPLATE.replace(/__LOGO_COLOR__/g, color)
return `data:image/svg+xml;base64,${Buffer.from(svg, 'utf8').toString('base64')}`
}
async function fetchNpmVersion(pkg, { fetchImpl = fetch, timeoutMs = DEFAULT_FETCH_TIMEOUT_MS } = {}) {
const controller = new AbortController()
const timeout = setTimeout(() => controller.abort(), timeoutMs)
try {
const name = encodeURIComponent(pkg)
const res = await fetchImpl(`https://registry.npmjs.org/${name}/latest`, {
headers: { accept: 'application/json' },
signal: controller.signal,
})
if (res.status === 404) {
const err = new Error('Package not found')
err.code = 'ENOTFOUND'
throw err
}
if (!res.ok) {
const err = new Error(`npm registry ${res.status}`)
err.code = 'EREGISTRY'
throw err
}
const data = await res.json()
if (!data?.version) {
const err = new Error('Missing version in registry response')
err.code = 'EBADJSON'
throw err
}
return String(data.version)
} catch (err) {
if (err?.name === 'AbortError') {
const timeoutErr = new Error('npm registry timeout')
timeoutErr.code = 'ETIMEOUT'
throw timeoutErr
}
throw err
} finally {
clearTimeout(timeout)
}
}
function clampStr(s, max) {
if (s.length <= max) return s
return `${s.slice(0, max - 1)}…`
}
async function getCachedNpmVersion(pkg, cache, inflight, options) {
const now = Date.now()
const cached = cache.get(pkg)
if (cached && cached.expiresAt > now) {
return cached.version
}
const pending = inflight.get(pkg)
if (pending) {
return pending
}
const request = fetchNpmVersion(pkg, options)
.then((version) => {
cache.set(pkg, {
version,
expiresAt: Date.now() + options.cacheTtlMs,
})
return version
})
.finally(() => {
inflight.delete(pkg)
})
inflight.set(pkg, request)
return request
}
async function handleBadge(url, options = {}) {
const q = url.searchParams
const {
defaultPkg = (process.env.DEFAULT_NPM_PKG ?? '').trim(),
versionCache = new Map(),
inflightRequests = new Map(),
fetchImpl = fetch,
fetchTimeoutMs = DEFAULT_FETCH_TIMEOUT_MS,
cacheTtlMs = DEFAULT_VERSION_CACHE_TTL_MS,
} = options
let message = (q.get('message') ?? '').trim()
const pkg = (q.get('pkg') ?? '').trim()
if (message && pkg) {
const err = new Error('Use either `message` or `pkg`, not both')
err.code = 'EBADQUERY'
throw err
}
let resolvedPkg = ''
if (pkg) {
resolvedPkg = pkg
} else if (!message && defaultPkg) {
resolvedPkg = defaultPkg
}
if (resolvedPkg) {
if (resolvedPkg.length > MAX_PKG_LEN) {
throw new Error('Package name too long')
}
const version = await getCachedNpmVersion(
resolvedPkg,
versionCache,
inflightRequests,
{
fetchImpl,
timeoutMs: fetchTimeoutMs,
cacheTtlMs,
},
)
message = `v${version}`
}
if (!message) {
message = 'npmx.dev'
}
message = clampStr(message, MAX_MESSAGE_LEN)
const color = resolvedPkg
? 'brightgreen'
: (q.get('color') ?? 'informational')
const labelColor = q.get('labelColor') ?? ''
const styleRaw = (q.get('style') ?? 'flat').trim()
if (!STYLES.has(styleRaw)) {
throw new Error(
`Invalid style (use ${[...STYLES].join(', ')})`,
)
}
const showIcon = wantsIcon(q)
const logoColor = parseHex(
q.get('logoColor') ?? q.get('accent'),
'#51c8fc',
)
const defaultLink = resolvedPkg ? npmxPackageUrl(resolvedPkg) : DEFAULT_LINK
const linkLeft = (q.get('link') ?? defaultLink).trim() || defaultLink
const linkRight = (q.get('linkRight') ?? linkLeft).trim() || linkLeft
const format = {
label: LABEL,
message,
color,
style: styleRaw,
links: [linkLeft, linkRight],
}
if (showIcon) {
format.logoBase64 = logoDataUrl(logoColor)
}
if (labelColor) {
format.labelColor = labelColor
}
return makeBadge(format)
}
function send(res, status, body, headers = {}) {
const h = { ...headers }
if (typeof body === 'string' && !h['content-type']) {
h['content-type'] = 'text/plain; charset=utf-8'
}
res.writeHead(status, h)
res.end(body)
}
const HELP_TEXT = [
'npmx badge server',
'',
'Label is always "npmx".',
'',
'Version (npm registry latest):',
' GET /badge.svg?pkg=react',
' (optional) DEFAULT_NPM_PKG=my-pkg env → /badge.svg with no query fetches that version',
'',
'Custom message (no registry):',
' GET /badge.svg?message=1.0.0',
'',
'Icon: icon=1 (default) or icon=0 / false / off / no to hide the logo',
'Logo color (single hex): logoColor (alias: accent), default #51c8fc',
'',
'Color: registry version badges (?pkg= or DEFAULT_NPM_PKG) always use brightgreen for the',
' value segment; the color query is ignored there. For custom messages only, color sets the',
' right segment (Shields-style; SVG via badge-maker).',
'',
'Other: labelColor, style (flat|flat-square|plastic|for-the-badge|social),',
'link, linkRight (default: https://npmx.dev/package/<pkg> when version is from a package,',
` else ${DEFAULT_LINK})`,
'',
'Web UI: GET /',
].join('\n')
export function createBadgeServer(options = {}) {
const versionCache = options.versionCache ?? new Map()
const inflightRequests = options.inflightRequests ?? new Map()
const fetchImpl = options.fetchImpl ?? fetch
const fetchTimeoutMs = options.fetchTimeoutMs ?? DEFAULT_FETCH_TIMEOUT_MS
const cacheTtlMs = options.cacheTtlMs ?? DEFAULT_VERSION_CACHE_TTL_MS
const defaultPkg = options.defaultPkg ?? (process.env.DEFAULT_NPM_PKG ?? '').trim()
const logger = options.logger ?? console.error
return http.createServer(async (req, res) => {
try {
const url = new URL(req.url ?? '/', `http://${req.headers.host}`)
if (req.method !== 'GET') {
send(res, 405, 'Method not allowed', { allow: 'GET' })
return
}
if (
url.pathname === '/' ||
url.pathname === '' ||
url.pathname === '/index.html'
) {
send(res, 200, readIndexHtml(), {
'content-type': 'text/html; charset=utf-8',
'cache-control': 'no-cache',
})
return
}
if (url.pathname === '/help') {
send(res, 200, HELP_TEXT, { 'cache-control': 'no-cache' })
return
}
if (url.pathname !== '/badge.svg') {
send(res, 404, 'Not found')
return
}
const svg = await handleBadge(url, {
defaultPkg,
versionCache,
inflightRequests,
fetchImpl,
fetchTimeoutMs,
cacheTtlMs,
})
const q = url.searchParams
const explicitPkg = q.has('pkg') && q.get('pkg')?.trim()
const versionBacked =
explicitPkg || (!q.get('message')?.trim() && defaultPkg)
const maxAge = versionBacked ? 120 : 300
send(res, 200, svg, {
'content-type': 'image/svg+xml; charset=utf-8',
'cache-control': `public, max-age=${maxAge}`,
'access-control-allow-origin': '*',
})
} catch (e) {
if (e instanceof ValidationError) {
send(res, 400, e.message)
return
}
if (e.code === 'ENOTFOUND') {
send(res, 404, e.message)
return
}
if (e.code === 'EREGISTRY' || e.code === 'EBADJSON') {
send(res, 502, e.message)
return
}
if (e.code === 'ETIMEOUT') {
send(res, 504, e.message)
return
}
if (e.code === 'EBADQUERY') {
send(res, 400, e.message)
return
}
if (
e.message?.startsWith('Invalid') ||
e.message?.includes('Invalid style') ||
e.message?.includes('Invalid icon')
) {
send(res, 400, e.message)
return
}
logger(e)
send(res, 500, 'Internal error')
}
})
}
const isMainModule = process.argv[1] === fileURLToPath(import.meta.url)
if (isMainModule) {
const port = Number(process.env.PORT) || 3000
const server = createBadgeServer()
server.listen(port, () => {
console.error(`npmx-badge listening on http://localhost:${port}`)
})
}