-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnpm.ts
More file actions
381 lines (340 loc) · 10.5 KB
/
npm.ts
File metadata and controls
381 lines (340 loc) · 10.5 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
374
375
376
377
378
379
380
381
import type { Client } from '../core/client.ts'
import type {
Dependency,
Maintainer,
Package,
Registry,
RegistryFactory,
URLBuilder,
Version,
} from '../core/types.ts'
import { register } from '../core/registry.ts'
import { HTTPError, NotFoundError } from '../core/errors.ts'
import { normalizeLicense } from '../core/license.ts'
import { normalizeRepositoryURL } from '../core/repository.ts'
/** npm registry API response for a single package. */
interface NpmPackageResponse {
name: string
description?: string
homepage?: string
repository?: {
type?: string
url?: string
} | string
license?: string | {
type?: string
}
keywords?: string[]
'dist-tags': {
latest: string
}
versions: Record<string, NpmVersion>
time?: Record<string, string>
}
/** npm version data. */
interface NpmVersion {
name: string
version: string
description?: string
license?: string | {
type?: string
}
keywords?: string[]
author?: {
name?: string
email?: string
url?: string
}
contributors?: Array<{
name?: string
email?: string
url?: string
}>
maintainers?: Array<{
name?: string
email?: string
url?: string
}>
dependencies?: Record<string, string>
devDependencies?: Record<string, string>
optionalDependencies?: Record<string, string>
peerDependencies?: Record<string, string>
dist?: {
integrity?: string
shasum?: string
tarball?: string
}
deprecated?: boolean | string
}
/** npm registry client. */
class NpmRegistry implements Registry {
constructor(
baseURL: string,
client: Client,
) {
this.baseURL = baseURL
this.client = client
}
readonly baseURL: string
readonly client: Client
ecosystem(): string {
return 'npm'
}
async fetchPackage(name: string, signal?: AbortSignal): Promise<Package> {
const encodedName = this.encodeName(name)
const url = `${this.baseURL}/${encodedName}`
try {
const data = await this.client.getJSON<NpmPackageResponse>(url, signal)
const latestVersion = data['dist-tags'].latest
const latestVersionData = data.versions[latestVersion]
const licenses = this.extractLicense(data.license || latestVersionData?.license)
const namespace = this.extractNamespace(name)
return {
name: data.name,
description: data.description || '',
homepage: data.homepage || '',
documentation: '',
repository: normalizeRepositoryURL(data.repository || ''),
licenses,
keywords: data.keywords || [],
namespace,
latestVersion,
metadata: {},
}
}
catch (error) {
if (error instanceof HTTPError && error.isNotFound()) {
throw new NotFoundError('npm', name)
}
throw error
}
}
async fetchVersions(name: string, signal?: AbortSignal): Promise<Version[]> {
const encodedName = this.encodeName(name)
const url = `${this.baseURL}/${encodedName}`
try {
const data = await this.client.getJSON<NpmPackageResponse>(url, signal)
const versions: Version[] = []
for (const [versionStr, versionData] of Object.entries(data.versions)) {
const licenses = this.extractLicense(versionData.license)
const publishedAt = data.time?.[versionStr] ? new Date(data.time[versionStr]) : null
const status = versionData.deprecated ? 'deprecated' : ''
const integrity = versionData.dist?.integrity
? versionData.dist.integrity
: versionData.dist?.shasum
? `sha1-${versionData.dist.shasum}`
: ''
versions.push({
number: versionStr,
publishedAt,
licenses,
integrity,
status,
metadata: {},
})
}
return versions
}
catch (error) {
if (error instanceof HTTPError && error.isNotFound()) {
throw new NotFoundError('npm', name)
}
throw error
}
}
async fetchDependencies(
name: string,
version: string,
signal?: AbortSignal,
): Promise<Dependency[]> {
const encodedName = this.encodeName(name)
const url = `${this.baseURL}/${encodedName}`
try {
const data = await this.client.getJSON<NpmPackageResponse>(url, signal)
const versionData = data.versions[version]
if (!versionData) {
throw new NotFoundError('npm', name, version)
}
const dependencies: Dependency[] = []
// Runtime dependencies
if (versionData.dependencies) {
for (const [depName, requirements] of Object.entries(versionData.dependencies)) {
dependencies.push({
name: depName,
requirements,
scope: 'runtime',
optional: false,
})
}
}
// Development dependencies
if (versionData.devDependencies) {
for (const [depName, requirements] of Object.entries(versionData.devDependencies)) {
dependencies.push({
name: depName,
requirements,
scope: 'development',
optional: false,
})
}
}
// Optional dependencies
if (versionData.optionalDependencies) {
for (const [depName, requirements] of Object.entries(versionData.optionalDependencies)) {
dependencies.push({
name: depName,
requirements,
scope: 'runtime',
optional: true,
})
}
}
// Peer dependencies
if (versionData.peerDependencies) {
for (const [depName, requirements] of Object.entries(versionData.peerDependencies)) {
dependencies.push({
name: depName,
requirements,
scope: 'runtime',
optional: false,
})
}
}
return dependencies
}
catch (error) {
if (error instanceof HTTPError && error.isNotFound()) {
throw new NotFoundError('npm', name, version)
}
throw error
}
}
async fetchMaintainers(name: string, signal?: AbortSignal): Promise<Maintainer[]> {
const encodedName = this.encodeName(name)
const url = `${this.baseURL}/${encodedName}`
try {
const data = await this.client.getJSON<NpmPackageResponse>(url, signal)
const maintainers: Maintainer[] = []
const seen = new Set<string>()
// Collect from maintainers field
if (data.versions) {
for (const versionData of Object.values(data.versions)) {
if (versionData.maintainers) {
for (const maintainer of versionData.maintainers) {
const key = `${maintainer.name}:${maintainer.email}`
if (!seen.has(key)) {
seen.add(key)
maintainers.push({
uuid: '',
login: maintainer.email ? maintainer.email.split('@')[0] : '',
name: maintainer.name || '',
email: maintainer.email || '',
url: maintainer.url || '',
role: '',
})
}
}
}
// Collect from author field
if (versionData.author) {
const key = `${versionData.author.name}:${versionData.author.email}`
if (!seen.has(key)) {
seen.add(key)
maintainers.push({
uuid: '',
login: versionData.author.email ? versionData.author.email.split('@')[0] : '',
name: versionData.author.name || '',
email: versionData.author.email || '',
url: versionData.author.url || '',
role: 'author',
})
}
}
// Collect from contributors field
if (versionData.contributors) {
for (const contributor of versionData.contributors) {
const key = `${contributor.name}:${contributor.email}`
if (!seen.has(key)) {
seen.add(key)
maintainers.push({
uuid: '',
login: contributor.email ? contributor.email.split('@')[0] : '',
name: contributor.name || '',
email: contributor.email || '',
url: contributor.url || '',
role: 'contributor',
})
}
}
}
}
}
return maintainers
}
catch (error) {
if (error instanceof HTTPError && error.isNotFound()) {
throw new NotFoundError('npm', name)
}
throw error
}
}
urls(): URLBuilder {
return {
registry: (name: string, version?: string) => {
const base = `https://www.npmjs.com/package/${name}`
return version ? `${base}/v/${version}` : base
},
download: (name: string, version: string) => {
const encodedName = this.encodeName(name)
const tarballName = name.includes('/') ? name.split('/')[1] : name
return `https://registry.npmjs.org/${encodedName}/-/${tarballName}-${version}.tgz`
},
documentation: (name: string, _version?: string) => {
return `https://www.npmjs.com/package/${name}`
},
readme: (name: string, version?: string) => {
const ver = version ? `@${version}` : ''
return `https://cdn.jsdelivr.net/npm/${name}${ver}/README.md`
},
purl: (name: string, version?: string) => {
const versionSuffix = version ? `@${version}` : ''
return `pkg:npm/${name}${versionSuffix}`
},
}
}
/** Encode package name for URL (handle scoped packages). */
private encodeName(name: string): string {
if (name.startsWith('@')) {
return name.replace('/', '%2F')
}
return name
}
/** Extract namespace from scoped package name. */
private extractNamespace(name: string): string {
if (name.startsWith('@')) {
const parts = name.split('/')
return parts[0] || ''
}
return ''
}
/** Extract and normalize license. */
private extractLicense(raw: string | { type?: string } | undefined): string {
if (!raw) return ''
if (typeof raw === 'string') {
return normalizeLicense(raw)
}
if (typeof raw === 'object' && raw !== null) {
const obj = raw as Record<string, unknown>
if (typeof obj['type'] === 'string') {
return normalizeLicense(obj['type'])
}
}
return ''
}
}
/** Factory function for creating npm registry instances. */
const factory: RegistryFactory = (baseURL: string, client: Client): Registry => {
return new NpmRegistry(baseURL, client)
}
// Self-register on import
register('npm', 'https://registry.npmjs.org', factory)