Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
103 changes: 65 additions & 38 deletions app/composables/npm/useNpmSearch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,10 @@ export function useNpmSearch(

const isLoadingMore = shallowRef(false)

// Track rate limit errors separately for better UX
// Using ref instead of shallowRef to ensure reactivity triggers properly
const isRateLimited = ref(false)

// Standard (non-incremental) search implementation
let lastSearch: NpmSearchResponse | undefined = undefined

Expand All @@ -74,34 +78,64 @@ export function useNpmSearch(
const q = toValue(query)

if (!q.trim()) {
isRateLimited.value = false
return emptySearchResponse
}

const opts = toValue(options)

// This only runs for initial load or query changes
// Reset cache for new query
// Reset cache for new query (but don't reset rate limit yet - only on success)
cache.value = null

const params = new URLSearchParams()
params.set('text', q)
// Use requested size for initial fetch
params.set('size', String(opts.size ?? 25))

if (q.length === 1) {
const encodedName = encodePackageName(q)
const [{ data: pkg, isStale }, { data: downloads }] = await Promise.all([
$npmRegistry<Packument>(`/${encodedName}`, { signal }),
$npmApi<NpmDownloadCount>(`/downloads/point/last-week/${encodedName}`, {
signal,
}),
])

if (!pkg) {
return emptySearchResponse
try {
if (q.length === 1) {
const encodedName = encodePackageName(q)
const [{ data: pkg, isStale }, { data: downloads }] = await Promise.all([
$npmRegistry<Packument>(`/${encodedName}`, { signal }),
$npmApi<NpmDownloadCount>(`/downloads/point/last-week/${encodedName}`, {
signal,
}),
])

if (!pkg) {
return emptySearchResponse
}

const result = packumentToSearchResult(pkg, downloads?.downloads)

// If query changed/outdated, return empty search response
if (q !== toValue(query)) {
return emptySearchResponse
}

cache.value = {
query: q,
objects: [result],
total: 1,
}

// Success - clear rate limit flag
isRateLimited.value = false

return {
objects: [result],
total: 1,
isStale,
time: new Date().toISOString(),
}
}

const result = packumentToSearchResult(pkg, downloads?.downloads)
const { data: response, isStale } = await $npmRegistry<NpmSearchResponse>(
`/-/v1/search?${params.toString()}`,
{ signal },
60,
)

// If query changed/outdated, return empty search response
if (q !== toValue(query)) {
Expand All @@ -110,36 +144,27 @@ export function useNpmSearch(

cache.value = {
query: q,
objects: [result],
total: 1,
}

return {
objects: [result],
total: 1,
isStale,
time: new Date().toISOString(),
objects: response.objects,
total: response.total,
}
}

const { data: response, isStale } = await $npmRegistry<NpmSearchResponse>(
`/-/v1/search?${params.toString()}`,
{ signal },
60,
)
// Success - clear rate limit flag
isRateLimited.value = false

// If query changed/outdated, return empty search response
if (q !== toValue(query)) {
return emptySearchResponse
}
return { ...response, isStale }
} catch (error: unknown) {
// Detect rate limit errors. npm's 429 response doesn't include CORS headers,
// so the browser reports "Failed to fetch" instead of the actual status code.
const errorMessage = (error as { message?: string })?.message || String(error)
const isRateLimitError =
errorMessage.includes('Failed to fetch') || errorMessage.includes('429')

cache.value = {
query: q,
objects: response.objects,
total: response.total,
if (isRateLimitError) {
isRateLimited.value = true
return emptySearchResponse
}
throw error
}

return { ...response, isStale }
},
{ default: () => lastSearch || emptySearchResponse },
)
Expand Down Expand Up @@ -260,5 +285,7 @@ export function useNpmSearch(
hasMore,
/** Manually fetch more results up to target size (incremental mode only) */
fetchMore,
/** Whether the search was rate limited by npm (429 error) */
isRateLimited: readonly(isRateLimited),
}
}
14 changes: 11 additions & 3 deletions app/pages/search.vue
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ const {
isLoadingMore,
hasMore,
fetchMore,
isRateLimited,
} = useNpmSearch(query, () => ({
size: requestedSize.value,
incremental: true,
Expand Down Expand Up @@ -706,8 +707,15 @@ defineOgImageComponent('Default', {
</button>
</div>

<!-- Rate limited by npm - check FIRST before showing any results -->
<div v-if="isRateLimited" role="status" class="py-12">
<p class="text-fg-muted font-mono mb-6 text-center">
{{ $t('search.rate_limited') }}
</p>
</div>

<!-- Enhanced toolbar -->
<div v-if="visibleResults.total > 0" class="mb-6">
<div v-else-if="visibleResults.total > 0" class="mb-6">
<PackageListToolbar
:filters="filters"
v-model:sort-option="sortOption"
Expand Down Expand Up @@ -805,7 +813,7 @@ defineOgImageComponent('Default', {
</div>

<PackageList
v-if="displayResults.length > 0"
v-if="displayResults.length > 0 && !isRateLimited"
:results="displayResults"
:search-query="query"
:filters="filters"
Expand All @@ -828,7 +836,7 @@ defineOgImageComponent('Default', {

<!-- Pagination controls -->
<PaginationControls
v-if="displayResults.length > 0"
v-if="displayResults.length > 0 && !isRateLimited"
v-model:mode="paginationMode"
v-model:page-size="preferredPageSize"
v-model:current-page="currentPage"
Expand Down
1 change: 1 addition & 0 deletions i18n/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
"found_packages": "No packages found | Found 1 package | Found {count} packages",
"updating": "(updating...)",
"no_results": "No packages found for \"{query}\"",
"rate_limited": "Hit npm rate limit, try again in a moment",
"title": "search",
"title_search": "search: {search}",
"title_packages": "search packages",
Expand Down
1 change: 1 addition & 0 deletions lunaria/files/en-GB.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
"found_packages": "No packages found | Found 1 package | Found {count} packages",
"updating": "(updating...)",
"no_results": "No packages found for \"{query}\"",
"rate_limited": "Hit npm rate limit, try again in a moment",
"title": "search",
"title_search": "search: {search}",
"title_packages": "search packages",
Expand Down
1 change: 1 addition & 0 deletions lunaria/files/en-US.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
"found_packages": "No packages found | Found 1 package | Found {count} packages",
"updating": "(updating...)",
"no_results": "No packages found for \"{query}\"",
"rate_limited": "Hit npm rate limit, try again in a moment",
"title": "search",
"title_search": "search: {search}",
"title_packages": "search packages",
Expand Down
Loading