-
-
Notifications
You must be signed in to change notification settings - Fork 424
Expand file tree
/
Copy pathsearch-utils.ts
More file actions
58 lines (50 loc) · 1.8 KB
/
search-utils.ts
File metadata and controls
58 lines (50 loc) · 1.8 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
import type { NpmSearchResult, PackageMetaResponse, SearchResponse } from '#shared/types'
export function metaToSearchResult(meta: PackageMetaResponse): NpmSearchResult {
return {
package: {
name: meta.name,
version: meta.version,
description: meta.description,
keywords: meta.keywords,
license: meta.license,
date: meta.date,
links: meta.links,
author: meta.author,
maintainers: meta.maintainers,
},
score: { final: 0, detail: { quality: 0, popularity: 0, maintenance: 0 } },
searchScore: 0,
downloads: meta.weeklyDownloads !== undefined ? { weekly: meta.weeklyDownloads } : undefined,
updated: meta.date,
}
}
export function emptySearchResponse(): SearchResponse {
return {
objects: [],
totalUnlimited: 0,
total: 0,
isStale: false,
time: new Date().toISOString(),
}
}
export type SuggestionIntent = 'user' | 'org' | 'both' | null
export function isValidNpmName(name: string): boolean {
if (!name || name.length === 0 || name.length > 214) return false
if (!/^[a-z0-9]/i.test(name)) return false
return /^[\w-]+$/.test(name)
}
/** Parse a search query into a suggestion intent (`~user`, `@org`, or plain `both`). */
export function parseSuggestionIntent(query: string): { intent: SuggestionIntent; name: string } {
const q = query.trim()
if (!q) return { intent: null, name: '' }
if (q.startsWith('~')) {
const name = q.slice(1)
return isValidNpmName(name) ? { intent: 'user', name } : { intent: null, name: '' }
}
if (q.startsWith('@')) {
if (q.includes('/')) return { intent: null, name: '' }
const name = q.slice(1)
return isValidNpmName(name) ? { intent: 'org', name } : { intent: null, name: '' }
}
return isValidNpmName(q) ? { intent: 'both', name: q } : { intent: null, name: '' }
}