|
| 1 | +import { ProvenanceEntry, RawContact, RepoPackage } from '../../types' |
| 2 | +import { fetchJson, isEmail } from '../http' |
| 3 | + |
| 4 | +import { ParsedPurl } from './purl' |
| 5 | + |
| 6 | +const SOURCE = 'npm-registry' |
| 7 | + |
| 8 | +/* eslint-disable @typescript-eslint/no-explicit-any */ |
| 9 | + |
| 10 | +function npmPackagePath(parsed: ParsedPurl): string { |
| 11 | + const full = parsed.namespace ? `${parsed.namespace}/${parsed.name}` : parsed.name |
| 12 | + // Scoped packages must percent-encode the slash for the registry path. |
| 13 | + return full.startsWith('@') ? full.replace('/', '%2F') : full |
| 14 | +} |
| 15 | + |
| 16 | +export function mapNpm(doc: unknown, sourceUrl: string, fetchedAt: string): RawContact[] { |
| 17 | + if (!doc || typeof doc !== 'object') return [] |
| 18 | + const d = doc as any |
| 19 | + |
| 20 | + const declaredAt = typeof d.time?.modified === 'string' ? d.time.modified : undefined |
| 21 | + const prov = (): ProvenanceEntry[] => [ |
| 22 | + { source: SOURCE, sourceTier: 'B', path: sourceUrl, fetchedAt, declaredAt }, |
| 23 | + ] |
| 24 | + |
| 25 | + const contacts: RawContact[] = [] |
| 26 | + const seen = new Set<string>() |
| 27 | + const addEmail = (email: string, name?: string): void => { |
| 28 | + if (!isEmail(email)) return |
| 29 | + const key = email.toLowerCase() |
| 30 | + if (seen.has(key)) return |
| 31 | + seen.add(key) |
| 32 | + contacts.push({ |
| 33 | + channel: 'email', |
| 34 | + value: email, |
| 35 | + name, |
| 36 | + role: 'maintainer', |
| 37 | + tier: 'B', |
| 38 | + provenance: prov(), |
| 39 | + }) |
| 40 | + } |
| 41 | + |
| 42 | + if (typeof d.bugs?.email === 'string') addEmail(d.bugs.email) |
| 43 | + for (const m of Array.isArray(d.maintainers) ? d.maintainers : []) { |
| 44 | + if (typeof m?.email === 'string') |
| 45 | + addEmail(m.email, typeof m.name === 'string' ? m.name : undefined) |
| 46 | + } |
| 47 | + |
| 48 | + return contacts |
| 49 | +} |
| 50 | + |
| 51 | +export async function fetchNpm( |
| 52 | + parsed: ParsedPurl, |
| 53 | + _pkg: RepoPackage, |
| 54 | + timeoutMs: number, |
| 55 | +): Promise<RawContact[]> { |
| 56 | + const url = `https://registry.npmjs.org/${npmPackagePath(parsed)}` |
| 57 | + const { json } = await fetchJson(url, timeoutMs) |
| 58 | + if (!json) return [] |
| 59 | + return mapNpm(json, url, new Date().toISOString()) |
| 60 | +} |
0 commit comments