@delali/narsil 0.3.1-next.79 → 0.3.1-next.80

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.
Files changed (48) hide show
  1. package/README.md +3 -3
  2. package/dist/{capabilities-1lEYL3WK.d.ts → capabilities-CcTDWh_P.d.ts} +2 -2
  3. package/dist/{chunk-AMGDG4ZJ.mjs → chunk-23HJ5QXQ.mjs} +1 -1
  4. package/dist/{chunk-R6WBLBTC.mjs → chunk-4QDQEJDV.mjs} +9 -45
  5. package/dist/chunk-DQABW5UQ.mjs +140 -0
  6. package/dist/chunk-GG2FBGVZ.mjs +30 -0
  7. package/dist/{chunk-XSZTF4ZQ.mjs → chunk-HJASKX4F.mjs} +1 -1
  8. package/dist/{chunk-DFW3U5UW.mjs → chunk-K4FZ55Q2.mjs} +21 -192
  9. package/dist/{chunk-PJWG547Z.mjs → chunk-MEOOYKWL.mjs} +3 -3
  10. package/dist/{chunk-55WEJKWT.mjs → chunk-NSXQCE4K.mjs} +17 -63
  11. package/dist/{chunk-PXDQFYD5.mjs → chunk-OSF3SGJV.mjs} +23 -139
  12. package/dist/{chunk-RTR44V2A.mjs → chunk-P2PYEZZE.mjs} +586 -4
  13. package/dist/{chunk-Z3BXCZXS.mjs → chunk-QPYV22XH.mjs} +2 -1
  14. package/dist/{chunk-4344I4MR.mjs → chunk-R2XCJIO7.mjs} +335 -12
  15. package/dist/{chunk-IBR6634K.mjs → chunk-R6A773WK.mjs} +2 -69
  16. package/dist/chunk-WQBCBKY3.mjs +8 -0
  17. package/dist/{chunk-P2BEMMOD.mjs → chunk-YGLSR7BC.mjs} +150 -203
  18. package/dist/chunk-YTJCGKM4.mjs +56 -0
  19. package/dist/{client-ZXcbSViH.d.ts → client-CsybN673.d.ts} +2 -2
  20. package/dist/client.d.ts +6 -6
  21. package/dist/{config-DTe5EbWW.d.ts → config-BCNQtszf.d.ts} +1 -1
  22. package/dist/{config-DHL2KsfD.d.ts → config-CFonR_gY.d.ts} +1 -1
  23. package/dist/direct-executor-VNMQ6NIH.mjs +19 -0
  24. package/dist/distribution/coordinator/etcd.mjs +2 -1
  25. package/dist/distribution/coordinator/in-memory.mjs +2 -1
  26. package/dist/distribution.d.ts +5 -5
  27. package/dist/distribution.mjs +15 -13
  28. package/dist/{engine-BjPBzWkA.d.ts → engine-B0oIF1_r.d.ts} +1 -1
  29. package/dist/index.browser.mjs +113 -516
  30. package/dist/index.d.ts +5 -5
  31. package/dist/index.mjs +14 -12
  32. package/dist/invalidation/filesystem.mjs +2 -1
  33. package/dist/{memory-DW3OJ0im.d.ts → memory-B6SBOKlS.d.ts} +1287 -1287
  34. package/dist/partial-words.mjs +5 -4
  35. package/dist/pattern.mjs +4 -1
  36. package/dist/persistence/durability/checkpoint-worker.d.ts +7 -7
  37. package/dist/persistence/durability/checkpoint-worker.mjs +14 -12
  38. package/dist/react.d.ts +6 -6
  39. package/dist/server.d.ts +8 -8
  40. package/dist/server.mjs +10 -7
  41. package/dist/{tasks-BTbwBqar.d.ts → tasks-CYAQe6qd.d.ts} +1 -1
  42. package/dist/{thread-XBDVXKUE.mjs → thread-P6QJ2Q5O.mjs} +11 -8
  43. package/dist/vector/search-worker.mjs +3 -2
  44. package/dist/workers/entry.mjs +3 -3
  45. package/package.json +9 -7
  46. package/dist/chunk-IOZPBNSG.mjs +0 -55
  47. package/dist/chunk-WFVOBZS4.mjs +0 -485
  48. package/dist/direct-executor-WB2HKU4N.mjs +0 -17
@@ -1,1528 +1,1528 @@
1
- import { A as AnyDocument, d as ScoringMode, S as SchemaDefinition } from './schema-DgyDijhf.js';
1
+ import { A as AnyDocument, S as SchemaDefinition, d as ScoringMode } from './schema-DgyDijhf.js';
2
2
 
3
3
  /**
4
- * Compares one field against a value. Setting several keys narrows the match,
5
- * because a document has to satisfy all of them.
6
- *
7
- * @public
8
- */
9
- type ComparisonFilter = {
10
- /** This matches a field equal to the value, or a list field where one element equals it. */
11
- eq?: number | string | boolean;
12
- /**
13
- * This matches a document that holds the field with a value other than this
14
- * one, or a list field where every element differs from it, which an empty
15
- * list does.
16
- */
17
- ne?: number | string | boolean;
18
- /** This matches a field greater than the number. */
19
- gt?: number;
20
- /** This matches a field less than the number. */
21
- lt?: number;
22
- /** This matches a field greater than or equal to the number. */
23
- gte?: number;
24
- /** This matches a field less than or equal to the number. */
25
- lte?: number;
26
- /** This matches a field inside the inclusive range, given as `[low, high]`. */
27
- between?: [number, number];
28
- };
29
- /**
30
- * The engine tests a text field against this filter for equality, for a text
31
- * range, or with the set, prefix, and pattern tests.
32
- *
33
- * On a `string[]`, `verbatim[]`, or `enum[]` field, the engine tests each
34
- * element of the list on its own. A document passes `eq`, `in`, `startsWith`,
35
- * `endsWith`, `contains`, `wildcard`, or `regex` when one element passes the
36
- * test. However, a document passes `ne` or `nin` only when every element
37
- * differs from the values.
38
- *
39
- * The engine applies the range tests `gt`, `gte`, `lt`, `lte`, and `between`
40
- * to a single `string` or `verbatim` field whose type includes `sortable`. It
41
- * throws `SEARCH_INVALID_FILTER` for a text range on any other field. It
42
- * orders the values as a sort on the field does, so it compares their case
43
- * folds first and compares their raw code points only where the folds are
44
- * equal.
45
- *
46
- * A pattern field is a `verbatim` or `verbatim[]` field, or a `string` or
47
- * `string[]` field whose type includes `pattern`. On a pattern field, the
48
- * engine answers `eq`, `ne`, `in`, `nin`, `startsWith`, `endsWith`,
49
- * `contains`, `wildcard`, and `regex` from the field's pattern index, and
50
- * `caseFold` applies to each of those tests. The engine compares the code
51
- * points of each value as they are stored, with no Unicode normalisation.
52
- *
53
- * On an `enum` or `enum[]` field, the engine answers `eq`, `ne`, `in`, `nin`,
54
- * `startsWith`, and `endsWith` from the field's index of values. A `string` or
55
- * `string[]` field whose type leaves out `pattern` keeps no index of whole
56
- * values, so the engine throws `SEARCH_INVALID_FILTER` for those six tests,
57
- * and for `matchesAny` and `containsAll`, on such a field.
58
- *
59
- * The engine also throws `SEARCH_INVALID_FILTER` in these cases:
60
- *
61
- * - The filter sets `contains`, `wildcard`, `regex`, or `caseFold` on a field
62
- * that is not a pattern field.
63
- * - The text or the pattern of a test on a pattern field holds more than 1,024
64
- * code points.
65
- * - A literal test under `caseFold` has a text whose case fold holds more than
66
- * 2,048 code points.
67
- * - A `wildcard` or `regex` pattern breaks its syntax or one of its limits.
68
- *
69
- * @public
70
- */
71
- type StringFilter = Pick<ComparisonFilter, 'eq' | 'ne'> & {
72
- /** This matches a value that comes after the text in sort order. */
73
- gt?: string;
74
- /** This matches a value that comes before the text in sort order. */
75
- lt?: string;
76
- /** This matches a value equal to the text or after it in sort order. */
77
- gte?: string;
78
- /** This matches a value equal to the text or before it in sort order. */
79
- lte?: string;
80
- /** This matches a value inside the inclusive range in sort order, given as `[low, high]`. */
81
- between?: [string, string];
82
- /** This matches a field equal to any value in the list, which holds at most 65,536 values. */
83
- in?: string[];
84
- /** This matches a field that differs from every value in the list, which holds at most 65,536 values. */
85
- nin?: string[];
86
- /** This matches a field starting with the text. */
87
- startsWith?: string;
88
- /** This matches a field ending with the text. */
89
- endsWith?: string;
90
- /** This matches a pattern field whose value holds the text anywhere in it. */
91
- contains?: string;
92
- /**
93
- * This matches a pattern field when the whole value matches the wildcard
94
- * pattern. For example, `INV-*-2024` matches `INV-0042-2024`.
95
- *
96
- * In the pattern, `*` matches any sequence of code points, including an
97
- * empty one, and `?` matches exactly one code point. Write `\` before a code
98
- * point to match that code point itself, so `\*` matches an asterisk.
99
- *
100
- * The engine throws `SEARCH_INVALID_FILTER` for a pattern that ends in a
101
- * `\` with no code point after it. It throws the same error for a pattern
102
- * with more than 2,048 positions. Each `*`, each `?`, and each other code
103
- * point counts as one position, except that under `caseFold` a code point
104
- * counts once for each code point of its case fold.
105
- */
106
- wildcard?: string;
107
- /**
108
- * This matches a pattern field when some part of the value matches the
109
- * regular expression. `^` and `$` match only at the start and at the end of
110
- * the whole value.
111
- *
112
- * The engine accepts literal code points, `.`, `\d`, `\w`, and `\s`, sets
113
- * such as `[a-z]` and `[^0-9]`, groups, and `|`. It also accepts the repeats
114
- * `*`, `+`, `?`, `{n}`, `{n,}`, and `{n,m}`, the anchors `^` and `$`, the
115
- * word edge `\b`, and number ranges such as `<1-65535>`. A number range
116
- * matches the digits of any whole number from its low end to its high end.
117
- * Write `\` before an ASCII punctuation mark to match the mark itself. The
118
- * `.` matches any code point, including a line break.
119
- *
120
- * The matcher never backtracks, so it checks a value in at most as many
121
- * steps as the value's code points multiplied by the pattern's positions.
122
- *
123
- * The engine throws `SEARCH_INVALID_FILTER` for any construct outside that
124
- * syntax, such as a back-reference, a lookaround, a lazy repeat, or an inline
125
- * flag. It throws the same error when the groups of a pattern nest more than
126
- * 32 deep, when a count is above 2,048, and when a pattern holds more than
127
- * 2,048 positions. When the operator of an HTTP server sets its `allowRegex`
128
- * option to false, the server refuses every `regex` test.
129
- */
130
- regex?: string;
131
- /**
132
- * When this is true, the engine compares the case fold of each value of a
133
- * pattern field with the case fold of the text, so a test for `error`
134
- * matches `ERROR`. It applies to `eq`, `ne`, `in`, `nin`, `startsWith`,
135
- * `endsWith`, `contains`, `wildcard`, and `regex`.
136
- *
137
- * Under `caseFold`, a set that does not open with `^` can also match a
138
- * sequence of code points. When a member that the set holds on its own folds
139
- * to several code points, the set matches that whole fold, so `[ß]` matches
140
- * `ss`.
141
- */
142
- caseFold?: boolean;
143
- /**
144
- * This lets the `eq` test of a pattern field match a value within this many
145
- * edits of the text, so a test for `INV-2O24` with a tolerance of 1 matches
146
- * `INV-2024`. An edit inserts, deletes, or replaces one code point, so a
147
- * swap of two neighbouring code points counts as two edits. With `caseFold`,
148
- * the engine counts the edits between the case folds of the value and the
149
- * text. The tolerance applies to `eq` alone, so the other tests of the field
150
- * still compare exactly.
151
- *
152
- * The engine takes its candidates from the pattern index, so the case fold
153
- * of the text has to hold enough distinct runs of three code points. For a
154
- * tolerance of `k`, the engine needs `k × (2 + f) + 1` runs, where `f` is
155
- * the number of code points in the longest case fold among the text's code
156
- * points, which is 1 for most text. A tolerance of 1 on `INV-2O24`
157
- * therefore needs 4 of its 6 runs, while a tolerance of 2 needs 7. Under
158
- * `'auto'`, the engine uses 2 where the text holds enough runs for 2,
159
- * otherwise 1 where it holds enough for 1, and otherwise 0.
160
- *
161
- * The engine throws `SEARCH_INVALID_FILTER` for a tolerance of 1 or 2 on a
162
- * text with too few runs, stating how many runs that tolerance needs. It
163
- * throws the same error for any other tolerance, for a tolerance on a field
164
- * that is not a pattern field, and for a tolerance in a filter without an
165
- * `eq` test. Towards the pattern work cap, it counts one unit for each cell
166
- * that it fills in the table of edit distances between the text and a
167
- * value.
168
- */
169
- tolerance?: 0 | 1 | 2 | 'auto';
170
- };
171
- /**
172
- * Tests the contents of a list field, which is a `number[]`, `boolean[]`,
173
- * `enum[]`, `verbatim[]`, or `string[]` field.
174
- *
175
- * The engine throws `SEARCH_INVALID_FILTER` for these tests on any other
176
- * field, for a value whose type differs from the type of the list's elements,
177
- * and for `containsAll` or `matchesAny` on a `string[]` field whose type leaves
178
- * out `pattern`.
179
- *
180
- * @public
181
- */
182
- type ArrayFilter = {
183
- /** This matches a list holding every one of the values, at most 65,536 of them, so an empty set of values matches every list. */
184
- containsAll?: (string | number | boolean)[];
185
- /** This matches a list holding at least one of the values, at most 65,536 of them. */
186
- matchesAny?: (string | number | boolean)[];
187
- /** This compares the number of elements in the list. */
188
- size?: ComparisonFilter;
189
- };
190
- /**
191
- * Tests whether a field carries a value at all, without looking at what it
192
- * holds.
193
- *
194
- * @public
195
- */
196
- type PresenceFilter = {
197
- /** This matches a document where the field holds a value other than null. */
198
- exists?: boolean;
199
- /** This matches a document where the field is absent or null. */
200
- notExists?: boolean;
201
- /** This matches a document where the field is absent, null, an empty string, or an empty list. */
202
- isEmpty?: boolean;
203
- /** This matches a document where the field holds a value other than an empty string or an empty list. */
204
- isNotEmpty?: boolean;
205
- };
206
- /**
207
- * Matches a `geopoint` field against a circle drawn on the earth.
208
- *
209
- * @public
210
- */
211
- type GeoRadiusFilter = {
212
- /** The engine tests the field against this circle. */
213
- radius: {
214
- /** The centre has this latitude, in degrees from -90 to 90. For any other value, the engine throws `SEARCH_INVALID_FILTER`. */
215
- lat: number;
216
- /** The centre has this longitude, in degrees from -180 to 180. For any other value, the engine throws `SEARCH_INVALID_FILTER`. */
217
- lon: number;
218
- /** The circle has this radius, measured in `unit`. */
219
- distance: number;
220
- /**
221
- * The engine measures `distance` in kilometres under `'km'`, in miles
222
- * under `'mi'`, and in metres under `'m'`. For any other unit, it throws
223
- * `SEARCH_INVALID_FILTER`.
224
- */
225
- unit: 'km' | 'mi' | 'm';
226
- /** The engine matches the points inside the circle while this is true, which is the default, and the points outside it while this is false. */
227
- inside?: boolean;
228
- /**
229
- * The engine measures each distance with the Haversine formula on a sphere
230
- * by default, and with Vincenty's formula on the WGS-84 ellipsoid while
231
- * this is true. Vincenty's formula iterates, so the engine takes longer
232
- * to compute each distance. The two formulas differ by less than 0.3% under about
233
- * 100 km, while across a continent they can differ by up to 0.5%.
234
- */
235
- highPrecision?: boolean;
236
- };
237
- };
238
- /**
239
- * Matches a `geopoint` field against a polygon drawn on the earth.
240
- *
241
- * @public
242
- */
243
- type GeoPolygonFilter = {
244
- /** The engine tests the field against this polygon. */
245
- polygon: {
246
- /**
247
- * The engine closes the ring through these corners in the order that you
248
- * list them, so you can leave the first point off the end. It throws
249
- * `SEARCH_INVALID_FILTER` for a ring of fewer than three corners, which
250
- * encloses no area, and for a corner whose latitude is outside -90 to 90
251
- * or whose longitude is outside -180 to 180. It also throws that error for
252
- * a ring of more than 65,536 corners. List the corners counter-clockwise
253
- * around the area, as in an exterior ring of GeoJSON. Where the corners
254
- * span 180 degrees of longitude or more, the engine matches the area on
255
- * the left of that path, so a ring listed that way can cross the
256
- * antimeridian or span more than half the globe.
257
- */
258
- points: Array<{
259
- lat: number;
260
- lon: number;
261
- }>;
262
- /** The engine matches the points inside the polygon while this is true, which is the default, and the points outside it while this is false. */
263
- inside?: boolean;
264
- };
265
- };
266
- /**
267
- * Either shape a `geopoint` field is matched against.
268
- *
269
- * @public
270
- */
271
- type GeoFilter = GeoRadiusFilter | GeoPolygonFilter;
272
- /**
273
- * The filter one field accepts. Which of these forms applies follows from the
274
- * field's declared type.
275
- *
276
- * @public
277
- */
278
- type FieldFilter = ComparisonFilter | StringFilter | ArrayFilter | PresenceFilter | GeoFilter;
279
- /**
280
- * The filter that a query runs, built from per-field tests and the boolean
281
- * operators that combine them.
4
+ * Every code a {@link NarsilError} carries, grouped by the part of the engine
5
+ * that raises it.
282
6
  *
283
- * The engine answers every test from an index that it keeps for the field. It
284
- * applies the filter before scoring, so a narrow filter makes a search
285
- * cheaper. A filter nests at most 30 levels deep and holds at most 1,024
286
- * tests, counted across every field and nested expression. Past either limit,
287
- * the engine throws `SEARCH_INVALID_FILTER`, while it throws
288
- * `SEARCH_INVALID_FIELD` for a test on a field that the schema leaves out.
7
+ * Match on the code rather than on the message, because a code is stable and a
8
+ * message is not. The HTTP server maps each code to a status, so a code also
9
+ * tells you whether the caller or the engine is at fault.
289
10
  *
290
11
  * @public
291
12
  */
292
- type FilterExpression = {
293
- /** These per-field tests are keyed by field name, and a document has to satisfy every entry. */
294
- fields?: Record<string, FieldFilter>;
295
- /** Every nested expression has to match. */
296
- and?: FilterExpression[];
297
- /** At least one nested expression has to match. */
298
- or?: FilterExpression[];
299
- /** The nested expression has to fail. */
300
- not?: FilterExpression;
13
+ declare const ErrorCodes: {
14
+ readonly SCHEMA_INVALID_TYPE: "SCHEMA_INVALID_TYPE";
15
+ readonly SCHEMA_DEPTH_EXCEEDED: "SCHEMA_DEPTH_EXCEEDED";
16
+ readonly SCHEMA_INVALID_VECTOR_DIMENSION: "SCHEMA_INVALID_VECTOR_DIMENSION";
17
+ readonly SCHEMA_INVALID_GEOPOINT: "SCHEMA_INVALID_GEOPOINT";
18
+ readonly DOC_NOT_FOUND: "DOC_NOT_FOUND";
19
+ readonly DOC_ALREADY_EXISTS: "DOC_ALREADY_EXISTS";
20
+ readonly DOC_VALIDATION_FAILED: "DOC_VALIDATION_FAILED";
21
+ readonly INDEX_NOT_FOUND: "INDEX_NOT_FOUND";
22
+ readonly INDEX_ALREADY_EXISTS: "INDEX_ALREADY_EXISTS";
23
+ readonly INDEX_ORPHANED: "INDEX_ORPHANED";
24
+ readonly INDEX_REOPEN_CAPACITY_EXHAUSTED: "INDEX_REOPEN_CAPACITY_EXHAUSTED";
25
+ readonly INSTANCE_SHUT_DOWN: "INSTANCE_SHUT_DOWN";
26
+ readonly PARTITION_CORRUPTED: "PARTITION_CORRUPTED";
27
+ readonly PARTITION_REBALANCING_BACKPRESSURE: "PARTITION_REBALANCING_BACKPRESSURE";
28
+ readonly WORKER_CRASHED: "WORKER_CRASHED";
29
+ readonly WORKER_BUSY: "WORKER_BUSY";
30
+ readonly WORKER_TIMEOUT: "WORKER_TIMEOUT";
31
+ readonly WORKER_ACTION_FAILED: "WORKER_ACTION_FAILED";
32
+ readonly PERSISTENCE_SAVE_FAILED: "PERSISTENCE_SAVE_FAILED";
33
+ readonly PERSISTENCE_LOAD_FAILED: "PERSISTENCE_LOAD_FAILED";
34
+ readonly PERSISTENCE_DELETE_FAILED: "PERSISTENCE_DELETE_FAILED";
35
+ readonly PERSISTENCE_CRC_MISMATCH: "PERSISTENCE_CRC_MISMATCH";
36
+ readonly PERSISTENCE_WAL_CORRUPT: "PERSISTENCE_WAL_CORRUPT";
37
+ readonly PERSISTENCE_FSYNC_FAILED: "PERSISTENCE_FSYNC_FAILED";
38
+ readonly SEARCH_INVALID_FIELD: "SEARCH_INVALID_FIELD";
39
+ readonly VECTOR_DIMENSION_MISMATCH: "VECTOR_DIMENSION_MISMATCH";
40
+ readonly SEARCH_INVALID_FILTER: "SEARCH_INVALID_FILTER";
41
+ readonly SEARCH_INVALID_MODE: "SEARCH_INVALID_MODE";
42
+ readonly SEARCH_INVALID_CURSOR: "SEARCH_INVALID_CURSOR";
43
+ readonly SEARCH_RESULT_WINDOW_EXCEEDED: "SEARCH_RESULT_WINDOW_EXCEEDED";
44
+ readonly SEARCH_WORK_CAP_EXCEEDED: "SEARCH_WORK_CAP_EXCEEDED";
45
+ readonly LANGUAGE_NOT_SUPPORTED: "LANGUAGE_NOT_SUPPORTED";
46
+ readonly ENVELOPE_VERSION_MISMATCH: "ENVELOPE_VERSION_MISMATCH";
47
+ readonly ENVELOPE_INVALID_MAGIC: "ENVELOPE_INVALID_MAGIC";
48
+ readonly PARTITION_CAPACITY_EXCEEDED: "PARTITION_CAPACITY_EXCEEDED";
49
+ readonly EMBEDDING_FAILED: "EMBEDDING_FAILED";
50
+ readonly EMBEDDING_DIMENSION_MISMATCH: "EMBEDDING_DIMENSION_MISMATCH";
51
+ readonly EMBEDDING_NO_SOURCE: "EMBEDDING_NO_SOURCE";
52
+ readonly EMBEDDING_CONFIG_INVALID: "EMBEDDING_CONFIG_INVALID";
53
+ readonly DOC_MISSING_REQUIRED_FIELD: "DOC_MISSING_REQUIRED_FIELD";
54
+ readonly CONFIG_INVALID: "CONFIG_INVALID";
55
+ readonly QUERY_ROUTING_FAILED: "QUERY_ROUTING_FAILED";
56
+ readonly QUERY_PARTIAL_FAILURE: "QUERY_PARTIAL_FAILURE";
57
+ readonly QUERY_NODE_TIMEOUT: "QUERY_NODE_TIMEOUT";
58
+ readonly QUERY_NO_ACTIVE_REPLICA: "QUERY_NO_ACTIVE_REPLICA";
59
+ readonly CLUSTER_OPERATION_UNSUPPORTED: "CLUSTER_OPERATION_UNSUPPORTED";
60
+ readonly ALLOCATION_NO_DATA_NODES: "ALLOCATION_NO_DATA_NODES";
61
+ readonly ALLOCATION_INVALID_CONFIG: "ALLOCATION_INVALID_CONFIG";
62
+ readonly ALLOCATION_FAILED: "ALLOCATION_FAILED";
63
+ readonly CONTROLLER_METADATA_INVALID: "CONTROLLER_METADATA_INVALID";
64
+ readonly NODE_BOOTSTRAP_FAILED: "NODE_BOOTSTRAP_FAILED";
65
+ readonly NODE_ALREADY_JOINED: "NODE_ALREADY_JOINED";
66
+ readonly NODE_NOT_JOINED: "NODE_NOT_JOINED";
67
+ readonly NODE_NOT_READY: "NODE_NOT_READY";
68
+ readonly NODE_NOT_CONTROLLER: "NODE_NOT_CONTROLLER";
69
+ readonly COORDINATOR_DEPENDENCY_MISSING: "COORDINATOR_DEPENDENCY_MISSING";
70
+ readonly TRANSPORT_DEPENDENCY_MISSING: "TRANSPORT_DEPENDENCY_MISSING";
71
+ readonly REPLICATION_ENTRY_INVALID: "REPLICATION_ENTRY_INVALID";
72
+ readonly REPLICATION_INSYNC_REMOVAL_FAILED: "REPLICATION_INSYNC_REMOVAL_FAILED";
73
+ readonly REPLICATION_ROLLBACK_FAILED: "REPLICATION_ROLLBACK_FAILED";
74
+ readonly REPLICATION_LOG_FULL: "REPLICATION_LOG_FULL";
75
+ readonly REPLICATION_ENTRY_CORRUPT: "REPLICATION_ENTRY_CORRUPT";
76
+ readonly REPLICATION_SNAPSHOT_CORRUPT: "REPLICATION_SNAPSHOT_CORRUPT";
77
+ readonly REPLICATION_TERM_MISMATCH: "REPLICATION_TERM_MISMATCH";
78
+ readonly REPLICATION_SYNC_FAILED: "REPLICATION_SYNC_FAILED";
79
+ readonly PARTITION_NOT_PRIMARY: "PARTITION_NOT_PRIMARY";
80
+ readonly PARTITION_UNASSIGNED: "PARTITION_UNASSIGNED";
81
+ readonly INSUFFICIENT_REPLICAS: "INSUFFICIENT_REPLICAS";
82
+ readonly SNAPSHOT_SYNC_UNAUTHORIZED: "SNAPSHOT_SYNC_UNAUTHORIZED";
83
+ readonly SNAPSHOT_SYNC_REQUEST_INVALID: "SNAPSHOT_SYNC_REQUEST_INVALID";
84
+ readonly SNAPSHOT_SYNC_INDEX_NOT_FOUND: "SNAPSHOT_SYNC_INDEX_NOT_FOUND";
85
+ readonly SNAPSHOT_SYNC_CAPACITY_EXHAUSTED: "SNAPSHOT_SYNC_CAPACITY_EXHAUSTED";
86
+ readonly SNAPSHOT_SYNC_SNAPSHOT_FAILED: "SNAPSHOT_SYNC_SNAPSHOT_FAILED";
87
+ readonly SNAPSHOT_SYNC_DECODE_FAILED: "SNAPSHOT_SYNC_DECODE_FAILED";
88
+ readonly SNAPSHOT_SYNC_FRAME_INVALID: "SNAPSHOT_SYNC_FRAME_INVALID";
89
+ readonly SNAPSHOT_SYNC_HEADER_INVALID: "SNAPSHOT_SYNC_HEADER_INVALID";
90
+ readonly SNAPSHOT_SYNC_HEADER_MISMATCH: "SNAPSHOT_SYNC_HEADER_MISMATCH";
91
+ readonly SNAPSHOT_SYNC_CHUNK_OUT_OF_ORDER: "SNAPSHOT_SYNC_CHUNK_OUT_OF_ORDER";
92
+ readonly SNAPSHOT_SYNC_CHUNK_OVERFLOW: "SNAPSHOT_SYNC_CHUNK_OVERFLOW";
93
+ readonly SNAPSHOT_SYNC_CHUNK_SIZE_EXCEEDED: "SNAPSHOT_SYNC_CHUNK_SIZE_EXCEEDED";
94
+ readonly SNAPSHOT_SYNC_CHUNK_MISSING: "SNAPSHOT_SYNC_CHUNK_MISSING";
95
+ readonly SNAPSHOT_SYNC_END_MISSING: "SNAPSHOT_SYNC_END_MISSING";
96
+ readonly SNAPSHOT_SYNC_CHECKSUM_MISMATCH: "SNAPSHOT_SYNC_CHECKSUM_MISMATCH";
97
+ readonly SNAPSHOT_SYNC_PRIMARY_ERROR: "SNAPSHOT_SYNC_PRIMARY_ERROR";
98
+ readonly SNAPSHOT_SYNC_NO_TARGETS: "SNAPSHOT_SYNC_NO_TARGETS";
99
+ readonly SNAPSHOT_SYNC_TRANSPORT_FAILED: "SNAPSHOT_SYNC_TRANSPORT_FAILED";
100
+ readonly SNAPSHOT_SYNC_SCHEMA_UNAVAILABLE: "SNAPSHOT_SYNC_SCHEMA_UNAVAILABLE";
101
+ readonly SNAPSHOT_SYNC_RESTORE_FAILED: "SNAPSHOT_SYNC_RESTORE_FAILED";
102
+ readonly SNAPSHOT_SYNC_RESTORE_CLEANUP_FAILED: "SNAPSHOT_SYNC_RESTORE_CLEANUP_FAILED";
103
+ readonly SNAPSHOT_SYNC_TIMEOUT: "SNAPSHOT_SYNC_TIMEOUT";
104
+ readonly SNAPSHOT_SYNC_ALLOCATION_UNAVAILABLE: "SNAPSHOT_SYNC_ALLOCATION_UNAVAILABLE";
105
+ readonly SNAPSHOT_SYNC_NOT_ASSIGNED: "SNAPSHOT_SYNC_NOT_ASSIGNED";
106
+ readonly SNAPSHOT_SYNC_ABORTED: "SNAPSHOT_SYNC_ABORTED";
301
107
  };
302
-
303
108
  /**
304
- * Everything {@link Narsil.suggest} accepts.
109
+ * Any one of the codes in {@link ErrorCodes}, which is the type to narrow on
110
+ * when you branch on a failure the engine raised.
305
111
  *
306
112
  * @public
307
113
  */
308
- interface SuggestParams {
309
- /** The returned terms complete this text. */
310
- prefix: string;
311
- /** The lookup returns this many completions, most widely used first, and 10 by default. */
312
- limit?: number;
313
- }
114
+ type ErrorCode = (typeof ErrorCodes)[keyof typeof ErrorCodes];
314
115
  /**
315
- * Everything {@link Narsil.listDocuments} accepts.
316
- *
317
- * {@link Narsil.listDocuments} reads the stored documents without ranking them,
318
- * which is how you page through a whole index. Leave `cursor` out to start at
319
- * the first document, then pass back the cursor each result carries until it
320
- * comes back null.
116
+ * Every code the HTTP layer raises for a failure that arises before or around
117
+ * the engine call, such as parsing the body, enforcing a limit, or routing.
321
118
  *
322
- * A cursor belongs to the sort it was made under, so pass the same `sort` back
323
- * with it. Changing `sort` invalidates the cursor, and the engine then throws
324
- * `SEARCH_INVALID_CURSOR` rather than returning a page from the wrong order.
119
+ * The engine raises none of these, so a failure carrying one of them says the
120
+ * request never reached the engine.
325
121
  *
326
122
  * @public
327
123
  */
328
- interface ListParams {
329
- /**
330
- * This cursor comes from a previous result, and continues where it stopped.
331
- * The engine ties a cursor to the sort that produced it, and it throws
332
- * `SEARCH_INVALID_CURSOR` for a cursor sent back under a different sort.
333
- */
334
- cursor?: string;
335
- /** The page carries this many documents, and 10 by default. The engine raises a value below one to one. */
336
- limit?: number;
337
- /** This narrows the listing to the documents the filter accepts. */
338
- filters?: FilterExpression;
339
- /**
340
- * This orders the listing by field value rather than by document id, and the
341
- * engine applies the fields in the order they are listed. Pass an object
342
- * keyed by field, or a list of fields in the order they apply. It breaks a
343
- * tie on document id, and it sorts by at most eight fields. The engine uses
344
- * document-id order when you leave this out.
345
- *
346
- * The engine reads every document the listing covers to build a sorted page,
347
- * so a sorted listing costs more than the default order on a large index.
348
- */
349
- sort?: SortSpec;
350
- /** This chooses how much of each stored document comes back, and the whole document by default. */
351
- document?: DocumentProjection;
352
- }
353
-
124
+ declare const ServerErrorCodes: {
125
+ readonly INVALID_REQUEST: "INVALID_REQUEST";
126
+ readonly INVALID_JSON: "INVALID_JSON";
127
+ readonly EMPTY_BODY: "EMPTY_BODY";
128
+ readonly PAYLOAD_TOO_LARGE: "PAYLOAD_TOO_LARGE";
129
+ readonly NOT_FOUND: "NOT_FOUND";
130
+ readonly TASK_NOT_FOUND: "TASK_NOT_FOUND";
131
+ readonly TASK_NOT_CANCELLABLE: "TASK_NOT_CANCELLABLE";
132
+ readonly TASK_OWNED_BY_ANOTHER_INSTANCE: "TASK_OWNED_BY_ANOTHER_INSTANCE";
133
+ readonly TASK_INTERRUPTED: "TASK_INTERRUPTED";
134
+ readonly TOO_MANY_REQUESTS: "TOO_MANY_REQUESTS";
135
+ readonly HOOK_ERROR: "HOOK_ERROR";
136
+ readonly INTERNAL_ERROR: "INTERNAL_ERROR";
137
+ };
354
138
  /**
355
- * Which engine answers a query: keyword matching, vector similarity, or both
356
- * merged into one ranking.
139
+ * Any one of the codes in {@link ServerErrorCodes}.
357
140
  *
358
141
  * @public
359
142
  */
360
- type SearchMode = 'fulltext' | 'vector' | 'hybrid';
143
+ type ServerErrorCode = (typeof ServerErrorCodes)[keyof typeof ServerErrorCodes];
361
144
  /**
362
- * How many of a query's terms a document has to carry. `all` demands every
363
- * term, `any` accepts one, and a number demands that many.
145
+ * Every code that the caller's own side raises, where a request never reaches
146
+ * a server, or where the caller cannot read the answer.
147
+ *
148
+ * The HTTP client raises the first five. The React bindings raise
149
+ * `CLIENT_UNEXPECTED_ERROR` alone, which reports a fault inside a hook. No
150
+ * server sends any of them, so a failure under one means the exchange broke
151
+ * before the operation ran. `STATUS_BY_CODE` in `src/server/errors.ts`
152
+ * therefore maps none of them, because no request can arrive under one and no
153
+ * HTTP status belongs to one.
364
154
  *
365
155
  * @public
366
156
  */
367
- type TermMatchPolicy = 'all' | 'any' | number;
157
+ declare const ClientErrorCodes: {
158
+ readonly CLIENT_CONNECTION_FAILED: "CLIENT_CONNECTION_FAILED";
159
+ readonly CLIENT_REQUEST_TIMEOUT: "CLIENT_REQUEST_TIMEOUT";
160
+ readonly CLIENT_REQUEST_ABORTED: "CLIENT_REQUEST_ABORTED";
161
+ readonly CLIENT_INVALID_RESPONSE: "CLIENT_INVALID_RESPONSE";
162
+ readonly CLIENT_TASK_TIMEOUT: "CLIENT_TASK_TIMEOUT";
163
+ readonly CLIENT_UNEXPECTED_ERROR: "CLIENT_UNEXPECTED_ERROR";
164
+ };
368
165
  /**
369
- * One field of a sort, and the direction that field orders by.
166
+ * Any one of the codes in {@link ClientErrorCodes}.
370
167
  *
371
168
  * @public
372
169
  */
373
- interface SortField {
374
- /** The field the engine reads, which may name a nested field with dots. */
375
- field: string;
376
- /** Ascending or descending order for this field. */
377
- direction: 'asc' | 'desc';
378
- /**
379
- * Where a document's field holds a list, the engine sorts that document by
380
- * one value from the list: the smallest under `'min'`, the largest under
381
- * `'max'`, and the mean or the median of the list's numbers under `'avg'`
382
- * or `'median'`. Where you leave this out, the engine uses `'min'` for an
383
- * ascending sort and `'max'` for a descending one. It sorts by a field that
384
- * holds a single value as that value stands, under every mode. It throws
385
- * `SEARCH_INVALID_FIELD` for `'avg'` or `'median'` on a field that the
386
- * schema declares as anything other than `number` or `number[]`.
387
- */
388
- mode?: 'min' | 'max' | 'avg' | 'median';
389
- }
170
+ type ClientErrorCode = (typeof ClientErrorCodes)[keyof typeof ClientErrorCodes];
390
171
  /**
391
- * A sort, either as an object keyed by field or as a list of fields in the
392
- * order they apply.
172
+ * Every code a {@link NarsilError} can carry: one the engine raised, one the
173
+ * HTTP layer raised, one the client raised, or any other string.
393
174
  *
394
- * Both forms order by the first field, break a tie on the second, and carry on
395
- * that way. Prefer the list where the order of the fields matters, because
396
- * JavaScript moves an all-digit key such as `2024` to the front of an object
397
- * and the list keeps the order you wrote.
175
+ * The last arm exists for a server's `onRequest` hook, which rejects a request
176
+ * under a code of its own, such as `UNAUTHORIZED`, and the client then passes
177
+ * that code through unchanged. An editor still completes every code Narsil
178
+ * defines.
398
179
  *
399
180
  * @public
400
181
  */
401
- type SortSpec = Record<string, 'asc' | 'desc'> | readonly SortField[];
182
+ type NarsilErrorCode = ErrorCode | ServerErrorCode | ClientErrorCode | (string & {});
402
183
  /**
403
- * Everything {@link Narsil.query} accepts.
184
+ * The error every part of the engine throws.
404
185
  *
405
- * Set `term` for keyword search, `vector` for similarity search, and `mode`
406
- * when you want both. The engine matches nothing for a query carrying neither
407
- * of them, so page through an index with {@link Narsil.listDocuments}
408
- * instead.
186
+ * Catch it, read {@link NarsilError.code} to decide what to do, and read
187
+ * {@link NarsilError.details} for the values that caused it. The engine lets
188
+ * this error propagate unchanged, so the code you catch is the code the
189
+ * failing operation raised.
409
190
  *
410
191
  * @public
411
192
  */
412
- interface QueryParams {
413
- /** The engine analyses this text with the index's language module and searches for the terms that result. */
414
- term?: string;
415
- /** The engine searches the term in these fields, and in every text field in the schema by default. */
416
- fields?: string[];
417
- /**
418
- * The engine scores only the documents that pass this filter. It throws
419
- * `SEARCH_INVALID_FILTER` for an operand of the wrong shape, and for an
420
- * operator on a field of another type, such as `startsWith` on a number
421
- * field.
422
- */
423
- filters?: FilterExpression;
424
- /**
425
- * The engine multiplies the score from each named field by its weight. It
426
- * throws `SEARCH_INVALID_FIELD` for any field other than a text field that
427
- * the schema declares, and `CONFIG_INVALID` for a weight that is not a
428
- * finite number.
429
- */
430
- boost?: Record<string, number>;
431
- /** The engine gathers term statistics this way, and follows the index's `defaultScoring` where the query sets none. */
432
- scoring?: ScoringMode;
433
- /**
434
- * The engine drops any hit scoring below this value. It ranks with BM25,
435
- * which has no fixed upper bound, so a floor that suits one index and one
436
- * query can reject every hit in another.
437
- */
438
- minScore?: number;
439
- /**
440
- * The engine keeps a document only where the document matches this many
441
- * query terms, under the same `tolerance` and `prefixLength` that the search
442
- * uses. One term is enough by default.
443
- */
444
- termMatch?: TermMatchPolicy;
445
- /**
446
- * The engine matches an indexed term within this edit distance of a query
447
- * term, so it finds a document for a query with a typo. It counts each
448
- * Unicode code point as one character. Set an integer from 0 to 10.
449
- */
450
- tolerance?: number;
451
- /**
452
- * The engine applies `tolerance` only to the indexed terms that share this
453
- * many leading characters with the query term, or to the terms that start
454
- * with the whole query term when the query term is shorter. Set an integer
455
- * from 0 to 1,024; the default is 2.
456
- */
457
- prefixLength?: number;
458
- /**
459
- * With this set, the engine treats the last query term as an unfinished
460
- * word, so `secur` matches `security`. The engine matches that last term by
461
- * its stem or by completing it, while `tolerance` applies only to the earlier
462
- * terms, which have to match whole. The engine scores completions against a
463
- * shared document frequency. It also ranks them below whole-word matches.
464
- * The engine ignores this setting where `exact` is true, and the setting is
465
- * false by default.
466
- */
467
- prefix?: boolean;
193
+ declare class NarsilError extends Error {
194
+ /** This says which failure it is. */
195
+ readonly code: NarsilErrorCode;
196
+ /** This carries the values behind the failure, such as the field, index, or limit involved. It is empty when the code says everything. */
197
+ readonly details: Record<string, unknown>;
468
198
  /**
469
- * With this set, the engine also matches each query word of three or more
470
- * characters inside the longer words of every field whose type includes
471
- * `partial`, so a search for `proof` matches a document with `waterproof`
472
- * in such a field. The engine counts each Unicode code point as one
473
- * character. It looks for the query word, before stemming, inside each word
474
- * exactly as that word appears in a document.
475
- *
476
- * The engine adds at most 50 such words to a query, which it divides as
477
- * evenly as it can among the query words. Within the share of each query
478
- * word, it adds first the words that the most documents contain. It scores
479
- * a match inside a longer word in proportion to the part of that word that
480
- * the query word makes up, so it scores such a match below a whole-word
481
- * match at the same frequency in a field of the same length. With
482
- * `highlight`, it tags each whole word that contains a query word in a
483
- * searched `partial` field.
199
+ * Builds an error carrying a code the caller can branch on.
484
200
  *
485
- * The engine applies no `tolerance` to these matches. It ignores this
486
- * setting where `exact` is true or where the searched fields include no
487
- * `partial` field. Where the setting is absent, the engine treats it as
488
- * false, while it throws `CONFIG_INVALID` for any value other than `true`
489
- * or `false`.
490
- */
491
- partialWords?: boolean;
492
- /**
493
- * With this set, the engine matches each query term only against an equal
494
- * indexed term, so it turns off fuzzy matching, prefix completion, and
495
- * partial-word matching. The engine still stems the query, because the
496
- * index stores stemmed terms, so a search for `running` matches a document
497
- * that contains `runs` through the stem that both words share.
498
- */
499
- exact?: boolean;
500
- /**
501
- * The engine counts the values of these fields across the matching
502
- * documents, and each entry sets how it cuts and sorts that field's counts.
503
- * For a field outside the schema, it counts the values that the documents
504
- * store. It throws `SEARCH_INVALID_FIELD` for a `geopoint` or a vector
505
- * field.
506
- */
507
- facets?: FacetConfig;
508
- /**
509
- * The engine sorts the hits by the values of these fields, in place of the
510
- * relevance ranking. Pass an object keyed by field, or a list of fields in
511
- * the order that the engine compares them. The engine sorts by a `number`,
512
- * `boolean`, or `enum` field, by a text field whose type includes
513
- * `sortable`, or by a list of any of these, which it reduces to one value by
514
- * the entry's `mode`. It throws `SEARCH_INVALID_FIELD` for a sort on a
515
- * `geopoint` or a vector field, because neither type has an order. It throws
516
- * the same code for a sort on any other text field, since the engine keeps
517
- * up to the first 512 code points of every document's value in memory to
518
- * sort by a text field. The engine orders hybrid results by fusion, so it
519
- * throws `SEARCH_INVALID_MODE` for a sort on a hybrid query. It also throws
520
- * that code for a direction other than `asc` and `desc`.
521
- */
522
- sort?: SortSpec;
523
- /** These settings collapse the hits into groups by field value. */
524
- group?: GroupConfig;
525
- /**
526
- * The query returns this many hits, and 10 by default. Pass 0 to read the
527
- * match count with no hits. The engine reads a value below 0 as 0. It falls
528
- * back to the default for `NaN` and for an infinite value, so a page size
529
- * that you compute from user input never fails the query.
530
- */
531
- limit?: number;
532
- /** The query skips this many hits before returning. A deep offset costs more than a cursor. */
533
- offset?: number;
534
- /** This cursor comes from a previous result's `cursor`, and pages without an offset's cost. */
535
- searchAfter?: string;
536
- /** These settings name the fields that come back with highlighted snippets. */
537
- highlight?: HighlightConfig;
538
- /** These documents take fixed positions, ahead of the ranking. */
539
- pinned?: Array<{
540
- docId: string;
541
- position: number;
542
- }>;
543
- /** This picks which engine answers the query. Keyword search runs by default. */
544
- mode?: SearchMode;
545
- /** These vector-search inputs are required in `vector` and `hybrid` mode. */
546
- vector?: VectorQueryConfig;
547
- /** These settings control how the keyword and vector rankings merge in `hybrid` mode. */
548
- hybrid?: HybridConfig;
549
- /**
550
- * Setting this returns relevance scores on a sorted query. A query that
551
- * names a sort ranks by sort values alone and computes no scores, so its
552
- * hits carry none until this restores them. A query without a sort ignores
553
- * this and always carries scores.
201
+ * @param code - The failure this error reports, from {@link ErrorCodes} for
202
+ * an engine failure, {@link ServerErrorCodes} for one the HTTP layer raised,
203
+ * or {@link ClientErrorCodes} for one that stopped a request from reaching a
204
+ * server.
205
+ * @param message - Plain description, for a log or a person.
206
+ * @param details - Values behind the failure, which reach
207
+ * {@link NarsilError.details}.
554
208
  */
555
- includeScores?: boolean;
556
- /** Setting this returns the numbers behind each hit's score, which is what you read when a ranking surprises you. */
557
- includeScoreComponents?: boolean;
558
- /** This chooses how much of each stored document comes back, and the whole document by default. */
559
- document?: DocumentProjection;
209
+ constructor(code: NarsilErrorCode, message: string, details?: Record<string, unknown>);
560
210
  }
561
211
  /**
562
- * How much of a stored document each hit carries back.
212
+ * Reports whether a caught value is a {@link NarsilError}, including one that
213
+ * another entry point of this package raises.
563
214
  *
564
- * Pass `false` when the ids and scores are all you need, and every hit's
565
- * `document` is then an empty object. Pass `include` to keep named fields
566
- * alone, or `exclude` to drop named fields and keep the rest; naming both
567
- * keeps the included fields and then drops the excluded ones from those. Use
568
- * dots to name a nested field, so `author.name` addresses the `name` inside
569
- * `author`, and a name that matches no field changes nothing.
215
+ * Each browser bundle holds its own copy of the class, so an `instanceof` test
216
+ * inside the React bindings returns false for an error that the client raises,
217
+ * although that error still holds its code. This function tests for the marker
218
+ * that the constructor writes, so it returns true for an error from any entry
219
+ * point.
570
220
  *
571
- * Drop a vector field on a similarity search, because the engine otherwise
572
- * reads every hit's vector back out of the index and writes it into the
573
- * response.
221
+ * @param value - The value that a `catch` block receives.
222
+ * @returns True where the value holds a code in {@link NarsilError.code}.
574
223
  *
575
224
  * @public
576
225
  */
577
- type DocumentProjection = boolean | {
578
- /** Names the fields to keep, so every field left out of this list is dropped. */
579
- include?: string[];
580
- /** Names the fields to drop, so every other field is kept. */
581
- exclude?: string[];
582
- };
226
+ declare function isNarsilError(value: unknown): value is NarsilError;
227
+
583
228
  /**
584
- * Vector-search inputs passed under `QueryParams.vector`.
229
+ * What {@link Narsil.query} returns: the ranked hits and everything the query
230
+ * asked for alongside them.
585
231
  *
586
- * Supply either a raw `value` array or a `text` string for auto-embedding;
587
- * passing both throws `EMBEDDING_CONFIG_INVALID`. Result count is governed
588
- * by the outer query's `limit`, not by any field on this object.
232
+ * @typeParam T - Shape of the stored documents, which flows through to each
233
+ * hit's `document`.
589
234
  *
590
235
  * @public
591
236
  */
592
- interface VectorQueryConfig {
593
- /**
594
- * Name of the schema field that holds the vector to compare against.
595
- * Must reference a field declared as `vector[N]` in the index schema.
596
- */
597
- field: string;
598
- /**
599
- * Raw query vector, given as a number array or a `Float32Array`. Length
600
- * must match the indexed field's dimension or the search rejects the
601
- * request with `VECTOR_DIMENSION_MISMATCH`.
602
- */
603
- value?: number[] | Float32Array;
604
- /**
605
- * Text to embed at query time using the index or instance embedding
606
- * adapter. Mutually exclusive with `value`; requires a configured adapter.
607
- */
608
- text?: string;
609
- /**
610
- * Score floor applied during ranking. Hits scoring below this value
611
- * are dropped before `limit` is enforced, so the returned hit count
612
- * can be smaller than `limit` even when more documents exist. The
613
- * floor is interpreted in score space for every metric; for
614
- * `euclidean`, distance is mapped to a similarity score of
615
- * `1 / (1 + distance)` first. Defaults to no floor.
616
- */
617
- similarity?: number;
618
- /**
619
- * Similarity metric used for ranking. Defaults to `cosine`. Choose
620
- * `dotProduct` for raw inner-product scoring on already-normalised
621
- * vectors and `euclidean` for distance-based ordering.
622
- */
623
- metric?: 'cosine' | 'dotProduct' | 'euclidean';
237
+ interface QueryResult<T = AnyDocument> {
238
+ /** These documents match, cut to the query's `limit`, best score first or in the query's sort order. */
239
+ hits: Array<Hit<T>>;
624
240
  /**
625
- * HNSW exploration factor for approximate search. Higher values raise
626
- * recall at the cost of latency. Ignored while the field is still
627
- * served by the brute-force backend. Defaults to the engine's built-in
628
- * value when omitted.
241
+ * This many documents match in total, before the engine applies `limit`
242
+ * and `offset`. For a keyword search the engine counts every match. For a
243
+ * vector search it counts every vector that passes the query's filter and
244
+ * its `similarity` floor, which is every vector in the field where the query
245
+ * sets neither of them. The engine also counts each pinned document that
246
+ * the query does not match, since it places that document among the hits.
629
247
  */
630
- efSearch?: number;
248
+ count: number;
631
249
  /**
632
- * How many times `limit` a quantized field re-scores against its
633
- * full-precision vectors before it returns the best `limit`. A value below
634
- * 1 or one that is not a finite number fails with `CONFIG_INVALID`. The
635
- * engine ignores this on a field whose quantization is `none`. When a query
636
- * omits it, the engine takes 3 for `osq1` and `osq2`, 2 for `osq8`, and 2
637
- * for `osq4` at 1,024 dimensions and above, but 5 for `osq4` below 1,024,
638
- * where a four-bit code ranks the true neighbours less reliably.
250
+ * `count` holds the exact number of matches where this is true, and a
251
+ * number at or below the true total where it is false. Where a query sets a
252
+ * `similarity` floor on a vector field that holds a graph, the engine
253
+ * counts only the vectors that it fetches, because it compares the query
254
+ * with only a fraction of that field's vectors. For a hybrid query the
255
+ * engine fuses two rankings, so the count is exact only where each of those
256
+ * rankings contains every matching document. Where you pin a document from
257
+ * outside the hits that the engine fetches, the engine reports true only
258
+ * where it holds every match of the query, because only then can it test
259
+ * whether the query matches that document.
639
260
  */
640
- oversample?: number;
261
+ countExact: boolean;
262
+ /** The engine spent this many milliseconds on the search. */
263
+ elapsed: number;
264
+ /** This opaque cursor reaches the next page. Pass it back as `searchAfter`. */
265
+ cursor?: string;
266
+ /** These facet counts are keyed by the field each facet was asked for. */
267
+ facets?: Record<string, FacetResult>;
268
+ /** These groups arrive when the query asked for grouping. */
269
+ groups?: GroupResult[];
270
+ /** This turns true when the index's terms came from an older analysis than its language module produces now. */
271
+ analysisStale?: boolean;
272
+ /** The search read this much of the index, which is how you spot a degraded answer. */
273
+ coverage: QueryCoverage;
641
274
  }
642
275
  /**
643
- * How a hybrid query merges its keyword ranking with its vector ranking.
276
+ * How much of an index one search read, which is what you check before you
277
+ * trust a count or a ranking.
644
278
  *
645
- * `rrf` combines the two by rank alone, which needs no tuning and handles
646
- * scores that live on different scales. `linear` blends the scores directly,
647
- * which gives you control once you know what each side's scores look like.
279
+ * An embedded engine reads every partition it holds, so `queriedPartitions`
280
+ * matches `totalPartitions` there and the other two stay zero. A search across
281
+ * a cluster may find a node slow or unreachable, which it counts here while
282
+ * still returning the hits the other nodes gave it.
648
283
  *
649
284
  * @public
650
285
  */
651
- interface HybridConfig {
652
- /** The engine merges the rankings this way, and by rank fusion by default. It throws `CONFIG_INVALID` for any other value. */
653
- strategy?: 'rrf' | 'linear';
654
- /** The engine uses this rank-fusion constant under `rrf` alone, where a larger value reduces the lead of the top ranks. Set a whole number of at least 1, or leave it out for 60. The engine throws `CONFIG_INVALID` for any other value. */
655
- k?: number;
656
- /** The engine uses this weight of the vector score, from 0 to 1, under `linear` alone, and 0.5 where you leave it out. It throws `CONFIG_INVALID` for a value outside that range. */
657
- alpha?: number;
286
+ interface QueryCoverage {
287
+ /** The search should have read this many partitions. */
288
+ totalPartitions: number;
289
+ /** The search read this many of them. */
290
+ queriedPartitions: number;
291
+ /** The search counts a partition here when the node holding it took longer than the query allowed. */
292
+ timedOutPartitions: number;
293
+ /** The search counts a partition here when the node holding it returned an error, and when no active replica served it. */
294
+ failedPartitions: number;
658
295
  }
659
296
  /**
660
- * Fields a query counts values for, keyed by field name.
297
+ * One matching document, with the score that ranked it.
661
298
  *
662
- * @public
663
- */
664
- interface FacetConfig {
665
- /** Each key names a field the query counts values for. */
666
- [field: string]: {
667
- /** The engine returns this many values for the field, in the order of `sort`. An engine returns every value where you leave this out, while a cluster returns 10, or every range of a field that sets `ranges`. */
668
- limit?: number;
669
- /** The engine orders the returned values by their count, putting the highest first under `'desc'`, which is the default, and the lowest first under `'asc'`. Under `'asc'`, each cluster node sends the count of up to 10,000 values of the field, so the lowest counts are exact wherever no node holds more values than that. */
670
- sort?: 'asc' | 'desc';
671
- /** The engine counts a numeric field's matches into these ranges, with one count for each range. A cluster search counts up to 1,000 ranges on a field and throws `CONFIG_INVALID` for more. */
672
- ranges?: Array<{
673
- from: number;
674
- to: number;
675
- }>;
676
- };
677
- }
678
- /**
679
- * How a query collapses its hits into groups.
299
+ * @typeParam T - Shape of the stored document.
680
300
  *
681
301
  * @public
682
302
  */
683
- interface GroupConfig {
684
- /** The values of these fields define a group, and several fields group by their combination. */
685
- fields: string[];
686
- /** The engine returns this many hits from each group, best first, and one hit where you leave this out. */
687
- maxPerGroup?: number;
688
- /** The engine returns this many groups, best first, and every group where you leave this out. */
689
- limit?: number;
303
+ interface Hit<T = AnyDocument> {
304
+ /** The document is stored under this id. */
305
+ id: string;
690
306
  /**
691
- * The engine folds every hit of each group into one value, such as a sum or
692
- * an average, including the hits beyond `maxPerGroup`. In cluster mode the
693
- * coordinator fetches up to 10,000 hits of each group to fold.
307
+ * This score ranked the hit. Scores compare within one result set, never
308
+ * across searches. A sorted query ranks by sort values instead and carries
309
+ * no score unless it sets `includeScores`.
694
310
  */
695
- reduce?: GroupReducer;
311
+ score?: number;
312
+ /** This is the stored document. */
313
+ document: T;
314
+ /** These are the parts the score was built from, which arrive when the query asked for them. */
315
+ scoreComponents?: ScoreComponents;
316
+ /** These highlighted snippets are keyed by field, and arrive when the query asked for highlighting. */
317
+ highlights?: Record<string, HighlightMatch>;
696
318
  }
697
319
  /**
698
- * Folds the hits of one group into a single value.
320
+ * The numbers BM25 combined into one hit's score, which is what you read when
321
+ * a ranking surprises you.
699
322
  *
700
323
  * @public
701
324
  */
702
- type GroupReducer = {
325
+ interface ScoreComponents {
703
326
  /**
704
- * Folds one hit into the running value.
705
- *
706
- * @param accumulator - What the previous call returned, or what
707
- * `initialValue` produced for the first hit.
708
- * @param doc - The hit's stored document.
709
- * @param score - The hit's relevance score.
710
- * @returns The new running value.
327
+ * Each query term appears in one field of this document this many times,
328
+ * under a key of `field:term`. A term that appears in two fields therefore
329
+ * has two entries here, while the keys of {@link ScoreComponents.idf} hold
330
+ * the bare term.
711
331
  */
712
- reducer: (accumulator: unknown, doc: AnyDocument, score: number) => unknown;
713
- /** Produces the starting value for each group. The engine calls it once per group. */
714
- initialValue: () => unknown;
715
- };
332
+ termFrequencies: Record<string, number>;
333
+ /** Each field the query searched holds this many tokens, keyed by field. */
334
+ fieldLengths: Record<string, number>;
335
+ /** Each query term carries this inverse document frequency, which is what makes a rare term count for more. */
336
+ idf: Record<string, number>;
337
+ }
716
338
  /**
717
- * This configuration names the fields that receive highlighted snippets. It
718
- * also sets how the engine marks those snippets up.
719
- *
720
- * The engine analyses the text of each returned field again to tag every word
721
- * that it matched, so it tags the same words whatever the index's
722
- * `trackPositions` setting is. It tags a word whose stem equals a query stem,
723
- * and a word within the query's `tolerance` of a query stem. For a `prefix`
724
- * query, it tags a word for the last query term only when that word completes
725
- * the term or shares its stem.
339
+ * A highlighted field, ready to render.
726
340
  *
727
341
  * @public
728
342
  */
729
- interface HighlightConfig {
730
- /** The engine highlights these fields. */
731
- fields: string[];
732
- /** The engine writes this before each match, and writes `<mark>` by default. */
733
- preTag?: string;
734
- /** The engine writes this after each match, and writes `</mark>` by default. */
735
- postTag?: string;
343
+ interface HighlightMatch {
344
+ /** This is the field's text around the match, wrapped in the query's tags. */
345
+ snippet: string;
736
346
  /**
737
- * The engine takes this many characters of the field around the densest run
738
- * of matches, 200 by default. It returns a snippet longer than that number,
739
- * because it then adds the opening and closing tags, and an ellipsis at each
740
- * end where it cuts the field.
347
+ * Each range gives the start and the end of one match in the original field,
348
+ * so you can render the highlight yourself. Where the snippet covers part of
349
+ * the field alone, the engine lists only the matches that the snippet
350
+ * displays. Every offset is a character count from the start of the original
351
+ * field, whatever the snippet contains.
741
352
  */
742
- maxSnippetLength?: number;
353
+ positions: Array<{
354
+ start: number;
355
+ end: number;
356
+ }>;
743
357
  }
744
-
745
358
  /**
746
- * Every code a {@link NarsilError} carries, grouped by the part of the engine
747
- * that raises it.
748
- *
749
- * Match on the code rather than on the message, because a code is stable and a
750
- * message is not. The HTTP server maps each code to a status, so a code also
751
- * tells you whether the caller or the engine is at fault.
359
+ * Counts for one faceted field.
752
360
  *
753
361
  * @public
754
362
  */
755
- declare const ErrorCodes: {
756
- readonly SCHEMA_INVALID_TYPE: "SCHEMA_INVALID_TYPE";
757
- readonly SCHEMA_DEPTH_EXCEEDED: "SCHEMA_DEPTH_EXCEEDED";
758
- readonly SCHEMA_INVALID_VECTOR_DIMENSION: "SCHEMA_INVALID_VECTOR_DIMENSION";
759
- readonly SCHEMA_INVALID_GEOPOINT: "SCHEMA_INVALID_GEOPOINT";
760
- readonly DOC_NOT_FOUND: "DOC_NOT_FOUND";
761
- readonly DOC_ALREADY_EXISTS: "DOC_ALREADY_EXISTS";
762
- readonly DOC_VALIDATION_FAILED: "DOC_VALIDATION_FAILED";
763
- readonly INDEX_NOT_FOUND: "INDEX_NOT_FOUND";
764
- readonly INDEX_ALREADY_EXISTS: "INDEX_ALREADY_EXISTS";
765
- readonly INDEX_ORPHANED: "INDEX_ORPHANED";
766
- readonly INDEX_REOPEN_CAPACITY_EXHAUSTED: "INDEX_REOPEN_CAPACITY_EXHAUSTED";
767
- readonly INSTANCE_SHUT_DOWN: "INSTANCE_SHUT_DOWN";
768
- readonly PARTITION_CORRUPTED: "PARTITION_CORRUPTED";
769
- readonly PARTITION_REBALANCING_BACKPRESSURE: "PARTITION_REBALANCING_BACKPRESSURE";
770
- readonly WORKER_CRASHED: "WORKER_CRASHED";
771
- readonly WORKER_BUSY: "WORKER_BUSY";
772
- readonly WORKER_TIMEOUT: "WORKER_TIMEOUT";
773
- readonly WORKER_ACTION_FAILED: "WORKER_ACTION_FAILED";
774
- readonly PERSISTENCE_SAVE_FAILED: "PERSISTENCE_SAVE_FAILED";
775
- readonly PERSISTENCE_LOAD_FAILED: "PERSISTENCE_LOAD_FAILED";
776
- readonly PERSISTENCE_DELETE_FAILED: "PERSISTENCE_DELETE_FAILED";
777
- readonly PERSISTENCE_CRC_MISMATCH: "PERSISTENCE_CRC_MISMATCH";
778
- readonly PERSISTENCE_WAL_CORRUPT: "PERSISTENCE_WAL_CORRUPT";
779
- readonly PERSISTENCE_FSYNC_FAILED: "PERSISTENCE_FSYNC_FAILED";
780
- readonly SEARCH_INVALID_FIELD: "SEARCH_INVALID_FIELD";
781
- readonly VECTOR_DIMENSION_MISMATCH: "VECTOR_DIMENSION_MISMATCH";
782
- readonly SEARCH_INVALID_FILTER: "SEARCH_INVALID_FILTER";
783
- readonly SEARCH_INVALID_MODE: "SEARCH_INVALID_MODE";
784
- readonly SEARCH_INVALID_CURSOR: "SEARCH_INVALID_CURSOR";
785
- readonly SEARCH_RESULT_WINDOW_EXCEEDED: "SEARCH_RESULT_WINDOW_EXCEEDED";
786
- readonly SEARCH_WORK_CAP_EXCEEDED: "SEARCH_WORK_CAP_EXCEEDED";
787
- readonly LANGUAGE_NOT_SUPPORTED: "LANGUAGE_NOT_SUPPORTED";
788
- readonly ENVELOPE_VERSION_MISMATCH: "ENVELOPE_VERSION_MISMATCH";
789
- readonly ENVELOPE_INVALID_MAGIC: "ENVELOPE_INVALID_MAGIC";
790
- readonly PARTITION_CAPACITY_EXCEEDED: "PARTITION_CAPACITY_EXCEEDED";
791
- readonly EMBEDDING_FAILED: "EMBEDDING_FAILED";
792
- readonly EMBEDDING_DIMENSION_MISMATCH: "EMBEDDING_DIMENSION_MISMATCH";
793
- readonly EMBEDDING_NO_SOURCE: "EMBEDDING_NO_SOURCE";
794
- readonly EMBEDDING_CONFIG_INVALID: "EMBEDDING_CONFIG_INVALID";
795
- readonly DOC_MISSING_REQUIRED_FIELD: "DOC_MISSING_REQUIRED_FIELD";
796
- readonly CONFIG_INVALID: "CONFIG_INVALID";
797
- readonly QUERY_ROUTING_FAILED: "QUERY_ROUTING_FAILED";
798
- readonly QUERY_PARTIAL_FAILURE: "QUERY_PARTIAL_FAILURE";
799
- readonly QUERY_NODE_TIMEOUT: "QUERY_NODE_TIMEOUT";
800
- readonly QUERY_NO_ACTIVE_REPLICA: "QUERY_NO_ACTIVE_REPLICA";
801
- readonly CLUSTER_OPERATION_UNSUPPORTED: "CLUSTER_OPERATION_UNSUPPORTED";
802
- readonly ALLOCATION_NO_DATA_NODES: "ALLOCATION_NO_DATA_NODES";
803
- readonly ALLOCATION_INVALID_CONFIG: "ALLOCATION_INVALID_CONFIG";
804
- readonly ALLOCATION_FAILED: "ALLOCATION_FAILED";
805
- readonly CONTROLLER_METADATA_INVALID: "CONTROLLER_METADATA_INVALID";
806
- readonly NODE_BOOTSTRAP_FAILED: "NODE_BOOTSTRAP_FAILED";
807
- readonly NODE_ALREADY_JOINED: "NODE_ALREADY_JOINED";
808
- readonly NODE_NOT_JOINED: "NODE_NOT_JOINED";
809
- readonly NODE_NOT_READY: "NODE_NOT_READY";
810
- readonly NODE_NOT_CONTROLLER: "NODE_NOT_CONTROLLER";
811
- readonly COORDINATOR_DEPENDENCY_MISSING: "COORDINATOR_DEPENDENCY_MISSING";
812
- readonly TRANSPORT_DEPENDENCY_MISSING: "TRANSPORT_DEPENDENCY_MISSING";
813
- readonly REPLICATION_ENTRY_INVALID: "REPLICATION_ENTRY_INVALID";
814
- readonly REPLICATION_INSYNC_REMOVAL_FAILED: "REPLICATION_INSYNC_REMOVAL_FAILED";
815
- readonly REPLICATION_ROLLBACK_FAILED: "REPLICATION_ROLLBACK_FAILED";
816
- readonly REPLICATION_LOG_FULL: "REPLICATION_LOG_FULL";
817
- readonly REPLICATION_ENTRY_CORRUPT: "REPLICATION_ENTRY_CORRUPT";
818
- readonly REPLICATION_SNAPSHOT_CORRUPT: "REPLICATION_SNAPSHOT_CORRUPT";
819
- readonly REPLICATION_TERM_MISMATCH: "REPLICATION_TERM_MISMATCH";
820
- readonly REPLICATION_SYNC_FAILED: "REPLICATION_SYNC_FAILED";
821
- readonly PARTITION_NOT_PRIMARY: "PARTITION_NOT_PRIMARY";
822
- readonly PARTITION_UNASSIGNED: "PARTITION_UNASSIGNED";
823
- readonly INSUFFICIENT_REPLICAS: "INSUFFICIENT_REPLICAS";
824
- readonly SNAPSHOT_SYNC_UNAUTHORIZED: "SNAPSHOT_SYNC_UNAUTHORIZED";
825
- readonly SNAPSHOT_SYNC_REQUEST_INVALID: "SNAPSHOT_SYNC_REQUEST_INVALID";
826
- readonly SNAPSHOT_SYNC_INDEX_NOT_FOUND: "SNAPSHOT_SYNC_INDEX_NOT_FOUND";
827
- readonly SNAPSHOT_SYNC_CAPACITY_EXHAUSTED: "SNAPSHOT_SYNC_CAPACITY_EXHAUSTED";
828
- readonly SNAPSHOT_SYNC_SNAPSHOT_FAILED: "SNAPSHOT_SYNC_SNAPSHOT_FAILED";
829
- readonly SNAPSHOT_SYNC_DECODE_FAILED: "SNAPSHOT_SYNC_DECODE_FAILED";
830
- readonly SNAPSHOT_SYNC_FRAME_INVALID: "SNAPSHOT_SYNC_FRAME_INVALID";
831
- readonly SNAPSHOT_SYNC_HEADER_INVALID: "SNAPSHOT_SYNC_HEADER_INVALID";
832
- readonly SNAPSHOT_SYNC_HEADER_MISMATCH: "SNAPSHOT_SYNC_HEADER_MISMATCH";
833
- readonly SNAPSHOT_SYNC_CHUNK_OUT_OF_ORDER: "SNAPSHOT_SYNC_CHUNK_OUT_OF_ORDER";
834
- readonly SNAPSHOT_SYNC_CHUNK_OVERFLOW: "SNAPSHOT_SYNC_CHUNK_OVERFLOW";
835
- readonly SNAPSHOT_SYNC_CHUNK_SIZE_EXCEEDED: "SNAPSHOT_SYNC_CHUNK_SIZE_EXCEEDED";
836
- readonly SNAPSHOT_SYNC_CHUNK_MISSING: "SNAPSHOT_SYNC_CHUNK_MISSING";
837
- readonly SNAPSHOT_SYNC_END_MISSING: "SNAPSHOT_SYNC_END_MISSING";
838
- readonly SNAPSHOT_SYNC_CHECKSUM_MISMATCH: "SNAPSHOT_SYNC_CHECKSUM_MISMATCH";
839
- readonly SNAPSHOT_SYNC_PRIMARY_ERROR: "SNAPSHOT_SYNC_PRIMARY_ERROR";
840
- readonly SNAPSHOT_SYNC_NO_TARGETS: "SNAPSHOT_SYNC_NO_TARGETS";
841
- readonly SNAPSHOT_SYNC_TRANSPORT_FAILED: "SNAPSHOT_SYNC_TRANSPORT_FAILED";
842
- readonly SNAPSHOT_SYNC_SCHEMA_UNAVAILABLE: "SNAPSHOT_SYNC_SCHEMA_UNAVAILABLE";
843
- readonly SNAPSHOT_SYNC_RESTORE_FAILED: "SNAPSHOT_SYNC_RESTORE_FAILED";
844
- readonly SNAPSHOT_SYNC_RESTORE_CLEANUP_FAILED: "SNAPSHOT_SYNC_RESTORE_CLEANUP_FAILED";
845
- readonly SNAPSHOT_SYNC_TIMEOUT: "SNAPSHOT_SYNC_TIMEOUT";
846
- readonly SNAPSHOT_SYNC_ALLOCATION_UNAVAILABLE: "SNAPSHOT_SYNC_ALLOCATION_UNAVAILABLE";
847
- readonly SNAPSHOT_SYNC_NOT_ASSIGNED: "SNAPSHOT_SYNC_NOT_ASSIGNED";
848
- readonly SNAPSHOT_SYNC_ABORTED: "SNAPSHOT_SYNC_ABORTED";
849
- };
363
+ interface FacetResult {
364
+ /** This many documents match per value, keyed by value. */
365
+ values: Record<string, number>;
366
+ /** This is the number of entries in `values`, which is at most the facet's `limit`. */
367
+ count: number;
368
+ /**
369
+ * Every count in `values` is at most this far below its true count. A value
370
+ * that the engine leaves out of `values` because of `limit` has a true
371
+ * count of at most this figure too. Where the engine counts a field on one
372
+ * thread, it counts every value exactly, so this figure is the largest
373
+ * count that it leaves out. Where it splits the count across worker copies
374
+ * or cluster nodes, each of them returns only its own top values, so the
375
+ * merged count of a value that is common overall but rare on one of them
376
+ * can lack the matches on that one. A bound of 0 means that `values` holds
377
+ * every matching value, each with its exact count.
378
+ */
379
+ errorBound: number;
380
+ }
850
381
  /**
851
- * Any one of the codes in {@link ErrorCodes}, which is the type to narrow on
852
- * when you branch on a failure the engine raised.
382
+ * One group of hits, produced by a query that grouped its results.
853
383
  *
854
384
  * @public
855
385
  */
856
- type ErrorCode = (typeof ErrorCodes)[keyof typeof ErrorCodes];
386
+ interface GroupResult {
387
+ /** Each grouping field holds this value for the group, keyed by field. */
388
+ values: Record<string, unknown>;
389
+ /** These hits fall in the group, cut to the query's `maxPerGroup`. */
390
+ hits: Array<Hit>;
391
+ /** The query's reducer produced this value for the group, and only a query that set `group.reduce` carries it. */
392
+ reduced?: unknown;
393
+ /** The reducer threw, and this holds its message, so the group carries its hits and no `reduced` value. */
394
+ reducerError?: string;
395
+ }
857
396
  /**
858
- * Every code the HTTP layer raises for a failure that arises before or around
859
- * the engine call, such as parsing the body, enforcing a limit, or routing.
860
- *
861
- * The engine raises none of these, so a failure carrying one of them says the
862
- * request never reached the engine.
397
+ * What {@link Narsil.preflight} returns: how many documents a query matches,
398
+ * without building or ranking a single hit.
863
399
  *
864
400
  * @public
865
401
  */
866
- declare const ServerErrorCodes: {
867
- readonly INVALID_REQUEST: "INVALID_REQUEST";
868
- readonly INVALID_JSON: "INVALID_JSON";
869
- readonly EMPTY_BODY: "EMPTY_BODY";
870
- readonly PAYLOAD_TOO_LARGE: "PAYLOAD_TOO_LARGE";
871
- readonly NOT_FOUND: "NOT_FOUND";
872
- readonly TASK_NOT_FOUND: "TASK_NOT_FOUND";
873
- readonly TASK_NOT_CANCELLABLE: "TASK_NOT_CANCELLABLE";
874
- readonly TASK_OWNED_BY_ANOTHER_INSTANCE: "TASK_OWNED_BY_ANOTHER_INSTANCE";
875
- readonly TASK_INTERRUPTED: "TASK_INTERRUPTED";
876
- readonly TOO_MANY_REQUESTS: "TOO_MANY_REQUESTS";
877
- readonly HOOK_ERROR: "HOOK_ERROR";
878
- readonly INTERNAL_ERROR: "INTERNAL_ERROR";
879
- };
402
+ interface PreflightResult {
403
+ /** The query matches this many documents. */
404
+ count: number;
405
+ /** `count` holds the exact number of matches where this is true, and a number at or below the true total where it is false, under the rule in {@link QueryResult.countExact}. */
406
+ countExact: boolean;
407
+ /** The count took this many milliseconds. */
408
+ elapsed: number;
409
+ /** This turns true when the index's terms came from an older analysis than its language module produces now. */
410
+ analysisStale?: boolean;
411
+ }
880
412
  /**
881
- * Any one of the codes in {@link ServerErrorCodes}.
413
+ * What a batch write returns. One bad document never abandons the rest, so
414
+ * read both lists.
882
415
  *
883
416
  * @public
884
417
  */
885
- type ServerErrorCode = (typeof ServerErrorCodes)[keyof typeof ServerErrorCodes];
418
+ interface BatchResult {
419
+ /** The engine wrote the documents under these ids. */
420
+ succeeded: string[];
421
+ /** The engine rejected each of these documents, and each entry carries the error that rejected it. */
422
+ failed: Array<{
423
+ docId: string;
424
+ error: NarsilError;
425
+ }>;
426
+ }
886
427
  /**
887
- * Every code that the caller's own side raises, where a request never reaches
888
- * a server, or where the caller cannot read the answer.
428
+ * What {@link Narsil.importDocumentExport} returns. The engine continues past each
429
+ * refused line, so read the refusals to learn which documents it skipped.
889
430
  *
890
- * The HTTP client raises the first five. The React bindings raise
891
- * `CLIENT_UNEXPECTED_ERROR` alone, which reports a fault inside a hook. No
892
- * server sends any of them, so a failure under one means the exchange broke
893
- * before the operation ran. `STATUS_BY_CODE` in `src/server/errors.ts`
894
- * therefore maps none of them, because no request can arrive under one and no
895
- * HTTP status belongs to one.
431
+ * @public
432
+ */
433
+ interface DocumentImportResult {
434
+ /** The engine wrote this many documents, counting each one that it replaced. */
435
+ imported: number;
436
+ /** The engine refused this many lines in total. */
437
+ refusedCount: number;
438
+ /** These are the 1,000 refusals with the lowest line numbers. Each entry contains the line number, where the header is line 1, along with the error code and a message. */
439
+ refused: Array<{
440
+ line: number;
441
+ code: NarsilErrorCode;
442
+ message: string;
443
+ }>;
444
+ }
445
+ /**
446
+ * What {@link Narsil.getStats} returns about one index.
896
447
  *
897
448
  * @public
898
449
  */
899
- declare const ClientErrorCodes: {
900
- readonly CLIENT_CONNECTION_FAILED: "CLIENT_CONNECTION_FAILED";
901
- readonly CLIENT_REQUEST_TIMEOUT: "CLIENT_REQUEST_TIMEOUT";
902
- readonly CLIENT_REQUEST_ABORTED: "CLIENT_REQUEST_ABORTED";
903
- readonly CLIENT_INVALID_RESPONSE: "CLIENT_INVALID_RESPONSE";
904
- readonly CLIENT_TASK_TIMEOUT: "CLIENT_TASK_TIMEOUT";
905
- readonly CLIENT_UNEXPECTED_ERROR: "CLIENT_UNEXPECTED_ERROR";
906
- };
450
+ interface IndexStats {
451
+ /** The index holds this many documents. A closed index reports its count as of the last checkpoint. */
452
+ documentCount: number;
453
+ /** The index is spread across this many partitions. */
454
+ partitionCount: number;
455
+ /**
456
+ * Formula-based estimate of the index's main-thread memory footprint, summed
457
+ * across every partition and vector index for this index. Computed from
458
+ * structural counters (document count, posting counts, field-index sizes),
459
+ * not measured. Per-object V8 overhead (hidden classes, map transitions,
460
+ * GC headers) is not captured here, so this number routinely undershoots
461
+ * the real heap by a meaningful factor. Use {@link Narsil.getMemoryStats}
462
+ * when sizing host memory.
463
+ */
464
+ estimatedMemoryBytes: number;
465
+ /** The index analyses text with this language module. */
466
+ language: string;
467
+ /** The index was created with this field layout. */
468
+ schema: SchemaDefinition;
469
+ }
907
470
  /**
908
- * Any one of the codes in {@link ClientErrorCodes}.
471
+ * A summary of one index, as {@link Narsil.listIndexes} reports it.
909
472
  *
910
473
  * @public
911
474
  */
912
- type ClientErrorCode = (typeof ClientErrorCodes)[keyof typeof ClientErrorCodes];
475
+ interface IndexInfo {
476
+ /** The index was created under this name. */
477
+ name: string;
478
+ /** The index holds this many documents. A closed index reports its count as of the last checkpoint. */
479
+ documentCount: number;
480
+ /** The index is spread across this many partitions. */
481
+ partitionCount: number;
482
+ /** The index analyses text with this language module. */
483
+ language: string;
484
+ /** This turns true when the index's terms came from an older analysis than its language module produces now. */
485
+ analysisStale?: boolean;
486
+ /** This is `open` in memory, `closed` after release, and `reopen-failed` after five recovery failures. */
487
+ state: 'open' | 'closed' | 'reopen-failed';
488
+ /** This counts successful loads since this engine started. */
489
+ reopenCount: number;
490
+ }
913
491
  /**
914
- * Every code a {@link NarsilError} can carry: one the engine raised, one the
915
- * HTTP layer raised, one the client raised, or any other string.
492
+ * What {@link Narsil.getPartitionStats} reports for one partition, which is
493
+ * where you look when an index grows unevenly.
916
494
  *
917
- * The last arm exists for a server's `onRequest` hook, which rejects a request
918
- * under a code of its own, such as `UNAUTHORIZED`, and the client then passes
919
- * that code through unchanged. An editor still completes every code Narsil
920
- * defines.
495
+ * @public
496
+ */
497
+ interface PartitionStatsResult {
498
+ /** This identifies the partition within its index. */
499
+ partitionId: number;
500
+ /** The partition holds this many documents. */
501
+ documentCount: number;
502
+ /**
503
+ * Formula-based estimate of this partition's memory footprint. V8 has no
504
+ * per-object heap accounting API, so this number is derived from structural
505
+ * counters (document count, posting counts, field-index sizes) and does not
506
+ * include per-object overhead. Treat as an estimate, not a measurement.
507
+ */
508
+ estimatedMemoryBytes: number;
509
+ }
510
+ /**
511
+ * What {@link Narsil.suggest} returns: the indexed terms that complete a
512
+ * prefix, ready to offer as you-type suggestions.
921
513
  *
922
514
  * @public
923
515
  */
924
- type NarsilErrorCode = ErrorCode | ServerErrorCode | ClientErrorCode | (string & {});
516
+ interface SuggestResult {
517
+ /** These completions run most widely used first. */
518
+ terms: Array<{
519
+ /** This is the completed term, as the index holds it. */
520
+ term: string;
521
+ /** The term appears in this many documents, which is what ordered the list. */
522
+ documentFrequency: number;
523
+ }>;
524
+ /** The lookup took this many milliseconds. */
525
+ elapsed: number;
526
+ /** This turns true when the index's terms came from an older analysis than its language module produces now. */
527
+ analysisStale?: boolean;
528
+ }
925
529
  /**
926
- * The error every part of the engine throws.
530
+ * The state of one vector field, and what maintenance would cost, as
531
+ * {@link Narsil.vectorMaintenanceStatus} reports it.
927
532
  *
928
- * Catch it, read {@link NarsilError.code} to decide what to do, and read
929
- * {@link NarsilError.details} for the values that caused it. The engine lets
930
- * this error propagate unchanged, so the code you catch is the code the
931
- * failing operation raised.
533
+ * Removing a vector leaves a tombstone in the graph, and enough of them slow a
534
+ * search down. Read this to decide when compaction earns its cost.
932
535
  *
933
536
  * @public
934
537
  */
935
- declare class NarsilError extends Error {
936
- /** This says which failure it is. */
937
- readonly code: NarsilErrorCode;
938
- /** This carries the values behind the failure, such as the field, index, or limit involved. It is empty when the code says everything. */
939
- readonly details: Record<string, unknown>;
538
+ interface VectorMaintenanceResult {
539
+ /** This describes the named vector field. */
540
+ fieldName: string;
940
541
  /**
941
- * Builds an error carrying a code the caller can branch on.
942
- *
943
- * @param code - The failure this error reports, from {@link ErrorCodes} for
944
- * an engine failure, {@link ServerErrorCodes} for one the HTTP layer raised,
945
- * or {@link ClientErrorCodes} for one that stopped a request from reaching a
946
- * server.
947
- * @param message - Plain description, for a log or a person.
948
- * @param details - Values behind the failure, which reach
949
- * {@link NarsilError.details}.
542
+ * Tombstones make up this share of the graph's nodes, from 0 to 1. Before
543
+ * the first build, where {@link VectorMaintenanceResult.graphCount} reads 0,
544
+ * the engine divides by the number of stored vectors, because no graph
545
+ * exists yet.
950
546
  */
951
- constructor(code: NarsilErrorCode, message: string, details?: Record<string, unknown>);
547
+ tombstoneRatio: number;
548
+ /** The field holds this many HNSW graphs: 0 before the first build and 1 once a graph exists. */
549
+ graphCount: number;
550
+ /** This many vectors wait outside the graph, which a search scans one by one. */
551
+ bufferSize: number;
552
+ /** This stays true while a graph build runs. */
553
+ building: boolean;
554
+ /** {@link Narsil.compactVectors} would take about this many milliseconds. */
555
+ estimatedCompactMs: number;
556
+ /** {@link Narsil.optimizeVectors} would take about this many milliseconds. */
557
+ estimatedOptimizeMs: number;
558
+ }
559
+ /**
560
+ * One stored document, as {@link Narsil.listDocuments} returns it.
561
+ *
562
+ * @typeParam T - Shape of the stored document.
563
+ *
564
+ * @public
565
+ */
566
+ interface ListedDocument<T = AnyDocument> {
567
+ /** The document is stored under this id. */
568
+ id: string;
569
+ /** This holds the stored document, cut down to what the projection kept. */
570
+ document: T;
571
+ }
572
+ /**
573
+ * What {@link Narsil.listDocuments} returns: one page of stored documents and
574
+ * the cursor that reaches the next one.
575
+ *
576
+ * @typeParam T - Shape of the stored documents.
577
+ *
578
+ * @public
579
+ */
580
+ interface ListResult<T = AnyDocument> {
581
+ /** These documents make up the page, in ascending document-id order. */
582
+ documents: Array<ListedDocument<T>>;
583
+ /** This opaque cursor reaches the next page, and is null once the listing is finished. */
584
+ cursor: string | null;
585
+ /** The listing covers this many documents in total, and any filter narrows that count. */
586
+ total: number;
587
+ /** The engine spent this many milliseconds building the page. */
588
+ elapsed: number;
952
589
  }
590
+
953
591
  /**
954
- * Reports whether a caught value is a {@link NarsilError}, including one that
955
- * another entry point of this package raises.
956
- *
957
- * Each browser bundle holds its own copy of the class, so an `instanceof` test
958
- * inside the React bindings returns false for an error that the client raises,
959
- * although that error still holds its code. This function tests for the marker
960
- * that the constructor writes, so it returns true for an error from any entry
961
- * point.
962
- *
963
- * @param value - The value that a `catch` block receives.
964
- * @returns True where the value holds a code in {@link NarsilError.code}.
592
+ * Compares one field against a value. Setting several keys narrows the match,
593
+ * because a document has to satisfy all of them.
965
594
  *
966
595
  * @public
967
596
  */
968
- declare function isNarsilError(value: unknown): value is NarsilError;
969
-
597
+ type ComparisonFilter = {
598
+ /** This matches a field equal to the value, or a list field where one element equals it. */
599
+ eq?: number | string | boolean;
600
+ /**
601
+ * This matches a document that holds the field with a value other than this
602
+ * one, or a list field where every element differs from it, which an empty
603
+ * list does.
604
+ */
605
+ ne?: number | string | boolean;
606
+ /** This matches a field greater than the number. */
607
+ gt?: number;
608
+ /** This matches a field less than the number. */
609
+ lt?: number;
610
+ /** This matches a field greater than or equal to the number. */
611
+ gte?: number;
612
+ /** This matches a field less than or equal to the number. */
613
+ lte?: number;
614
+ /** This matches a field inside the inclusive range, given as `[low, high]`. */
615
+ between?: [number, number];
616
+ };
970
617
  /**
971
- * This map lists every event that the engine emits, with the payload of each
972
- * one.
618
+ * The engine tests a text field against this filter for equality, for a text
619
+ * range, or with the set, prefix, and pattern tests.
973
620
  *
974
- * {@link Narsil.on} registers a listener under a key from this map, so that the
975
- * engine can pass the matching payload to that listener. Most of these events
976
- * report work that the engine does in the background, away from the call that
977
- * started it, so a failure that such an event reports never rejects a promise
978
- * that you are holding.
621
+ * On a `string[]`, `verbatim[]`, or `enum[]` field, the engine tests each
622
+ * element of the list on its own. A document passes `eq`, `in`, `startsWith`,
623
+ * `endsWith`, `contains`, `wildcard`, or `regex` when one element passes the
624
+ * test. However, a document passes `ne` or `nin` only when every element
625
+ * differs from the values.
626
+ *
627
+ * The engine applies the range tests `gt`, `gte`, `lt`, `lte`, and `between`
628
+ * to a single `string` or `verbatim` field whose type includes `sortable`. It
629
+ * throws `SEARCH_INVALID_FILTER` for a text range on any other field. It
630
+ * orders the values as a sort on the field does, so it compares their case
631
+ * folds first and compares their raw code points only where the folds are
632
+ * equal.
633
+ *
634
+ * A pattern field is a `verbatim` or `verbatim[]` field, or a `string` or
635
+ * `string[]` field whose type includes `pattern`. On a pattern field, the
636
+ * engine answers `eq`, `ne`, `in`, `nin`, `startsWith`, `endsWith`,
637
+ * `contains`, `wildcard`, and `regex` from the field's pattern index, and
638
+ * `caseFold` applies to each of those tests. The engine compares the code
639
+ * points of each value as they are stored, with no Unicode normalisation.
640
+ *
641
+ * On an `enum` or `enum[]` field, the engine answers `eq`, `ne`, `in`, `nin`,
642
+ * `startsWith`, and `endsWith` from the field's index of values. A `string` or
643
+ * `string[]` field whose type leaves out `pattern` keeps no index of whole
644
+ * values, so the engine throws `SEARCH_INVALID_FILTER` for those six tests,
645
+ * and for `matchesAny` and `containsAll`, on such a field.
646
+ *
647
+ * The engine also throws `SEARCH_INVALID_FILTER` in these cases:
648
+ *
649
+ * - The filter sets `contains`, `wildcard`, `regex`, or `caseFold` on a field
650
+ * that is not a pattern field.
651
+ * - The text or the pattern of a test on a pattern field holds more than 1,024
652
+ * code points.
653
+ * - A literal test under `caseFold` has a text whose case fold holds more than
654
+ * 2,048 code points.
655
+ * - A `wildcard` or `regex` pattern breaks its syntax or one of its limits.
979
656
  *
980
657
  * @public
981
658
  */
982
- type NarsilEventMap = {
659
+ type StringFilter = Pick<ComparisonFilter, 'eq' | 'ne'> & {
660
+ /** This matches a value that comes after the text in sort order. */
661
+ gt?: string;
662
+ /** This matches a value that comes before the text in sort order. */
663
+ lt?: string;
664
+ /** This matches a value equal to the text or after it in sort order. */
665
+ gte?: string;
666
+ /** This matches a value equal to the text or before it in sort order. */
667
+ lte?: string;
668
+ /** This matches a value inside the inclusive range in sort order, given as `[low, high]`. */
669
+ between?: [string, string];
670
+ /** This matches a field equal to any value in the list, which holds at most 65,536 values. */
671
+ in?: string[];
672
+ /** This matches a field that differs from every value in the list, which holds at most 65,536 values. */
673
+ nin?: string[];
674
+ /** This matches a field starting with the text. */
675
+ startsWith?: string;
676
+ /** This matches a field ending with the text. */
677
+ endsWith?: string;
678
+ /** This matches a pattern field whose value holds the text anywhere in it. */
679
+ contains?: string;
983
680
  /**
984
- * The engine emits this event after a call changes what a read returns from
985
- * an index. The calls are the inserts, updates, and removals, singly or in a
986
- * batch, together with `clear`, `restore`, `rebalance`, `rebuildAnalysis`,
987
- * `compactVectors`, `optimizeVectors`, `createIndex`, and `dropIndex`. The
988
- * engine emits the event after a call that throws as well, because a call can
989
- * change the index before it throws. It also emits the event after it reloads
990
- * an index, once a shared invalidation adapter reports that another instance
991
- * saved that index. The engine emits one event per batch, however many
992
- * documents the batch holds.
681
+ * This matches a pattern field when the whole value matches the wildcard
682
+ * pattern. For example, `INV-*-2024` matches `INV-0042-2024`.
993
683
  *
994
- * The engine emits the event once a query can see the change, which means
995
- * after every worker copy applies the change and after any rebalance in
996
- * progress replays it. A query that a listener sends from its handler
997
- * therefore returns results that include the change. The engine waits for the
998
- * change to become visible only while a listener is registered for the event.
684
+ * In the pattern, `*` matches any sequence of code points, including an
685
+ * empty one, and `?` matches exactly one code point. Write `\` before a code
686
+ * point to match that code point itself, so `\*` matches an asterisk.
687
+ *
688
+ * The engine throws `SEARCH_INVALID_FILTER` for a pattern that ends in a
689
+ * `\` with no code point after it. It throws the same error for a pattern
690
+ * with more than 2,048 positions. Each `*`, each `?`, and each other code
691
+ * point counts as one position, except that under `caseFold` a code point
692
+ * counts once for each code point of its case fold.
999
693
  */
1000
- write: {
1001
- /** This is the name of the index that changed. */
1002
- indexName: string;
1003
- };
694
+ wildcard?: string;
1004
695
  /**
1005
- * A worker thread exited unexpectedly. The pool removes the thread and fails
1006
- * the requests that the thread was serving with `WORKER_CRASHED`. The engine
1007
- * then sends each of those queries again on the main thread, so the caller
1008
- * receives a result with no error. The remaining workers keep serving
1009
- * queries, because each of them holds a full worker copy of every promoted
1010
- * index.
696
+ * This matches a pattern field when some part of the value matches the
697
+ * regular expression. `^` and `$` match only at the start and at the end of
698
+ * the whole value.
1011
699
  *
1012
- * After a delay, the engine spawns a replacement and loads every copy onto
1013
- * it before it sends queries to the replacement. Once no worker is left, the
1014
- * main thread serves every query, because it holds every document. The first
1015
- * request after the delay then starts a new pool. The delay starts at one
1016
- * second and doubles up to a minute while replacements keep failing.
700
+ * The engine accepts literal code points, `.`, `\d`, `\w`, and `\s`, sets
701
+ * such as `[a-z]` and `[^0-9]`, groups, and `|`. It also accepts the repeats
702
+ * `*`, `+`, `?`, `{n}`, `{n,}`, and `{n,m}`, the anchors `^` and `$`, the
703
+ * word edge `\b`, and number ranges such as `<1-65535>`. A number range
704
+ * matches the digits of any whole number from its low end to its high end.
705
+ * Write `\` before an ASCII punctuation mark to match the mark itself. The
706
+ * `.` matches any code point, including a line break.
707
+ *
708
+ * The matcher never backtracks, so it checks a value in at most as many
709
+ * steps as the value's code points multiplied by the pattern's positions.
710
+ *
711
+ * The engine throws `SEARCH_INVALID_FILTER` for any construct outside that
712
+ * syntax, such as a back-reference, a lookaround, a lazy repeat, or an inline
713
+ * flag. It throws the same error when the groups of a pattern nest more than
714
+ * 32 deep, when a count is above 2,048, and when a pattern holds more than
715
+ * 2,048 positions. When the operator of an HTTP server sets its `allowRegex`
716
+ * option to false, the server refuses every `regex` test.
1017
717
  */
1018
- workerCrash: {
1019
- /** This is the id of the worker that exited. */
1020
- workerId: number;
1021
- /** These are the indexes that the worker held. */
1022
- indexNames: string[];
1023
- /** This is the error that ended the worker. */
1024
- error: Error;
1025
- };
1026
- /** An index gained worker copies, either because it reached the copy
1027
- * threshold or because a request loaded its copies again after an idle
1028
- * spell. */
1029
- workerPromote: {
1030
- /** This is the number of workers in the pool. */
1031
- workerCount: number;
1032
- /** This is the reason that the index gained its copies, such as the copy
1033
- * threshold that it reached. */
1034
- reason: string;
1035
- };
1036
- /** An index could not gain worker copies, so the main thread keeps serving
1037
- * its queries. */
1038
- workerPromoteFailure: {
1039
- /** This is the reason that the engine tried to load the copies. */
1040
- reason: string;
1041
- /** This is the error that stopped the load. */
1042
- error: Error;
1043
- /** This is true when the engine will try again at a later threshold. */
1044
- retryable: boolean;
1045
- };
1046
- /** An index finished spreading its documents across a new number of
1047
- * partitions. */
1048
- partitionRebalance: {
1049
- /** This is the name of the index that the engine rebalanced. */
1050
- indexName: string;
1051
- /** This is the number of partitions before the rebalance. */
1052
- oldCount: number;
1053
- /** This is the number of partitions after the rebalance. */
1054
- newCount: number;
1055
- };
718
+ regex?: string;
1056
719
  /**
1057
- * An index passed its watermark, so its partitions are close to their
1058
- * capacity. On a cluster node, the engine reports the document count and the
1059
- * capacity of the one partition that `partitionId` identifies, which this
1060
- * node leads.
720
+ * When this is true, the engine compares the case fold of each value of a
721
+ * pattern field with the case fold of the text, so a test for `error`
722
+ * matches `ERROR`. It applies to `eq`, `ne`, `in`, `nin`, `startsWith`,
723
+ * `endsWith`, `contains`, `wildcard`, and `regex`.
724
+ *
725
+ * Under `caseFold`, a set that does not open with `^` can also match a
726
+ * sequence of code points. When a member that the set holds on its own folds
727
+ * to several code points, the set matches that whole fold, so `[ß]` matches
728
+ * `ss`.
1061
729
  */
1062
- partitionWatermark: {
1063
- /** This is the name of the index that crossed the mark. */
1064
- indexName: string;
1065
- /** This is the number of documents in the index, or in the partition on a
1066
- * cluster node. */
1067
- documentCount: number;
1068
- /** This is the number of documents that the current partitions of the
1069
- * index can hold, or that the partition can hold on a cluster node. */
1070
- capacity: number;
1071
- /** This is the number of partitions in the index. */
1072
- partitionCount: number;
1073
- /** On a cluster node, this is the partition that crossed the mark, while
1074
- * outside a cluster the field is absent. */
1075
- partitionId?: number;
1076
- };
730
+ caseFold?: boolean;
1077
731
  /**
1078
- * The process uses nine tenths of its heap, as measured during a write or a
1079
- * load, so the next large index can end the process with an out-of-memory
1080
- * error.
732
+ * This lets the `eq` test of a pattern field match a value within this many
733
+ * edits of the text, so a test for `INV-2O24` with a tolerance of 1 matches
734
+ * `INV-2024`. An edit inserts, deletes, or replaces one code point, so a
735
+ * swap of two neighbouring code points counts as two edits. With `caseFold`,
736
+ * the engine counts the edits between the case folds of the value and the
737
+ * text. The tolerance applies to `eq` alone, so the other tests of the field
738
+ * still compare exactly.
1081
739
  *
1082
- * Where `--max-old-space-size` or `--max-old-space-size-percentage` sets a
1083
- * limit, on the command line or in `NODE_OPTIONS`, the engine measures the
1084
- * used bytes against that limit, which `heapLimit` then reports. Where
1085
- * neither flag sets a limit, the engine measures the share of the heap that
1086
- * V8 reports as no longer available. V8 reports a limit about 192 MB above
1087
- * the true ceiling, so a process on a default heap below about 2 GB can end before
1088
- * this event fires.
740
+ * The engine takes its candidates from the pattern index, so the case fold
741
+ * of the text has to hold enough distinct runs of three code points. For a
742
+ * tolerance of `k`, the engine needs `k × (2 + f) + 1` runs, where `f` is
743
+ * the number of code points in the longest case fold among the text's code
744
+ * points, which is 1 for most text. A tolerance of 1 on `INV-2O24`
745
+ * therefore needs 4 of its 6 runs, while a tolerance of 2 needs 7. Under
746
+ * `'auto'`, the engine uses 2 where the text holds enough runs for 2,
747
+ * otherwise 1 where it holds enough for 1, and otherwise 0.
1089
748
  *
1090
- * The engine emits the event once per crossing, then arms it again once the
1091
- * free share of the heap recovers to two tenths. Raise the limit with
1092
- * `--max-old-space-size-percentage` or `--max-old-space-size`, or close an
1093
- * idle index; see {@link ProcessMemoryReport.heapLimit}.
749
+ * The engine throws `SEARCH_INVALID_FILTER` for a tolerance of 1 or 2 on a
750
+ * text with too few runs, stating how many runs that tolerance needs. It
751
+ * throws the same error for any other tolerance, for a tolerance on a field
752
+ * that is not a pattern field, and for a tolerance in a filter without an
753
+ * `eq` test. Towards the pattern work cap, it counts one unit for each cell
754
+ * that it fills in the table of edit distances between the text and a
755
+ * value.
1094
756
  */
1095
- heapPressure: {
1096
- /** This is the index that a write or a load was touching when the heap
1097
- * reached that point. */
1098
- indexName: string;
1099
- /** This is the heap that the process uses, in bytes. */
1100
- heapUsed: number;
1101
- /** This is the size in bytes that the heap can grow to. */
1102
- heapLimit: number;
1103
- /** This is the estimate of the bytes that the index holds. */
1104
- estimatedMemoryBytes: number;
1105
- };
1106
- /** The engine started, completed, or failed a rebuild that brings the terms
1107
- * of an index up to the current analysis of its language module. */
1108
- analysisRebuild: {
1109
- /** This is the name of the index under rebuild. */
1110
- indexName: string;
1111
- /** This is the stage that the rebuild has reached. */
1112
- status: 'started' | 'completed' | 'failed';
1113
- /** This is the number of partitions that the rebuild has covered so far. */
1114
- partitionsRebuilt: number;
1115
- /** This is the number of partitions that the rebuild covers in total. */
1116
- partitionCount: number;
1117
- /** This is the error that stopped the rebuild, which only a `failed`
1118
- * status includes. */
1119
- error?: Error;
1120
- };
1121
- /** The engine started, completed, or failed the rewrite of an index that you
1122
- * saved with an earlier release. The engine rewrites the index as it
1123
- * recovers it, before it serves the index's first request. Because the
1124
- * engine writes the new manifest last, the earlier files stay intact through
1125
- * a failed rewrite. The engine then starts the rewrite again the next time
1126
- * it recovers the index. Without index lifecycle settings, the engine
1127
- * recovers every index before {@link createNarsil} returns, so pass the
1128
- * listener in the `events` setting of {@link createNarsil}. */
1129
- layoutUpgrade: {
1130
- /** This is the name of the index under rewrite. */
1131
- indexName: string;
1132
- /** This is the stage that the rewrite has reached. */
1133
- status: 'started' | 'completed' | 'failed';
1134
- /** This is `manifest` where the earlier index is a segment manifest with
1135
- * its files, and `bundle` where it is a single snapshot bundle. */
1136
- layout: 'manifest' | 'bundle';
1137
- /** This is the error that stopped the rewrite, which only a `failed`
1138
- * status includes. */
1139
- error?: Error;
1140
- };
1141
- /** A write to the write-ahead log or a checkpoint failed, so the writes since
1142
- * the last checkpoint are at risk. */
1143
- durabilityError: {
1144
- /** This is the error that the durability layer threw. */
1145
- error: Error;
757
+ tolerance?: 0 | 1 | 2 | 'auto';
758
+ };
759
+ /**
760
+ * Tests the contents of a list field, which is a `number[]`, `boolean[]`,
761
+ * `enum[]`, `verbatim[]`, or `string[]` field.
762
+ *
763
+ * The engine throws `SEARCH_INVALID_FILTER` for these tests on any other
764
+ * field, for a value whose type differs from the type of the list's elements,
765
+ * and for `containsAll` or `matchesAny` on a `string[]` field whose type leaves
766
+ * out `pattern`.
767
+ *
768
+ * @public
769
+ */
770
+ type ArrayFilter = {
771
+ /** This matches a list holding every one of the values, at most 65,536 of them, so an empty set of values matches every list. */
772
+ containsAll?: (string | number | boolean)[];
773
+ /** This matches a list holding at least one of the values, at most 65,536 of them. */
774
+ matchesAny?: (string | number | boolean)[];
775
+ /** This compares the number of elements in the list. */
776
+ size?: ComparisonFilter;
777
+ };
778
+ /**
779
+ * Tests whether a field carries a value at all, without looking at what it
780
+ * holds.
781
+ *
782
+ * @public
783
+ */
784
+ type PresenceFilter = {
785
+ /** This matches a document where the field holds a value other than null. */
786
+ exists?: boolean;
787
+ /** This matches a document where the field is absent or null. */
788
+ notExists?: boolean;
789
+ /** This matches a document where the field is absent, null, an empty string, or an empty list. */
790
+ isEmpty?: boolean;
791
+ /** This matches a document where the field holds a value other than an empty string or an empty list. */
792
+ isNotEmpty?: boolean;
793
+ };
794
+ /**
795
+ * Matches a `geopoint` field against a circle drawn on the earth.
796
+ *
797
+ * @public
798
+ */
799
+ type GeoRadiusFilter = {
800
+ /** The engine tests the field against this circle. */
801
+ radius: {
802
+ /** The centre has this latitude, in degrees from -90 to 90. For any other value, the engine throws `SEARCH_INVALID_FILTER`. */
803
+ lat: number;
804
+ /** The centre has this longitude, in degrees from -180 to 180. For any other value, the engine throws `SEARCH_INVALID_FILTER`. */
805
+ lon: number;
806
+ /** The circle has this radius, measured in `unit`. */
807
+ distance: number;
808
+ /**
809
+ * The engine measures `distance` in kilometres under `'km'`, in miles
810
+ * under `'mi'`, and in metres under `'m'`. For any other unit, it throws
811
+ * `SEARCH_INVALID_FILTER`.
812
+ */
813
+ unit: 'km' | 'mi' | 'm';
814
+ /** The engine matches the points inside the circle while this is true, which is the default, and the points outside it while this is false. */
815
+ inside?: boolean;
816
+ /**
817
+ * The engine measures each distance with the Haversine formula on a sphere
818
+ * by default, and with Vincenty's formula on the WGS-84 ellipsoid while
819
+ * this is true. Vincenty's formula iterates, so the engine takes longer
820
+ * to compute each distance. The two formulas differ by less than 0.3% under about
821
+ * 100 km, while across a continent they can differ by up to 0.5%.
822
+ */
823
+ highPrecision?: boolean;
1146
824
  };
1147
- /** The invalidation channel failed, so this instance can serve partitions
1148
- * that another instance has since changed. */
1149
- invalidationError: {
1150
- /** This is the error that the adapter threw. */
1151
- error: Error;
825
+ };
826
+ /**
827
+ * Matches a `geopoint` field against a polygon drawn on the earth.
828
+ *
829
+ * @public
830
+ */
831
+ type GeoPolygonFilter = {
832
+ /** The engine tests the field against this polygon. */
833
+ polygon: {
834
+ /**
835
+ * The engine closes the ring through these corners in the order that you
836
+ * list them, so you can leave the first point off the end. It throws
837
+ * `SEARCH_INVALID_FILTER` for a ring of fewer than three corners, which
838
+ * encloses no area, and for a corner whose latitude is outside -90 to 90
839
+ * or whose longitude is outside -180 to 180. It also throws that error for
840
+ * a ring of more than 65,536 corners. List the corners counter-clockwise
841
+ * around the area, as in an exterior ring of GeoJSON. Where the corners
842
+ * span 180 degrees of longitude or more, the engine matches the area on
843
+ * the left of that path, so a ring listed that way can cross the
844
+ * antimeridian or span more than half the globe.
845
+ */
846
+ points: Array<{
847
+ lat: number;
848
+ lon: number;
849
+ }>;
850
+ /** The engine matches the points inside the polygon while this is true, which is the default, and the points outside it while this is false. */
851
+ inside?: boolean;
1152
852
  };
1153
853
  };
1154
854
  /**
1155
- * This map holds a listener for any event of {@link NarsilEventMap}, so that
1156
- * the engine can register each listener before it starts.
855
+ * Either shape a `geopoint` field is matched against.
1157
856
  *
1158
857
  * @public
1159
858
  */
1160
- type NarsilEventHandlers = {
1161
- [K in keyof NarsilEventMap]?: (payload: NarsilEventMap[K]) => void;
859
+ type GeoFilter = GeoRadiusFilter | GeoPolygonFilter;
860
+ /**
861
+ * The filter one field accepts. Which of these forms applies follows from the
862
+ * field's declared type.
863
+ *
864
+ * @public
865
+ */
866
+ type FieldFilter = ComparisonFilter | StringFilter | ArrayFilter | PresenceFilter | GeoFilter;
867
+ /**
868
+ * The filter that a query runs, built from per-field tests and the boolean
869
+ * operators that combine them.
870
+ *
871
+ * The engine answers every test from an index that it keeps for the field. It
872
+ * applies the filter before scoring, so a narrow filter makes a search
873
+ * cheaper. A filter nests at most 30 levels deep and holds at most 1,024
874
+ * tests, counted across every field and nested expression. Past either limit,
875
+ * the engine throws `SEARCH_INVALID_FILTER`, while it throws
876
+ * `SEARCH_INVALID_FIELD` for a test on a field that the schema leaves out.
877
+ *
878
+ * @public
879
+ */
880
+ type FilterExpression = {
881
+ /** These per-field tests are keyed by field name, and a document has to satisfy every entry. */
882
+ fields?: Record<string, FieldFilter>;
883
+ /** Every nested expression has to match. */
884
+ and?: FilterExpression[];
885
+ /** At least one nested expression has to match. */
886
+ or?: FilterExpression[];
887
+ /** The nested expression has to fail. */
888
+ not?: FilterExpression;
1162
889
  };
1163
890
 
1164
891
  /**
1165
- * What {@link Narsil.query} returns: the ranked hits and everything the query
1166
- * asked for alongside them.
892
+ * Everything {@link Narsil.suggest} accepts.
1167
893
  *
1168
- * @typeParam T - Shape of the stored documents, which flows through to each
1169
- * hit's `document`.
894
+ * @public
895
+ */
896
+ interface SuggestParams {
897
+ /** The returned terms complete this text. */
898
+ prefix: string;
899
+ /** The lookup returns this many completions, most widely used first, and 10 by default. */
900
+ limit?: number;
901
+ }
902
+ /**
903
+ * Everything {@link Narsil.listDocuments} accepts.
904
+ *
905
+ * {@link Narsil.listDocuments} reads the stored documents without ranking them,
906
+ * which is how you page through a whole index. Leave `cursor` out to start at
907
+ * the first document, then pass back the cursor each result carries until it
908
+ * comes back null.
909
+ *
910
+ * A cursor belongs to the sort it was made under, so pass the same `sort` back
911
+ * with it. Changing `sort` invalidates the cursor, and the engine then throws
912
+ * `SEARCH_INVALID_CURSOR` rather than returning a page from the wrong order.
1170
913
  *
1171
914
  * @public
1172
915
  */
1173
- interface QueryResult<T = AnyDocument> {
1174
- /** These documents match, cut to the query's `limit`, best score first or in the query's sort order. */
1175
- hits: Array<Hit<T>>;
916
+ interface ListParams {
1176
917
  /**
1177
- * This many documents match in total, before the engine applies `limit`
1178
- * and `offset`. For a keyword search the engine counts every match. For a
1179
- * vector search it counts every vector that passes the query's filter and
1180
- * its `similarity` floor, which is every vector in the field where the query
1181
- * sets neither of them. The engine also counts each pinned document that
1182
- * the query does not match, since it places that document among the hits.
918
+ * This cursor comes from a previous result, and continues where it stopped.
919
+ * The engine ties a cursor to the sort that produced it, and it throws
920
+ * `SEARCH_INVALID_CURSOR` for a cursor sent back under a different sort.
1183
921
  */
1184
- count: number;
922
+ cursor?: string;
923
+ /** The page carries this many documents, and 10 by default. The engine raises a value below one to one. */
924
+ limit?: number;
925
+ /** This narrows the listing to the documents the filter accepts. */
926
+ filters?: FilterExpression;
1185
927
  /**
1186
- * `count` holds the exact number of matches where this is true, and a
1187
- * number at or below the true total where it is false. Where a query sets a
1188
- * `similarity` floor on a vector field that holds a graph, the engine
1189
- * counts only the vectors that it fetches, because it compares the query
1190
- * with only a fraction of that field's vectors. For a hybrid query the
1191
- * engine fuses two rankings, so the count is exact only where each of those
1192
- * rankings contains every matching document. Where you pin a document from
1193
- * outside the hits that the engine fetches, the engine reports true only
1194
- * where it holds every match of the query, because only then can it test
1195
- * whether the query matches that document.
928
+ * This orders the listing by field value rather than by document id, and the
929
+ * engine applies the fields in the order they are listed. Pass an object
930
+ * keyed by field, or a list of fields in the order they apply. It breaks a
931
+ * tie on document id, and it sorts by at most eight fields. The engine uses
932
+ * document-id order when you leave this out.
933
+ *
934
+ * The engine reads every document the listing covers to build a sorted page,
935
+ * so a sorted listing costs more than the default order on a large index.
1196
936
  */
1197
- countExact: boolean;
1198
- /** The engine spent this many milliseconds on the search. */
1199
- elapsed: number;
1200
- /** This opaque cursor reaches the next page. Pass it back as `searchAfter`. */
1201
- cursor?: string;
1202
- /** These facet counts are keyed by the field each facet was asked for. */
1203
- facets?: Record<string, FacetResult>;
1204
- /** These groups arrive when the query asked for grouping. */
1205
- groups?: GroupResult[];
1206
- /** This turns true when the index's terms came from an older analysis than its language module produces now. */
1207
- analysisStale?: boolean;
1208
- /** The search read this much of the index, which is how you spot a degraded answer. */
1209
- coverage: QueryCoverage;
937
+ sort?: SortSpec;
938
+ /** This chooses how much of each stored document comes back, and the whole document by default. */
939
+ document?: DocumentProjection;
1210
940
  }
941
+
1211
942
  /**
1212
- * How much of an index one search read, which is what you check before you
1213
- * trust a count or a ranking.
1214
- *
1215
- * An embedded engine reads every partition it holds, so `queriedPartitions`
1216
- * matches `totalPartitions` there and the other two stay zero. A search across
1217
- * a cluster may find a node slow or unreachable, which it counts here while
1218
- * still returning the hits the other nodes gave it.
943
+ * Which engine answers a query: keyword matching, vector similarity, or both
944
+ * merged into one ranking.
1219
945
  *
1220
946
  * @public
1221
947
  */
1222
- interface QueryCoverage {
1223
- /** The search should have read this many partitions. */
1224
- totalPartitions: number;
1225
- /** The search read this many of them. */
1226
- queriedPartitions: number;
1227
- /** The search counts a partition here when the node holding it took longer than the query allowed. */
1228
- timedOutPartitions: number;
1229
- /** The search counts a partition here when the node holding it returned an error, and when no active replica served it. */
1230
- failedPartitions: number;
1231
- }
948
+ type SearchMode = 'fulltext' | 'vector' | 'hybrid';
1232
949
  /**
1233
- * One matching document, with the score that ranked it.
1234
- *
1235
- * @typeParam T - Shape of the stored document.
950
+ * How many of a query's terms a document has to carry. `all` demands every
951
+ * term, `any` accepts one, and a number demands that many.
1236
952
  *
1237
953
  * @public
1238
954
  */
1239
- interface Hit<T = AnyDocument> {
1240
- /** The document is stored under this id. */
1241
- id: string;
1242
- /**
1243
- * This score ranked the hit. Scores compare within one result set, never
1244
- * across searches. A sorted query ranks by sort values instead and carries
1245
- * no score unless it sets `includeScores`.
1246
- */
1247
- score?: number;
1248
- /** This is the stored document. */
1249
- document: T;
1250
- /** These are the parts the score was built from, which arrive when the query asked for them. */
1251
- scoreComponents?: ScoreComponents;
1252
- /** These highlighted snippets are keyed by field, and arrive when the query asked for highlighting. */
1253
- highlights?: Record<string, HighlightMatch>;
1254
- }
955
+ type TermMatchPolicy = 'all' | 'any' | number;
1255
956
  /**
1256
- * The numbers BM25 combined into one hit's score, which is what you read when
1257
- * a ranking surprises you.
957
+ * One field of a sort, and the direction that field orders by.
1258
958
  *
1259
959
  * @public
1260
960
  */
1261
- interface ScoreComponents {
961
+ interface SortField {
962
+ /** The field the engine reads, which may name a nested field with dots. */
963
+ field: string;
964
+ /** Ascending or descending order for this field. */
965
+ direction: 'asc' | 'desc';
1262
966
  /**
1263
- * Each query term appears in one field of this document this many times,
1264
- * under a key of `field:term`. A term that appears in two fields therefore
1265
- * has two entries here, while the keys of {@link ScoreComponents.idf} hold
1266
- * the bare term.
967
+ * Where a document's field holds a list, the engine sorts that document by
968
+ * one value from the list: the smallest under `'min'`, the largest under
969
+ * `'max'`, and the mean or the median of the list's numbers under `'avg'`
970
+ * or `'median'`. Where you leave this out, the engine uses `'min'` for an
971
+ * ascending sort and `'max'` for a descending one. It sorts by a field that
972
+ * holds a single value as that value stands, under every mode. It throws
973
+ * `SEARCH_INVALID_FIELD` for `'avg'` or `'median'` on a field that the
974
+ * schema declares as anything other than `number` or `number[]`.
1267
975
  */
1268
- termFrequencies: Record<string, number>;
1269
- /** Each field the query searched holds this many tokens, keyed by field. */
1270
- fieldLengths: Record<string, number>;
1271
- /** Each query term carries this inverse document frequency, which is what makes a rare term count for more. */
1272
- idf: Record<string, number>;
976
+ mode?: 'min' | 'max' | 'avg' | 'median';
1273
977
  }
1274
978
  /**
1275
- * A highlighted field, ready to render.
979
+ * A sort, either as an object keyed by field or as a list of fields in the
980
+ * order they apply.
981
+ *
982
+ * Both forms order by the first field, break a tie on the second, and carry on
983
+ * that way. Prefer the list where the order of the fields matters, because
984
+ * JavaScript moves an all-digit key such as `2024` to the front of an object
985
+ * and the list keeps the order you wrote.
1276
986
  *
1277
987
  * @public
1278
988
  */
1279
- interface HighlightMatch {
1280
- /** This is the field's text around the match, wrapped in the query's tags. */
1281
- snippet: string;
1282
- /**
1283
- * Each range gives the start and the end of one match in the original field,
1284
- * so you can render the highlight yourself. Where the snippet covers part of
1285
- * the field alone, the engine lists only the matches that the snippet
1286
- * displays. Every offset is a character count from the start of the original
1287
- * field, whatever the snippet contains.
1288
- */
1289
- positions: Array<{
1290
- start: number;
1291
- end: number;
1292
- }>;
1293
- }
989
+ type SortSpec = Record<string, 'asc' | 'desc'> | readonly SortField[];
1294
990
  /**
1295
- * Counts for one faceted field.
991
+ * Everything {@link Narsil.query} accepts.
992
+ *
993
+ * Set `term` for keyword search, `vector` for similarity search, and `mode`
994
+ * when you want both. The engine matches nothing for a query carrying neither
995
+ * of them, so page through an index with {@link Narsil.listDocuments}
996
+ * instead.
1296
997
  *
1297
998
  * @public
1298
999
  */
1299
- interface FacetResult {
1300
- /** This many documents match per value, keyed by value. */
1301
- values: Record<string, number>;
1302
- /** This is the number of entries in `values`, which is at most the facet's `limit`. */
1303
- count: number;
1000
+ interface QueryParams {
1001
+ /** The engine analyses this text with the index's language module and searches for the terms that result. */
1002
+ term?: string;
1003
+ /** The engine searches the term in these fields, and in every text field in the schema by default. */
1004
+ fields?: string[];
1005
+ /**
1006
+ * The engine scores only the documents that pass this filter. It throws
1007
+ * `SEARCH_INVALID_FILTER` for an operand of the wrong shape, and for an
1008
+ * operator on a field of another type, such as `startsWith` on a number
1009
+ * field.
1010
+ */
1011
+ filters?: FilterExpression;
1012
+ /**
1013
+ * The engine multiplies the score from each named field by its weight. It
1014
+ * throws `SEARCH_INVALID_FIELD` for any field other than a text field that
1015
+ * the schema declares, and `CONFIG_INVALID` for a weight that is not a
1016
+ * finite number.
1017
+ */
1018
+ boost?: Record<string, number>;
1019
+ /** The engine gathers term statistics this way, and follows the index's `defaultScoring` where the query sets none. */
1020
+ scoring?: ScoringMode;
1021
+ /**
1022
+ * The engine drops any hit scoring below this value. It ranks with BM25,
1023
+ * which has no fixed upper bound, so a floor that suits one index and one
1024
+ * query can reject every hit in another.
1025
+ */
1026
+ minScore?: number;
1027
+ /**
1028
+ * The engine keeps a document only where the document matches this many
1029
+ * query terms, under the same `tolerance` and `prefixLength` that the search
1030
+ * uses. One term is enough by default.
1031
+ */
1032
+ termMatch?: TermMatchPolicy;
1033
+ /**
1034
+ * The engine matches an indexed term within this edit distance of a query
1035
+ * term, so it finds a document for a query with a typo. It counts each
1036
+ * Unicode code point as one character. Set an integer from 0 to 10.
1037
+ */
1038
+ tolerance?: number;
1039
+ /**
1040
+ * The engine applies `tolerance` only to the indexed terms that share this
1041
+ * many leading characters with the query term, or to the terms that start
1042
+ * with the whole query term when the query term is shorter. Set an integer
1043
+ * from 0 to 1,024; the default is 2.
1044
+ */
1045
+ prefixLength?: number;
1046
+ /**
1047
+ * With this set, the engine treats the last query term as an unfinished
1048
+ * word, so `secur` matches `security`. The engine matches that last term by
1049
+ * its stem or by completing it, while `tolerance` applies only to the earlier
1050
+ * terms, which have to match whole. The engine scores completions against a
1051
+ * shared document frequency. It also ranks them below whole-word matches.
1052
+ * The engine ignores this setting where `exact` is true, and the setting is
1053
+ * false by default.
1054
+ */
1055
+ prefix?: boolean;
1056
+ /**
1057
+ * With this set, the engine also matches each query word of three or more
1058
+ * characters inside the longer words of every field whose type includes
1059
+ * `partial`, so a search for `proof` matches a document with `waterproof`
1060
+ * in such a field. The engine counts each Unicode code point as one
1061
+ * character. It looks for the query word, before stemming, inside each word
1062
+ * exactly as that word appears in a document.
1063
+ *
1064
+ * The engine adds at most 50 such words to a query, which it divides as
1065
+ * evenly as it can among the query words. Within the share of each query
1066
+ * word, it adds first the words that the most documents contain. It scores
1067
+ * a match inside a longer word in proportion to the part of that word that
1068
+ * the query word makes up, so it scores such a match below a whole-word
1069
+ * match at the same frequency in a field of the same length. With
1070
+ * `highlight`, it tags each whole word that contains a query word in a
1071
+ * searched `partial` field.
1072
+ *
1073
+ * The engine applies no `tolerance` to these matches. It ignores this
1074
+ * setting where `exact` is true or where the searched fields include no
1075
+ * `partial` field. Where the setting is absent, the engine treats it as
1076
+ * false, while it throws `CONFIG_INVALID` for any value other than `true`
1077
+ * or `false`.
1078
+ */
1079
+ partialWords?: boolean;
1080
+ /**
1081
+ * With this set, the engine matches each query term only against an equal
1082
+ * indexed term, so it turns off fuzzy matching, prefix completion, and
1083
+ * partial-word matching. The engine still stems the query, because the
1084
+ * index stores stemmed terms, so a search for `running` matches a document
1085
+ * that contains `runs` through the stem that both words share.
1086
+ */
1087
+ exact?: boolean;
1088
+ /**
1089
+ * The engine counts the values of these fields across the matching
1090
+ * documents, and each entry sets how it cuts and sorts that field's counts.
1091
+ * For a field outside the schema, it counts the values that the documents
1092
+ * store. It throws `SEARCH_INVALID_FIELD` for a `geopoint` or a vector
1093
+ * field.
1094
+ */
1095
+ facets?: FacetConfig;
1096
+ /**
1097
+ * The engine sorts the hits by the values of these fields, in place of the
1098
+ * relevance ranking. Pass an object keyed by field, or a list of fields in
1099
+ * the order that the engine compares them. The engine sorts by a `number`,
1100
+ * `boolean`, or `enum` field, by a text field whose type includes
1101
+ * `sortable`, or by a list of any of these, which it reduces to one value by
1102
+ * the entry's `mode`. It throws `SEARCH_INVALID_FIELD` for a sort on a
1103
+ * `geopoint` or a vector field, because neither type has an order. It throws
1104
+ * the same code for a sort on any other text field, since the engine keeps
1105
+ * up to the first 512 code points of every document's value in memory to
1106
+ * sort by a text field. The engine orders hybrid results by fusion, so it
1107
+ * throws `SEARCH_INVALID_MODE` for a sort on a hybrid query. It also throws
1108
+ * that code for a direction other than `asc` and `desc`.
1109
+ */
1110
+ sort?: SortSpec;
1111
+ /** These settings collapse the hits into groups by field value. */
1112
+ group?: GroupConfig;
1113
+ /**
1114
+ * The query returns this many hits, and 10 by default. Pass 0 to read the
1115
+ * match count with no hits. The engine reads a value below 0 as 0. It falls
1116
+ * back to the default for `NaN` and for an infinite value, so a page size
1117
+ * that you compute from user input never fails the query.
1118
+ */
1119
+ limit?: number;
1120
+ /** The query skips this many hits before returning. A deep offset costs more than a cursor. */
1121
+ offset?: number;
1122
+ /** This cursor comes from a previous result's `cursor`, and pages without an offset's cost. */
1123
+ searchAfter?: string;
1124
+ /** These settings name the fields that come back with highlighted snippets. */
1125
+ highlight?: HighlightConfig;
1126
+ /** These documents take fixed positions, ahead of the ranking. */
1127
+ pinned?: Array<{
1128
+ docId: string;
1129
+ position: number;
1130
+ }>;
1131
+ /** This picks which engine answers the query. Keyword search runs by default. */
1132
+ mode?: SearchMode;
1133
+ /** These vector-search inputs are required in `vector` and `hybrid` mode. */
1134
+ vector?: VectorQueryConfig;
1135
+ /** These settings control how the keyword and vector rankings merge in `hybrid` mode. */
1136
+ hybrid?: HybridConfig;
1304
1137
  /**
1305
- * Every count in `values` is at most this far below its true count. A value
1306
- * that the engine leaves out of `values` because of `limit` has a true
1307
- * count of at most this figure too. Where the engine counts a field on one
1308
- * thread, it counts every value exactly, so this figure is the largest
1309
- * count that it leaves out. Where it splits the count across worker copies
1310
- * or cluster nodes, each of them returns only its own top values, so the
1311
- * merged count of a value that is common overall but rare on one of them
1312
- * can lack the matches on that one. A bound of 0 means that `values` holds
1313
- * every matching value, each with its exact count.
1138
+ * Setting this returns relevance scores on a sorted query. A query that
1139
+ * names a sort ranks by sort values alone and computes no scores, so its
1140
+ * hits carry none until this restores them. A query without a sort ignores
1141
+ * this and always carries scores.
1314
1142
  */
1315
- errorBound: number;
1143
+ includeScores?: boolean;
1144
+ /** Setting this returns the numbers behind each hit's score, which is what you read when a ranking surprises you. */
1145
+ includeScoreComponents?: boolean;
1146
+ /** This chooses how much of each stored document comes back, and the whole document by default. */
1147
+ document?: DocumentProjection;
1316
1148
  }
1317
1149
  /**
1318
- * One group of hits, produced by a query that grouped its results.
1150
+ * How much of a stored document each hit carries back.
1319
1151
  *
1320
- * @public
1321
- */
1322
- interface GroupResult {
1323
- /** Each grouping field holds this value for the group, keyed by field. */
1324
- values: Record<string, unknown>;
1325
- /** These hits fall in the group, cut to the query's `maxPerGroup`. */
1326
- hits: Array<Hit>;
1327
- /** The query's reducer produced this value for the group, and only a query that set `group.reduce` carries it. */
1328
- reduced?: unknown;
1329
- /** The reducer threw, and this holds its message, so the group carries its hits and no `reduced` value. */
1330
- reducerError?: string;
1331
- }
1332
- /**
1333
- * What {@link Narsil.preflight} returns: how many documents a query matches,
1334
- * without building or ranking a single hit.
1152
+ * Pass `false` when the ids and scores are all you need, and every hit's
1153
+ * `document` is then an empty object. Pass `include` to keep named fields
1154
+ * alone, or `exclude` to drop named fields and keep the rest; naming both
1155
+ * keeps the included fields and then drops the excluded ones from those. Use
1156
+ * dots to name a nested field, so `author.name` addresses the `name` inside
1157
+ * `author`, and a name that matches no field changes nothing.
1335
1158
  *
1336
- * @public
1337
- */
1338
- interface PreflightResult {
1339
- /** The query matches this many documents. */
1340
- count: number;
1341
- /** `count` holds the exact number of matches where this is true, and a number at or below the true total where it is false, under the rule in {@link QueryResult.countExact}. */
1342
- countExact: boolean;
1343
- /** The count took this many milliseconds. */
1344
- elapsed: number;
1345
- /** This turns true when the index's terms came from an older analysis than its language module produces now. */
1346
- analysisStale?: boolean;
1347
- }
1348
- /**
1349
- * What a batch write returns. One bad document never abandons the rest, so
1350
- * read both lists.
1159
+ * Drop a vector field on a similarity search, because the engine otherwise
1160
+ * reads every hit's vector back out of the index and writes it into the
1161
+ * response.
1351
1162
  *
1352
1163
  * @public
1353
1164
  */
1354
- interface BatchResult {
1355
- /** The engine wrote the documents under these ids. */
1356
- succeeded: string[];
1357
- /** The engine rejected each of these documents, and each entry carries the error that rejected it. */
1358
- failed: Array<{
1359
- docId: string;
1360
- error: NarsilError;
1361
- }>;
1362
- }
1165
+ type DocumentProjection = boolean | {
1166
+ /** Names the fields to keep, so every field left out of this list is dropped. */
1167
+ include?: string[];
1168
+ /** Names the fields to drop, so every other field is kept. */
1169
+ exclude?: string[];
1170
+ };
1363
1171
  /**
1364
- * What {@link Narsil.importDocumentExport} returns. The engine continues past each
1365
- * refused line, so read the refusals to learn which documents it skipped.
1172
+ * Vector-search inputs passed under `QueryParams.vector`.
1173
+ *
1174
+ * Supply either a raw `value` array or a `text` string for auto-embedding;
1175
+ * passing both throws `EMBEDDING_CONFIG_INVALID`. Result count is governed
1176
+ * by the outer query's `limit`, not by any field on this object.
1366
1177
  *
1367
1178
  * @public
1368
1179
  */
1369
- interface DocumentImportResult {
1370
- /** The engine wrote this many documents, counting each one that it replaced. */
1371
- imported: number;
1372
- /** The engine refused this many lines in total. */
1373
- refusedCount: number;
1374
- /** These are the 1,000 refusals with the lowest line numbers. Each entry contains the line number, where the header is line 1, along with the error code and a message. */
1375
- refused: Array<{
1376
- line: number;
1377
- code: NarsilErrorCode;
1378
- message: string;
1379
- }>;
1180
+ interface VectorQueryConfig {
1181
+ /**
1182
+ * Name of the schema field that holds the vector to compare against.
1183
+ * Must reference a field declared as `vector[N]` in the index schema.
1184
+ */
1185
+ field: string;
1186
+ /**
1187
+ * Raw query vector, given as a number array or a `Float32Array`. Length
1188
+ * must match the indexed field's dimension or the search rejects the
1189
+ * request with `VECTOR_DIMENSION_MISMATCH`.
1190
+ */
1191
+ value?: number[] | Float32Array;
1192
+ /**
1193
+ * Text to embed at query time using the index or instance embedding
1194
+ * adapter. Mutually exclusive with `value`; requires a configured adapter.
1195
+ */
1196
+ text?: string;
1197
+ /**
1198
+ * Score floor applied during ranking. Hits scoring below this value
1199
+ * are dropped before `limit` is enforced, so the returned hit count
1200
+ * can be smaller than `limit` even when more documents exist. The
1201
+ * floor is interpreted in score space for every metric; for
1202
+ * `euclidean`, distance is mapped to a similarity score of
1203
+ * `1 / (1 + distance)` first. Defaults to no floor.
1204
+ */
1205
+ similarity?: number;
1206
+ /**
1207
+ * Similarity metric used for ranking. Defaults to `cosine`. Choose
1208
+ * `dotProduct` for raw inner-product scoring on already-normalised
1209
+ * vectors and `euclidean` for distance-based ordering.
1210
+ */
1211
+ metric?: 'cosine' | 'dotProduct' | 'euclidean';
1212
+ /**
1213
+ * HNSW exploration factor for approximate search. Higher values raise
1214
+ * recall at the cost of latency. Ignored while the field is still
1215
+ * served by the brute-force backend. Defaults to the engine's built-in
1216
+ * value when omitted.
1217
+ */
1218
+ efSearch?: number;
1219
+ /**
1220
+ * How many times `limit` a quantized field re-scores against its
1221
+ * full-precision vectors before it returns the best `limit`. A value below
1222
+ * 1 or one that is not a finite number fails with `CONFIG_INVALID`. The
1223
+ * engine ignores this on a field whose quantization is `none`. When a query
1224
+ * omits it, the engine takes 3 for `osq1` and `osq2`, 2 for `osq8`, and 2
1225
+ * for `osq4` at 1,024 dimensions and above, but 5 for `osq4` below 1,024,
1226
+ * where a four-bit code ranks the true neighbours less reliably.
1227
+ */
1228
+ oversample?: number;
1380
1229
  }
1381
1230
  /**
1382
- * What {@link Narsil.getStats} returns about one index.
1231
+ * How a hybrid query merges its keyword ranking with its vector ranking.
1232
+ *
1233
+ * `rrf` combines the two by rank alone, which needs no tuning and handles
1234
+ * scores that live on different scales. `linear` blends the scores directly,
1235
+ * which gives you control once you know what each side's scores look like.
1383
1236
  *
1384
1237
  * @public
1385
1238
  */
1386
- interface IndexStats {
1387
- /** The index holds this many documents. A closed index reports its count as of the last checkpoint. */
1388
- documentCount: number;
1389
- /** The index is spread across this many partitions. */
1390
- partitionCount: number;
1391
- /**
1392
- * Formula-based estimate of the index's main-thread memory footprint, summed
1393
- * across every partition and vector index for this index. Computed from
1394
- * structural counters (document count, posting counts, field-index sizes),
1395
- * not measured. Per-object V8 overhead (hidden classes, map transitions,
1396
- * GC headers) is not captured here, so this number routinely undershoots
1397
- * the real heap by a meaningful factor. Use {@link Narsil.getMemoryStats}
1398
- * when sizing host memory.
1399
- */
1400
- estimatedMemoryBytes: number;
1401
- /** The index analyses text with this language module. */
1402
- language: string;
1403
- /** The index was created with this field layout. */
1404
- schema: SchemaDefinition;
1239
+ interface HybridConfig {
1240
+ /** The engine merges the rankings this way, and by rank fusion by default. It throws `CONFIG_INVALID` for any other value. */
1241
+ strategy?: 'rrf' | 'linear';
1242
+ /** The engine uses this rank-fusion constant under `rrf` alone, where a larger value reduces the lead of the top ranks. Set a whole number of at least 1, or leave it out for 60. The engine throws `CONFIG_INVALID` for any other value. */
1243
+ k?: number;
1244
+ /** The engine uses this weight of the vector score, from 0 to 1, under `linear` alone, and 0.5 where you leave it out. It throws `CONFIG_INVALID` for a value outside that range. */
1245
+ alpha?: number;
1405
1246
  }
1406
1247
  /**
1407
- * A summary of one index, as {@link Narsil.listIndexes} reports it.
1248
+ * Fields a query counts values for, keyed by field name.
1408
1249
  *
1409
1250
  * @public
1410
1251
  */
1411
- interface IndexInfo {
1412
- /** The index was created under this name. */
1413
- name: string;
1414
- /** The index holds this many documents. A closed index reports its count as of the last checkpoint. */
1415
- documentCount: number;
1416
- /** The index is spread across this many partitions. */
1417
- partitionCount: number;
1418
- /** The index analyses text with this language module. */
1419
- language: string;
1420
- /** This turns true when the index's terms came from an older analysis than its language module produces now. */
1421
- analysisStale?: boolean;
1422
- /** This is `open` in memory, `closed` after release, and `reopen-failed` after five recovery failures. */
1423
- state: 'open' | 'closed' | 'reopen-failed';
1424
- /** This counts successful loads since this engine started. */
1425
- reopenCount: number;
1252
+ interface FacetConfig {
1253
+ /** Each key names a field the query counts values for. */
1254
+ [field: string]: {
1255
+ /** The engine returns this many values for the field, in the order of `sort`. An engine returns every value where you leave this out, while a cluster returns 10, or every range of a field that sets `ranges`. */
1256
+ limit?: number;
1257
+ /** The engine orders the returned values by their count, putting the highest first under `'desc'`, which is the default, and the lowest first under `'asc'`. Under `'asc'`, each cluster node sends the count of up to 10,000 values of the field, so the lowest counts are exact wherever no node holds more values than that. */
1258
+ sort?: 'asc' | 'desc';
1259
+ /** The engine counts a numeric field's matches into these ranges, with one count for each range. A cluster search counts up to 1,000 ranges on a field and throws `CONFIG_INVALID` for more. */
1260
+ ranges?: Array<{
1261
+ from: number;
1262
+ to: number;
1263
+ }>;
1264
+ };
1426
1265
  }
1427
1266
  /**
1428
- * What {@link Narsil.getPartitionStats} reports for one partition, which is
1429
- * where you look when an index grows unevenly.
1267
+ * How a query collapses its hits into groups.
1430
1268
  *
1431
1269
  * @public
1432
1270
  */
1433
- interface PartitionStatsResult {
1434
- /** This identifies the partition within its index. */
1435
- partitionId: number;
1436
- /** The partition holds this many documents. */
1437
- documentCount: number;
1271
+ interface GroupConfig {
1272
+ /** The values of these fields define a group, and several fields group by their combination. */
1273
+ fields: string[];
1274
+ /** The engine returns this many hits from each group, best first, and one hit where you leave this out. */
1275
+ maxPerGroup?: number;
1276
+ /** The engine returns this many groups, best first, and every group where you leave this out. */
1277
+ limit?: number;
1438
1278
  /**
1439
- * Formula-based estimate of this partition's memory footprint. V8 has no
1440
- * per-object heap accounting API, so this number is derived from structural
1441
- * counters (document count, posting counts, field-index sizes) and does not
1442
- * include per-object overhead. Treat as an estimate, not a measurement.
1279
+ * The engine folds every hit of each group into one value, such as a sum or
1280
+ * an average, including the hits beyond `maxPerGroup`. In cluster mode the
1281
+ * coordinator fetches up to 10,000 hits of each group to fold.
1443
1282
  */
1444
- estimatedMemoryBytes: number;
1283
+ reduce?: GroupReducer;
1445
1284
  }
1446
1285
  /**
1447
- * What {@link Narsil.suggest} returns: the indexed terms that complete a
1448
- * prefix, ready to offer as you-type suggestions.
1286
+ * Folds the hits of one group into a single value.
1449
1287
  *
1450
1288
  * @public
1451
1289
  */
1452
- interface SuggestResult {
1453
- /** These completions run most widely used first. */
1454
- terms: Array<{
1455
- /** This is the completed term, as the index holds it. */
1456
- term: string;
1457
- /** The term appears in this many documents, which is what ordered the list. */
1458
- documentFrequency: number;
1459
- }>;
1460
- /** The lookup took this many milliseconds. */
1461
- elapsed: number;
1462
- /** This turns true when the index's terms came from an older analysis than its language module produces now. */
1463
- analysisStale?: boolean;
1464
- }
1290
+ type GroupReducer = {
1291
+ /**
1292
+ * Folds one hit into the running value.
1293
+ *
1294
+ * @param accumulator - What the previous call returned, or what
1295
+ * `initialValue` produced for the first hit.
1296
+ * @param doc - The hit's stored document.
1297
+ * @param score - The hit's relevance score.
1298
+ * @returns The new running value.
1299
+ */
1300
+ reducer: (accumulator: unknown, doc: AnyDocument, score: number) => unknown;
1301
+ /** Produces the starting value for each group. The engine calls it once per group. */
1302
+ initialValue: () => unknown;
1303
+ };
1465
1304
  /**
1466
- * The state of one vector field, and what maintenance would cost, as
1467
- * {@link Narsil.vectorMaintenanceStatus} reports it.
1305
+ * This configuration names the fields that receive highlighted snippets. It
1306
+ * also sets how the engine marks those snippets up.
1468
1307
  *
1469
- * Removing a vector leaves a tombstone in the graph, and enough of them slow a
1470
- * search down. Read this to decide when compaction earns its cost.
1308
+ * The engine analyses the text of each returned field again to tag every word
1309
+ * that it matched, so it tags the same words whatever the index's
1310
+ * `trackPositions` setting is. It tags a word whose stem equals a query stem,
1311
+ * and a word within the query's `tolerance` of a query stem. For a `prefix`
1312
+ * query, it tags a word for the last query term only when that word completes
1313
+ * the term or shares its stem.
1471
1314
  *
1472
1315
  * @public
1473
1316
  */
1474
- interface VectorMaintenanceResult {
1475
- /** This describes the named vector field. */
1476
- fieldName: string;
1317
+ interface HighlightConfig {
1318
+ /** The engine highlights these fields. */
1319
+ fields: string[];
1320
+ /** The engine writes this before each match, and writes `<mark>` by default. */
1321
+ preTag?: string;
1322
+ /** The engine writes this after each match, and writes `</mark>` by default. */
1323
+ postTag?: string;
1477
1324
  /**
1478
- * Tombstones make up this share of the graph's nodes, from 0 to 1. Before
1479
- * the first build, where {@link VectorMaintenanceResult.graphCount} reads 0,
1480
- * the engine divides by the number of stored vectors, because no graph
1481
- * exists yet.
1325
+ * The engine takes this many characters of the field around the densest run
1326
+ * of matches, 200 by default. It returns a snippet longer than that number,
1327
+ * because it then adds the opening and closing tags, and an ellipsis at each
1328
+ * end where it cuts the field.
1482
1329
  */
1483
- tombstoneRatio: number;
1484
- /** The field holds this many HNSW graphs: 0 before the first build and 1 once a graph exists. */
1485
- graphCount: number;
1486
- /** This many vectors wait outside the graph, which a search scans one by one. */
1487
- bufferSize: number;
1488
- /** This stays true while a graph build runs. */
1489
- building: boolean;
1490
- /** {@link Narsil.compactVectors} would take about this many milliseconds. */
1491
- estimatedCompactMs: number;
1492
- /** {@link Narsil.optimizeVectors} would take about this many milliseconds. */
1493
- estimatedOptimizeMs: number;
1330
+ maxSnippetLength?: number;
1494
1331
  }
1332
+
1495
1333
  /**
1496
- * One stored document, as {@link Narsil.listDocuments} returns it.
1334
+ * This map lists every event that the engine emits, with the payload of each
1335
+ * one.
1497
1336
  *
1498
- * @typeParam T - Shape of the stored document.
1337
+ * {@link Narsil.on} registers a listener under a key from this map, so that the
1338
+ * engine can pass the matching payload to that listener. Most of these events
1339
+ * report work that the engine does in the background, away from the call that
1340
+ * started it, so a failure that such an event reports never rejects a promise
1341
+ * that you are holding.
1499
1342
  *
1500
1343
  * @public
1501
1344
  */
1502
- interface ListedDocument<T = AnyDocument> {
1503
- /** The document is stored under this id. */
1504
- id: string;
1505
- /** This holds the stored document, cut down to what the projection kept. */
1506
- document: T;
1507
- }
1345
+ type NarsilEventMap = {
1346
+ /**
1347
+ * The engine emits this event after a call changes what a read returns from
1348
+ * an index. The calls are the inserts, updates, and removals, singly or in a
1349
+ * batch, together with `clear`, `restore`, `rebalance`, `rebuildAnalysis`,
1350
+ * `compactVectors`, `optimizeVectors`, `createIndex`, and `dropIndex`. The
1351
+ * engine emits the event after a call that throws as well, because a call can
1352
+ * change the index before it throws. It also emits the event after it reloads
1353
+ * an index, once a shared invalidation adapter reports that another instance
1354
+ * saved that index. The engine emits one event per batch, however many
1355
+ * documents the batch holds.
1356
+ *
1357
+ * The engine emits the event once a query can see the change, which means
1358
+ * after every worker copy applies the change and after any rebalance in
1359
+ * progress replays it. A query that a listener sends from its handler
1360
+ * therefore returns results that include the change. The engine waits for the
1361
+ * change to become visible only while a listener is registered for the event.
1362
+ */
1363
+ write: {
1364
+ /** This is the name of the index that changed. */
1365
+ indexName: string;
1366
+ };
1367
+ /**
1368
+ * A worker thread exited unexpectedly. The pool removes the thread and fails
1369
+ * the requests that the thread was serving with `WORKER_CRASHED`. The engine
1370
+ * then sends each of those queries again on the main thread, so the caller
1371
+ * receives a result with no error. The remaining workers keep serving
1372
+ * queries, because each of them holds a full worker copy of every promoted
1373
+ * index.
1374
+ *
1375
+ * After a delay, the engine spawns a replacement and loads every copy onto
1376
+ * it before it sends queries to the replacement. Once no worker is left, the
1377
+ * main thread serves every query, because it holds every document. The first
1378
+ * request after the delay then starts a new pool. The delay starts at one
1379
+ * second and doubles up to a minute while replacements keep failing.
1380
+ */
1381
+ workerCrash: {
1382
+ /** This is the id of the worker that exited. */
1383
+ workerId: number;
1384
+ /** These are the indexes that the worker held. */
1385
+ indexNames: string[];
1386
+ /** This is the error that ended the worker. */
1387
+ error: Error;
1388
+ };
1389
+ /** An index gained worker copies, either because it reached the copy
1390
+ * threshold or because a request loaded its copies again after an idle
1391
+ * spell. */
1392
+ workerPromote: {
1393
+ /** This is the number of workers in the pool. */
1394
+ workerCount: number;
1395
+ /** This is the reason that the index gained its copies, such as the copy
1396
+ * threshold that it reached. */
1397
+ reason: string;
1398
+ };
1399
+ /** An index could not gain worker copies, so the main thread keeps serving
1400
+ * its queries. */
1401
+ workerPromoteFailure: {
1402
+ /** This is the reason that the engine tried to load the copies. */
1403
+ reason: string;
1404
+ /** This is the error that stopped the load. */
1405
+ error: Error;
1406
+ /** This is true when the engine will try again at a later threshold. */
1407
+ retryable: boolean;
1408
+ };
1409
+ /** An index finished spreading its documents across a new number of
1410
+ * partitions. */
1411
+ partitionRebalance: {
1412
+ /** This is the name of the index that the engine rebalanced. */
1413
+ indexName: string;
1414
+ /** This is the number of partitions before the rebalance. */
1415
+ oldCount: number;
1416
+ /** This is the number of partitions after the rebalance. */
1417
+ newCount: number;
1418
+ };
1419
+ /**
1420
+ * An index passed its watermark, so its partitions are close to their
1421
+ * capacity. On a cluster node, the engine reports the document count and the
1422
+ * capacity of the one partition that `partitionId` identifies, which this
1423
+ * node leads.
1424
+ */
1425
+ partitionWatermark: {
1426
+ /** This is the name of the index that crossed the mark. */
1427
+ indexName: string;
1428
+ /** This is the number of documents in the index, or in the partition on a
1429
+ * cluster node. */
1430
+ documentCount: number;
1431
+ /** This is the number of documents that the current partitions of the
1432
+ * index can hold, or that the partition can hold on a cluster node. */
1433
+ capacity: number;
1434
+ /** This is the number of partitions in the index. */
1435
+ partitionCount: number;
1436
+ /** On a cluster node, this is the partition that crossed the mark, while
1437
+ * outside a cluster the field is absent. */
1438
+ partitionId?: number;
1439
+ };
1440
+ /**
1441
+ * The process uses nine tenths of its heap, as measured during a write or a
1442
+ * load, so the next large index can end the process with an out-of-memory
1443
+ * error.
1444
+ *
1445
+ * Where `--max-old-space-size` or `--max-old-space-size-percentage` sets a
1446
+ * limit, on the command line or in `NODE_OPTIONS`, the engine measures the
1447
+ * used bytes against that limit, which `heapLimit` then reports. Where
1448
+ * neither flag sets a limit, the engine measures the share of the heap that
1449
+ * V8 reports as no longer available. V8 reports a limit about 192 MB above
1450
+ * the true ceiling, so a process on a default heap below about 2 GB can end before
1451
+ * this event fires.
1452
+ *
1453
+ * The engine emits the event once per crossing, then arms it again once the
1454
+ * free share of the heap recovers to two tenths. Raise the limit with
1455
+ * `--max-old-space-size-percentage` or `--max-old-space-size`, or close an
1456
+ * idle index; see {@link ProcessMemoryReport.heapLimit}.
1457
+ */
1458
+ heapPressure: {
1459
+ /** This is the index that a write or a load was touching when the heap
1460
+ * reached that point. */
1461
+ indexName: string;
1462
+ /** This is the heap that the process uses, in bytes. */
1463
+ heapUsed: number;
1464
+ /** This is the size in bytes that the heap can grow to. */
1465
+ heapLimit: number;
1466
+ /** This is the estimate of the bytes that the index holds. */
1467
+ estimatedMemoryBytes: number;
1468
+ };
1469
+ /** The engine started, completed, or failed a rebuild that brings the terms
1470
+ * of an index up to the current analysis of its language module. */
1471
+ analysisRebuild: {
1472
+ /** This is the name of the index under rebuild. */
1473
+ indexName: string;
1474
+ /** This is the stage that the rebuild has reached. */
1475
+ status: 'started' | 'completed' | 'failed';
1476
+ /** This is the number of partitions that the rebuild has covered so far. */
1477
+ partitionsRebuilt: number;
1478
+ /** This is the number of partitions that the rebuild covers in total. */
1479
+ partitionCount: number;
1480
+ /** This is the error that stopped the rebuild, which only a `failed`
1481
+ * status includes. */
1482
+ error?: Error;
1483
+ };
1484
+ /** The engine started, completed, or failed the rewrite of an index that you
1485
+ * saved with an earlier release. The engine rewrites the index as it
1486
+ * recovers it, before it serves the index's first request. Because the
1487
+ * engine writes the new manifest last, the earlier files stay intact through
1488
+ * a failed rewrite. The engine then starts the rewrite again the next time
1489
+ * it recovers the index. Without index lifecycle settings, the engine
1490
+ * recovers every index before {@link createNarsil} returns, so pass the
1491
+ * listener in the `events` setting of {@link createNarsil}. */
1492
+ layoutUpgrade: {
1493
+ /** This is the name of the index under rewrite. */
1494
+ indexName: string;
1495
+ /** This is the stage that the rewrite has reached. */
1496
+ status: 'started' | 'completed' | 'failed';
1497
+ /** This is `manifest` where the earlier index is a segment manifest with
1498
+ * its files, and `bundle` where it is a single snapshot bundle. */
1499
+ layout: 'manifest' | 'bundle';
1500
+ /** This is the error that stopped the rewrite, which only a `failed`
1501
+ * status includes. */
1502
+ error?: Error;
1503
+ };
1504
+ /** A write to the write-ahead log or a checkpoint failed, so the writes since
1505
+ * the last checkpoint are at risk. */
1506
+ durabilityError: {
1507
+ /** This is the error that the durability layer threw. */
1508
+ error: Error;
1509
+ };
1510
+ /** The invalidation channel failed, so this instance can serve partitions
1511
+ * that another instance has since changed. */
1512
+ invalidationError: {
1513
+ /** This is the error that the adapter threw. */
1514
+ error: Error;
1515
+ };
1516
+ };
1508
1517
  /**
1509
- * What {@link Narsil.listDocuments} returns: one page of stored documents and
1510
- * the cursor that reaches the next one.
1511
- *
1512
- * @typeParam T - Shape of the stored documents.
1518
+ * This map holds a listener for any event of {@link NarsilEventMap}, so that
1519
+ * the engine can register each listener before it starts.
1513
1520
  *
1514
1521
  * @public
1515
1522
  */
1516
- interface ListResult<T = AnyDocument> {
1517
- /** These documents make up the page, in ascending document-id order. */
1518
- documents: Array<ListedDocument<T>>;
1519
- /** This opaque cursor reaches the next page, and is null once the listing is finished. */
1520
- cursor: string | null;
1521
- /** The listing covers this many documents in total, and any filter narrows that count. */
1522
- total: number;
1523
- /** The engine spent this many milliseconds building the page. */
1524
- elapsed: number;
1525
- }
1523
+ type NarsilEventHandlers = {
1524
+ [K in keyof NarsilEventMap]?: (payload: NarsilEventMap[K]) => void;
1525
+ };
1526
1526
 
1527
1527
  /**
1528
1528
  * Snapshot of V8 heap usage as reported by `process.memoryUsage()`, with the