@nomideusz/svelte-search 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,18 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0 — 2026-04-23
4
+
5
+ Initial public release.
6
+
7
+ ### Added
8
+ - **Search engine** — `createSearchEngine({ db, adapter, locale?, dialect? })` with synonym expansion, full-text search, trigram fuzzy fallback, score blending, quality gate, and primary/nearby relevance boundaries.
9
+ - **Dialect support** — `sqlite` (FTS5 `MATCH` + custom trigram tables) and `postgres` (`tsvector` + `pg_trgm`).
10
+ - **Schema adapter** — `SchemaAdapter` interface for mapping any DB schema to the engine's concepts (entities, trigrams, FTS, synonyms).
11
+ - **Indexer** — `createIndexer()` with `indexTrigrams()`, `reindexAllTrigrams()`, `rebuildFts()`, `checkFtsSync()`, `updateSearchVector()` (Postgres).
12
+ - **Query resolver** — `parseQuery()` classifies tokens into location / category / area / rest; `findMatchingArea()` and `findNearestLocationWithEntities()` helpers.
13
+ - **Geo helpers** — `haversineKm`, `walkingMinutes`, `boundingBox`, `formatDistance`, `formatWalkingTime`, `walkingRoute` (OSRM).
14
+ - **Normalization & similarity** — `normalize`, `stripDiacriticsGeneric`, `trigrams`, `trigramSimilarity`, `levenshtein`, `levenshteinSimilarity`, `isPostcode`, `hasGeoIntent`, `stripGeoIntent`, `stripStopWords`.
15
+ - **Polish locale** (`@nomideusz/svelte-search/locales/pl`) — diacritics, stop words and phrases, geo-intent patterns (`blisko mnie`, `niedaleko`, `w okolicy`, …), and nominative-form stemming.
16
+ - **Tracker** — `createTracker()` fire-and-forget analytics via `navigator.sendBeacon`, session ID in `sessionStorage`.
17
+ - **Types** — `SearchParams`, `SearchResult`, `SearchResponse`, `AutocompleteResult`, `SearchLocale`, `ResolverLookups`, `ResolverAction`, `TrackSearchEvent`, `DatabaseClient`, `SqlDialect`.
18
+ - 67 unit tests across core (geo, normalize, resolver) and the Polish locale.
package/README.md ADDED
@@ -0,0 +1,295 @@
1
+ # @nomideusz/svelte-search
2
+
3
+ A full-text search engine for Svelte 5 apps backed by your own database. Combines FTS5 (SQLite) or `tsvector` (PostgreSQL) with trigram fuzzy matching, geo proximity, synonym expansion, and a pluggable schema adapter. Ships with a Polish locale that handles diacritics, stop words, and locative-case stemming.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ pnpm add @nomideusz/svelte-search
9
+ ```
10
+
11
+ > Requires Svelte 5 (`^5.0.0`). Works with any SQL client that exposes an `execute()` method — libsql, better-sqlite3, postgres.js, etc.
12
+
13
+ ## Why
14
+
15
+ Most Svelte search libraries index in-memory or hit an external service. This one pushes the query down to your database so it stays fast at any table size, but stays generic: you provide a `SchemaAdapter` that maps the engine's concepts (entities, trigrams, FTS, synonyms) onto your tables. The engine then handles:
16
+
17
+ 1. Synonym expansion
18
+ 2. Full-text search (FTS5 `MATCH` / Postgres `tsvector @@ tsquery`)
19
+ 3. Trigram fuzzy fallback (custom tables on SQLite, `pg_trgm` on Postgres)
20
+ 4. Score blending (FTS rank + name similarity + field match + geo)
21
+ 5. Quality gate (Levenshtein threshold to reject junk fuzzy hits)
22
+ 6. Relevance boundaries (primary radius + "also within reach" list)
23
+
24
+ ## Quick Start
25
+
26
+ Define a `SchemaAdapter` that points at your tables and columns, then create an engine:
27
+
28
+ ```ts
29
+ import { createSearchEngine, type SchemaAdapter, type SearchResult } from '@nomideusz/svelte-search';
30
+ import { plLocale } from '@nomideusz/svelte-search/locales/pl';
31
+
32
+ interface SchoolResult extends SearchResult {
33
+ city: string;
34
+ styles: string[];
35
+ }
36
+
37
+ const schema: SchemaAdapter<SchoolResult> = {
38
+ tables: {
39
+ entities: 'schools',
40
+ trigrams: 'school_trigrams',
41
+ fts: 'schools_fts',
42
+ synonyms: 'search_synonyms',
43
+ },
44
+ columns: {
45
+ id: 'id',
46
+ name: 'name',
47
+ nameNormalized: 'name_n',
48
+ slug: 'slug',
49
+ lat: 'latitude',
50
+ lng: 'longitude',
51
+ locationSlug: 'city_slug',
52
+ categoriesNormalized: 'styles_n',
53
+ locationNormalized: 'city_n',
54
+ areaNormalized: 'district_n',
55
+ },
56
+ trigramColumns: { trigram: 'trigram', entityId: 'school_id', field: 'field' },
57
+ toResult(row, lat, lng) {
58
+ return {
59
+ id: row.id as string,
60
+ name: row.name as string,
61
+ slug: row.slug as string,
62
+ city: row.city as string,
63
+ styles: JSON.parse((row.styles as string) || '[]'),
64
+ lat: row.latitude as number | null,
65
+ lng: row.longitude as number | null,
66
+ distanceKm: null,
67
+ walkingMin: null,
68
+ score: 0,
69
+ };
70
+ },
71
+ trigramFields(row) {
72
+ return [
73
+ { text: row.name as string, field: 'name' },
74
+ { text: row.city as string, field: 'city' },
75
+ ];
76
+ },
77
+ };
78
+
79
+ const engine = createSearchEngine<SchoolResult>({
80
+ db, // any client with .execute({ sql, args })
81
+ adapter: schema,
82
+ locale: plLocale, // optional
83
+ });
84
+
85
+ const response = await engine.search({
86
+ query: 'hatha w poblizu',
87
+ lat: 52.229, lng: 21.012,
88
+ limit: 20,
89
+ });
90
+ ```
91
+
92
+ `response.results` has your primary hits, `response.nearby` has matches just outside the primary radius, and `response.nearestLocationWithEntities` suggests where to look if the user's area has none.
93
+
94
+ ## Dialects
95
+
96
+ Pick a dialect when you create the engine — defaults to SQLite:
97
+
98
+ ```ts
99
+ createSearchEngine({ db, adapter, dialect: 'sqlite' }); // FTS5 + custom trigram tables
100
+ createSearchEngine({ db, adapter, dialect: 'postgres' }); // tsvector + pg_trgm
101
+ ```
102
+
103
+ On SQLite, you're expected to maintain your own trigram table and FTS5 virtual table — the indexer helps with that. On Postgres, `pg_trgm` handles trigrams automatically; just keep a `tsvector` column updated (via trigger or `indexer.updateSearchVector()`).
104
+
105
+ ## Indexer
106
+
107
+ The indexer rebuilds trigrams and FTS from your entities table:
108
+
109
+ ```ts
110
+ import { createIndexer } from '@nomideusz/svelte-search';
111
+
112
+ const indexer = createIndexer({ db, adapter: schema, locale: plLocale });
113
+
114
+ await indexer.indexTrigrams(schoolId, schoolRow); // one entity
115
+ await indexer.reindexAllTrigrams(); // full rebuild
116
+ await indexer.rebuildFts(); // SQLite FTS5 rebuild
117
+ const stats = await indexer.checkFtsSync(); // diagnose drift
118
+ ```
119
+
120
+ On Postgres, `indexTrigrams` and `rebuildFts` are no-ops — use your trigger or `updateSearchVector()` instead.
121
+
122
+ ## Search parameters
123
+
124
+ ```ts
125
+ engine.search({
126
+ query: 'hatha near me', // raw user input
127
+ locationSlug: 'warsaw', // restrict to city
128
+ categorySlug: 'hatha', // restrict to style
129
+ lat: 52.229, lng: 21.012, // user coords for proximity
130
+ limit: 20, offset: 0,
131
+ });
132
+ ```
133
+
134
+ The engine automatically detects geo intent (`"near me"`, `"blisko"`) and strips it before the FTS/trigram step, then uses the supplied coordinates for proximity sorting. Empty queries with coordinates fall back to pure geo search.
135
+
136
+ ### Tunables
137
+
138
+ | Option | Default | Description |
139
+ |--------|---------|-------------|
140
+ | `ftsTimeoutMs` | `5000` | FTS query timeout (returns empty on overrun) |
141
+ | `fuzzyTimeoutMs` | `3000` | Trigram fallback timeout |
142
+ | `primaryRadiusKm` | `15` | Max distance for primary results |
143
+ | `nearbyRadiusKm` | `30` | Max distance for "also within reach" results |
144
+ | `maxNearby` | `5` | Cap on nearby entries |
145
+ | `qualityThreshold` | `0.75` | Min Levenshtein similarity for fuzzy-only hits |
146
+ | `maxFtsTerms` | `6` | Cap on terms sent to FTS |
147
+
148
+ ## Autocomplete
149
+
150
+ Autocomplete is app-specific (every app wants different suggestion types: cities, styles, neighborhoods, products, …), so the package exports only the `AutocompleteResult` type — you write the query logic against your tables. A typical shape:
151
+
152
+ ```ts
153
+ export interface AutocompleteResult {
154
+ text: string;
155
+ type: string; // 'school' | 'city' | 'style' | …
156
+ slug?: string;
157
+ }
158
+ ```
159
+
160
+ ## Query resolver
161
+
162
+ `parseQuery()` classifies tokens into location / category / area / rest using lookup maps you build from your DB. It's the parsing half of a full resolver — apps provide the dispatch rules:
163
+
164
+ ```ts
165
+ import { parseQuery, type ResolverLookups } from '@nomideusz/svelte-search';
166
+
167
+ const lookups: ResolverLookups = {
168
+ locationMap: new Map([['warszawa', 'warsaw'], ['krakow', 'krakow']]),
169
+ categoryMap: new Map([['hatha', 'hatha'], ['vinyasa', 'vinyasa']]),
170
+ areaMap: new Map([['warsaw', ['mokotow', 'praga']]]),
171
+ };
172
+
173
+ const parsed = parseQuery('hatha w warszawie mokotow', lookups, plLocale);
174
+ // { location: 'warsaw', category: 'hatha', rest: ['mokotow'], geoIntent: false, ... }
175
+ ```
176
+
177
+ `findMatchingArea()` and `findNearestLocationWithEntities()` are helpers for "did they type a neighborhood?" and "what's the nearest populated city?" resolutions.
178
+
179
+ ## Geo helpers
180
+
181
+ Pure functions — no DB:
182
+
183
+ ```ts
184
+ import {
185
+ haversineKm, walkingMinutes, boundingBox,
186
+ formatDistance, formatWalkingTime, walkingRoute,
187
+ } from '@nomideusz/svelte-search';
188
+
189
+ haversineKm(52.229, 21.012, 50.062, 19.937); // km between Warsaw and Kraków
190
+ walkingMinutes(0.8); // ~13 (min)
191
+ formatDistance(0.85); // "850 m"
192
+ formatWalkingTime(72); // "1 hr 12 min walk"
193
+
194
+ // Fast SQL pre-filter before exact Haversine:
195
+ const bb = boundingBox(52.229, 21.012, 5); // 5 km box
196
+ // WHERE lat BETWEEN bb.minLat AND bb.maxLat AND lng BETWEEN bb.minLng AND bb.maxLng
197
+
198
+ // Optional real walking route via OSRM (self-host for production):
199
+ const route = await walkingRoute(52.229, 21.012, 52.237, 21.017);
200
+ // { distanceM, durationS } | null
201
+ ```
202
+
203
+ ## Normalization & similarity
204
+
205
+ ```ts
206
+ import {
207
+ normalize, stripDiacriticsGeneric,
208
+ trigrams, trigramSimilarity,
209
+ levenshtein, levenshteinSimilarity,
210
+ isPostcode, hasGeoIntent, stripGeoIntent, stripStopWords,
211
+ } from '@nomideusz/svelte-search';
212
+
213
+ normalize('Łódź, ulica Piotrkowska', plLocale); // 'lodz ulica piotrkowska'
214
+ trigrams('hatha'); // ['hat','ath','tha']
215
+ trigramSimilarity('hatha', 'hata'); // ~0.67
216
+ levenshteinSimilarity('vinyasa', 'vinjasa'); // ~0.86
217
+ isPostcode('00-001'); // true
218
+ hasGeoIntent('yoga near me'); // true
219
+ stripGeoIntent('yoga near me'); // 'yoga'
220
+ ```
221
+
222
+ ## Locales
223
+
224
+ The package ships a Polish locale handling:
225
+
226
+ - diacritics (`ą → a`, `ł → l`, `ó → o`, …)
227
+ - stop words and phrases (`w`, `na`, `joga`, `szkoła jogi`, …)
228
+ - geo-intent patterns (`blisko mnie`, `niedaleko`, `w okolicy`, …)
229
+ - nominative-form stemming (`warszawie → warszawa`, `krakowie → krakow`, …)
230
+
231
+ ```ts
232
+ import { plLocale } from '@nomideusz/svelte-search/locales/pl';
233
+ ```
234
+
235
+ Bring your own locale by implementing the `SearchLocale` interface — `stripDiacritics`, `stopTokens`, `stopPhrases`, `geoPatterns`, and optionally `locationStems`. No locale = generic NFD diacritic stripping and no stop words.
236
+
237
+ ## Tracking
238
+
239
+ A minimal analytics helper that fire-and-forgets search events via `navigator.sendBeacon`, never throwing:
240
+
241
+ ```ts
242
+ import { createTracker } from '@nomideusz/svelte-search';
243
+
244
+ const { track } = createTracker({ endpoint: '/api/search-events' });
245
+
246
+ track({
247
+ query: 'hatha warszawa',
248
+ queryNormalized: 'hatha warszawa',
249
+ page: 'home',
250
+ action: 'filter',
251
+ layer: 'server',
252
+ resultCount: 12,
253
+ });
254
+ ```
255
+
256
+ A session ID is stored in `sessionStorage` (no PII). The server endpoint shape is up to you.
257
+
258
+ ## Database client interface
259
+
260
+ Any client with an `execute()` matching this shape works:
261
+
262
+ ```ts
263
+ interface DatabaseClient {
264
+ execute(query: { sql: string; args: unknown[] } | string): Promise<{
265
+ rows: Record<string, unknown>[];
266
+ lastInsertRowid?: bigint | number;
267
+ }>;
268
+ }
269
+ ```
270
+
271
+ libsql's `Client` matches directly. For other drivers, wrap them:
272
+
273
+ ```ts
274
+ function wrapClient(client: MyClient): DatabaseClient {
275
+ return {
276
+ execute: (query) => typeof query === 'string'
277
+ ? client.execute(query)
278
+ : client.execute({ sql: query.sql, args: query.args as any }),
279
+ };
280
+ }
281
+ ```
282
+
283
+ ## Development
284
+
285
+ ```bash
286
+ pnpm install
287
+ pnpm dev # SvelteKit dev server (demo)
288
+ pnpm check # Typecheck
289
+ pnpm test # Vitest
290
+ pnpm run package # Build the library
291
+ ```
292
+
293
+ ## License
294
+
295
+ MIT
@@ -0,0 +1,25 @@
1
+ import type { DatabaseClient, SchemaAdapter, SearchParams, SearchResult, SearchResponse, SearchLocale, SqlDialect } from './types.js';
2
+ export interface SearchEngineConfig<TResult extends SearchResult = SearchResult> {
3
+ db: DatabaseClient;
4
+ adapter: SchemaAdapter<TResult>;
5
+ locale?: SearchLocale;
6
+ /** SQL dialect: 'sqlite' (default) or 'postgres' */
7
+ dialect?: SqlDialect;
8
+ /** FTS query timeout in ms (default: 5000) */
9
+ ftsTimeoutMs?: number;
10
+ /** Fuzzy query timeout in ms (default: 3000) */
11
+ fuzzyTimeoutMs?: number;
12
+ /** Primary result radius in km (default: 15) */
13
+ primaryRadiusKm?: number;
14
+ /** Nearby result radius in km (default: 30) */
15
+ nearbyRadiusKm?: number;
16
+ /** Max nearby results in response (default: 5) */
17
+ maxNearby?: number;
18
+ /** Quality gate threshold for fuzzy-only results (default: 0.75) */
19
+ qualityThreshold?: number;
20
+ /** Max FTS terms per query (default: 6) */
21
+ maxFtsTerms?: number;
22
+ }
23
+ export declare function createSearchEngine<TResult extends SearchResult = SearchResult>(config: SearchEngineConfig<TResult>): {
24
+ search: (params: SearchParams) => Promise<SearchResponse<TResult>>;
25
+ };