Busca do site com texto completo do Postgres: radicais por idioma, prefixos, trechos seguros e erros de digitação
Instalar
genpm add @core/searchO que você recebe
- Código em src/lib/search/, 8 arquivos. (13,2 kB)
- Regras de IA em src/lib/search/AGENTS.md, mais arquivos de regras da IDE.
- Resolve @core/contracts, @core/db, @core/jobs para você.
README
Este pacote não tem README.
Isto é exatamente o que sua IA lê quando trabalha em src/lib/search. Nada mais é adicionado ao contexto dela.
@core/search — rules for AI agents
Purpose
Site search on Postgres full-text search: one search_documents table fed by any SearchSource (@core/contracts),
weighted title/body vectors with the stemmer of each document's language, prefix matching for search-as-you-type,
snippets returned as plain parts (never HTML) and, if the pg_trgm extension exists, a typo-tolerant fallback on
titles. No external engine, no semantic search.
Map
index.ts— public API:search,registerSearchSource,reindex,indexDocument,removeDocument,reindexJob.search.ts— indexing and querying.schema.ts— table and GIN index.adapters/hono.ts—searchRoutes().adapters/next.ts—searchRoute(GET).
Integration
- Generate and apply migrations (see
src/lib/db/AGENTS.md). Optional typo tolerance: runcreate extension if not exists pg_trgm;once (available on Neon, Supabase, RDS). - Register sources in the project file
src/genpm/search.ts, imported at startup:registerSearchSource(contentSearchSource('pages', { path: ({ slug }) =>/${slug}})). - Build the index once and then daily:
await reindexJob.enqueue({})andschedule('search.reindex', '0 3 * * *')(@core/jobs). - Query:
const { hits } = await search(q, { locale }), or mountsearchRoutes()/searchRouteat/api/search. - Render snippets by mapping parts:
hit.snippet.map(p => p.match ? <mark>{p.text}</mark> : p.text). - Verify: index a document and find it by the first letters of a word in its title.
Conventions
- Sources yield plain text bodies (strip Markdown/HTML first, e.g. with
toPlainTextof @core/rich-text). - Pass
localewhen you know it: the query uses that language's stemmer and the GIN index. - Only index published, public content; private data never goes into
search_documents.
Don't
- Don't build SQL from the query string;
search()already sanitizes it to words. - Don't render snippets with
dangerouslySetInnerHTML. - Don't call
reindex()inside a request: use the job.
# @core/search — rules for AI agents
## Purpose
Site search on Postgres full-text search: one `search_documents` table fed by any `SearchSource` (@core/contracts),
weighted title/body vectors with the stemmer of each document's language, prefix matching for search-as-you-type,
snippets returned as plain parts (never HTML) and, if the `pg_trgm` extension exists, a typo-tolerant fallback on
titles. No external engine, no semantic search.
## Map
- `index.ts` — public API: `search`, `registerSearchSource`, `reindex`, `indexDocument`, `removeDocument`, `reindexJob`.
- `search.ts` — indexing and querying. `schema.ts` — table and GIN index.
- `adapters/hono.ts` — `searchRoutes()`. `adapters/next.ts` — `searchRoute` (GET).
## Integration
1. Generate and apply migrations (see `src/lib/db/AGENTS.md`). Optional typo tolerance: run
`create extension if not exists pg_trgm;` once (available on Neon, Supabase, RDS).
2. Register sources in the project file `src/genpm/search.ts`, imported at startup:
`registerSearchSource(contentSearchSource('pages', { path: ({ slug }) => `/${slug}` }))`.
3. Build the index once and then daily: `await reindexJob.enqueue({})` and `schedule('search.reindex', '0 3 * * *')` (@core/jobs).
4. Query: `const { hits } = await search(q, { locale })`, or mount `searchRoutes()` / `searchRoute` at `/api/search`.
5. Render snippets by mapping parts: `hit.snippet.map(p => p.match ? <mark>{p.text}</mark> : p.text)`.
6. Verify: index a document and find it by the first letters of a word in its title.
## Conventions
- Sources yield plain text bodies (strip Markdown/HTML first, e.g. with `toPlainText` of @core/rich-text).
- Pass `locale` when you know it: the query uses that language's stemmer and the GIN index.
- Only index published, public content; private data never goes into `search_documents`.
## Don't
- Don't build SQL from the query string; `search()` already sanitizes it to words.
- Don't render snippets with `dangerouslySetInnerHTML`.
- Don't call `reindex()` inside a request: use the job.
A árvore exata que será injetada, após o .genpmignore. Fixada em
// Tablas de @core/search. Las recoge drizzle-kit vía src/lib/db/drizzle.config.ts.
import { customType, index, pgTable, primaryKey, text, timestamp } from 'drizzle-orm/pg-core';
const tsvector = customType<{ data: string }>({ dataType: () => 'tsvector' });
/** Índice de búsqueda: una fila por documento (`type` + `id`) con su vector ponderado (título A, cuerpo B). */
export const searchDocuments = pgTable(
'search_documents',
{
type: text('type').notNull(),
id: text('id').notNull(),
locale: text('locale').notNull(),
url: text('url').notNull(),
title: text('title').notNull(),
body: text('body').notNull(),
/** Configuración de texto de Postgres usada (`spanish`, `english`, `simple`…). */
config: text('config').notNull(),
tsv: tsvector('tsv').notNull(),
indexedAt: timestamp('indexed_at', { withTimezone: true, mode: 'date' }).notNull().defaultNow(),
},
(t) => [
primaryKey({ columns: [t.type, t.id] }),
index('search_documents_tsv_idx').using('gin', t.tsv),
index('search_documents_locale_idx').on(t.locale, t.type),
],
);
export type SearchRow = typeof searchDocuments.$inferSelect;
Este pacote não declara servidores MCP.
| Versão | Commit | Publicado | Análise |
|---|---|---|---|
| 1.0.0 | ae66128 | há 6 horas | análise aprovada |
- npm
- zod ^4.0.0
- proposto
- O GenPM propõe o comando npm e só o executa se você disser sim.
- Usado por (1)
- @core/kit-cms ^1.0.0
- análise
- análise aprovada · 0 achados
- commit
- v1.0.0 → ae6612826aed11b87040adc5f891b5bf6e858c58 · verificado após o download
- scripts
- Nenhum. O GenPM nunca executa código de pacotes.
- licença
- MIT
- Qualidade
- 100/100
- Licença reconhecidacumprido
- AGENTS.md explica o propósitocumprido
- AGENTS.md tem passos de integraçãocumprido
- AGENTS.md lista convenções ou proibiçõescumprido
- Inclui testescumprido
- Escaneamento de segurança aprovadocumprido
- Publicado nos últimos 6 mesescumprido
- Publicador verificadocumprido
- Resumo e palavras-chavecumprido
- denúncia
- Viu algo errado?