@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/snippet.ts ADDED
@@ -0,0 +1,125 @@
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 {
4
+ as,
5
+ col,
6
+ eq,
7
+ type Expr,
8
+ fn,
9
+ lit,
10
+ op,
11
+ select,
12
+ sub,
13
+ table,
14
+ val,
15
+ when,
16
+ } from '@yaks/sql'
17
+ import { CLOSE, OPEN } from './term.js'
18
+
19
+ export let TOKENIZE = 64 * 1024
20
+
21
+ let join = (...parts: Expr[]) => parts.reduce((a, b) => op('||', a, b))
22
+
23
+ // The longest displayed phrase is a useful anchor even when a body repeats
24
+ // short terms thousands of times. Membership and ranking remain FTS5's.
25
+ let anchor = (marked: string) =>
26
+ [...marked.matchAll(/"([^"]+)"/g)].map((m) => m[1])
27
+ .sort((a, b) => b.length - a.length)[0] ?? ''
28
+
29
+ let window = (text: Expr, needle: string, context: number): Expr => {
30
+ let p = col('position'), source = text
31
+ if (!needle) return lit(null)
32
+ return sub(select({
33
+ with: [{
34
+ name: '__window',
35
+ q: select({
36
+ cols: [
37
+ as(
38
+ fn(
39
+ 'coalesce',
40
+ fn('nullif', fn('instr', text, val(needle)), lit(0)),
41
+ fn('instr', fn('lower', text), fn('lower', val(needle))),
42
+ ),
43
+ 'position',
44
+ ),
45
+ ],
46
+ }),
47
+ materialized: true,
48
+ }],
49
+ cols: [when([[
50
+ op('>', p, lit(0)),
51
+ join(
52
+ when([[op('>', p, lit(context * 4 + 1)), lit('…')]], lit('')),
53
+ fn(
54
+ 'substr',
55
+ source,
56
+ fn('max', lit(1), op('-', p, lit(context * 4))),
57
+ fn('min', op('-', p, lit(1)), lit(context * 4)),
58
+ ),
59
+ lit(OPEN),
60
+ fn('substr', source, p, fn('length', val(needle))),
61
+ lit(CLOSE),
62
+ fn(
63
+ 'substr',
64
+ source,
65
+ op('+', p, fn('length', val(needle))),
66
+ lit(context * 8),
67
+ ),
68
+ lit('…'),
69
+ ),
70
+ ]], lit(null))],
71
+ from: table('__window'),
72
+ }))
73
+ }
74
+
75
+ export let cut = (
76
+ fts: string,
77
+ props: string[],
78
+ marked: string,
79
+ context: number,
80
+ content?: string,
81
+ ): Expr => {
82
+ let size = props.map((p) => fn('coalesce', fn('length', col(p)), lit(0)))
83
+ .reduce((a, b) => op('+', a, b))
84
+ let needle = anchor(marked)
85
+ let large = fn(
86
+ 'coalesce',
87
+ ...props.map((p) => {
88
+ let text = col(p)
89
+ return window(text, needle, context)
90
+ }),
91
+ fn('substr', col(props[0]), lit(1), lit(context * 12)),
92
+ )
93
+ return sub(select({
94
+ with: [{
95
+ name: '__source',
96
+ q: select({
97
+ cols: props.map((p) =>
98
+ as(fn('substr', col(p, content ?? fts), lit(1), lit(1024 * 1024)), p)
99
+ ),
100
+ ...content
101
+ ? {
102
+ from: { t: 'table' as const, name: content, physical: true },
103
+ where: eq(col('entity', content), col('rowid', fts)),
104
+ }
105
+ : {},
106
+ }),
107
+ materialized: true,
108
+ }],
109
+ cols: [
110
+ when(
111
+ [[op('>', size, lit(TOKENIZE)), large]],
112
+ fn(
113
+ 'snippet',
114
+ col(fts),
115
+ lit(-1),
116
+ lit(OPEN),
117
+ lit(CLOSE),
118
+ lit('…'),
119
+ lit(context),
120
+ ),
121
+ ),
122
+ ],
123
+ from: table('__source'),
124
+ }))
125
+ }
package/term.js ADDED
@@ -0,0 +1,153 @@
1
+ // The two pieces of text this package is careful about: what goes into an FTS5
2
+ // match, and what comes back marked.
3
+ //
4
+ // FTS5's match syntax is a small language of its own — quotes, near, boolean
5
+ // operators, column filters. What a person types into a search box is none of
6
+ // that; it is just text. So every word is written as a quoted phrase, which
7
+ // makes each character in it literal, and the only match syntax a person can
8
+ // reach is two things: a quoted run, which stays one phrase, and a trailing
9
+ // `*`.
10
+ //
11
+ // Words, not one phrase. What somebody types is a set of words — `entropy
12
+ // purge`, or a whole question — and each word becomes a term of its own, ANDed
13
+ // together and ranked by relevance (./search.ts). Turning the whole string into
14
+ // a single phrase would match only where those words appear next to each other
15
+ // in that order, which means a question typed into a search box finds nothing
16
+ // at all. A bare word also matches as a prefix, so `research` finds
17
+ // `researching`: the tokenizer does not stem, and a word's ending is the part a
18
+ // person is least deliberate about. The cost is a wider match — `fix` also
19
+ // matches `fixture` — which is what the ranking is for. Quoting is how somebody
20
+ // asks for exactly those words, in that order.
21
+ //
22
+ // Matches come back wrapped in two control characters rather than in HTML. A
23
+ // snippet is content, and content that arrives as markup is markup a renderer
24
+ // has to trust; a control character is a mark no browser and no terminal acts
25
+ // on, and every renderer can turn it into whatever emphasis it likes.
26
+ // The characters a snippet wraps each match in.
27
+ export let OPEN = '\x01';
28
+ export let CLOSE = '\x02';
29
+ // One typed word, or one quoted run, as a safe FTS5 term: every character in it
30
+ // literal. A single word matches as a prefix, unless it is a common word (a
31
+ // grammatical word is whole as typed) or its last token is shorter than three
32
+ // letters: FTS5 reads a prefix by merging every token it begins, and `a*`,
33
+ // `of*`, or the `s*` that ends `step's`, merges a large share of a big index
34
+ // for a word nobody meant to complete. A run becomes a phrase, matched
35
+ // exactly, and a trailing `*` makes its final word a prefix match. Returns ''
36
+ // for text containing no word — a caller must read that as "matches
37
+ // nothing", never as "matches everything".
38
+ export let term = (text)=>{
39
+ let star = /\*+$/.test(text);
40
+ let phrase = text.replace(/\*+$/, '').replaceAll('"', '').trim();
41
+ if (!phrase) return '';
42
+ let open = !/\s/.test(phrase) && !common(phrase) && (phrase.match(TOKEN)?.at(-1)?.length ?? 0) > 2;
43
+ return `"${phrase}"${star || open ? '*' : ''}`;
44
+ };
45
+ // A token as FTS5's default tokenizer reads one: a run of letters and digits.
46
+ let TOKEN = /[\p{L}\p{N}]+/gu;
47
+ // Grammatical words. They still take part in matching and ranking, as whole
48
+ // words; an excerpt leaves them unmarked, since they obscure the useful words
49
+ // and make FTS5 scan large matches just to cut the display text.
50
+ let COMMON = new Set('a an and are as at be by for from in is it of on or the to was were with about after all also am any before between but can could did do does each had has have if into its may more my not our out per so than that their them there these this those through up we what when where which who will would your'.split(' '));
51
+ // Whether a typed word is one of the {@link COMMON} ones, its trailing
52
+ // punctuation aside. A quoted run never is.
53
+ let common = (word)=>!word.startsWith('"') && COMMON.has(word.toLowerCase().replace(/\W+$/, ''));
54
+ // A quoted run is one token; everything else splits on whitespace. An unclosed
55
+ // quote takes the rest of the string, which is what somebody halfway through
56
+ // typing a phrase means by it.
57
+ let WORDS = /"[^"]*"?|\S+/g;
58
+ // What somebody typed, as its words and quoted runs, each as typed.
59
+ export let split = (text)=>text.match(WORDS) ?? [];
60
+ // A whole search string as an FTS5 match expression: each word becomes its own
61
+ // {@link term}, each quoted run becomes one phrase, and they are ANDed together
62
+ // (FTS5 treats a space that way). Order of results comes from the ranking, not
63
+ // from here. Returns '' for text containing no word, just as `term` does.
64
+ export let match = (text)=>split(text).map(term).filter(Boolean).join(' ');
65
+ // The words as a name is written: quotes and stars gone, one space between
66
+ // them. A hit whose whole text is this is the thing searched for by name
67
+ // (./search.ts ranks it first). Returns '' for text containing no word.
68
+ export let named = (text)=>split(text).map((word)=>word.replace(/\*+$/, '').replaceAll('"', '').trim()).filter(Boolean).join(' ');
69
+ // The distinctive words of a text, each a search of its own: what a question
70
+ // is about once its grammatical words are gone. A quoted phrase stays whole.
71
+ export let keywords = (text)=>split(text).filter((word)=>!common(word));
72
+ // Common wording for the same lifecycle event. Keep the literal query as
73
+ // well, and leave quoted terms to the person who asked for exact words.
74
+ let END_OF_LIFE = '(?<![\\w.-])(?:end[\\s-]+of[\\s-]+life|eol)\\b(?![\\w-])';
75
+ let LIFECYCLE = /"[^"]*"?/.source + '|' + END_OF_LIFE + '(?:\\s+' + END_OF_LIFE + ')*';
76
+ export let lifecycleTerms = [
77
+ 'sunset*',
78
+ 'eol',
79
+ 'end of life'
80
+ ];
81
+ let lifecycle = (text, word)=>text.replace(new RegExp(LIFECYCLE, 'gi'), (m)=>m.startsWith('"') ? m : word);
82
+ /** Literal and alternate word searches for a product's end of life. */ export let wordings = (text)=>[
83
+ ...new Set([
84
+ text,
85
+ ...lifecycleTerms.map((word)=>lifecycle(text, word.includes(' ') ? `"${word}"` : word))
86
+ ])
87
+ ];
88
+ /** Wording to embed for a ranked search. Keep the literal query for FTS. */ export let meaningWords = (text)=>lifecycle(text, 'sunset');
89
+ /** The subject immediately before an end-of-life premise in prose. */ export let lifecycleSubject = (text)=>{
90
+ let premise = new RegExp(END_OF_LIFE, 'i').exec(text);
91
+ if (!premise) return;
92
+ let subject = /(?:^|[^\p{L}\p{N}_.-])`?([\p{L}\p{N}][\p{L}\p{N}_.-]*)`?(?:['’]s)?(?:\s+(?:is|was|reached))?\s+$/iu.exec(text.slice(0, premise.index))?.[1];
93
+ return subject && !common(subject) ? subject : undefined;
94
+ };
95
+ // Mark distinctive words in a snippet, while still searching for *all* words.
96
+ // Keep quoted phrases intact, even those made only of common words, and a
97
+ // common word explicitly starred. If the query has nothing else, marking one
98
+ // word is better than a blank excerpt or an expensive snippet of all common
99
+ // terms.
100
+ export let excerpt = (text)=>{
101
+ let words = split(text).filter((word)=>word.endsWith('*') || !common(word));
102
+ return words.length ? words.map(term).filter(Boolean).join(' ') : term(split(text).find((word)=>term(word)) ?? '');
103
+ };
104
+ // How many of a needle's trigrams a substring test asks the index for. All of
105
+ // them would narrow no better than a spread: what one misses, the test that
106
+ // reads each row catches.
107
+ export let GRAMS = 8;
108
+ // A `~=` needle as a query of a substring index (`contains: true`): up to
109
+ // `most` of its trigrams, spread from its start to its end, each quoted and
110
+ // all required. An index keeping only which rows hold each trigram answers
111
+ // the rows holding all of them, every row that holds the needle among them.
112
+ // Null for a needle shorter than a trigram, which the index cannot find.
113
+ ///
114
+ /// grammed('wyrm') -> '"wyr" AND "yrm"'
115
+ /// grammed('a"b') -> '"a""b"'
116
+ /// grammed('ab') -> null
117
+ /// grammed('abcdefghij', 3) -> '"abc" AND "efg" AND "hij"'
118
+ export let grammed = (needle, most = GRAMS)=>{
119
+ let chars = [
120
+ ...needle
121
+ ];
122
+ let last = chars.length - 3;
123
+ if (last < 0) return null;
124
+ let n = Math.min(most, last + 1);
125
+ let at = new Set(Array.from({
126
+ length: n
127
+ }, (_, i)=>Math.round(n > 1 ? i * last / (n - 1) : 0)));
128
+ return [
129
+ ...at
130
+ ].map((i)=>`"${chars.slice(i, i + 3).join('').replaceAll('"', '""')}"`).join(' AND ');
131
+ };
132
+ // An ASCII `~=` needle as a phrase of a word index: its whole words in order,
133
+ // as FTS5's default tokenizer splits them (runs of letters and digits), less a
134
+ // first one it may have cut from the end of a longer word. A last one it may
135
+ // have cut is the start of its word, and stays as the phrase's prefix token. A
136
+ // text holding the needle holds those words one after another, so a word index
137
+ // that keeps where each word stands finds every such text, and few others:
138
+ // dropping the last word as well left `unless Jeff explicitly` the phrase
139
+ // "jeff", which more than 4,000 transcript texts hold, and the read walked the
140
+ // box's 17 million entities (bug fe86c295); "jeff explicitly" * is in 31. Null
141
+ // for a needle with no word inside it but one it may have cut from its start.
142
+ ///
143
+ /// phrased('apps shows the new button') -> '"shows the new button" *'
144
+ /// phrased(' the new') -> '"the new" *'
145
+ /// phrased('on-the hoard.') -> '"the hoard"'
146
+ /// phrased(' wyrm') -> '"wyrm" *'
147
+ /// phrased('wyrmling') -> null
148
+ export let phrased = (needle)=>{
149
+ let words = (needle.match(/[a-z0-9]+/gi) ?? []).slice(Number(/^[a-z0-9]/i.test(needle)));
150
+ let cut = /[a-z0-9]$/i.test(needle) ? ' *' : '';
151
+ return words.length ? `"${words.join(' ')}"${cut}` : null;
152
+ };
153
+ //# sourceMappingURL=term.js.map
package/term.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"term.js","sources":["./term.ts"],"names":[],"mappings":"AAAA,+EAA+E;AAC/E,qCAAqC;AACrC,EAAE;AACF,6EAA6E;AAC7E,8EAA8E;AAC9E,4EAA4E;AAC5E,6E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GAAG,IAAI,CAAC,IAAI,UAAU,CAAC,KAAK,MAAM,CAAC,CAAC,EACtE,IAAI,CAAC;AACV,EAAC;AAED,8EAA8E;AAC9E,+EAA+E;AAC/E,6EAA6E;AAC7E,+EAA+E;AAC/E,+EAA+E;AAC/E,2EAA2E;AAC3E,0EAA0E;AAC1E,+EAA+E;AAC/E,+EAA+E;AAC/E,8EAA8E;AAC9E,GAAG;AACH,sEAAsE;AACtE,wCAAwC;AACxC,6CAA6C;AAC7C,kCAAkC;AAClC,+BAA+B;AAC/B,OAAO,IAAI,UAAU,CAAC;EACpB,IAAI,QAAQ,CAAC,OAAO,KAAK,CAAC,kBAAkB,EAAE,EAC3C,KAAK,CAAC,OAAO,aAAa,IAAI,CAAC;EAClC,IAAI,MAAM,aAAa,IAAI,CAAC,UAAU,OAAO;EAC7C,OAAO,MAAM,MAAM,GAAG,CAAC,CAAC,EAAE,MAAM,IAAI,CAAC,KAAK,CAAC,EAAE,KAAK,GAAG;AACvD,EAAC"}
package/term.ts ADDED
@@ -0,0 +1,193 @@
1
+ // The two pieces of text this package is careful about: what goes into an FTS5
2
+ // match, and what comes back marked.
3
+ //
4
+ // FTS5's match syntax is a small language of its own — quotes, near, boolean
5
+ // operators, column filters. What a person types into a search box is none of
6
+ // that; it is just text. So every word is written as a quoted phrase, which
7
+ // makes each character in it literal, and the only match syntax a person can
8
+ // reach is two things: a quoted run, which stays one phrase, and a trailing
9
+ // `*`.
10
+ //
11
+ // Words, not one phrase. What somebody types is a set of words — `entropy
12
+ // purge`, or a whole question — and each word becomes a term of its own, ANDed
13
+ // together and ranked by relevance (./search.ts). Turning the whole string into
14
+ // a single phrase would match only where those words appear next to each other
15
+ // in that order, which means a question typed into a search box finds nothing
16
+ // at all. A bare word also matches as a prefix, so `research` finds
17
+ // `researching`: the tokenizer does not stem, and a word's ending is the part a
18
+ // person is least deliberate about. The cost is a wider match — `fix` also
19
+ // matches `fixture` — which is what the ranking is for. Quoting is how somebody
20
+ // asks for exactly those words, in that order.
21
+ //
22
+ // Matches come back wrapped in two control characters rather than in HTML. A
23
+ // snippet is content, and content that arrives as markup is markup a renderer
24
+ // has to trust; a control character is a mark no browser and no terminal acts
25
+ // on, and every renderer can turn it into whatever emphasis it likes.
26
+
27
+ // The characters a snippet wraps each match in.
28
+ export let OPEN = '\x01'
29
+ export let CLOSE = '\x02'
30
+
31
+ // One typed word, or one quoted run, as a safe FTS5 term: every character in it
32
+ // literal. A single word matches as a prefix, unless it is a common word (a
33
+ // grammatical word is whole as typed) or its last token is shorter than three
34
+ // letters: FTS5 reads a prefix by merging every token it begins, and `a*`,
35
+ // `of*`, or the `s*` that ends `step's`, merges a large share of a big index
36
+ // for a word nobody meant to complete. A run becomes a phrase, matched
37
+ // exactly, and a trailing `*` makes its final word a prefix match. Returns ''
38
+ // for text containing no word — a caller must read that as "matches
39
+ // nothing", never as "matches everything".
40
+ export let term = (text: string): string => {
41
+ let star = /\*+$/.test(text)
42
+ let phrase = text.replace(/\*+$/, '').replaceAll('"', '').trim()
43
+ if (!phrase) return ''
44
+ let open = !/\s/.test(phrase) && !common(phrase) &&
45
+ (phrase.match(TOKEN)?.at(-1)?.length ?? 0) > 2
46
+ return `"${phrase}"${star || open ? '*' : ''}`
47
+ }
48
+
49
+ // A token as FTS5's default tokenizer reads one: a run of letters and digits.
50
+ let TOKEN = /[\p{L}\p{N}]+/gu
51
+
52
+ // Grammatical words. They still take part in matching and ranking, as whole
53
+ // words; an excerpt leaves them unmarked, since they obscure the useful words
54
+ // and make FTS5 scan large matches just to cut the display text.
55
+ let COMMON = new Set(
56
+ 'a an and are as at be by for from in is it of on or the to was were with about after all also am any before between but can could did do does each had has have if into its may more my not our out per so than that their them there these this those through up we what when where which who will would your'
57
+ .split(' '),
58
+ )
59
+
60
+ // Whether a typed word is one of the {@link COMMON} ones, its trailing
61
+ // punctuation aside. A quoted run never is.
62
+ let common = (word: string): boolean =>
63
+ !word.startsWith('"') && COMMON.has(word.toLowerCase().replace(/\W+$/, ''))
64
+
65
+ // A quoted run is one token; everything else splits on whitespace. An unclosed
66
+ // quote takes the rest of the string, which is what somebody halfway through
67
+ // typing a phrase means by it.
68
+ let WORDS = /"[^"]*"?|\S+/g
69
+
70
+ // What somebody typed, as its words and quoted runs, each as typed.
71
+ export let split = (text: string): string[] => text.match(WORDS) ?? []
72
+
73
+ // A whole search string as an FTS5 match expression: each word becomes its own
74
+ // {@link term}, each quoted run becomes one phrase, and they are ANDed together
75
+ // (FTS5 treats a space that way). Order of results comes from the ranking, not
76
+ // from here. Returns '' for text containing no word, just as `term` does.
77
+ export let match = (text: string): string =>
78
+ split(text).map(term).filter(Boolean).join(' ')
79
+
80
+ // The words as a name is written: quotes and stars gone, one space between
81
+ // them. A hit whose whole text is this is the thing searched for by name
82
+ // (./search.ts ranks it first). Returns '' for text containing no word.
83
+ export let named = (text: string): string =>
84
+ split(text)
85
+ .map((word) => word.replace(/\*+$/, '').replaceAll('"', '').trim())
86
+ .filter(Boolean).join(' ')
87
+
88
+ // The distinctive words of a text, each a search of its own: what a question
89
+ // is about once its grammatical words are gone. A quoted phrase stays whole.
90
+ export let keywords = (text: string): string[] =>
91
+ split(text).filter((word) => !common(word))
92
+
93
+ // Common wording for the same lifecycle event. Keep the literal query as
94
+ // well, and leave quoted terms to the person who asked for exact words.
95
+ let END_OF_LIFE = '(?<![\\w.-])(?:end[\\s-]+of[\\s-]+life|eol)\\b(?![\\w-])'
96
+ let LIFECYCLE = /"[^"]*"?/.source + '|' +
97
+ END_OF_LIFE + '(?:\\s+' + END_OF_LIFE + ')*'
98
+ export let lifecycleTerms: readonly string[] = ['sunset*', 'eol', 'end of life']
99
+
100
+ let lifecycle = (text: string, word: string): string =>
101
+ text.replace(
102
+ new RegExp(LIFECYCLE, 'gi'),
103
+ (m) => m.startsWith('"') ? m : word,
104
+ )
105
+
106
+ /** Literal and alternate word searches for a product's end of life. */
107
+ export let wordings = (text: string): string[] => [
108
+ ...new Set([
109
+ text,
110
+ ...lifecycleTerms.map((word) =>
111
+ lifecycle(text, word.includes(' ') ? `"${word}"` : word)
112
+ ),
113
+ ]),
114
+ ]
115
+
116
+ /** Wording to embed for a ranked search. Keep the literal query for FTS. */
117
+ export let meaningWords = (text: string): string => lifecycle(text, 'sunset')
118
+
119
+ /** The subject immediately before an end-of-life premise in prose. */
120
+ export let lifecycleSubject = (text: string): string | undefined => {
121
+ let premise = new RegExp(END_OF_LIFE, 'i').exec(text)
122
+ if (!premise) return
123
+ let subject =
124
+ /(?:^|[^\p{L}\p{N}_.-])`?([\p{L}\p{N}][\p{L}\p{N}_.-]*)`?(?:['’]s)?(?:\s+(?:is|was|reached))?\s+$/iu
125
+ .exec(text.slice(0, premise.index))?.[1]
126
+ return subject && !common(subject) ? subject : undefined
127
+ }
128
+
129
+ // Mark distinctive words in a snippet, while still searching for *all* words.
130
+ // Keep quoted phrases intact, even those made only of common words, and a
131
+ // common word explicitly starred. If the query has nothing else, marking one
132
+ // word is better than a blank excerpt or an expensive snippet of all common
133
+ // terms.
134
+ export let excerpt = (text: string): string => {
135
+ let words = split(text).filter((word) => word.endsWith('*') || !common(word))
136
+ return words.length
137
+ ? words.map(term).filter(Boolean).join(' ')
138
+ : term(split(text).find((word) => term(word)) ?? '')
139
+ }
140
+
141
+ // How many of a needle's trigrams a substring test asks the index for. All of
142
+ // them would narrow no better than a spread: what one misses, the test that
143
+ // reads each row catches.
144
+ export let GRAMS = 8
145
+
146
+ // A `~=` needle as a query of a substring index (`contains: true`): up to
147
+ // `most` of its trigrams, spread from its start to its end, each quoted and
148
+ // all required. An index keeping only which rows hold each trigram answers
149
+ // the rows holding all of them, every row that holds the needle among them.
150
+ // Null for a needle shorter than a trigram, which the index cannot find.
151
+ ///
152
+ /// grammed('wyrm') -> '"wyr" AND "yrm"'
153
+ /// grammed('a"b') -> '"a""b"'
154
+ /// grammed('ab') -> null
155
+ /// grammed('abcdefghij', 3) -> '"abc" AND "efg" AND "hij"'
156
+ export let grammed = (needle: string, most = GRAMS): string | null => {
157
+ let chars = [...needle]
158
+ let last = chars.length - 3
159
+ if (last < 0) return null
160
+ let n = Math.min(most, last + 1)
161
+ let at = new Set(
162
+ Array.from(
163
+ { length: n },
164
+ (_, i) => Math.round(n > 1 ? i * last / (n - 1) : 0),
165
+ ),
166
+ )
167
+ return [...at]
168
+ .map((i) => `"${chars.slice(i, i + 3).join('').replaceAll('"', '""')}"`)
169
+ .join(' AND ')
170
+ }
171
+
172
+ // An ASCII `~=` needle as a phrase of a word index: its whole words in order,
173
+ // as FTS5's default tokenizer splits them (runs of letters and digits), less a
174
+ // first one it may have cut from the end of a longer word. A last one it may
175
+ // have cut is the start of its word, and stays as the phrase's prefix token. A
176
+ // text holding the needle holds those words one after another, so a word index
177
+ // that keeps where each word stands finds every such text, and few others:
178
+ // dropping the last word as well left `unless Jeff explicitly` the phrase
179
+ // "jeff", which more than 4,000 transcript texts hold, and the read walked the
180
+ // box's 17 million entities (bug fe86c295); "jeff explicitly" * is in 31. Null
181
+ // for a needle with no word inside it but one it may have cut from its start.
182
+ ///
183
+ /// phrased('apps shows the new button') -> '"shows the new button" *'
184
+ /// phrased(' the new') -> '"the new" *'
185
+ /// phrased('on-the hoard.') -> '"the hoard"'
186
+ /// phrased(' wyrm') -> '"wyrm" *'
187
+ /// phrased('wyrmling') -> null
188
+ export let phrased = (needle: string): string | null => {
189
+ let words = (needle.match(/[a-z0-9]+/gi) ?? [])
190
+ .slice(Number(/^[a-z0-9]/i.test(needle)))
191
+ let cut = /[a-z0-9]$/i.test(needle) ? ' *' : ''
192
+ return words.length ? `"${words.join(' ')}"${cut}` : null
193
+ }