@trishchuk/coolors-mcp 1.0.1 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/.github/workflows/ci.yml +23 -20
  2. package/.github/workflows/deploy-docs.yml +6 -3
  3. package/.github/workflows/release.yml +11 -9
  4. package/README.md +123 -14
  5. package/dist/bin/server.js +997 -256
  6. package/dist/bin/server.js.map +1 -1
  7. package/dist/{chunk-P3ARRKLS.js → chunk-HOMDMKUY.js} +3 -1
  8. package/dist/{chunk-P3ARRKLS.js.map → chunk-HOMDMKUY.js.map} +1 -1
  9. package/dist/{chunk-IQ7NN26V.js → chunk-LHW2ZTOU.js} +14 -2
  10. package/dist/chunk-LHW2ZTOU.js.map +1 -0
  11. package/dist/color/index.js +1 -1
  12. package/dist/coolors-mcp.d.ts +4 -4
  13. package/dist/coolors-mcp.js +1 -1
  14. package/eslint.config.ts +13 -0
  15. package/jsr.json +1 -1
  16. package/package.json +16 -12
  17. package/src/bin/server.ts +13 -1
  18. package/src/color/__tests__/extract-colors.test.ts +20 -30
  19. package/src/color/apca.ts +105 -0
  20. package/src/color/color-blindness.ts +109 -0
  21. package/src/coolors-mcp.ts +1 -1
  22. package/src/session.ts +10 -2
  23. package/src/theme/matcher.ts +1 -1
  24. package/src/theme/refactor.ts +1 -1
  25. package/src/theme/types.ts +3 -0
  26. package/src/tools/__tests__/cohesion.test.ts +97 -0
  27. package/src/tools/__tests__/color-blindness.test.ts +45 -0
  28. package/src/tools/__tests__/color-conversion.test.ts +38 -0
  29. package/src/tools/__tests__/contrast-checker.test.ts +56 -0
  30. package/src/tools/__tests__/palette-export.test.ts +54 -0
  31. package/src/tools/adjust-color.tool.ts +80 -0
  32. package/src/tools/cohesion.tools.ts +380 -0
  33. package/src/tools/color-blindness.tool.ts +168 -0
  34. package/src/tools/color-conversion.tool.ts +1 -1
  35. package/src/tools/contrast-checker.tool.ts +53 -14
  36. package/src/tools/dislike-analyzer.tool.ts +41 -54
  37. package/src/tools/image-extraction.tools.ts +62 -115
  38. package/src/tools/index.ts +15 -2
  39. package/src/tools/palette-export.tool.ts +174 -0
  40. package/src/tools/palette-with-locks.tool.ts +8 -6
  41. package/src/types.ts +2 -3
  42. package/tsconfig.json +12 -2
  43. package/vitest.config.js +1 -3
  44. package/.claude/settings.local.json +0 -35
  45. package/.env +0 -2
  46. package/.mcp.json +0 -12
  47. package/CLAUDE.md +0 -201
  48. package/DOCUMENTATION.md +0 -274
  49. package/GEMINI.md +0 -54
  50. package/TOOLS_UK.md +0 -233
  51. package/demo/content_based_color.png +0 -0
  52. package/demo/music-player.html +0 -621
  53. package/demo/podcast-player.html +0 -903
  54. package/dist/chunk-IQ7NN26V.js.map +0 -1
  55. package/docs/.vitepress/cache/deps/@braintree_sanitize-url.js +0 -111
  56. package/docs/.vitepress/cache/deps/@braintree_sanitize-url.js.map +0 -7
  57. package/docs/.vitepress/cache/deps/_metadata.json +0 -127
  58. package/docs/.vitepress/cache/deps/chunk-BUSYA2B4.js +0 -12
  59. package/docs/.vitepress/cache/deps/chunk-BUSYA2B4.js.map +0 -7
  60. package/docs/.vitepress/cache/deps/chunk-JD3CXNQ6.js +0 -13614
  61. package/docs/.vitepress/cache/deps/chunk-JD3CXNQ6.js.map +0 -7
  62. package/docs/.vitepress/cache/deps/chunk-SYPOPCWC.js +0 -10698
  63. package/docs/.vitepress/cache/deps/chunk-SYPOPCWC.js.map +0 -7
  64. package/docs/.vitepress/cache/deps/cytoscape-cose-bilkent.js +0 -5609
  65. package/docs/.vitepress/cache/deps/cytoscape-cose-bilkent.js.map +0 -7
  66. package/docs/.vitepress/cache/deps/cytoscape.js +0 -36234
  67. package/docs/.vitepress/cache/deps/cytoscape.js.map +0 -7
  68. package/docs/.vitepress/cache/deps/dayjs.js +0 -507
  69. package/docs/.vitepress/cache/deps/dayjs.js.map +0 -7
  70. package/docs/.vitepress/cache/deps/debug.js +0 -512
  71. package/docs/.vitepress/cache/deps/debug.js.map +0 -7
  72. package/docs/.vitepress/cache/deps/package.json +0 -3
  73. package/docs/.vitepress/cache/deps/prismjs.js +0 -1638
  74. package/docs/.vitepress/cache/deps/prismjs.js.map +0 -7
  75. package/docs/.vitepress/cache/deps/prismjs_components_prism-bash.js +0 -235
  76. package/docs/.vitepress/cache/deps/prismjs_components_prism-bash.js.map +0 -7
  77. package/docs/.vitepress/cache/deps/prismjs_components_prism-javascript.js +0 -173
  78. package/docs/.vitepress/cache/deps/prismjs_components_prism-javascript.js.map +0 -7
  79. package/docs/.vitepress/cache/deps/prismjs_components_prism-json.js +0 -27
  80. package/docs/.vitepress/cache/deps/prismjs_components_prism-json.js.map +0 -7
  81. package/docs/.vitepress/cache/deps/prismjs_components_prism-python.js +0 -72
  82. package/docs/.vitepress/cache/deps/prismjs_components_prism-python.js.map +0 -7
  83. package/docs/.vitepress/cache/deps/prismjs_components_prism-typescript.js +0 -56
  84. package/docs/.vitepress/cache/deps/prismjs_components_prism-typescript.js.map +0 -7
  85. package/docs/.vitepress/cache/deps/prismjs_components_prism-yaml.js +0 -107
  86. package/docs/.vitepress/cache/deps/prismjs_components_prism-yaml.js.map +0 -7
  87. package/docs/.vitepress/cache/deps/vitepress___@vue_devtools-api.js +0 -5074
  88. package/docs/.vitepress/cache/deps/vitepress___@vue_devtools-api.js.map +0 -7
  89. package/docs/.vitepress/cache/deps/vitepress___@vueuse_core.js +0 -584
  90. package/docs/.vitepress/cache/deps/vitepress___@vueuse_core.js.map +0 -7
  91. package/docs/.vitepress/cache/deps/vitepress___@vueuse_integrations_useFocusTrap.js +0 -1483
  92. package/docs/.vitepress/cache/deps/vitepress___@vueuse_integrations_useFocusTrap.js.map +0 -7
  93. package/docs/.vitepress/cache/deps/vitepress___mark__js_src_vanilla__js.js +0 -1779
  94. package/docs/.vitepress/cache/deps/vitepress___mark__js_src_vanilla__js.js.map +0 -7
  95. package/docs/.vitepress/cache/deps/vitepress___minisearch.js +0 -2023
  96. package/docs/.vitepress/cache/deps/vitepress___minisearch.js.map +0 -7
  97. package/docs/.vitepress/cache/deps/vue.js +0 -344
  98. package/docs/.vitepress/cache/deps/vue.js.map +0 -7
  99. package/examples/theme-matching.md +0 -113
  100. package/mcp-config.json +0 -8
  101. package/note.md +0 -34
  102. package/research_results.md +0 -53
  103. package/src/tools/colors.ts +0 -31
  104. package/src/tools/registry.ts +0 -142
  105. package/src/tools/simple-tools.ts +0 -37
@@ -1,2023 +0,0 @@
1
- import "./chunk-BUSYA2B4.js";
2
-
3
- // node_modules/minisearch/dist/es/index.js
4
- var ENTRIES = "ENTRIES";
5
- var KEYS = "KEYS";
6
- var VALUES = "VALUES";
7
- var LEAF = "";
8
- var TreeIterator = class {
9
- constructor(set, type) {
10
- const node = set._tree;
11
- const keys = Array.from(node.keys());
12
- this.set = set;
13
- this._type = type;
14
- this._path = keys.length > 0 ? [{ node, keys }] : [];
15
- }
16
- next() {
17
- const value = this.dive();
18
- this.backtrack();
19
- return value;
20
- }
21
- dive() {
22
- if (this._path.length === 0) {
23
- return { done: true, value: void 0 };
24
- }
25
- const { node, keys } = last$1(this._path);
26
- if (last$1(keys) === LEAF) {
27
- return { done: false, value: this.result() };
28
- }
29
- const child = node.get(last$1(keys));
30
- this._path.push({ node: child, keys: Array.from(child.keys()) });
31
- return this.dive();
32
- }
33
- backtrack() {
34
- if (this._path.length === 0) {
35
- return;
36
- }
37
- const keys = last$1(this._path).keys;
38
- keys.pop();
39
- if (keys.length > 0) {
40
- return;
41
- }
42
- this._path.pop();
43
- this.backtrack();
44
- }
45
- key() {
46
- return (
47
- this.set._prefix +
48
- this._path
49
- .map(({ keys }) => last$1(keys))
50
- .filter((key) => key !== LEAF)
51
- .join("")
52
- );
53
- }
54
- value() {
55
- return last$1(this._path).node.get(LEAF);
56
- }
57
- result() {
58
- switch (this._type) {
59
- case VALUES:
60
- return this.value();
61
- case KEYS:
62
- return this.key();
63
- default:
64
- return [this.key(), this.value()];
65
- }
66
- }
67
- [Symbol.iterator]() {
68
- return this;
69
- }
70
- };
71
- var last$1 = (array) => {
72
- return array[array.length - 1];
73
- };
74
- var fuzzySearch = (node, query, maxDistance) => {
75
- const results = /* @__PURE__ */ new Map();
76
- if (query === void 0) return results;
77
- const n = query.length + 1;
78
- const m = n + maxDistance;
79
- const matrix = new Uint8Array(m * n).fill(maxDistance + 1);
80
- for (let j = 0; j < n; ++j) matrix[j] = j;
81
- for (let i = 1; i < m; ++i) matrix[i * n] = i;
82
- recurse(node, query, maxDistance, results, matrix, 1, n, "");
83
- return results;
84
- };
85
- var recurse = (node, query, maxDistance, results, matrix, m, n, prefix) => {
86
- const offset = m * n;
87
- key: for (const key of node.keys()) {
88
- if (key === LEAF) {
89
- const distance = matrix[offset - 1];
90
- if (distance <= maxDistance) {
91
- results.set(prefix, [node.get(key), distance]);
92
- }
93
- } else {
94
- let i = m;
95
- for (let pos = 0; pos < key.length; ++pos, ++i) {
96
- const char = key[pos];
97
- const thisRowOffset = n * i;
98
- const prevRowOffset = thisRowOffset - n;
99
- let minDistance = matrix[thisRowOffset];
100
- const jmin = Math.max(0, i - maxDistance - 1);
101
- const jmax = Math.min(n - 1, i + maxDistance);
102
- for (let j = jmin; j < jmax; ++j) {
103
- const different = char !== query[j];
104
- const rpl = matrix[prevRowOffset + j] + +different;
105
- const del = matrix[prevRowOffset + j + 1] + 1;
106
- const ins = matrix[thisRowOffset + j] + 1;
107
- const dist = (matrix[thisRowOffset + j + 1] = Math.min(
108
- rpl,
109
- del,
110
- ins,
111
- ));
112
- if (dist < minDistance) minDistance = dist;
113
- }
114
- if (minDistance > maxDistance) {
115
- continue key;
116
- }
117
- }
118
- recurse(
119
- node.get(key),
120
- query,
121
- maxDistance,
122
- results,
123
- matrix,
124
- i,
125
- n,
126
- prefix + key,
127
- );
128
- }
129
- }
130
- };
131
- var SearchableMap = class _SearchableMap {
132
- /**
133
- * The constructor is normally called without arguments, creating an empty
134
- * map. In order to create a {@link SearchableMap} from an iterable or from an
135
- * object, check {@link SearchableMap.from} and {@link
136
- * SearchableMap.fromObject}.
137
- *
138
- * The constructor arguments are for internal use, when creating derived
139
- * mutable views of a map at a prefix.
140
- */
141
- constructor(tree = /* @__PURE__ */ new Map(), prefix = "") {
142
- this._size = void 0;
143
- this._tree = tree;
144
- this._prefix = prefix;
145
- }
146
- /**
147
- * Creates and returns a mutable view of this {@link SearchableMap},
148
- * containing only entries that share the given prefix.
149
- *
150
- * ### Usage:
151
- *
152
- * ```javascript
153
- * let map = new SearchableMap()
154
- * map.set("unicorn", 1)
155
- * map.set("universe", 2)
156
- * map.set("university", 3)
157
- * map.set("unique", 4)
158
- * map.set("hello", 5)
159
- *
160
- * let uni = map.atPrefix("uni")
161
- * uni.get("unique") // => 4
162
- * uni.get("unicorn") // => 1
163
- * uni.get("hello") // => undefined
164
- *
165
- * let univer = map.atPrefix("univer")
166
- * univer.get("unique") // => undefined
167
- * univer.get("universe") // => 2
168
- * univer.get("university") // => 3
169
- * ```
170
- *
171
- * @param prefix The prefix
172
- * @return A {@link SearchableMap} representing a mutable view of the original
173
- * Map at the given prefix
174
- */
175
- atPrefix(prefix) {
176
- if (!prefix.startsWith(this._prefix)) {
177
- throw new Error("Mismatched prefix");
178
- }
179
- const [node, path] = trackDown(
180
- this._tree,
181
- prefix.slice(this._prefix.length),
182
- );
183
- if (node === void 0) {
184
- const [parentNode, key] = last(path);
185
- for (const k of parentNode.keys()) {
186
- if (k !== LEAF && k.startsWith(key)) {
187
- const node2 = /* @__PURE__ */ new Map();
188
- node2.set(k.slice(key.length), parentNode.get(k));
189
- return new _SearchableMap(node2, prefix);
190
- }
191
- }
192
- }
193
- return new _SearchableMap(node, prefix);
194
- }
195
- /**
196
- * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/clear
197
- */
198
- clear() {
199
- this._size = void 0;
200
- this._tree.clear();
201
- }
202
- /**
203
- * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/delete
204
- * @param key Key to delete
205
- */
206
- delete(key) {
207
- this._size = void 0;
208
- return remove(this._tree, key);
209
- }
210
- /**
211
- * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/entries
212
- * @return An iterator iterating through `[key, value]` entries.
213
- */
214
- entries() {
215
- return new TreeIterator(this, ENTRIES);
216
- }
217
- /**
218
- * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/forEach
219
- * @param fn Iteration function
220
- */
221
- forEach(fn) {
222
- for (const [key, value] of this) {
223
- fn(key, value, this);
224
- }
225
- }
226
- /**
227
- * Returns a Map of all the entries that have a key within the given edit
228
- * distance from the search key. The keys of the returned Map are the matching
229
- * keys, while the values are two-element arrays where the first element is
230
- * the value associated to the key, and the second is the edit distance of the
231
- * key to the search key.
232
- *
233
- * ### Usage:
234
- *
235
- * ```javascript
236
- * let map = new SearchableMap()
237
- * map.set('hello', 'world')
238
- * map.set('hell', 'yeah')
239
- * map.set('ciao', 'mondo')
240
- *
241
- * // Get all entries that match the key 'hallo' with a maximum edit distance of 2
242
- * map.fuzzyGet('hallo', 2)
243
- * // => Map(2) { 'hello' => ['world', 1], 'hell' => ['yeah', 2] }
244
- *
245
- * // In the example, the "hello" key has value "world" and edit distance of 1
246
- * // (change "e" to "a"), the key "hell" has value "yeah" and edit distance of 2
247
- * // (change "e" to "a", delete "o")
248
- * ```
249
- *
250
- * @param key The search key
251
- * @param maxEditDistance The maximum edit distance (Levenshtein)
252
- * @return A Map of the matching keys to their value and edit distance
253
- */
254
- fuzzyGet(key, maxEditDistance) {
255
- return fuzzySearch(this._tree, key, maxEditDistance);
256
- }
257
- /**
258
- * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/get
259
- * @param key Key to get
260
- * @return Value associated to the key, or `undefined` if the key is not
261
- * found.
262
- */
263
- get(key) {
264
- const node = lookup(this._tree, key);
265
- return node !== void 0 ? node.get(LEAF) : void 0;
266
- }
267
- /**
268
- * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/has
269
- * @param key Key
270
- * @return True if the key is in the map, false otherwise
271
- */
272
- has(key) {
273
- const node = lookup(this._tree, key);
274
- return node !== void 0 && node.has(LEAF);
275
- }
276
- /**
277
- * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/keys
278
- * @return An `Iterable` iterating through keys
279
- */
280
- keys() {
281
- return new TreeIterator(this, KEYS);
282
- }
283
- /**
284
- * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/set
285
- * @param key Key to set
286
- * @param value Value to associate to the key
287
- * @return The {@link SearchableMap} itself, to allow chaining
288
- */
289
- set(key, value) {
290
- if (typeof key !== "string") {
291
- throw new Error("key must be a string");
292
- }
293
- this._size = void 0;
294
- const node = createPath(this._tree, key);
295
- node.set(LEAF, value);
296
- return this;
297
- }
298
- /**
299
- * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/size
300
- */
301
- get size() {
302
- if (this._size) {
303
- return this._size;
304
- }
305
- this._size = 0;
306
- const iter = this.entries();
307
- while (!iter.next().done) this._size += 1;
308
- return this._size;
309
- }
310
- /**
311
- * Updates the value at the given key using the provided function. The function
312
- * is called with the current value at the key, and its return value is used as
313
- * the new value to be set.
314
- *
315
- * ### Example:
316
- *
317
- * ```javascript
318
- * // Increment the current value by one
319
- * searchableMap.update('somekey', (currentValue) => currentValue == null ? 0 : currentValue + 1)
320
- * ```
321
- *
322
- * If the value at the given key is or will be an object, it might not require
323
- * re-assignment. In that case it is better to use `fetch()`, because it is
324
- * faster.
325
- *
326
- * @param key The key to update
327
- * @param fn The function used to compute the new value from the current one
328
- * @return The {@link SearchableMap} itself, to allow chaining
329
- */
330
- update(key, fn) {
331
- if (typeof key !== "string") {
332
- throw new Error("key must be a string");
333
- }
334
- this._size = void 0;
335
- const node = createPath(this._tree, key);
336
- node.set(LEAF, fn(node.get(LEAF)));
337
- return this;
338
- }
339
- /**
340
- * Fetches the value of the given key. If the value does not exist, calls the
341
- * given function to create a new value, which is inserted at the given key
342
- * and subsequently returned.
343
- *
344
- * ### Example:
345
- *
346
- * ```javascript
347
- * const map = searchableMap.fetch('somekey', () => new Map())
348
- * map.set('foo', 'bar')
349
- * ```
350
- *
351
- * @param key The key to update
352
- * @param initial A function that creates a new value if the key does not exist
353
- * @return The existing or new value at the given key
354
- */
355
- fetch(key, initial) {
356
- if (typeof key !== "string") {
357
- throw new Error("key must be a string");
358
- }
359
- this._size = void 0;
360
- const node = createPath(this._tree, key);
361
- let value = node.get(LEAF);
362
- if (value === void 0) {
363
- node.set(LEAF, (value = initial()));
364
- }
365
- return value;
366
- }
367
- /**
368
- * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/values
369
- * @return An `Iterable` iterating through values.
370
- */
371
- values() {
372
- return new TreeIterator(this, VALUES);
373
- }
374
- /**
375
- * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/@@iterator
376
- */
377
- [Symbol.iterator]() {
378
- return this.entries();
379
- }
380
- /**
381
- * Creates a {@link SearchableMap} from an `Iterable` of entries
382
- *
383
- * @param entries Entries to be inserted in the {@link SearchableMap}
384
- * @return A new {@link SearchableMap} with the given entries
385
- */
386
- static from(entries) {
387
- const tree = new _SearchableMap();
388
- for (const [key, value] of entries) {
389
- tree.set(key, value);
390
- }
391
- return tree;
392
- }
393
- /**
394
- * Creates a {@link SearchableMap} from the iterable properties of a JavaScript object
395
- *
396
- * @param object Object of entries for the {@link SearchableMap}
397
- * @return A new {@link SearchableMap} with the given entries
398
- */
399
- static fromObject(object) {
400
- return _SearchableMap.from(Object.entries(object));
401
- }
402
- };
403
- var trackDown = (tree, key, path = []) => {
404
- if (key.length === 0 || tree == null) {
405
- return [tree, path];
406
- }
407
- for (const k of tree.keys()) {
408
- if (k !== LEAF && key.startsWith(k)) {
409
- path.push([tree, k]);
410
- return trackDown(tree.get(k), key.slice(k.length), path);
411
- }
412
- }
413
- path.push([tree, key]);
414
- return trackDown(void 0, "", path);
415
- };
416
- var lookup = (tree, key) => {
417
- if (key.length === 0 || tree == null) {
418
- return tree;
419
- }
420
- for (const k of tree.keys()) {
421
- if (k !== LEAF && key.startsWith(k)) {
422
- return lookup(tree.get(k), key.slice(k.length));
423
- }
424
- }
425
- };
426
- var createPath = (node, key) => {
427
- const keyLength = key.length;
428
- outer: for (let pos = 0; node && pos < keyLength; ) {
429
- for (const k of node.keys()) {
430
- if (k !== LEAF && key[pos] === k[0]) {
431
- const len = Math.min(keyLength - pos, k.length);
432
- let offset = 1;
433
- while (offset < len && key[pos + offset] === k[offset]) ++offset;
434
- const child2 = node.get(k);
435
- if (offset === k.length) {
436
- node = child2;
437
- } else {
438
- const intermediate = /* @__PURE__ */ new Map();
439
- intermediate.set(k.slice(offset), child2);
440
- node.set(key.slice(pos, pos + offset), intermediate);
441
- node.delete(k);
442
- node = intermediate;
443
- }
444
- pos += offset;
445
- continue outer;
446
- }
447
- }
448
- const child = /* @__PURE__ */ new Map();
449
- node.set(key.slice(pos), child);
450
- return child;
451
- }
452
- return node;
453
- };
454
- var remove = (tree, key) => {
455
- const [node, path] = trackDown(tree, key);
456
- if (node === void 0) {
457
- return;
458
- }
459
- node.delete(LEAF);
460
- if (node.size === 0) {
461
- cleanup(path);
462
- } else if (node.size === 1) {
463
- const [key2, value] = node.entries().next().value;
464
- merge(path, key2, value);
465
- }
466
- };
467
- var cleanup = (path) => {
468
- if (path.length === 0) {
469
- return;
470
- }
471
- const [node, key] = last(path);
472
- node.delete(key);
473
- if (node.size === 0) {
474
- cleanup(path.slice(0, -1));
475
- } else if (node.size === 1) {
476
- const [key2, value] = node.entries().next().value;
477
- if (key2 !== LEAF) {
478
- merge(path.slice(0, -1), key2, value);
479
- }
480
- }
481
- };
482
- var merge = (path, key, value) => {
483
- if (path.length === 0) {
484
- return;
485
- }
486
- const [node, nodeKey] = last(path);
487
- node.set(nodeKey + key, value);
488
- node.delete(nodeKey);
489
- };
490
- var last = (array) => {
491
- return array[array.length - 1];
492
- };
493
- var OR = "or";
494
- var AND = "and";
495
- var AND_NOT = "and_not";
496
- var MiniSearch = class _MiniSearch {
497
- /**
498
- * @param options Configuration options
499
- *
500
- * ### Examples:
501
- *
502
- * ```javascript
503
- * // Create a search engine that indexes the 'title' and 'text' fields of your
504
- * // documents:
505
- * const miniSearch = new MiniSearch({ fields: ['title', 'text'] })
506
- * ```
507
- *
508
- * ### ID Field:
509
- *
510
- * ```javascript
511
- * // Your documents are assumed to include a unique 'id' field, but if you want
512
- * // to use a different field for document identification, you can set the
513
- * // 'idField' option:
514
- * const miniSearch = new MiniSearch({ idField: 'key', fields: ['title', 'text'] })
515
- * ```
516
- *
517
- * ### Options and defaults:
518
- *
519
- * ```javascript
520
- * // The full set of options (here with their default value) is:
521
- * const miniSearch = new MiniSearch({
522
- * // idField: field that uniquely identifies a document
523
- * idField: 'id',
524
- *
525
- * // extractField: function used to get the value of a field in a document.
526
- * // By default, it assumes the document is a flat object with field names as
527
- * // property keys and field values as string property values, but custom logic
528
- * // can be implemented by setting this option to a custom extractor function.
529
- * extractField: (document, fieldName) => document[fieldName],
530
- *
531
- * // tokenize: function used to split fields into individual terms. By
532
- * // default, it is also used to tokenize search queries, unless a specific
533
- * // `tokenize` search option is supplied. When tokenizing an indexed field,
534
- * // the field name is passed as the second argument.
535
- * tokenize: (string, _fieldName) => string.split(SPACE_OR_PUNCTUATION),
536
- *
537
- * // processTerm: function used to process each tokenized term before
538
- * // indexing. It can be used for stemming and normalization. Return a falsy
539
- * // value in order to discard a term. By default, it is also used to process
540
- * // search queries, unless a specific `processTerm` option is supplied as a
541
- * // search option. When processing a term from a indexed field, the field
542
- * // name is passed as the second argument.
543
- * processTerm: (term, _fieldName) => term.toLowerCase(),
544
- *
545
- * // searchOptions: default search options, see the `search` method for
546
- * // details
547
- * searchOptions: undefined,
548
- *
549
- * // fields: document fields to be indexed. Mandatory, but not set by default
550
- * fields: undefined
551
- *
552
- * // storeFields: document fields to be stored and returned as part of the
553
- * // search results.
554
- * storeFields: []
555
- * })
556
- * ```
557
- */
558
- constructor(options) {
559
- if (
560
- (options === null || options === void 0 ? void 0 : options.fields) == null
561
- ) {
562
- throw new Error('MiniSearch: option "fields" must be provided');
563
- }
564
- const autoVacuum =
565
- options.autoVacuum == null || options.autoVacuum === true
566
- ? defaultAutoVacuumOptions
567
- : options.autoVacuum;
568
- this._options = {
569
- ...defaultOptions,
570
- ...options,
571
- autoVacuum,
572
- searchOptions: {
573
- ...defaultSearchOptions,
574
- ...(options.searchOptions || {}),
575
- },
576
- autoSuggestOptions: {
577
- ...defaultAutoSuggestOptions,
578
- ...(options.autoSuggestOptions || {}),
579
- },
580
- };
581
- this._index = new SearchableMap();
582
- this._documentCount = 0;
583
- this._documentIds = /* @__PURE__ */ new Map();
584
- this._idToShortId = /* @__PURE__ */ new Map();
585
- this._fieldIds = {};
586
- this._fieldLength = /* @__PURE__ */ new Map();
587
- this._avgFieldLength = [];
588
- this._nextId = 0;
589
- this._storedFields = /* @__PURE__ */ new Map();
590
- this._dirtCount = 0;
591
- this._currentVacuum = null;
592
- this._enqueuedVacuum = null;
593
- this._enqueuedVacuumConditions = defaultVacuumConditions;
594
- this.addFields(this._options.fields);
595
- }
596
- /**
597
- * Adds a document to the index
598
- *
599
- * @param document The document to be indexed
600
- */
601
- add(document) {
602
- const { extractField, tokenize, processTerm, fields, idField } =
603
- this._options;
604
- const id = extractField(document, idField);
605
- if (id == null) {
606
- throw new Error(
607
- `MiniSearch: document does not have ID field "${idField}"`,
608
- );
609
- }
610
- if (this._idToShortId.has(id)) {
611
- throw new Error(`MiniSearch: duplicate ID ${id}`);
612
- }
613
- const shortDocumentId = this.addDocumentId(id);
614
- this.saveStoredFields(shortDocumentId, document);
615
- for (const field of fields) {
616
- const fieldValue = extractField(document, field);
617
- if (fieldValue == null) continue;
618
- const tokens = tokenize(fieldValue.toString(), field);
619
- const fieldId = this._fieldIds[field];
620
- const uniqueTerms = new Set(tokens).size;
621
- this.addFieldLength(
622
- shortDocumentId,
623
- fieldId,
624
- this._documentCount - 1,
625
- uniqueTerms,
626
- );
627
- for (const term of tokens) {
628
- const processedTerm = processTerm(term, field);
629
- if (Array.isArray(processedTerm)) {
630
- for (const t of processedTerm) {
631
- this.addTerm(fieldId, shortDocumentId, t);
632
- }
633
- } else if (processedTerm) {
634
- this.addTerm(fieldId, shortDocumentId, processedTerm);
635
- }
636
- }
637
- }
638
- }
639
- /**
640
- * Adds all the given documents to the index
641
- *
642
- * @param documents An array of documents to be indexed
643
- */
644
- addAll(documents) {
645
- for (const document of documents) this.add(document);
646
- }
647
- /**
648
- * Adds all the given documents to the index asynchronously.
649
- *
650
- * Returns a promise that resolves (to `undefined`) when the indexing is done.
651
- * This method is useful when index many documents, to avoid blocking the main
652
- * thread. The indexing is performed asynchronously and in chunks.
653
- *
654
- * @param documents An array of documents to be indexed
655
- * @param options Configuration options
656
- * @return A promise resolving to `undefined` when the indexing is done
657
- */
658
- addAllAsync(documents, options = {}) {
659
- const { chunkSize = 10 } = options;
660
- const acc = { chunk: [], promise: Promise.resolve() };
661
- const { chunk, promise } = documents.reduce(
662
- ({ chunk: chunk2, promise: promise2 }, document, i) => {
663
- chunk2.push(document);
664
- if ((i + 1) % chunkSize === 0) {
665
- return {
666
- chunk: [],
667
- promise: promise2
668
- .then(() => new Promise((resolve) => setTimeout(resolve, 0)))
669
- .then(() => this.addAll(chunk2)),
670
- };
671
- } else {
672
- return { chunk: chunk2, promise: promise2 };
673
- }
674
- },
675
- acc,
676
- );
677
- return promise.then(() => this.addAll(chunk));
678
- }
679
- /**
680
- * Removes the given document from the index.
681
- *
682
- * The document to remove must NOT have changed between indexing and removal,
683
- * otherwise the index will be corrupted.
684
- *
685
- * This method requires passing the full document to be removed (not just the
686
- * ID), and immediately removes the document from the inverted index, allowing
687
- * memory to be released. A convenient alternative is {@link
688
- * MiniSearch#discard}, which needs only the document ID, and has the same
689
- * visible effect, but delays cleaning up the index until the next vacuuming.
690
- *
691
- * @param document The document to be removed
692
- */
693
- remove(document) {
694
- const { tokenize, processTerm, extractField, fields, idField } =
695
- this._options;
696
- const id = extractField(document, idField);
697
- if (id == null) {
698
- throw new Error(
699
- `MiniSearch: document does not have ID field "${idField}"`,
700
- );
701
- }
702
- const shortId = this._idToShortId.get(id);
703
- if (shortId == null) {
704
- throw new Error(
705
- `MiniSearch: cannot remove document with ID ${id}: it is not in the index`,
706
- );
707
- }
708
- for (const field of fields) {
709
- const fieldValue = extractField(document, field);
710
- if (fieldValue == null) continue;
711
- const tokens = tokenize(fieldValue.toString(), field);
712
- const fieldId = this._fieldIds[field];
713
- const uniqueTerms = new Set(tokens).size;
714
- this.removeFieldLength(
715
- shortId,
716
- fieldId,
717
- this._documentCount,
718
- uniqueTerms,
719
- );
720
- for (const term of tokens) {
721
- const processedTerm = processTerm(term, field);
722
- if (Array.isArray(processedTerm)) {
723
- for (const t of processedTerm) {
724
- this.removeTerm(fieldId, shortId, t);
725
- }
726
- } else if (processedTerm) {
727
- this.removeTerm(fieldId, shortId, processedTerm);
728
- }
729
- }
730
- }
731
- this._storedFields.delete(shortId);
732
- this._documentIds.delete(shortId);
733
- this._idToShortId.delete(id);
734
- this._fieldLength.delete(shortId);
735
- this._documentCount -= 1;
736
- }
737
- /**
738
- * Removes all the given documents from the index. If called with no arguments,
739
- * it removes _all_ documents from the index.
740
- *
741
- * @param documents The documents to be removed. If this argument is omitted,
742
- * all documents are removed. Note that, for removing all documents, it is
743
- * more efficient to call this method with no arguments than to pass all
744
- * documents.
745
- */
746
- removeAll(documents) {
747
- if (documents) {
748
- for (const document of documents) this.remove(document);
749
- } else if (arguments.length > 0) {
750
- throw new Error(
751
- "Expected documents to be present. Omit the argument to remove all documents.",
752
- );
753
- } else {
754
- this._index = new SearchableMap();
755
- this._documentCount = 0;
756
- this._documentIds = /* @__PURE__ */ new Map();
757
- this._idToShortId = /* @__PURE__ */ new Map();
758
- this._fieldLength = /* @__PURE__ */ new Map();
759
- this._avgFieldLength = [];
760
- this._storedFields = /* @__PURE__ */ new Map();
761
- this._nextId = 0;
762
- }
763
- }
764
- /**
765
- * Discards the document with the given ID, so it won't appear in search results
766
- *
767
- * It has the same visible effect of {@link MiniSearch.remove} (both cause the
768
- * document to stop appearing in searches), but a different effect on the
769
- * internal data structures:
770
- *
771
- * - {@link MiniSearch#remove} requires passing the full document to be
772
- * removed as argument, and removes it from the inverted index immediately.
773
- *
774
- * - {@link MiniSearch#discard} instead only needs the document ID, and
775
- * works by marking the current version of the document as discarded, so it
776
- * is immediately ignored by searches. This is faster and more convenient
777
- * than {@link MiniSearch#remove}, but the index is not immediately
778
- * modified. To take care of that, vacuuming is performed after a certain
779
- * number of documents are discarded, cleaning up the index and allowing
780
- * memory to be released.
781
- *
782
- * After discarding a document, it is possible to re-add a new version, and
783
- * only the new version will appear in searches. In other words, discarding
784
- * and re-adding a document works exactly like removing and re-adding it. The
785
- * {@link MiniSearch.replace} method can also be used to replace a document
786
- * with a new version.
787
- *
788
- * #### Details about vacuuming
789
- *
790
- * Repetite calls to this method would leave obsolete document references in
791
- * the index, invisible to searches. Two mechanisms take care of cleaning up:
792
- * clean up during search, and vacuuming.
793
- *
794
- * - Upon search, whenever a discarded ID is found (and ignored for the
795
- * results), references to the discarded document are removed from the
796
- * inverted index entries for the search terms. This ensures that subsequent
797
- * searches for the same terms do not need to skip these obsolete references
798
- * again.
799
- *
800
- * - In addition, vacuuming is performed automatically by default (see the
801
- * `autoVacuum` field in {@link Options}) after a certain number of
802
- * documents are discarded. Vacuuming traverses all terms in the index,
803
- * cleaning up all references to discarded documents. Vacuuming can also be
804
- * triggered manually by calling {@link MiniSearch#vacuum}.
805
- *
806
- * @param id The ID of the document to be discarded
807
- */
808
- discard(id) {
809
- const shortId = this._idToShortId.get(id);
810
- if (shortId == null) {
811
- throw new Error(
812
- `MiniSearch: cannot discard document with ID ${id}: it is not in the index`,
813
- );
814
- }
815
- this._idToShortId.delete(id);
816
- this._documentIds.delete(shortId);
817
- this._storedFields.delete(shortId);
818
- (this._fieldLength.get(shortId) || []).forEach((fieldLength, fieldId) => {
819
- this.removeFieldLength(
820
- shortId,
821
- fieldId,
822
- this._documentCount,
823
- fieldLength,
824
- );
825
- });
826
- this._fieldLength.delete(shortId);
827
- this._documentCount -= 1;
828
- this._dirtCount += 1;
829
- this.maybeAutoVacuum();
830
- }
831
- maybeAutoVacuum() {
832
- if (this._options.autoVacuum === false) {
833
- return;
834
- }
835
- const { minDirtFactor, minDirtCount, batchSize, batchWait } =
836
- this._options.autoVacuum;
837
- this.conditionalVacuum(
838
- { batchSize, batchWait },
839
- { minDirtCount, minDirtFactor },
840
- );
841
- }
842
- /**
843
- * Discards the documents with the given IDs, so they won't appear in search
844
- * results
845
- *
846
- * It is equivalent to calling {@link MiniSearch#discard} for all the given
847
- * IDs, but with the optimization of triggering at most one automatic
848
- * vacuuming at the end.
849
- *
850
- * Note: to remove all documents from the index, it is faster and more
851
- * convenient to call {@link MiniSearch.removeAll} with no argument, instead
852
- * of passing all IDs to this method.
853
- */
854
- discardAll(ids) {
855
- const autoVacuum = this._options.autoVacuum;
856
- try {
857
- this._options.autoVacuum = false;
858
- for (const id of ids) {
859
- this.discard(id);
860
- }
861
- } finally {
862
- this._options.autoVacuum = autoVacuum;
863
- }
864
- this.maybeAutoVacuum();
865
- }
866
- /**
867
- * It replaces an existing document with the given updated version
868
- *
869
- * It works by discarding the current version and adding the updated one, so
870
- * it is functionally equivalent to calling {@link MiniSearch#discard}
871
- * followed by {@link MiniSearch#add}. The ID of the updated document should
872
- * be the same as the original one.
873
- *
874
- * Since it uses {@link MiniSearch#discard} internally, this method relies on
875
- * vacuuming to clean up obsolete document references from the index, allowing
876
- * memory to be released (see {@link MiniSearch#discard}).
877
- *
878
- * @param updatedDocument The updated document to replace the old version
879
- * with
880
- */
881
- replace(updatedDocument) {
882
- const { idField, extractField } = this._options;
883
- const id = extractField(updatedDocument, idField);
884
- this.discard(id);
885
- this.add(updatedDocument);
886
- }
887
- /**
888
- * Triggers a manual vacuuming, cleaning up references to discarded documents
889
- * from the inverted index
890
- *
891
- * Vacuuming is only useful for applications that use the {@link
892
- * MiniSearch#discard} or {@link MiniSearch#replace} methods.
893
- *
894
- * By default, vacuuming is performed automatically when needed (controlled by
895
- * the `autoVacuum` field in {@link Options}), so there is usually no need to
896
- * call this method, unless one wants to make sure to perform vacuuming at a
897
- * specific moment.
898
- *
899
- * Vacuuming traverses all terms in the inverted index in batches, and cleans
900
- * up references to discarded documents from the posting list, allowing memory
901
- * to be released.
902
- *
903
- * The method takes an optional object as argument with the following keys:
904
- *
905
- * - `batchSize`: the size of each batch (1000 by default)
906
- *
907
- * - `batchWait`: the number of milliseconds to wait between batches (10 by
908
- * default)
909
- *
910
- * On large indexes, vacuuming could have a non-negligible cost: batching
911
- * avoids blocking the thread for long, diluting this cost so that it is not
912
- * negatively affecting the application. Nonetheless, this method should only
913
- * be called when necessary, and relying on automatic vacuuming is usually
914
- * better.
915
- *
916
- * It returns a promise that resolves (to undefined) when the clean up is
917
- * completed. If vacuuming is already ongoing at the time this method is
918
- * called, a new one is enqueued immediately after the ongoing one, and a
919
- * corresponding promise is returned. However, no more than one vacuuming is
920
- * enqueued on top of the ongoing one, even if this method is called more
921
- * times (enqueuing multiple ones would be useless).
922
- *
923
- * @param options Configuration options for the batch size and delay. See
924
- * {@link VacuumOptions}.
925
- */
926
- vacuum(options = {}) {
927
- return this.conditionalVacuum(options);
928
- }
929
- conditionalVacuum(options, conditions) {
930
- if (this._currentVacuum) {
931
- this._enqueuedVacuumConditions =
932
- this._enqueuedVacuumConditions && conditions;
933
- if (this._enqueuedVacuum != null) {
934
- return this._enqueuedVacuum;
935
- }
936
- this._enqueuedVacuum = this._currentVacuum.then(() => {
937
- const conditions2 = this._enqueuedVacuumConditions;
938
- this._enqueuedVacuumConditions = defaultVacuumConditions;
939
- return this.performVacuuming(options, conditions2);
940
- });
941
- return this._enqueuedVacuum;
942
- }
943
- if (this.vacuumConditionsMet(conditions) === false) {
944
- return Promise.resolve();
945
- }
946
- this._currentVacuum = this.performVacuuming(options);
947
- return this._currentVacuum;
948
- }
949
- async performVacuuming(options, conditions) {
950
- const initialDirtCount = this._dirtCount;
951
- if (this.vacuumConditionsMet(conditions)) {
952
- const batchSize = options.batchSize || defaultVacuumOptions.batchSize;
953
- const batchWait = options.batchWait || defaultVacuumOptions.batchWait;
954
- let i = 1;
955
- for (const [term, fieldsData] of this._index) {
956
- for (const [fieldId, fieldIndex] of fieldsData) {
957
- for (const [shortId] of fieldIndex) {
958
- if (this._documentIds.has(shortId)) {
959
- continue;
960
- }
961
- if (fieldIndex.size <= 1) {
962
- fieldsData.delete(fieldId);
963
- } else {
964
- fieldIndex.delete(shortId);
965
- }
966
- }
967
- }
968
- if (this._index.get(term).size === 0) {
969
- this._index.delete(term);
970
- }
971
- if (i % batchSize === 0) {
972
- await new Promise((resolve) => setTimeout(resolve, batchWait));
973
- }
974
- i += 1;
975
- }
976
- this._dirtCount -= initialDirtCount;
977
- }
978
- await null;
979
- this._currentVacuum = this._enqueuedVacuum;
980
- this._enqueuedVacuum = null;
981
- }
982
- vacuumConditionsMet(conditions) {
983
- if (conditions == null) {
984
- return true;
985
- }
986
- let { minDirtCount, minDirtFactor } = conditions;
987
- minDirtCount = minDirtCount || defaultAutoVacuumOptions.minDirtCount;
988
- minDirtFactor = minDirtFactor || defaultAutoVacuumOptions.minDirtFactor;
989
- return this.dirtCount >= minDirtCount && this.dirtFactor >= minDirtFactor;
990
- }
991
- /**
992
- * Is `true` if a vacuuming operation is ongoing, `false` otherwise
993
- */
994
- get isVacuuming() {
995
- return this._currentVacuum != null;
996
- }
997
- /**
998
- * The number of documents discarded since the most recent vacuuming
999
- */
1000
- get dirtCount() {
1001
- return this._dirtCount;
1002
- }
1003
- /**
1004
- * A number between 0 and 1 giving an indication about the proportion of
1005
- * documents that are discarded, and can therefore be cleaned up by vacuuming.
1006
- * A value close to 0 means that the index is relatively clean, while a higher
1007
- * value means that the index is relatively dirty, and vacuuming could release
1008
- * memory.
1009
- */
1010
- get dirtFactor() {
1011
- return this._dirtCount / (1 + this._documentCount + this._dirtCount);
1012
- }
1013
- /**
1014
- * Returns `true` if a document with the given ID is present in the index and
1015
- * available for search, `false` otherwise
1016
- *
1017
- * @param id The document ID
1018
- */
1019
- has(id) {
1020
- return this._idToShortId.has(id);
1021
- }
1022
- /**
1023
- * Returns the stored fields (as configured in the `storeFields` constructor
1024
- * option) for the given document ID. Returns `undefined` if the document is
1025
- * not present in the index.
1026
- *
1027
- * @param id The document ID
1028
- */
1029
- getStoredFields(id) {
1030
- const shortId = this._idToShortId.get(id);
1031
- if (shortId == null) {
1032
- return void 0;
1033
- }
1034
- return this._storedFields.get(shortId);
1035
- }
1036
- /**
1037
- * Search for documents matching the given search query.
1038
- *
1039
- * The result is a list of scored document IDs matching the query, sorted by
1040
- * descending score, and each including data about which terms were matched and
1041
- * in which fields.
1042
- *
1043
- * ### Basic usage:
1044
- *
1045
- * ```javascript
1046
- * // Search for "zen art motorcycle" with default options: terms have to match
1047
- * // exactly, and individual terms are joined with OR
1048
- * miniSearch.search('zen art motorcycle')
1049
- * // => [ { id: 2, score: 2.77258, match: { ... } }, { id: 4, score: 1.38629, match: { ... } } ]
1050
- * ```
1051
- *
1052
- * ### Restrict search to specific fields:
1053
- *
1054
- * ```javascript
1055
- * // Search only in the 'title' field
1056
- * miniSearch.search('zen', { fields: ['title'] })
1057
- * ```
1058
- *
1059
- * ### Field boosting:
1060
- *
1061
- * ```javascript
1062
- * // Boost a field
1063
- * miniSearch.search('zen', { boost: { title: 2 } })
1064
- * ```
1065
- *
1066
- * ### Prefix search:
1067
- *
1068
- * ```javascript
1069
- * // Search for "moto" with prefix search (it will match documents
1070
- * // containing terms that start with "moto" or "neuro")
1071
- * miniSearch.search('moto neuro', { prefix: true })
1072
- * ```
1073
- *
1074
- * ### Fuzzy search:
1075
- *
1076
- * ```javascript
1077
- * // Search for "ismael" with fuzzy search (it will match documents containing
1078
- * // terms similar to "ismael", with a maximum edit distance of 0.2 term.length
1079
- * // (rounded to nearest integer)
1080
- * miniSearch.search('ismael', { fuzzy: 0.2 })
1081
- * ```
1082
- *
1083
- * ### Combining strategies:
1084
- *
1085
- * ```javascript
1086
- * // Mix of exact match, prefix search, and fuzzy search
1087
- * miniSearch.search('ismael mob', {
1088
- * prefix: true,
1089
- * fuzzy: 0.2
1090
- * })
1091
- * ```
1092
- *
1093
- * ### Advanced prefix and fuzzy search:
1094
- *
1095
- * ```javascript
1096
- * // Perform fuzzy and prefix search depending on the search term. Here
1097
- * // performing prefix and fuzzy search only on terms longer than 3 characters
1098
- * miniSearch.search('ismael mob', {
1099
- * prefix: term => term.length > 3
1100
- * fuzzy: term => term.length > 3 ? 0.2 : null
1101
- * })
1102
- * ```
1103
- *
1104
- * ### Combine with AND:
1105
- *
1106
- * ```javascript
1107
- * // Combine search terms with AND (to match only documents that contain both
1108
- * // "motorcycle" and "art")
1109
- * miniSearch.search('motorcycle art', { combineWith: 'AND' })
1110
- * ```
1111
- *
1112
- * ### Combine with AND_NOT:
1113
- *
1114
- * There is also an AND_NOT combinator, that finds documents that match the
1115
- * first term, but do not match any of the other terms. This combinator is
1116
- * rarely useful with simple queries, and is meant to be used with advanced
1117
- * query combinations (see later for more details).
1118
- *
1119
- * ### Filtering results:
1120
- *
1121
- * ```javascript
1122
- * // Filter only results in the 'fiction' category (assuming that 'category'
1123
- * // is a stored field)
1124
- * miniSearch.search('motorcycle art', {
1125
- * filter: (result) => result.category === 'fiction'
1126
- * })
1127
- * ```
1128
- *
1129
- * ### Wildcard query
1130
- *
1131
- * Searching for an empty string (assuming the default tokenizer) returns no
1132
- * results. Sometimes though, one needs to match all documents, like in a
1133
- * "wildcard" search. This is possible by passing the special value
1134
- * {@link MiniSearch.wildcard} as the query:
1135
- *
1136
- * ```javascript
1137
- * // Return search results for all documents
1138
- * miniSearch.search(MiniSearch.wildcard)
1139
- * ```
1140
- *
1141
- * Note that search options such as `filter` and `boostDocument` are still
1142
- * applied, influencing which results are returned, and their order:
1143
- *
1144
- * ```javascript
1145
- * // Return search results for all documents in the 'fiction' category
1146
- * miniSearch.search(MiniSearch.wildcard, {
1147
- * filter: (result) => result.category === 'fiction'
1148
- * })
1149
- * ```
1150
- *
1151
- * ### Advanced combination of queries:
1152
- *
1153
- * It is possible to combine different subqueries with OR, AND, and AND_NOT,
1154
- * and even with different search options, by passing a query expression
1155
- * tree object as the first argument, instead of a string.
1156
- *
1157
- * ```javascript
1158
- * // Search for documents that contain "zen" and ("motorcycle" or "archery")
1159
- * miniSearch.search({
1160
- * combineWith: 'AND',
1161
- * queries: [
1162
- * 'zen',
1163
- * {
1164
- * combineWith: 'OR',
1165
- * queries: ['motorcycle', 'archery']
1166
- * }
1167
- * ]
1168
- * })
1169
- *
1170
- * // Search for documents that contain ("apple" or "pear") but not "juice" and
1171
- * // not "tree"
1172
- * miniSearch.search({
1173
- * combineWith: 'AND_NOT',
1174
- * queries: [
1175
- * {
1176
- * combineWith: 'OR',
1177
- * queries: ['apple', 'pear']
1178
- * },
1179
- * 'juice',
1180
- * 'tree'
1181
- * ]
1182
- * })
1183
- * ```
1184
- *
1185
- * Each node in the expression tree can be either a string, or an object that
1186
- * supports all {@link SearchOptions} fields, plus a `queries` array field for
1187
- * subqueries.
1188
- *
1189
- * Note that, while this can become complicated to do by hand for complex or
1190
- * deeply nested queries, it provides a formalized expression tree API for
1191
- * external libraries that implement a parser for custom query languages.
1192
- *
1193
- * @param query Search query
1194
- * @param searchOptions Search options. Each option, if not given, defaults to the corresponding value of `searchOptions` given to the constructor, or to the library default.
1195
- */
1196
- search(query, searchOptions = {}) {
1197
- const { searchOptions: globalSearchOptions } = this._options;
1198
- const searchOptionsWithDefaults = {
1199
- ...globalSearchOptions,
1200
- ...searchOptions,
1201
- };
1202
- const rawResults = this.executeQuery(query, searchOptions);
1203
- const results = [];
1204
- for (const [docId, { score, terms, match }] of rawResults) {
1205
- const quality = terms.length || 1;
1206
- const result = {
1207
- id: this._documentIds.get(docId),
1208
- score: score * quality,
1209
- terms: Object.keys(match),
1210
- queryTerms: terms,
1211
- match,
1212
- };
1213
- Object.assign(result, this._storedFields.get(docId));
1214
- if (
1215
- searchOptionsWithDefaults.filter == null ||
1216
- searchOptionsWithDefaults.filter(result)
1217
- ) {
1218
- results.push(result);
1219
- }
1220
- }
1221
- if (
1222
- query === _MiniSearch.wildcard &&
1223
- searchOptionsWithDefaults.boostDocument == null
1224
- ) {
1225
- return results;
1226
- }
1227
- results.sort(byScore);
1228
- return results;
1229
- }
1230
- /**
1231
- * Provide suggestions for the given search query
1232
- *
1233
- * The result is a list of suggested modified search queries, derived from the
1234
- * given search query, each with a relevance score, sorted by descending score.
1235
- *
1236
- * By default, it uses the same options used for search, except that by
1237
- * default it performs prefix search on the last term of the query, and
1238
- * combine terms with `'AND'` (requiring all query terms to match). Custom
1239
- * options can be passed as a second argument. Defaults can be changed upon
1240
- * calling the {@link MiniSearch} constructor, by passing a
1241
- * `autoSuggestOptions` option.
1242
- *
1243
- * ### Basic usage:
1244
- *
1245
- * ```javascript
1246
- * // Get suggestions for 'neuro':
1247
- * miniSearch.autoSuggest('neuro')
1248
- * // => [ { suggestion: 'neuromancer', terms: [ 'neuromancer' ], score: 0.46240 } ]
1249
- * ```
1250
- *
1251
- * ### Multiple words:
1252
- *
1253
- * ```javascript
1254
- * // Get suggestions for 'zen ar':
1255
- * miniSearch.autoSuggest('zen ar')
1256
- * // => [
1257
- * // { suggestion: 'zen archery art', terms: [ 'zen', 'archery', 'art' ], score: 1.73332 },
1258
- * // { suggestion: 'zen art', terms: [ 'zen', 'art' ], score: 1.21313 }
1259
- * // ]
1260
- * ```
1261
- *
1262
- * ### Fuzzy suggestions:
1263
- *
1264
- * ```javascript
1265
- * // Correct spelling mistakes using fuzzy search:
1266
- * miniSearch.autoSuggest('neromancer', { fuzzy: 0.2 })
1267
- * // => [ { suggestion: 'neuromancer', terms: [ 'neuromancer' ], score: 1.03998 } ]
1268
- * ```
1269
- *
1270
- * ### Filtering:
1271
- *
1272
- * ```javascript
1273
- * // Get suggestions for 'zen ar', but only within the 'fiction' category
1274
- * // (assuming that 'category' is a stored field):
1275
- * miniSearch.autoSuggest('zen ar', {
1276
- * filter: (result) => result.category === 'fiction'
1277
- * })
1278
- * // => [
1279
- * // { suggestion: 'zen archery art', terms: [ 'zen', 'archery', 'art' ], score: 1.73332 },
1280
- * // { suggestion: 'zen art', terms: [ 'zen', 'art' ], score: 1.21313 }
1281
- * // ]
1282
- * ```
1283
- *
1284
- * @param queryString Query string to be expanded into suggestions
1285
- * @param options Search options. The supported options and default values
1286
- * are the same as for the {@link MiniSearch#search} method, except that by
1287
- * default prefix search is performed on the last term in the query, and terms
1288
- * are combined with `'AND'`.
1289
- * @return A sorted array of suggestions sorted by relevance score.
1290
- */
1291
- autoSuggest(queryString, options = {}) {
1292
- options = { ...this._options.autoSuggestOptions, ...options };
1293
- const suggestions = /* @__PURE__ */ new Map();
1294
- for (const { score, terms } of this.search(queryString, options)) {
1295
- const phrase = terms.join(" ");
1296
- const suggestion = suggestions.get(phrase);
1297
- if (suggestion != null) {
1298
- suggestion.score += score;
1299
- suggestion.count += 1;
1300
- } else {
1301
- suggestions.set(phrase, { score, terms, count: 1 });
1302
- }
1303
- }
1304
- const results = [];
1305
- for (const [suggestion, { score, terms, count }] of suggestions) {
1306
- results.push({ suggestion, terms, score: score / count });
1307
- }
1308
- results.sort(byScore);
1309
- return results;
1310
- }
1311
- /**
1312
- * Total number of documents available to search
1313
- */
1314
- get documentCount() {
1315
- return this._documentCount;
1316
- }
1317
- /**
1318
- * Number of terms in the index
1319
- */
1320
- get termCount() {
1321
- return this._index.size;
1322
- }
1323
- /**
1324
- * Deserializes a JSON index (serialized with `JSON.stringify(miniSearch)`)
1325
- * and instantiates a MiniSearch instance. It should be given the same options
1326
- * originally used when serializing the index.
1327
- *
1328
- * ### Usage:
1329
- *
1330
- * ```javascript
1331
- * // If the index was serialized with:
1332
- * let miniSearch = new MiniSearch({ fields: ['title', 'text'] })
1333
- * miniSearch.addAll(documents)
1334
- *
1335
- * const json = JSON.stringify(miniSearch)
1336
- * // It can later be deserialized like this:
1337
- * miniSearch = MiniSearch.loadJSON(json, { fields: ['title', 'text'] })
1338
- * ```
1339
- *
1340
- * @param json JSON-serialized index
1341
- * @param options configuration options, same as the constructor
1342
- * @return An instance of MiniSearch deserialized from the given JSON.
1343
- */
1344
- static loadJSON(json, options) {
1345
- if (options == null) {
1346
- throw new Error(
1347
- "MiniSearch: loadJSON should be given the same options used when serializing the index",
1348
- );
1349
- }
1350
- return this.loadJS(JSON.parse(json), options);
1351
- }
1352
- /**
1353
- * Async equivalent of {@link MiniSearch.loadJSON}
1354
- *
1355
- * This function is an alternative to {@link MiniSearch.loadJSON} that returns
1356
- * a promise, and loads the index in batches, leaving pauses between them to avoid
1357
- * blocking the main thread. It tends to be slower than the synchronous
1358
- * version, but does not block the main thread, so it can be a better choice
1359
- * when deserializing very large indexes.
1360
- *
1361
- * @param json JSON-serialized index
1362
- * @param options configuration options, same as the constructor
1363
- * @return A Promise that will resolve to an instance of MiniSearch deserialized from the given JSON.
1364
- */
1365
- static async loadJSONAsync(json, options) {
1366
- if (options == null) {
1367
- throw new Error(
1368
- "MiniSearch: loadJSON should be given the same options used when serializing the index",
1369
- );
1370
- }
1371
- return this.loadJSAsync(JSON.parse(json), options);
1372
- }
1373
- /**
1374
- * Returns the default value of an option. It will throw an error if no option
1375
- * with the given name exists.
1376
- *
1377
- * @param optionName Name of the option
1378
- * @return The default value of the given option
1379
- *
1380
- * ### Usage:
1381
- *
1382
- * ```javascript
1383
- * // Get default tokenizer
1384
- * MiniSearch.getDefault('tokenize')
1385
- *
1386
- * // Get default term processor
1387
- * MiniSearch.getDefault('processTerm')
1388
- *
1389
- * // Unknown options will throw an error
1390
- * MiniSearch.getDefault('notExisting')
1391
- * // => throws 'MiniSearch: unknown option "notExisting"'
1392
- * ```
1393
- */
1394
- static getDefault(optionName) {
1395
- if (defaultOptions.hasOwnProperty(optionName)) {
1396
- return getOwnProperty(defaultOptions, optionName);
1397
- } else {
1398
- throw new Error(`MiniSearch: unknown option "${optionName}"`);
1399
- }
1400
- }
1401
- /**
1402
- * @ignore
1403
- */
1404
- static loadJS(js, options) {
1405
- const {
1406
- index,
1407
- documentIds,
1408
- fieldLength,
1409
- storedFields,
1410
- serializationVersion,
1411
- } = js;
1412
- const miniSearch = this.instantiateMiniSearch(js, options);
1413
- miniSearch._documentIds = objectToNumericMap(documentIds);
1414
- miniSearch._fieldLength = objectToNumericMap(fieldLength);
1415
- miniSearch._storedFields = objectToNumericMap(storedFields);
1416
- for (const [shortId, id] of miniSearch._documentIds) {
1417
- miniSearch._idToShortId.set(id, shortId);
1418
- }
1419
- for (const [term, data] of index) {
1420
- const dataMap = /* @__PURE__ */ new Map();
1421
- for (const fieldId of Object.keys(data)) {
1422
- let indexEntry = data[fieldId];
1423
- if (serializationVersion === 1) {
1424
- indexEntry = indexEntry.ds;
1425
- }
1426
- dataMap.set(parseInt(fieldId, 10), objectToNumericMap(indexEntry));
1427
- }
1428
- miniSearch._index.set(term, dataMap);
1429
- }
1430
- return miniSearch;
1431
- }
1432
- /**
1433
- * @ignore
1434
- */
1435
- static async loadJSAsync(js, options) {
1436
- const {
1437
- index,
1438
- documentIds,
1439
- fieldLength,
1440
- storedFields,
1441
- serializationVersion,
1442
- } = js;
1443
- const miniSearch = this.instantiateMiniSearch(js, options);
1444
- miniSearch._documentIds = await objectToNumericMapAsync(documentIds);
1445
- miniSearch._fieldLength = await objectToNumericMapAsync(fieldLength);
1446
- miniSearch._storedFields = await objectToNumericMapAsync(storedFields);
1447
- for (const [shortId, id] of miniSearch._documentIds) {
1448
- miniSearch._idToShortId.set(id, shortId);
1449
- }
1450
- let count = 0;
1451
- for (const [term, data] of index) {
1452
- const dataMap = /* @__PURE__ */ new Map();
1453
- for (const fieldId of Object.keys(data)) {
1454
- let indexEntry = data[fieldId];
1455
- if (serializationVersion === 1) {
1456
- indexEntry = indexEntry.ds;
1457
- }
1458
- dataMap.set(
1459
- parseInt(fieldId, 10),
1460
- await objectToNumericMapAsync(indexEntry),
1461
- );
1462
- }
1463
- if (++count % 1e3 === 0) await wait(0);
1464
- miniSearch._index.set(term, dataMap);
1465
- }
1466
- return miniSearch;
1467
- }
1468
- /**
1469
- * @ignore
1470
- */
1471
- static instantiateMiniSearch(js, options) {
1472
- const {
1473
- documentCount,
1474
- nextId,
1475
- fieldIds,
1476
- averageFieldLength,
1477
- dirtCount,
1478
- serializationVersion,
1479
- } = js;
1480
- if (serializationVersion !== 1 && serializationVersion !== 2) {
1481
- throw new Error(
1482
- "MiniSearch: cannot deserialize an index created with an incompatible version",
1483
- );
1484
- }
1485
- const miniSearch = new _MiniSearch(options);
1486
- miniSearch._documentCount = documentCount;
1487
- miniSearch._nextId = nextId;
1488
- miniSearch._idToShortId = /* @__PURE__ */ new Map();
1489
- miniSearch._fieldIds = fieldIds;
1490
- miniSearch._avgFieldLength = averageFieldLength;
1491
- miniSearch._dirtCount = dirtCount || 0;
1492
- miniSearch._index = new SearchableMap();
1493
- return miniSearch;
1494
- }
1495
- /**
1496
- * @ignore
1497
- */
1498
- executeQuery(query, searchOptions = {}) {
1499
- if (query === _MiniSearch.wildcard) {
1500
- return this.executeWildcardQuery(searchOptions);
1501
- }
1502
- if (typeof query !== "string") {
1503
- const options2 = { ...searchOptions, ...query, queries: void 0 };
1504
- const results2 = query.queries.map((subquery) =>
1505
- this.executeQuery(subquery, options2),
1506
- );
1507
- return this.combineResults(results2, options2.combineWith);
1508
- }
1509
- const {
1510
- tokenize,
1511
- processTerm,
1512
- searchOptions: globalSearchOptions,
1513
- } = this._options;
1514
- const options = {
1515
- tokenize,
1516
- processTerm,
1517
- ...globalSearchOptions,
1518
- ...searchOptions,
1519
- };
1520
- const { tokenize: searchTokenize, processTerm: searchProcessTerm } =
1521
- options;
1522
- const terms = searchTokenize(query)
1523
- .flatMap((term) => searchProcessTerm(term))
1524
- .filter((term) => !!term);
1525
- const queries = terms.map(termToQuerySpec(options));
1526
- const results = queries.map((query2) =>
1527
- this.executeQuerySpec(query2, options),
1528
- );
1529
- return this.combineResults(results, options.combineWith);
1530
- }
1531
- /**
1532
- * @ignore
1533
- */
1534
- executeQuerySpec(query, searchOptions) {
1535
- const options = { ...this._options.searchOptions, ...searchOptions };
1536
- const boosts = (options.fields || this._options.fields).reduce(
1537
- (boosts2, field) => ({
1538
- ...boosts2,
1539
- [field]: getOwnProperty(options.boost, field) || 1,
1540
- }),
1541
- {},
1542
- );
1543
- const { boostDocument, weights, maxFuzzy, bm25: bm25params } = options;
1544
- const { fuzzy: fuzzyWeight, prefix: prefixWeight } = {
1545
- ...defaultSearchOptions.weights,
1546
- ...weights,
1547
- };
1548
- const data = this._index.get(query.term);
1549
- const results = this.termResults(
1550
- query.term,
1551
- query.term,
1552
- 1,
1553
- query.termBoost,
1554
- data,
1555
- boosts,
1556
- boostDocument,
1557
- bm25params,
1558
- );
1559
- let prefixMatches;
1560
- let fuzzyMatches;
1561
- if (query.prefix) {
1562
- prefixMatches = this._index.atPrefix(query.term);
1563
- }
1564
- if (query.fuzzy) {
1565
- const fuzzy = query.fuzzy === true ? 0.2 : query.fuzzy;
1566
- const maxDistance =
1567
- fuzzy < 1
1568
- ? Math.min(maxFuzzy, Math.round(query.term.length * fuzzy))
1569
- : fuzzy;
1570
- if (maxDistance)
1571
- fuzzyMatches = this._index.fuzzyGet(query.term, maxDistance);
1572
- }
1573
- if (prefixMatches) {
1574
- for (const [term, data2] of prefixMatches) {
1575
- const distance = term.length - query.term.length;
1576
- if (!distance) {
1577
- continue;
1578
- }
1579
- fuzzyMatches === null || fuzzyMatches === void 0
1580
- ? void 0
1581
- : fuzzyMatches.delete(term);
1582
- const weight =
1583
- (prefixWeight * term.length) / (term.length + 0.3 * distance);
1584
- this.termResults(
1585
- query.term,
1586
- term,
1587
- weight,
1588
- query.termBoost,
1589
- data2,
1590
- boosts,
1591
- boostDocument,
1592
- bm25params,
1593
- results,
1594
- );
1595
- }
1596
- }
1597
- if (fuzzyMatches) {
1598
- for (const term of fuzzyMatches.keys()) {
1599
- const [data2, distance] = fuzzyMatches.get(term);
1600
- if (!distance) {
1601
- continue;
1602
- }
1603
- const weight = (fuzzyWeight * term.length) / (term.length + distance);
1604
- this.termResults(
1605
- query.term,
1606
- term,
1607
- weight,
1608
- query.termBoost,
1609
- data2,
1610
- boosts,
1611
- boostDocument,
1612
- bm25params,
1613
- results,
1614
- );
1615
- }
1616
- }
1617
- return results;
1618
- }
1619
- /**
1620
- * @ignore
1621
- */
1622
- executeWildcardQuery(searchOptions) {
1623
- const results = /* @__PURE__ */ new Map();
1624
- const options = { ...this._options.searchOptions, ...searchOptions };
1625
- for (const [shortId, id] of this._documentIds) {
1626
- const score = options.boostDocument
1627
- ? options.boostDocument(id, "", this._storedFields.get(shortId))
1628
- : 1;
1629
- results.set(shortId, {
1630
- score,
1631
- terms: [],
1632
- match: {},
1633
- });
1634
- }
1635
- return results;
1636
- }
1637
- /**
1638
- * @ignore
1639
- */
1640
- combineResults(results, combineWith = OR) {
1641
- if (results.length === 0) {
1642
- return /* @__PURE__ */ new Map();
1643
- }
1644
- const operator = combineWith.toLowerCase();
1645
- const combinator = combinators[operator];
1646
- if (!combinator) {
1647
- throw new Error(`Invalid combination operator: ${combineWith}`);
1648
- }
1649
- return results.reduce(combinator) || /* @__PURE__ */ new Map();
1650
- }
1651
- /**
1652
- * Allows serialization of the index to JSON, to possibly store it and later
1653
- * deserialize it with {@link MiniSearch.loadJSON}.
1654
- *
1655
- * Normally one does not directly call this method, but rather call the
1656
- * standard JavaScript `JSON.stringify()` passing the {@link MiniSearch}
1657
- * instance, and JavaScript will internally call this method. Upon
1658
- * deserialization, one must pass to {@link MiniSearch.loadJSON} the same
1659
- * options used to create the original instance that was serialized.
1660
- *
1661
- * ### Usage:
1662
- *
1663
- * ```javascript
1664
- * // Serialize the index:
1665
- * let miniSearch = new MiniSearch({ fields: ['title', 'text'] })
1666
- * miniSearch.addAll(documents)
1667
- * const json = JSON.stringify(miniSearch)
1668
- *
1669
- * // Later, to deserialize it:
1670
- * miniSearch = MiniSearch.loadJSON(json, { fields: ['title', 'text'] })
1671
- * ```
1672
- *
1673
- * @return A plain-object serializable representation of the search index.
1674
- */
1675
- toJSON() {
1676
- const index = [];
1677
- for (const [term, fieldIndex] of this._index) {
1678
- const data = {};
1679
- for (const [fieldId, freqs] of fieldIndex) {
1680
- data[fieldId] = Object.fromEntries(freqs);
1681
- }
1682
- index.push([term, data]);
1683
- }
1684
- return {
1685
- documentCount: this._documentCount,
1686
- nextId: this._nextId,
1687
- documentIds: Object.fromEntries(this._documentIds),
1688
- fieldIds: this._fieldIds,
1689
- fieldLength: Object.fromEntries(this._fieldLength),
1690
- averageFieldLength: this._avgFieldLength,
1691
- storedFields: Object.fromEntries(this._storedFields),
1692
- dirtCount: this._dirtCount,
1693
- index,
1694
- serializationVersion: 2,
1695
- };
1696
- }
1697
- /**
1698
- * @ignore
1699
- */
1700
- termResults(
1701
- sourceTerm,
1702
- derivedTerm,
1703
- termWeight,
1704
- termBoost,
1705
- fieldTermData,
1706
- fieldBoosts,
1707
- boostDocumentFn,
1708
- bm25params,
1709
- results = /* @__PURE__ */ new Map(),
1710
- ) {
1711
- if (fieldTermData == null) return results;
1712
- for (const field of Object.keys(fieldBoosts)) {
1713
- const fieldBoost = fieldBoosts[field];
1714
- const fieldId = this._fieldIds[field];
1715
- const fieldTermFreqs = fieldTermData.get(fieldId);
1716
- if (fieldTermFreqs == null) continue;
1717
- let matchingFields = fieldTermFreqs.size;
1718
- const avgFieldLength = this._avgFieldLength[fieldId];
1719
- for (const docId of fieldTermFreqs.keys()) {
1720
- if (!this._documentIds.has(docId)) {
1721
- this.removeTerm(fieldId, docId, derivedTerm);
1722
- matchingFields -= 1;
1723
- continue;
1724
- }
1725
- const docBoost = boostDocumentFn
1726
- ? boostDocumentFn(
1727
- this._documentIds.get(docId),
1728
- derivedTerm,
1729
- this._storedFields.get(docId),
1730
- )
1731
- : 1;
1732
- if (!docBoost) continue;
1733
- const termFreq = fieldTermFreqs.get(docId);
1734
- const fieldLength = this._fieldLength.get(docId)[fieldId];
1735
- const rawScore = calcBM25Score(
1736
- termFreq,
1737
- matchingFields,
1738
- this._documentCount,
1739
- fieldLength,
1740
- avgFieldLength,
1741
- bm25params,
1742
- );
1743
- const weightedScore =
1744
- termWeight * termBoost * fieldBoost * docBoost * rawScore;
1745
- const result = results.get(docId);
1746
- if (result) {
1747
- result.score += weightedScore;
1748
- assignUniqueTerm(result.terms, sourceTerm);
1749
- const match = getOwnProperty(result.match, derivedTerm);
1750
- if (match) {
1751
- match.push(field);
1752
- } else {
1753
- result.match[derivedTerm] = [field];
1754
- }
1755
- } else {
1756
- results.set(docId, {
1757
- score: weightedScore,
1758
- terms: [sourceTerm],
1759
- match: { [derivedTerm]: [field] },
1760
- });
1761
- }
1762
- }
1763
- }
1764
- return results;
1765
- }
1766
- /**
1767
- * @ignore
1768
- */
1769
- addTerm(fieldId, documentId, term) {
1770
- const indexData = this._index.fetch(term, createMap);
1771
- let fieldIndex = indexData.get(fieldId);
1772
- if (fieldIndex == null) {
1773
- fieldIndex = /* @__PURE__ */ new Map();
1774
- fieldIndex.set(documentId, 1);
1775
- indexData.set(fieldId, fieldIndex);
1776
- } else {
1777
- const docs = fieldIndex.get(documentId);
1778
- fieldIndex.set(documentId, (docs || 0) + 1);
1779
- }
1780
- }
1781
- /**
1782
- * @ignore
1783
- */
1784
- removeTerm(fieldId, documentId, term) {
1785
- if (!this._index.has(term)) {
1786
- this.warnDocumentChanged(documentId, fieldId, term);
1787
- return;
1788
- }
1789
- const indexData = this._index.fetch(term, createMap);
1790
- const fieldIndex = indexData.get(fieldId);
1791
- if (fieldIndex == null || fieldIndex.get(documentId) == null) {
1792
- this.warnDocumentChanged(documentId, fieldId, term);
1793
- } else if (fieldIndex.get(documentId) <= 1) {
1794
- if (fieldIndex.size <= 1) {
1795
- indexData.delete(fieldId);
1796
- } else {
1797
- fieldIndex.delete(documentId);
1798
- }
1799
- } else {
1800
- fieldIndex.set(documentId, fieldIndex.get(documentId) - 1);
1801
- }
1802
- if (this._index.get(term).size === 0) {
1803
- this._index.delete(term);
1804
- }
1805
- }
1806
- /**
1807
- * @ignore
1808
- */
1809
- warnDocumentChanged(shortDocumentId, fieldId, term) {
1810
- for (const fieldName of Object.keys(this._fieldIds)) {
1811
- if (this._fieldIds[fieldName] === fieldId) {
1812
- this._options.logger(
1813
- "warn",
1814
- `MiniSearch: document with ID ${this._documentIds.get(shortDocumentId)} has changed before removal: term "${term}" was not present in field "${fieldName}". Removing a document after it has changed can corrupt the index!`,
1815
- "version_conflict",
1816
- );
1817
- return;
1818
- }
1819
- }
1820
- }
1821
- /**
1822
- * @ignore
1823
- */
1824
- addDocumentId(documentId) {
1825
- const shortDocumentId = this._nextId;
1826
- this._idToShortId.set(documentId, shortDocumentId);
1827
- this._documentIds.set(shortDocumentId, documentId);
1828
- this._documentCount += 1;
1829
- this._nextId += 1;
1830
- return shortDocumentId;
1831
- }
1832
- /**
1833
- * @ignore
1834
- */
1835
- addFields(fields) {
1836
- for (let i = 0; i < fields.length; i++) {
1837
- this._fieldIds[fields[i]] = i;
1838
- }
1839
- }
1840
- /**
1841
- * @ignore
1842
- */
1843
- addFieldLength(documentId, fieldId, count, length) {
1844
- let fieldLengths = this._fieldLength.get(documentId);
1845
- if (fieldLengths == null)
1846
- this._fieldLength.set(documentId, (fieldLengths = []));
1847
- fieldLengths[fieldId] = length;
1848
- const averageFieldLength = this._avgFieldLength[fieldId] || 0;
1849
- const totalFieldLength = averageFieldLength * count + length;
1850
- this._avgFieldLength[fieldId] = totalFieldLength / (count + 1);
1851
- }
1852
- /**
1853
- * @ignore
1854
- */
1855
- removeFieldLength(documentId, fieldId, count, length) {
1856
- if (count === 1) {
1857
- this._avgFieldLength[fieldId] = 0;
1858
- return;
1859
- }
1860
- const totalFieldLength = this._avgFieldLength[fieldId] * count - length;
1861
- this._avgFieldLength[fieldId] = totalFieldLength / (count - 1);
1862
- }
1863
- /**
1864
- * @ignore
1865
- */
1866
- saveStoredFields(documentId, doc) {
1867
- const { storeFields, extractField } = this._options;
1868
- if (storeFields == null || storeFields.length === 0) {
1869
- return;
1870
- }
1871
- let documentFields = this._storedFields.get(documentId);
1872
- if (documentFields == null)
1873
- this._storedFields.set(documentId, (documentFields = {}));
1874
- for (const fieldName of storeFields) {
1875
- const fieldValue = extractField(doc, fieldName);
1876
- if (fieldValue !== void 0) documentFields[fieldName] = fieldValue;
1877
- }
1878
- }
1879
- };
1880
- MiniSearch.wildcard = Symbol("*");
1881
- var getOwnProperty = (object, property) =>
1882
- Object.prototype.hasOwnProperty.call(object, property)
1883
- ? object[property]
1884
- : void 0;
1885
- var combinators = {
1886
- [OR]: (a, b) => {
1887
- for (const docId of b.keys()) {
1888
- const existing = a.get(docId);
1889
- if (existing == null) {
1890
- a.set(docId, b.get(docId));
1891
- } else {
1892
- const { score, terms, match } = b.get(docId);
1893
- existing.score = existing.score + score;
1894
- existing.match = Object.assign(existing.match, match);
1895
- assignUniqueTerms(existing.terms, terms);
1896
- }
1897
- }
1898
- return a;
1899
- },
1900
- [AND]: (a, b) => {
1901
- const combined = /* @__PURE__ */ new Map();
1902
- for (const docId of b.keys()) {
1903
- const existing = a.get(docId);
1904
- if (existing == null) continue;
1905
- const { score, terms, match } = b.get(docId);
1906
- assignUniqueTerms(existing.terms, terms);
1907
- combined.set(docId, {
1908
- score: existing.score + score,
1909
- terms: existing.terms,
1910
- match: Object.assign(existing.match, match),
1911
- });
1912
- }
1913
- return combined;
1914
- },
1915
- [AND_NOT]: (a, b) => {
1916
- for (const docId of b.keys()) a.delete(docId);
1917
- return a;
1918
- },
1919
- };
1920
- var defaultBM25params = { k: 1.2, b: 0.7, d: 0.5 };
1921
- var calcBM25Score = (
1922
- termFreq,
1923
- matchingCount,
1924
- totalCount,
1925
- fieldLength,
1926
- avgFieldLength,
1927
- bm25params,
1928
- ) => {
1929
- const { k, b, d } = bm25params;
1930
- const invDocFreq = Math.log(
1931
- 1 + (totalCount - matchingCount + 0.5) / (matchingCount + 0.5),
1932
- );
1933
- return (
1934
- invDocFreq *
1935
- (d +
1936
- (termFreq * (k + 1)) /
1937
- (termFreq + k * (1 - b + (b * fieldLength) / avgFieldLength)))
1938
- );
1939
- };
1940
- var termToQuerySpec = (options) => (term, i, terms) => {
1941
- const fuzzy =
1942
- typeof options.fuzzy === "function"
1943
- ? options.fuzzy(term, i, terms)
1944
- : options.fuzzy || false;
1945
- const prefix =
1946
- typeof options.prefix === "function"
1947
- ? options.prefix(term, i, terms)
1948
- : options.prefix === true;
1949
- const termBoost =
1950
- typeof options.boostTerm === "function"
1951
- ? options.boostTerm(term, i, terms)
1952
- : 1;
1953
- return { term, fuzzy, prefix, termBoost };
1954
- };
1955
- var defaultOptions = {
1956
- idField: "id",
1957
- extractField: (document, fieldName) => document[fieldName],
1958
- tokenize: (text) => text.split(SPACE_OR_PUNCTUATION),
1959
- processTerm: (term) => term.toLowerCase(),
1960
- fields: void 0,
1961
- searchOptions: void 0,
1962
- storeFields: [],
1963
- logger: (level, message) => {
1964
- if (
1965
- typeof (console === null || console === void 0
1966
- ? void 0
1967
- : console[level]) === "function"
1968
- )
1969
- console[level](message);
1970
- },
1971
- autoVacuum: true,
1972
- };
1973
- var defaultSearchOptions = {
1974
- combineWith: OR,
1975
- prefix: false,
1976
- fuzzy: false,
1977
- maxFuzzy: 6,
1978
- boost: {},
1979
- weights: { fuzzy: 0.45, prefix: 0.375 },
1980
- bm25: defaultBM25params,
1981
- };
1982
- var defaultAutoSuggestOptions = {
1983
- combineWith: AND,
1984
- prefix: (term, i, terms) => i === terms.length - 1,
1985
- };
1986
- var defaultVacuumOptions = { batchSize: 1e3, batchWait: 10 };
1987
- var defaultVacuumConditions = { minDirtFactor: 0.1, minDirtCount: 20 };
1988
- var defaultAutoVacuumOptions = {
1989
- ...defaultVacuumOptions,
1990
- ...defaultVacuumConditions,
1991
- };
1992
- var assignUniqueTerm = (target, term) => {
1993
- if (!target.includes(term)) target.push(term);
1994
- };
1995
- var assignUniqueTerms = (target, source) => {
1996
- for (const term of source) {
1997
- if (!target.includes(term)) target.push(term);
1998
- }
1999
- };
2000
- var byScore = ({ score: a }, { score: b }) => b - a;
2001
- var createMap = () => /* @__PURE__ */ new Map();
2002
- var objectToNumericMap = (object) => {
2003
- const map = /* @__PURE__ */ new Map();
2004
- for (const key of Object.keys(object)) {
2005
- map.set(parseInt(key, 10), object[key]);
2006
- }
2007
- return map;
2008
- };
2009
- var objectToNumericMapAsync = async (object) => {
2010
- const map = /* @__PURE__ */ new Map();
2011
- let count = 0;
2012
- for (const key of Object.keys(object)) {
2013
- map.set(parseInt(key, 10), object[key]);
2014
- if (++count % 1e3 === 0) {
2015
- await wait(0);
2016
- }
2017
- }
2018
- return map;
2019
- };
2020
- var wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
2021
- var SPACE_OR_PUNCTUATION = /[\n\r\p{Z}\p{P}]+/u;
2022
- export { MiniSearch as default };
2023
- //# sourceMappingURL=vitepress___minisearch.js.map