Skip to content

Commit 981df8c

Browse files
committed
feat: add OpenSearch support
Add OpenSearch support so browsers can use npmx.dev as a search engine. - Add OpenSearch description XML file at /public/opensearch.xml - Add autodiscovery link tag to HTML head - Add search suggestions API endpoint for browser autocomplete
1 parent 5f2316a commit 981df8c

3 files changed

Lines changed: 45 additions & 0 deletions

File tree

nuxt.config.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,14 @@ export default defineNuxtConfig({
2222
app: {
2323
head: {
2424
htmlAttrs: { lang: 'en' },
25+
link: [
26+
{
27+
rel: 'search',
28+
type: 'application/opensearchdescription+xml',
29+
title: 'npm',
30+
href: '/opensearch.xml',
31+
},
32+
],
2533
},
2634
},
2735

public/opensearch.xml

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/">
3+
<ShortName>npm</ShortName>
4+
<Description>Search npm packages on npmx.dev</Description>
5+
<InputEncoding>UTF-8</InputEncoding>
6+
<Image width="16" height="16" type="image/svg+xml">https://npmx.dev/favicon.svg</Image>
7+
<Url type="text/html" template="https://npmx.dev/search?q={searchTerms}"/>
8+
<Url type="application/x-suggestions+json" template="https://npmx.dev/api/opensearch/suggestions?q={searchTerms}"/>
9+
<Url type="application/opensearchdescription+xml" rel="self" template="https://npmx.dev/opensearch.xml"/>
10+
</OpenSearchDescription>
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import type { NpmSearchResponse } from '#shared/types'
2+
import { NPM_REGISTRY } from '#shared/utils/constants'
3+
4+
export default defineCachedEventHandler(
5+
async event => {
6+
const query = getQuery(event)
7+
const q = String(query.q || '').trim()
8+
9+
if (!q) {
10+
return [q, []]
11+
}
12+
13+
const params = new URLSearchParams({ text: q, size: '10' })
14+
const response = await $fetch<NpmSearchResponse>(`${NPM_REGISTRY}/-/v1/search?${params}`)
15+
16+
const suggestions = response.objects.map(obj => obj.package.name)
17+
return [q, suggestions]
18+
},
19+
{
20+
maxAge: 60,
21+
swr: true,
22+
getKey: event => {
23+
const query = getQuery(event)
24+
return `opensearch-suggestions:${query.q || ''}`
25+
},
26+
},
27+
)

0 commit comments

Comments
 (0)