You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2252 lines
65 KiB

4 years ago
  1. /**
  2. * Fuse.js v6.4.5 - Lightweight fuzzy-search (http://fusejs.io)
  3. *
  4. * Copyright (c) 2021 Kiro Risk (http://kiro.me)
  5. * All Rights Reserved. Apache Software License 2.0
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. */
  9. (function (global, factory) {
  10. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  11. typeof define === 'function' && define.amd ? define(factory) :
  12. (global = global || self, global.Fuse = factory());
  13. }(this, (function () { 'use strict';
  14. function _typeof(obj) {
  15. "@babel/helpers - typeof";
  16. if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
  17. _typeof = function (obj) {
  18. return typeof obj;
  19. };
  20. } else {
  21. _typeof = function (obj) {
  22. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  23. };
  24. }
  25. return _typeof(obj);
  26. }
  27. function _classCallCheck(instance, Constructor) {
  28. if (!(instance instanceof Constructor)) {
  29. throw new TypeError("Cannot call a class as a function");
  30. }
  31. }
  32. function _defineProperties(target, props) {
  33. for (var i = 0; i < props.length; i++) {
  34. var descriptor = props[i];
  35. descriptor.enumerable = descriptor.enumerable || false;
  36. descriptor.configurable = true;
  37. if ("value" in descriptor) descriptor.writable = true;
  38. Object.defineProperty(target, descriptor.key, descriptor);
  39. }
  40. }
  41. function _createClass(Constructor, protoProps, staticProps) {
  42. if (protoProps) _defineProperties(Constructor.prototype, protoProps);
  43. if (staticProps) _defineProperties(Constructor, staticProps);
  44. return Constructor;
  45. }
  46. function _defineProperty(obj, key, value) {
  47. if (key in obj) {
  48. Object.defineProperty(obj, key, {
  49. value: value,
  50. enumerable: true,
  51. configurable: true,
  52. writable: true
  53. });
  54. } else {
  55. obj[key] = value;
  56. }
  57. return obj;
  58. }
  59. function ownKeys(object, enumerableOnly) {
  60. var keys = Object.keys(object);
  61. if (Object.getOwnPropertySymbols) {
  62. var symbols = Object.getOwnPropertySymbols(object);
  63. if (enumerableOnly) symbols = symbols.filter(function (sym) {
  64. return Object.getOwnPropertyDescriptor(object, sym).enumerable;
  65. });
  66. keys.push.apply(keys, symbols);
  67. }
  68. return keys;
  69. }
  70. function _objectSpread2(target) {
  71. for (var i = 1; i < arguments.length; i++) {
  72. var source = arguments[i] != null ? arguments[i] : {};
  73. if (i % 2) {
  74. ownKeys(Object(source), true).forEach(function (key) {
  75. _defineProperty(target, key, source[key]);
  76. });
  77. } else if (Object.getOwnPropertyDescriptors) {
  78. Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
  79. } else {
  80. ownKeys(Object(source)).forEach(function (key) {
  81. Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
  82. });
  83. }
  84. }
  85. return target;
  86. }
  87. function _inherits(subClass, superClass) {
  88. if (typeof superClass !== "function" && superClass !== null) {
  89. throw new TypeError("Super expression must either be null or a function");
  90. }
  91. subClass.prototype = Object.create(superClass && superClass.prototype, {
  92. constructor: {
  93. value: subClass,
  94. writable: true,
  95. configurable: true
  96. }
  97. });
  98. if (superClass) _setPrototypeOf(subClass, superClass);
  99. }
  100. function _getPrototypeOf(o) {
  101. _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
  102. return o.__proto__ || Object.getPrototypeOf(o);
  103. };
  104. return _getPrototypeOf(o);
  105. }
  106. function _setPrototypeOf(o, p) {
  107. _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
  108. o.__proto__ = p;
  109. return o;
  110. };
  111. return _setPrototypeOf(o, p);
  112. }
  113. function _isNativeReflectConstruct() {
  114. if (typeof Reflect === "undefined" || !Reflect.construct) return false;
  115. if (Reflect.construct.sham) return false;
  116. if (typeof Proxy === "function") return true;
  117. try {
  118. Date.prototype.toString.call(Reflect.construct(Date, [], function () {}));
  119. return true;
  120. } catch (e) {
  121. return false;
  122. }
  123. }
  124. function _assertThisInitialized(self) {
  125. if (self === void 0) {
  126. throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  127. }
  128. return self;
  129. }
  130. function _possibleConstructorReturn(self, call) {
  131. if (call && (typeof call === "object" || typeof call === "function")) {
  132. return call;
  133. }
  134. return _assertThisInitialized(self);
  135. }
  136. function _createSuper(Derived) {
  137. var hasNativeReflectConstruct = _isNativeReflectConstruct();
  138. return function _createSuperInternal() {
  139. var Super = _getPrototypeOf(Derived),
  140. result;
  141. if (hasNativeReflectConstruct) {
  142. var NewTarget = _getPrototypeOf(this).constructor;
  143. result = Reflect.construct(Super, arguments, NewTarget);
  144. } else {
  145. result = Super.apply(this, arguments);
  146. }
  147. return _possibleConstructorReturn(this, result);
  148. };
  149. }
  150. function _toConsumableArray(arr) {
  151. return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
  152. }
  153. function _arrayWithoutHoles(arr) {
  154. if (Array.isArray(arr)) return _arrayLikeToArray(arr);
  155. }
  156. function _iterableToArray(iter) {
  157. if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter);
  158. }
  159. function _unsupportedIterableToArray(o, minLen) {
  160. if (!o) return;
  161. if (typeof o === "string") return _arrayLikeToArray(o, minLen);
  162. var n = Object.prototype.toString.call(o).slice(8, -1);
  163. if (n === "Object" && o.constructor) n = o.constructor.name;
  164. if (n === "Map" || n === "Set") return Array.from(o);
  165. if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
  166. }
  167. function _arrayLikeToArray(arr, len) {
  168. if (len == null || len > arr.length) len = arr.length;
  169. for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
  170. return arr2;
  171. }
  172. function _nonIterableSpread() {
  173. throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  174. }
  175. function isArray(value) {
  176. return !Array.isArray ? getTag(value) === '[object Array]' : Array.isArray(value);
  177. } // Adapted from: https://github.com/lodash/lodash/blob/master/.internal/baseToString.js
  178. var INFINITY = 1 / 0;
  179. function baseToString(value) {
  180. // Exit early for strings to avoid a performance hit in some environments.
  181. if (typeof value == 'string') {
  182. return value;
  183. }
  184. var result = value + '';
  185. return result == '0' && 1 / value == -INFINITY ? '-0' : result;
  186. }
  187. function toString(value) {
  188. return value == null ? '' : baseToString(value);
  189. }
  190. function isString(value) {
  191. return typeof value === 'string';
  192. }
  193. function isNumber(value) {
  194. return typeof value === 'number';
  195. } // Adapted from: https://github.com/lodash/lodash/blob/master/isBoolean.js
  196. function isBoolean(value) {
  197. return value === true || value === false || isObjectLike(value) && getTag(value) == '[object Boolean]';
  198. }
  199. function isObject(value) {
  200. return _typeof(value) === 'object';
  201. } // Checks if `value` is object-like.
  202. function isObjectLike(value) {
  203. return isObject(value) && value !== null;
  204. }
  205. function isDefined(value) {
  206. return value !== undefined && value !== null;
  207. }
  208. function isBlank(value) {
  209. return !value.trim().length;
  210. } // Gets the `toStringTag` of `value`.
  211. // Adapted from: https://github.com/lodash/lodash/blob/master/.internal/getTag.js
  212. function getTag(value) {
  213. return value == null ? value === undefined ? '[object Undefined]' : '[object Null]' : Object.prototype.toString.call(value);
  214. }
  215. var EXTENDED_SEARCH_UNAVAILABLE = 'Extended search is not available';
  216. var INCORRECT_INDEX_TYPE = "Incorrect 'index' type";
  217. var LOGICAL_SEARCH_INVALID_QUERY_FOR_KEY = function LOGICAL_SEARCH_INVALID_QUERY_FOR_KEY(key) {
  218. return "Invalid value for key ".concat(key);
  219. };
  220. var PATTERN_LENGTH_TOO_LARGE = function PATTERN_LENGTH_TOO_LARGE(max) {
  221. return "Pattern length exceeds max of ".concat(max, ".");
  222. };
  223. var MISSING_KEY_PROPERTY = function MISSING_KEY_PROPERTY(name) {
  224. return "Missing ".concat(name, " property in key");
  225. };
  226. var INVALID_KEY_WEIGHT_VALUE = function INVALID_KEY_WEIGHT_VALUE(key) {
  227. return "Property 'weight' in key '".concat(key, "' must be a positive integer");
  228. };
  229. var hasOwn = Object.prototype.hasOwnProperty;
  230. var KeyStore = /*#__PURE__*/function () {
  231. function KeyStore(keys) {
  232. var _this = this;
  233. _classCallCheck(this, KeyStore);
  234. this._keys = [];
  235. this._keyMap = {};
  236. var totalWeight = 0;
  237. keys.forEach(function (key) {
  238. var obj = createKey(key);
  239. totalWeight += obj.weight;
  240. _this._keys.push(obj);
  241. _this._keyMap[obj.id] = obj;
  242. totalWeight += obj.weight;
  243. }); // Normalize weights so that their sum is equal to 1
  244. this._keys.forEach(function (key) {
  245. key.weight /= totalWeight;
  246. });
  247. }
  248. _createClass(KeyStore, [{
  249. key: "get",
  250. value: function get(keyId) {
  251. return this._keyMap[keyId];
  252. }
  253. }, {
  254. key: "keys",
  255. value: function keys() {
  256. return this._keys;
  257. }
  258. }, {
  259. key: "toJSON",
  260. value: function toJSON() {
  261. return JSON.stringify(this._keys);
  262. }
  263. }]);
  264. return KeyStore;
  265. }();
  266. function createKey(key) {
  267. var path = null;
  268. var id = null;
  269. var src = null;
  270. var weight = 1;
  271. if (isString(key) || isArray(key)) {
  272. src = key;
  273. path = createKeyPath(key);
  274. id = createKeyId(key);
  275. } else {
  276. if (!hasOwn.call(key, 'name')) {
  277. throw new Error(MISSING_KEY_PROPERTY('name'));
  278. }
  279. var name = key.name;
  280. src = name;
  281. if (hasOwn.call(key, 'weight')) {
  282. weight = key.weight;
  283. if (weight <= 0) {
  284. throw new Error(INVALID_KEY_WEIGHT_VALUE(name));
  285. }
  286. }
  287. path = createKeyPath(name);
  288. id = createKeyId(name);
  289. }
  290. return {
  291. path: path,
  292. id: id,
  293. weight: weight,
  294. src: src
  295. };
  296. }
  297. function createKeyPath(key) {
  298. return isArray(key) ? key : key.split('.');
  299. }
  300. function createKeyId(key) {
  301. return isArray(key) ? key.join('.') : key;
  302. }
  303. function get(obj, path) {
  304. var list = [];
  305. var arr = false;
  306. var deepGet = function deepGet(obj, path, index) {
  307. if (!isDefined(obj)) {
  308. return;
  309. }
  310. if (!path[index]) {
  311. // If there's no path left, we've arrived at the object we care about.
  312. list.push(obj);
  313. } else {
  314. var key = path[index];
  315. var value = obj[key];
  316. if (!isDefined(value)) {
  317. return;
  318. } // If we're at the last value in the path, and if it's a string/number/bool,
  319. // add it to the list
  320. if (index === path.length - 1 && (isString(value) || isNumber(value) || isBoolean(value))) {
  321. list.push(toString(value));
  322. } else if (isArray(value)) {
  323. arr = true; // Search each item in the array.
  324. for (var i = 0, len = value.length; i < len; i += 1) {
  325. deepGet(value[i], path, index + 1);
  326. }
  327. } else if (path.length) {
  328. // An object. Recurse further.
  329. deepGet(value, path, index + 1);
  330. }
  331. }
  332. }; // Backwards compatibility (since path used to be a string)
  333. deepGet(obj, isString(path) ? path.split('.') : path, 0);
  334. return arr ? list : list[0];
  335. }
  336. var MatchOptions = {
  337. // Whether the matches should be included in the result set. When `true`, each record in the result
  338. // set will include the indices of the matched characters.
  339. // These can consequently be used for highlighting purposes.
  340. includeMatches: false,
  341. // When `true`, the matching function will continue to the end of a search pattern even if
  342. // a perfect match has already been located in the string.
  343. findAllMatches: false,
  344. // Minimum number of characters that must be matched before a result is considered a match
  345. minMatchCharLength: 1
  346. };
  347. var BasicOptions = {
  348. // When `true`, the algorithm continues searching to the end of the input even if a perfect
  349. // match is found before the end of the same input.
  350. isCaseSensitive: false,
  351. // When true, the matching function will continue to the end of a search pattern even if
  352. includeScore: false,
  353. // List of properties that will be searched. This also supports nested properties.
  354. keys: [],
  355. // Whether to sort the result list, by score
  356. shouldSort: true,
  357. // Default sort function: sort by ascending score, ascending index
  358. sortFn: function sortFn(a, b) {
  359. return a.score === b.score ? a.idx < b.idx ? -1 : 1 : a.score < b.score ? -1 : 1;
  360. }
  361. };
  362. var FuzzyOptions = {
  363. // Approximately where in the text is the pattern expected to be found?
  364. location: 0,
  365. // At what point does the match algorithm give up. A threshold of '0.0' requires a perfect match
  366. // (of both letters and location), a threshold of '1.0' would match anything.
  367. threshold: 0.6,
  368. // Determines how close the match must be to the fuzzy location (specified above).
  369. // An exact letter match which is 'distance' characters away from the fuzzy location
  370. // would score as a complete mismatch. A distance of '0' requires the match be at
  371. // the exact location specified, a threshold of '1000' would require a perfect match
  372. // to be within 800 characters of the fuzzy location to be found using a 0.8 threshold.
  373. distance: 100
  374. };
  375. var AdvancedOptions = {
  376. // When `true`, it enables the use of unix-like search commands
  377. useExtendedSearch: false,
  378. // The get function to use when fetching an object's properties.
  379. // The default will search nested paths *ie foo.bar.baz*
  380. getFn: get,
  381. // When `true`, search will ignore `location` and `distance`, so it won't matter
  382. // where in the string the pattern appears.
  383. // More info: https://fusejs.io/concepts/scoring-theory.html#fuzziness-score
  384. ignoreLocation: false,
  385. // When `true`, the calculation for the relevance score (used for sorting) will
  386. // ignore the field-length norm.
  387. // More info: https://fusejs.io/concepts/scoring-theory.html#field-length-norm
  388. ignoreFieldNorm: false
  389. };
  390. var Config = _objectSpread2({}, BasicOptions, {}, MatchOptions, {}, FuzzyOptions, {}, AdvancedOptions);
  391. var SPACE = /[^ ]+/g; // Field-length norm: the shorter the field, the higher the weight.
  392. // Set to 3 decimals to reduce index size.
  393. function norm() {
  394. var mantissa = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 3;
  395. var cache = new Map();
  396. return {
  397. get: function get(value) {
  398. var numTokens = value.match(SPACE).length;
  399. if (cache.has(numTokens)) {
  400. return cache.get(numTokens);
  401. }
  402. var n = parseFloat((1 / Math.sqrt(numTokens)).toFixed(mantissa));
  403. cache.set(numTokens, n);
  404. return n;
  405. },
  406. clear: function clear() {
  407. cache.clear();
  408. }
  409. };
  410. }
  411. var FuseIndex = /*#__PURE__*/function () {
  412. function FuseIndex() {
  413. var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
  414. _ref$getFn = _ref.getFn,
  415. getFn = _ref$getFn === void 0 ? Config.getFn : _ref$getFn;
  416. _classCallCheck(this, FuseIndex);
  417. this.norm = norm(3);
  418. this.getFn = getFn;
  419. this.isCreated = false;
  420. this.setIndexRecords();
  421. }
  422. _createClass(FuseIndex, [{
  423. key: "setSources",
  424. value: function setSources() {
  425. var docs = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
  426. this.docs = docs;
  427. }
  428. }, {
  429. key: "setIndexRecords",
  430. value: function setIndexRecords() {
  431. var records = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
  432. this.records = records;
  433. }
  434. }, {
  435. key: "setKeys",
  436. value: function setKeys() {
  437. var _this = this;
  438. var keys = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
  439. this.keys = keys;
  440. this._keysMap = {};
  441. keys.forEach(function (key, idx) {
  442. _this._keysMap[key.id] = idx;
  443. });
  444. }
  445. }, {
  446. key: "create",
  447. value: function create() {
  448. var _this2 = this;
  449. if (this.isCreated || !this.docs.length) {
  450. return;
  451. }
  452. this.isCreated = true; // List is Array<String>
  453. if (isString(this.docs[0])) {
  454. this.docs.forEach(function (doc, docIndex) {
  455. _this2._addString(doc, docIndex);
  456. });
  457. } else {
  458. // List is Array<Object>
  459. this.docs.forEach(function (doc, docIndex) {
  460. _this2._addObject(doc, docIndex);
  461. });
  462. }
  463. this.norm.clear();
  464. } // Adds a doc to the end of the index
  465. }, {
  466. key: "add",
  467. value: function add(doc) {
  468. var idx = this.size();
  469. if (isString(doc)) {
  470. this._addString(doc, idx);
  471. } else {
  472. this._addObject(doc, idx);
  473. }
  474. } // Removes the doc at the specified index of the index
  475. }, {
  476. key: "removeAt",
  477. value: function removeAt(idx) {
  478. this.records.splice(idx, 1); // Change ref index of every subsquent doc
  479. for (var i = idx, len = this.size(); i < len; i += 1) {
  480. this.records[i].i -= 1;
  481. }
  482. }
  483. }, {
  484. key: "getValueForItemAtKeyId",
  485. value: function getValueForItemAtKeyId(item, keyId) {
  486. return item[this._keysMap[keyId]];
  487. }
  488. }, {
  489. key: "size",
  490. value: function size() {
  491. return this.records.length;
  492. }
  493. }, {
  494. key: "_addString",
  495. value: function _addString(doc, docIndex) {
  496. if (!isDefined(doc) || isBlank(doc)) {
  497. return;
  498. }
  499. var record = {
  500. v: doc,
  501. i: docIndex,
  502. n: this.norm.get(doc)
  503. };
  504. this.records.push(record);
  505. }
  506. }, {
  507. key: "_addObject",
  508. value: function _addObject(doc, docIndex) {
  509. var _this3 = this;
  510. var record = {
  511. i: docIndex,
  512. $: {}
  513. }; // Iterate over every key (i.e, path), and fetch the value at that key
  514. this.keys.forEach(function (key, keyIndex) {
  515. // console.log(key)
  516. var value = _this3.getFn(doc, key.path);
  517. if (!isDefined(value)) {
  518. return;
  519. }
  520. if (isArray(value)) {
  521. (function () {
  522. var subRecords = [];
  523. var stack = [{
  524. nestedArrIndex: -1,
  525. value: value
  526. }];
  527. while (stack.length) {
  528. var _stack$pop = stack.pop(),
  529. nestedArrIndex = _stack$pop.nestedArrIndex,
  530. _value = _stack$pop.value;
  531. if (!isDefined(_value)) {
  532. continue;
  533. }
  534. if (isString(_value) && !isBlank(_value)) {
  535. var subRecord = {
  536. v: _value,
  537. i: nestedArrIndex,
  538. n: _this3.norm.get(_value)
  539. };
  540. subRecords.push(subRecord);
  541. } else if (isArray(_value)) {
  542. _value.forEach(function (item, k) {
  543. stack.push({
  544. nestedArrIndex: k,
  545. value: item
  546. });
  547. });
  548. }
  549. }
  550. record.$[keyIndex] = subRecords;
  551. })();
  552. } else if (!isBlank(value)) {
  553. var subRecord = {
  554. v: value,
  555. n: _this3.norm.get(value)
  556. };
  557. record.$[keyIndex] = subRecord;
  558. }
  559. });
  560. this.records.push(record);
  561. }
  562. }, {
  563. key: "toJSON",
  564. value: function toJSON() {
  565. return {
  566. keys: this.keys,
  567. records: this.records
  568. };
  569. }
  570. }]);
  571. return FuseIndex;
  572. }();
  573. function createIndex(keys, docs) {
  574. var _ref2 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {},
  575. _ref2$getFn = _ref2.getFn,
  576. getFn = _ref2$getFn === void 0 ? Config.getFn : _ref2$getFn;
  577. var myIndex = new FuseIndex({
  578. getFn: getFn
  579. });
  580. myIndex.setKeys(keys.map(createKey));
  581. myIndex.setSources(docs);
  582. myIndex.create();
  583. return myIndex;
  584. }
  585. function parseIndex(data) {
  586. var _ref3 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
  587. _ref3$getFn = _ref3.getFn,
  588. getFn = _ref3$getFn === void 0 ? Config.getFn : _ref3$getFn;
  589. var keys = data.keys,
  590. records = data.records;
  591. var myIndex = new FuseIndex({
  592. getFn: getFn
  593. });
  594. myIndex.setKeys(keys);
  595. myIndex.setIndexRecords(records);
  596. return myIndex;
  597. }
  598. function transformMatches(result, data) {
  599. var matches = result.matches;
  600. data.matches = [];
  601. if (!isDefined(matches)) {
  602. return;
  603. }
  604. matches.forEach(function (match) {
  605. if (!isDefined(match.indices) || !match.indices.length) {
  606. return;
  607. }
  608. var indices = match.indices,
  609. value = match.value;
  610. var obj = {
  611. indices: indices,
  612. value: value
  613. };
  614. if (match.key) {
  615. obj.key = match.key.src;
  616. }
  617. if (match.idx > -1) {
  618. obj.refIndex = match.idx;
  619. }
  620. data.matches.push(obj);
  621. });
  622. }
  623. function transformScore(result, data) {
  624. data.score = result.score;
  625. }
  626. function computeScore(pattern) {
  627. var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
  628. _ref$errors = _ref.errors,
  629. errors = _ref$errors === void 0 ? 0 : _ref$errors,
  630. _ref$currentLocation = _ref.currentLocation,
  631. currentLocation = _ref$currentLocation === void 0 ? 0 : _ref$currentLocation,
  632. _ref$expectedLocation = _ref.expectedLocation,
  633. expectedLocation = _ref$expectedLocation === void 0 ? 0 : _ref$expectedLocation,
  634. _ref$distance = _ref.distance,
  635. distance = _ref$distance === void 0 ? Config.distance : _ref$distance,
  636. _ref$ignoreLocation = _ref.ignoreLocation,
  637. ignoreLocation = _ref$ignoreLocation === void 0 ? Config.ignoreLocation : _ref$ignoreLocation;
  638. var accuracy = errors / pattern.length;
  639. if (ignoreLocation) {
  640. return accuracy;
  641. }
  642. var proximity = Math.abs(expectedLocation - currentLocation);
  643. if (!distance) {
  644. // Dodge divide by zero error.
  645. return proximity ? 1.0 : accuracy;
  646. }
  647. return accuracy + proximity / distance;
  648. }
  649. function convertMaskToIndices() {
  650. var matchmask = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
  651. var minMatchCharLength = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Config.minMatchCharLength;
  652. var indices = [];
  653. var start = -1;
  654. var end = -1;
  655. var i = 0;
  656. for (var len = matchmask.length; i < len; i += 1) {
  657. var match = matchmask[i];
  658. if (match && start === -1) {
  659. start = i;
  660. } else if (!match && start !== -1) {
  661. end = i - 1;
  662. if (end - start + 1 >= minMatchCharLength) {
  663. indices.push([start, end]);
  664. }
  665. start = -1;
  666. }
  667. } // (i-1 - start) + 1 => i - start
  668. if (matchmask[i - 1] && i - start >= minMatchCharLength) {
  669. indices.push([start, i - 1]);
  670. }
  671. return indices;
  672. }
  673. // Machine word size
  674. var MAX_BITS = 32;
  675. function search(text, pattern, patternAlphabet) {
  676. var _ref = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {},
  677. _ref$location = _ref.location,
  678. location = _ref$location === void 0 ? Config.location : _ref$location,
  679. _ref$distance = _ref.distance,
  680. distance = _ref$distance === void 0 ? Config.distance : _ref$distance,
  681. _ref$threshold = _ref.threshold,
  682. threshold = _ref$threshold === void 0 ? Config.threshold : _ref$threshold,
  683. _ref$findAllMatches = _ref.findAllMatches,
  684. findAllMatches = _ref$findAllMatches === void 0 ? Config.findAllMatches : _ref$findAllMatches,
  685. _ref$minMatchCharLeng = _ref.minMatchCharLength,
  686. minMatchCharLength = _ref$minMatchCharLeng === void 0 ? Config.minMatchCharLength : _ref$minMatchCharLeng,
  687. _ref$includeMatches = _ref.includeMatches,
  688. includeMatches = _ref$includeMatches === void 0 ? Config.includeMatches : _ref$includeMatches,
  689. _ref$ignoreLocation = _ref.ignoreLocation,
  690. ignoreLocation = _ref$ignoreLocation === void 0 ? Config.ignoreLocation : _ref$ignoreLocation;
  691. if (pattern.length > MAX_BITS) {
  692. throw new Error(PATTERN_LENGTH_TOO_LARGE(MAX_BITS));
  693. }
  694. var patternLen = pattern.length; // Set starting location at beginning text and initialize the alphabet.
  695. var textLen = text.length; // Handle the case when location > text.length
  696. var expectedLocation = Math.max(0, Math.min(location, textLen)); // Highest score beyond which we give up.
  697. var currentThreshold = threshold; // Is there a nearby exact match? (speedup)
  698. var bestLocation = expectedLocation; // Performance: only computer matches when the minMatchCharLength > 1
  699. // OR if `includeMatches` is true.
  700. var computeMatches = minMatchCharLength > 1 || includeMatches; // A mask of the matches, used for building the indices
  701. var matchMask = computeMatches ? Array(textLen) : [];
  702. var index; // Get all exact matches, here for speed up
  703. while ((index = text.indexOf(pattern, bestLocation)) > -1) {
  704. var score = computeScore(pattern, {
  705. currentLocation: index,
  706. expectedLocation: expectedLocation,
  707. distance: distance,
  708. ignoreLocation: ignoreLocation
  709. });
  710. currentThreshold = Math.min(score, currentThreshold);
  711. bestLocation = index + patternLen;
  712. if (computeMatches) {
  713. var i = 0;
  714. while (i < patternLen) {
  715. matchMask[index + i] = 1;
  716. i += 1;
  717. }
  718. }
  719. } // Reset the best location
  720. bestLocation = -1;
  721. var lastBitArr = [];
  722. var finalScore = 1;
  723. var binMax = patternLen + textLen;
  724. var mask = 1 << patternLen - 1;
  725. for (var _i = 0; _i < patternLen; _i += 1) {
  726. // Scan for the best match; each iteration allows for one more error.
  727. // Run a binary search to determine how far from the match location we can stray
  728. // at this error level.
  729. var binMin = 0;
  730. var binMid = binMax;
  731. while (binMin < binMid) {
  732. var _score2 = computeScore(pattern, {
  733. errors: _i,
  734. currentLocation: expectedLocation + binMid,
  735. expectedLocation: expectedLocation,
  736. distance: distance,
  737. ignoreLocation: ignoreLocation
  738. });
  739. if (_score2 <= currentThreshold) {
  740. binMin = binMid;
  741. } else {
  742. binMax = binMid;
  743. }
  744. binMid = Math.floor((binMax - binMin) / 2 + binMin);
  745. } // Use the result from this iteration as the maximum for the next.
  746. binMax = binMid;
  747. var start = Math.max(1, expectedLocation - binMid + 1);
  748. var finish = findAllMatches ? textLen : Math.min(expectedLocation + binMid, textLen) + patternLen; // Initialize the bit array
  749. var bitArr = Array(finish + 2);
  750. bitArr[finish + 1] = (1 << _i) - 1;
  751. for (var j = finish; j >= start; j -= 1) {
  752. var currentLocation = j - 1;
  753. var charMatch = patternAlphabet[text.charAt(currentLocation)];
  754. if (computeMatches) {
  755. // Speed up: quick bool to int conversion (i.e, `charMatch ? 1 : 0`)
  756. matchMask[currentLocation] = +!!charMatch;
  757. } // First pass: exact match
  758. bitArr[j] = (bitArr[j + 1] << 1 | 1) & charMatch; // Subsequent passes: fuzzy match
  759. if (_i) {
  760. bitArr[j] |= (lastBitArr[j + 1] | lastBitArr[j]) << 1 | 1 | lastBitArr[j + 1];
  761. }
  762. if (bitArr[j] & mask) {
  763. finalScore = computeScore(pattern, {
  764. errors: _i,
  765. currentLocation: currentLocation,
  766. expectedLocation: expectedLocation,
  767. distance: distance,
  768. ignoreLocation: ignoreLocation
  769. }); // This match will almost certainly be better than any existing match.
  770. // But check anyway.
  771. if (finalScore <= currentThreshold) {
  772. // Indeed it is
  773. currentThreshold = finalScore;
  774. bestLocation = currentLocation; // Already passed `loc`, downhill from here on in.
  775. if (bestLocation <= expectedLocation) {
  776. break;
  777. } // When passing `bestLocation`, don't exceed our current distance from `expectedLocation`.
  778. start = Math.max(1, 2 * expectedLocation - bestLocation);
  779. }
  780. }
  781. } // No hope for a (better) match at greater error levels.
  782. var _score = computeScore(pattern, {
  783. errors: _i + 1,
  784. currentLocation: expectedLocation,
  785. expectedLocation: expectedLocation,
  786. distance: distance,
  787. ignoreLocation: ignoreLocation
  788. });
  789. if (_score > currentThreshold) {
  790. break;
  791. }
  792. lastBitArr = bitArr;
  793. }
  794. var result = {
  795. isMatch: bestLocation >= 0,
  796. // Count exact matches (those with a score of 0) to be "almost" exact
  797. score: Math.max(0.001, finalScore)
  798. };
  799. if (computeMatches) {
  800. var indices = convertMaskToIndices(matchMask, minMatchCharLength);
  801. if (!indices.length) {
  802. result.isMatch = false;
  803. } else if (includeMatches) {
  804. result.indices = indices;
  805. }
  806. }
  807. return result;
  808. }
  809. function createPatternAlphabet(pattern) {
  810. var mask = {};
  811. for (var i = 0, len = pattern.length; i < len; i += 1) {
  812. var char = pattern.charAt(i);
  813. mask[char] = (mask[char] || 0) | 1 << len - i - 1;
  814. }
  815. return mask;
  816. }
  817. var BitapSearch = /*#__PURE__*/function () {
  818. function BitapSearch(pattern) {
  819. var _this = this;
  820. var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
  821. _ref$location = _ref.location,
  822. location = _ref$location === void 0 ? Config.location : _ref$location,
  823. _ref$threshold = _ref.threshold,
  824. threshold = _ref$threshold === void 0 ? Config.threshold : _ref$threshold,
  825. _ref$distance = _ref.distance,
  826. distance = _ref$distance === void 0 ? Config.distance : _ref$distance,
  827. _ref$includeMatches = _ref.includeMatches,
  828. includeMatches = _ref$includeMatches === void 0 ? Config.includeMatches : _ref$includeMatches,
  829. _ref$findAllMatches = _ref.findAllMatches,
  830. findAllMatches = _ref$findAllMatches === void 0 ? Config.findAllMatches : _ref$findAllMatches,
  831. _ref$minMatchCharLeng = _ref.minMatchCharLength,
  832. minMatchCharLength = _ref$minMatchCharLeng === void 0 ? Config.minMatchCharLength : _ref$minMatchCharLeng,
  833. _ref$isCaseSensitive = _ref.isCaseSensitive,
  834. isCaseSensitive = _ref$isCaseSensitive === void 0 ? Config.isCaseSensitive : _ref$isCaseSensitive,
  835. _ref$ignoreLocation = _ref.ignoreLocation,
  836. ignoreLocation = _ref$ignoreLocation === void 0 ? Config.ignoreLocation : _ref$ignoreLocation;
  837. _classCallCheck(this, BitapSearch);
  838. this.options = {
  839. location: location,
  840. threshold: threshold,
  841. distance: distance,
  842. includeMatches: includeMatches,
  843. findAllMatches: findAllMatches,
  844. minMatchCharLength: minMatchCharLength,
  845. isCaseSensitive: isCaseSensitive,
  846. ignoreLocation: ignoreLocation
  847. };
  848. this.pattern = isCaseSensitive ? pattern : pattern.toLowerCase();
  849. this.chunks = [];
  850. if (!this.pattern.length) {
  851. return;
  852. }
  853. var addChunk = function addChunk(pattern, startIndex) {
  854. _this.chunks.push({
  855. pattern: pattern,
  856. alphabet: createPatternAlphabet(pattern),
  857. startIndex: startIndex
  858. });
  859. };
  860. var len = this.pattern.length;
  861. if (len > MAX_BITS) {
  862. var i = 0;
  863. var remainder = len % MAX_BITS;
  864. var end = len - remainder;
  865. while (i < end) {
  866. addChunk(this.pattern.substr(i, MAX_BITS), i);
  867. i += MAX_BITS;
  868. }
  869. if (remainder) {
  870. var startIndex = len - MAX_BITS;
  871. addChunk(this.pattern.substr(startIndex), startIndex);
  872. }
  873. } else {
  874. addChunk(this.pattern, 0);
  875. }
  876. }
  877. _createClass(BitapSearch, [{
  878. key: "searchIn",
  879. value: function searchIn(text) {
  880. var _this$options = this.options,
  881. isCaseSensitive = _this$options.isCaseSensitive,
  882. includeMatches = _this$options.includeMatches;
  883. if (!isCaseSensitive) {
  884. text = text.toLowerCase();
  885. } // Exact match
  886. if (this.pattern === text) {
  887. var _result = {
  888. isMatch: true,
  889. score: 0
  890. };
  891. if (includeMatches) {
  892. _result.indices = [[0, text.length - 1]];
  893. }
  894. return _result;
  895. } // Otherwise, use Bitap algorithm
  896. var _this$options2 = this.options,
  897. location = _this$options2.location,
  898. distance = _this$options2.distance,
  899. threshold = _this$options2.threshold,
  900. findAllMatches = _this$options2.findAllMatches,
  901. minMatchCharLength = _this$options2.minMatchCharLength,
  902. ignoreLocation = _this$options2.ignoreLocation;
  903. var allIndices = [];
  904. var totalScore = 0;
  905. var hasMatches = false;
  906. this.chunks.forEach(function (_ref2) {
  907. var pattern = _ref2.pattern,
  908. alphabet = _ref2.alphabet,
  909. startIndex = _ref2.startIndex;
  910. var _search = search(text, pattern, alphabet, {
  911. location: location + startIndex,
  912. distance: distance,
  913. threshold: threshold,
  914. findAllMatches: findAllMatches,
  915. minMatchCharLength: minMatchCharLength,
  916. includeMatches: includeMatches,
  917. ignoreLocation: ignoreLocation
  918. }),
  919. isMatch = _search.isMatch,
  920. score = _search.score,
  921. indices = _search.indices;
  922. if (isMatch) {
  923. hasMatches = true;
  924. }
  925. totalScore += score;
  926. if (isMatch && indices) {
  927. allIndices = [].concat(_toConsumableArray(allIndices), _toConsumableArray(indices));
  928. }
  929. });
  930. var result = {
  931. isMatch: hasMatches,
  932. score: hasMatches ? totalScore / this.chunks.length : 1
  933. };
  934. if (hasMatches && includeMatches) {
  935. result.indices = allIndices;
  936. }
  937. return result;
  938. }
  939. }]);
  940. return BitapSearch;
  941. }();
  942. var BaseMatch = /*#__PURE__*/function () {
  943. function BaseMatch(pattern) {
  944. _classCallCheck(this, BaseMatch);
  945. this.pattern = pattern;
  946. }
  947. _createClass(BaseMatch, [{
  948. key: "search",
  949. value: function search()
  950. /*text*/
  951. {}
  952. }], [{
  953. key: "isMultiMatch",
  954. value: function isMultiMatch(pattern) {
  955. return getMatch(pattern, this.multiRegex);
  956. }
  957. }, {
  958. key: "isSingleMatch",
  959. value: function isSingleMatch(pattern) {
  960. return getMatch(pattern, this.singleRegex);
  961. }
  962. }]);
  963. return BaseMatch;
  964. }();
  965. function getMatch(pattern, exp) {
  966. var matches = pattern.match(exp);
  967. return matches ? matches[1] : null;
  968. }
  969. var ExactMatch = /*#__PURE__*/function (_BaseMatch) {
  970. _inherits(ExactMatch, _BaseMatch);
  971. var _super = _createSuper(ExactMatch);
  972. function ExactMatch(pattern) {
  973. _classCallCheck(this, ExactMatch);
  974. return _super.call(this, pattern);
  975. }
  976. _createClass(ExactMatch, [{
  977. key: "search",
  978. value: function search(text) {
  979. var isMatch = text === this.pattern;
  980. return {
  981. isMatch: isMatch,
  982. score: isMatch ? 0 : 1,
  983. indices: [0, this.pattern.length - 1]
  984. };
  985. }
  986. }], [{
  987. key: "type",
  988. get: function get() {
  989. return 'exact';
  990. }
  991. }, {
  992. key: "multiRegex",
  993. get: function get() {
  994. return /^="(.*)"$/;
  995. }
  996. }, {
  997. key: "singleRegex",
  998. get: function get() {
  999. return /^=(.*)$/;
  1000. }
  1001. }]);
  1002. return ExactMatch;
  1003. }(BaseMatch);
  1004. var InverseExactMatch = /*#__PURE__*/function (_BaseMatch) {
  1005. _inherits(InverseExactMatch, _BaseMatch);
  1006. var _super = _createSuper(InverseExactMatch);
  1007. function InverseExactMatch(pattern) {
  1008. _classCallCheck(this, InverseExactMatch);
  1009. return _super.call(this, pattern);
  1010. }
  1011. _createClass(InverseExactMatch, [{
  1012. key: "search",
  1013. value: function search(text) {
  1014. var index = text.indexOf(this.pattern);
  1015. var isMatch = index === -1;
  1016. return {
  1017. isMatch: isMatch,
  1018. score: isMatch ? 0 : 1,
  1019. indices: [0, text.length - 1]
  1020. };
  1021. }
  1022. }], [{
  1023. key: "type",
  1024. get: function get() {
  1025. return 'inverse-exact';
  1026. }
  1027. }, {
  1028. key: "multiRegex",
  1029. get: function get() {
  1030. return /^!"(.*)"$/;
  1031. }
  1032. }, {
  1033. key: "singleRegex",
  1034. get: function get() {
  1035. return /^!(.*)$/;
  1036. }
  1037. }]);
  1038. return InverseExactMatch;
  1039. }(BaseMatch);
  1040. var PrefixExactMatch = /*#__PURE__*/function (_BaseMatch) {
  1041. _inherits(PrefixExactMatch, _BaseMatch);
  1042. var _super = _createSuper(PrefixExactMatch);
  1043. function PrefixExactMatch(pattern) {
  1044. _classCallCheck(this, PrefixExactMatch);
  1045. return _super.call(this, pattern);
  1046. }
  1047. _createClass(PrefixExactMatch, [{
  1048. key: "search",
  1049. value: function search(text) {
  1050. var isMatch = text.startsWith(this.pattern);
  1051. return {
  1052. isMatch: isMatch,
  1053. score: isMatch ? 0 : 1,
  1054. indices: [0, this.pattern.length - 1]
  1055. };
  1056. }
  1057. }], [{
  1058. key: "type",
  1059. get: function get() {
  1060. return 'prefix-exact';
  1061. }
  1062. }, {
  1063. key: "multiRegex",
  1064. get: function get() {
  1065. return /^\^"(.*)"$/;
  1066. }
  1067. }, {
  1068. key: "singleRegex",
  1069. get: function get() {
  1070. return /^\^(.*)$/;
  1071. }
  1072. }]);
  1073. return PrefixExactMatch;
  1074. }(BaseMatch);
  1075. var InversePrefixExactMatch = /*#__PURE__*/function (_BaseMatch) {
  1076. _inherits(InversePrefixExactMatch, _BaseMatch);
  1077. var _super = _createSuper(InversePrefixExactMatch);
  1078. function InversePrefixExactMatch(pattern) {
  1079. _classCallCheck(this, InversePrefixExactMatch);
  1080. return _super.call(this, pattern);
  1081. }
  1082. _createClass(InversePrefixExactMatch, [{
  1083. key: "search",
  1084. value: function search(text) {
  1085. var isMatch = !text.startsWith(this.pattern);
  1086. return {
  1087. isMatch: isMatch,
  1088. score: isMatch ? 0 : 1,
  1089. indices: [0, text.length - 1]
  1090. };
  1091. }
  1092. }], [{
  1093. key: "type",
  1094. get: function get() {
  1095. return 'inverse-prefix-exact';
  1096. }
  1097. }, {
  1098. key: "multiRegex",
  1099. get: function get() {
  1100. return /^!\^"(.*)"$/;
  1101. }
  1102. }, {
  1103. key: "singleRegex",
  1104. get: function get() {
  1105. return /^!\^(.*)$/;
  1106. }
  1107. }]);
  1108. return InversePrefixExactMatch;
  1109. }(BaseMatch);
  1110. var SuffixExactMatch = /*#__PURE__*/function (_BaseMatch) {
  1111. _inherits(SuffixExactMatch, _BaseMatch);
  1112. var _super = _createSuper(SuffixExactMatch);
  1113. function SuffixExactMatch(pattern) {
  1114. _classCallCheck(this, SuffixExactMatch);
  1115. return _super.call(this, pattern);
  1116. }
  1117. _createClass(SuffixExactMatch, [{
  1118. key: "search",
  1119. value: function search(text) {
  1120. var isMatch = text.endsWith(this.pattern);
  1121. return {
  1122. isMatch: isMatch,
  1123. score: isMatch ? 0 : 1,
  1124. indices: [text.length - this.pattern.length, text.length - 1]
  1125. };
  1126. }
  1127. }], [{
  1128. key: "type",
  1129. get: function get() {
  1130. return 'suffix-exact';
  1131. }
  1132. }, {
  1133. key: "multiRegex",
  1134. get: function get() {
  1135. return /^"(.*)"\$$/;
  1136. }
  1137. }, {
  1138. key: "singleRegex",
  1139. get: function get() {
  1140. return /^(.*)\$$/;
  1141. }
  1142. }]);
  1143. return SuffixExactMatch;
  1144. }(BaseMatch);
  1145. var InverseSuffixExactMatch = /*#__PURE__*/function (_BaseMatch) {
  1146. _inherits(InverseSuffixExactMatch, _BaseMatch);
  1147. var _super = _createSuper(InverseSuffixExactMatch);
  1148. function InverseSuffixExactMatch(pattern) {
  1149. _classCallCheck(this, InverseSuffixExactMatch);
  1150. return _super.call(this, pattern);
  1151. }
  1152. _createClass(InverseSuffixExactMatch, [{
  1153. key: "search",
  1154. value: function search(text) {
  1155. var isMatch = !text.endsWith(this.pattern);
  1156. return {
  1157. isMatch: isMatch,
  1158. score: isMatch ? 0 : 1,
  1159. indices: [0, text.length - 1]
  1160. };
  1161. }
  1162. }], [{
  1163. key: "type",
  1164. get: function get() {
  1165. return 'inverse-suffix-exact';
  1166. }
  1167. }, {
  1168. key: "multiRegex",
  1169. get: function get() {
  1170. return /^!"(.*)"\$$/;
  1171. }
  1172. }, {
  1173. key: "singleRegex",
  1174. get: function get() {
  1175. return /^!(.*)\$$/;
  1176. }
  1177. }]);
  1178. return InverseSuffixExactMatch;
  1179. }(BaseMatch);
  1180. var FuzzyMatch = /*#__PURE__*/function (_BaseMatch) {
  1181. _inherits(FuzzyMatch, _BaseMatch);
  1182. var _super = _createSuper(FuzzyMatch);
  1183. function FuzzyMatch(pattern) {
  1184. var _this;
  1185. var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
  1186. _ref$location = _ref.location,
  1187. location = _ref$location === void 0 ? Config.location : _ref$location,
  1188. _ref$threshold = _ref.threshold,
  1189. threshold = _ref$threshold === void 0 ? Config.threshold : _ref$threshold,
  1190. _ref$distance = _ref.distance,
  1191. distance = _ref$distance === void 0 ? Config.distance : _ref$distance,
  1192. _ref$includeMatches = _ref.includeMatches,
  1193. includeMatches = _ref$includeMatches === void 0 ? Config.includeMatches : _ref$includeMatches,
  1194. _ref$findAllMatches = _ref.findAllMatches,
  1195. findAllMatches = _ref$findAllMatches === void 0 ? Config.findAllMatches : _ref$findAllMatches,
  1196. _ref$minMatchCharLeng = _ref.minMatchCharLength,
  1197. minMatchCharLength = _ref$minMatchCharLeng === void 0 ? Config.minMatchCharLength : _ref$minMatchCharLeng,
  1198. _ref$isCaseSensitive = _ref.isCaseSensitive,
  1199. isCaseSensitive = _ref$isCaseSensitive === void 0 ? Config.isCaseSensitive : _ref$isCaseSensitive,
  1200. _ref$ignoreLocation = _ref.ignoreLocation,
  1201. ignoreLocation = _ref$ignoreLocation === void 0 ? Config.ignoreLocation : _ref$ignoreLocation;
  1202. _classCallCheck(this, FuzzyMatch);
  1203. _this = _super.call(this, pattern);
  1204. _this._bitapSearch = new BitapSearch(pattern, {
  1205. location: location,
  1206. threshold: threshold,
  1207. distance: distance,
  1208. includeMatches: includeMatches,
  1209. findAllMatches: findAllMatches,
  1210. minMatchCharLength: minMatchCharLength,
  1211. isCaseSensitive: isCaseSensitive,
  1212. ignoreLocation: ignoreLocation
  1213. });
  1214. return _this;
  1215. }
  1216. _createClass(FuzzyMatch, [{
  1217. key: "search",
  1218. value: function search(text) {
  1219. return this._bitapSearch.searchIn(text);
  1220. }
  1221. }], [{
  1222. key: "type",
  1223. get: function get() {
  1224. return 'fuzzy';
  1225. }
  1226. }, {
  1227. key: "multiRegex",
  1228. get: function get() {
  1229. return /^"(.*)"$/;
  1230. }
  1231. }, {
  1232. key: "singleRegex",
  1233. get: function get() {
  1234. return /^(.*)$/;
  1235. }
  1236. }]);
  1237. return FuzzyMatch;
  1238. }(BaseMatch);
  1239. var IncludeMatch = /*#__PURE__*/function (_BaseMatch) {
  1240. _inherits(IncludeMatch, _BaseMatch);
  1241. var _super = _createSuper(IncludeMatch);
  1242. function IncludeMatch(pattern) {
  1243. _classCallCheck(this, IncludeMatch);
  1244. return _super.call(this, pattern);
  1245. }
  1246. _createClass(IncludeMatch, [{
  1247. key: "search",
  1248. value: function search(text) {
  1249. var location = 0;
  1250. var index;
  1251. var indices = [];
  1252. var patternLen = this.pattern.length; // Get all exact matches
  1253. while ((index = text.indexOf(this.pattern, location)) > -1) {
  1254. location = index + patternLen;
  1255. indices.push([index, location - 1]);
  1256. }
  1257. var isMatch = !!indices.length;
  1258. return {
  1259. isMatch: isMatch,
  1260. score: isMatch ? 0 : 1,
  1261. indices: indices
  1262. };
  1263. }
  1264. }], [{
  1265. key: "type",
  1266. get: function get() {
  1267. return 'include';
  1268. }
  1269. }, {
  1270. key: "multiRegex",
  1271. get: function get() {
  1272. return /^'"(.*)"$/;
  1273. }
  1274. }, {
  1275. key: "singleRegex",
  1276. get: function get() {
  1277. return /^'(.*)$/;
  1278. }
  1279. }]);
  1280. return IncludeMatch;
  1281. }(BaseMatch);
  1282. var searchers = [ExactMatch, IncludeMatch, PrefixExactMatch, InversePrefixExactMatch, InverseSuffixExactMatch, SuffixExactMatch, InverseExactMatch, FuzzyMatch];
  1283. var searchersLen = searchers.length; // Regex to split by spaces, but keep anything in quotes together
  1284. var SPACE_RE = / +(?=([^\"]*\"[^\"]*\")*[^\"]*$)/;
  1285. var OR_TOKEN = '|'; // Return a 2D array representation of the query, for simpler parsing.
  1286. // Example:
  1287. // "^core go$ | rb$ | py$ xy$" => [["^core", "go$"], ["rb$"], ["py$", "xy$"]]
  1288. function parseQuery(pattern) {
  1289. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  1290. return pattern.split(OR_TOKEN).map(function (item) {
  1291. var query = item.trim().split(SPACE_RE).filter(function (item) {
  1292. return item && !!item.trim();
  1293. });
  1294. var results = [];
  1295. for (var i = 0, len = query.length; i < len; i += 1) {
  1296. var queryItem = query[i]; // 1. Handle multiple query match (i.e, once that are quoted, like `"hello world"`)
  1297. var found = false;
  1298. var idx = -1;
  1299. while (!found && ++idx < searchersLen) {
  1300. var searcher = searchers[idx];
  1301. var token = searcher.isMultiMatch(queryItem);
  1302. if (token) {
  1303. results.push(new searcher(token, options));
  1304. found = true;
  1305. }
  1306. }
  1307. if (found) {
  1308. continue;
  1309. } // 2. Handle single query matches (i.e, once that are *not* quoted)
  1310. idx = -1;
  1311. while (++idx < searchersLen) {
  1312. var _searcher = searchers[idx];
  1313. var _token = _searcher.isSingleMatch(queryItem);
  1314. if (_token) {
  1315. results.push(new _searcher(_token, options));
  1316. break;
  1317. }
  1318. }
  1319. }
  1320. return results;
  1321. });
  1322. }
  1323. // to a singl match
  1324. var MultiMatchSet = new Set([FuzzyMatch.type, IncludeMatch.type]);
  1325. /**
  1326. * Command-like searching
  1327. * ======================
  1328. *
  1329. * Given multiple search terms delimited by spaces.e.g. `^jscript .python$ ruby !java`,
  1330. * search in a given text.
  1331. *
  1332. * Search syntax:
  1333. *
  1334. * | Token | Match type | Description |
  1335. * | ----------- | -------------------------- | -------------------------------------- |
  1336. * | `jscript` | fuzzy-match | Items that fuzzy match `jscript` |
  1337. * | `=scheme` | exact-match | Items that are `scheme` |
  1338. * | `'python` | include-match | Items that include `python` |
  1339. * | `!ruby` | inverse-exact-match | Items that do not include `ruby` |
  1340. * | `^java` | prefix-exact-match | Items that start with `java` |
  1341. * | `!^earlang` | inverse-prefix-exact-match | Items that do not start with `earlang` |
  1342. * | `.js$` | suffix-exact-match | Items that end with `.js` |
  1343. * | `!.go$` | inverse-suffix-exact-match | Items that do not end with `.go` |
  1344. *
  1345. * A single pipe character acts as an OR operator. For example, the following
  1346. * query matches entries that start with `core` and end with either`go`, `rb`,
  1347. * or`py`.
  1348. *
  1349. * ```
  1350. * ^core go$ | rb$ | py$
  1351. * ```
  1352. */
  1353. var ExtendedSearch = /*#__PURE__*/function () {
  1354. function ExtendedSearch(pattern) {
  1355. var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
  1356. _ref$isCaseSensitive = _ref.isCaseSensitive,
  1357. isCaseSensitive = _ref$isCaseSensitive === void 0 ? Config.isCaseSensitive : _ref$isCaseSensitive,
  1358. _ref$includeMatches = _ref.includeMatches,
  1359. includeMatches = _ref$includeMatches === void 0 ? Config.includeMatches : _ref$includeMatches,
  1360. _ref$minMatchCharLeng = _ref.minMatchCharLength,
  1361. minMatchCharLength = _ref$minMatchCharLeng === void 0 ? Config.minMatchCharLength : _ref$minMatchCharLeng,
  1362. _ref$ignoreLocation = _ref.ignoreLocation,
  1363. ignoreLocation = _ref$ignoreLocation === void 0 ? Config.ignoreLocation : _ref$ignoreLocation,
  1364. _ref$findAllMatches = _ref.findAllMatches,
  1365. findAllMatches = _ref$findAllMatches === void 0 ? Config.findAllMatches : _ref$findAllMatches,
  1366. _ref$location = _ref.location,
  1367. location = _ref$location === void 0 ? Config.location : _ref$location,
  1368. _ref$threshold = _ref.threshold,
  1369. threshold = _ref$threshold === void 0 ? Config.threshold : _ref$threshold,
  1370. _ref$distance = _ref.distance,
  1371. distance = _ref$distance === void 0 ? Config.distance : _ref$distance;
  1372. _classCallCheck(this, ExtendedSearch);
  1373. this.query = null;
  1374. this.options = {
  1375. isCaseSensitive: isCaseSensitive,
  1376. includeMatches: includeMatches,
  1377. minMatchCharLength: minMatchCharLength,
  1378. findAllMatches: findAllMatches,
  1379. ignoreLocation: ignoreLocation,
  1380. location: location,
  1381. threshold: threshold,
  1382. distance: distance
  1383. };
  1384. this.pattern = isCaseSensitive ? pattern : pattern.toLowerCase();
  1385. this.query = parseQuery(this.pattern, this.options);
  1386. }
  1387. _createClass(ExtendedSearch, [{
  1388. key: "searchIn",
  1389. value: function searchIn(text) {
  1390. var query = this.query;
  1391. if (!query) {
  1392. return {
  1393. isMatch: false,
  1394. score: 1
  1395. };
  1396. }
  1397. var _this$options = this.options,
  1398. includeMatches = _this$options.includeMatches,
  1399. isCaseSensitive = _this$options.isCaseSensitive;
  1400. text = isCaseSensitive ? text : text.toLowerCase();
  1401. var numMatches = 0;
  1402. var allIndices = [];
  1403. var totalScore = 0; // ORs
  1404. for (var i = 0, qLen = query.length; i < qLen; i += 1) {
  1405. var searchers = query[i]; // Reset indices
  1406. allIndices.length = 0;
  1407. numMatches = 0; // ANDs
  1408. for (var j = 0, pLen = searchers.length; j < pLen; j += 1) {
  1409. var searcher = searchers[j];
  1410. var _searcher$search = searcher.search(text),
  1411. isMatch = _searcher$search.isMatch,
  1412. indices = _searcher$search.indices,
  1413. score = _searcher$search.score;
  1414. if (isMatch) {
  1415. numMatches += 1;
  1416. totalScore += score;
  1417. if (includeMatches) {
  1418. var type = searcher.constructor.type;
  1419. if (MultiMatchSet.has(type)) {
  1420. allIndices = [].concat(_toConsumableArray(allIndices), _toConsumableArray(indices));
  1421. } else {
  1422. allIndices.push(indices);
  1423. }
  1424. }
  1425. } else {
  1426. totalScore = 0;
  1427. numMatches = 0;
  1428. allIndices.length = 0;
  1429. break;
  1430. }
  1431. } // OR condition, so if TRUE, return
  1432. if (numMatches) {
  1433. var result = {
  1434. isMatch: true,
  1435. score: totalScore / numMatches
  1436. };
  1437. if (includeMatches) {
  1438. result.indices = allIndices;
  1439. }
  1440. return result;
  1441. }
  1442. } // Nothing was matched
  1443. return {
  1444. isMatch: false,
  1445. score: 1
  1446. };
  1447. }
  1448. }], [{
  1449. key: "condition",
  1450. value: function condition(_, options) {
  1451. return options.useExtendedSearch;
  1452. }
  1453. }]);
  1454. return ExtendedSearch;
  1455. }();
  1456. var registeredSearchers = [];
  1457. function register() {
  1458. registeredSearchers.push.apply(registeredSearchers, arguments);
  1459. }
  1460. function createSearcher(pattern, options) {
  1461. for (var i = 0, len = registeredSearchers.length; i < len; i += 1) {
  1462. var searcherClass = registeredSearchers[i];
  1463. if (searcherClass.condition(pattern, options)) {
  1464. return new searcherClass(pattern, options);
  1465. }
  1466. }
  1467. return new BitapSearch(pattern, options);
  1468. }
  1469. var LogicalOperator = {
  1470. AND: '$and',
  1471. OR: '$or'
  1472. };
  1473. var KeyType = {
  1474. PATH: '$path',
  1475. PATTERN: '$val'
  1476. };
  1477. var isExpression = function isExpression(query) {
  1478. return !!(query[LogicalOperator.AND] || query[LogicalOperator.OR]);
  1479. };
  1480. var isPath = function isPath(query) {
  1481. return !!query[KeyType.PATH];
  1482. };
  1483. var isLeaf = function isLeaf(query) {
  1484. return !isArray(query) && isObject(query) && !isExpression(query);
  1485. };
  1486. var convertToExplicit = function convertToExplicit(query) {
  1487. return _defineProperty({}, LogicalOperator.AND, Object.keys(query).map(function (key) {
  1488. return _defineProperty({}, key, query[key]);
  1489. }));
  1490. }; // When `auto` is `true`, the parse function will infer and initialize and add
  1491. // the appropriate `Searcher` instance
  1492. function parse(query, options) {
  1493. var _ref3 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {},
  1494. _ref3$auto = _ref3.auto,
  1495. auto = _ref3$auto === void 0 ? true : _ref3$auto;
  1496. var next = function next(query) {
  1497. var keys = Object.keys(query);
  1498. var isQueryPath = isPath(query);
  1499. if (!isQueryPath && keys.length > 1 && !isExpression(query)) {
  1500. return next(convertToExplicit(query));
  1501. }
  1502. if (isLeaf(query)) {
  1503. var key = isQueryPath ? query[KeyType.PATH] : keys[0];
  1504. var pattern = isQueryPath ? query[KeyType.PATTERN] : query[key];
  1505. if (!isString(pattern)) {
  1506. throw new Error(LOGICAL_SEARCH_INVALID_QUERY_FOR_KEY(key));
  1507. }
  1508. var obj = {
  1509. keyId: createKeyId(key),
  1510. pattern: pattern
  1511. };
  1512. if (auto) {
  1513. obj.searcher = createSearcher(pattern, options);
  1514. }
  1515. return obj;
  1516. }
  1517. var node = {
  1518. children: [],
  1519. operator: keys[0]
  1520. };
  1521. keys.forEach(function (key) {
  1522. var value = query[key];
  1523. if (isArray(value)) {
  1524. value.forEach(function (item) {
  1525. node.children.push(next(item));
  1526. });
  1527. }
  1528. });
  1529. return node;
  1530. };
  1531. if (!isExpression(query)) {
  1532. query = convertToExplicit(query);
  1533. }
  1534. return next(query);
  1535. }
  1536. var Fuse = /*#__PURE__*/function () {
  1537. function Fuse(docs) {
  1538. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  1539. var index = arguments.length > 2 ? arguments[2] : undefined;
  1540. _classCallCheck(this, Fuse);
  1541. this.options = _objectSpread2({}, Config, {}, options);
  1542. if (this.options.useExtendedSearch && !true) {
  1543. throw new Error(EXTENDED_SEARCH_UNAVAILABLE);
  1544. }
  1545. this._keyStore = new KeyStore(this.options.keys);
  1546. this.setCollection(docs, index);
  1547. }
  1548. _createClass(Fuse, [{
  1549. key: "setCollection",
  1550. value: function setCollection(docs, index) {
  1551. this._docs = docs;
  1552. if (index && !(index instanceof FuseIndex)) {
  1553. throw new Error(INCORRECT_INDEX_TYPE);
  1554. }
  1555. this._myIndex = index || createIndex(this.options.keys, this._docs, {
  1556. getFn: this.options.getFn
  1557. });
  1558. }
  1559. }, {
  1560. key: "add",
  1561. value: function add(doc) {
  1562. if (!isDefined(doc)) {
  1563. return;
  1564. }
  1565. this._docs.push(doc);
  1566. this._myIndex.add(doc);
  1567. }
  1568. }, {
  1569. key: "remove",
  1570. value: function remove() {
  1571. var predicate = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : function () {
  1572. return (
  1573. /* doc, idx */
  1574. false
  1575. );
  1576. };
  1577. var results = [];
  1578. for (var i = 0, len = this._docs.length; i < len; i += 1) {
  1579. var doc = this._docs[i];
  1580. if (predicate(doc, i)) {
  1581. this.removeAt(i);
  1582. i -= 1;
  1583. len -= 1;
  1584. results.push(doc);
  1585. }
  1586. }
  1587. return results;
  1588. }
  1589. }, {
  1590. key: "removeAt",
  1591. value: function removeAt(idx) {
  1592. this._docs.splice(idx, 1);
  1593. this._myIndex.removeAt(idx);
  1594. }
  1595. }, {
  1596. key: "getIndex",
  1597. value: function getIndex() {
  1598. return this._myIndex;
  1599. }
  1600. }, {
  1601. key: "search",
  1602. value: function search(query) {
  1603. var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
  1604. _ref$limit = _ref.limit,
  1605. limit = _ref$limit === void 0 ? -1 : _ref$limit;
  1606. var _this$options = this.options,
  1607. includeMatches = _this$options.includeMatches,
  1608. includeScore = _this$options.includeScore,
  1609. shouldSort = _this$options.shouldSort,
  1610. sortFn = _this$options.sortFn,
  1611. ignoreFieldNorm = _this$options.ignoreFieldNorm;
  1612. var results = isString(query) ? isString(this._docs[0]) ? this._searchStringList(query) : this._searchObjectList(query) : this._searchLogical(query);
  1613. computeScore$1(results, {
  1614. ignoreFieldNorm: ignoreFieldNorm
  1615. });
  1616. if (shouldSort) {
  1617. results.sort(sortFn);
  1618. }
  1619. if (isNumber(limit) && limit > -1) {
  1620. results = results.slice(0, limit);
  1621. }
  1622. return format(results, this._docs, {
  1623. includeMatches: includeMatches,
  1624. includeScore: includeScore
  1625. });
  1626. }
  1627. }, {
  1628. key: "_searchStringList",
  1629. value: function _searchStringList(query) {
  1630. var searcher = createSearcher(query, this.options);
  1631. var records = this._myIndex.records;
  1632. var results = []; // Iterate over every string in the index
  1633. records.forEach(function (_ref2) {
  1634. var text = _ref2.v,
  1635. idx = _ref2.i,
  1636. norm = _ref2.n;
  1637. if (!isDefined(text)) {
  1638. return;
  1639. }
  1640. var _searcher$searchIn = searcher.searchIn(text),
  1641. isMatch = _searcher$searchIn.isMatch,
  1642. score = _searcher$searchIn.score,
  1643. indices = _searcher$searchIn.indices;
  1644. if (isMatch) {
  1645. results.push({
  1646. item: text,
  1647. idx: idx,
  1648. matches: [{
  1649. score: score,
  1650. value: text,
  1651. norm: norm,
  1652. indices: indices
  1653. }]
  1654. });
  1655. }
  1656. });
  1657. return results;
  1658. }
  1659. }, {
  1660. key: "_searchLogical",
  1661. value: function _searchLogical(query) {
  1662. var _this = this;
  1663. var expression = parse(query, this.options);
  1664. var evaluate = function evaluate(node, item, idx) {
  1665. if (!node.children) {
  1666. var keyId = node.keyId,
  1667. searcher = node.searcher;
  1668. var matches = _this._findMatches({
  1669. key: _this._keyStore.get(keyId),
  1670. value: _this._myIndex.getValueForItemAtKeyId(item, keyId),
  1671. searcher: searcher
  1672. });
  1673. if (matches && matches.length) {
  1674. return [{
  1675. idx: idx,
  1676. item: item,
  1677. matches: matches
  1678. }];
  1679. }
  1680. return [];
  1681. }
  1682. /*eslint indent: [2, 2, {"SwitchCase": 1}]*/
  1683. switch (node.operator) {
  1684. case LogicalOperator.AND:
  1685. {
  1686. var res = [];
  1687. for (var i = 0, len = node.children.length; i < len; i += 1) {
  1688. var child = node.children[i];
  1689. var result = evaluate(child, item, idx);
  1690. if (result.length) {
  1691. res.push.apply(res, _toConsumableArray(result));
  1692. } else {
  1693. return [];
  1694. }
  1695. }
  1696. return res;
  1697. }
  1698. case LogicalOperator.OR:
  1699. {
  1700. var _res = [];
  1701. for (var _i = 0, _len = node.children.length; _i < _len; _i += 1) {
  1702. var _child = node.children[_i];
  1703. var _result = evaluate(_child, item, idx);
  1704. if (_result.length) {
  1705. _res.push.apply(_res, _toConsumableArray(_result));
  1706. break;
  1707. }
  1708. }
  1709. return _res;
  1710. }
  1711. }
  1712. };
  1713. var records = this._myIndex.records;
  1714. var resultMap = {};
  1715. var results = [];
  1716. records.forEach(function (_ref3) {
  1717. var item = _ref3.$,
  1718. idx = _ref3.i;
  1719. if (isDefined(item)) {
  1720. var expResults = evaluate(expression, item, idx);
  1721. if (expResults.length) {
  1722. // Dedupe when adding
  1723. if (!resultMap[idx]) {
  1724. resultMap[idx] = {
  1725. idx: idx,
  1726. item: item,
  1727. matches: []
  1728. };
  1729. results.push(resultMap[idx]);
  1730. }
  1731. expResults.forEach(function (_ref4) {
  1732. var _resultMap$idx$matche;
  1733. var matches = _ref4.matches;
  1734. (_resultMap$idx$matche = resultMap[idx].matches).push.apply(_resultMap$idx$matche, _toConsumableArray(matches));
  1735. });
  1736. }
  1737. }
  1738. });
  1739. return results;
  1740. }
  1741. }, {
  1742. key: "_searchObjectList",
  1743. value: function _searchObjectList(query) {
  1744. var _this2 = this;
  1745. var searcher = createSearcher(query, this.options);
  1746. var _this$_myIndex = this._myIndex,
  1747. keys = _this$_myIndex.keys,
  1748. records = _this$_myIndex.records;
  1749. var results = []; // List is Array<Object>
  1750. records.forEach(function (_ref5) {
  1751. var item = _ref5.$,
  1752. idx = _ref5.i;
  1753. if (!isDefined(item)) {
  1754. return;
  1755. }
  1756. var matches = []; // Iterate over every key (i.e, path), and fetch the value at that key
  1757. keys.forEach(function (key, keyIndex) {
  1758. matches.push.apply(matches, _toConsumableArray(_this2._findMatches({
  1759. key: key,
  1760. value: item[keyIndex],
  1761. searcher: searcher
  1762. })));
  1763. });
  1764. if (matches.length) {
  1765. results.push({
  1766. idx: idx,
  1767. item: item,
  1768. matches: matches
  1769. });
  1770. }
  1771. });
  1772. return results;
  1773. }
  1774. }, {
  1775. key: "_findMatches",
  1776. value: function _findMatches(_ref6) {
  1777. var key = _ref6.key,
  1778. value = _ref6.value,
  1779. searcher = _ref6.searcher;
  1780. if (!isDefined(value)) {
  1781. return [];
  1782. }
  1783. var matches = [];
  1784. if (isArray(value)) {
  1785. value.forEach(function (_ref7) {
  1786. var text = _ref7.v,
  1787. idx = _ref7.i,
  1788. norm = _ref7.n;
  1789. if (!isDefined(text)) {
  1790. return;
  1791. }
  1792. var _searcher$searchIn2 = searcher.searchIn(text),
  1793. isMatch = _searcher$searchIn2.isMatch,
  1794. score = _searcher$searchIn2.score,
  1795. indices = _searcher$searchIn2.indices;
  1796. if (isMatch) {
  1797. matches.push({
  1798. score: score,
  1799. key: key,
  1800. value: text,
  1801. idx: idx,
  1802. norm: norm,
  1803. indices: indices
  1804. });
  1805. }
  1806. });
  1807. } else {
  1808. var text = value.v,
  1809. norm = value.n;
  1810. var _searcher$searchIn3 = searcher.searchIn(text),
  1811. isMatch = _searcher$searchIn3.isMatch,
  1812. score = _searcher$searchIn3.score,
  1813. indices = _searcher$searchIn3.indices;
  1814. if (isMatch) {
  1815. matches.push({
  1816. score: score,
  1817. key: key,
  1818. value: text,
  1819. norm: norm,
  1820. indices: indices
  1821. });
  1822. }
  1823. }
  1824. return matches;
  1825. }
  1826. }]);
  1827. return Fuse;
  1828. }(); // Practical scoring function
  1829. function computeScore$1(results, _ref8) {
  1830. var _ref8$ignoreFieldNorm = _ref8.ignoreFieldNorm,
  1831. ignoreFieldNorm = _ref8$ignoreFieldNorm === void 0 ? Config.ignoreFieldNorm : _ref8$ignoreFieldNorm;
  1832. results.forEach(function (result) {
  1833. var totalScore = 1;
  1834. result.matches.forEach(function (_ref9) {
  1835. var key = _ref9.key,
  1836. norm = _ref9.norm,
  1837. score = _ref9.score;
  1838. var weight = key ? key.weight : null;
  1839. totalScore *= Math.pow(score === 0 && weight ? Number.EPSILON : score, (weight || 1) * (ignoreFieldNorm ? 1 : norm));
  1840. });
  1841. result.score = totalScore;
  1842. });
  1843. }
  1844. function format(results, docs) {
  1845. var _ref10 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {},
  1846. _ref10$includeMatches = _ref10.includeMatches,
  1847. includeMatches = _ref10$includeMatches === void 0 ? Config.includeMatches : _ref10$includeMatches,
  1848. _ref10$includeScore = _ref10.includeScore,
  1849. includeScore = _ref10$includeScore === void 0 ? Config.includeScore : _ref10$includeScore;
  1850. var transformers = [];
  1851. if (includeMatches) transformers.push(transformMatches);
  1852. if (includeScore) transformers.push(transformScore);
  1853. return results.map(function (result) {
  1854. var idx = result.idx;
  1855. var data = {
  1856. item: docs[idx],
  1857. refIndex: idx
  1858. };
  1859. if (transformers.length) {
  1860. transformers.forEach(function (transformer) {
  1861. transformer(result, data);
  1862. });
  1863. }
  1864. return data;
  1865. });
  1866. }
  1867. Fuse.version = '6.4.5';
  1868. Fuse.createIndex = createIndex;
  1869. Fuse.parseIndex = parseIndex;
  1870. Fuse.config = Config;
  1871. {
  1872. Fuse.parseQuery = parse;
  1873. }
  1874. {
  1875. register(ExtendedSearch);
  1876. }
  1877. return Fuse;
  1878. })));