forked from npmx-dev/npmx.dev
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path[...pkg].get.ts
More file actions
273 lines (242 loc) · 8.7 KB
/
[...pkg].get.ts
File metadata and controls
273 lines (242 loc) · 8.7 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
import * as v from 'valibot'
import { PackageRouteParamsSchema } from '#shared/schemas/package'
import type {
PackageAnalysis,
ExtendedPackageJson,
TypesPackageInfo,
CreatePackageInfo,
} from '#shared/utils/package-analysis'
import {
analyzePackage,
getTypesPackageName,
getCreatePackageName,
hasBuiltInTypes,
} from '#shared/utils/package-analysis'
import {
NPM_REGISTRY,
CACHE_MAX_AGE_ONE_DAY,
ERROR_PACKAGE_ANALYSIS_FAILED,
} from '#shared/utils/constants'
import { parseRepoUrl } from '#shared/utils/git-providers'
import { getLatestVersion, getLatestVersionBatch } from 'fast-npm-meta'
import type { ChangelogInfo } from '#shared/types'
import { findChangelogFile } from '#shared/utils/changelog'
import { fetchFileTree } from '../../../utils/file-tree'
import { checkReleaseTag } from '../../../utils/release-tag'
export default defineCachedEventHandler(
async event => {
// Parse package name and optional version from path
// e.g., "vue" or "vue/v/3.4.0" or "@nuxt/kit" or "@nuxt/kit/v/1.0.0"
const pkgParamSegments = getRouterParam(event, 'pkg')?.split('/') ?? []
const { rawPackageName, rawVersion } = parsePackageParams(pkgParamSegments)
try {
const { packageName, version } = v.parse(PackageRouteParamsSchema, {
packageName: rawPackageName,
version: rawVersion,
})
// Fetch package data
const encodedName = encodePackageName(packageName)
const versionSuffix = version ? `/${version}` : '/latest'
const pkg = await $fetch<ExtendedPackageJson>(
`${NPM_REGISTRY}/${encodedName}${versionSuffix}`,
)
// Only check for @types package if the package doesn't ship its own types
let typesPackage: TypesPackageInfo | undefined
if (!hasBuiltInTypes(pkg)) {
const typesPkgName = getTypesPackageName(packageName)
typesPackage = await fetchTypesPackageInfo(typesPkgName)
}
// Check for associated create-* package (e.g., vite -> create-vite, next -> create-next-app)
// Only show if the packages are actually associated (same maintainers or same org)
const createPackage = await findAssociatedCreatePackage(packageName, pkg)
// Detect changelog: check release tag first (faster), then fall back to file tree
const resolvedVersion = pkg.version ?? version ?? 'latest'
const changelog = await detectChangelog(pkg, packageName, resolvedVersion)
const analysis = analyzePackage(pkg, { typesPackage, createPackage })
return {
package: packageName,
version: resolvedVersion,
...analysis,
changelog,
} satisfies PackageAnalysisResponse
} catch (error: unknown) {
handleApiError(error, {
statusCode: 502,
message: ERROR_PACKAGE_ANALYSIS_FAILED,
})
}
},
{
maxAge: CACHE_MAX_AGE_ONE_DAY, // 24 hours - analysis rarely changes
swr: true,
getKey: event => {
const pkg = getRouterParam(event, 'pkg') ?? ''
return `analysis:v2:${pkg.replace(/\/+$/, '').trim()}`
},
},
)
function encodePackageName(name: string): string {
if (name.startsWith('@')) {
return `@${encodeURIComponent(name.slice(1))}`
}
return encodeURIComponent(name)
}
/**
* Fetch @types package info including deprecation status using fast-npm-meta.
* Returns undefined if the package doesn't exist.
*/
async function fetchTypesPackageInfo(packageName: string): Promise<TypesPackageInfo | undefined> {
const result = await getLatestVersion(packageName, { metadata: true, throw: false })
if ('error' in result) {
return undefined
}
return {
packageName,
deprecated: result.deprecated,
}
}
/** Package metadata needed for association validation */
interface PackageWithMeta {
maintainers?: Array<{ name: string }>
repository?: { url?: string }
deprecated?: string
}
/**
* Get all possible create-* package name patterns for a given package.
* e.g., "next" -> ["create-next", "create-next-app"]
* e.g., "@scope/foo" -> ["@scope/create-foo", "@scope/create-foo-app"]
*/
function getCreatePackageNameCandidates(packageName: string): string[] {
const baseName = getCreatePackageName(packageName)
return [baseName, `${baseName}-app`]
}
/**
* Find an associated create-* package by trying multiple naming patterns using batch API.
* Returns the first associated package found (preferring create-{name} over create-{name}-app).
*/
async function findAssociatedCreatePackage(
packageName: string,
basePkg: ExtendedPackageJson,
): Promise<CreatePackageInfo | undefined> {
const candidates = getCreatePackageNameCandidates(packageName)
// Use batch API to fetch all candidates in a single request
const results = await getLatestVersionBatch(candidates, { metadata: true, throw: false })
// Process results in order (first valid match wins)
for (let i = 0; i < candidates.length; i++) {
const result = results[i]
const candidateName = candidates[i]
if (!result || !candidateName || 'error' in result) continue
// Need to fetch full package data for association validation (maintainers/repo)
const createPkgInfo = await fetchCreatePackageForValidation(
candidateName,
basePkg,
result.deprecated,
)
if (createPkgInfo) {
return createPkgInfo
}
}
return undefined
}
/**
* Fetch create-* package metadata for association validation.
* Returns CreatePackageInfo if the package is associated with the base package.
*/
async function fetchCreatePackageForValidation(
createPkgName: string,
basePkg: ExtendedPackageJson,
deprecated: string | undefined,
): Promise<CreatePackageInfo | undefined> {
try {
const encodedName = encodePackageName(createPkgName)
// Fetch /latest to get maintainers and repository for association validation
const createPkg = await $fetch<PackageWithMeta>(`${NPM_REGISTRY}/${encodedName}/latest`)
// Validate that the packages are actually associated
if (!isAssociatedPackage(basePkg, createPkg)) {
return undefined
}
return {
packageName: createPkgName,
deprecated,
}
} catch {
return undefined
}
}
/**
* Check if two packages are associated (share maintainers or same repo owner).
*/
function isAssociatedPackage(
basePkg: { maintainers?: Array<{ name: string }>; repository?: { url?: string } },
createPkg: { maintainers?: Array<{ name: string }>; repository?: { url?: string } },
): boolean {
const baseMaintainers = new Set(basePkg.maintainers?.map(m => m.name.toLowerCase()) ?? [])
const createMaintainers = createPkg.maintainers?.map(m => m.name.toLowerCase()) ?? []
const hasSharedMaintainer = createMaintainers.some(name => baseMaintainers.has(name))
return (
hasSharedMaintainer ||
hasSameRepositoryOwner(basePkg.repository?.url, createPkg.repository?.url)
)
}
/**
* Check if two repository URLs have the same owner (works with any git provider).
*/
function hasSameRepositoryOwner(
baseRepoUrl: string | undefined,
createRepoUrl: string | undefined,
): boolean {
if (!baseRepoUrl || !createRepoUrl) return false
const baseRef = parseRepoUrl(baseRepoUrl)
const createRef = parseRepoUrl(createRepoUrl)
if (!baseRef || !createRef) return false
if (baseRef.provider !== createRef.provider) return false
if (baseRef.host && createRef.host && baseRef.host !== createRef.host) return false
return baseRef.owner.toLowerCase() === createRef.owner.toLowerCase()
}
export interface PackageAnalysisResponse extends PackageAnalysis {
package: string
version: string
}
/**
* Detect changelog for a package version.
* Priority: release tag (faster) > changelog file in tarball
*/
async function detectChangelog(
pkg: ExtendedPackageJson,
packageName: string,
version: string,
): Promise<ChangelogInfo | undefined> {
// Step 1: Check for release tag (faster - single API call per tag format)
if (pkg.repository?.url) {
const repoRef = parseRepoUrl(pkg.repository.url)
if (repoRef) {
try {
const releaseInfo = await checkReleaseTag(repoRef, version, packageName)
if (releaseInfo.exists && releaseInfo.url) {
return {
source: 'releases',
url: releaseInfo.url,
}
}
} catch {
// Release tag check failed, continue to file tree check
}
}
}
// Step 2: Check for changelog file in tarball (fallback)
try {
const fileTreeResult = await fetchFileTree(packageName, version)
const changelogFile = findChangelogFile(fileTreeResult.files)
if (changelogFile) {
return {
source: 'file',
url: `/package-code/${packageName}/v/${version}/${changelogFile}`,
filename: changelogFile,
}
}
} catch {
// File tree fetch failed, no changelog available
}
// Neither release tag nor changelog file found
return undefined
}