@orchidjs/sifter 1.0.3 → 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 (41) hide show
  1. package/dist/cjs/package.json +1 -0
  2. package/dist/cjs/sifter.d.ts +72 -0
  3. package/dist/cjs/sifter.js +290 -1101
  4. package/dist/cjs/sifter.js.map +1 -1
  5. package/dist/cjs/types.d.ts +57 -0
  6. package/dist/cjs/types.js +3 -0
  7. package/dist/cjs/types.js.map +1 -0
  8. package/dist/cjs/utils.d.ts +48 -0
  9. package/dist/cjs/utils.js +102 -0
  10. package/dist/cjs/utils.js.map +1 -0
  11. package/dist/esm/sifter.d.ts +72 -0
  12. package/dist/esm/sifter.js +267 -330
  13. package/dist/esm/sifter.js.map +1 -1
  14. package/dist/esm/types.d.ts +57 -0
  15. package/dist/esm/types.js +2 -0
  16. package/dist/esm/types.js.map +1 -0
  17. package/dist/esm/utils.d.ts +48 -0
  18. package/dist/esm/utils.js +54 -56
  19. package/dist/esm/utils.js.map +1 -1
  20. package/dist/types/sifter.d.ts +3 -2
  21. package/dist/types/types.d.ts +12 -12
  22. package/dist/types/utils.d.ts +2 -2
  23. package/dist/umd/package.json +1 -0
  24. package/dist/umd/sifter.js +796 -1036
  25. package/dist/umd/sifter.js.map +1 -1
  26. package/dist/umd/sifter.min.js +56 -57
  27. package/dist/umd/sifter.min.js.map +1 -1
  28. package/lib/sifter.ts +3 -2
  29. package/lib/types.ts +1 -1
  30. package/lib/utils.ts +1 -1
  31. package/package.json +31 -21
  32. package/dist/esm/lib/sifter.js +0 -368
  33. package/dist/esm/lib/sifter.js.map +0 -1
  34. package/dist/esm/lib/utils.js +0 -95
  35. package/dist/esm/lib/utils.js.map +0 -1
  36. package/dist/esm/node_modules/@orchidjs/unicode-variants/dist/esm/index.js +0 -547
  37. package/dist/esm/node_modules/@orchidjs/unicode-variants/dist/esm/index.js.map +0 -1
  38. package/dist/esm/node_modules/@orchidjs/unicode-variants/dist/esm/regex.js +0 -113
  39. package/dist/esm/node_modules/@orchidjs/unicode-variants/dist/esm/regex.js.map +0 -1
  40. package/dist/esm/node_modules/@orchidjs/unicode-variants/dist/esm/strings.js +0 -29
  41. package/dist/esm/node_modules/@orchidjs/unicode-variants/dist/esm/strings.js.map +0 -1
@@ -1,774 +1,4 @@
1
- /*! sifter.js | https://github.com/orchidjs/sifter.js | Apache License (v2) */
2
- 'use strict';
3
-
4
- Object.defineProperty(exports, '__esModule', { value: true });
5
-
6
- /*! @orchidjs/unicode-variants | https://github.com/orchidjs/unicode-variants | Apache License (v2) */
7
-
8
- /**
9
- * Convert array of strings to a regular expression
10
- * ex ['ab','a'] => (?:ab|a)
11
- * ex ['a','b'] => [ab]
12
- * @param {string[]} chars
13
- * @return {string}
14
- */
15
- const arrayToPattern = chars => {
16
- chars = chars.filter(Boolean);
17
-
18
- if (chars.length < 2) {
19
- return chars[0] || '';
20
- }
21
-
22
- return maxValueLength(chars) == 1 ? '[' + chars.join('') + ']' : '(?:' + chars.join('|') + ')';
23
- };
24
- /**
25
- * @param {string[]} array
26
- * @return {string}
27
- */
28
-
29
-
30
- const sequencePattern = array => {
31
- if (!hasDuplicates(array)) {
32
- return array.join('');
33
- }
34
-
35
- let pattern = '';
36
- let prev_char_count = 0;
37
-
38
- const prev_pattern = () => {
39
- if (prev_char_count > 1) {
40
- pattern += '{' + prev_char_count + '}';
41
- }
42
- };
43
-
44
- array.forEach((char, i) => {
45
- if (char === array[i - 1]) {
46
- prev_char_count++;
47
- return;
48
- }
49
-
50
- prev_pattern();
51
- pattern += char;
52
- prev_char_count = 1;
53
- });
54
- prev_pattern();
55
- return pattern;
56
- };
57
- /**
58
- * Convert array of strings to a regular expression
59
- * ex ['ab','a'] => (?:ab|a)
60
- * ex ['a','b'] => [ab]
61
- * @param {Set<string>} chars
62
- * @return {string}
63
- */
64
-
65
-
66
- const setToPattern = chars => {
67
- let array = toArray(chars);
68
- return arrayToPattern(array);
69
- };
70
- /**
71
- *
72
- * https://stackoverflow.com/questions/7376598/in-javascript-how-do-i-check-if-an-array-has-duplicate-values
73
- * @param {any[]} array
74
- */
75
-
76
-
77
- const hasDuplicates = array => {
78
- return new Set(array).size !== array.length;
79
- };
80
- /**
81
- * https://stackoverflow.com/questions/63006601/why-does-u-throw-an-invalid-escape-error
82
- * @param {string} str
83
- * @return {string}
84
- */
85
-
86
-
87
- const escape_regex = str => {
88
- return (str + '').replace(/([\$\(-\+\.\?\[-\^\{-\}])/g, '\\$1');
89
- };
90
- /**
91
- * Return the max length of array values
92
- * @param {string[]} array
93
- *
94
- */
95
-
96
-
97
- const maxValueLength = array => {
98
- return array.reduce((longest, value) => Math.max(longest, unicodeLength(value)), 0);
99
- };
100
- /**
101
- * @param {string} str
102
- */
103
-
104
-
105
- const unicodeLength = str => {
106
- return toArray(str).length;
107
- };
108
- /**
109
- * @param {any} p
110
- * @return {any[]}
111
- */
112
-
113
-
114
- const toArray = p => Array.from(p);
115
-
116
- /*! @orchidjs/unicode-variants | https://github.com/orchidjs/unicode-variants | Apache License (v2) */
117
-
118
- /**
119
- * Get all possible combinations of substrings that add up to the given string
120
- * https://stackoverflow.com/questions/30169587/find-all-the-combination-of-substrings-that-add-up-to-the-given-string
121
- * @param {string} input
122
- * @return {string[][]}
123
- */
124
- const allSubstrings = input => {
125
- if (input.length === 1) return [[input]];
126
- /** @type {string[][]} */
127
-
128
- let result = [];
129
- const start = input.substring(1);
130
- const suba = allSubstrings(start);
131
- suba.forEach(function (subresult) {
132
- let tmp = subresult.slice(0);
133
- tmp[0] = input.charAt(0) + tmp[0];
134
- result.push(tmp);
135
- tmp = subresult.slice(0);
136
- tmp.unshift(input.charAt(0));
137
- result.push(tmp);
138
- });
139
- return result;
140
- };
141
-
142
- /*! @orchidjs/unicode-variants | https://github.com/orchidjs/unicode-variants | Apache License (v2) */
143
- /**
144
- * @typedef {{[key:string]:string}} TUnicodeMap
145
- * @typedef {{[key:string]:Set<string>}} TUnicodeSets
146
- * @typedef {[[number,number]]} TCodePoints
147
- * @typedef {{folded:string,composed:string,code_point:number}} TCodePointObj
148
- * @typedef {{start:number,end:number,length:number,substr:string}} TSequencePart
149
- */
150
-
151
- /** @type {TCodePoints} */
152
-
153
- const code_points = [[0, 65535]];
154
- const accent_pat = '[\u0300-\u036F\u{b7}\u{2be}\u{2bc}]';
155
- /** @type {TUnicodeMap} */
156
-
157
- let unicode_map;
158
- /** @type {RegExp} */
159
-
160
- let multi_char_reg;
161
- const max_char_length = 3;
162
- /** @type {TUnicodeMap} */
163
-
164
- const latin_convert = {};
165
- /** @type {TUnicodeMap} */
166
-
167
- const latin_condensed = {
168
- '/': '⁄∕',
169
- '0': '߀',
170
- "a": "ⱥɐɑ",
171
- "aa": "ꜳ",
172
- "ae": "æǽǣ",
173
- "ao": "ꜵ",
174
- "au": "ꜷ",
175
- "av": "ꜹꜻ",
176
- "ay": "ꜽ",
177
- "b": "ƀɓƃ",
178
- "c": "ꜿƈȼↄ",
179
- "d": "đɗɖᴅƌꮷԁɦ",
180
- "e": "ɛǝᴇɇ",
181
- "f": "ꝼƒ",
182
- "g": "ǥɠꞡᵹꝿɢ",
183
- "h": "ħⱨⱶɥ",
184
- "i": "ɨı",
185
- "j": "ɉȷ",
186
- "k": "ƙⱪꝁꝃꝅꞣ",
187
- "l": "łƚɫⱡꝉꝇꞁɭ",
188
- "m": "ɱɯϻ",
189
- "n": "ꞥƞɲꞑᴎлԉ",
190
- "o": "øǿɔɵꝋꝍᴑ",
191
- "oe": "œ",
192
- "oi": "ƣ",
193
- "oo": "ꝏ",
194
- "ou": "ȣ",
195
- "p": "ƥᵽꝑꝓꝕρ",
196
- "q": "ꝗꝙɋ",
197
- "r": "ɍɽꝛꞧꞃ",
198
- "s": "ßȿꞩꞅʂ",
199
- "t": "ŧƭʈⱦꞇ",
200
- "th": "þ",
201
- "tz": "ꜩ",
202
- "u": "ʉ",
203
- "v": "ʋꝟʌ",
204
- "vy": "ꝡ",
205
- "w": "ⱳ",
206
- "y": "ƴɏỿ",
207
- "z": "ƶȥɀⱬꝣ",
208
- "hv": "ƕ"
209
- };
210
-
211
- for (let latin in latin_condensed) {
212
- let unicode = latin_condensed[latin] || '';
213
-
214
- for (let i = 0; i < unicode.length; i++) {
215
- let char = unicode.substring(i, i + 1);
216
- latin_convert[char] = latin;
217
- }
218
- }
219
-
220
- const convert_pat = new RegExp(Object.keys(latin_convert).join('|') + '|' + accent_pat, 'gu');
221
- /**
222
- * Initialize the unicode_map from the give code point ranges
223
- *
224
- * @param {TCodePoints=} _code_points
225
- */
226
-
227
- const initialize = _code_points => {
228
- if (unicode_map !== undefined) return;
229
- unicode_map = generateMap(_code_points || code_points);
230
- };
231
- /**
232
- * Helper method for normalize a string
233
- * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize
234
- * @param {string} str
235
- * @param {string} form
236
- */
237
-
238
-
239
- const normalize = (str, form = 'NFKD') => str.normalize(form);
240
- /**
241
- * Remove accents without reordering string
242
- * calling str.normalize('NFKD') on \u{594}\u{595}\u{596} becomes \u{596}\u{594}\u{595}
243
- * via https://github.com/krisk/Fuse/issues/133#issuecomment-318692703
244
- * @param {string} str
245
- * @return {string}
246
- */
247
-
248
-
249
- const asciifold = str => {
250
- return toArray(str).reduce(
251
- /**
252
- * @param {string} result
253
- * @param {string} char
254
- */
255
- (result, char) => {
256
- return result + _asciifold(char);
257
- }, '');
258
- };
259
- /**
260
- * @param {string} str
261
- * @return {string}
262
- */
263
-
264
-
265
- const _asciifold = str => {
266
- str = normalize(str).toLowerCase().replace(convert_pat,
267
- /** @type {string} */
268
- char => {
269
- return latin_convert[char] || '';
270
- }); //return str;
271
-
272
- return normalize(str, 'NFC');
273
- };
274
- /**
275
- * Generate a list of unicode variants from the list of code points
276
- * @param {TCodePoints} code_points
277
- * @yield {TCodePointObj}
278
- */
279
-
280
-
281
- function* generator(code_points) {
282
- for (const [code_point_min, code_point_max] of code_points) {
283
- for (let i = code_point_min; i <= code_point_max; i++) {
284
- let composed = String.fromCharCode(i);
285
- let folded = asciifold(composed);
286
-
287
- if (folded == composed.toLowerCase()) {
288
- continue;
289
- } // skip when folded is a string longer than 3 characters long
290
- // bc the resulting regex patterns will be long
291
- // eg:
292
- // folded صلى الله عليه وسلم length 18 code point 65018
293
- // folded جل جلاله length 8 code point 65019
294
-
295
-
296
- if (folded.length > max_char_length) {
297
- continue;
298
- }
299
-
300
- if (folded.length == 0) {
301
- continue;
302
- }
303
-
304
- yield {
305
- folded: folded,
306
- composed: composed,
307
- code_point: i
308
- };
309
- }
310
- }
311
- }
312
- /**
313
- * Generate a unicode map from the list of code points
314
- * @param {TCodePoints} code_points
315
- * @return {TUnicodeSets}
316
- */
317
-
318
-
319
- const generateSets = code_points => {
320
- /** @type {{[key:string]:Set<string>}} */
321
- const unicode_sets = {};
322
- /**
323
- * @param {string} folded
324
- * @param {string} to_add
325
- */
326
-
327
- const addMatching = (folded, to_add) => {
328
- /** @type {Set<string>} */
329
- const folded_set = unicode_sets[folded] || new Set();
330
- const patt = new RegExp('^' + setToPattern(folded_set) + '$', 'iu');
331
-
332
- if (to_add.match(patt)) {
333
- return;
334
- }
335
-
336
- folded_set.add(escape_regex(to_add));
337
- unicode_sets[folded] = folded_set;
338
- };
339
-
340
- for (let value of generator(code_points)) {
341
- addMatching(value.folded, value.folded);
342
- addMatching(value.folded, value.composed);
343
- }
344
-
345
- return unicode_sets;
346
- };
347
- /**
348
- * Generate a unicode map from the list of code points
349
- * ae => (?:(?:ae|Æ|Ǽ|Ǣ)|(?:A|Ⓐ|A...)(?:E|ɛ|Ⓔ...))
350
- *
351
- * @param {TCodePoints} code_points
352
- * @return {TUnicodeMap}
353
- */
354
-
355
-
356
- const generateMap = code_points => {
357
- /** @type {TUnicodeSets} */
358
- const unicode_sets = generateSets(code_points);
359
- /** @type {TUnicodeMap} */
360
-
361
- const unicode_map = {};
362
- /** @type {string[]} */
363
-
364
- let multi_char = [];
365
-
366
- for (let folded in unicode_sets) {
367
- let set = unicode_sets[folded];
368
-
369
- if (set) {
370
- unicode_map[folded] = setToPattern(set);
371
- }
372
-
373
- if (folded.length > 1) {
374
- multi_char.push(escape_regex(folded));
375
- }
376
- }
377
-
378
- multi_char.sort((a, b) => b.length - a.length);
379
- const multi_char_patt = arrayToPattern(multi_char);
380
- multi_char_reg = new RegExp('^' + multi_char_patt, 'u');
381
- return unicode_map;
382
- };
383
- /**
384
- * Map each element of an array from it's folded value to all possible unicode matches
385
- * @param {string[]} strings
386
- * @param {number} min_replacement
387
- * @return {string}
388
- */
389
-
390
-
391
- const mapSequence = (strings, min_replacement = 1) => {
392
- let chars_replaced = 0;
393
- strings = strings.map(str => {
394
- if (unicode_map[str]) {
395
- chars_replaced += str.length;
396
- }
397
-
398
- return unicode_map[str] || str;
399
- });
400
-
401
- if (chars_replaced >= min_replacement) {
402
- return sequencePattern(strings);
403
- }
404
-
405
- return '';
406
- };
407
- /**
408
- * Convert a short string and split it into all possible patterns
409
- * Keep a pattern only if min_replacement is met
410
- *
411
- * 'abc'
412
- * => [['abc'],['ab','c'],['a','bc'],['a','b','c']]
413
- * => ['abc-pattern','ab-c-pattern'...]
414
- *
415
- *
416
- * @param {string} str
417
- * @param {number} min_replacement
418
- * @return {string}
419
- */
420
-
421
-
422
- const substringsToPattern = (str, min_replacement = 1) => {
423
- min_replacement = Math.max(min_replacement, str.length - 1);
424
- return arrayToPattern(allSubstrings(str).map(sub_pat => {
425
- return mapSequence(sub_pat, min_replacement);
426
- }));
427
- };
428
- /**
429
- * Convert an array of sequences into a pattern
430
- * [{start:0,end:3,length:3,substr:'iii'}...] => (?:iii...)
431
- *
432
- * @param {Sequence[]} sequences
433
- * @param {boolean} all
434
- */
435
-
436
-
437
- const sequencesToPattern = (sequences, all = true) => {
438
- let min_replacement = sequences.length > 1 ? 1 : 0;
439
- return arrayToPattern(sequences.map(sequence => {
440
- let seq = [];
441
- const len = all ? sequence.length() : sequence.length() - 1;
442
-
443
- for (let j = 0; j < len; j++) {
444
- seq.push(substringsToPattern(sequence.substrs[j] || '', min_replacement));
445
- }
446
-
447
- return sequencePattern(seq);
448
- }));
449
- };
450
- /**
451
- * Return true if the sequence is already in the sequences
452
- * @param {Sequence} needle_seq
453
- * @param {Sequence[]} sequences
454
- */
455
-
456
-
457
- const inSequences = (needle_seq, sequences) => {
458
- for (const seq of sequences) {
459
- if (seq.start != needle_seq.start || seq.end != needle_seq.end) {
460
- continue;
461
- }
462
-
463
- if (seq.substrs.join('') !== needle_seq.substrs.join('')) {
464
- continue;
465
- }
466
-
467
- let needle_parts = needle_seq.parts;
468
- /**
469
- * @param {TSequencePart} part
470
- */
471
-
472
- const filter = part => {
473
- for (const needle_part of needle_parts) {
474
- if (needle_part.start === part.start && needle_part.substr === part.substr) {
475
- return false;
476
- }
477
-
478
- if (part.length == 1 || needle_part.length == 1) {
479
- continue;
480
- } // check for overlapping parts
481
- // a = ['::=','==']
482
- // b = ['::','===']
483
- // a = ['r','sm']
484
- // b = ['rs','m']
485
-
486
-
487
- if (part.start < needle_part.start && part.end > needle_part.start) {
488
- return true;
489
- }
490
-
491
- if (needle_part.start < part.start && needle_part.end > part.start) {
492
- return true;
493
- }
494
- }
495
-
496
- return false;
497
- };
498
-
499
- let filtered = seq.parts.filter(filter);
500
-
501
- if (filtered.length > 0) {
502
- continue;
503
- }
504
-
505
- return true;
506
- }
507
-
508
- return false;
509
- };
510
-
511
- class Sequence {
512
- constructor() {
513
- /** @type {TSequencePart[]} */
514
- this.parts = [];
515
- /** @type {string[]} */
516
-
517
- this.substrs = [];
518
- this.start = 0;
519
- this.end = 0;
520
- }
521
- /**
522
- * @param {TSequencePart|undefined} part
523
- */
524
-
525
-
526
- add(part) {
527
- if (part) {
528
- this.parts.push(part);
529
- this.substrs.push(part.substr);
530
- this.start = Math.min(part.start, this.start);
531
- this.end = Math.max(part.end, this.end);
532
- }
533
- }
534
-
535
- last() {
536
- return this.parts[this.parts.length - 1];
537
- }
538
-
539
- length() {
540
- return this.parts.length;
541
- }
542
- /**
543
- * @param {number} position
544
- * @param {TSequencePart} last_piece
545
- */
546
-
547
-
548
- clone(position, last_piece) {
549
- let clone = new Sequence();
550
- let parts = JSON.parse(JSON.stringify(this.parts));
551
- let last_part = parts.pop();
552
-
553
- for (const part of parts) {
554
- clone.add(part);
555
- }
556
-
557
- let last_substr = last_piece.substr.substring(0, position - last_part.start);
558
- let clone_last_len = last_substr.length;
559
- clone.add({
560
- start: last_part.start,
561
- end: last_part.start + clone_last_len,
562
- length: clone_last_len,
563
- substr: last_substr
564
- });
565
- return clone;
566
- }
567
-
568
- }
569
- /**
570
- * Expand a regular expression pattern to include unicode variants
571
- * eg /a/ becomes /aⓐaẚàáâầấẫẩãāăằắẵẳȧǡäǟảåǻǎȁȃạậặḁąⱥɐɑAⒶAÀÁÂẦẤẪẨÃĀĂẰẮẴẲȦǠÄǞẢÅǺǍȀȂẠẬẶḀĄȺⱯ/
572
- *
573
- * Issue:
574
- * ﺊﺋ [ 'ﺊ = \\u{fe8a}', 'ﺋ = \\u{fe8b}' ]
575
- * becomes: ئئ [ 'ي = \\u{64a}', 'ٔ = \\u{654}', 'ي = \\u{64a}', 'ٔ = \\u{654}' ]
576
- *
577
- * İIJ = IIJ = ⅡJ
578
- *
579
- * 1/2/4
580
- *
581
- * @param {string} str
582
- * @return {string|undefined}
583
- */
584
-
585
-
586
- const getPattern = str => {
587
- initialize();
588
- str = asciifold(str);
589
- let pattern = '';
590
- let sequences = [new Sequence()];
591
-
592
- for (let i = 0; i < str.length; i++) {
593
- let substr = str.substring(i);
594
- let match = substr.match(multi_char_reg);
595
- const char = str.substring(i, i + 1);
596
- const match_str = match ? match[0] : null; // loop through sequences
597
- // add either the char or multi_match
598
-
599
- let overlapping = [];
600
- let added_types = new Set();
601
-
602
- for (const sequence of sequences) {
603
- const last_piece = sequence.last();
604
-
605
- if (!last_piece || last_piece.length == 1 || last_piece.end <= i) {
606
- // if we have a multi match
607
- if (match_str) {
608
- const len = match_str.length;
609
- sequence.add({
610
- start: i,
611
- end: i + len,
612
- length: len,
613
- substr: match_str
614
- });
615
- added_types.add('1');
616
- } else {
617
- sequence.add({
618
- start: i,
619
- end: i + 1,
620
- length: 1,
621
- substr: char
622
- });
623
- added_types.add('2');
624
- }
625
- } else if (match_str) {
626
- let clone = sequence.clone(i, last_piece);
627
- const len = match_str.length;
628
- clone.add({
629
- start: i,
630
- end: i + len,
631
- length: len,
632
- substr: match_str
633
- });
634
- overlapping.push(clone);
635
- } else {
636
- // don't add char
637
- // adding would create invalid patterns: 234 => [2,34,4]
638
- added_types.add('3');
639
- }
640
- } // if we have overlapping
641
-
642
-
643
- if (overlapping.length > 0) {
644
- // ['ii','iii'] before ['i','i','iii']
645
- overlapping = overlapping.sort((a, b) => {
646
- return a.length() - b.length();
647
- });
648
-
649
- for (let clone of overlapping) {
650
- // don't add if we already have an equivalent sequence
651
- if (inSequences(clone, sequences)) {
652
- continue;
653
- }
654
-
655
- sequences.push(clone);
656
- }
657
-
658
- continue;
659
- } // if we haven't done anything unique
660
- // clean up the patterns
661
- // helps keep patterns smaller
662
- // if str = 'r₨㎧aarss', pattern will be 446 instead of 655
663
-
664
-
665
- if (i > 0 && added_types.size == 1 && !added_types.has('3')) {
666
- pattern += sequencesToPattern(sequences, false);
667
- let new_seq = new Sequence();
668
- const old_seq = sequences[0];
669
-
670
- if (old_seq) {
671
- new_seq.add(old_seq.last());
672
- }
673
-
674
- sequences = [new_seq];
675
- }
676
- }
677
-
678
- pattern += sequencesToPattern(sequences, true);
679
- return pattern;
680
- };
681
-
682
- /**
683
- * A property getter resolving dot-notation
684
- * @param {Object} obj The root object to fetch property on
685
- * @param {String} name The optionally dotted property name to fetch
686
- * @return {Object} The resolved property value
687
- */
688
- const getAttr = (obj, name) => {
689
- if (!obj) return;
690
- return obj[name];
691
- };
692
- /**
693
- * A property getter resolving dot-notation
694
- * @param {Object} obj The root object to fetch property on
695
- * @param {String} name The optionally dotted property name to fetch
696
- * @return {Object} The resolved property value
697
- */
698
-
699
- const getAttrNesting = (obj, name) => {
700
- if (!obj) return;
701
- var part,
702
- names = name.split(".");
703
-
704
- while ((part = names.shift()) && (obj = obj[part]));
705
-
706
- return obj;
707
- };
708
- /**
709
- * Calculates how close of a match the
710
- * given value is against a search token.
711
- *
712
- */
713
-
714
- const scoreValue = (value, token, weight) => {
715
- var score, pos;
716
- if (!value) return 0;
717
- value = value + '';
718
- if (token.regex == null) return 0;
719
- pos = value.search(token.regex);
720
- if (pos === -1) return 0;
721
- score = token.string.length / value.length;
722
- if (pos === 0) score += 0.5;
723
- return score * weight;
724
- };
725
- /**
726
- * Cast object property to an array if it exists and has a value
727
- *
728
- */
729
-
730
- const propToArray = (obj, key) => {
731
- var value = obj[key];
732
- if (typeof value == 'function') return value;
733
-
734
- if (value && !Array.isArray(value)) {
735
- obj[key] = [value];
736
- }
737
- };
738
- /**
739
- * Iterates over arrays and hashes.
740
- *
741
- * ```
742
- * iterate(this.items, function(item, id) {
743
- * // invoked for each item
744
- * });
745
- * ```
746
- *
747
- */
748
-
749
- const iterate = (object, callback) => {
750
- if (Array.isArray(object)) {
751
- object.forEach(callback);
752
- } else {
753
- for (var key in object) {
754
- if (object.hasOwnProperty(key)) {
755
- callback(object[key], key);
756
- }
757
- }
758
- }
759
- };
760
- const cmp = (a, b) => {
761
- if (typeof a === 'number' && typeof b === 'number') {
762
- return a > b ? 1 : a < b ? -1 : 0;
763
- }
764
-
765
- a = asciifold(a + '').toLowerCase();
766
- b = asciifold(b + '').toLowerCase();
767
- if (a > b) return 1;
768
- if (b > a) return -1;
769
- return 0;
770
- };
771
-
1
+ "use strict";
772
2
  /**
773
3
  * sifter.js
774
4
  * Copyright (c) 2013–2020 Brian Reavis & contributors
@@ -784,356 +14,315 @@ const cmp = (a, b) => {
784
14
  *
785
15
  * @author Brian Reavis <brian@thirdroute.com>
786
16
  */
787
-
17
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
18
+ if (k2 === undefined) k2 = k;
19
+ var desc = Object.getOwnPropertyDescriptor(m, k);
20
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
21
+ desc = { enumerable: true, get: function() { return m[k]; } };
22
+ }
23
+ Object.defineProperty(o, k2, desc);
24
+ }) : (function(o, m, k, k2) {
25
+ if (k2 === undefined) k2 = k;
26
+ o[k2] = m[k];
27
+ }));
28
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
29
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
30
+ };
31
+ Object.defineProperty(exports, "__esModule", { value: true });
32
+ exports.getPattern = exports.cmp = exports.iterate = exports.propToArray = exports.getAttrNesting = exports.getAttr = exports.scoreValue = exports.Sifter = void 0;
33
+ const utils_ts_1 = require("./utils.js");
34
+ Object.defineProperty(exports, "scoreValue", { enumerable: true, get: function () { return utils_ts_1.scoreValue; } });
35
+ Object.defineProperty(exports, "getAttr", { enumerable: true, get: function () { return utils_ts_1.getAttr; } });
36
+ Object.defineProperty(exports, "getAttrNesting", { enumerable: true, get: function () { return utils_ts_1.getAttrNesting; } });
37
+ Object.defineProperty(exports, "propToArray", { enumerable: true, get: function () { return utils_ts_1.propToArray; } });
38
+ Object.defineProperty(exports, "iterate", { enumerable: true, get: function () { return utils_ts_1.iterate; } });
39
+ Object.defineProperty(exports, "cmp", { enumerable: true, get: function () { return utils_ts_1.cmp; } });
40
+ const unicode_variants_1 = require("@orchidjs/unicode-variants");
41
+ Object.defineProperty(exports, "getPattern", { enumerable: true, get: function () { return unicode_variants_1.getPattern; } });
788
42
  class Sifter {
789
- // []|{};
790
-
791
- /**
792
- * Textually searches arrays and hashes of objects
793
- * by property (or multiple properties). Designed
794
- * specifically for autocomplete.
795
- *
796
- */
797
- constructor(items, settings) {
798
- this.items = void 0;
799
- this.settings = void 0;
800
- this.items = items;
801
- this.settings = settings || {
802
- diacritics: true
803
- };
804
- }
805
-
806
- /**
807
- * Splits a search string into an array of individual
808
- * regexps to be used to match results.
809
- *
810
- */
811
- tokenize(query, respect_word_boundaries, weights) {
812
- if (!query || !query.length) return [];
813
- const tokens = [];
814
- const words = query.split(/\s+/);
815
- var field_regex;
816
-
817
- if (weights) {
818
- field_regex = new RegExp('^(' + Object.keys(weights).map(escape_regex).join('|') + ')\:(.*)$');
43
+ items; // []|{};
44
+ settings;
45
+ /**
46
+ * Textually searches arrays and hashes of objects
47
+ * by property (or multiple properties). Designed
48
+ * specifically for autocomplete.
49
+ *
50
+ */
51
+ constructor(items, settings) {
52
+ this.items = items;
53
+ this.settings = settings || { diacritics: true };
819
54
  }
820
-
821
- words.forEach(word => {
822
- let field_match;
823
- let field = null;
824
- let regex = null; // look for "field:query" tokens
825
-
826
- if (field_regex && (field_match = word.match(field_regex))) {
827
- field = field_match[1];
828
- word = field_match[2];
829
- }
830
-
831
- if (word.length > 0) {
832
- if (this.settings.diacritics) {
833
- regex = getPattern(word) || null;
834
- } else {
835
- regex = escape_regex(word);
55
+ ;
56
+ /**
57
+ * Splits a search string into an array of individual
58
+ * regexps to be used to match results.
59
+ *
60
+ */
61
+ tokenize(query, respect_word_boundaries, weights) {
62
+ if (!query || !query.length)
63
+ return [];
64
+ const tokens = [];
65
+ const words = query.split(/\s+/);
66
+ var field_regex;
67
+ if (weights) {
68
+ field_regex = new RegExp('^(' + Object.keys(weights).map(unicode_variants_1.escape_regex).join('|') + ')\:(.*)$');
836
69
  }
837
-
838
- if (regex && respect_word_boundaries) regex = "\\b" + regex;
839
- }
840
-
841
- tokens.push({
842
- string: word,
843
- regex: regex ? new RegExp(regex, 'iu') : null,
844
- field: field
845
- });
846
- });
847
- return tokens;
848
- }
849
-
850
- /**
851
- * Returns a function to be used to score individual results.
852
- *
853
- * Good matches will have a higher score than poor matches.
854
- * If an item is not a match, 0 will be returned by the function.
855
- *
856
- * @returns {T.ScoreFn}
857
- */
858
- getScoreFunction(query, options) {
859
- var search = this.prepareSearch(query, options);
860
- return this._getScoreFunction(search);
861
- }
862
- /**
863
- * @returns {T.ScoreFn}
864
- *
865
- */
866
-
867
-
868
- _getScoreFunction(search) {
869
- const tokens = search.tokens,
870
- token_count = tokens.length;
871
-
872
- if (!token_count) {
873
- return function () {
874
- return 0;
875
- };
70
+ words.forEach((word) => {
71
+ let field_match;
72
+ let field = null;
73
+ let regex = null;
74
+ // look for "field:query" tokens
75
+ if (field_regex && (field_match = word.match(field_regex))) {
76
+ field = field_match[1];
77
+ word = field_match[2];
78
+ }
79
+ if (word.length > 0) {
80
+ if (this.settings.diacritics) {
81
+ regex = (0, unicode_variants_1.getPattern)(word) || null;
82
+ }
83
+ else {
84
+ regex = (0, unicode_variants_1.escape_regex)(word);
85
+ }
86
+ if (regex && respect_word_boundaries)
87
+ regex = "\\b" + regex;
88
+ }
89
+ tokens.push({
90
+ string: word,
91
+ regex: regex ? new RegExp(regex, 'iu') : null,
92
+ field: field,
93
+ });
94
+ });
95
+ return tokens;
876
96
  }
877
-
878
- const fields = search.options.fields,
879
- weights = search.weights,
880
- field_count = fields.length,
881
- getAttrFn = search.getAttrFn;
882
-
883
- if (!field_count) {
884
- return function () {
885
- return 1;
886
- };
97
+ ;
98
+ /**
99
+ * Returns a function to be used to score individual results.
100
+ *
101
+ * Good matches will have a higher score than poor matches.
102
+ * If an item is not a match, 0 will be returned by the function.
103
+ *
104
+ * @returns {T.ScoreFn}
105
+ */
106
+ getScoreFunction(query, options) {
107
+ var search = this.prepareSearch(query, options);
108
+ return this._getScoreFunction(search);
887
109
  }
888
110
  /**
889
- * Calculates the score of an object
890
- * against the search query.
111
+ * @returns {T.ScoreFn}
891
112
  *
892
113
  */
893
-
894
-
895
- const scoreObject = function () {
896
- if (field_count === 1) {
897
- return function (token, data) {
898
- const field = fields[0].field;
899
- return scoreValue(getAttrFn(data, field), token, weights[field] || 1);
900
- };
901
- }
902
-
903
- return function (token, data) {
904
- var sum = 0; // is the token specific to a field?
905
-
906
- if (token.field) {
907
- const value = getAttrFn(data, token.field);
908
-
909
- if (!token.regex && value) {
910
- sum += 1 / field_count;
911
- } else {
912
- sum += scoreValue(value, token, 1);
913
- }
914
- } else {
915
- iterate(weights, (weight, field) => {
916
- sum += scoreValue(getAttrFn(data, field), token, weight);
917
- });
114
+ _getScoreFunction(search) {
115
+ const tokens = search.tokens, token_count = tokens.length;
116
+ if (!token_count) {
117
+ return function () { return 0; };
918
118
  }
919
-
920
- return sum / field_count;
921
- };
922
- }();
923
-
924
- if (token_count === 1) {
925
- return function (data) {
926
- return scoreObject(tokens[0], data);
927
- };
928
- }
929
-
930
- if (search.options.conjunction === 'and') {
931
- return function (data) {
932
- var score,
933
- sum = 0;
934
-
935
- for (let token of tokens) {
936
- score = scoreObject(token, data);
937
- if (score <= 0) return 0;
938
- sum += score;
119
+ const fields = search.options.fields, weights = search.weights, field_count = fields.length, getAttrFn = search.getAttrFn;
120
+ if (!field_count) {
121
+ return function () { return 1; };
122
+ }
123
+ /**
124
+ * Calculates the score of an object
125
+ * against the search query.
126
+ *
127
+ */
128
+ const scoreObject = (function () {
129
+ if (field_count === 1) {
130
+ return function (token, data) {
131
+ const field = fields[0].field;
132
+ return (0, utils_ts_1.scoreValue)(getAttrFn(data, field), token, weights[field] || 1);
133
+ };
134
+ }
135
+ return function (token, data) {
136
+ var sum = 0;
137
+ // is the token specific to a field?
138
+ if (token.field) {
139
+ const value = getAttrFn(data, token.field);
140
+ if (!token.regex && value) {
141
+ sum += (1 / field_count);
142
+ }
143
+ else {
144
+ sum += (0, utils_ts_1.scoreValue)(value, token, 1);
145
+ }
146
+ }
147
+ else {
148
+ (0, utils_ts_1.iterate)(weights, (weight, field) => {
149
+ sum += (0, utils_ts_1.scoreValue)(getAttrFn(data, field), token, weight);
150
+ });
151
+ }
152
+ return sum / field_count;
153
+ };
154
+ })();
155
+ if (token_count === 1) {
156
+ return function (data) {
157
+ return scoreObject(tokens[0], data);
158
+ };
159
+ }
160
+ if (search.options.conjunction === 'and') {
161
+ return function (data) {
162
+ var score, sum = 0;
163
+ for (let token of tokens) {
164
+ score = scoreObject(token, data);
165
+ if (score <= 0)
166
+ return 0;
167
+ sum += score;
168
+ }
169
+ return sum / token_count;
170
+ };
171
+ }
172
+ else {
173
+ return function (data) {
174
+ var sum = 0;
175
+ (0, utils_ts_1.iterate)(tokens, (token) => {
176
+ sum += scoreObject(token, data);
177
+ });
178
+ return sum / token_count;
179
+ };
939
180
  }
940
-
941
- return sum / token_count;
942
- };
943
- } else {
944
- return function (data) {
945
- var sum = 0;
946
- iterate(tokens, token => {
947
- sum += scoreObject(token, data);
948
- });
949
- return sum / token_count;
950
- };
951
- }
952
- }
953
-
954
- /**
955
- * Returns a function that can be used to compare two
956
- * results, for sorting purposes. If no sorting should
957
- * be performed, `null` will be returned.
958
- *
959
- * @return function(a,b)
960
- */
961
- getSortFunction(query, options) {
962
- var search = this.prepareSearch(query, options);
963
- return this._getSortFunction(search);
964
- }
965
-
966
- _getSortFunction(search) {
967
- var implicit_score,
968
- sort_flds = [];
969
- const self = this,
970
- options = search.options,
971
- sort = !search.query && options.sort_empty ? options.sort_empty : options.sort;
972
-
973
- if (typeof sort == 'function') {
974
- return sort.bind(this);
975
181
  }
182
+ ;
976
183
  /**
977
- * Fetches the specified sort field value
978
- * from a search result item.
184
+ * Returns a function that can be used to compare two
185
+ * results, for sorting purposes. If no sorting should
186
+ * be performed, `null` will be returned.
979
187
  *
188
+ * @return function(a,b)
980
189
  */
981
-
982
-
983
- const get_field = function get_field(name, result) {
984
- if (name === '$score') return result.score;
985
- return search.getAttrFn(self.items[result.id], name);
986
- }; // parse options
987
-
988
-
989
- if (sort) {
990
- for (let s of sort) {
991
- if (search.query || s.field !== '$score') {
992
- sort_flds.push(s);
190
+ getSortFunction(query, options) {
191
+ var search = this.prepareSearch(query, options);
192
+ return this._getSortFunction(search);
193
+ }
194
+ _getSortFunction(search) {
195
+ var implicit_score, sort_flds = [];
196
+ const self = this, options = search.options, sort = (!search.query && options.sort_empty) ? options.sort_empty : options.sort;
197
+ if (typeof sort == 'function') {
198
+ return sort.bind(this);
993
199
  }
994
- }
995
- } // the "$score" field is implied to be the primary
996
- // sort field, unless it's manually specified
997
-
998
-
999
- if (search.query) {
1000
- implicit_score = true;
1001
-
1002
- for (let fld of sort_flds) {
1003
- if (fld.field === '$score') {
1004
- implicit_score = false;
1005
- break;
200
+ /**
201
+ * Fetches the specified sort field value
202
+ * from a search result item.
203
+ *
204
+ */
205
+ const get_field = function (name, result) {
206
+ if (name === '$score')
207
+ return result.score;
208
+ return search.getAttrFn(self.items[result.id], name);
209
+ };
210
+ // parse options
211
+ if (sort) {
212
+ for (let s of sort) {
213
+ if (search.query || s.field !== '$score') {
214
+ sort_flds.push(s);
215
+ }
216
+ }
1006
217
  }
1007
- }
1008
-
1009
- if (implicit_score) {
1010
- sort_flds.unshift({
1011
- field: '$score',
1012
- direction: 'desc'
1013
- });
1014
- } // without a search.query, all items will have the same score
1015
-
1016
- } else {
1017
- sort_flds = sort_flds.filter(fld => fld.field !== '$score');
1018
- } // build function
1019
-
1020
-
1021
- const sort_flds_count = sort_flds.length;
1022
-
1023
- if (!sort_flds_count) {
1024
- return null;
1025
- }
1026
-
1027
- return function (a, b) {
1028
- var result, field;
1029
-
1030
- for (let sort_fld of sort_flds) {
1031
- field = sort_fld.field;
1032
- let multiplier = sort_fld.direction === 'desc' ? -1 : 1;
1033
- result = multiplier * cmp(get_field(field, a), get_field(field, b));
1034
- if (result) return result;
1035
- }
1036
-
1037
- return 0;
1038
- };
1039
- }
1040
-
1041
- /**
1042
- * Parses a search query and returns an object
1043
- * with tokens and fields ready to be populated
1044
- * with results.
1045
- *
1046
- */
1047
- prepareSearch(query, optsUser) {
1048
- const weights = {};
1049
- var options = Object.assign({}, optsUser);
1050
- propToArray(options, 'sort');
1051
- propToArray(options, 'sort_empty'); // convert fields to new format
1052
-
1053
- if (options.fields) {
1054
- propToArray(options, 'fields');
1055
- const fields = [];
1056
- options.fields.forEach(field => {
1057
- if (typeof field == 'string') {
1058
- field = {
1059
- field: field,
1060
- weight: 1
1061
- };
218
+ // the "$score" field is implied to be the primary
219
+ // sort field, unless it's manually specified
220
+ if (search.query) {
221
+ implicit_score = true;
222
+ for (let fld of sort_flds) {
223
+ if (fld.field === '$score') {
224
+ implicit_score = false;
225
+ break;
226
+ }
227
+ }
228
+ if (implicit_score) {
229
+ sort_flds.unshift({ field: '$score', direction: 'desc' });
230
+ }
231
+ // without a search.query, all items will have the same score
1062
232
  }
1063
-
1064
- fields.push(field);
1065
- weights[field.field] = 'weight' in field ? field.weight : 1;
1066
- });
1067
- options.fields = fields;
233
+ else {
234
+ sort_flds = sort_flds.filter((fld) => fld.field !== '$score');
235
+ }
236
+ // build function
237
+ const sort_flds_count = sort_flds.length;
238
+ if (!sort_flds_count) {
239
+ return null;
240
+ }
241
+ return function (a, b) {
242
+ var result, field;
243
+ for (let sort_fld of sort_flds) {
244
+ field = sort_fld.field;
245
+ let multiplier = sort_fld.direction === 'desc' ? -1 : 1;
246
+ result = multiplier * (0, utils_ts_1.cmp)(get_field(field, a), get_field(field, b));
247
+ if (result)
248
+ return result;
249
+ }
250
+ return 0;
251
+ };
1068
252
  }
1069
-
1070
- return {
1071
- options: options,
1072
- query: query.toLowerCase().trim(),
1073
- tokens: this.tokenize(query, options.respect_word_boundaries, weights),
1074
- total: 0,
1075
- items: [],
1076
- weights: weights,
1077
- getAttrFn: options.nesting ? getAttrNesting : getAttr
1078
- };
1079
- }
1080
-
1081
- /**
1082
- * Searches through all items and returns a sorted array of matches.
1083
- *
1084
- */
1085
- search(query, options) {
1086
- var self = this,
1087
- score,
1088
- search;
1089
- search = this.prepareSearch(query, options);
1090
- options = search.options;
1091
- query = search.query; // generate result scoring function
1092
-
1093
- const fn_score = options.score || self._getScoreFunction(search); // perform search and sort
1094
-
1095
-
1096
- if (query.length) {
1097
- iterate(self.items, (item, id) => {
1098
- score = fn_score(item);
1099
-
1100
- if (options.filter === false || score > 0) {
1101
- search.items.push({
1102
- 'score': score,
1103
- 'id': id
1104
- });
253
+ ;
254
+ /**
255
+ * Parses a search query and returns an object
256
+ * with tokens and fields ready to be populated
257
+ * with results.
258
+ *
259
+ */
260
+ prepareSearch(query, optsUser) {
261
+ const weights = {};
262
+ var options = Object.assign({}, optsUser);
263
+ (0, utils_ts_1.propToArray)(options, 'sort');
264
+ (0, utils_ts_1.propToArray)(options, 'sort_empty');
265
+ // convert fields to new format
266
+ if (options.fields) {
267
+ (0, utils_ts_1.propToArray)(options, 'fields');
268
+ const fields = [];
269
+ options.fields.forEach((field) => {
270
+ if (typeof field == 'string') {
271
+ field = { field: field, weight: 1 };
272
+ }
273
+ fields.push(field);
274
+ weights[field.field] = ('weight' in field) ? field.weight : 1;
275
+ });
276
+ options.fields = fields;
1105
277
  }
1106
- });
1107
- } else {
1108
- iterate(self.items, (_, id) => {
1109
- search.items.push({
1110
- 'score': 1,
1111
- 'id': id
1112
- });
1113
- });
278
+ return {
279
+ options: options,
280
+ query: query.toLowerCase().trim(),
281
+ tokens: this.tokenize(query, options.respect_word_boundaries, weights),
282
+ total: 0,
283
+ items: [],
284
+ weights: weights,
285
+ getAttrFn: (options.nesting) ? utils_ts_1.getAttrNesting : utils_ts_1.getAttr,
286
+ };
1114
287
  }
1115
-
1116
- const fn_sort = self._getSortFunction(search);
1117
-
1118
- if (fn_sort) search.items.sort(fn_sort); // apply limits
1119
-
1120
- search.total = search.items.length;
1121
-
1122
- if (typeof options.limit === 'number') {
1123
- search.items = search.items.slice(0, options.limit);
288
+ ;
289
+ /**
290
+ * Searches through all items and returns a sorted array of matches.
291
+ *
292
+ */
293
+ search(query, options) {
294
+ var self = this, score, search;
295
+ search = this.prepareSearch(query, options);
296
+ options = search.options;
297
+ query = search.query;
298
+ // generate result scoring function
299
+ const fn_score = options.score || self._getScoreFunction(search);
300
+ // perform search and sort
301
+ if (query.length) {
302
+ (0, utils_ts_1.iterate)(self.items, (item, id) => {
303
+ score = fn_score(item);
304
+ if (options.filter === false || score > 0) {
305
+ search.items.push({ 'score': score, 'id': id });
306
+ }
307
+ });
308
+ }
309
+ else {
310
+ (0, utils_ts_1.iterate)(self.items, (_, id) => {
311
+ search.items.push({ 'score': 1, 'id': id });
312
+ });
313
+ }
314
+ const fn_sort = self._getSortFunction(search);
315
+ if (fn_sort)
316
+ search.items.sort(fn_sort);
317
+ // apply limits
318
+ search.total = search.items.length;
319
+ if (typeof options.limit === 'number') {
320
+ search.items = search.items.slice(0, options.limit);
321
+ }
322
+ return search;
1124
323
  }
1125
-
1126
- return search;
1127
- }
1128
-
324
+ ;
1129
325
  }
1130
-
1131
326
  exports.Sifter = Sifter;
1132
- exports.cmp = cmp;
1133
- exports.getAttr = getAttr;
1134
- exports.getAttrNesting = getAttrNesting;
1135
- exports.getPattern = getPattern;
1136
- exports.iterate = iterate;
1137
- exports.propToArray = propToArray;
1138
- exports.scoreValue = scoreValue;
1139
- //# sourceMappingURL=sifter.js.map
327
+ __exportStar(require("./types.js"), exports);
328
+ //# sourceMappingURL=sifter.js.map