forked from npmx-dev/npmx.dev
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpackages.get.ts
More file actions
61 lines (55 loc) · 1.86 KB
/
packages.get.ts
File metadata and controls
61 lines (55 loc) · 1.86 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
import { CACHE_MAX_AGE_ONE_HOUR, NPM_REGISTRY } from '#shared/utils/constants'
import { FetchError } from 'ofetch'
// Validation pattern for npm org names - url-safe symbol and not start with a dot (incl. ~test24214. or -ex~-)
const NPM_ORG_NAME_RE = /^[\w~-][\w.~-]*$/
function validateOrgName(name: string): void {
if (!name || name.length > 50 || !NPM_ORG_NAME_RE.test(name)) {
throw createError({
// TODO: throwing 404 rather than 400 as it's cacheable
statusCode: 404,
message: `Invalid org name: ${name}`,
})
}
}
export default defineCachedEventHandler(
async event => {
const org = getRouterParam(event, 'org')?.toLowerCase()
if (!org) {
throw createError({
// TODO: throwing 404 rather than 400 as it's cacheable
statusCode: 404,
message: 'Org name is required',
})
}
validateOrgName(org)
try {
const data = await $fetch<Record<string, string>>(
`${NPM_REGISTRY}/-/org/${encodeURIComponent(org)}/package`,
)
return {
packages: Object.keys(data),
count: Object.keys(data).length,
}
} catch (error) {
// Let 404s propagate (org not found) so consumers can distinguish from empty
if (error instanceof FetchError && error.statusCode === 404) {
throw createError({ statusCode: 404, message: `Organization not found: ${org}` })
}
// For other errors (network, etc.), return empty
// oxlint-disable-next-line no-console -- log npm registry fetch errors for debugging
console.warn(`[org-packages] Failed to fetch packages for org ${org}:`, error)
return {
packages: [],
count: 0,
}
}
},
{
maxAge: CACHE_MAX_AGE_ONE_HOUR,
swr: true,
getKey: event => {
const org = getRouterParam(event, 'org')?.toLowerCase() ?? ''
return `org-packages:v1:${org}`
},
},
)