@yaks/fts 0.0.0-stage → 0.2.36

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/search.ts ADDED
@@ -0,0 +1,585 @@
1
+ // Ranked results, with a snippet.
2
+ //
3
+ // The extension (./compile.ts) decides membership — which entities a search
4
+ // selects. This module answers the other question a search box asks: of those,
5
+ // which come first, and what text matched? That is FTS5's `bm25` relevance and
6
+ // its `snippet()`, both of which can only be read in a statement that queries
7
+ // the index itself, so this module builds those statements and runs them.
8
+ //
9
+ // `hits()` runs them through a driver and returns {@link Hit}s; `find()` reads
10
+ // the indexes' sources off the file first. Ranking is by relevance alone;
11
+ // mixing in recency, popularity or anything else is an application's policy,
12
+ // applied to the results it gets back.
13
+
14
+ import type { Eid } from 'jsr:@yaks/graph@0.2.36'
15
+ import {
16
+ absentFrom,
17
+ among,
18
+ and,
19
+ array,
20
+ as,
21
+ at,
22
+ type BindOpts,
23
+ catalogue,
24
+ col,
25
+ type Cte,
26
+ desc,
27
+ type Driver,
28
+ eq,
29
+ exists,
30
+ type Expr,
31
+ field,
32
+ fn,
33
+ from,
34
+ type Join,
35
+ lit,
36
+ member,
37
+ not,
38
+ op,
39
+ or,
40
+ type Raw,
41
+ type Select,
42
+ select,
43
+ type Selection,
44
+ sourceScreen,
45
+ sub,
46
+ table,
47
+ val,
48
+ when,
49
+ } from '@yaks/sql'
50
+ import type { Vocab } from 'jsr:@yaks/vocab@0.2.36'
51
+ import {
52
+ columnsOf,
53
+ type Field,
54
+ type Index,
55
+ indexes,
56
+ tableOf,
57
+ trim,
58
+ worded,
59
+ } from './fields.js'
60
+ import { excerpt, match, named, wordings } from './term.js'
61
+ import { cut } from './snippet.js'
62
+
63
+ // One search hit: the entity, its rank, and a snippet marking the matches.
64
+ export type Hit = {
65
+ // the matched entity
66
+ entity: Eid
67
+ // FTS5's bm25 for the matched wording, where a lower number is a closer match
68
+ rank: number
69
+ // matching text with distinctive terms wrapped in OPEN…CLOSE for display
70
+ snippet: string
71
+ }
72
+
73
+ export type SearchOpts = {
74
+ // how many hits at most (default 20)
75
+ limit?: number
76
+ // Index-order pages minimize billed rows; a single SQL sort minimizes CPU
77
+ // when reopening a prefix match to refill tied ranks would cost more.
78
+ plan?: 'index' | 'sort'
79
+ // a statement selecting the ids of the entities a hit must be among — pass
80
+ // @yaks/sql's `screen` of the rest of the query, and only rows the filters
81
+ // already allow are ranked. One the compiler made carries its keyed `probe`
82
+ screen?: Selection
83
+ // the owner ids permitted to contribute matching text, per index
84
+ screens?: Record<string, Raw>
85
+ // how many words of context a snippet carries (default 10)
86
+ context?: number
87
+ // External-content sources, keyed by index. find() reads these from the schema.
88
+ content?: Record<string, string>
89
+ // the words as a name is written (./term.ts `named`): a hit whose stored
90
+ // text is exactly this ranks before every other. `hits()` reads it off its
91
+ // text; `ranked()` is handed it beside the match it ranks by
92
+ name?: string
93
+ }
94
+
95
+ type RankOpts = SearchOpts & {
96
+ // Candidate owner ids when the compiler could seek a subset of the filters.
97
+ owners?: readonly number[]
98
+ }
99
+
100
+ // The most owners a screen read whole (@yaks/sql `Selection.whole`) holds for
101
+ // a CPU sort to ask whether any of them carries an index's component before
102
+ // opening it (`best`). Such a screen is read in full to be joined, whichever
103
+ // side drives: `(!entry&!knock&!notification|.created.by.person)` took 3.7 s
104
+ // to say none of the box's 1.9M transcript entries was among its owners,
105
+ // where opening the index and probing each match by key took 0.2 s. A screen
106
+ // past this is read no further, and the index is opened.
107
+ export let PROVE = 1024
108
+
109
+ // Each index has one text source and may be gated by another component.
110
+ // Restrict both before matching, so a public owner cannot reveal private text.
111
+ export let screens = (
112
+ fields: Field[],
113
+ vocab: Vocab,
114
+ opts: BindOpts,
115
+ ): Record<string, Raw> =>
116
+ Object.fromEntries(
117
+ indexes(worded(fields)).flatMap(({ name, comp, on }) => {
118
+ let screen = sourceScreen(vocab, opts, [comp, ...on ? [on] : []])
119
+ return screen ? [[name, screen]] : []
120
+ }),
121
+ )
122
+
123
+ export let permitted = (
124
+ name: string,
125
+ owner: ReturnType<typeof col>,
126
+ screens?: Record<string, Raw>,
127
+ ): Expr => {
128
+ let screen = screens?.[name]
129
+ return screen
130
+ ? exists(select({
131
+ cols: [lit(1)],
132
+ from: from(screen, '__allowed'),
133
+ where: eq(col('id', '__allowed'), owner),
134
+ }))
135
+ : lit(true)
136
+ }
137
+
138
+ // Component owner IDs are integer primary keys, so SQLite can test their
139
+ // indexes directly for IN without building a set or running a subquery per hit.
140
+ export let unworn = (comps: string[] = [], owner: Expr): Expr[] =>
141
+ comps.map((comp) =>
142
+ not(among(owner, select({ cols: [col('entity')], from: table(comp) })))
143
+ )
144
+
145
+ // A prefix match can reopen and merge its postings for each keyed seek.
146
+ export let FEW = 4
147
+
148
+ // Seek into the postings' rowid range once, then test membership without
149
+ // asking FTS5 to reopen and merge a prefix's postings for each owner.
150
+ export let withinOwners = (owner: Expr, ids: readonly number[]): Expr =>
151
+ ids.length <= FEW ? among(owner, ids.map((id) => lit(id))) : and(
152
+ op('>=', owner, lit(Math.min(...ids))),
153
+ op('<=', owner, lit(Math.max(...ids))),
154
+ among(op('+', owner, lit(0)), array(ids)),
155
+ )
156
+
157
+ // The ranked hits for a search, best first, or null when the text contains no
158
+ // word. The words are ANDed terms (./term.ts) and bm25 orders the results, so
159
+ // a search behaves as a set of words rather than as one phrase.
160
+ //
161
+ // The ranking is `best`; a snippet is read last, and only for the rows
162
+ // returned. FTS5 reads a row's text back to cut one, and a search over
163
+ // transcripts matches thousands of rows, some of them megabytes of command
164
+ // output: cutting a snippet for every match before choosing twenty took
165
+ // seconds where ranking alone takes milliseconds.
166
+ let alternatives = (forms: string[]): string =>
167
+ forms.length == 1 ? forms[0] : forms.map((f) => `(${f})`).join(' OR ')
168
+
169
+ // Compare positions across wordings. Putting every term in one BM25 query
170
+ // rewards rows that repeat several spellings, which buries the original text
171
+ // under later discussions of how to find it.
172
+ let interleave = (rankings: Candidate[][], limit: number): Candidate[] => {
173
+ let kept = new Map<number, Candidate>()
174
+ let depth = Math.max(0, ...rankings.map((rows) => rows.length))
175
+ for (let i = 0; i < depth; i++) {
176
+ for (let rows of rankings) {
177
+ let hit = rows[i]
178
+ if (!hit || kept.has(hit.owner)) continue
179
+ kept.set(hit.owner, hit)
180
+ if (kept.size >= limit) return [...kept.values()]
181
+ }
182
+ }
183
+ return [...kept.values()]
184
+ }
185
+
186
+ export let hits = (
187
+ db: Driver,
188
+ fields: Field[],
189
+ text: string,
190
+ opts: SearchOpts = {},
191
+ ): Hit[] | null => {
192
+ let forms = wordings(text)
193
+ let rank = (words: string) =>
194
+ best(db, fields, match(words), { name: named(words), ...opts })
195
+ let literal = rank(text)
196
+ if (!literal) return null
197
+ let ranking = forms.length == 1 ? literal : interleave([
198
+ literal,
199
+ ...forms.slice(1).map((words) => rank(words) ?? []),
200
+ ], opts.limit ?? 20)
201
+ if (!ranking.length) return []
202
+ let context = opts.context ?? 10
203
+ // Membership and rank still use the full match; the excerpt leaves common
204
+ // terms unmarked, so FTS5 does less work cutting large matching texts.
205
+ let marked = alternatives(forms.map(excerpt))
206
+ let ids = (rows: Candidate[]) => rows.map((r) => lit(r.owner))
207
+ // FTS5 takes a rowid list beside a match as one seek an id, and each seek
208
+ // merges again every token a prefix term begins: the forty hits of
209
+ // `yaks.app test space probe live operator our own space` in the box's
210
+ // transcripts merged `test*`, `own*` and the rest forty times, 14.6 s where
211
+ // one pass takes 0.4 s. A CPU sort has already read every match to rank it,
212
+ // so it reads them once more and keeps the ranked ones: `rowid + 0` is no
213
+ // constraint FTS5 is offered. Index-order pages seek, for billed rows.
214
+ let kept = opts.plan == 'sort'
215
+ ? (fts: string) => op('+', col('rowid', fts), lit(0))
216
+ : (fts: string) => col('rowid', fts)
217
+ // Each eid is read by id, a seek a row: asked as a set, SQLite may walk
218
+ // `entity` whole however few the ids, whatever its statistics say.
219
+ let o = at('__owner'), e = at('entity')
220
+ let eids = new Map(
221
+ db.query(select({
222
+ cols: [
223
+ as(o('column1'), 'id'),
224
+ as(
225
+ sub(select({
226
+ cols: [e('eid')],
227
+ from: table('entity'),
228
+ where: eq(e('id'), o('column1')),
229
+ })),
230
+ 'eid',
231
+ ),
232
+ ],
233
+ from: from(
234
+ { t: 'values', rows: ids(ranking).map((id) => [id]) },
235
+ '__owner',
236
+ ),
237
+ })).map((r) => [Number(r.id), String(r.eid)]),
238
+ )
239
+ let snippets = new Map<string, string>()
240
+ indexes(worded(fields), db.stored?.v).forEach((ix, i) => {
241
+ let mine = ranking.filter((r) => r.arm == i)
242
+ if (!mine.length) return
243
+ let fts = tableOf(ix)
244
+ let cuts = db.query(select({
245
+ cols: [
246
+ as(col('rowid', fts), 'owner'),
247
+ as(
248
+ cut(fts, columnsOf(ix), marked, context, opts.content?.[ix.name]),
249
+ 'snippet',
250
+ ),
251
+ ],
252
+ from: table(fts),
253
+ where: and(
254
+ op('match', col(fts), val(marked)),
255
+ among(kept(fts), ids(mine)),
256
+ ),
257
+ }))
258
+ for (let r of cuts) snippets.set(`${i} ${r.owner}`, String(r.snippet ?? ''))
259
+ })
260
+ return ranking.flatMap((r) => {
261
+ let entity = eids.get(r.owner)
262
+ return entity == null ? [] : [{
263
+ entity,
264
+ rank: r.rank,
265
+ snippet: snippets.get(`${r.arm} ${r.owner}`) ?? '',
266
+ }]
267
+ })
268
+ }
269
+
270
+ // The same ranking over a match expression already built from the words
271
+ // (term.ts), without snippets — what `.order=search` ranks by (./compile.ts):
272
+ // the entities' integer owners, best first.
273
+ export let ranked = (
274
+ db: Driver,
275
+ fields: Field[],
276
+ t: string,
277
+ opts: RankOpts = {},
278
+ ): number[] => (best(db, fields, t, opts) ?? []).map((r) => r.owner)
279
+
280
+ // A ranked entity: its integer owner, its bm25 rank, the index it ranked best
281
+ // in (`arm`), and whether its stored text is the words exactly (`named`).
282
+ type Candidate = { owner: number; rank: number; arm: number; named: number }
283
+
284
+ // The best `limit` entities, one row each. An entity's best rank is its
285
+ // `min` across indexes, and its arm the index that rank came from.
286
+ //
287
+ // The ranking runs as a statement a step, and each statement admits through
288
+ // one index's screen. Workerd's SQLite refuses to name a common table
289
+ // expression once a statement holds 100 cursors (@yaks/sql `cursors`), and a
290
+ // visibility screen reads dozens, so four indexes' pages refused as one
291
+ // statement with their screens named, and written out without CTEs they pass
292
+ // the engine's 100 KB. So each index's page, its tied places and its
293
+ // exact names are read alone, and what joins them (the edge of a page, an
294
+ // entity's best index, the order) is plain arithmetic here.
295
+ //
296
+ // A page stops reading at its best rows. Each index answers only its own best
297
+ // `limit` admitted rows (`page`), through FTS5's own `order by rank`, which
298
+ // sorts inside the index and hands back just the rows taken: a yaks.app store
299
+ // bills each row a cursor hands back, so a broad word costs a page, not every
300
+ // match. The best `limit` entities across indexes are among each index's best
301
+ // `limit`, so nothing is lost by cutting each first. Admission (the screen,
302
+ // visibility, a tombstone) is tested as the index hands rows back, so a row
303
+ // the rest of the query refuses never takes a place.
304
+ //
305
+ // Equal matches go newest first, as a listing does, but FTS5 hands equal ranks
306
+ // back oldest first. So an index-order page reads one row past its last place,
307
+ // and when that row ranks the same as the last place, the places at that rank
308
+ // are taken again, newest first, by a `rowid desc` scan of the rows ranking
309
+ // exactly that (`newest`). A CPU sort orders ties itself.
310
+ //
311
+ // A name comes first. bm25 rewards a word said often in a short text, so a
312
+ // task saying "Mossvale" twice in its title outranks the project whose title
313
+ // is the one word, which sat past a hundred others for `mossvale`. So the
314
+ // matches whose stored text is exactly the words, ignoring case (`exactly`),
315
+ // rank before every other. They are found through the index as rows whose
316
+ // text begins with the words (FTS5's `^`), and only those rows are read to
317
+ // compare.
318
+ let best = (
319
+ db: Driver,
320
+ fields: Field[],
321
+ t: string,
322
+ opts: RankOpts,
323
+ ): Candidate[] | null => {
324
+ let arms = indexes(worded(fields), db.stored?.v)
325
+ if (!t || !arms.length) return null
326
+ if (opts.owners?.length == 0) return []
327
+ let limit = opts.limit ?? 20
328
+ let sorting = opts.plan == 'sort'
329
+ // A compiler screen can join the postings by owner ID. Keep the FTS cursor
330
+ // first so a sparse term never walks the visibility relation to find its
331
+ // matches. A bare screen on the CPU sort is read once per statement.
332
+ let keyed = opts.owners ? undefined : opts.screen?.keyed
333
+ let probed = !!opts.screen?.probe
334
+ let screen: Cte[] = opts.screen &&
335
+ (sorting && !opts.owners || !keyed && !probed)
336
+ ? [{
337
+ name: '__fts_screen',
338
+ // Selection already projects id. Keep the CTE eligible for unfolding.
339
+ q: opts.screen,
340
+ materialized: sorting && !probed,
341
+ }]
342
+ : []
343
+ let ask = (q: Select, arm: number, named: 0 | 1): Candidate[] => {
344
+ let joins: Join[] = keyed
345
+ ? [{
346
+ how: 'cross',
347
+ src: from(keyed, '__fts_visible'),
348
+ on: eq(
349
+ col('id', '__fts_visible'),
350
+ col('rowid', tableOf(arms[arm])),
351
+ ),
352
+ }]
353
+ : []
354
+ return db.query({ ...q, with: screen, joins }).map((r) => ({
355
+ owner: Number(r.owner),
356
+ rank: Number(r.rank),
357
+ arm,
358
+ named,
359
+ }))
360
+ }
361
+ let eligible = (owner: Expr) =>
362
+ probed ? member(opts.screen!, owner) : exists(select({
363
+ cols: [lit(1)],
364
+ from: table('__fts_screen'),
365
+ where: eq(col('id', '__fts_screen'), owner),
366
+ }))
367
+ // A kind can have no owners in an index at all. A CPU sort proves that
368
+ // through the selected owners' component keys before opening its cursor.
369
+ // Joined, not crossed, with the index's component first: SQLite drives from
370
+ // the smaller side, so a broad screen seeks a rare component's few owners,
371
+ // and a rare component seeks a broad screen's, rather than walking either
372
+ // in id order to find one. A screen's own CROSS JOIN pins every table
373
+ // written after it, so the component written second could only be probed:
374
+ // `.entry` walked 1.9M transcript entries to find one carrying a doc.
375
+ let source = (arm: Index) => table(arm.on ?? arm.comp, '__source')
376
+ let owned = (arm: Index): Select =>
377
+ opts.owners
378
+ ? select({
379
+ cols: [lit(1)],
380
+ from: from(array(opts.owners), '__fts_screen'),
381
+ joins: [{
382
+ how: 'cross',
383
+ src: source(arm),
384
+ on: eq(col('entity', '__source'), col('value', '__fts_screen')),
385
+ }],
386
+ })
387
+ : select({
388
+ cols: [lit(1)],
389
+ from: source(arm),
390
+ joins: [{
391
+ how: 'join',
392
+ src: table('__fts_screen'),
393
+ on: eq(col('entity', '__source'), col('id', '__fts_screen')),
394
+ }],
395
+ })
396
+ // A screen read whole is asked no further than PROVE owners: one past them
397
+ // opens the index.
398
+ let wide = (n: number): [Expr, Expr][] =>
399
+ !opts.owners && opts.screen?.whole
400
+ ? [[
401
+ exists(select({
402
+ cols: [lit(1)],
403
+ from: table('__fts_screen'),
404
+ limit: lit(1),
405
+ offset: lit(PROVE),
406
+ })),
407
+ lit(n),
408
+ ]]
409
+ : []
410
+ let take = (arm: Index, n: number): Expr =>
411
+ opts.owners || sorting && opts.screen
412
+ ? when([...wide(n), [exists(owned(arm)), lit(n)]], lit(0))
413
+ : lit(n)
414
+ // An index's rows matching `expr`, among the live owners the caller admits.
415
+ let admitted: Admitted = (ix, expr) => {
416
+ let fts = tableOf(ix)
417
+ let owner = col('rowid', fts)
418
+ return and(
419
+ op('match', col(fts), val(expr)),
420
+ ...opts.owners ? [withinOwners(owner, opts.owners)] : [],
421
+ permitted(ix.name, owner, opts.screens),
422
+ ...unworn(
423
+ ['tombstone', ...ix.not ?? []],
424
+ owner,
425
+ ),
426
+ ...opts.screen && !keyed ? [eligible(owner)] : [],
427
+ )
428
+ }
429
+ let found = arms.flatMap((arm, i) => {
430
+ let page = ask(
431
+ select({
432
+ cols: [as(col('rowid'), 'owner'), as(col('rank'), 'rank')],
433
+ from: table(tableOf(arm)),
434
+ where: admitted(arm, t),
435
+ order: [col('rank'), ...sorting ? [desc(col('rowid'))] : []],
436
+ limit: take(arm, sorting ? limit : limit + 1),
437
+ }),
438
+ i,
439
+ 0,
440
+ )
441
+ let worst = page.at(-1)?.rank
442
+ let tied = page.filter((r) => r.rank == worst).length
443
+ let placed = page.length > limit
444
+ ? [
445
+ ...page.filter((r) => r.rank != worst),
446
+ ...tied > 1
447
+ ? ask(newest(arm, t, worst!, tied - 1, admitted), i, 0)
448
+ : [],
449
+ ]
450
+ : page
451
+ let names = opts.name
452
+ ? ask(exactly(arm, t, opts.name, take(arm, limit), admitted), i, 1)
453
+ : []
454
+ return [...placed, ...names]
455
+ })
456
+ let by = new Map<number, Candidate>()
457
+ for (let c of found) {
458
+ let held = by.get(c.owner)
459
+ if (!held) by.set(c.owner, { ...c })
460
+ else {
461
+ if (c.rank < held.rank) Object.assign(held, { rank: c.rank, arm: c.arm })
462
+ held.named = Math.max(held.named, c.named)
463
+ }
464
+ }
465
+ return [...by.values()]
466
+ .sort((a, b) => b.named - a.named || a.rank - b.rank || b.owner - a.owner)
467
+ .slice(0, limit)
468
+ }
469
+
470
+ type Admitted = (ix: Index, expr: string) => Expr
471
+
472
+ // An index's places at its worst rank `worst` when the row past its last place
473
+ // ties with them, taken again newest first: `room` of them, all who share that
474
+ // rank but the row past. It matches the rank through `bm25`, since FTS5 reads
475
+ // a constraint on `rank` as its configuration.
476
+ let newest = (
477
+ ix: Index,
478
+ t: string,
479
+ worst: number,
480
+ room: number,
481
+ admitted: Admitted,
482
+ ): Select => {
483
+ let fts = tableOf(ix)
484
+ return select({
485
+ cols: [as(col('rowid'), 'owner'), as(col('rank'), 'rank')],
486
+ from: table(fts),
487
+ where: and(eq(fn('bm25', col(fts)), val(worst)), admitted(ix, t)),
488
+ order: [desc(col('rowid'))],
489
+ limit: lit(room),
490
+ })
491
+ }
492
+
493
+ // An index's best `limit` admitted owners whose stored text, in any of its
494
+ // columns, is exactly `name`: the rows whose text begins with it (`^`), each
495
+ // read once to compare, and each ranked by the words `t` as a hit is. In an
496
+ // index of one column every such row says the same words in the same length,
497
+ // so all rank alike and the best are the newest: the scan stops at `limit`.
498
+ // In an index of several, the rest of a row moves its rank, so every name is
499
+ // ranked. A property kept elsewhere is compared as stored: a body @yaks/blob
500
+ // holds is its address, never its words.
501
+ let exactly = (
502
+ ix: Index,
503
+ t: string,
504
+ name: string,
505
+ limit: Expr,
506
+ admitted: Admitted,
507
+ ): Select => {
508
+ let { comp, props } = ix, fts = tableOf(ix)
509
+ let n = at('__named')
510
+ let same = (p: string) =>
511
+ eq(fn('lower', fn('trim', n(field(p)))), fn('lower', val(name)))
512
+ let rank = sub(select({
513
+ cols: [col('rank', '__rank')],
514
+ from: table(fts, '__rank'),
515
+ where: and(
516
+ op('match', col(fts, '__rank'), val(t)),
517
+ eq(col('rowid', '__rank'), col('rowid', fts)),
518
+ ),
519
+ }))
520
+ return select({
521
+ cols: [as(col('rowid'), 'owner'), as(rank, 'rank')],
522
+ from: table(fts),
523
+ where: and(
524
+ admitted(ix, `^"${name.replaceAll('"', '')}"`),
525
+ exists(select({
526
+ cols: [lit(1)],
527
+ from: table(comp, '__named'),
528
+ where: and(
529
+ eq(n('entity'), col('rowid', fts)),
530
+ or(...props.map(same)),
531
+ ),
532
+ })),
533
+ ),
534
+ order: [...props.length > 1 ? [col('rank')] : [], desc(col('rowid'))],
535
+ limit,
536
+ })
537
+ }
538
+
539
+ /** What {@link find} is asked beside its words: {@link SearchOpts} less the
540
+ * screens and sources it reads off the file itself. */
541
+ export type FindOpts = Omit<SearchOpts, 'screens' | 'content'> & {
542
+ // The reader's scope (@yaks/graph `scope`). The vocabulary supplies the
543
+ // layout for its screen when the connection has no fitted vocabulary.
544
+ scope?: BindOpts
545
+ vocab?: Vocab
546
+ }
547
+
548
+ // The hits for a search, closest first. Returns [] for text containing no word
549
+ // and for a vocabulary with nothing indexed — a search that cannot be run finds
550
+ // nothing, rather than everything.
551
+ export let find = (
552
+ db: Driver,
553
+ fields: Field[],
554
+ text: string,
555
+ { scope, vocab, ...opts }: FindOpts = {},
556
+ ): Hit[] => {
557
+ let v = db.stored?.v
558
+ let layout = v ?? vocab
559
+ if (scope && !layout) throw new Error('a scoped search requires a vocabulary')
560
+ let tables = catalogue(db).filter((o) => o.type == 'table')
561
+ let namesOf = new Map(
562
+ indexes(worded(fields), v).map((ix) => [tableOf(ix), ix.name]),
563
+ )
564
+ let content = Object.fromEntries(tables.flatMap((o) => {
565
+ let source = /content='([^']*)'/.exec(o.sql ?? '')?.[1]
566
+ let name = namesOf.get(o.name)
567
+ return source && name != null ? [[name, source]] : []
568
+ }))
569
+ // An index stands once its component's first write made it, and a scope
570
+ // reads a component no table stands for as worn by nobody (@yaks/sqlite).
571
+ let names = new Set(tables.map((o) => o.name))
572
+ let live = fields.filter((f) => (f.on ?? f.comp) in content)
573
+ .map((f) => trim(f, (comp) => names.has(comp)))
574
+ return hits(db, live, text, {
575
+ plan: db.file ? 'sort' : 'index',
576
+ content,
577
+ ...scope && layout && {
578
+ screens: screens(live, layout, {
579
+ ...scope,
580
+ absent: absentFrom(layout, names),
581
+ }),
582
+ },
583
+ ...opts,
584
+ }) ?? []
585
+ }
package/snippet.js ADDED
@@ -0,0 +1,79 @@
1
+ // FTS5 retokenizes a whole external-content row to cut its best snippet.
2
+ // Bound that work: large transcripts get a term-centered text window instead.
3
+ import { as, col, eq, fn, lit, op, select, sub, table, val, when } from "@yaks/sql";
4
+ import { CLOSE, OPEN } from "./term.js";
5
+ export let TOKENIZE = 64 * 1024;
6
+ let join = (...parts)=>parts.reduce((a, b)=>op('||', a, b));
7
+ // The longest displayed phrase is a useful anchor even when a body repeats
8
+ // short terms thousands of times. Membership and ranking remain FTS5's.
9
+ let anchor = (marked)=>[
10
+ ...marked.matchAll(/"([^"]+)"/g)
11
+ ].map((m)=>m[1]).sort((a, b)=>b.length - a.length)[0] ?? '';
12
+ let window = (text, needle, context)=>{
13
+ let p = col('position'), source = text;
14
+ if (!needle) return lit(null);
15
+ return sub(select({
16
+ with: [
17
+ {
18
+ name: '__window',
19
+ q: select({
20
+ cols: [
21
+ as(fn('coalesce', fn('nullif', fn('instr', text, val(needle)), lit(0)), fn('instr', fn('lower', text), fn('lower', val(needle)))), 'position')
22
+ ]
23
+ }),
24
+ materialized: true
25
+ }
26
+ ],
27
+ cols: [
28
+ when([
29
+ [
30
+ op('>', p, lit(0)),
31
+ join(when([
32
+ [
33
+ op('>', p, lit(context * 4 + 1)),
34
+ lit('…')
35
+ ]
36
+ ], lit('')), fn('substr', source, fn('max', lit(1), op('-', p, lit(context * 4))), fn('min', op('-', p, lit(1)), lit(context * 4))), lit(OPEN), fn('substr', source, p, fn('length', val(needle))), lit(CLOSE), fn('substr', source, op('+', p, fn('length', val(needle))), lit(context * 8)), lit('…'))
37
+ ]
38
+ ], lit(null))
39
+ ],
40
+ from: table('__window')
41
+ }));
42
+ };
43
+ export let cut = (fts, props, marked, context, content)=>{
44
+ let size = props.map((p)=>fn('coalesce', fn('length', col(p)), lit(0))).reduce((a, b)=>op('+', a, b));
45
+ let needle = anchor(marked);
46
+ let large = fn('coalesce', ...props.map((p)=>{
47
+ let text = col(p);
48
+ return window(text, needle, context);
49
+ }), fn('substr', col(props[0]), lit(1), lit(context * 12)));
50
+ return sub(select({
51
+ with: [
52
+ {
53
+ name: '__source',
54
+ q: select({
55
+ cols: props.map((p)=>as(fn('substr', col(p, content ?? fts), lit(1), lit(1024 * 1024)), p)),
56
+ ...content ? {
57
+ from: {
58
+ t: 'table',
59
+ name: content,
60
+ physical: true
61
+ },
62
+ where: eq(col('entity', content), col('rowid', fts))
63
+ } : {}
64
+ }),
65
+ materialized: true
66
+ }
67
+ ],
68
+ cols: [
69
+ when([
70
+ [
71
+ op('>', size, lit(TOKENIZE)),
72
+ large
73
+ ]
74
+ ], fn('snippet', col(fts), lit(-1), lit(OPEN), lit(CLOSE), lit('…'), lit(context)))
75
+ ],
76
+ from: table('__source')
77
+ }));
78
+ };
79
+ //# sourceMappingURL=snippet.js.map
package/snippet.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"snippet.js","sources":["./snippet.ts"],"names":[],"mappings":"AAAA,yEAAyE;AACzE,8EAA8E;AAC9E,SACE,EAAE,EACF,GAAG,EACH,EAAE,EAEF,EAAE,EACF,GAAG,EACH,EAAE,EACF,MAAM,EACN,GAAG,EACH,KAAK,EACL,GAAG,EACH,IAAI,yBACuB;AAC7B,SAAS,KAAK,E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