@foundrykit/search-plugin 0.3.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +100 -0
- package/dist/components/useSiteSearch.d.ts +21 -0
- package/dist/components/useSiteSearch.js +49 -0
- package/dist/components/useSiteSearch.js.map +1 -0
- package/dist/endpoints/handlers.d.ts +8 -0
- package/dist/endpoints/handlers.js +12 -0
- package/dist/endpoints/handlers.js.map +1 -1
- package/dist/exports/client.d.ts +4 -0
- package/dist/exports/client.js +2 -0
- package/dist/exports/client.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +29 -2
- package/dist/index.js.map +1 -1
- package/dist/project.d.ts +4 -16
- package/dist/project.js +12 -2
- package/dist/project.js.map +1 -1
- package/dist/rank.d.ts +15 -8
- package/dist/rank.js +27 -4
- package/dist/rank.js.map +1 -1
- package/dist/resolve.d.ts +12 -1
- package/dist/resolve.js +51 -8
- package/dist/resolve.js.map +1 -1
- package/dist/searchClient.d.ts +40 -0
- package/dist/searchClient.js +61 -0
- package/dist/searchClient.js.map +1 -0
- package/dist/types.d.ts +58 -0
- package/dist/types.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -79,6 +79,7 @@ export default buildConfig({
|
|
|
79
79
|
| Method | Path | Purpose |
|
|
80
80
|
| ------ | -------------------------- | ------------------------------------------------------------------- |
|
|
81
81
|
| `GET` | `/api/site-search?q=` | Grouped, ranked results. Empty `q` returns the preset. |
|
|
82
|
+
| `GET` | `/api/site-search/results` | Flat, ranked, paginated: `?q=&collection=&page=&limit=`. |
|
|
82
83
|
| `POST` | `/api/site-search/reindex` | Rebuild the projection now. Returns counts. |
|
|
83
84
|
| `GET` | `/api/site-search/inspect` | What is indexed, and why anything missing was skipped. |
|
|
84
85
|
| `POST` | `/api/site-search/track` | Record a settled search and its clicks. Only when analytics are on. |
|
|
@@ -99,9 +100,73 @@ you set `requireAdminForOperations: false`.
|
|
|
99
100
|
| `analytics` | `false` | `true`, or `{ retentionDays, collectionSlug }`. |
|
|
100
101
|
| `rateLimit` | `{ limit: 30, window: 60 }` | Per-IP limit on the public track endpoint. `false` disables it. |
|
|
101
102
|
| `requireAdminForOperations` | `true` | Guard reindex and inspect. |
|
|
103
|
+
| `indexCollection` | `search` | plugin-search's collection slug, if you renamed it. |
|
|
102
104
|
| `routePrefix` | `/site-search` | Base path for endpoints. |
|
|
103
105
|
| `disabled` | `false` | Bypass the plugin entirely. |
|
|
104
106
|
|
|
107
|
+
### Per-collection options
|
|
108
|
+
|
|
109
|
+
| Option | Notes |
|
|
110
|
+
| -------------- | ------------------------------------------------------------------------------------------- |
|
|
111
|
+
| `slug` | Required. The source collection. |
|
|
112
|
+
| `group` | Required. A configured group's slug. |
|
|
113
|
+
| `path` | Required. URL prefix; `''` for the site root. |
|
|
114
|
+
| `weight` | Ranking multiplier. Default `1`. |
|
|
115
|
+
| `icon` | Opaque token passed through to your icon map. |
|
|
116
|
+
| `excludeSlugs` | Slugs never returned. |
|
|
117
|
+
| `excludeField` | A checkbox on the source collection (e.g. `excludeFromSearch`) that hides a document. |
|
|
118
|
+
| `href` | `(row) => string` for URLs `path` + slug can't express. Gets the raw index row (see below). |
|
|
119
|
+
|
|
120
|
+
`excludeField` is read once per projection build, so it costs nothing per request. Toggling it saves
|
|
121
|
+
the document, plugin-search re-syncs the row, and the plugin drops its cache, so the change shows
|
|
122
|
+
straight away.
|
|
123
|
+
|
|
124
|
+
For nested URLs (`/destinations/asia/indonesia/bali`), add the URL to the index row with
|
|
125
|
+
plugin-search's `beforeSync` and a field in `searchOverrides`, then read it back:
|
|
126
|
+
|
|
127
|
+
```ts
|
|
128
|
+
{ slug: 'regions', group: 'destinations', path: '/regions', href: row => row.url as string }
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
### Results
|
|
132
|
+
|
|
133
|
+
Each result carries `id`, `docId` (the source document's ID), `collection`, `group`, `title`,
|
|
134
|
+
`description`, `href`, `icon`, `score` and `highlights`: the matched `[start, end)` ranges in
|
|
135
|
+
`title`, for bolding the match.
|
|
136
|
+
|
|
137
|
+
### Flat results and filtered archives
|
|
138
|
+
|
|
139
|
+
`GET /api/site-search/results` (or `service.query()`) returns every match ranked and paginated,
|
|
140
|
+
ignoring group caps: `{ docs, totalDocs, page, totalPages, limit }`. A listing with its own filters
|
|
141
|
+
can use it for fuzzy, ranked matching instead of `title: { contains: q }`:
|
|
142
|
+
|
|
143
|
+
```ts
|
|
144
|
+
const service = createSearchService({
|
|
145
|
+
cache: searchIndexCache,
|
|
146
|
+
config,
|
|
147
|
+
payload,
|
|
148
|
+
});
|
|
149
|
+
const { docs } = await service.query({
|
|
150
|
+
q,
|
|
151
|
+
collections: ['hotels'],
|
|
152
|
+
limit: 100,
|
|
153
|
+
});
|
|
154
|
+
const ids = docs.map(d => d.docId);
|
|
155
|
+
const hotels = await payload.find({
|
|
156
|
+
collection: 'hotels',
|
|
157
|
+
where: { and: [{ id: { in: ids } }, ...filters] },
|
|
158
|
+
pagination: false,
|
|
159
|
+
});
|
|
160
|
+
// Restore relevance order: hotels.docs.sort((a, b) => ids.indexOf(String(a.id)) - ids.indexOf(String(b.id)))
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
### Caching
|
|
164
|
+
|
|
165
|
+
The projection is cached in memory for `cacheTTL` and dropped whenever plugin-search writes the
|
|
166
|
+
index, so a published change shows up straight away (on the instance that handled the write; others
|
|
167
|
+
wait out the TTL). The cache is one per process: give every `createSearchService` call the same
|
|
168
|
+
config as the plugin, or they will overwrite each other's projection.
|
|
169
|
+
|
|
105
170
|
### A note on `minMatchCharLength`
|
|
106
171
|
|
|
107
172
|
The default of `3` is deliberate. Two-character fragments match too much to be useful, and that is
|
|
@@ -135,6 +200,41 @@ useSearchHotkey(open); // Cmd+K / Ctrl+K
|
|
|
135
200
|
The hotkey is suppressed inside inputs, textareas, selects and contenteditable. That guard matters:
|
|
136
201
|
`Ctrl+K` is Lexical's "insert link" binding, and Lexical is Payload's own editor.
|
|
137
202
|
|
|
203
|
+
### Headless search hook
|
|
204
|
+
|
|
205
|
+
```tsx
|
|
206
|
+
'use client';
|
|
207
|
+
import { useSiteSearch } from '@foundrykit/search-plugin/client';
|
|
208
|
+
|
|
209
|
+
const { query, setQuery, results, resultsQuery, loading, error } =
|
|
210
|
+
useSiteSearch();
|
|
211
|
+
// results: GroupedResults for `resultsQuery`; `loading` until it catches up with `query`.
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
It debounces (250ms), aborts the request a newer keystroke supersedes, and ignores any response
|
|
215
|
+
that arrives late, so an older term's results never overwrite a newer one's. Options: `endpoint`,
|
|
216
|
+
`debounceMs`, `initialQuery`, or `fetcher(q, signal)` to call your own route. Outside React,
|
|
217
|
+
`createSearchRunner` does the same, and `fetchSiteSearch(q, { endpoint, signal })` is the bare request.
|
|
218
|
+
|
|
219
|
+
### With the advanced search bar
|
|
220
|
+
|
|
221
|
+
`@foundrykit/components`' advanced search bar (via `@foundrykit/hooks`' `useAdvancedSearch`) takes
|
|
222
|
+
`onSearch(query) => SearchResult[]`. `flattenResults` turns grouped results into that shape, with the
|
|
223
|
+
group label as `category` and `collection`, `docId`, `icon` and `highlights` in `metadata`:
|
|
224
|
+
|
|
225
|
+
```tsx
|
|
226
|
+
import {
|
|
227
|
+
fetchSiteSearch,
|
|
228
|
+
flattenResults,
|
|
229
|
+
} from '@foundrykit/search-plugin/client';
|
|
230
|
+
|
|
231
|
+
<AdvancedSearchProvider
|
|
232
|
+
onSearch={async q => flattenResults(await fetchSiteSearch(q), groups)}
|
|
233
|
+
/>;
|
|
234
|
+
```
|
|
235
|
+
|
|
236
|
+
Pass the same `groups` you gave the plugin to keep its order and labels.
|
|
237
|
+
|
|
138
238
|
## Analytics and privacy
|
|
139
239
|
|
|
140
240
|
With `analytics` on, the `search-events` collection records **one row per settled search**: the
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { GroupedResults } from '../types.js';
|
|
2
|
+
export type UseSiteSearchOptions<T> = {
|
|
3
|
+
debounceMs?: number;
|
|
4
|
+
/** Default `/api/site-search`. Point it at your own route if you wrap the plugin. */
|
|
5
|
+
endpoint?: string;
|
|
6
|
+
/** Replace the request entirely, e.g. to hit `/results` or add params. */
|
|
7
|
+
fetcher?: (q: string, signal: AbortSignal) => Promise<T>;
|
|
8
|
+
initialQuery?: string;
|
|
9
|
+
};
|
|
10
|
+
/**
|
|
11
|
+
* Headless site search: holds the query, fetches on a debounce, drops stale responses.
|
|
12
|
+
* `resultsQuery` is the term `results` belong to; until it equals `query` they are an older term's.
|
|
13
|
+
*/
|
|
14
|
+
export declare function useSiteSearch<T = GroupedResults>({ debounceMs, endpoint, fetcher, initialQuery, }?: UseSiteSearchOptions<T>): {
|
|
15
|
+
error: unknown;
|
|
16
|
+
loading: boolean;
|
|
17
|
+
query: string;
|
|
18
|
+
results: T | null;
|
|
19
|
+
resultsQuery: string | null;
|
|
20
|
+
setQuery: import("react").Dispatch<import("react").SetStateAction<string>>;
|
|
21
|
+
};
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
import { useEffect, useRef, useState } from 'react';
|
|
3
|
+
import { createSearchRunner, fetchSiteSearch } from '../searchClient.js';
|
|
4
|
+
/**
|
|
5
|
+
* Headless site search: holds the query, fetches on a debounce, drops stale responses.
|
|
6
|
+
* `resultsQuery` is the term `results` belong to; until it equals `query` they are an older term's.
|
|
7
|
+
*/ export function useSiteSearch({ debounceMs = 250, endpoint, fetcher, initialQuery = '' } = {}) {
|
|
8
|
+
const [query, setQuery] = useState(initialQuery);
|
|
9
|
+
const [results, setResults] = useState(null);
|
|
10
|
+
const [resultsQuery, setResultsQuery] = useState(null);
|
|
11
|
+
const [error, setError] = useState(null);
|
|
12
|
+
const fetcherRef = useRef(fetcher);
|
|
13
|
+
fetcherRef.current = fetcher;
|
|
14
|
+
const [runner] = useState(()=>createSearchRunner({
|
|
15
|
+
debounceMs,
|
|
16
|
+
fetcher: (q, signal)=>fetcherRef.current?.(q, signal) ?? fetchSiteSearch(q, {
|
|
17
|
+
endpoint,
|
|
18
|
+
signal
|
|
19
|
+
}),
|
|
20
|
+
onError: (err, q)=>{
|
|
21
|
+
setError(err);
|
|
22
|
+
setResultsQuery(q);
|
|
23
|
+
},
|
|
24
|
+
onResult: (data, q)=>{
|
|
25
|
+
setError(null);
|
|
26
|
+
setResults(data);
|
|
27
|
+
setResultsQuery(q);
|
|
28
|
+
}
|
|
29
|
+
}));
|
|
30
|
+
useEffect(()=>{
|
|
31
|
+
runner.run(query);
|
|
32
|
+
}, [
|
|
33
|
+
query,
|
|
34
|
+
runner
|
|
35
|
+
]);
|
|
36
|
+
useEffect(()=>runner.cancel, [
|
|
37
|
+
runner
|
|
38
|
+
]);
|
|
39
|
+
return {
|
|
40
|
+
error,
|
|
41
|
+
loading: resultsQuery !== query,
|
|
42
|
+
query,
|
|
43
|
+
results,
|
|
44
|
+
resultsQuery,
|
|
45
|
+
setQuery
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
//# sourceMappingURL=useSiteSearch.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/components/useSiteSearch.ts"],"sourcesContent":["'use client';\n\nimport { useEffect, useRef, useState } from 'react';\n\nimport { createSearchRunner, fetchSiteSearch } from '../searchClient.js';\nimport type { GroupedResults } from '../types.js';\n\nexport type UseSiteSearchOptions<T> = {\n debounceMs?: number;\n /** Default `/api/site-search`. Point it at your own route if you wrap the plugin. */\n endpoint?: string;\n /** Replace the request entirely, e.g. to hit `/results` or add params. */\n fetcher?: (q: string, signal: AbortSignal) => Promise<T>;\n initialQuery?: string;\n};\n\n/**\n * Headless site search: holds the query, fetches on a debounce, drops stale responses.\n * `resultsQuery` is the term `results` belong to; until it equals `query` they are an older term's.\n */\nexport function useSiteSearch<T = GroupedResults>({\n debounceMs = 250,\n endpoint,\n fetcher,\n initialQuery = '',\n}: UseSiteSearchOptions<T> = {}) {\n const [query, setQuery] = useState(initialQuery);\n const [results, setResults] = useState<null | T>(null);\n const [resultsQuery, setResultsQuery] = useState<null | string>(null);\n const [error, setError] = useState<unknown>(null);\n const fetcherRef = useRef(fetcher);\n fetcherRef.current = fetcher;\n\n const [runner] = useState(() =>\n createSearchRunner<T>({\n debounceMs,\n fetcher: (q, signal) =>\n fetcherRef.current?.(q, signal) ??\n fetchSiteSearch<T>(q, { endpoint, signal }),\n onError: (err, q) => {\n setError(err);\n setResultsQuery(q);\n },\n onResult: (data, q) => {\n setError(null);\n setResults(data);\n setResultsQuery(q);\n },\n })\n );\n\n useEffect(() => {\n runner.run(query);\n }, [query, runner]);\n useEffect(() => runner.cancel, [runner]);\n\n return {\n error,\n loading: resultsQuery !== query,\n query,\n results,\n resultsQuery,\n setQuery,\n };\n}\n"],"names":["useEffect","useRef","useState","createSearchRunner","fetchSiteSearch","useSiteSearch","debounceMs","endpoint","fetcher","initialQuery","query","setQuery","results","setResults","resultsQuery","setResultsQuery","error","setError","fetcherRef","current","runner","q","signal","onError","err","onResult","data","run","cancel","loading"],"mappings":"AAAA;AAEA,SAASA,SAAS,EAAEC,MAAM,EAAEC,QAAQ,QAAQ,QAAQ;AAEpD,SAASC,kBAAkB,EAAEC,eAAe,QAAQ,qBAAqB;AAYzE;;;CAGC,GACD,OAAO,SAASC,cAAkC,EAChDC,aAAa,GAAG,EAChBC,QAAQ,EACRC,OAAO,EACPC,eAAe,EAAE,EACO,GAAG,CAAC,CAAC;IAC7B,MAAM,CAACC,OAAOC,SAAS,GAAGT,SAASO;IACnC,MAAM,CAACG,SAASC,WAAW,GAAGX,SAAmB;IACjD,MAAM,CAACY,cAAcC,gBAAgB,GAAGb,SAAwB;IAChE,MAAM,CAACc,OAAOC,SAAS,GAAGf,SAAkB;IAC5C,MAAMgB,aAAajB,OAAOO;IAC1BU,WAAWC,OAAO,GAAGX;IAErB,MAAM,CAACY,OAAO,GAAGlB,SAAS,IACxBC,mBAAsB;YACpBG;YACAE,SAAS,CAACa,GAAGC,SACXJ,WAAWC,OAAO,GAAGE,GAAGC,WACxBlB,gBAAmBiB,GAAG;oBAAEd;oBAAUe;gBAAO;YAC3CC,SAAS,CAACC,KAAKH;gBACbJ,SAASO;gBACTT,gBAAgBM;YAClB;YACAI,UAAU,CAACC,MAAML;gBACfJ,SAAS;gBACTJ,WAAWa;gBACXX,gBAAgBM;YAClB;QACF;IAGFrB,UAAU;QACRoB,OAAOO,GAAG,CAACjB;IACb,GAAG;QAACA;QAAOU;KAAO;IAClBpB,UAAU,IAAMoB,OAAOQ,MAAM,EAAE;QAACR;KAAO;IAEvC,OAAO;QACLJ;QACAa,SAASf,iBAAiBJ;QAC1BA;QACAE;QACAE;QACAH;IACF;AACF"}
|
|
@@ -6,6 +6,14 @@ export declare const createSearchHandler: ({ cache, config, }: {
|
|
|
6
6
|
cache: SearchIndexCache;
|
|
7
7
|
config: SearchPluginConfig;
|
|
8
8
|
}) => PayloadHandler;
|
|
9
|
+
/**
|
|
10
|
+
* GET — flat, ranked, paginated results for `?q=&collection=&page=&limit=`. `collection` may
|
|
11
|
+
* repeat. For a full results page, where the grouped endpoint's caps get in the way.
|
|
12
|
+
*/
|
|
13
|
+
export declare const createResultsHandler: ({ cache, config, }: {
|
|
14
|
+
cache: SearchIndexCache;
|
|
15
|
+
config: SearchPluginConfig;
|
|
16
|
+
}) => PayloadHandler;
|
|
9
17
|
/** POST — rebuild the projection now. This is the editor-facing recovery path for a desync. */
|
|
10
18
|
export declare const createReindexHandler: ({ cache, config, requireAdmin, }: {
|
|
11
19
|
cache: SearchIndexCache;
|
|
@@ -20,6 +20,18 @@ const service = (req, cache, config)=>createSearchService({
|
|
|
20
20
|
const results = await service(req, cache, config).search(query);
|
|
21
21
|
return json(results);
|
|
22
22
|
};
|
|
23
|
+
/**
|
|
24
|
+
* GET — flat, ranked, paginated results for `?q=&collection=&page=&limit=`. `collection` may
|
|
25
|
+
* repeat. For a full results page, where the grouped endpoint's caps get in the way.
|
|
26
|
+
*/ export const createResultsHandler = ({ cache, config })=>async (req)=>{
|
|
27
|
+
const params = new URL(req.url ?? '', 'http://localhost').searchParams;
|
|
28
|
+
return json(await service(req, cache, config).query({
|
|
29
|
+
collections: params.getAll('collection'),
|
|
30
|
+
limit: Number(params.get('limit')) || undefined,
|
|
31
|
+
page: Number(params.get('page')) || undefined,
|
|
32
|
+
q: params.get('q') ?? ''
|
|
33
|
+
}));
|
|
34
|
+
};
|
|
23
35
|
/** POST — rebuild the projection now. This is the editor-facing recovery path for a desync. */ export const createReindexHandler = ({ cache, config, requireAdmin })=>async (req)=>{
|
|
24
36
|
if (requireAdmin && !req.user) {
|
|
25
37
|
return forbidden();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/endpoints/handlers.ts"],"sourcesContent":["import type { PayloadHandler, PayloadRequest } from 'payload';\n\nimport type { SearchIndexCache } from '../cache.js';\nimport { resolveAnalytics } from '../options.js';\nimport { createSearchService } from '../resolve.js';\nimport {\n deviceOf,\n isBot,\n parseTrackPayload,\n recordSearchEvent,\n} from '../track.js';\nimport type { SearchPluginConfig } from '../types.js';\n\nconst json = (body: unknown, status = 200): Response =>\n new Response(JSON.stringify(body), {\n headers: { 'Content-Type': 'application/json' },\n status,\n });\n\nconst forbidden = () => json({ error: 'Not permitted' }, 403);\n\nconst service = (\n req: PayloadRequest,\n cache: SearchIndexCache,\n config: SearchPluginConfig\n) => createSearchService({ cache, config, payload: req.payload });\n\n/** GET — grouped, ranked results for `?q=`. Records nothing: it runs per keystroke, so the track endpoint owns recording. */\nexport const createSearchHandler =\n ({\n cache,\n config,\n }: {\n cache: SearchIndexCache;\n config: SearchPluginConfig;\n }): PayloadHandler =>\n async req => {\n const query =\n new URL(req.url ?? '', 'http://localhost').searchParams.get('q') ?? '';\n const results = await service(req, cache, config).search(query);\n\n return json(results);\n };\n\n/** POST — rebuild the projection now. This is the editor-facing recovery path for a desync. */\nexport const createReindexHandler =\n ({\n cache,\n config,\n requireAdmin,\n }: {\n cache: SearchIndexCache;\n config: SearchPluginConfig;\n requireAdmin: boolean;\n }): PayloadHandler =>\n async req => {\n if (requireAdmin && !req.user) {\n return forbidden();\n }\n\n const stats = await service(req, cache, config).reindex();\n\n // Reported rather than silently succeeding: the point is for a non-developer to be able to\n // tell whether it worked.\n return json({\n message: `Reindexed ${stats.indexed} documents, ${stats.skipped} skipped.`,\n ...stats,\n });\n };\n\n/** GET — what is searchable, and why anything missing was left out. */\nexport const createInspectHandler =\n ({\n cache,\n config,\n requireAdmin,\n }: {\n cache: SearchIndexCache;\n config: SearchPluginConfig;\n requireAdmin: boolean;\n }): PayloadHandler =>\n async req => {\n if (requireAdmin && !req.user) {\n return forbidden();\n }\n\n return json(await service(req, cache, config).inspect());\n };\n\n/** POST — attribute a click to a query, so click-through is measurable. */\nexport const createTrackHandler =\n ({ config }: { config: SearchPluginConfig }): PayloadHandler =>\n async req => {\n const analytics = resolveAnalytics(config.analytics);\n if (!analytics.enabled || !(await analytics.isEnabled(req))) {\n return json({ tracked: false });\n }\n\n const userAgent = req.headers.get('user-agent') ?? '';\n if (req.user || isBot(userAgent)) {\n return json({ tracked: false });\n }\n\n const event = parseTrackPayload(await req.json?.().catch(() => null));\n if (!event) {\n return json({ error: 'Invalid payload' }, 400);\n }\n\n const cookieName = analytics.visitorCookie;\n const visitorId = cookieName\n ? req.headers\n .get('cookie')\n ?.split(';')\n .map(c => c.trim().split('='))\n .find(([name]) => name === cookieName)?.[1]\n ?.slice(0, 100)\n : undefined;\n\n // Same-site referrers say nothing about acquisition; keep external hosts only.\n const host = (req.headers.get('host') ?? '').split(':')[0];\n if (event.referrer === host) {\n event.referrer = undefined;\n }\n\n try {\n await recordSearchEvent({\n collectionSlug: analytics.collectionSlug,\n device: deviceOf(userAgent),\n event,\n payload: req.payload,\n req,\n retentionDays: analytics.retentionDays,\n visitorId,\n });\n } catch (error) {\n req.payload.logger.error({\n err: error,\n msg: 'search-plugin: failed to record search event',\n });\n }\n\n return json({ tracked: true });\n };\n"],"names":["resolveAnalytics","createSearchService","deviceOf","isBot","parseTrackPayload","recordSearchEvent","json","body","status","Response","JSON","stringify","headers","forbidden","error","service","req","cache","config","payload","createSearchHandler","query","URL","url","searchParams","get","results","search","createReindexHandler","requireAdmin","user","stats","reindex","message","indexed","skipped","createInspectHandler","inspect","createTrackHandler","analytics","enabled","isEnabled","tracked","userAgent","event","catch","cookieName","visitorCookie","visitorId","split","map","c","trim","find","name","slice","
|
|
1
|
+
{"version":3,"sources":["../../src/endpoints/handlers.ts"],"sourcesContent":["import type { PayloadHandler, PayloadRequest } from 'payload';\n\nimport type { SearchIndexCache } from '../cache.js';\nimport { resolveAnalytics } from '../options.js';\nimport { createSearchService } from '../resolve.js';\nimport {\n deviceOf,\n isBot,\n parseTrackPayload,\n recordSearchEvent,\n} from '../track.js';\nimport type { SearchPluginConfig } from '../types.js';\n\nconst json = (body: unknown, status = 200): Response =>\n new Response(JSON.stringify(body), {\n headers: { 'Content-Type': 'application/json' },\n status,\n });\n\nconst forbidden = () => json({ error: 'Not permitted' }, 403);\n\nconst service = (\n req: PayloadRequest,\n cache: SearchIndexCache,\n config: SearchPluginConfig\n) => createSearchService({ cache, config, payload: req.payload });\n\n/** GET — grouped, ranked results for `?q=`. Records nothing: it runs per keystroke, so the track endpoint owns recording. */\nexport const createSearchHandler =\n ({\n cache,\n config,\n }: {\n cache: SearchIndexCache;\n config: SearchPluginConfig;\n }): PayloadHandler =>\n async req => {\n const query =\n new URL(req.url ?? '', 'http://localhost').searchParams.get('q') ?? '';\n const results = await service(req, cache, config).search(query);\n\n return json(results);\n };\n\n/**\n * GET — flat, ranked, paginated results for `?q=&collection=&page=&limit=`. `collection` may\n * repeat. For a full results page, where the grouped endpoint's caps get in the way.\n */\nexport const createResultsHandler =\n ({\n cache,\n config,\n }: {\n cache: SearchIndexCache;\n config: SearchPluginConfig;\n }): PayloadHandler =>\n async req => {\n const params = new URL(req.url ?? '', 'http://localhost').searchParams;\n return json(\n await service(req, cache, config).query({\n collections: params.getAll('collection'),\n limit: Number(params.get('limit')) || undefined,\n page: Number(params.get('page')) || undefined,\n q: params.get('q') ?? '',\n })\n );\n };\n\n/** POST — rebuild the projection now. This is the editor-facing recovery path for a desync. */\nexport const createReindexHandler =\n ({\n cache,\n config,\n requireAdmin,\n }: {\n cache: SearchIndexCache;\n config: SearchPluginConfig;\n requireAdmin: boolean;\n }): PayloadHandler =>\n async req => {\n if (requireAdmin && !req.user) {\n return forbidden();\n }\n\n const stats = await service(req, cache, config).reindex();\n\n // Reported rather than silently succeeding: the point is for a non-developer to be able to\n // tell whether it worked.\n return json({\n message: `Reindexed ${stats.indexed} documents, ${stats.skipped} skipped.`,\n ...stats,\n });\n };\n\n/** GET — what is searchable, and why anything missing was left out. */\nexport const createInspectHandler =\n ({\n cache,\n config,\n requireAdmin,\n }: {\n cache: SearchIndexCache;\n config: SearchPluginConfig;\n requireAdmin: boolean;\n }): PayloadHandler =>\n async req => {\n if (requireAdmin && !req.user) {\n return forbidden();\n }\n\n return json(await service(req, cache, config).inspect());\n };\n\n/** POST — attribute a click to a query, so click-through is measurable. */\nexport const createTrackHandler =\n ({ config }: { config: SearchPluginConfig }): PayloadHandler =>\n async req => {\n const analytics = resolveAnalytics(config.analytics);\n if (!analytics.enabled || !(await analytics.isEnabled(req))) {\n return json({ tracked: false });\n }\n\n const userAgent = req.headers.get('user-agent') ?? '';\n if (req.user || isBot(userAgent)) {\n return json({ tracked: false });\n }\n\n const event = parseTrackPayload(await req.json?.().catch(() => null));\n if (!event) {\n return json({ error: 'Invalid payload' }, 400);\n }\n\n const cookieName = analytics.visitorCookie;\n const visitorId = cookieName\n ? req.headers\n .get('cookie')\n ?.split(';')\n .map(c => c.trim().split('='))\n .find(([name]) => name === cookieName)?.[1]\n ?.slice(0, 100)\n : undefined;\n\n // Same-site referrers say nothing about acquisition; keep external hosts only.\n const host = (req.headers.get('host') ?? '').split(':')[0];\n if (event.referrer === host) {\n event.referrer = undefined;\n }\n\n try {\n await recordSearchEvent({\n collectionSlug: analytics.collectionSlug,\n device: deviceOf(userAgent),\n event,\n payload: req.payload,\n req,\n retentionDays: analytics.retentionDays,\n visitorId,\n });\n } catch (error) {\n req.payload.logger.error({\n err: error,\n msg: 'search-plugin: failed to record search event',\n });\n }\n\n return json({ tracked: true });\n };\n"],"names":["resolveAnalytics","createSearchService","deviceOf","isBot","parseTrackPayload","recordSearchEvent","json","body","status","Response","JSON","stringify","headers","forbidden","error","service","req","cache","config","payload","createSearchHandler","query","URL","url","searchParams","get","results","search","createResultsHandler","params","collections","getAll","limit","Number","undefined","page","q","createReindexHandler","requireAdmin","user","stats","reindex","message","indexed","skipped","createInspectHandler","inspect","createTrackHandler","analytics","enabled","isEnabled","tracked","userAgent","event","catch","cookieName","visitorCookie","visitorId","split","map","c","trim","find","name","slice","host","referrer","collectionSlug","device","retentionDays","logger","err","msg"],"mappings":"AAGA,SAASA,gBAAgB,QAAQ,gBAAgB;AACjD,SAASC,mBAAmB,QAAQ,gBAAgB;AACpD,SACEC,QAAQ,EACRC,KAAK,EACLC,iBAAiB,EACjBC,iBAAiB,QACZ,cAAc;AAGrB,MAAMC,OAAO,CAACC,MAAeC,SAAS,GAAG,GACvC,IAAIC,SAASC,KAAKC,SAAS,CAACJ,OAAO;QACjCK,SAAS;YAAE,gBAAgB;QAAmB;QAC9CJ;IACF;AAEF,MAAMK,YAAY,IAAMP,KAAK;QAAEQ,OAAO;IAAgB,GAAG;AAEzD,MAAMC,UAAU,CACdC,KACAC,OACAC,SACGjB,oBAAoB;QAAEgB;QAAOC;QAAQC,SAASH,IAAIG,OAAO;IAAC;AAE/D,2HAA2H,GAC3H,OAAO,MAAMC,sBACX,CAAC,EACCH,KAAK,EACLC,MAAM,EAIP,GACD,OAAMF;QACJ,MAAMK,QACJ,IAAIC,IAAIN,IAAIO,GAAG,IAAI,IAAI,oBAAoBC,YAAY,CAACC,GAAG,CAAC,QAAQ;QACtE,MAAMC,UAAU,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mD,MAAM,CAACxD,KAAK,CAAC;gBACvByD,KAAKzD;gBACL0D,KAAK;YACP;QACF;QAEA,OAAOlE,KAAK;YAAE6C,SAAS;QAAK;IAC9B,EAAE"}
|
package/dist/exports/client.d.ts
CHANGED
|
@@ -1,3 +1,7 @@
|
|
|
1
1
|
export { isEditableTarget, useIsAppleDevice, useSearchHotkey, } from '../components/useSearchHotkey.js';
|
|
2
|
+
export type { UseSiteSearchOptions } from '../components/useSiteSearch.js';
|
|
3
|
+
export { useSiteSearch } from '../components/useSiteSearch.js';
|
|
4
|
+
export type { FlatSearchResult } from '../searchClient.js';
|
|
5
|
+
export { createSearchRunner, fetchSiteSearch, flattenResults, } from '../searchClient.js';
|
|
2
6
|
export type { ShownResult, TrackPayload } from '../track.js';
|
|
3
7
|
export { trackSearchEvent } from '../trackClient.js';
|
package/dist/exports/client.js
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
export { isEditableTarget, useIsAppleDevice, useSearchHotkey } from '../components/useSearchHotkey.js';
|
|
2
|
+
export { useSiteSearch } from '../components/useSiteSearch.js';
|
|
3
|
+
export { createSearchRunner, fetchSiteSearch, flattenResults } from '../searchClient.js';
|
|
2
4
|
export { trackSearchEvent } from '../trackClient.js';
|
|
3
5
|
|
|
4
6
|
//# sourceMappingURL=client.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/exports/client.ts"],"sourcesContent":["export {\n isEditableTarget,\n useIsAppleDevice,\n useSearchHotkey,\n} from '../components/useSearchHotkey.js';\nexport type { ShownResult, TrackPayload } from '../track.js';\nexport { trackSearchEvent } from '../trackClient.js';\n"],"names":["isEditableTarget","useIsAppleDevice","useSearchHotkey","trackSearchEvent"],"mappings":"AAAA,SACEA,gBAAgB,EAChBC,gBAAgB,EAChBC,eAAe,QACV,mCAAmC;AAE1C,SAASC,gBAAgB,QAAQ,oBAAoB"}
|
|
1
|
+
{"version":3,"sources":["../../src/exports/client.ts"],"sourcesContent":["export {\n isEditableTarget,\n useIsAppleDevice,\n useSearchHotkey,\n} from '../components/useSearchHotkey.js';\nexport type { UseSiteSearchOptions } from '../components/useSiteSearch.js';\nexport { useSiteSearch } from '../components/useSiteSearch.js';\nexport type { FlatSearchResult } from '../searchClient.js';\nexport {\n createSearchRunner,\n fetchSiteSearch,\n flattenResults,\n} from '../searchClient.js';\nexport type { ShownResult, TrackPayload } from '../track.js';\nexport { trackSearchEvent } from '../trackClient.js';\n"],"names":["isEditableTarget","useIsAppleDevice","useSearchHotkey","useSiteSearch","createSearchRunner","fetchSiteSearch","flattenResults","trackSearchEvent"],"mappings":"AAAA,SACEA,gBAAgB,EAChBC,gBAAgB,EAChBC,eAAe,QACV,mCAAmC;AAE1C,SAASC,aAAa,QAAQ,iCAAiC;AAE/D,SACEC,kBAAkB,EAClBC,eAAe,EACfC,cAAc,QACT,qBAAqB;AAE5B,SAASC,gBAAgB,QAAQ,oBAAoB"}
|
package/dist/index.d.ts
CHANGED
|
@@ -5,7 +5,7 @@ export { SearchIndexCache, searchIndexCache } from './cache.js';
|
|
|
5
5
|
export { decodeEntities } from './decodeEntities.js';
|
|
6
6
|
export { hrefFor, projectDocs } from './project.js';
|
|
7
7
|
export { DEFAULT_FIELDS, DEFAULT_FUZZY, groupResults, presetResults, rankDocs, } from './rank.js';
|
|
8
|
-
export { createSearchService } from './resolve.js';
|
|
8
|
+
export { createSearchService, DEFAULT_INDEX_COLLECTION, } from './resolve.js';
|
|
9
9
|
export type { ShownResult, TrackPayload } from './track.js';
|
|
10
10
|
export { deviceOf, isBot, parseTrackPayload, recordSearchEvent, } from './track.js';
|
|
11
11
|
export type * from './types.js';
|
package/dist/index.js
CHANGED
|
@@ -2,14 +2,15 @@ import { withRateLimit } from '@foundrykit/rate-limit';
|
|
|
2
2
|
import { recordActivePlugin } from './activePlugins.js';
|
|
3
3
|
import { searchIndexCache } from './cache.js';
|
|
4
4
|
import { createSearchEventsCollection } from './collections/SearchEvents.js';
|
|
5
|
-
import { createInspectHandler, createReindexHandler, createSearchHandler, createTrackHandler } from './endpoints/handlers.js';
|
|
5
|
+
import { createInspectHandler, createReindexHandler, createResultsHandler, createSearchHandler, createTrackHandler } from './endpoints/handlers.js';
|
|
6
6
|
import { assertConfig, DEFAULT_TRACK_RATE_LIMIT, resolveAnalytics } from './options.js';
|
|
7
|
+
import { DEFAULT_INDEX_COLLECTION } from './resolve.js';
|
|
7
8
|
export { aggregateEvents, cleanSearchTerm } from './analytics.js';
|
|
8
9
|
export { SearchIndexCache, searchIndexCache } from './cache.js';
|
|
9
10
|
export { decodeEntities } from './decodeEntities.js';
|
|
10
11
|
export { hrefFor, projectDocs } from './project.js';
|
|
11
12
|
export { DEFAULT_FIELDS, DEFAULT_FUZZY, groupResults, presetResults, rankDocs } from './rank.js';
|
|
12
|
-
export { createSearchService } from './resolve.js';
|
|
13
|
+
export { createSearchService, DEFAULT_INDEX_COLLECTION } from './resolve.js';
|
|
13
14
|
export { deviceOf, isBot, parseTrackPayload, recordSearchEvent } from './track.js';
|
|
14
15
|
/**
|
|
15
16
|
* Cached, grouped and ranked site search over the `@payloadcms/plugin-search` index.
|
|
@@ -30,6 +31,24 @@ export { deviceOf, isBot, parseTrackPayload, recordSearchEvent } from './track.j
|
|
|
30
31
|
const prefix = pluginOptions.routePrefix ?? '/site-search';
|
|
31
32
|
const requireAdmin = pluginOptions.requireAdminForOperations ?? true;
|
|
32
33
|
searchIndexCache.configure(pluginOptions.cacheTTL ?? 60_000);
|
|
34
|
+
// Drop the projection whenever plugin-search writes the index, so a published edit shows up
|
|
35
|
+
// now rather than after the TTL. Per process: other instances still wait out the TTL.
|
|
36
|
+
const indexSlug = pluginOptions.indexCollection ?? DEFAULT_INDEX_COLLECTION;
|
|
37
|
+
const invalidate = ()=>searchIndexCache.invalidate();
|
|
38
|
+
config.collections = (config.collections || []).map((collection)=>collection.slug === indexSlug ? {
|
|
39
|
+
...collection,
|
|
40
|
+
hooks: {
|
|
41
|
+
...collection.hooks,
|
|
42
|
+
afterChange: [
|
|
43
|
+
...collection.hooks?.afterChange ?? [],
|
|
44
|
+
invalidate
|
|
45
|
+
],
|
|
46
|
+
afterDelete: [
|
|
47
|
+
...collection.hooks?.afterDelete ?? [],
|
|
48
|
+
invalidate
|
|
49
|
+
]
|
|
50
|
+
}
|
|
51
|
+
} : collection);
|
|
33
52
|
if (analytics.enabled) {
|
|
34
53
|
config.collections = [
|
|
35
54
|
...config.collections || [],
|
|
@@ -48,6 +67,14 @@ export { deviceOf, isBot, parseTrackPayload, recordSearchEvent } from './track.j
|
|
|
48
67
|
method: 'get',
|
|
49
68
|
path: prefix
|
|
50
69
|
},
|
|
70
|
+
{
|
|
71
|
+
handler: createResultsHandler({
|
|
72
|
+
cache: searchIndexCache,
|
|
73
|
+
config: pluginOptions
|
|
74
|
+
}),
|
|
75
|
+
method: 'get',
|
|
76
|
+
path: `${prefix}/results`
|
|
77
|
+
},
|
|
51
78
|
{
|
|
52
79
|
handler: createReindexHandler({
|
|
53
80
|
cache: searchIndexCache,
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import { withRateLimit } from '@foundrykit/rate-limit';\nimport type { Config } from 'payload';\nimport { recordActivePlugin } from './activePlugins.js';\nimport { searchIndexCache } from './cache.js';\nimport { createSearchEventsCollection } from './collections/SearchEvents.js';\nimport {\n createInspectHandler,\n createReindexHandler,\n createSearchHandler,\n createTrackHandler,\n} from './endpoints/handlers.js';\nimport {\n assertConfig,\n DEFAULT_TRACK_RATE_LIMIT,\n resolveAnalytics,\n} from './options.js';\nimport type { SearchPluginConfig } from './types.js';\n\nexport { aggregateEvents, cleanSearchTerm } from './analytics.js';\nexport { SearchIndexCache, searchIndexCache } from './cache.js';\nexport { decodeEntities } from './decodeEntities.js';\nexport { hrefFor, projectDocs } from './project.js';\nexport {\n DEFAULT_FIELDS,\n DEFAULT_FUZZY,\n groupResults,\n presetResults,\n rankDocs,\n} from './rank.js';\nexport {
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import { withRateLimit } from '@foundrykit/rate-limit';\nimport type { Config } from 'payload';\nimport { recordActivePlugin } from './activePlugins.js';\nimport { searchIndexCache } from './cache.js';\nimport { createSearchEventsCollection } from './collections/SearchEvents.js';\nimport {\n createInspectHandler,\n createReindexHandler,\n createResultsHandler,\n createSearchHandler,\n createTrackHandler,\n} from './endpoints/handlers.js';\nimport {\n assertConfig,\n DEFAULT_TRACK_RATE_LIMIT,\n resolveAnalytics,\n} from './options.js';\nimport { DEFAULT_INDEX_COLLECTION } from './resolve.js';\nimport type { SearchPluginConfig } from './types.js';\n\nexport { aggregateEvents, cleanSearchTerm } from './analytics.js';\nexport { SearchIndexCache, searchIndexCache } from './cache.js';\nexport { decodeEntities } from './decodeEntities.js';\nexport { hrefFor, projectDocs } from './project.js';\nexport {\n DEFAULT_FIELDS,\n DEFAULT_FUZZY,\n groupResults,\n presetResults,\n rankDocs,\n} from './rank.js';\nexport {\n createSearchService,\n DEFAULT_INDEX_COLLECTION,\n} from './resolve.js';\nexport type { ShownResult, TrackPayload } from './track.js';\nexport {\n deviceOf,\n isBot,\n parseTrackPayload,\n recordSearchEvent,\n} from './track.js';\nexport type * from './types.js';\n\n/**\n * Cached, grouped and ranked site search over the `@payloadcms/plugin-search` index.\n *\n * Layered on top of plugin-search rather than replacing it: that plugin already keeps a `search`\n * collection in sync through afterChange/afterDelete hooks, and sync is the part of an index\n * implementation that rots. This owns the read side — projection, caching, fuzzy ranking,\n * grouping — plus the operational surface an editor needs.\n *\n * Install it AFTER searchPlugin in the plugins array, since it reads the collection that one\n * creates.\n */\nexport const searchPlugin =\n (pluginOptions: SearchPluginConfig) =>\n (config: Config): Config => {\n if (pluginOptions.disabled) {\n return config;\n }\n\n assertConfig(pluginOptions);\n\n const analytics = resolveAnalytics(pluginOptions.analytics);\n const prefix = pluginOptions.routePrefix ?? '/site-search';\n const requireAdmin = pluginOptions.requireAdminForOperations ?? true;\n\n searchIndexCache.configure(pluginOptions.cacheTTL ?? 60_000);\n\n // Drop the projection whenever plugin-search writes the index, so a published edit shows up\n // now rather than after the TTL. Per process: other instances still wait out the TTL.\n const indexSlug = pluginOptions.indexCollection ?? DEFAULT_INDEX_COLLECTION;\n const invalidate = () => searchIndexCache.invalidate();\n config.collections = (config.collections || []).map(collection =>\n collection.slug === indexSlug\n ? {\n ...collection,\n hooks: {\n ...collection.hooks,\n afterChange: [\n ...(collection.hooks?.afterChange ?? []),\n invalidate,\n ],\n afterDelete: [\n ...(collection.hooks?.afterDelete ?? []),\n invalidate,\n ],\n },\n }\n : collection\n );\n\n if (analytics.enabled) {\n config.collections = [\n ...(config.collections || []),\n createSearchEventsCollection({ slug: analytics.collectionSlug }),\n ];\n }\n\n config.endpoints = [\n ...(config.endpoints || []),\n {\n handler: createSearchHandler({\n cache: searchIndexCache,\n config: pluginOptions,\n }),\n method: 'get',\n path: prefix,\n },\n {\n handler: createResultsHandler({\n cache: searchIndexCache,\n config: pluginOptions,\n }),\n method: 'get',\n path: `${prefix}/results`,\n },\n {\n handler: createReindexHandler({\n cache: searchIndexCache,\n config: pluginOptions,\n requireAdmin,\n }),\n method: 'post',\n path: `${prefix}/reindex`,\n },\n {\n handler: createInspectHandler({\n cache: searchIndexCache,\n config: pluginOptions,\n requireAdmin,\n }),\n method: 'get',\n path: `${prefix}/inspect`,\n },\n ...(analytics.enabled\n ? [\n {\n // Public and writes a row per call, so it is always limited unless the host opts out.\n handler:\n pluginOptions.rateLimit === false\n ? createTrackHandler({ config: pluginOptions })\n : withRateLimit(\n createTrackHandler({ config: pluginOptions }),\n {\n key: (_req, ip) => `search-track:${ip}`,\n ...DEFAULT_TRACK_RATE_LIMIT,\n ...pluginOptions.rateLimit,\n }\n ),\n method: 'post' as const,\n path: `${prefix}/track`,\n },\n ]\n : []),\n ];\n\n return recordActivePlugin(config, '@foundrykit/search-plugin');\n };\n"],"names":["withRateLimit","recordActivePlugin","searchIndexCache","createSearchEventsCollection","createInspectHandler","createReindexHandler","createResultsHandler","createSearchHandler","createTrackHandler","assertConfig","DEFAULT_TRACK_RATE_LIMIT","resolveAnalytics","DEFAULT_INDEX_COLLECTION","aggregateEvents","cleanSearchTerm","SearchIndexCache","decodeEntities","hrefFor","projectDocs","DEFAULT_FIELDS","DEFAULT_FUZZY","groupResults","presetResults","rankDocs","createSearchService","deviceOf","isBot","parseTrackPayload","recordSearchEvent","searchPlugin","pluginOptions","config","disabled","analytics","prefix","routePrefix","requireAdmin","requireAdminForOperations","configure","cacheTTL","indexSlug","indexCollection","invalidate","collections","map","collection","slug","hooks","afterChange","afterDelete","enabled","collectionSlug","endpoints","handler","cache","method","path","rateLimit","key","_req","ip"],"mappings":"AAAA,SAASA,aAAa,QAAQ,yBAAyB;AAEvD,SAASC,kBAAkB,QAAQ,qBAAqB;AACxD,SAASC,gBAAgB,QAAQ,aAAa;AAC9C,SAASC,4BAA4B,QAAQ,gCAAgC;AAC7E,SACEC,oBAAoB,EACpBC,oBAAoB,EACpBC,oBAAoB,EACpBC,mBAAmB,EACnBC,kBAAkB,QACb,0BAA0B;AACjC,SACEC,YAAY,EACZC,wBAAwB,EACxBC,gBAAgB,QACX,eAAe;AACtB,SAASC,wBAAwB,QAAQ,eAAe;AAGxD,SAASC,eAAe,EAAEC,eAAe,QAAQ,iBAAiB;AAClE,SAASC,gBAAgB,EAAEb,gBAAgB,QAAQ,aAAa;AAChE,SAASc,cAAc,QAAQ,sBAAsB;AACrD,SAASC,OAAO,EAAEC,WAAW,QAAQ,eAAe;AACpD,SACEC,cAAc,EACdC,aAAa,EACbC,YAAY,EACZC,aAAa,EACbC,QAAQ,QACH,YAAY;AACnB,SACEC,mBAAmB,EACnBZ,wBAAwB,QACnB,eAAe;AAEtB,SACEa,QAAQ,EACRC,KAAK,EACLC,iBAAiB,EACjBC,iBAAiB,QACZ,aAAa;AAGpB;;;;;;;;;;CAUC,GACD,OAAO,MAAMC,eACX,CAACC,gBACD,CAACC;Q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BACP6B,QAAQD;oBACRM;gBACF;gBACAmB,QAAQ;gBACRC,MAAM,GAAGtB,OAAO,QAAQ,CAAC;YAC3B;YACA;gBACEmB,SAASjD,qBAAqB;oBAC5BkD,OAAOpD;oBACP6B,QAAQD;oBACRM;gBACF;gBACAmB,QAAQ;gBACRC,MAAM,GAAGtB,OAAO,QAAQ,CAAC;YAC3B;eACID,UAAUiB,OAAO,GACjB;gBACE;oBACE,sFAAsF;oBACtFG,SACEvB,cAAc2B,SAAS,KAAK,QACxBjD,mBAAmB;wBAAEuB,QAAQD;oBAAc,KAC3C9B,cACEQ,mBAAmB;wBAAEuB,QAAQD;oBAAc,IAC3C;wBACE4B,KAAK,CAACC,MAAMC,KAAO,CAAC,aAAa,EAAEA,IAAI;wBACvC,GAAGlD,wBAAwB;wBAC3B,GAAGoB,cAAc2B,SAAS;oBAC5B;oBAERF,QAAQ;oBACRC,MAAM,GAAGtB,OAAO,MAAM,CAAC;gBACzB;aACD,GACD,EAAE;SACP;QAED,OAAOjC,mBAAmB8B,QAAQ;IACpC,EAAE"}
|
package/dist/project.d.ts
CHANGED
|
@@ -1,18 +1,4 @@
|
|
|
1
|
-
import type { IndexedDoc, SearchableCollection } from './types.js';
|
|
2
|
-
/** A row as it comes back from the plugin-search `search` collection. */
|
|
3
|
-
export type SearchDoc = {
|
|
4
|
-
doc?: {
|
|
5
|
-
relationTo?: string;
|
|
6
|
-
value?: number | string;
|
|
7
|
-
} | null;
|
|
8
|
-
id?: number | string;
|
|
9
|
-
meta?: {
|
|
10
|
-
description?: null | string;
|
|
11
|
-
title?: null | string;
|
|
12
|
-
} | null;
|
|
13
|
-
slug?: null | string;
|
|
14
|
-
title?: null | string;
|
|
15
|
-
};
|
|
1
|
+
import type { IndexedDoc, SearchableCollection, SearchDoc } from './types.js';
|
|
16
2
|
export type ProjectionResult = {
|
|
17
3
|
docs: IndexedDoc[];
|
|
18
4
|
skipped: {
|
|
@@ -28,9 +14,11 @@ export type ProjectionResult = {
|
|
|
28
14
|
* drop is recorded with a reason — an inventory count tells you nothing when the document you care
|
|
29
15
|
* about is the one that is missing.
|
|
30
16
|
*/
|
|
31
|
-
export declare function projectDocs({ collections, decode, rows, }: {
|
|
17
|
+
export declare function projectDocs({ collections, decode, hidden, rows, }: {
|
|
32
18
|
collections: SearchableCollection[];
|
|
33
19
|
decode?: boolean;
|
|
20
|
+
/** `${collection}:${docId}` keys hidden by a collection's `excludeField`. */
|
|
21
|
+
hidden?: Set<string>;
|
|
34
22
|
rows: SearchDoc[];
|
|
35
23
|
}): ProjectionResult;
|
|
36
24
|
/** Build the href for a projected document. */
|
package/dist/project.js
CHANGED
|
@@ -5,7 +5,7 @@ import { decodeEntities } from './decodeEntities.js';
|
|
|
5
5
|
* Rows are dropped rather than half-rendered when they cannot produce a working result, and every
|
|
6
6
|
* drop is recorded with a reason — an inventory count tells you nothing when the document you care
|
|
7
7
|
* about is the one that is missing.
|
|
8
|
-
*/ export function projectDocs({ collections, decode = true, rows }) {
|
|
8
|
+
*/ export function projectDocs({ collections, decode = true, hidden, rows }) {
|
|
9
9
|
const byslug = new Map(collections.map((entry)=>[
|
|
10
10
|
entry.slug,
|
|
11
11
|
entry
|
|
@@ -58,11 +58,21 @@ import { decodeEntities } from './decodeEntities.js';
|
|
|
58
58
|
});
|
|
59
59
|
continue;
|
|
60
60
|
}
|
|
61
|
+
if (hidden?.has(`${collection}:${id}`)) {
|
|
62
|
+
skipped.push({
|
|
63
|
+
id,
|
|
64
|
+
slug: collection,
|
|
65
|
+
reason: `hidden by "${config.excludeField}"`
|
|
66
|
+
});
|
|
67
|
+
continue;
|
|
68
|
+
}
|
|
61
69
|
docs.push({
|
|
62
70
|
id: `${collection}-${id}`,
|
|
63
71
|
collection,
|
|
64
72
|
description: decode ? decodeEntities(row.meta?.description) : row.meta?.description ?? undefined,
|
|
73
|
+
docId: id,
|
|
65
74
|
group: config.group,
|
|
75
|
+
href: config.href?.(row) || undefined,
|
|
66
76
|
icon: config.icon,
|
|
67
77
|
// An empty prefix is meaningful: it marks a collection served at the site root. Compared
|
|
68
78
|
// against undefined rather than truthiness so those documents are not silently dropped.
|
|
@@ -77,6 +87,6 @@ import { decodeEntities } from './decodeEntities.js';
|
|
|
77
87
|
skipped
|
|
78
88
|
};
|
|
79
89
|
}
|
|
80
|
-
/** Build the href for a projected document. */ export const hrefFor = (doc)
|
|
90
|
+
/** Build the href for a projected document. */ export const hrefFor = (doc)=>doc.href ?? `${doc.path}/${doc.slug}`;
|
|
81
91
|
|
|
82
92
|
//# sourceMappingURL=project.js.map
|
package/dist/project.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/project.ts"],"sourcesContent":["import { decodeEntities } from './decodeEntities.js';\nimport type { IndexedDoc, SearchableCollection } from './types.js';\n\
|
|
1
|
+
{"version":3,"sources":["../src/project.ts"],"sourcesContent":["import { decodeEntities } from './decodeEntities.js';\nimport type { IndexedDoc, SearchableCollection, SearchDoc } from './types.js';\n\nexport type ProjectionResult = {\n docs: IndexedDoc[];\n skipped: { id: string; reason: string; slug: string }[];\n};\n\n/**\n * Turn plugin-search rows into the flat projection the read path searches.\n *\n * Rows are dropped rather than half-rendered when they cannot produce a working result, and every\n * drop is recorded with a reason — an inventory count tells you nothing when the document you care\n * about is the one that is missing.\n */\nexport function projectDocs({\n collections,\n decode = true,\n hidden,\n rows,\n}: {\n collections: SearchableCollection[];\n decode?: boolean;\n /** `${collection}:${docId}` keys hidden by a collection's `excludeField`. */\n hidden?: Set<string>;\n rows: SearchDoc[];\n}): ProjectionResult {\n const byslug = new Map(collections.map(entry => [entry.slug, entry]));\n const docs: IndexedDoc[] = [];\n const skipped: ProjectionResult['skipped'] = [];\n\n for (const row of rows) {\n const collection = row.doc?.relationTo;\n const id = String(row.doc?.value ?? row.id ?? '');\n\n if (!collection) {\n skipped.push({\n id,\n slug: '',\n reason: 'no source collection on the index row',\n });\n continue;\n }\n\n const config = byslug.get(collection);\n if (!config) {\n skipped.push({\n id,\n slug: collection,\n reason: `collection \"${collection}\" is not configured`,\n });\n continue;\n }\n\n const slug = row.slug;\n const title = row.title || row.meta?.title;\n\n if (!slug) {\n skipped.push({\n id,\n slug: collection,\n reason: 'no slug, so no URL can be built',\n });\n continue;\n }\n\n if (!title) {\n skipped.push({ id, slug: collection, reason: 'no title to display' });\n continue;\n }\n\n if (config.excludeSlugs?.includes(slug)) {\n skipped.push({ id, slug: collection, reason: 'excluded by config' });\n continue;\n }\n\n if (hidden?.has(`${collection}:${id}`)) {\n skipped.push({\n id,\n slug: collection,\n reason: `hidden by \"${config.excludeField}\"`,\n });\n continue;\n }\n\n docs.push({\n id: `${collection}-${id}`,\n collection,\n description: decode\n ? decodeEntities(row.meta?.description)\n : (row.meta?.description ?? undefined),\n docId: id,\n group: config.group,\n href: config.href?.(row) || undefined,\n icon: config.icon,\n // An empty prefix is meaningful: it marks a collection served at the site root. Compared\n // against undefined rather than truthiness so those documents are not silently dropped.\n slug,\n path: config.path,\n title: decode ? decodeEntities(title) : title,\n weight: config.weight ?? 1,\n });\n }\n\n return { docs, skipped };\n}\n\n/** Build the href for a projected document. */\nexport const hrefFor = (doc: IndexedDoc): string =>\n doc.href ?? `${doc.path}/${doc.slug}`;\n"],"names":["decodeEntities","projectDocs","collections","decode","hidden","rows","byslug","Map","map","entry","slug","docs","skipped","row","collection","doc","relationTo","id","String","value","push","reason","config","get","title","meta","excludeSlugs","includes","has","excludeField","description","undefined","docId","group","href","icon","path","weight","hrefFor"],"mappings":"AAAA,SAASA,cAAc,QAAQ,sBAAsB;AAQrD;;;;;;CAMC,GACD,OAAO,SAASC,YAAY,EAC1BC,WAAW,EACXC,SAAS,IAAI,EACbC,MAAM,EACNC,IAAI,EAOL;IACC,MAAMC,SAAS,IAAIC,IAAIL,YAAYM,GAAG,CAACC,CAAAA,QAAS;YAACA,MAAMC,IAAI;YAAED;SAAM;IACnE,MAAME,OAAqB,EAAE;IAC7B,MAAMC,UAAuC,EAAE;IAE/C,KAAK,MA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Of;YACPgB,OAAOX,OAAOW,KAAK;YACnBC,MAAMZ,OAAOY,IAAI,GAAGrB,QAAQkB;YAC5BI,MAAMb,OAAOa,IAAI;YACjB,yFAAyF;YACzF,wFAAwF;YACxFzB;YACA0B,MAAMd,OAAOc,IAAI;YACjBZ,OAAOrB,SAASH,eAAewB,SAASA;YACxCa,QAAQf,OAAOe,MAAM,IAAI;QAC3B;IACF;IAEA,OAAO;QAAE1B;QAAMC;IAAQ;AACzB;AAEA,6CAA6C,GAC7C,OAAO,MAAM0B,UAAU,CAACvB,MACtBA,IAAImB,IAAI,IAAI,GAAGnB,IAAIqB,IAAI,CAAC,CAAC,EAAErB,IAAIL,IAAI,EAAE,CAAC"}
|
package/dist/rank.d.ts
CHANGED
|
@@ -1,6 +1,17 @@
|
|
|
1
|
-
import type { FuzzyOptions, GroupedResults, IndexedDoc, SearchField, SearchGroup } from './types.js';
|
|
1
|
+
import type { FuzzyOptions, GroupedResults, IndexedDoc, SearchField, SearchGroup, SearchResult } from './types.js';
|
|
2
2
|
export declare const DEFAULT_FIELDS: SearchField[];
|
|
3
3
|
export declare const DEFAULT_FUZZY: Required<FuzzyOptions>;
|
|
4
|
+
export type RankedDoc = {
|
|
5
|
+
doc: IndexedDoc;
|
|
6
|
+
highlights?: [number, number][];
|
|
7
|
+
score?: number;
|
|
8
|
+
};
|
|
9
|
+
export declare const toResult: ({ doc, highlights, score, }: RankedDoc) => SearchResult;
|
|
10
|
+
/** Fuse's inclusive title match indices as sorted, merged `[start, end)` ranges. */
|
|
11
|
+
export declare function titleHighlights(matches?: readonly {
|
|
12
|
+
indices: readonly (readonly [number, number])[];
|
|
13
|
+
key?: string;
|
|
14
|
+
}[]): [number, number][];
|
|
4
15
|
/**
|
|
5
16
|
* Rank documents against a query.
|
|
6
17
|
*
|
|
@@ -18,17 +29,13 @@ export declare function rankDocs({ docs, fields, fuzzy, query, }: {
|
|
|
18
29
|
fields?: SearchField[];
|
|
19
30
|
fuzzy?: FuzzyOptions;
|
|
20
31
|
query: string;
|
|
21
|
-
}): {
|
|
22
|
-
doc: IndexedDoc;
|
|
32
|
+
}): (RankedDoc & {
|
|
23
33
|
score: number;
|
|
24
|
-
}[];
|
|
34
|
+
})[];
|
|
25
35
|
/** Bucket ranked documents into their groups, applying each group's cap. */
|
|
26
36
|
export declare function groupResults({ groups, ranked, }: {
|
|
27
37
|
groups: SearchGroup[];
|
|
28
|
-
ranked:
|
|
29
|
-
doc: IndexedDoc;
|
|
30
|
-
score?: number;
|
|
31
|
-
}[];
|
|
38
|
+
ranked: RankedDoc[];
|
|
32
39
|
}): GroupedResults;
|
|
33
40
|
/**
|
|
34
41
|
* The empty-query preset.
|
package/dist/rank.js
CHANGED
|
@@ -21,15 +21,36 @@ export const DEFAULT_FUZZY = {
|
|
|
21
21
|
minMatchCharLength: 3,
|
|
22
22
|
threshold: 0.35
|
|
23
23
|
};
|
|
24
|
-
const toResult = (doc, score)=>({
|
|
24
|
+
export const toResult = ({ doc, highlights, score })=>({
|
|
25
25
|
id: doc.id,
|
|
26
26
|
collection: doc.collection,
|
|
27
|
+
description: doc.description,
|
|
28
|
+
docId: doc.docId,
|
|
27
29
|
group: doc.group,
|
|
30
|
+
highlights,
|
|
28
31
|
href: hrefFor(doc),
|
|
29
32
|
icon: doc.icon,
|
|
30
33
|
score,
|
|
31
34
|
title: doc.title
|
|
32
35
|
});
|
|
36
|
+
/** Fuse's inclusive title match indices as sorted, merged `[start, end)` ranges. */ export function titleHighlights(matches = []) {
|
|
37
|
+
const ranges = matches.filter((match)=>match.key === 'title').flatMap((match)=>match.indices.map(([a, b])=>[
|
|
38
|
+
a,
|
|
39
|
+
b + 1
|
|
40
|
+
])).sort((a, b)=>a[0] - b[0]);
|
|
41
|
+
const merged = [];
|
|
42
|
+
for (const range of ranges){
|
|
43
|
+
const last = merged.at(-1);
|
|
44
|
+
if (last && range[0] <= last[1]) {
|
|
45
|
+
last[1] = Math.max(last[1], range[1]);
|
|
46
|
+
} else {
|
|
47
|
+
merged.push([
|
|
48
|
+
...range
|
|
49
|
+
]);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return merged;
|
|
53
|
+
}
|
|
33
54
|
/**
|
|
34
55
|
* Rank documents against a query.
|
|
35
56
|
*
|
|
@@ -53,6 +74,7 @@ const toResult = (doc, score)=>({
|
|
|
53
74
|
const search = (useTokenSearch)=>new Fuse(docs, {
|
|
54
75
|
distance: options.distance,
|
|
55
76
|
ignoreLocation: true,
|
|
77
|
+
includeMatches: true,
|
|
56
78
|
includeScore: true,
|
|
57
79
|
keys: fields.map((field)=>({
|
|
58
80
|
name: field.name,
|
|
@@ -63,6 +85,7 @@ const toResult = (doc, score)=>({
|
|
|
63
85
|
useTokenSearch
|
|
64
86
|
}).search(trimmed).map((hit)=>({
|
|
65
87
|
doc: hit.item,
|
|
88
|
+
highlights: titleHighlights(hit.matches),
|
|
66
89
|
// Fuse scores are "lower is better", so dividing by weight promotes a heavier collection.
|
|
67
90
|
score: (hit.score ?? 1) / (hit.item.weight || 1)
|
|
68
91
|
})).sort((a, b)=>a.score - b.score);
|
|
@@ -85,8 +108,8 @@ const toResult = (doc, score)=>({
|
|
|
85
108
|
for (const group of groups){
|
|
86
109
|
grouped[group.slug] = [];
|
|
87
110
|
}
|
|
88
|
-
for (const
|
|
89
|
-
const group = bySlug.get(doc.group);
|
|
111
|
+
for (const hit of ranked){
|
|
112
|
+
const group = bySlug.get(hit.doc.group);
|
|
90
113
|
if (!group) {
|
|
91
114
|
continue;
|
|
92
115
|
}
|
|
@@ -94,7 +117,7 @@ const toResult = (doc, score)=>({
|
|
|
94
117
|
if (group.limit !== undefined && bucket.length >= group.limit) {
|
|
95
118
|
continue;
|
|
96
119
|
}
|
|
97
|
-
bucket.push(toResult(
|
|
120
|
+
bucket.push(toResult(hit));
|
|
98
121
|
}
|
|
99
122
|
return grouped;
|
|
100
123
|
}
|
package/dist/rank.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/rank.ts"],"sourcesContent":["import Fuse from 'fuse.js';\nimport { hrefFor } from './project.js';\nimport type {\n FuzzyOptions,\n GroupedResults,\n IndexedDoc,\n SearchField,\n SearchGroup,\n SearchResult,\n} from './types.js';\n\nexport const DEFAULT_FIELDS: SearchField[] = [\n { name: 'title', weight: 1 },\n { name: 'slug', weight: 0.4 },\n { name: 'description', weight: 0.2 },\n];\n\nexport const DEFAULT_FUZZY: Required<FuzzyOptions> = {\n distance: 100,\n // Two-character queries match too much to be useful; this is what stops a query like \"tuni\"\n // pulling documents that merely contain those letters somewhere in a description.\n minMatchCharLength: 3,\n threshold: 0.35,\n};\n\
|
|
1
|
+
{"version":3,"sources":["../src/rank.ts"],"sourcesContent":["import Fuse from 'fuse.js';\nimport { hrefFor } from './project.js';\nimport type {\n FuzzyOptions,\n GroupedResults,\n IndexedDoc,\n SearchField,\n SearchGroup,\n SearchResult,\n} from './types.js';\n\nexport const DEFAULT_FIELDS: SearchField[] = [\n { name: 'title', weight: 1 },\n { name: 'slug', weight: 0.4 },\n { name: 'description', weight: 0.2 },\n];\n\nexport const DEFAULT_FUZZY: Required<FuzzyOptions> = {\n distance: 100,\n // Two-character queries match too much to be useful; this is what stops a query like \"tuni\"\n // pulling documents that merely contain those letters somewhere in a description.\n minMatchCharLength: 3,\n threshold: 0.35,\n};\n\nexport type RankedDoc = {\n doc: IndexedDoc;\n highlights?: [number, number][];\n score?: number;\n};\n\nexport const toResult = ({\n doc,\n highlights,\n score,\n}: RankedDoc): SearchResult => ({\n id: doc.id,\n collection: doc.collection,\n description: doc.description,\n docId: doc.docId,\n group: doc.group,\n highlights,\n href: hrefFor(doc),\n icon: doc.icon,\n score,\n title: doc.title,\n});\n\n/** Fuse's inclusive title match indices as sorted, merged `[start, end)` ranges. */\nexport function titleHighlights(\n matches: readonly {\n indices: readonly (readonly [number, number])[];\n key?: string;\n }[] = []\n): [number, number][] {\n const ranges = matches\n .filter(match => match.key === 'title')\n .flatMap(match =>\n match.indices.map(([a, b]) => [a, b + 1] as [number, number])\n )\n .sort((a, b) => a[0] - b[0]);\n const merged: [number, number][] = [];\n for (const range of ranges) {\n const last = merged.at(-1);\n if (last && range[0] <= last[1]) {\n last[1] = Math.max(last[1], range[1]);\n } else {\n merged.push([...range]);\n }\n }\n return merged;\n}\n\n/**\n * Rank documents against a query.\n *\n * Fuse gives fuzzy tolerance for typos and plurals. Its score is then divided by the collection\n * weight so a configured priority can lift an otherwise equal match — cheaper and far more\n * predictable than trying to express priority through Fuse's own field weights.\n *\n * Fuse matches the query as one phrase, so a word the title lacks or a different word order\n * (\"royal palm mauritius\", \"seychelles hilton\") matches nothing. A multi-word query therefore also\n * matches word by word, and those hits follow every phrase hit: the phrase ranking stays as it was,\n * and the words only add what it missed.\n */\nexport function rankDocs({\n docs,\n fields = DEFAULT_FIELDS,\n fuzzy,\n query,\n}: {\n docs: IndexedDoc[];\n fields?: SearchField[];\n fuzzy?: FuzzyOptions;\n query: string;\n}): (RankedDoc & { score: number })[] {\n const trimmed = query.trim();\n if (!trimmed) {\n return [];\n }\n\n const options = { ...DEFAULT_FUZZY, ...fuzzy };\n const search = (useTokenSearch: boolean) =>\n new Fuse(docs, {\n distance: options.distance,\n ignoreLocation: true,\n includeMatches: true,\n includeScore: true,\n keys: fields.map(field => ({\n name: field.name,\n weight: field.weight ?? 1,\n })),\n minMatchCharLength: options.minMatchCharLength,\n threshold: options.threshold,\n useTokenSearch,\n })\n .search(trimmed)\n .map(hit => ({\n doc: hit.item,\n highlights: titleHighlights(hit.matches),\n // Fuse scores are \"lower is better\", so dividing by weight promotes a heavier collection.\n score: (hit.score ?? 1) / (hit.item.weight || 1),\n }))\n .sort((a, b) => a.score - b.score);\n\n const phrase = search(false);\n if (!/\\s/.test(trimmed)) {\n return phrase;\n }\n const found = new Set(phrase.map(hit => hit.doc));\n return [...phrase, ...search(true).filter(hit => !found.has(hit.doc))];\n}\n\n/** Bucket ranked documents into their groups, applying each group's cap. */\nexport function groupResults({\n groups,\n ranked,\n}: {\n groups: SearchGroup[];\n ranked: RankedDoc[];\n}): GroupedResults {\n const bySlug = new Map(groups.map(group => [group.slug, group]));\n const grouped: GroupedResults = {};\n\n for (const group of groups) {\n grouped[group.slug] = [];\n }\n\n for (const hit of ranked) {\n const group = bySlug.get(hit.doc.group);\n if (!group) {\n continue;\n }\n\n const bucket = grouped[group.slug];\n if (group.limit !== undefined && bucket.length >= group.limit) {\n continue;\n }\n\n bucket.push(toResult(hit));\n }\n\n return grouped;\n}\n\n/**\n * The empty-query preset.\n *\n * Ordered by collection weight and then alphabetically, and only for groups that opted in. Callers\n * that want a curated list should configure weights — this is explicitly not popularity-ranked,\n * and saying so here is cheaper than a client learning it later.\n */\nexport function presetResults({\n docs,\n groups,\n}: {\n docs: IndexedDoc[];\n groups: SearchGroup[];\n}): GroupedResults {\n const eligible = new Set(\n groups\n .filter(group => group.showWhenEmpty !== false)\n .map(group => group.slug)\n );\n\n const ordered = docs\n .filter(doc => eligible.has(doc.group))\n .sort((a, b) => b.weight - a.weight || a.title.localeCompare(b.title))\n .map(doc => ({ doc }));\n\n const grouped = groupResults({ groups, ranked: ordered });\n\n for (const group of groups) {\n if (!eligible.has(group.slug)) {\n grouped[group.slug] = [];\n }\n }\n\n return grouped;\n}\n"],"names":["Fuse","hrefFor","DEFAULT_FIELDS","name","weight","DEFAULT_FUZZY","distance","minMatchCharLength","threshold","toResult","doc","highlights","score","id","collection","description","docId","group","href","icon","title","titleHighlights","matches","ranges","filter","match","key","flatMap","indices","map","a","b","sort","merged","range","last","at","Math","max","push","rankDocs","docs","fields","fuzzy","query","trimmed","trim","options","search","useTokenSearch","ignoreLocation","includeMatches","includeScore","keys","field","hit","item","phrase","test","found","Set","has","groupResults","groups","ranked","bySlug","Map","slug","grouped","get","bucket","limit","undefined","length","presetResults","eligible","showWhenEmpty","ordered","localeCompare"],"mappings":"AAAA,OAAOA,UAAU,UAAU;AAC3B,SAASC,OAAO,QAAQ,eAAe;AAUvC,OAAO,MAAMC,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AAQa;IAAQ;IAEvD,KAAK,MAAM5D,SAAS8C,OAAQ;QAC1B,IAAI,CAACY,SAASd,GAAG,CAAC5C,MAAMkD,IAAI,GAAG;YAC7BC,OAAO,CAACnD,MAAMkD,IAAI,CAAC,GAAG,EAAE;QAC1B;IACF;IAEA,OAAOC;AACT"}
|
package/dist/resolve.d.ts
CHANGED
|
@@ -1,8 +1,19 @@
|
|
|
1
1
|
import type { Payload } from 'payload';
|
|
2
2
|
import type { SearchIndexCache } from './cache.js';
|
|
3
|
-
import type { GroupedResults, IndexReport, SearchPluginConfig } from './types.js';
|
|
3
|
+
import type { GroupedResults, IndexReport, PaginatedResults, SearchPluginConfig, SearchQuery } from './types.js';
|
|
4
|
+
/**
|
|
5
|
+
* The collection plugin-search maintains. Reading it rather than the source collections is the
|
|
6
|
+
* whole point: one query instead of one per collection, and sync is already solved by the hooks
|
|
7
|
+
* plugin-search installs.
|
|
8
|
+
*/
|
|
9
|
+
export declare const DEFAULT_INDEX_COLLECTION = "search";
|
|
4
10
|
export type SearchService = {
|
|
5
11
|
inspect: () => Promise<IndexReport>;
|
|
12
|
+
/**
|
|
13
|
+
* Flat, ranked and paginated, ignoring group caps: for a results page, or for the ranked
|
|
14
|
+
* `docId`s a filtered archive narrows with its own `where`.
|
|
15
|
+
*/
|
|
16
|
+
query: (query: SearchQuery) => Promise<PaginatedResults>;
|
|
6
17
|
reindex: () => Promise<{
|
|
7
18
|
indexed: number;
|
|
8
19
|
skipped: number;
|
package/dist/resolve.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { projectDocs } from './project.js';
|
|
2
|
-
import { groupResults, presetResults, rankDocs } from './rank.js';
|
|
2
|
+
import { groupResults, presetResults, rankDocs, toResult } from './rank.js';
|
|
3
3
|
/**
|
|
4
4
|
* The collection plugin-search maintains. Reading it rather than the source collections is the
|
|
5
5
|
* whole point: one query instead of one per collection, and sync is already solved by the hooks
|
|
6
6
|
* plugin-search installs.
|
|
7
|
-
*/ const
|
|
7
|
+
*/ export const DEFAULT_INDEX_COLLECTION = 'search';
|
|
8
8
|
/**
|
|
9
9
|
* Build the read path.
|
|
10
10
|
*
|
|
@@ -15,16 +15,40 @@ import { groupResults, presetResults, rankDocs } from './rank.js';
|
|
|
15
15
|
* editor rather than a developer.
|
|
16
16
|
*/ export function createSearchService({ cache, config, payload }) {
|
|
17
17
|
const decode = config.decodeEntities ?? true;
|
|
18
|
+
/** `${collection}:${id}` for every document an `excludeField` checkbox hides. */ const hiddenDocs = async ()=>{
|
|
19
|
+
const keys = await Promise.all(config.collections.filter((entry)=>entry.excludeField).map(async (entry)=>{
|
|
20
|
+
const { docs } = await payload.find({
|
|
21
|
+
collection: entry.slug,
|
|
22
|
+
depth: 0,
|
|
23
|
+
limit: 0,
|
|
24
|
+
pagination: false,
|
|
25
|
+
select: {
|
|
26
|
+
[entry.excludeField]: true
|
|
27
|
+
},
|
|
28
|
+
where: {
|
|
29
|
+
[entry.excludeField]: {
|
|
30
|
+
equals: true
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
});
|
|
34
|
+
return docs.map((doc)=>`${entry.slug}:${doc.id}`);
|
|
35
|
+
}));
|
|
36
|
+
return new Set(keys.flat());
|
|
37
|
+
};
|
|
18
38
|
const load = async ()=>{
|
|
19
|
-
const response = await
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
39
|
+
const [response, hidden] = await Promise.all([
|
|
40
|
+
payload.find({
|
|
41
|
+
collection: config.indexCollection ?? DEFAULT_INDEX_COLLECTION,
|
|
42
|
+
depth: 0,
|
|
43
|
+
limit: 0,
|
|
44
|
+
pagination: false
|
|
45
|
+
}),
|
|
46
|
+
hiddenDocs()
|
|
47
|
+
]);
|
|
25
48
|
return projectDocs({
|
|
26
49
|
collections: config.collections,
|
|
27
50
|
decode,
|
|
51
|
+
hidden,
|
|
28
52
|
rows: response.docs
|
|
29
53
|
});
|
|
30
54
|
};
|
|
@@ -52,6 +76,25 @@ import { groupResults, presetResults, rankDocs } from './rank.js';
|
|
|
52
76
|
total: fresh.length
|
|
53
77
|
};
|
|
54
78
|
},
|
|
79
|
+
async query ({ collections, limit = 10, page = 1, q }) {
|
|
80
|
+
const trimmed = q.trim();
|
|
81
|
+
const size = Math.min(Math.max(1, Math.floor(limit) || 10), 100);
|
|
82
|
+
const current = Math.max(1, Math.floor(page) || 1);
|
|
83
|
+
const wanted = collections?.length ? new Set(collections) : null;
|
|
84
|
+
const ranked = trimmed ? rankDocs({
|
|
85
|
+
docs: (await docs()).filter((doc)=>!wanted || wanted.has(doc.collection)),
|
|
86
|
+
fields: config.fields,
|
|
87
|
+
fuzzy: config.fuzzy,
|
|
88
|
+
query: trimmed
|
|
89
|
+
}) : [];
|
|
90
|
+
return {
|
|
91
|
+
docs: ranked.slice((current - 1) * size, current * size).map(toResult),
|
|
92
|
+
limit: size,
|
|
93
|
+
page: current,
|
|
94
|
+
totalDocs: ranked.length,
|
|
95
|
+
totalPages: Math.ceil(ranked.length / size)
|
|
96
|
+
};
|
|
97
|
+
},
|
|
55
98
|
async reindex () {
|
|
56
99
|
cache.invalidate();
|
|
57
100
|
const { docs: fresh, skipped } = await load();
|
package/dist/resolve.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/resolve.ts"],"sourcesContent":["import type { Payload } from 'payload';\n\nimport type { SearchIndexCache } from './cache.js';\nimport
|
|
1
|
+
{"version":3,"sources":["../src/resolve.ts"],"sourcesContent":["import type { Payload } from 'payload';\n\nimport type { SearchIndexCache } from './cache.js';\nimport { projectDocs } from './project.js';\nimport { groupResults, presetResults, rankDocs, toResult } from './rank.js';\nimport type {\n GroupedResults,\n IndexedDoc,\n IndexReport,\n PaginatedResults,\n SearchDoc,\n SearchPluginConfig,\n SearchQuery,\n} from './types.js';\n\n/**\n * The collection plugin-search maintains. Reading it rather than the source collections is the\n * whole point: one query instead of one per collection, and sync is already solved by the hooks\n * plugin-search installs.\n */\nexport const DEFAULT_INDEX_COLLECTION = 'search';\n\nexport type SearchService = {\n inspect: () => Promise<IndexReport>;\n /**\n * Flat, ranked and paginated, ignoring group caps: for a results page, or for the ranked\n * `docId`s a filtered archive narrows with its own `where`.\n */\n query: (query: SearchQuery) => Promise<PaginatedResults>;\n reindex: () => Promise<{ indexed: number; skipped: number }>;\n search: (query: string) => Promise<GroupedResults>;\n};\n\n/**\n * Build the read path.\n *\n * The projection is cached, so a burst of keystrokes costs one index read rather than one per\n * request per collection. `reindex` drops the snapshot and rebuilds immediately, which is what\n * makes the CMS button meaningful — hook-driven sync always desyncs eventually (a bulk migration\n * write, a restore from backup, a failed hook), and the recovery path has to be operable by an\n * editor rather than a developer.\n */\nexport function createSearchService({\n cache,\n config,\n payload,\n}: {\n cache: SearchIndexCache;\n config: SearchPluginConfig;\n payload: Payload;\n}): SearchService {\n const decode = config.decodeEntities ?? true;\n\n /** `${collection}:${id}` for every document an `excludeField` checkbox hides. */\n const hiddenDocs = async (): Promise<Set<string>> => {\n const keys = await Promise.all(\n config.collections\n .filter(entry => entry.excludeField)\n .map(async entry => {\n const { docs } = await payload.find({\n collection: entry.slug,\n depth: 0,\n limit: 0,\n pagination: false,\n select: { [entry.excludeField as string]: true },\n where: { [entry.excludeField as string]: { equals: true } },\n });\n return docs.map(doc => `${entry.slug}:${doc.id}`);\n })\n );\n return new Set(keys.flat());\n };\n\n const load = async (): Promise<{\n docs: IndexedDoc[];\n skipped: IndexReport['skipped'];\n }> => {\n const [response, hidden] = await Promise.all([\n payload.find({\n collection: (config.indexCollection ??\n DEFAULT_INDEX_COLLECTION) as never,\n depth: 0,\n limit: 0,\n pagination: false,\n }),\n hiddenDocs(),\n ]);\n\n return projectDocs({\n collections: config.collections,\n decode,\n hidden,\n rows: response.docs as SearchDoc[],\n });\n };\n\n const docs = async (): Promise<IndexedDoc[]> => {\n const cached = cache.get();\n if (cached) {\n return cached;\n }\n\n const { docs: fresh } = await load();\n cache.set(fresh);\n return fresh;\n };\n\n return {\n async inspect() {\n const { docs: fresh, skipped } = await load();\n cache.set(fresh);\n\n return {\n builtAt: cache.builtAt()\n ? new Date(cache.builtAt() as number).toISOString()\n : null,\n collections: config.collections.map(entry => ({\n slug: entry.slug,\n excluded: skipped.filter(row => row.slug === entry.slug).length,\n indexed: fresh.filter(doc => doc.collection === entry.slug).length,\n })),\n skipped,\n total: fresh.length,\n };\n },\n\n async query({ collections, limit = 10, page = 1, q }) {\n const trimmed = q.trim();\n const size = Math.min(Math.max(1, Math.floor(limit) || 10), 100);\n const current = Math.max(1, Math.floor(page) || 1);\n const wanted = collections?.length ? new Set(collections) : null;\n const ranked = trimmed\n ? rankDocs({\n docs: (await docs()).filter(\n doc => !wanted || wanted.has(doc.collection)\n ),\n fields: config.fields,\n fuzzy: config.fuzzy,\n query: trimmed,\n })\n : [];\n\n return {\n docs: ranked.slice((current - 1) * size, current * size).map(toResult),\n limit: size,\n page: current,\n totalDocs: ranked.length,\n totalPages: Math.ceil(ranked.length / size),\n };\n },\n\n async reindex() {\n cache.invalidate();\n const { docs: fresh, skipped } = await load();\n cache.set(fresh);\n return { indexed: fresh.length, skipped: skipped.length };\n },\n\n async search(query: string) {\n const all = await docs();\n const trimmed = query.trim();\n\n if (!trimmed) {\n return presetResults({ docs: all, groups: config.groups });\n }\n\n return groupResults({\n groups: config.groups,\n ranked: rankDocs({\n docs: all,\n fields: config.fields,\n fuzzy: config.fuzzy,\n query: trimmed,\n }),\n });\n },\n };\n}\n"],"names":["projectDocs","groupResults","presetResults","rankDocs","toResult","DEFAULT_INDEX_COLLECTION","createSearchService","cache","config","payload","decode","decodeEntities","hiddenDocs","keys","Promise","all","collections","filter","entry","excludeField","map","docs","find","collection","slug","depth","limit","pagination","select","where","equals","doc","id","Set","flat","load","response","hidden","indexCollection","rows","cached","get","fresh","set","inspect","skipped","builtAt","Date","toISOString","excluded","row","length","indexed","total","query","page","q","trimmed","trim","size","Math","min","max","floor","current","wanted","ranked","has","fields","fuzzy","slice","total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,CAAAA,MAAO,CAACkC,UAAUA,OAAOE,GAAG,CAACpC,IAAIR,UAAU;gBAE7C6C,QAAQ5D,OAAO4D,MAAM;gBACrBC,OAAO7D,OAAO6D,KAAK;gBACnBf,OAAOG;YACT,KACA,EAAE;YAEN,OAAO;gBACLpC,MAAM6C,OAAOI,KAAK,CAAC,AAACN,CAAAA,UAAU,CAAA,IAAKL,MAAMK,UAAUL,MAAMvC,GAAG,CAAChB;gBAC7DsB,OAAOiC;gBACPJ,MAAMS;gBACNO,WAAWL,OAAOf,MAAM;gBACxBqB,YAAYZ,KAAKa,IAAI,CAACP,OAAOf,MAAM,GAAGQ;YACxC;QACF;QAEA,MAAMe;YACJnE,MAAMoE,UAAU;YAChB,MAAM,EAAEtD,MAAMqB,KAAK,EAAEG,OAAO,EAAE,GAAG,MAAMV;YACvC5B,MAAMoC,GAAG,CAACD;YACV,OAAO;gBAAEU,SAASV,MAAMS,MAAM;gBAAEN,SAASA,QAAQM,MAAM;YAAC;QAC1D;QAEA,MAAMyB,QAAOtB,KAAa;YACxB,MAAMvC,MAAM,MAAMM;YAClB,MAAMoC,UAAUH,MAAMI,IAAI;YAE1B,IAAI,CAACD,SAAS;gBACZ,OAAOvD,cAAc;oBAAEmB,MAAMN;oBAAK8D,QAAQrE,OAAOqE,MAAM;gBAAC;YAC1D;YAEA,OAAO5E,aAAa;gBAClB4E,QAAQrE,OAAOqE,MAAM;gBACrBX,QAAQ/D,SAAS;oBACfkB,MAAMN;oBACNqD,QAAQ5D,OAAO4D,MAAM;oBACrBC,OAAO7D,OAAO6D,KAAK;oBACnBf,OAAOG;gBACT;YACF;QACF;IACF;AACF"}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import type { GroupedResults, SearchResult } from './types.js';
|
|
2
|
+
/** GET the grouped endpoint. Empty `q` returns the preset. Throws on a non-2xx. */
|
|
3
|
+
export declare function fetchSiteSearch<T = GroupedResults>(q: string, { endpoint, signal, }?: {
|
|
4
|
+
endpoint?: string;
|
|
5
|
+
signal?: AbortSignal;
|
|
6
|
+
}): Promise<T>;
|
|
7
|
+
/**
|
|
8
|
+
* Debounces queries and aborts the request it supersedes, so a slow response for "mal" can never
|
|
9
|
+
* overwrite the results for "maldives". Framework-free; `useSiteSearch` wraps it.
|
|
10
|
+
*/
|
|
11
|
+
export declare function createSearchRunner<T>({ debounceMs, fetcher, onError, onResult, }: {
|
|
12
|
+
debounceMs?: number;
|
|
13
|
+
fetcher: (q: string, signal: AbortSignal) => Promise<T>;
|
|
14
|
+
onError?: (error: unknown, q: string) => void;
|
|
15
|
+
onResult: (results: T, q: string) => void;
|
|
16
|
+
}): {
|
|
17
|
+
cancel: () => void;
|
|
18
|
+
run(q: string): void;
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* The shape `@foundrykit/hooks`' `useAdvancedSearch` and the advanced search bar take (structurally
|
|
22
|
+
* `SearchResult` from `@foundrykit/types`): `category` is the group's label, and the plugin's own
|
|
23
|
+
* fields ride in `metadata`.
|
|
24
|
+
*/
|
|
25
|
+
export type FlatSearchResult = {
|
|
26
|
+
category?: string;
|
|
27
|
+
description?: string;
|
|
28
|
+
href: string;
|
|
29
|
+
id: string;
|
|
30
|
+
metadata: Pick<SearchResult, 'collection' | 'docId' | 'group' | 'highlights' | 'icon'>;
|
|
31
|
+
title: string;
|
|
32
|
+
};
|
|
33
|
+
/**
|
|
34
|
+
* Grouped results as one list in group order, for a component that takes a flat list.
|
|
35
|
+
* `groups` sets the order and labels; groups it leaves out keep response order, labelled by slug.
|
|
36
|
+
*/
|
|
37
|
+
export declare function flattenResults(grouped: GroupedResults, groups?: {
|
|
38
|
+
label?: string;
|
|
39
|
+
slug: string;
|
|
40
|
+
}[]): FlatSearchResult[];
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/** GET the grouped endpoint. Empty `q` returns the preset. Throws on a non-2xx. */ export async function fetchSiteSearch(q, { endpoint = '/api/site-search', signal } = {}) {
|
|
2
|
+
const res = await fetch(`${endpoint}?q=${encodeURIComponent(q.trim())}`, {
|
|
3
|
+
signal
|
|
4
|
+
});
|
|
5
|
+
if (!res.ok) {
|
|
6
|
+
throw new Error(`site search failed: ${res.status}`);
|
|
7
|
+
}
|
|
8
|
+
return res.json();
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Debounces queries and aborts the request it supersedes, so a slow response for "mal" can never
|
|
12
|
+
* overwrite the results for "maldives". Framework-free; `useSiteSearch` wraps it.
|
|
13
|
+
*/ export function createSearchRunner({ debounceMs = 250, fetcher, onError, onResult }) {
|
|
14
|
+
let timer;
|
|
15
|
+
let controller;
|
|
16
|
+
const cancel = ()=>{
|
|
17
|
+
clearTimeout(timer);
|
|
18
|
+
controller?.abort();
|
|
19
|
+
};
|
|
20
|
+
return {
|
|
21
|
+
cancel,
|
|
22
|
+
run (q) {
|
|
23
|
+
cancel();
|
|
24
|
+
timer = setTimeout(async ()=>{
|
|
25
|
+
const current = new AbortController();
|
|
26
|
+
controller = current;
|
|
27
|
+
try {
|
|
28
|
+
const results = await fetcher(q, current.signal);
|
|
29
|
+
if (!current.signal.aborted) onResult(results, q);
|
|
30
|
+
} catch (error) {
|
|
31
|
+
if (!current.signal.aborted) onError?.(error, q);
|
|
32
|
+
}
|
|
33
|
+
}, debounceMs);
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Grouped results as one list in group order, for a component that takes a flat list.
|
|
39
|
+
* `groups` sets the order and labels; groups it leaves out keep response order, labelled by slug.
|
|
40
|
+
*/ export function flattenResults(grouped, groups = []) {
|
|
41
|
+
const order = [
|
|
42
|
+
...groups.map((group)=>group.slug),
|
|
43
|
+
...Object.keys(grouped).filter((slug)=>!groups.some((group)=>group.slug === slug))
|
|
44
|
+
];
|
|
45
|
+
return order.flatMap((slug)=>(grouped[slug] ?? []).map((result)=>({
|
|
46
|
+
category: groups.find((group)=>group.slug === slug)?.label ?? slug,
|
|
47
|
+
description: result.description,
|
|
48
|
+
href: result.href,
|
|
49
|
+
id: result.id,
|
|
50
|
+
metadata: {
|
|
51
|
+
collection: result.collection,
|
|
52
|
+
docId: result.docId,
|
|
53
|
+
group: result.group,
|
|
54
|
+
highlights: result.highlights,
|
|
55
|
+
icon: result.icon
|
|
56
|
+
},
|
|
57
|
+
title: result.title
|
|
58
|
+
})));
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
//# sourceMappingURL=searchClient.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/searchClient.ts"],"sourcesContent":["import type { GroupedResults, SearchResult } from './types.js';\n\n/** GET the grouped endpoint. Empty `q` returns the preset. Throws on a non-2xx. */\nexport async function fetchSiteSearch<T = GroupedResults>(\n q: string,\n {\n endpoint = '/api/site-search',\n signal,\n }: { endpoint?: string; signal?: AbortSignal } = {}\n): Promise<T> {\n const res = await fetch(`${endpoint}?q=${encodeURIComponent(q.trim())}`, {\n signal,\n });\n if (!res.ok) {\n throw new Error(`site search failed: ${res.status}`);\n }\n return res.json() as Promise<T>;\n}\n\n/**\n * Debounces queries and aborts the request it supersedes, so a slow response for \"mal\" can never\n * overwrite the results for \"maldives\". Framework-free; `useSiteSearch` wraps it.\n */\nexport function createSearchRunner<T>({\n debounceMs = 250,\n fetcher,\n onError,\n onResult,\n}: {\n debounceMs?: number;\n fetcher: (q: string, signal: AbortSignal) => Promise<T>;\n onError?: (error: unknown, q: string) => void;\n onResult: (results: T, q: string) => void;\n}) {\n let timer: ReturnType<typeof setTimeout> | undefined;\n let controller: AbortController | undefined;\n\n const cancel = () => {\n clearTimeout(timer);\n controller?.abort();\n };\n\n return {\n cancel,\n run(q: string) {\n cancel();\n timer = setTimeout(async () => {\n const current = new AbortController();\n controller = current;\n try {\n const results = await fetcher(q, current.signal);\n if (!current.signal.aborted) onResult(results, q);\n } catch (error) {\n if (!current.signal.aborted) onError?.(error, q);\n }\n }, debounceMs);\n },\n };\n}\n\n/**\n * The shape `@foundrykit/hooks`' `useAdvancedSearch` and the advanced search bar take (structurally\n * `SearchResult` from `@foundrykit/types`): `category` is the group's label, and the plugin's own\n * fields ride in `metadata`.\n */\nexport type FlatSearchResult = {\n category?: string;\n description?: string;\n href: string;\n id: string;\n metadata: Pick<\n SearchResult,\n 'collection' | 'docId' | 'group' | 'highlights' | 'icon'\n >;\n title: string;\n};\n\n/**\n * Grouped results as one list in group order, for a component that takes a flat list.\n * `groups` sets the order and labels; groups it leaves out keep response order, labelled by slug.\n */\nexport function flattenResults(\n grouped: GroupedResults,\n groups: { label?: string; slug: string }[] = []\n): FlatSearchResult[] {\n const order = [\n ...groups.map(group => group.slug),\n ...Object.keys(grouped).filter(\n slug => !groups.some(group => group.slug === slug)\n ),\n ];\n return order.flatMap(slug =>\n (grouped[slug] ?? []).map(result => ({\n category: groups.find(group => group.slug === slug)?.label ?? slug,\n description: result.description,\n href: result.href,\n id: result.id,\n metadata: {\n collection: result.collection,\n docId: result.docId,\n group: result.group,\n highlights: result.highlights,\n icon: result.icon,\n },\n title: result.title,\n }))\n );\n}\n"],"names":["fetchSiteSearch","q","endpoint","signal","res","fetch","encodeURIComponent","trim","ok","Error","status","json","createSearchRunner","debounceMs","fetcher","onError","onResult","timer","controller","cancel","clearTimeout","abort","run","setTimeout","current","AbortController","results","aborted","error","flattenResults","grouped","groups","order","map","group","slug","Object","keys","filter","some","flatMap","result","category","find","label","description","href","id","metadata","collection","docId","highlights","icon","title"],"mappings":"AAEA,iFAAiF,GACjF,OAAO,eAAeA,gBACpBC,CAAS,EACT,EACEC,WAAW,kBAAkB,EAC7BC,MAAM,EACsC,GAAG,CAAC,CAAC;IAEnD,MAAMC,MAAM,MAAMC,MAAM,GAAGH,SAAS,GAAG,EAAEI,mBAAmBL,EAAEM,IAAI,KAAK,EAAE;QACvEJ;IACF;IACA,IAAI,CAACC,IAAII,EAAE,EAAE;QACX,MAAM,IAAIC,MAAM,CAAC,oBAAoB,EAAEL,IAAIM,MAAM,EAAE;IACrD;IAC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KAAK;oBACnBhB,OAAOO,OAAOP,KAAK;oBACnBiB,YAAYV,OAAOU,UAAU;oBAC7BC,MAAMX,OAAOW,IAAI;gBACnB;gBACAC,OAAOZ,OAAOY,KAAK;YACrB,CAAA;AAEJ"}
|
package/dist/types.d.ts
CHANGED
|
@@ -7,10 +7,21 @@ import type { CollectionSlug, PayloadRequest } from 'payload';
|
|
|
7
7
|
* in, how its URLs are built, how strongly it ranks, and which documents are held back.
|
|
8
8
|
*/
|
|
9
9
|
export type SearchableCollection = {
|
|
10
|
+
/**
|
|
11
|
+
* A checkbox on the source collection (e.g. `excludeFromSearch`) that hides a document from
|
|
12
|
+
* search. Resolved once per projection build, so it costs nothing per request.
|
|
13
|
+
*/
|
|
14
|
+
excludeField?: string;
|
|
10
15
|
/** Documents whose slug appears here are never returned. */
|
|
11
16
|
excludeSlugs?: string[];
|
|
12
17
|
/** Group key this collection's results are filed under. Must match a configured group. */
|
|
13
18
|
group: string;
|
|
19
|
+
/**
|
|
20
|
+
* Build a result's URL from its raw index row, for URLs `path` + slug can't express (nested
|
|
21
|
+
* paths). Add the data it needs to the row with plugin-search's `beforeSync`. Return nothing to
|
|
22
|
+
* fall back to `path`.
|
|
23
|
+
*/
|
|
24
|
+
href?: (row: SearchDoc) => null | string | undefined;
|
|
14
25
|
/** Opaque icon token passed through to the consumer's own icon map. */
|
|
15
26
|
icon?: string;
|
|
16
27
|
/**
|
|
@@ -89,6 +100,8 @@ export type SearchPluginConfig = {
|
|
|
89
100
|
fields?: SearchField[];
|
|
90
101
|
fuzzy?: FuzzyOptions;
|
|
91
102
|
groups: SearchGroup[];
|
|
103
|
+
/** Slug of the collection plugin-search maintains (its `searchOverrides.slug`). */
|
|
104
|
+
indexCollection?: string;
|
|
92
105
|
/**
|
|
93
106
|
* Rate-limit the public track endpoint per client IP, using Payload's KV store. Default
|
|
94
107
|
* `{ limit: 30, window: 60 }`; `false` turns it off. Set `trustedProxies` (see
|
|
@@ -104,8 +117,13 @@ export type SearchPluginConfig = {
|
|
|
104
117
|
export type IndexedDoc = {
|
|
105
118
|
collection: string;
|
|
106
119
|
description?: string;
|
|
120
|
+
/** The source document's ID. */
|
|
121
|
+
docId: string;
|
|
107
122
|
group: string;
|
|
123
|
+
/** Set when the collection's `href` built one; otherwise `path` + slug. */
|
|
124
|
+
href?: string;
|
|
108
125
|
icon?: string;
|
|
126
|
+
/** `${collection}-${docId}`, unique across collections. */
|
|
109
127
|
id: string;
|
|
110
128
|
path: string;
|
|
111
129
|
slug: string;
|
|
@@ -114,7 +132,15 @@ export type IndexedDoc = {
|
|
|
114
132
|
};
|
|
115
133
|
export type SearchResult = {
|
|
116
134
|
collection: string;
|
|
135
|
+
description?: string;
|
|
136
|
+
/** The source document's ID, for querying the source collection (e.g. `where: { id: { in } }`). */
|
|
137
|
+
docId: string;
|
|
117
138
|
group: string;
|
|
139
|
+
/**
|
|
140
|
+
* Matched character ranges in `title`, as `[start, end)` pairs, for bolding the match. Absent on
|
|
141
|
+
* the empty-query preset.
|
|
142
|
+
*/
|
|
143
|
+
highlights?: [number, number][];
|
|
118
144
|
href: string;
|
|
119
145
|
icon?: string;
|
|
120
146
|
id: string;
|
|
@@ -123,6 +149,38 @@ export type SearchResult = {
|
|
|
123
149
|
title: string;
|
|
124
150
|
};
|
|
125
151
|
export type GroupedResults = Record<string, SearchResult[]>;
|
|
152
|
+
/** Options for a flat, paginated query: a results page, or ranked IDs for a filtered archive. */
|
|
153
|
+
export type SearchQuery = {
|
|
154
|
+
/** Only these collections. Default: every configured collection. */
|
|
155
|
+
collections?: string[];
|
|
156
|
+
/** Results per page, capped at 100. Default 10. */
|
|
157
|
+
limit?: number;
|
|
158
|
+
/** 1-based. Default 1. */
|
|
159
|
+
page?: number;
|
|
160
|
+
q: string;
|
|
161
|
+
};
|
|
162
|
+
export type PaginatedResults = {
|
|
163
|
+
docs: SearchResult[];
|
|
164
|
+
limit: number;
|
|
165
|
+
page: number;
|
|
166
|
+
totalDocs: number;
|
|
167
|
+
totalPages: number;
|
|
168
|
+
};
|
|
169
|
+
/** A row as it comes back from the plugin-search index collection. */
|
|
170
|
+
export type SearchDoc = {
|
|
171
|
+
[key: string]: unknown;
|
|
172
|
+
doc?: {
|
|
173
|
+
relationTo?: string;
|
|
174
|
+
value?: number | string;
|
|
175
|
+
} | null;
|
|
176
|
+
id?: number | string;
|
|
177
|
+
meta?: {
|
|
178
|
+
description?: null | string;
|
|
179
|
+
title?: null | string;
|
|
180
|
+
} | null;
|
|
181
|
+
slug?: null | string;
|
|
182
|
+
title?: null | string;
|
|
183
|
+
};
|
|
126
184
|
/** What the inspector reports, so "is this searchable" stops needing a code read. */
|
|
127
185
|
export type IndexReport = {
|
|
128
186
|
builtAt: null | string;
|
package/dist/types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/types.ts"],"sourcesContent":["import type { RateLimitOptions } from '@foundrykit/rate-limit';\nimport type { CollectionSlug, PayloadRequest } from 'payload';\n\n/**\n * A collection that should appear in site search, and how its results present.\n *\n * Everything a host project would otherwise hardcode lives here: which group a collection lands\n * in, how its URLs are built, how strongly it ranks, and which documents are held back.\n */\nexport type SearchableCollection = {\n /** Documents whose slug appears here are never returned. */\n excludeSlugs?: string[];\n /** Group key this collection's results are filed under. Must match a configured group. */\n group: string;\n /** Opaque icon token passed through to the consumer's own icon map. */\n icon?: string;\n /**\n * URL prefix for a result, without a trailing slash. Use an empty string for collections served\n * at the site root — it is deliberately distinct from \"unset\".\n */\n path: string;\n slug: CollectionSlug;\n /**\n * Ranking multiplier relative to other collections. 1 is neutral; raise it to float a\n * collection's matches above equally-good matches elsewhere.\n */\n weight?: number;\n};\n\n/** A presentation group that results are bucketed into. */\nexport type SearchGroup = {\n /** Human label. The plugin never renders it, but ships it so consumers stay consistent. */\n label: string;\n /** Maximum results returned for this group. Omit for no cap. */\n limit?: number;\n /** Sort position in the returned group list. Lower comes first. */\n order?: number;\n /** Whether this group appears in the empty-query preset list. */\n showWhenEmpty?: boolean;\n slug: string;\n};\n\n/**\n * A field on the indexed document to match against, with a relative weight.\n *\n * Weights are what stop the \"search for tuni, get unrelated results\" class of complaint: a title\n * hit and an incidental description hit stop being treated identically.\n */\nexport type SearchField = {\n name: string;\n weight?: number;\n};\n\nexport type FuzzyOptions = {\n /** Character distance a match may drift from the expected location. */\n distance?: number;\n /** Shortest run of characters that counts as a match. Guards against 1-2 letter noise. */\n minMatchCharLength?: number;\n /** 0 demands a perfect match, 1 matches anything. */\n threshold?: number;\n};\n\nexport type AnalyticsOptions = {\n /** Collection slug for stored events. */\n collectionSlug?: string;\n enabled?: boolean;\n /** Per-request gate, e.g. a consent check. Return false to record nothing. Default: always true. */\n isEnabled?: (req: PayloadRequest) => boolean | Promise<boolean>;\n /**\n * Days to keep events. Events older than this are pruned on write rather than accumulating an\n * unbounded log.\n */\n retentionDays?: number;\n /** Name of the cookie holding a visitor ID. Unset means visitor IDs are never read. */\n visitorCookie?: string;\n};\n\n/** `AnalyticsOptions` after defaults: `isEnabled` is always callable, `visitorCookie` stays optional. */\nexport type ResolvedAnalytics = {\n isEnabled: NonNullable<AnalyticsOptions['isEnabled']>;\n} & Omit<Required<AnalyticsOptions>, 'isEnabled' | 'visitorCookie'> &\n Pick<AnalyticsOptions, 'visitorCookie'>;\n\nexport type SearchPluginConfig = {\n analytics?: AnalyticsOptions | boolean;\n /** Milliseconds to hold the projected index in memory. */\n cacheTTL?: number;\n collections: SearchableCollection[];\n /**\n * Decode HTML entities in titles before returning them. Content migrated out of a CMS that\n * stored encoded markup will otherwise surface \"&\" as literal text wherever a result is\n * rendered as plain text.\n */\n decodeEntities?: boolean;\n disabled?: boolean;\n /** Fields matched against, with relative weights. */\n fields?: SearchField[];\n fuzzy?: FuzzyOptions;\n groups: SearchGroup[];\n /**\n * Rate-limit the public track endpoint per client IP, using Payload's KV store. Default\n * `{ limit: 30, window: 60 }`; `false` turns it off. Set `trustedProxies` (see\n * `@foundrykit/rate-limit`) or every visitor shares one bucket.\n */\n rateLimit?:\n | false\n | Partial<Pick<RateLimitOptions, 'limit' | 'window' | 'trustedProxies'>>;\n /** Restrict the reindex and inspect endpoints to admin users. */\n requireAdminForOperations?: boolean;\n /** Base path for the plugin's endpoints. */\n routePrefix?: string;\n};\n\n/** One document as held in the in-memory projection. */\nexport type IndexedDoc = {\n collection: string;\n description?: string;\n group: string;\n icon?: string;\n id: string;\n path: string;\n slug: string;\n title: string;\n weight: number;\n};\n\nexport type SearchResult = {\n collection: string;\n group: string;\n href: string;\n icon?: string;\n id: string;\n /** Fuse score, carried through so consumers can debug ranking. Lower is a better match. */\n score?: number;\n title: string;\n};\n\nexport type GroupedResults = Record<string, SearchResult[]>;\n\n/** What the inspector reports, so \"is this searchable\" stops needing a code read. */\nexport type IndexReport = {\n builtAt: null | string;\n collections: {\n excluded: number;\n indexed: number;\n slug: string;\n }[];\n skipped: {\n id: string;\n reason: string;\n slug: string;\n }[];\n total: number;\n};\n"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"sources":["../src/types.ts"],"sourcesContent":["import type { RateLimitOptions } from '@foundrykit/rate-limit';\nimport type { CollectionSlug, PayloadRequest } from 'payload';\n\n/**\n * A collection that should appear in site search, and how its results present.\n *\n * Everything a host project would otherwise hardcode lives here: which group a collection lands\n * in, how its URLs are built, how strongly it ranks, and which documents are held back.\n */\nexport type SearchableCollection = {\n /**\n * A checkbox on the source collection (e.g. `excludeFromSearch`) that hides a document from\n * search. Resolved once per projection build, so it costs nothing per request.\n */\n excludeField?: string;\n /** Documents whose slug appears here are never returned. */\n excludeSlugs?: string[];\n /** Group key this collection's results are filed under. Must match a configured group. */\n group: string;\n /**\n * Build a result's URL from its raw index row, for URLs `path` + slug can't express (nested\n * paths). Add the data it needs to the row with plugin-search's `beforeSync`. Return nothing to\n * fall back to `path`.\n */\n href?: (row: SearchDoc) => null | string | undefined;\n /** Opaque icon token passed through to the consumer's own icon map. */\n icon?: string;\n /**\n * URL prefix for a result, without a trailing slash. Use an empty string for collections served\n * at the site root — it is deliberately distinct from \"unset\".\n */\n path: string;\n slug: CollectionSlug;\n /**\n * Ranking multiplier relative to other collections. 1 is neutral; raise it to float a\n * collection's matches above equally-good matches elsewhere.\n */\n weight?: number;\n};\n\n/** A presentation group that results are bucketed into. */\nexport type SearchGroup = {\n /** Human label. The plugin never renders it, but ships it so consumers stay consistent. */\n label: string;\n /** Maximum results returned for this group. Omit for no cap. */\n limit?: number;\n /** Sort position in the returned group list. Lower comes first. */\n order?: number;\n /** Whether this group appears in the empty-query preset list. */\n showWhenEmpty?: boolean;\n slug: string;\n};\n\n/**\n * A field on the indexed document to match against, with a relative weight.\n *\n * Weights are what stop the \"search for tuni, get unrelated results\" class of complaint: a title\n * hit and an incidental description hit stop being treated identically.\n */\nexport type SearchField = {\n name: string;\n weight?: number;\n};\n\nexport type FuzzyOptions = {\n /** Character distance a match may drift from the expected location. */\n distance?: number;\n /** Shortest run of characters that counts as a match. Guards against 1-2 letter noise. */\n minMatchCharLength?: number;\n /** 0 demands a perfect match, 1 matches anything. */\n threshold?: number;\n};\n\nexport type AnalyticsOptions = {\n /** Collection slug for stored events. */\n collectionSlug?: string;\n enabled?: boolean;\n /** Per-request gate, e.g. a consent check. Return false to record nothing. Default: always true. */\n isEnabled?: (req: PayloadRequest) => boolean | Promise<boolean>;\n /**\n * Days to keep events. Events older than this are pruned on write rather than accumulating an\n * unbounded log.\n */\n retentionDays?: number;\n /** Name of the cookie holding a visitor ID. Unset means visitor IDs are never read. */\n visitorCookie?: string;\n};\n\n/** `AnalyticsOptions` after defaults: `isEnabled` is always callable, `visitorCookie` stays optional. */\nexport type ResolvedAnalytics = {\n isEnabled: NonNullable<AnalyticsOptions['isEnabled']>;\n} & Omit<Required<AnalyticsOptions>, 'isEnabled' | 'visitorCookie'> &\n Pick<AnalyticsOptions, 'visitorCookie'>;\n\nexport type SearchPluginConfig = {\n analytics?: AnalyticsOptions | boolean;\n /** Milliseconds to hold the projected index in memory. */\n cacheTTL?: number;\n collections: SearchableCollection[];\n /**\n * Decode HTML entities in titles before returning them. Content migrated out of a CMS that\n * stored encoded markup will otherwise surface \"&\" as literal text wherever a result is\n * rendered as plain text.\n */\n decodeEntities?: boolean;\n disabled?: boolean;\n /** Fields matched against, with relative weights. */\n fields?: SearchField[];\n fuzzy?: FuzzyOptions;\n groups: SearchGroup[];\n /** Slug of the collection plugin-search maintains (its `searchOverrides.slug`). */\n indexCollection?: string;\n /**\n * Rate-limit the public track endpoint per client IP, using Payload's KV store. Default\n * `{ limit: 30, window: 60 }`; `false` turns it off. Set `trustedProxies` (see\n * `@foundrykit/rate-limit`) or every visitor shares one bucket.\n */\n rateLimit?:\n | false\n | Partial<Pick<RateLimitOptions, 'limit' | 'window' | 'trustedProxies'>>;\n /** Restrict the reindex and inspect endpoints to admin users. */\n requireAdminForOperations?: boolean;\n /** Base path for the plugin's endpoints. */\n routePrefix?: string;\n};\n\n/** One document as held in the in-memory projection. */\nexport type IndexedDoc = {\n collection: string;\n description?: string;\n /** The source document's ID. */\n docId: string;\n group: string;\n /** Set when the collection's `href` built one; otherwise `path` + slug. */\n href?: string;\n icon?: string;\n /** `${collection}-${docId}`, unique across collections. */\n id: string;\n path: string;\n slug: string;\n title: string;\n weight: number;\n};\n\nexport type SearchResult = {\n collection: string;\n description?: string;\n /** The source document's ID, for querying the source collection (e.g. `where: { id: { in } }`). */\n docId: string;\n group: string;\n /**\n * Matched character ranges in `title`, as `[start, end)` pairs, for bolding the match. Absent on\n * the empty-query preset.\n */\n highlights?: [number, number][];\n href: string;\n icon?: string;\n id: string;\n /** Fuse score, carried through so consumers can debug ranking. Lower is a better match. */\n score?: number;\n title: string;\n};\n\nexport type GroupedResults = Record<string, SearchResult[]>;\n\n/** Options for a flat, paginated query: a results page, or ranked IDs for a filtered archive. */\nexport type SearchQuery = {\n /** Only these collections. Default: every configured collection. */\n collections?: string[];\n /** Results per page, capped at 100. Default 10. */\n limit?: number;\n /** 1-based. Default 1. */\n page?: number;\n q: string;\n};\n\nexport type PaginatedResults = {\n docs: SearchResult[];\n limit: number;\n page: number;\n totalDocs: number;\n totalPages: number;\n};\n\n/** A row as it comes back from the plugin-search index collection. */\nexport type SearchDoc = {\n [key: string]: unknown;\n doc?: { relationTo?: string; value?: number | string } | null;\n id?: number | string;\n meta?: { description?: null | string; title?: null | string } | null;\n slug?: null | string;\n title?: null | string;\n};\n\n/** What the inspector reports, so \"is this searchable\" stops needing a code read. */\nexport type IndexReport = {\n builtAt: null | string;\n collections: {\n excluded: number;\n indexed: number;\n slug: string;\n }[];\n skipped: {\n id: string;\n reason: string;\n slug: string;\n }[];\n total: number;\n};\n"],"names":[],"mappings":"AAkMA,mFAAmF,GACnF,WAaE"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@foundrykit/search-plugin",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"description": "A plugin for Payload CMS that provides a cached, grouped and ranked site search over the plugin-search index, with fuzzy matching, editor-controlled relevance and search analytics.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|