forked from npmx-dev/npmx.dev
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseNpmSearch.ts
More file actions
364 lines (311 loc) · 10 KB
/
useNpmSearch.ts
File metadata and controls
364 lines (311 loc) · 10 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
import type {
Packument,
NpmSearchResponse,
NpmSearchResult,
NpmDownloadCount,
MinimalPackument,
} from '#shared/types'
import type { SearchProvider } from '~/composables/useSettings'
/**
* Convert packument to search result format for display
*/
export function packumentToSearchResult(
pkg: MinimalPackument,
weeklyDownloads?: number,
): NpmSearchResult {
let latestVersion = ''
if (pkg['dist-tags']) {
latestVersion = pkg['dist-tags'].latest || Object.values(pkg['dist-tags'])[0] || ''
}
const modified = pkg.time.modified || pkg.time[latestVersion] || ''
return {
package: {
name: pkg.name,
version: latestVersion,
description: pkg.description,
keywords: pkg.keywords,
date: pkg.time[latestVersion] || modified,
links: {
npm: `https://www.npmjs.com/package/${pkg.name}`,
},
maintainers: pkg.maintainers,
},
score: { final: 0, detail: { quality: 0, popularity: 0, maintenance: 0 } },
searchScore: 0,
downloads: weeklyDownloads !== undefined ? { weekly: weeklyDownloads } : undefined,
updated: pkg.time[latestVersion] || modified,
}
}
export interface NpmSearchOptions {
/** Number of results to fetch */
size?: number
onResponse?: (result: { query: string }) => void
}
export const emptySearchResponse = {
objects: [],
total: 0,
isStale: false,
time: new Date().toISOString(),
} satisfies NpmSearchResponse
export function useNpmSearch(
query: MaybeRefOrGetter<string>,
options: MaybeRefOrGetter<NpmSearchOptions> = {},
) {
const { $npmRegistry } = useNuxtApp()
const { searchProvider } = useSearchProvider()
const { search: searchAlgolia } = useAlgoliaSearch()
// Client-side cache
const cache = shallowRef<{
query: string
provider: SearchProvider
objects: NpmSearchResult[]
total: number
} | null>(null)
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
const asyncData = useLazyAsyncData(
() => `search:${searchProvider.value}:${toValue(query)}`,
async ({ $npmRegistry, $npmApi }, { signal }) => {
const q = toValue(query)
const provider = searchProvider.value
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 (but don't reset rate limit yet - only on success)
cache.value = null
// --- Algolia path (client-side only) ---
if (provider === 'algolia') {
const response = await searchAlgolia(q, {
size: opts.size ?? 25,
})
opts.onResponse?.({ query: q })
if (q !== toValue(query)) {
return emptySearchResponse
}
isRateLimited.value = false
cache.value = {
query: q,
provider,
objects: response.objects,
total: response.total,
}
return response
}
// --- npm registry path ---
const params = new URLSearchParams()
params.set('text', q)
params.set('size', String(opts.size ?? 25))
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,
}),
])
opts.onResponse?.({ query: q })
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,
provider,
objects: [result],
total: 1,
}
// Success - clear rate limit flag
isRateLimited.value = false
return {
objects: [result],
total: 1,
isStale,
time: new Date().toISOString(),
}
}
const { data: response, isStale } = await $npmRegistry<NpmSearchResponse>(
`/-/v1/search?${params.toString()}`,
{ signal },
60,
)
opts.onResponse?.({ query: q })
// If query changed/outdated, return empty search response
if (q !== toValue(query)) {
return emptySearchResponse
}
cache.value = {
query: q,
provider,
objects: response.objects,
total: response.total,
}
// Success - clear rate limit flag
isRateLimited.value = false
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')
if (isRateLimitError) {
isRateLimited.value = true
return emptySearchResponse
}
throw error
}
},
{ default: () => lastSearch || emptySearchResponse },
)
// Fetch more results incrementally
async function fetchMore(targetSize: number): Promise<void> {
const q = toValue(query).trim()
const provider = searchProvider.value
if (!q) {
cache.value = null
return
}
// If query or provider changed, reset cache
if (cache.value && (cache.value.query !== q || cache.value.provider !== provider)) {
cache.value = null
await asyncData.refresh()
return
}
const currentCount = cache.value?.objects.length ?? 0
const total = cache.value?.total ?? Infinity
// Already have enough or no more to fetch
if (currentCount >= targetSize || currentCount >= total) {
return
}
isLoadingMore.value = true
try {
const from = currentCount
const size = Math.min(targetSize - currentCount, total - currentCount)
if (provider === 'algolia') {
// Algolia incremental fetch
const response = await searchAlgolia(q, { size, from })
if (cache.value && cache.value.query === q && cache.value.provider === provider) {
const existingNames = new Set(cache.value.objects.map(obj => obj.package.name))
const newObjects = response.objects.filter(obj => !existingNames.has(obj.package.name))
cache.value = {
query: q,
provider,
objects: [...cache.value.objects, ...newObjects],
total: response.total,
}
} else {
cache.value = {
query: q,
provider,
objects: response.objects,
total: response.total,
}
}
} else {
// npm registry incremental fetch
const params = new URLSearchParams()
params.set('text', q)
params.set('size', String(size))
params.set('from', String(from))
const { data: response } = await $npmRegistry<NpmSearchResponse>(
`/-/v1/search?${params.toString()}`,
{},
60,
)
if (cache.value && cache.value.query === q && cache.value.provider === provider) {
const existingNames = new Set(cache.value.objects.map(obj => obj.package.name))
const newObjects = response.objects.filter(obj => !existingNames.has(obj.package.name))
cache.value = {
query: q,
provider,
objects: [...cache.value.objects, ...newObjects],
total: response.total,
}
} else {
cache.value = {
query: q,
provider,
objects: response.objects,
total: response.total,
}
}
}
// If we still need more, fetch again recursively
if (
cache.value &&
cache.value.objects.length < targetSize &&
cache.value.objects.length < cache.value.total
) {
await fetchMore(targetSize)
}
} finally {
isLoadingMore.value = false
}
}
// Watch for size increases
watch(
() => toValue(options).size,
async (newSize, oldSize) => {
if (!newSize) return
if (oldSize && newSize > oldSize && toValue(query).trim()) {
await fetchMore(newSize)
}
},
)
// Re-search when provider changes
watch(searchProvider, async () => {
cache.value = null
await asyncData.refresh()
const targetSize = toValue(options).size
if (targetSize) {
await fetchMore(targetSize)
}
})
// Computed data that uses cache
const data = computed<NpmSearchResponse | null>(() => {
if (cache.value) {
return {
isStale: false,
objects: cache.value.objects,
total: cache.value.total,
time: new Date().toISOString(),
}
}
return asyncData.data.value
})
if (import.meta.client && asyncData.data.value?.isStale) {
onMounted(() => {
asyncData.refresh()
})
}
// Whether there are more results available
const hasMore = computed(() => {
if (!cache.value) return true
return cache.value.objects.length < cache.value.total
})
return {
...asyncData,
/** Reactive search results (uses cache in incremental mode) */
data,
/** Whether currently loading more results */
isLoadingMore,
/** Whether there are more results available */
hasMore,
/** Manually fetch more results up to target size */
fetchMore,
/** Whether the search was rate limited by npm (429 error) */
isRateLimited: readonly(isRateLimited),
}
}