@foundrykit/search-plugin 0.2.1 → 0.2.3
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 +45 -29
- package/dist/analytics.js.map +1 -1
- package/dist/cache.js.map +1 -1
- package/dist/collections/SearchEvents.js.map +1 -1
- package/dist/components/SearchDashboard.d.ts +1 -2
- package/dist/components/SearchDashboard.js +2 -2
- package/dist/components/SearchDashboard.js.map +1 -1
- package/dist/components/useSearchHotkey.js.map +1 -1
- package/dist/decodeEntities.js.map +1 -1
- package/dist/endpoints/handlers.js +1 -0
- package/dist/endpoints/handlers.js.map +1 -1
- package/dist/exports/client.d.ts +2 -2
- package/dist/exports/client.js.map +1 -1
- package/dist/exports/rsc.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js.map +1 -1
- package/dist/options.js.map +1 -1
- package/dist/project.js.map +1 -1
- package/dist/rank.js.map +1 -1
- package/dist/resolve.js.map +1 -1
- package/dist/track.d.ts +5 -2
- package/dist/track.js +5 -2
- package/dist/track.js.map +1 -1
- package/dist/trackClient.js.map +1 -1
- package/dist/types.js.map +1 -1
- package/package.json +23 -34
package/README.md
CHANGED
|
@@ -33,8 +33,8 @@ pnpm add @foundrykit/search-plugin
|
|
|
33
33
|
Install it **after** `searchPlugin`, since it reads the collection that one creates.
|
|
34
34
|
|
|
35
35
|
```ts
|
|
36
|
-
import { searchPlugin as payloadSearchPlugin } from '@payloadcms/plugin-search'
|
|
37
|
-
import { searchPlugin } from '@foundrykit/search-plugin'
|
|
36
|
+
import { searchPlugin as payloadSearchPlugin } from '@payloadcms/plugin-search';
|
|
37
|
+
import { searchPlugin } from '@foundrykit/search-plugin';
|
|
38
38
|
|
|
39
39
|
export default buildConfig({
|
|
40
40
|
plugins: [
|
|
@@ -52,7 +52,13 @@ export default buildConfig({
|
|
|
52
52
|
|
|
53
53
|
collections: [
|
|
54
54
|
{ slug: 'regions', group: 'destinations', path: '/regions', weight: 3 },
|
|
55
|
-
{
|
|
55
|
+
{
|
|
56
|
+
slug: 'hotels',
|
|
57
|
+
group: 'stays',
|
|
58
|
+
path: '/hotels',
|
|
59
|
+
icon: 'bed',
|
|
60
|
+
weight: 2,
|
|
61
|
+
},
|
|
56
62
|
{
|
|
57
63
|
slug: 'pages',
|
|
58
64
|
group: 'pages',
|
|
@@ -65,35 +71,35 @@ export default buildConfig({
|
|
|
65
71
|
analytics: { retentionDays: 90 },
|
|
66
72
|
}),
|
|
67
73
|
],
|
|
68
|
-
})
|
|
74
|
+
});
|
|
69
75
|
```
|
|
70
76
|
|
|
71
77
|
### Endpoints
|
|
72
78
|
|
|
73
|
-
| Method | Path
|
|
74
|
-
|
|
|
75
|
-
| `GET`
|
|
76
|
-
| `POST` | `/api/site-search/reindex` | Rebuild the projection now. Returns counts.
|
|
77
|
-
| `GET`
|
|
78
|
-
| `POST` | `/api/site-search/track`
|
|
79
|
+
| Method | Path | Purpose |
|
|
80
|
+
| ------ | -------------------------- | ------------------------------------------------------------------- |
|
|
81
|
+
| `GET` | `/api/site-search?q=` | Grouped, ranked results. Empty `q` returns the preset. |
|
|
82
|
+
| `POST` | `/api/site-search/reindex` | Rebuild the projection now. Returns counts. |
|
|
83
|
+
| `GET` | `/api/site-search/inspect` | What is indexed, and why anything missing was skipped. |
|
|
84
|
+
| `POST` | `/api/site-search/track` | Record a settled search and its clicks. Only when analytics are on. |
|
|
79
85
|
|
|
80
86
|
Change the base with `routePrefix`. `reindex` and `inspect` require an authenticated user unless
|
|
81
87
|
you set `requireAdminForOperations: false`.
|
|
82
88
|
|
|
83
89
|
## Options
|
|
84
90
|
|
|
85
|
-
| Option
|
|
86
|
-
|
|
|
87
|
-
| `collections`
|
|
88
|
-
| `groups`
|
|
89
|
-
| `cacheTTL`
|
|
90
|
-
| `fields`
|
|
91
|
-
| `fuzzy`
|
|
92
|
-
| `decodeEntities`
|
|
93
|
-
| `analytics`
|
|
94
|
-
| `requireAdminForOperations` | `true`
|
|
95
|
-
| `routePrefix`
|
|
96
|
-
| `disabled`
|
|
91
|
+
| Option | Default | Notes |
|
|
92
|
+
| --------------------------- | ----------------------------------------------------------- | -------------------------------------------------------------------------- |
|
|
93
|
+
| `collections` | — | Required. Which collections are searchable, and how their results present. |
|
|
94
|
+
| `groups` | — | Required. Presentation buckets, with caps and empty-state opt-in. |
|
|
95
|
+
| `cacheTTL` | `60000` | Milliseconds to hold the projection. |
|
|
96
|
+
| `fields` | title 1, slug 0.4, description 0.2 | Fields matched, with relative weights. |
|
|
97
|
+
| `fuzzy` | `{ threshold: 0.35, distance: 100, minMatchCharLength: 3 }` | Fuse tuning. |
|
|
98
|
+
| `decodeEntities` | `true` | Decode HTML entities in titles. |
|
|
99
|
+
| `analytics` | `false` | `true`, or `{ retentionDays, collectionSlug }`. |
|
|
100
|
+
| `requireAdminForOperations` | `true` | Guard reindex and inspect. |
|
|
101
|
+
| `routePrefix` | `/site-search` | Base path for endpoints. |
|
|
102
|
+
| `disabled` | `false` | Bypass the plugin entirely. |
|
|
97
103
|
|
|
98
104
|
### A note on `minMatchCharLength`
|
|
99
105
|
|
|
@@ -117,9 +123,12 @@ projection time fixes all of them at once.
|
|
|
117
123
|
## Client helpers
|
|
118
124
|
|
|
119
125
|
```tsx
|
|
120
|
-
import {
|
|
126
|
+
import {
|
|
127
|
+
useSearchHotkey,
|
|
128
|
+
useIsAppleDevice,
|
|
129
|
+
} from '@foundrykit/search-plugin/client';
|
|
121
130
|
|
|
122
|
-
useSearchHotkey(open) // Cmd+K / Ctrl+K
|
|
131
|
+
useSearchHotkey(open); // Cmd+K / Ctrl+K
|
|
123
132
|
```
|
|
124
133
|
|
|
125
134
|
The hotkey is suppressed inside inputs, textareas, selects and contenteditable. That guard matters:
|
|
@@ -135,7 +144,7 @@ relationship is stored.
|
|
|
135
144
|
- **Recording.** The browser reports searches to `POST /api/site-search/track`. The `GET` search
|
|
136
145
|
endpoint no longer records anything.
|
|
137
146
|
- **`visitorCookie`** (opt-in). Name a cookie and the plugin stores its value on the event, so you
|
|
138
|
-
can tell repeat searchers apart. The plugin only
|
|
147
|
+
can tell repeat searchers apart. The plugin only _reads_ it; your site sets it, and should do so
|
|
139
148
|
only with consent.
|
|
140
149
|
- **`isEnabled(req)`**. Return `false` to skip recording for a request, e.g. when consent is absent.
|
|
141
150
|
- **Retention.** Events older than `retentionDays` (default **400**) are pruned on write, so the log
|
|
@@ -144,9 +153,16 @@ relationship is stored.
|
|
|
144
153
|
a migration (`payload migrate:create`).
|
|
145
154
|
|
|
146
155
|
```tsx
|
|
147
|
-
import { trackSearchEvent } from '@foundrykit/search-plugin/client'
|
|
148
|
-
|
|
149
|
-
trackSearchEvent({
|
|
156
|
+
import { trackSearchEvent } from '@foundrykit/search-plugin/client';
|
|
157
|
+
|
|
158
|
+
trackSearchEvent({
|
|
159
|
+
searchId,
|
|
160
|
+
query,
|
|
161
|
+
resultCount,
|
|
162
|
+
results,
|
|
163
|
+
pagePath,
|
|
164
|
+
source: 'dialog',
|
|
165
|
+
});
|
|
150
166
|
```
|
|
151
167
|
|
|
152
168
|
`trackSearchEvent(payload, endpoint = '/api/site-search/track')` uses `sendBeacon`, falls back to a
|
|
@@ -155,7 +171,7 @@ trackSearchEvent({ searchId, query, resultCount, results, pagePath, source: 'dia
|
|
|
155
171
|
## Dashboard
|
|
156
172
|
|
|
157
173
|
```tsx
|
|
158
|
-
import { SearchDashboard } from '@foundrykit/search-plugin/rsc'
|
|
174
|
+
import { SearchDashboard } from '@foundrykit/search-plugin/rsc';
|
|
159
175
|
```
|
|
160
176
|
|
|
161
177
|
A server component showing index counts, skipped documents **with reasons**, zero-result queries
|
package/dist/analytics.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/analytics.ts"],"sourcesContent":["const EMAIL = /[^\\s@]+@[^\\s@]+\\.[^\\s@]+/g
|
|
1
|
+
{"version":3,"sources":["../src/analytics.ts"],"sourcesContent":["const EMAIL = /[^\\s@]+@[^\\s@]+\\.[^\\s@]+/g;\nconst NUMBER_RUN = /\\+?\\d[\\d\\s().-]*\\d/g;\n\n/**\n * A search box's text as a stored term: whitespace-collapsed and lower-cased so \"Maldives \" and\n * \"maldives\" report as one term. Anything shaped like an email address or a phone number is\n * masked — people do paste contact details into search boxes, and those must not reach analytics.\n */\nexport function cleanSearchTerm(raw: string): string {\n return raw\n .replace(EMAIL, '[email]')\n .replace(NUMBER_RUN, run =>\n run.replace(/\\D/g, '').length >= 7 ? '[number]' : run\n )\n .replace(/\\s+/g, ' ')\n .trim()\n .toLowerCase()\n .slice(0, 100);\n}\n\nexport type QueryStat = {\n count: number;\n query: string;\n zeroResultCount: number;\n};\n\n/**\n * Aggregate raw events into the per-query counts the dashboard shows.\n *\n * Kept as a pure function so it is testable without a database, and so the dashboard has no query\n * logic of its own.\n */\nexport function aggregateEvents(\n events: { query: string; resultCount: number }[]\n): { topQueries: QueryStat[]; total: number; zeroResultQueries: QueryStat[] } {\n const byQuery = new Map<string, QueryStat>();\n\n for (const event of events) {\n const query = cleanSearchTerm(event.query);\n if (!query) {\n continue;\n }\n\n const stat = byQuery.get(query) ?? { count: 0, query, zeroResultCount: 0 };\n stat.count += 1;\n if (event.resultCount === 0) {\n stat.zeroResultCount += 1;\n }\n byQuery.set(query, stat);\n }\n\n const stats = [...byQuery.values()];\n const byCount = (a: QueryStat, b: QueryStat) =>\n b.count - a.count || a.query.localeCompare(b.query);\n\n return {\n topQueries: [...stats].sort(byCount),\n total: events.length,\n zeroResultQueries: stats\n .filter(stat => stat.zeroResultCount > 0)\n .sort(\n (a, b) =>\n b.zeroResultCount - a.zeroResultCount ||\n a.query.localeCompare(b.query)\n ),\n };\n}\n"],"names":["EMAIL","NUMBER_RUN","cleanSearchTerm","raw","replace","run","length","trim","toLowerCase","slice","aggregateEvents","events","byQuery","Map","event","query","stat","get","count","zeroResultCount","resultCount","set","stats","values","byCount","a","b","localeCompare","topQueries","sort","total","zeroResultQueries","filter"],"mappings":"AAAA,MAAMA,Q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":3,"sources":["../src/cache.ts"],"sourcesContent":["import type { IndexedDoc } from './types.js'
|
|
1
|
+
{"version":3,"sources":["../src/cache.ts"],"sourcesContent":["import type { IndexedDoc } from './types.js';\n\ntype Snapshot = {\n builtAt: number;\n docs: IndexedDoc[];\n};\n\n/**\n * Holds the projected index in memory for a TTL.\n *\n * The read path is otherwise one query per configured collection on every keystroke-driven\n * request. A short TTL removes that without the staleness of a full-page cache: the projection is\n * cheap to rebuild, and `invalidate` gives content changes an immediate path back to fresh data\n * rather than waiting the TTL out.\n */\nexport class SearchIndexCache {\n private snapshot: null | Snapshot = null;\n\n private ttl: number;\n\n constructor(ttlMs = 60_000) {\n this.ttl = ttlMs;\n }\n\n /** Timestamp of the held snapshot, for the inspector. */\n builtAt(): null | number {\n return this.snapshot?.builtAt ?? null;\n }\n\n configure(ttlMs: number): void {\n this.ttl = ttlMs;\n }\n\n get(): IndexedDoc[] | undefined {\n if (!this.snapshot) {\n return undefined;\n }\n if (Date.now() - this.snapshot.builtAt > this.ttl) {\n this.snapshot = null;\n return undefined;\n }\n return this.snapshot.docs;\n }\n\n invalidate(): void {\n this.snapshot = null;\n }\n\n set(docs: IndexedDoc[]): void {\n this.snapshot = { builtAt: Date.now(), docs };\n }\n}\n\nexport const searchIndexCache = new SearchIndexCache();\n"],"names":["SearchIndexCache","snapshot","ttl","ttlMs","builtAt","configure","get","undefined","Date","now","docs","invalidate","set","searchIndexCache"],"mappings":"AAOA;;;;;;;CAOC,GACD,OAAO,MAAMA;IACHC,WAA4B,KAAK;IAEjCC,IAAY;IAEpB,YAAYC,QAAQ,MAAM,CAAE;QAC1B,IAAI,CAACD,GAAG,GAAGC;IACb;IAEA,uDAAuD,GACvDC,UAAyB;QACvB,OAAO,IAAI,CAACH,QAAQ,EAAEG,WAAW;IACnC;IAEAC,UAAUF,KAAa,EAAQ;QAC7B,IAAI,CAACD,GAAG,GAAGC;IACb;IAEAG,MAAgC;QAC9B,IAAI,CAAC,IAAI,CAACL,QAAQ,EAAE;YAClB,OAAOM;QACT;QACA,IAAIC,KAAKC,GAAG,KAAK,IAAI,CAACR,QAAQ,CAACG,OAAO,GAAG,IAAI,CAACF,GAAG,EAAE;YACjD,IAAI,CAACD,QAAQ,GAAG;YAChB,OAAOM;QACT;QACA,OAAO,IAAI,CAACN,QAAQ,CAACS,IAAI;IAC3B;IAEAC,aAAmB;QACjB,IAAI,CAACV,QAAQ,GAAG;IAClB;IAEAW,IAAIF,IAAkB,EAAQ;QAC5B,IAAI,CAACT,QAAQ,GAAG;YAAEG,SAASI,KAAKC,GAAG;YAAIC;QAAK;IAC9C;AACF;AAEA,OAAO,MAAMG,mBAAmB,IAAIb,mBAAmB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/collections/SearchEvents.ts"],"sourcesContent":["import type { CollectionConfig } from 'payload'
|
|
1
|
+
{"version":3,"sources":["../../src/collections/SearchEvents.ts"],"sourcesContent":["import type { CollectionConfig } from 'payload';\n\nconst readOnly = { readOnly: true };\n\n/**\n * Stored search events: one row per settled search.\n *\n * Queries are behavioural data, so the stored term is masked (emails and phone numbers) before it\n * is written. A visitor ID is stored only when the host opts in with `visitorCookie`; without it\n * nothing here identifies a user. No IP and no user relationship are stored either way.\n *\n * Every search complaint on a project tends to arrive anecdotally — \"pages like careers don't\n * appear\", \"searching X shows things that don't match\". A zero-result log surfaces those before a\n * client has to notice.\n */\nexport const createSearchEventsCollection = ({\n slug = 'search-events',\n}: {\n slug?: string;\n} = {}): CollectionConfig => ({\n slug,\n access: {\n // Written by the tracking endpoint via overrideAccess, never by a public API caller.\n create: () => false,\n delete: ({ req }) => Boolean(req.user),\n read: ({ req }) => Boolean(req.user),\n update: () => false,\n },\n admin: {\n defaultColumns: ['query', 'resultCount', 'createdAt'],\n description:\n 'What visitors search for, what they click, and what returns nothing. Queries are masked for emails and phone numbers; a visitor ID is stored only if the site opts in.',\n group: 'Settings',\n useAsTitle: 'query',\n },\n fields: [\n {\n name: 'searchId',\n type: 'text',\n admin: readOnly,\n index: true,\n required: true,\n unique: true,\n },\n {\n name: 'query',\n type: 'text',\n admin: readOnly,\n index: true,\n required: true,\n },\n { name: 'source', type: 'text', admin: readOnly, index: true },\n {\n name: 'resultCount',\n type: 'number',\n index: true,\n admin: {\n description:\n 'Zero means the query returned nothing — the most useful signal here.',\n ...readOnly,\n },\n },\n { name: 'results', type: 'json', admin: readOnly },\n { name: 'clicks', type: 'json', admin: readOnly },\n { name: 'pagePath', type: 'text', admin: readOnly },\n { name: 'referrer', type: 'text', admin: readOnly },\n { name: 'utm', type: 'json', admin: readOnly },\n {\n name: 'device',\n type: 'select',\n admin: readOnly,\n options: ['mobile', 'tablet', 'desktop'],\n },\n { name: 'visitorId', type: 'text', admin: readOnly, index: true },\n ],\n timestamps: true,\n});\n"],"names":["readOnly","createSearchEventsCollection","slug","access","create","delete","req","Boolean","user","read","update","admin","defaultColumns","description","group","useAsTitle","fields","name","type","index","required","unique","options","timestamps"],"mappings":"AAEA,MAAMA,WAAW;IAAEA,UAAU;AAAK;AAElC;;;;;;;;;;CAUC,GACD,OAAO,MAAMC,+BAA+B,CAAC,EAC3CC,OAAO,eAAe,EAGvB,GAAG,CAAC,CAAC,GAAwB,CAAA;QAC5BA;QACAC,QAAQ;YACN,qFAAqF;YACrFC,QAAQ,IAAM;YACdC,QAAQ,CAAC,EAAEC,GAAG,EAAE,GAAKC,QAAQD,IAAIE,IAAI;YACrCC,MAAM,CAAC,EAAEH,GAAG,EAAE,GAAKC,QAAQD,IAAIE,IAAI;YACnCE,QAAQ,IAAM;QAChB;QACAC,OAAO;YACLC,gBAAgB;gBAAC;gBAAS;gBAAe;aAAY;YACrDC,aACE;YACFC,OAAO;YACPC,YAAY;QACd;QACAC,QAAQ;YACN;gBACEC,MAAM;gBACNC,MAAM;gBACNP,OAAOX;gBACPmB,OAAO;gBACPC,UAAU;gBACVC,QAAQ;YACV;YACA;gBACEJ,MAAM;gBACNC,MAAM;gBACNP,OAAOX;gBACPmB,OAAO;gBACPC,UAAU;YACZ;YACA;gBAAEH,MAAM;gBAAUC,MAAM;gBAAQP,OAAOX;gBAAUmB,OAAO;YAAK;YAC7D;gBACEF,MAAM;gBACNC,MAAM;gBACNC,OAAO;gBACPR,OAAO;oBACLE,aACE;oBACF,GAAGb,QAAQ;gBACb;YACF;YACA;gBAAEiB,MAAM;gBAAWC,MAAM;gBAAQP,OAAOX;YAAS;YACjD;gBAAEiB,MAAM;gBAAUC,MAAM;gBAAQP,OAAOX;YAAS;YAChD;gBAAEiB,MAAM;gBAAYC,MAAM;gBAAQP,OAAOX;YAAS;YAClD;gBAAEiB,MAAM;gBAAYC,MAAM;gBAAQP,OAAOX;YAAS;YAClD;gBAAEiB,MAAM;gBAAOC,MAAM;gBAAQP,OAAOX;YAAS;YAC7C;gBACEiB,MAAM;gBACNC,MAAM;gBACNP,OAAOX;gBACPsB,SAAS;oBAAC;oBAAU;oBAAU;iBAAU;YAC1C;YACA;gBAAEL,MAAM;gBAAaC,MAAM;gBAAQP,OAAOX;gBAAUmB,OAAO;YAAK;SACjE;QACDI,YAAY;IACd,CAAA,EAAG"}
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import type { Payload } from 'payload';
|
|
2
|
-
import React from 'react';
|
|
3
2
|
import type { SearchPluginConfig } from '../types.js';
|
|
4
3
|
/**
|
|
5
4
|
* Admin dashboard: what people search for, what returns nothing, and what is actually indexed.
|
|
@@ -10,4 +9,4 @@ import type { SearchPluginConfig } from '../types.js';
|
|
|
10
9
|
export declare function SearchDashboard({ config, payload, }: {
|
|
11
10
|
config: SearchPluginConfig;
|
|
12
11
|
payload: Payload;
|
|
13
|
-
}): Promise<
|
|
12
|
+
}): Promise<import("react").JSX.Element>;
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
|
|
2
|
-
import React from 'react';
|
|
3
2
|
import { aggregateEvents } from '../analytics.js';
|
|
4
3
|
import { searchIndexCache } from '../cache.js';
|
|
5
4
|
import { resolveAnalytics } from '../options.js';
|
|
@@ -110,7 +109,8 @@ import { createSearchService } from '../resolve.js';
|
|
|
110
109
|
/*#__PURE__*/ _jsx("code", {
|
|
111
110
|
children: "analytics"
|
|
112
111
|
}),
|
|
113
|
-
|
|
112
|
+
' ',
|
|
113
|
+
"option to record what visitors search for and which queries return nothing."
|
|
114
114
|
]
|
|
115
115
|
})
|
|
116
116
|
}),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/components/SearchDashboard.tsx"],"sourcesContent":["import type { Payload } from 'payload'
|
|
1
|
+
{"version":3,"sources":["../../src/components/SearchDashboard.tsx"],"sourcesContent":["import type { Payload } from 'payload';\n\nimport { aggregateEvents } from '../analytics.js';\nimport { searchIndexCache } from '../cache.js';\nimport { resolveAnalytics } from '../options.js';\nimport { createSearchService } from '../resolve.js';\nimport type { SearchPluginConfig } from '../types.js';\n\n/**\n * Admin dashboard: what people search for, what returns nothing, and what is actually indexed.\n *\n * A server component so it can read the index and the event log directly. It renders counts only —\n * the aggregation lives in `aggregateEvents` so it stays testable without a database.\n */\nexport async function SearchDashboard({\n config,\n payload,\n}: {\n config: SearchPluginConfig;\n payload: Payload;\n}) {\n const analytics = resolveAnalytics(config.analytics);\n const report = await createSearchService({\n cache: searchIndexCache,\n config,\n payload,\n }).inspect();\n\n let topQueries: ReturnType<typeof aggregateEvents>['topQueries'] = [];\n let zeroResultQueries: ReturnType<\n typeof aggregateEvents\n >['zeroResultQueries'] = [];\n let totalSearches = 0;\n\n if (analytics.enabled) {\n const events = await payload.find({\n collection: analytics.collectionSlug as never,\n depth: 0,\n limit: 0,\n pagination: false,\n });\n\n const aggregated = aggregateEvents(\n events.docs as unknown as { query: string; resultCount: number }[]\n );\n topQueries = aggregated.topQueries.slice(0, 20);\n zeroResultQueries = aggregated.zeroResultQueries.slice(0, 20);\n totalSearches = aggregated.total;\n }\n\n return (\n <div className='search-dashboard'>\n <h2>Search</h2>\n\n <section>\n <h3>Index</h3>\n <p>\n {report.total} documents indexed\n {report.builtAt ? ` — built ${report.builtAt}` : ''}\n </p>\n <table>\n <thead>\n <tr>\n <th>Collection</th>\n <th>Indexed</th>\n <th>Skipped</th>\n </tr>\n </thead>\n <tbody>\n {report.collections.map(row => (\n <tr key={row.slug}>\n <td>{row.slug}</td>\n <td>{row.indexed}</td>\n <td>{row.excluded}</td>\n </tr>\n ))}\n </tbody>\n </table>\n </section>\n\n {report.skipped.length > 0 && (\n <section>\n <h3>Skipped documents</h3>\n {/* Reasons, not just a count: an inventory tells you nothing when the document you care\n about is the missing one. */}\n <ul>\n {report.skipped.slice(0, 50).map(row => (\n <li key={`${row.slug}-${row.id}`}>\n {row.slug} #{row.id} — {row.reason}\n </li>\n ))}\n </ul>\n </section>\n )}\n\n {!analytics.enabled && (\n <section>\n <p>\n Search analytics are disabled. Enable the <code>analytics</code>{' '}\n option to record what visitors search for and which queries return\n nothing.\n </p>\n </section>\n )}\n\n {analytics.enabled && (\n <>\n <section>\n <h3>Zero-result queries</h3>\n <p>\n Searches that found nothing — the shortest path to a content or\n relevance gap.\n </p>\n {zeroResultQueries.length === 0 ? (\n <p>None recorded.</p>\n ) : (\n <ol>\n {zeroResultQueries.map(stat => (\n <li key={stat.query}>\n {stat.query} — {stat.zeroResultCount}\n </li>\n ))}\n </ol>\n )}\n </section>\n\n <section>\n <h3>Top queries</h3>\n <p>{totalSearches} searches recorded.</p>\n {topQueries.length === 0 ? (\n <p>None recorded.</p>\n ) : (\n <ol>\n {topQueries.map(stat => (\n <li key={stat.query}>\n {stat.query} — {stat.count}\n </li>\n ))}\n </ol>\n )}\n </section>\n </>\n )}\n </div>\n );\n}\n"],"names":["aggregateEvents","searchIndexCache","resolveAnalytics","createSearchService","SearchDashboard","config","payload","analytics","report","cache","inspect","topQueries","zeroResultQueries","totalSearches","enabled","events","find","collection","collectionSlug","depth","limit","pagination","aggregated","docs","slice","total","div","className","h2","section","h3","p","builtAt","table","thead","tr","th","tbody","collections","map","row","td","slug","indexed","excluded","skipped","length","ul","li","id","reason","code","ol","stat","query","zeroResultCount","count"],"mappings":";AAEA,SAASA,eAAe,QAAQ,kBAAkB;AAClD,SAASC,gBAAgB,QAAQ,cAAc;AAC/C,SAASC,gBAAgB,QAAQ,gBAAgB;AACjD,SAASC,mBAAmB,QAAQ,gBAAgB;AAGpD;;;;;CAKC,GACD,OAAO,eAAeC,gBAAgB,EACpCC,MAAM,EACNC,OAAO,EAIR;IACC,MAAMC,YAAYL,iBAAiBG,OAAOE,SAAS;IACnD,MAAMC,SAAS,MAAML,oBAAoB;QACvCM,OAAOR;QACPI;QACAC;IACF,GAAGI,OAAO;IAEV,IAAIC,aAA+D,EAAE;IACrE,IAAIC,oBAEqB,EAAE;IAC3B,IAAIC,gBAAgB;IAEpB,IAAIN,UAAUO,OAAO,EAAE;QACrB,MAAMC,SAAS,MAAMT,QAAQU,IAAI,CAAC;YAChCC,YAAYV,UAAUW,cAAc;YACpCC,OAAO;YACPC,OAAO;YACPC,YAAY;QACd;QAEA,MAAMC,aAAatB,gBACjBe,OAAOQ,IAAI;QAEbZ,aAAaW,WAAWX,UAAU,CAACa,KAAK,CAAC,GAAG;QAC5CZ,oBAAoBU,WAAWV,iBAAiB,CAACY,KAAK,CAAC,GAAG;QAC1DX,gBAAgBS,WAAWG,KAAK;IAClC;IAEA,qBACE,MAACC;QAAIC,WAAU;;0BACb,KAACC;0BAAG;;0BAEJ,MAACC;;kCACC,KAACC;kCAAG;;kCACJ,MAACC;;4BACEvB,OAAOiB,KAAK;4BAAC;4BACbjB,OAAOwB,OAAO,GAAG,CAAC,SAAS,EAAExB,OAAOwB,OAAO,EAAE,GAAG;;;kCAEnD,MAACC;;0CACC,KAACC;0CACC,cAAA,MAACC;;sDACC,KAACC;sDAAG;;sDACJ,KAACA;sDAAG;;sDACJ,KAACA;sDAAG;;;;;0CAGR,KAACC;0CACE7B,OAAO8B,WAAW,CAACC,GAAG,CAACC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esContent":["'use client'
|
|
1
|
+
{"version":3,"sources":["../../src/components/useSearchHotkey.ts"],"sourcesContent":["'use client';\n\nimport { useEffect, useState } from 'react';\n\n/**\n * True when the event originated inside something the user is typing into.\n *\n * A search shortcut must not fire while the user is in an input, textarea or contenteditable. This\n * matters specifically for Ctrl+K, which is Lexical's \"insert link\" binding — and Lexical is\n * Payload's own editor, so a plugin that got this wrong would break the admin panel it ships with.\n */\nexport function isEditableTarget(target: EventTarget | null): boolean {\n if (!(target instanceof HTMLElement)) {\n return false;\n }\n if (target.isContentEditable) {\n return true;\n }\n\n const tag = target.tagName;\n if (tag === 'TEXTAREA' || tag === 'SELECT') {\n return true;\n }\n\n if (tag === 'INPUT') {\n // Checkboxes, radios and buttons are inputs but not text entry, so the shortcut is still\n // welcome while they are focused.\n const { type } = target as HTMLInputElement;\n return ![\n 'button',\n 'checkbox',\n 'file',\n 'radio',\n 'range',\n 'reset',\n 'submit',\n ].includes(type);\n }\n\n return false;\n}\n\n/** Cmd+K (macOS) / Ctrl+K (Windows, Linux) to open search from anywhere on the page. */\nexport function useSearchHotkey(onOpen: () => void): void {\n useEffect(() => {\n const onKeyDown = (event: KeyboardEvent) => {\n if (event.key.toLowerCase() !== 'k') {\n return;\n }\n if (!(event.metaKey || event.ctrlKey)) {\n return;\n }\n if (event.altKey || event.shiftKey) {\n return;\n }\n if (isEditableTarget(event.target)) {\n return;\n }\n\n event.preventDefault();\n onOpen();\n };\n\n document.addEventListener('keydown', onKeyDown);\n return () => document.removeEventListener('keydown', onKeyDown);\n }, [onOpen]);\n}\n\n/**\n * Whether to render the hint as \"⌘\" or \"Ctrl\". Resolved after mount so server and client markup\n * match and React does not warn on hydration.\n */\nexport function useIsAppleDevice(): boolean {\n const [isApple, setIsApple] = useState(false);\n\n useEffect(() => {\n setIsApple(/mac|iphone|ipad|ipod/i.test(navigator.platform));\n }, []);\n\n return isApple;\n}\n"],"names":["useEffect","useState","isEditableTarget","target","HTMLElement","isContentEditable","tag","tagName","type","includes","useSearchHotkey","onOpen","onKeyDown","event","key","toLowerCase","metaKey","ctrlKey","altKey","shiftKey","preventDefault","document","addEventListener","removeEventListener","useIsAppleDevice","isApple","setIsApple","test","navigator","platform"],"mappings":"AAAA;AAEA,SAASA,SAAS,EAAEC,QAAQ,QAAQ,QAAQ;AAE5C;;;;;;CAMC,GACD,OAAO,SAASC,iBAAiBC,MAA0B;IACzD,IAAI,CAAEA,CAAAA,kBAAkBC,WAAU,GAAI;QACpC,OAAO;IACT;IACA,IAAID,OAAOE,iBAAiB,EAAE;QAC5B,OAAO;IACT;IAEA,MAAMC,MAAMH,OAAOI,OAAO;IAC1B,IAAID,QAAQ,cAAcA,QAAQ,UAAU;QAC1C,OAAO;IACT;IAEA,IAAIA,QAAQ,SAAS;QACnB,yFAAyF;QACzF,kCAAkC;QAClC,MAAM,EAAEE,IAAI,EAAE,GAAGL;QACjB,OAAO,CAAC;YACN;YACA;YACA;YACA;YACA;YACA;YACA;SACD,CAACM,QAAQ,CAACD;IACb;IAEA,OAAO;AACT;AAEA,sFAAsF,GACtF,OAAO,SAASE,gBAAgBC,MAAkB;IAChDX,UAAU;QACR,MAAMY,YAAY,CAACC;YACjB,IAAIA,MAAMC,GAAG,CAACC,WAAW,OAAO,KAAK;gBACnC;YACF;YACA,IAAI,CAAEF,CAAAA,MAAMG,OAAO,IAAIH,MAAMI,OAAO,AAAD,GAAI;gBACrC;YACF;YACA,IAAIJ,MAAMK,MAAM,IAAIL,MAAMM,QAAQ,EAAE;gBAClC;YACF;YACA,IAAIjB,iBAAiBW,MAAMV,MAAM,GAAG;gBAClC;YACF;YAEAU,MAAMO,cAAc;YACpBT;QACF;QAEAU,SAASC,gBAAgB,CAAC,WAAWV;QACrC,OAAO,IAAMS,SAASE,mBAAmB,CAAC,WAAWX;IACvD,GAAG;QAACD;KAAO;AACb;AAEA;;;CAGC,GACD,OAAO,SAASa;IACd,MAAM,CAACC,SAASC,WAAW,GAAGzB,SAAS;IAEvCD,UAAU;QACR0B,WAAW,wBAAwBC,IAAI,CAACC,UAAUC,QAAQ;IAC5D,GAAG,EAAE;IAEL,OAAOJ;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/decodeEntities.ts"],"sourcesContent":["/**\n * Decode the HTML entities that survive in titles and labels migrated out of a CMS which stored\n * them encoded.\n *\n * Rich-text renderers decode on the way out, so a body reads correctly while a plain-text surface\n * — a search result, a filter label, a map pin — shows the literal \"&\". This is why the same\n * stored string can look right on a page and wrong in search.\n *\n * Server-safe: no DOM dependency. `&` is decoded LAST, deliberately — decoding it first would\n * feed the output of one replacement into the next and turn a literal \"&pound;\" into \"£\".\n */\nexport const decodeEntities = (value?: null | string): string =>\n (value || '')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/"/g, '\"')\n .replace(/�?39;|'|’|’/g, \"'\")\n .replace(/‘|‘/g, \"'\")\n .replace(/“|“/g, '\"')\n .replace(/”|”/g, '\"')\n .replace(/–|–/g, '–')\n .replace(/—|—/g, '—')\n .replace(/…|…/g, '…')\n .replace(/£|£/g, '£')\n .replace(/€|€/g, '€')\n .replace(/ | /g, ' ')\n .replace(/&/g, '&')
|
|
1
|
+
{"version":3,"sources":["../src/decodeEntities.ts"],"sourcesContent":["/**\n * Decode the HTML entities that survive in titles and labels migrated out of a CMS which stored\n * them encoded.\n *\n * Rich-text renderers decode on the way out, so a body reads correctly while a plain-text surface\n * — a search result, a filter label, a map pin — shows the literal \"&\". This is why the same\n * stored string can look right on a page and wrong in search.\n *\n * Server-safe: no DOM dependency. `&` is decoded LAST, deliberately — decoding it first would\n * feed the output of one replacement into the next and turn a literal \"&pound;\" into \"£\".\n */\nexport const decodeEntities = (value?: null | string): string =>\n (value || '')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/"/g, '\"')\n .replace(/�?39;|'|’|’/g, \"'\")\n .replace(/‘|‘/g, \"'\")\n .replace(/“|“/g, '\"')\n .replace(/”|”/g, '\"')\n .replace(/–|–/g, '–')\n .replace(/—|—/g, '—')\n .replace(/…|…/g, '…')\n .replace(/£|£/g, '£')\n .replace(/€|€/g, '€')\n .replace(/ | /g, ' ')\n .replace(/&/g, '&');\n"],"names":["decodeEntities","value","replace"],"mappings":"AAAA;;;;;;;;;;CAUC,GACD,OAAO,MAAMA,iBAAiB,CAACC,QAC7B,AAACA,CAAAA,SAAS,EAAC,EACRC,OAAO,CAAC,SAAS,KACjBA,OAAO,CAAC,SAAS,KACjBA,OAAO,CAAC,WAAW,KACnBA,OAAO,CAAC,mCAAmC,KAC3CA,OAAO,CAAC,oBAAoB,KAC5BA,OAAO,CAAC,oBAAoB,KAC5BA,OAAO,CAAC,oBAAoB,KAC5BA,OAAO,CAAC,oBAAoB,KAC5BA,OAAO,CAAC,oBAAoB,KAC5BA,OAAO,CAAC,qBAAqB,KAC7BA,OAAO,CAAC,mBAAmB,KAC3BA,OAAO,CAAC,mBAAmB,KAC3BA,OAAO,CAAC,kBAAkB,KAC1BA,OAAO,CAAC,UAAU,KAAK"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/endpoints/handlers.ts"],"sourcesContent":["import type { PayloadHandler, PayloadRequest } from 'payload'
|
|
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","undefined","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,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AEA,MAAME,QAAQxC,kBAAkB,MAAMY,IAAIV,IAAI,KAAKuC,MAAM,IAAM;QAC/D,IAAI,CAACD,OAAO;YACV,OAAOtC,KAAK;gBAAEQ,OAAO;YAAkB,GAAG;QAC5C;QAEA,MAAMgC,aAAaP,UAAUQ,aAAa;QAC1C,MAAMC,YAAYF,aACd9B,IAAIJ,OAAO,CACRa,GAAG,CAAC,WACHwB,MAAM,KACPC,IAAIC,CAAAA,IAAKA,EAAEC,IAAI,GAAGH,KAAK,CAAC,MACxBI,KAAK,CAAC,CAACC,KAAK,GAAKA,SAASR,aAAa,CAAC,EAAE,EACzCS,MAAM,GAAG,OACbC;QAEJ,+EAA+E;QAC/E,MAAMC,OAAO,AAACzC,CAAAA,IAAIJ,OAAO,CAACa,GAAG,CAAC,WAAW,EAAC,EAAGwB,KAAK,CAAC,IAAI,CAAC,EAAE;QAC1D,IAAIL,MAAMc,QAAQ,KAAKD,MAAM;YAC3Bb,MAAMc,QAAQ,GAAGF;QACnB;QAEA,IAAI;YACF,MAAMnD,kBAAkB;gBACtBsD,gBAAgBpB,UAAUoB,cAAc;gBACxCC,QAAQ1D,SAASyC;gBACjBC;gBACAzB,SAASH,IAAIG,OAAO;gBACpBH;gBACA6C,eAAetB,UAAUsB,aAAa;gBACtCb;YACF;QACF,EAAE,OAAOlC,OAAO;YACdE,IAAIG,OAAO,CAAC2C,MAAM,CAAChD,KAAK,CAAC;gBACvBiD,KAAKjD;gBACLkD,KAAK;YACP;QACF;QAEA,OAAO1D,KAAK;YAAEoC,SAAS;QAAK;IAC9B,EAAE"}
|
package/dist/exports/client.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export { isEditableTarget, useIsAppleDevice, useSearchHotkey } from '../components/useSearchHotkey.js';
|
|
2
|
-
export { trackSearchEvent } from '../trackClient.js';
|
|
1
|
+
export { isEditableTarget, useIsAppleDevice, useSearchHotkey, } from '../components/useSearchHotkey.js';
|
|
3
2
|
export type { ShownResult, TrackPayload } from '../track.js';
|
|
3
|
+
export { trackSearchEvent } from '../trackClient.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/exports/client.ts"],"sourcesContent":["export {
|
|
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"}
|
package/dist/exports/rsc.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/exports/rsc.ts"],"sourcesContent":["export { SearchDashboard } from '../components/SearchDashboard.js'
|
|
1
|
+
{"version":3,"sources":["../../src/exports/rsc.ts"],"sourcesContent":["export { SearchDashboard } from '../components/SearchDashboard.js';\n"],"names":["SearchDashboard"],"mappings":"AAAA,SAASA,eAAe,QAAQ,mCAAmC"}
|
package/dist/index.d.ts
CHANGED
|
@@ -4,10 +4,10 @@ export { aggregateEvents, cleanSearchTerm } from './analytics.js';
|
|
|
4
4
|
export { SearchIndexCache, searchIndexCache } from './cache.js';
|
|
5
5
|
export { decodeEntities } from './decodeEntities.js';
|
|
6
6
|
export { hrefFor, projectDocs } from './project.js';
|
|
7
|
-
export { DEFAULT_FIELDS, DEFAULT_FUZZY, groupResults, presetResults, rankDocs } from './rank.js';
|
|
7
|
+
export { DEFAULT_FIELDS, DEFAULT_FUZZY, groupResults, presetResults, rankDocs, } from './rank.js';
|
|
8
8
|
export { createSearchService } from './resolve.js';
|
|
9
|
-
export { deviceOf, isBot, parseTrackPayload, recordSearchEvent } from './track.js';
|
|
10
9
|
export type { ShownResult, TrackPayload } from './track.js';
|
|
10
|
+
export { deviceOf, isBot, parseTrackPayload, recordSearchEvent, } from './track.js';
|
|
11
11
|
export type * from './types.js';
|
|
12
12
|
/**
|
|
13
13
|
* Cached, grouped and ranked site search over the `@payloadcms/plugin-search` index.
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { Config } from 'payload'
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { Config } from 'payload';\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 { assertConfig, resolveAnalytics } 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 { createSearchService } 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 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: 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 handler: createTrackHandler({ config: pluginOptions }),\n method: 'post' as const,\n path: `${prefix}/track`,\n },\n ]\n : []),\n ];\n\n return config;\n };\n"],"names":["searchIndexCache","createSearchEventsCollection","createInspectHandler","createReindexHandler","createSearchHandler","createTrackHandler","assertConfig","resolveAnalytics","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","enabled","collections","slug","collectionSlug","endpoints","handler","cache","method","path"],"mappings":"AACA,SAASA,gBAAgB,QAAQ,aAAa;AAC9C,SAASC,4BAA4B,QAAQ,gCAAgC;AAC7E,SACEC,oBAAoB,EACpBC,oBAAoB,EACpBC,mBAAmB,EACnBC,kBAAkB,QACb,0BAA0B;AACjC,SAASC,YAAY,EAAEC,gBAAgB,QAAQ,eAAe;AAG9D,SAASC,eAAe,EAAEC,eAAe,QAAQ,iBAAiB;AAClE,SAASC,gBA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B;gBACE;oBACEK,SAASnC,mBAAmB;wBAAEqB,QAAQD;oBAAc;oBACpDiB,QAAQ;oBACRC,MAAM,GAAGd,OAAO,MAAM,CAAC;gBACzB;aACD,GACD,EAAE;SACP;QAED,OAAOH;IACT,EAAE"}
|
package/dist/options.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/options.ts"],"sourcesContent":["import type { ResolvedAnalytics, SearchPluginConfig } from './types.js'
|
|
1
|
+
{"version":3,"sources":["../src/options.ts"],"sourcesContent":["import type { ResolvedAnalytics, SearchPluginConfig } from './types.js';\n\nexport const DEFAULT_ANALYTICS: ResolvedAnalytics = {\n collectionSlug: 'search-events',\n enabled: false,\n isEnabled: () => true,\n // Long enough to compare a full year, short enough that the log stays bounded and the\n // retention question is answered up front rather than by accumulation.\n retentionDays: 400,\n};\n\n/** Normalise the `analytics` option, which accepts a boolean shorthand. */\nexport const resolveAnalytics = (\n analytics: SearchPluginConfig['analytics']\n): ResolvedAnalytics => {\n if (analytics === undefined) {\n return DEFAULT_ANALYTICS;\n }\n if (typeof analytics === 'boolean') {\n return { ...DEFAULT_ANALYTICS, enabled: analytics };\n }\n return {\n collectionSlug:\n analytics.collectionSlug ?? DEFAULT_ANALYTICS.collectionSlug,\n enabled: analytics.enabled ?? true,\n isEnabled: analytics.isEnabled ?? DEFAULT_ANALYTICS.isEnabled,\n retentionDays: analytics.retentionDays ?? DEFAULT_ANALYTICS.retentionDays,\n visitorCookie: analytics.visitorCookie,\n };\n};\n\n/**\n * Fail loudly on a misconfiguration rather than silently returning nothing.\n *\n * A collection pointing at a group that does not exist is the most likely mistake, and its symptom\n * — results vanishing — is indistinguishable from an empty index.\n */\nexport function assertConfig(config: SearchPluginConfig): void {\n const groups = new Set(config.groups.map(group => group.slug));\n\n for (const entry of config.collections) {\n if (!groups.has(entry.group)) {\n throw new Error(\n `search-plugin: collection \"${String(entry.slug)}\" is assigned to group \"${entry.group}\", which is not configured.`\n );\n }\n }\n\n const duplicateGroup = config.groups.find(\n (group, index) =>\n config.groups.findIndex(other => other.slug === group.slug) !== index\n );\n if (duplicateGroup) {\n throw new Error(`search-plugin: duplicate group \"${duplicateGroup.slug}\".`);\n }\n}\n"],"names":["DEFAULT_ANALYTICS","collectionSlug","enabled","isEnabled","retentionDays","resolveAnalytics","analytics","undefined","visitorCookie","assertConfig","config","groups","Set","map","group","slug","entry","collections","has","Error","String","duplicateGroup","find","index","findIndex","other"],"mappings":"AAEA,OAAO,MAAMA,oBAAuC;IAClDC,gBAAgB;IAChBC,SAAS;IACTC,WAAW,IAAM;IACjB,sFAAsF;IACtF,uEAAuE;IACvEC,eAAe;AACjB,EAAE;AAEF,yEAAyE,GACzE,OAAO,MAAMC,mBAAmB,CAC9BC;IAEA,IAAIA,cAAcC,WAAW;QAC3B,OAAOP;IACT;IACA,IAAI,OAAOM,cAAc,WAAW;QAClC,OAAO;YAAE,GAAGN,iBAAiB;YAAEE,SAASI;QAAU;IACpD;IACA,OAAO;QACLL,gBACEK,UAAUL,cAAc,IAAID,kBAAkBC,cAAc;QAC9DC,SAASI,UAAUJ,OAAO,IAAI;QAC9BC,WAAWG,UAAUH,SAAS,IAAIH,kBAAkBG,SAAS;QAC7DC,eAAeE,UAAUF,aAAa,IAAIJ,kBAAkBI,aAAa;QACzEI,eAAeF,UAAUE,aAAa;IACxC;AACF,EAAE;AAEF;;;;;CAKC,GACD,OAAO,SAASC,aAAaC,MAA0B;IACrD,MAAMC,SAAS,IAAIC,IAAIF,OAAOC,MAAM,CAACE,GAAG,CAACC,CAAAA,QAASA,MAAMC,IAAI;IAE5D,KAAK,MAAMC,SAASN,OAAOO,WAAW,CAAE;QACtC,IAAI,CAACN,OAAOO,GAAG,CAACF,MAAMF,KAAK,GAAG;YAC5B,MAAM,IAAIK,MACR,CAAC,2BAA2B,EAAEC,OAAOJ,MAAMD,IAAI,EAAE,wBAAwB,EAAEC,MAAMF,KAAK,CAAC,2BAA2B,CAAC;QAEvH;IACF;IAEA,MAAMO,iBAAiBX,OAAOC,MAAM,CAACW,IAAI,CACvC,CAACR,OAAOS,QACNb,OAAOC,MAAM,CAACa,SAAS,CAACC,CAAAA,QAASA,MAAMV,IAAI,KAAKD,MAAMC,IAAI,MAAMQ;IAEpE,IAAIF,gBAAgB;QAClB,MAAM,IAAIF,MAAM,CAAC,gCAAgC,EAAEE,eAAeN,IAAI,CAAC,EAAE,CAAC;IAC5E;AACF"}
|
package/dist/project.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/project.ts"],"sourcesContent":["import
|
|
1
|
+
{"version":3,"sources":["../src/project.ts"],"sourcesContent":["import { decodeEntities } from './decodeEntities.js';\nimport type { IndexedDoc, SearchableCollection } from './types.js';\n\n/** A row as it comes back from the plugin-search `search` collection. */\nexport type SearchDoc = {\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\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 rows,\n}: {\n collections: SearchableCollection[];\n decode?: boolean;\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 docs.push({\n id: `${collection}-${id}`,\n collection,\n description: decode\n ? decodeEntities(row.meta?.description)\n : (row.meta?.description ?? undefined),\n group: config.group,\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 => `${doc.path}/${doc.slug}`;\n"],"names":["decodeEntities","projectDocs","collections","decode","rows","byslug","Map","map","entry","slug","docs","skipped","row","collection","doc","relationTo","id","String","value","push","reason","config","get","title","meta","excludeSlugs","includes","description","undefined","group","icon","path","weight","hrefFor"],"mappings":"AAAA,SAASA,cAAc,QAAQ,sBAAsB;AAiBrD;;;;;;CAMC,GACD,OAAO,SAASC,YAAY,EAC1BC,WAAW,EACXC,SAAS,IAAI,EACbC,IAAI,EAKL;IACC,MAAMC,SAAS,IAAIC,IAAIJ,YAAYK,GAAG,CAACC,CAAAA,QAAS;YAACA,MAAMC,IAAI;YAAED;SAAM;IACnE,MAAME,OAAqB,EAAE;IAC7B,MAAMC,UAAuC,EAAE;IAE/C,KAAK,MAAMC,OAAOR,KAAM;QACtB,MAAMS,aAAaD,IAAIE,GAAG,EAAEC;QAC5B,MAAMC,KAAKC,OAAOL,IAAIE,GAAG,EAAEI,SAASN,IAAII,EAAE,IAAI;QAE9C,IAAI,CAACH,YAAY;YACfF,QAAQQ,IAAI,CAAC;gBACXH;gBACAP,MAAM;gBACNW,QAAQ;YACV;Y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":["../src/rank.ts"],"sourcesContent":["import Fuse from 'fuse.js'
|
|
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\nconst toResult = (doc: IndexedDoc, score?: number): SearchResult => ({\n id: doc.id,\n collection: doc.collection,\n group: doc.group,\n href: hrefFor(doc),\n icon: doc.icon,\n score,\n title: doc.title,\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}): { doc: IndexedDoc; 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 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 // 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: { doc: IndexedDoc; score?: number }[];\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 { doc, score } of ranked) {\n const group = bySlug.get(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(doc, score));\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","score","id","collection","group","href","icon","title","rankDocs","docs","fields","fuzzy","query","trimmed","trim","options","search","useTokenSearch","ignoreLocation","includeScore","keys","map","field","hit","item","sort","a","b","phrase","test","found","Set","filter","has","groupResults","groups","ranked","bySlug","Map","slug","grouped","get","bucket","limit","undefined","length","push","presetResults","eligible","showWhenEmpty","ordered","localeCompare"],"mappings":"AAAA,OAAOA,UAAU,UAAU;AAC3B,SAASC,OAAO,QAAQ,eAAe;AAUvC,OAAO,MAAMC,iBAAgC;IAC3C;QAAEC,MAAM;QAASC,QAAQ;IAAE;IAC3B;QAAED,MAAM;QAAQC,QAAQ;IAAI;IAC5B;QAAED,MAAM;QAAeC,QAAQ;IAAI;CACpC,CAAC;AAEF,OAAO,MAAMC,gBAAwC;IACnDC,UAAU;IACV,4FAA4F;IAC5F,kFAAkF;IAClFC,oBAAoB;IACpBC,WAAW;AACb,EAAE;AAEF,MAAMC,WAAW,CAACC,KAAiBC,QAAkC,CAAA;QACnEC,IAAIF,IAAIE,EAAE;QACVC,YAAYH,IAAIG,UAAU;QAC1BC,OAAOJ,IAAII,KAAK;QAChBC,MAAMd,QAAQS;QACdM,MAAMN,IAAIM,IAAI;QACdL;QACAM,OAAOP,IAAIO,KAAK;IAClB,CAAA;AAEA;;;;;;;;;;;CAWC,GACD,OAAO,SAASC,SAAS,EACvBC,IAAI,EACJC,SAASlB,cAAc,EACvBmB,KAAK,EACLC,KAAK,EAMN;IACC,MAAMC,UAAUD,MAAME,IAAI;IAC1B,IAAI,CAACD,SAAS;QACZ,OAAO,EAAE;IACX;IAEA,MAAME,UAAU;QAAE,GAAGpB,aAAa;QAAE,GAAGgB,KAAK;IAAC;IAC7C,MAAMK,SAAS,CAACC,iBACd,IAAI3B,KAAKmB,MAAM;YACbb,UAAUmB,QAAQnB,QAAQ;YAC1BsB,gBAAgB;YAChBC,cAAc;YACdC,MAAMV,OAAOW,GAAG,CAACC,CAAAA,QAAU,CAAA;oBACzB7B,MAA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AACpC,MAAMmC,IAAI,CAAC;QAClC,IAAInC,MAAMuC,KAAK,KAAKC,aAAaF,OAAOG,MAAM,IAAIzC,MAAMuC,KAAK,EAAE;YAC7D;QACF;QAEAD,OAAOI,IAAI,CAAC/C,SAASC,KAAKC;IAC5B;IAEA,OAAOuC;AACT;AAEA;;;;;;CAMC,GACD,OAAO,SAASO,cAAc,EAC5BtC,IAAI,EACJ0B,MAAM,EAIP;IACC,MAAMa,WAAW,IAAIjB,IACnBI,OACGH,MAAM,CAAC5B,CAAAA,QAASA,MAAM6C,aAAa,KAAK,OACxC5B,GAAG,CAACjB,CAAAA,QAASA,MAAMmC,IAAI;IAG5B,MAAMW,UAAUzC,KACbuB,MAAM,CAAChC,CAAAA,MAAOgD,SAASf,GAAG,CAACjC,IAAII,KAAK,GACpCqB,IAAI,CAAC,CAACC,GAAGC,IAAMA,EAAEjC,MAAM,GAAGgC,EAAEhC,MAAM,IAAIgC,EAAEnB,KAAK,CAAC4C,aAAa,CAACxB,EAAEpB,KAAK,GACnEc,GAAG,CAACrB,CAAAA,MAAQ,CAAA;YAAEA;QAAI,CAAA;IAErB,MAAMwC,UAAUN,aAAa;QAAEC;QAAQC,QAAQc;IAAQ;IAEvD,KAAK,MAAM9C,SAAS+B,OAAQ;QAC1B,IAAI,CAACa,SAASf,GAAG,CAAC7B,MAAMmC,IAAI,GAAG;YAC7BC,OAAO,CAACpC,MAAMmC,IAAI,CAAC,GAAG,EAAE;QAC1B;IACF;IAEA,OAAOC;AACT"}
|
package/dist/resolve.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/resolve.ts"],"sourcesContent":["import type { Payload } from 'payload'
|
|
1
|
+
{"version":3,"sources":["../src/resolve.ts"],"sourcesContent":["import type { Payload } from 'payload';\n\nimport type { SearchIndexCache } from './cache.js';\nimport type { SearchDoc } from './project.js';\nimport { projectDocs } from './project.js';\nimport { groupResults, presetResults, rankDocs } from './rank.js';\nimport type {\n GroupedResults,\n IndexedDoc,\n IndexReport,\n SearchPluginConfig,\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 */\nconst SEARCH_COLLECTION = 'search';\n\nexport type SearchService = {\n inspect: () => Promise<IndexReport>;\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 const load = async (): Promise<{\n docs: IndexedDoc[];\n skipped: IndexReport['skipped'];\n }> => {\n const response = await payload.find({\n collection: SEARCH_COLLECTION as never,\n depth: 0,\n limit: 0,\n pagination: false,\n });\n\n return projectDocs({\n collections: config.collections,\n decode,\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 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","SEARCH_COLLECTION","createSearchService","cache","config","payload","decode","decodeEntities","load","response","find","collection","depth","limit","pagination","collections","rows","docs","cached","get","fresh","set","inspect","skipped","builtAt","Date","toISOString","map","entry","slug","excluded","filter","row","length","indexed","doc","total","reindex","invalidate","search","query","all","trimmed","trim","groups","ranked","fields","fuzzy"],"mappings":"AAIA,SAASA,WAAW,QAAQ,eAAe;AAC3C,SAASC,YAAY,EAAEC,aAAa,EAAEC,QAAQ,QAAQ,YAAY;AAQlE;;;;CAIC,GACD,MAAMC,oBAAoB;AAQ1B;;;;;;;;CAQC,GACD,OAAO,SAASC,oBAAoB,EAClCC,KAAK,EACLC,MAAM,EACNC,OAAO,EAKR;IACC,MAAMC,SAASF,OAAOG,cAAc,IAAI;IAExC,MAAMC,OAAO;QAIX,MAAMC,WAAW,MAAMJ,QAAQK,IAAI,CAAC;YAClCC,YAAYV;YACZW,OAAO;YACPC,OAAO;YACPC,YAAY;QACd;QAEA,OAAOjB,YAAY;YACjBkB,aAAaX,OAAOW,WAAW;YAC/BT;YACAU,MAAMP,SAASQ,IAAI;QACrB;IACF;IAEA,MAAMA,OAAO;QACX,MAAMC,SAASf,MAAMgB,GAAG;QACxB,IAAID,QAAQ;YACV,OAAOA;QACT;QAEA,MAAM,EAAED,MAAMG,KAAK,EAAE,GAAG,MAAMZ;QAC9BL,MAAMkB,GAAG,CAACD;QACV,OAAOA;IACT;IAEA,OAAO;QACL,MAAME;YACJ,MAAM,EAAEL,MAAMG,KAAK,EAAEG,OAAO,EAAE,GAAG,MAAMf;YACvCL,MAAMkB,GAAG,CAACD;YAEV,OAAO;gBACLI,SAASrB,MAAMqB,OAAO,KAClB,IAAIC,KAAKtB,MAAMqB,OAAO,IAAcE,WAAW,KAC/C;gBACJX,aAAaX,OAAOW,WAAW,CAACY,GAAG,CAACC,CAAAA,QAAU,CAAA;wBAC5CC,MAAMD,MAAMC,IAAI;wBAChBC,UAAUP,QAAQQ,MAAM,CAACC,CAAAA,MAAOA,IAAIH,IAAI,KAAKD,MAAMC,IAAI,EAAEI,MAAM;wBAC/DC,SAASd,MAAMW,MAAM,CAACI,CAAAA,MAAOA,IAAIxB,UAAU,KAAKiB,MAAMC,IAAI,EAAEI,MAAM;oBACpE,CAAA;gBACAV;gBACAa,OAAOhB,MAAMa,MAAM;YACrB;QACF;QAEA,MAAMI;YACJlC,MAAMmC,UAAU;YAChB,MAAM,EAAErB,MAAMG,KAAK,EAAEG,OAAO,EAAE,GAAG,MAAMf;YACvCL,MAAMkB,GAAG,CAACD;YACV,OAAO;gBAAEc,SAASd,MAAMa,MAAM;gBAAEV,SAASA,QAAQU,MAAM;YAAC;QAC1D;QAEA,MAAMM,QAAOC,KAAa;YACxB,MAAMC,MAAM,MAAMxB;YAClB,MAAMyB,UAAUF,MAAMG,IAAI;YAE1B,IAAI,CAACD,SAAS;gBACZ,OAAO3C,cAAc;oBAAEkB,MAAMwB;oBAAKG,QAAQxC,OAAOwC,MAAM;gBAAC;YAC1D;YAEA,OAAO9C,aAAa;gBAClB8C,QAAQxC,OAAOwC,MAAM;gBACrBC,QAAQ7C,SAAS;oBACfiB,MAAMwB;oBACNK,QAAQ1C,OAAO0C,MAAM;oBACrBC,OAAO3C,OAAO2C,KAAK;oBACnBP,OAAOE;gBACT;YACF;QACF;IACF;AACF"}
|
package/dist/track.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { Payload } from 'payload';
|
|
1
|
+
import type { Payload, PayloadRequest } from 'payload';
|
|
2
2
|
export type ShownResult = {
|
|
3
3
|
group: string;
|
|
4
4
|
href: string;
|
|
@@ -28,11 +28,14 @@ export declare function isBot(userAgent: string): boolean;
|
|
|
28
28
|
* Upsert one row per searchId: the search creates it, later beacons for the same search append
|
|
29
29
|
* their click. Prunes past retention on write (no scheduled job to assume).
|
|
30
30
|
*/
|
|
31
|
-
export declare function recordSearchEvent({ collectionSlug, device, event, payload, retentionDays, visitorId, }: {
|
|
31
|
+
export declare function recordSearchEvent({ collectionSlug, device, event, payload, req, retentionDays, visitorId, }: {
|
|
32
32
|
collectionSlug: string;
|
|
33
33
|
device: Device;
|
|
34
34
|
event: TrackPayload;
|
|
35
35
|
payload: Payload;
|
|
36
|
+
/** The beacon's request. Passed to the create so host hooks on the collection can read it (an
|
|
37
|
+
* IP allow list, say); the handler only records anonymous requests, so it carries no user. */
|
|
38
|
+
req?: PayloadRequest;
|
|
36
39
|
retentionDays: number;
|
|
37
40
|
visitorId?: string;
|
|
38
41
|
}): Promise<void>;
|
package/dist/track.js
CHANGED
|
@@ -67,7 +67,7 @@ export function isBot(userAgent) {
|
|
|
67
67
|
/**
|
|
68
68
|
* Upsert one row per searchId: the search creates it, later beacons for the same search append
|
|
69
69
|
* their click. Prunes past retention on write (no scheduled job to assume).
|
|
70
|
-
*/ export async function recordSearchEvent({ collectionSlug, device, event, payload, retentionDays, visitorId }) {
|
|
70
|
+
*/ export async function recordSearchEvent({ collectionSlug, device, event, payload, req, retentionDays, visitorId }) {
|
|
71
71
|
const collection = collectionSlug;
|
|
72
72
|
const click = event.click && {
|
|
73
73
|
...event.click,
|
|
@@ -123,7 +123,10 @@ export function isBot(userAgent) {
|
|
|
123
123
|
utm: event.utm,
|
|
124
124
|
visitorId
|
|
125
125
|
},
|
|
126
|
-
overrideAccess: true
|
|
126
|
+
overrideAccess: true,
|
|
127
|
+
...req && {
|
|
128
|
+
req
|
|
129
|
+
}
|
|
127
130
|
});
|
|
128
131
|
} catch (error) {
|
|
129
132
|
// Payload wraps pg 23505 in a ValidationError with no code, so don't sniff the error: if the
|
package/dist/track.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/track.ts"],"sourcesContent":["import type { Payload } from 'payload'\n\nimport { cleanSearchTerm } from './analytics.js'\n\nexport type ShownResult = { group: string; href: string; title: string }\nexport type TrackPayload = {\n click?: { position: number } & ShownResult\n pagePath: string\n query: string\n referrer?: string\n results: ({ position: number } & ShownResult)[]\n resultCount: number\n searchId: string\n source: string\n utm?: Record<string, string>\n}\ntype Device = 'desktop' | 'mobile' | 'tablet'\n\nconst UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i\nconst str = (v: unknown, max: number): string => (typeof v === 'string' ? v.slice(0, max) : '')\nconst isObj = (v: unknown): v is Record<string, unknown> =>\n typeof v === 'object' && v !== null && !Array.isArray(v)\n\nconst shown = (v: unknown, position: number): ({ position: number } & ShownResult) | null => {\n if (!isObj(v)) {\n return null\n }\n return {\n group: str(v.group, 200),\n href: str(v.href, 2000).split(/[?#]/)[0].slice(0, 200),\n position: typeof v.position === 'number' && Number.isFinite(v.position) ? v.position : position,\n title: str(v.title, 200),\n }\n}\n\n/** Validate and bound an untrusted beacon body. Null means reject. */\nexport function parseTrackPayload(body: unknown): null | TrackPayload {\n if (!isObj(body)) {\n return null\n }\n const searchId = str(body.searchId, 64)\n if (!UUID.test(searchId)) {\n return null\n }\n const query = cleanSearchTerm(str(body.query, 1000))\n if (!query) {\n return null\n }\n if (typeof body.resultCount !== 'number' || !Number.isFinite(body.resultCount) || body.resultCount < 0) {\n return null\n }\n\n const results = (Array.isArray(body.results) ? body.results.slice(0, 20) : [])\n .map((r, i) => shown(r, i))\n .filter((r): r is NonNullable<typeof r> => r !== null)\n\n const utm: Record<string, string> = {}\n if (isObj(body.utm)) {\n for (const [k, v] of Object.entries(body.utm)) {\n if (k.startsWith('utm_') && typeof v === 'string') {\n utm[k.slice(0, 50)] = v.slice(0, 100)\n }\n }\n }\n\n let referrer = ''\n try {\n referrer = new URL(str(body.referrer, 2000)).hostname\n } catch {\n // unparseable: dropped\n }\n\n return {\n click: shown(body.click, 0) ?? undefined,\n pagePath: str(body.pagePath, 2000).split(/[?#]/)[0].slice(0, 300),\n query,\n referrer: referrer || undefined,\n resultCount: body.resultCount,\n results,\n searchId,\n source: str(body.source, 32),\n utm: Object.keys(utm).length ? utm : undefined,\n }\n}\n\nexport function deviceOf(userAgent: string): Device {\n if (/ipad|tablet/i.test(userAgent) || (/android/i.test(userAgent) && !/mobile/i.test(userAgent))) {\n return 'tablet'\n }\n return /mobi|iphone|ipod|android/i.test(userAgent) ? 'mobile' : 'desktop'\n}\n\nexport function isBot(userAgent: string): boolean {\n return /bot|crawl|spider|slurp|headless|lighthouse|preview|curl|wget/i.test(userAgent)\n}\n\n/**\n * Upsert one row per searchId: the search creates it, later beacons for the same search append\n * their click. Prunes past retention on write (no scheduled job to assume).\n */\nexport async function recordSearchEvent({\n collectionSlug,\n device,\n event,\n payload,\n retentionDays,\n visitorId,\n}: {\n collectionSlug: string\n device: Device\n event: TrackPayload\n payload: Payload\n retentionDays: number\n visitorId?: string\n}): Promise<void> {\n const collection = collectionSlug as never\n const click = event.click && { ...event.click, at: new Date().toISOString() }\n\n const findRow = async () =>\n (\n await payload.find({\n collection,\n depth: 0,\n limit: 1,\n overrideAccess: true,\n where: { searchId: { equals: event.searchId } },\n })\n ).docs[0] as undefined | { clicks?: unknown; id: number | string }\n\n const appendClick = async (row: undefined | { clicks?: unknown; id: number | string }) => {\n const prior = Array.isArray(row?.clicks) ? row.clicks : []\n if (!row || !click || prior.length >= 20) {\n return\n }\n await payload.update({\n id: row.id,\n collection,\n data: { clicks: [...prior, click] } as never,\n overrideAccess: true,\n })\n }\n\n const existing = await findRow()\n if (existing) {\n await appendClick(existing)\n } else {\n try {\n await payload.create({\n collection,\n data: {\n clicks: click ? [click] : [],\n device,\n pagePath: event.pagePath,\n query: event.query,\n referrer: event.referrer,\n resultCount: event.resultCount,\n results: event.results,\n searchId: event.searchId,\n source: event.source,\n utm: event.utm,\n visitorId,\n } as never,\n overrideAccess: true,\n })\n } catch (error) {\n // Payload wraps pg 23505 in a ValidationError with no code, so don't sniff the error: if the\n // row now exists we lost a race, otherwise the failure is real.\n const raced = await findRow()\n if (!raced) {\n throw error\n }\n await appendClick(raced)\n }\n }\n\n if (retentionDays > 0) {\n await payload.delete({\n collection,\n overrideAccess: true,\n where: {\n createdAt: { less_than: new Date(Date.now() - retentionDays * 86_400_000).toISOString() },\n },\n })\n }\n}\n"],"names":["cleanSearchTerm","UUID","str","v","max","slice","isObj","Array","isArray","shown","position","group","href","split","Number","isFinite","title","parseTrackPayload","body","searchId","test","query","resultCount","results","map","r","i","filter","utm","k","Object","entries","startsWith","referrer","URL","hostname","click","undefined","pagePath","source","keys","length","deviceOf","userAgent","isBot","recordSearchEvent","collectionSlug","device","event","payload","retentionDays","visitorId","collection","at","Date","toISOString","findRow","find","depth","limit","overrideAccess","where","equals","docs","appendClick","row","prior","clicks","update","id","data","existing","create","error","raced","delete","createdAt","less_than","now"],"mappings":"AAEA,SAASA,eAAe,QAAQ,iBAAgB;AAgBhD,MAAMC,OAAO;AACb,MAAMC,MAAM,CAACC,GAAYC,MAAyB,OAAOD,MAAM,WAAWA,EAAEE,KAAK,CAAC,GAAGD,OAAO;AAC5F,MAAME,QAAQ,CAACH,IACb,OAAOA,MAAM,YAAYA,MAAM,QAAQ,CAACI,MAAMC,OAAO,CAACL;AAExD,MAAMM,QAAQ,CAACN,GAAYO;IACzB,IAAI,CAACJ,MAAMH,IAAI;QACb,OAAO;IACT;IACA,OAAO;QACLQ,OAAOT,IAAIC,EAAEQ,KAAK,EAAE;QACpBC,MAAMV,IAAIC,EAAES,IAAI,EAAE,MAAMC,KAAK,CAAC,OAAO,CAAC,EAAE,CAACR,KAAK,CAAC,GAAG;QAClDK,UAAU,OAAOP,EAAEO,QAAQ,KAAK,YAAYI,OAAOC,QAAQ,CAACZ,EAAEO,QAAQ,IAAIP,EAAEO,QAAQ,GAAGA;QACvFM,OAAOd,IAA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MQ,QAAQmB,MAAM,CAAC;YACnBC,IAAIJ,IAAII,EAAE;YACVjB;YACAkB,MAAM;gBAAEH,QAAQ;uBAAID;oBAAO9B;iBAAM;YAAC;YAClCwB,gBAAgB;QAClB;IACF;IAEA,MAAMW,WAAW,MAAMf;IACvB,IAAIe,UAAU;QACZ,MAAMP,YAAYO;IACpB,OAAO;QACL,IAAI;YACF,MAAMtB,QAAQuB,MAAM,CAAC;gBACnBpB;gBACAkB,MAAM;oBACJH,QAAQ/B,QAAQ;wBAACA;qBAAM,GAAG,EAAE;oBAC5BW;oBACAT,UAAUU,MAAMV,QAAQ;oBACxBjB,OAAO2B,MAAM3B,KAAK;oBAClBY,UAAUe,MAAMf,QAAQ;oBACxBX,aAAa0B,MAAM1B,WAAW;oBAC9BC,SAASyB,MAAMzB,OAAO;oBACtBJ,UAAU6B,MAAM7B,QAAQ;oBACxBoB,QAAQS,MAAMT,MAAM;oBACpBX,KAAKoB,MAAMpB,GAAG;oBACduB;gBACF;gBACAS,gBAAgB;YAClB;QACF,EAAE,OAAOa,OAAO;YACd,6FAA6F;YAC7F,gEAAgE;YAChE,MAAMC,QAAQ,MAAMlB;YACpB,IAAI,CAACkB,OAAO;gBACV,MAAMD;YACR;YACA,MAAMT,YAAYU;QACpB;IACF;IAEA,IAAIxB,gBAAgB,GAAG;QACrB,MAAMD,QAAQ0B,MAAM,CAAC;YACnBvB;YACAQ,gBAAgB;YAChBC,OAAO;gBACLe,WAAW;oBAAEC,WAAW,IAAIvB,KAAKA,KAAKwB,GAAG,KAAK5B,gBAAgB,YAAYK,WAAW;gBAAG;YAC1F;QACF;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["../src/track.ts"],"sourcesContent":["import type { Payload, PayloadRequest } from 'payload';\n\nimport { cleanSearchTerm } from './analytics.js';\n\nexport type ShownResult = { group: string; href: string; title: string };\nexport type TrackPayload = {\n click?: { position: number } & ShownResult;\n pagePath: string;\n query: string;\n referrer?: string;\n results: ({ position: number } & ShownResult)[];\n resultCount: number;\n searchId: string;\n source: string;\n utm?: Record<string, string>;\n};\ntype Device = 'desktop' | 'mobile' | 'tablet';\n\nconst UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\nconst str = (v: unknown, max: number): string =>\n typeof v === 'string' ? v.slice(0, max) : '';\nconst isObj = (v: unknown): v is Record<string, unknown> =>\n typeof v === 'object' && v !== null && !Array.isArray(v);\n\nconst shown = (\n v: unknown,\n position: number\n): ({ position: number } & ShownResult) | null => {\n if (!isObj(v)) {\n return null;\n }\n return {\n group: str(v.group, 200),\n href: str(v.href, 2000).split(/[?#]/)[0].slice(0, 200),\n position:\n typeof v.position === 'number' && Number.isFinite(v.position)\n ? v.position\n : position,\n title: str(v.title, 200),\n };\n};\n\n/** Validate and bound an untrusted beacon body. Null means reject. */\nexport function parseTrackPayload(body: unknown): null | TrackPayload {\n if (!isObj(body)) {\n return null;\n }\n const searchId = str(body.searchId, 64);\n if (!UUID.test(searchId)) {\n return null;\n }\n const query = cleanSearchTerm(str(body.query, 1000));\n if (!query) {\n return null;\n }\n if (\n typeof body.resultCount !== 'number' ||\n !Number.isFinite(body.resultCount) ||\n body.resultCount < 0\n ) {\n return null;\n }\n\n const results = (Array.isArray(body.results) ? body.results.slice(0, 20) : [])\n .map((r, i) => shown(r, i))\n .filter((r): r is NonNullable<typeof r> => r !== null);\n\n const utm: Record<string, string> = {};\n if (isObj(body.utm)) {\n for (const [k, v] of Object.entries(body.utm)) {\n if (k.startsWith('utm_') && typeof v === 'string') {\n utm[k.slice(0, 50)] = v.slice(0, 100);\n }\n }\n }\n\n let referrer = '';\n try {\n referrer = new URL(str(body.referrer, 2000)).hostname;\n } catch {\n // unparseable: dropped\n }\n\n return {\n click: shown(body.click, 0) ?? undefined,\n pagePath: str(body.pagePath, 2000).split(/[?#]/)[0].slice(0, 300),\n query,\n referrer: referrer || undefined,\n resultCount: body.resultCount,\n results,\n searchId,\n source: str(body.source, 32),\n utm: Object.keys(utm).length ? utm : undefined,\n };\n}\n\nexport function deviceOf(userAgent: string): Device {\n if (\n /ipad|tablet/i.test(userAgent) ||\n (/android/i.test(userAgent) && !/mobile/i.test(userAgent))\n ) {\n return 'tablet';\n }\n return /mobi|iphone|ipod|android/i.test(userAgent) ? 'mobile' : 'desktop';\n}\n\nexport function isBot(userAgent: string): boolean {\n return /bot|crawl|spider|slurp|headless|lighthouse|preview|curl|wget/i.test(\n userAgent\n );\n}\n\n/**\n * Upsert one row per searchId: the search creates it, later beacons for the same search append\n * their click. Prunes past retention on write (no scheduled job to assume).\n */\nexport async function recordSearchEvent({\n collectionSlug,\n device,\n event,\n payload,\n req,\n retentionDays,\n visitorId,\n}: {\n collectionSlug: string;\n device: Device;\n event: TrackPayload;\n payload: Payload;\n /** The beacon's request. Passed to the create so host hooks on the collection can read it (an\n * IP allow list, say); the handler only records anonymous requests, so it carries no user. */\n req?: PayloadRequest;\n retentionDays: number;\n visitorId?: string;\n}): Promise<void> {\n const collection = collectionSlug as never;\n const click = event.click && { ...event.click, at: new Date().toISOString() };\n\n const findRow = async () =>\n (\n await payload.find({\n collection,\n depth: 0,\n limit: 1,\n overrideAccess: true,\n where: { searchId: { equals: event.searchId } },\n })\n ).docs[0] as undefined | { clicks?: unknown; id: number | string };\n\n const appendClick = async (\n row: undefined | { clicks?: unknown; id: number | string }\n ) => {\n const prior = Array.isArray(row?.clicks) ? row.clicks : [];\n if (!row || !click || prior.length >= 20) {\n return;\n }\n await payload.update({\n id: row.id,\n collection,\n data: { clicks: [...prior, click] } as never,\n overrideAccess: true,\n });\n };\n\n const existing = await findRow();\n if (existing) {\n await appendClick(existing);\n } else {\n try {\n await payload.create({\n collection,\n data: {\n clicks: click ? [click] : [],\n device,\n pagePath: event.pagePath,\n query: event.query,\n referrer: event.referrer,\n resultCount: event.resultCount,\n results: event.results,\n searchId: event.searchId,\n source: event.source,\n utm: event.utm,\n visitorId,\n } as never,\n overrideAccess: true,\n ...(req && { req }),\n });\n } catch (error) {\n // Payload wraps pg 23505 in a ValidationError with no code, so don't sniff the error: if the\n // row now exists we lost a race, otherwise the failure is real.\n const raced = await findRow();\n if (!raced) {\n throw error;\n }\n await appendClick(raced);\n }\n }\n\n if (retentionDays > 0) {\n await payload.delete({\n collection,\n overrideAccess: true,\n where: {\n createdAt: {\n less_than: new Date(\n Date.now() - retentionDays * 86_400_000\n ).toISOString(),\n },\n },\n });\n }\n}\n"],"names":["cleanSearchTerm","UUID","str","v","max","slice","isObj","Array","isArray","shown","position","group","href","split","Number","isFinite","title","parseTrackPayload","body","searchId","test","query","resultCount","results","map","r","i","filter","utm","k","Object","entries","startsWith","referrer","URL","hostname","click","undefined","pagePath","source","keys","length","deviceOf","userAgent","isBot","recordSearchEvent","collectionSlug","device","event","payload","req","retentionDays","visitorId","collection","at","Date","toISOString","findRow","find","depth","limit","overrideAccess","where","equals","docs","appendClick","row","prior","clicks","update","id","data","existing","create","error","raced","delete","createdAt","less_than","now"],"mappings":"AAEA,SAASA,eAAe,QAAQ,iBAAiB;AAgBjD,MAAMC,OAAO;AACb,MAAMC,MAAM,CAACC,GAAYC,MACvB,OAAOD,MAAM,WAAWA,EAAEE,KAAK,CAAC,GAAGD,OAAO;AAC5C,MAAME,QAAQ,CAACH,IACb,OAAOA,MAAM,YAAYA,MAAM,QAAQ,CAACI,MAAMC,OAAO,CAACL;AAExD,MAAMM,QAAQ,CACZN,GACAO;IAEA,IAAI,CAACJ,MAAMH,IAAI;QACb,OAAO;IACT;IACA,OAAO;QACLQ,OAAOT,IAAIC,EAAEQ,KAAK,EAAE;QACpBC,MAAMV,IAAIC,EAAES,IAAI,EAAE,MAAMC,KAAK,CAAC,OAAO,CAAC,EAAE,CAACR,KAAK,CAAC,GAAG;QAClDK,UACE,OAAOP,EAAEO,QAAQ,KAAK,YAAYI,OAAOC,QAAQ,CAACZ,EAAEO,QAAQ,IACxDP,EAAEO,QAAQ,GACVA;QACNM,OAAOd,IAAIC,EA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,MAAMQ,QAAQoB,MAAM,CAAC;YACnBC,IAAIJ,IAAII,EAAE;YACVjB;YACAkB,MAAM;gBAAEH,QAAQ;uBAAID;oBAAO/B;iBAAM;YAAC;YAClCyB,gBAAgB;QAClB;IACF;IAEA,MAAMW,WAAW,MAAMf;IACvB,IAAIe,UAAU;QACZ,MAAMP,YAAYO;IACpB,OAAO;QACL,IAAI;YACF,MAAMvB,QAAQwB,MAAM,CAAC;gBACnBpB;gBACAkB,MAAM;oBACJH,QAAQhC,QAAQ;wBAACA;qBAAM,GAAG,EAAE;oBAC5BW;oBACAT,UAAUU,MAAMV,QAAQ;oBACxBjB,OAAO2B,MAAM3B,KAAK;oBAClBY,UAAUe,MAAMf,QAAQ;oBACxBX,aAAa0B,MAAM1B,WAAW;oBAC9BC,SAASyB,MAAMzB,OAAO;oBACtBJ,UAAU6B,MAAM7B,QAAQ;oBACxBoB,QAAQS,MAAMT,MAAM;oBACpBX,KAAKoB,MAAMpB,GAAG;oBACdwB;gBACF;gBACAS,gBAAgB;gBAChB,GAAIX,OAAO;oBAAEA;gBAAI,CAAC;YACpB;QACF,EAAE,OAAOwB,OAAO;YACd,6FAA6F;YAC7F,gEAAgE;YAChE,MAAMC,QAAQ,MAAMlB;YACpB,IAAI,CAACkB,OAAO;gBACV,MAAMD;YACR;YACA,MAAMT,YAAYU;QACpB;IACF;IAEA,IAAIxB,gBAAgB,GAAG;QACrB,MAAMF,QAAQ2B,MAAM,CAAC;YACnBvB;YACAQ,gBAAgB;YAChBC,OAAO;gBACLe,WAAW;oBACTC,WAAW,IAAIvB,KACbA,KAAKwB,GAAG,KAAK5B,gBAAgB,YAC7BK,WAAW;gBACf;YACF;QACF;IACF;AACF"}
|
package/dist/trackClient.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/trackClient.ts"],"sourcesContent":["import type { TrackPayload } from './track.js'
|
|
1
|
+
{"version":3,"sources":["../src/trackClient.ts"],"sourcesContent":["import type { TrackPayload } from './track.js';\n\n/** Fire-and-forget search event; survives page unload and never throws. */\nexport function trackSearchEvent(\n payload: TrackPayload,\n endpoint = '/api/site-search/track'\n): void {\n try {\n const body = JSON.stringify(payload);\n if (\n navigator.sendBeacon?.(\n endpoint,\n new Blob([body], { type: 'application/json' })\n )\n ) {\n return;\n }\n void fetch(endpoint, {\n body,\n headers: { 'Content-Type': 'application/json' },\n keepalive: true,\n method: 'POST',\n }).catch(() => {});\n } catch {\n // analytics must never break the page\n }\n}\n"],"names":["trackSearchEvent","payload","endpoint","body","JSON","stringify","navigator","sendBeacon","Blob","type","fetch","headers","keepalive","method","catch"],"mappings":"AAEA,yEAAyE,GACzE,OAAO,SAASA,iBACdC,OAAqB,EACrBC,WAAW,wBAAwB;IAEnC,IAAI;QACF,MAAMC,OAAOC,KAAKC,SAAS,CAACJ;QAC5B,IACEK,UAAUC,UAAU,GAClBL,UACA,IAAIM,KAAK;YAACL;SAAK,EAAE;YAAEM,MAAM;QAAmB,KAE9C;YACA;QACF;QACA,KAAKC,MAAMR,UAAU;YACnBC;YACAQ,SAAS;gBAAE,gBAAgB;YAAmB;YAC9CC,WAAW;YACXC,QAAQ;QACV,GAAGC,KAAK,CAAC,KAAO;IAClB,EAAE,OAAM;IACN,sCAAsC;IACxC;AACF"}
|
package/dist/types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/types.ts"],"sourcesContent":["import type { CollectionSlug, PayloadRequest } from 'payload'
|
|
1
|
+
{"version":3,"sources":["../src/types.ts"],"sourcesContent":["import 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 /** 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":"AAkIA,mFAAmF,GACnF,WAaE"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@foundrykit/search-plugin",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.3",
|
|
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",
|
|
@@ -38,43 +38,22 @@
|
|
|
38
38
|
"files": [
|
|
39
39
|
"dist"
|
|
40
40
|
],
|
|
41
|
-
"scripts": {
|
|
42
|
-
"build": "pnpm clean && pnpm copyfiles && pnpm build:types && pnpm build:swc",
|
|
43
|
-
"build:swc": "swc ./src -d ./dist --config-file .swcrc --strip-leading-paths --ignore \"**/*.test.ts,**/*.test.tsx\"",
|
|
44
|
-
"build:types": "tsc --outDir dist --rootDir ./src",
|
|
45
|
-
"clean": "rimraf {dist,*.tsbuildinfo}",
|
|
46
|
-
"copyfiles": "copyfiles -u 1 \"src/**/*.{html,css,scss,ttf,woff,woff2,eot,svg,jpg,png,json}\" dist/",
|
|
47
|
-
"lint": "eslint",
|
|
48
|
-
"lint:fix": "eslint ./src --fix",
|
|
49
|
-
"prepublishOnly": "pnpm build && node scripts/verify-pack.mjs",
|
|
50
|
-
"verify:pack": "node scripts/verify-pack.mjs",
|
|
51
|
-
"test": "pnpm test:unit",
|
|
52
|
-
"test:unit": "vitest run",
|
|
53
|
-
"release": "release-it",
|
|
54
|
-
"release:dry": "release-it --dry-run"
|
|
55
|
-
},
|
|
56
41
|
"dependencies": {
|
|
57
42
|
"fuse.js": "^7.5.0"
|
|
58
43
|
},
|
|
59
44
|
"devDependencies": {
|
|
60
|
-
"@
|
|
61
|
-
"@payloadcms/
|
|
62
|
-
"@payloadcms/plugin-search": "3.37.0",
|
|
63
|
-
"@payloadcms/ui": "3.37.0",
|
|
64
|
-
"@release-it/conventional-changelog": "^10.0.5",
|
|
45
|
+
"@payloadcms/plugin-search": "3.84.1",
|
|
46
|
+
"@payloadcms/ui": "3.84.1",
|
|
65
47
|
"@swc/cli": "0.6.0",
|
|
66
48
|
"@types/node": "22.19.9",
|
|
67
49
|
"@types/react": "19.2.9",
|
|
68
50
|
"copyfiles": "2.4.1",
|
|
69
51
|
"cross-env": "^7.0.3",
|
|
70
|
-
"
|
|
71
|
-
"
|
|
72
|
-
"prettier": "^3.4.2",
|
|
73
|
-
"react": "19.2.1",
|
|
74
|
-
"release-it": "^19.2.4",
|
|
52
|
+
"payload": "3.84.1",
|
|
53
|
+
"react": "19.2.6",
|
|
75
54
|
"rimraf": "3.0.2",
|
|
76
|
-
"typescript": "5.
|
|
77
|
-
"vitest": "4.
|
|
55
|
+
"typescript": "5.9.2",
|
|
56
|
+
"vitest": "4.1.10"
|
|
78
57
|
},
|
|
79
58
|
"peerDependencies": {
|
|
80
59
|
"@payloadcms/plugin-search": "^3.37.0",
|
|
@@ -82,18 +61,28 @@
|
|
|
82
61
|
"react": "^19.0.0"
|
|
83
62
|
},
|
|
84
63
|
"engines": {
|
|
85
|
-
"node": "
|
|
86
|
-
"pnpm": "^9 || ^10"
|
|
64
|
+
"node": ">=20.9.0"
|
|
87
65
|
},
|
|
88
66
|
"publishConfig": {
|
|
89
67
|
"access": "public"
|
|
90
68
|
},
|
|
91
69
|
"repository": {
|
|
92
70
|
"type": "git",
|
|
93
|
-
"url": "git+https://github.com/umi-labs/
|
|
71
|
+
"url": "git+https://github.com/umi-labs/foundry.git",
|
|
72
|
+
"directory": "packages/payload/search-plugin"
|
|
94
73
|
},
|
|
95
74
|
"bugs": {
|
|
96
|
-
"url": "https://github.com/umi-labs/
|
|
75
|
+
"url": "https://github.com/umi-labs/foundry/issues"
|
|
97
76
|
},
|
|
98
|
-
"homepage": "https://github.com/umi-labs/search-plugin#readme"
|
|
99
|
-
|
|
77
|
+
"homepage": "https://github.com/umi-labs/foundry/tree/prod/packages/payload/search-plugin#readme",
|
|
78
|
+
"scripts": {
|
|
79
|
+
"build": "pnpm clean && pnpm copyfiles && pnpm build:types && pnpm build:swc",
|
|
80
|
+
"build:swc": "swc ./src -d ./dist --config-file .swcrc --strip-leading-paths --ignore \"**/*.test.ts,**/*.test.tsx\"",
|
|
81
|
+
"build:types": "tsc --outDir dist --rootDir ./src",
|
|
82
|
+
"clean": "rimraf {dist,*.tsbuildinfo}",
|
|
83
|
+
"copyfiles": "copyfiles -u 1 \"src/**/*.{html,css,scss,ttf,woff,woff2,eot,svg,jpg,png,json}\" dist/",
|
|
84
|
+
"verify:pack": "node scripts/verify-pack.mjs",
|
|
85
|
+
"test": "pnpm test:unit",
|
|
86
|
+
"test:unit": "vitest run"
|
|
87
|
+
}
|
|
88
|
+
}
|