reg-cli 0.18.16 → 0.19.0-rc1

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.
@@ -1,1535 +0,0 @@
1
- (function() {
2
- "use strict";
3
- function isArray(value) {
4
- return !Array.isArray ? getTag(value) === "[object Array]" : Array.isArray(value);
5
- }
6
- function baseToString(value) {
7
- if (typeof value == "string") {
8
- return value;
9
- }
10
- let result = value + "";
11
- return result == "0" && 1 / value == -Infinity ? "-0" : result;
12
- }
13
- function toString(value) {
14
- return value == null ? "" : baseToString(value);
15
- }
16
- function isString(value) {
17
- return typeof value === "string";
18
- }
19
- function isNumber(value) {
20
- return typeof value === "number";
21
- }
22
- function isBoolean(value) {
23
- return value === true || value === false || isObjectLike(value) && getTag(value) == "[object Boolean]";
24
- }
25
- function isObject(value) {
26
- return typeof value === "object";
27
- }
28
- function isObjectLike(value) {
29
- return isObject(value) && value !== null;
30
- }
31
- function isDefined(value) {
32
- return value !== void 0 && value !== null;
33
- }
34
- function isBlank(value) {
35
- return !value.trim().length;
36
- }
37
- function getTag(value) {
38
- return value == null ? value === void 0 ? "[object Undefined]" : "[object Null]" : Object.prototype.toString.call(value);
39
- }
40
- const INCORRECT_INDEX_TYPE = "Incorrect 'index' type";
41
- const LOGICAL_SEARCH_INVALID_QUERY_FOR_KEY = (key) => `Invalid value for key ${key}`;
42
- const PATTERN_LENGTH_TOO_LARGE = (max) => `Pattern length exceeds max of ${max}.`;
43
- const MISSING_KEY_PROPERTY = (name) => `Missing ${name} property in key`;
44
- const INVALID_KEY_WEIGHT_VALUE = (key) => `Property 'weight' in key '${key}' must be a positive integer`;
45
- const hasOwn = Object.prototype.hasOwnProperty;
46
- class KeyStore {
47
- constructor(keys) {
48
- this._keys = [];
49
- this._keyMap = {};
50
- let totalWeight = 0;
51
- keys.forEach((key) => {
52
- let obj = createKey(key);
53
- this._keys.push(obj);
54
- this._keyMap[obj.id] = obj;
55
- totalWeight += obj.weight;
56
- });
57
- this._keys.forEach((key) => {
58
- key.weight /= totalWeight;
59
- });
60
- }
61
- get(keyId) {
62
- return this._keyMap[keyId];
63
- }
64
- keys() {
65
- return this._keys;
66
- }
67
- toJSON() {
68
- return JSON.stringify(this._keys);
69
- }
70
- }
71
- function createKey(key) {
72
- let path = null;
73
- let id = null;
74
- let src = null;
75
- let weight = 1;
76
- let getFn = null;
77
- if (isString(key) || isArray(key)) {
78
- src = key;
79
- path = createKeyPath(key);
80
- id = createKeyId(key);
81
- } else {
82
- if (!hasOwn.call(key, "name")) {
83
- throw new Error(MISSING_KEY_PROPERTY("name"));
84
- }
85
- const name = key.name;
86
- src = name;
87
- if (hasOwn.call(key, "weight")) {
88
- weight = key.weight;
89
- if (weight <= 0) {
90
- throw new Error(INVALID_KEY_WEIGHT_VALUE(name));
91
- }
92
- }
93
- path = createKeyPath(name);
94
- id = createKeyId(name);
95
- getFn = key.getFn;
96
- }
97
- return { path, id, weight, src, getFn };
98
- }
99
- function createKeyPath(key) {
100
- return isArray(key) ? key : key.split(".");
101
- }
102
- function createKeyId(key) {
103
- return isArray(key) ? key.join(".") : key;
104
- }
105
- function get(obj, path) {
106
- let list = [];
107
- let arr = false;
108
- const deepGet = (obj2, path2, index) => {
109
- if (!isDefined(obj2)) {
110
- return;
111
- }
112
- if (!path2[index]) {
113
- list.push(obj2);
114
- } else {
115
- let key = path2[index];
116
- const value = obj2[key];
117
- if (!isDefined(value)) {
118
- return;
119
- }
120
- if (index === path2.length - 1 && (isString(value) || isNumber(value) || isBoolean(value))) {
121
- list.push(toString(value));
122
- } else if (isArray(value)) {
123
- arr = true;
124
- for (let i = 0, len = value.length; i < len; i += 1) {
125
- deepGet(value[i], path2, index + 1);
126
- }
127
- } else if (path2.length) {
128
- deepGet(value, path2, index + 1);
129
- }
130
- }
131
- };
132
- deepGet(obj, isString(path) ? path.split(".") : path, 0);
133
- return arr ? list : list[0];
134
- }
135
- const MatchOptions = {
136
- // Whether the matches should be included in the result set. When `true`, each record in the result
137
- // set will include the indices of the matched characters.
138
- // These can consequently be used for highlighting purposes.
139
- includeMatches: false,
140
- // When `true`, the matching function will continue to the end of a search pattern even if
141
- // a perfect match has already been located in the string.
142
- findAllMatches: false,
143
- // Minimum number of characters that must be matched before a result is considered a match
144
- minMatchCharLength: 1
145
- };
146
- const BasicOptions = {
147
- // When `true`, the algorithm continues searching to the end of the input even if a perfect
148
- // match is found before the end of the same input.
149
- isCaseSensitive: false,
150
- // When `true`, the algorithm will ignore diacritics (accents) in comparisons
151
- ignoreDiacritics: false,
152
- // When true, the matching function will continue to the end of a search pattern even if
153
- includeScore: false,
154
- // List of properties that will be searched. This also supports nested properties.
155
- keys: [],
156
- // Whether to sort the result list, by score
157
- shouldSort: true,
158
- // Default sort function: sort by ascending score, ascending index
159
- sortFn: (a, b) => a.score === b.score ? a.idx < b.idx ? -1 : 1 : a.score < b.score ? -1 : 1
160
- };
161
- const FuzzyOptions = {
162
- // Approximately where in the text is the pattern expected to be found?
163
- location: 0,
164
- // At what point does the match algorithm give up. A threshold of '0.0' requires a perfect match
165
- // (of both letters and location), a threshold of '1.0' would match anything.
166
- threshold: 0.6,
167
- // Determines how close the match must be to the fuzzy location (specified above).
168
- // An exact letter match which is 'distance' characters away from the fuzzy location
169
- // would score as a complete mismatch. A distance of '0' requires the match be at
170
- // the exact location specified, a threshold of '1000' would require a perfect match
171
- // to be within 800 characters of the fuzzy location to be found using a 0.8 threshold.
172
- distance: 100
173
- };
174
- const AdvancedOptions = {
175
- // When `true`, it enables the use of unix-like search commands
176
- useExtendedSearch: false,
177
- // The get function to use when fetching an object's properties.
178
- // The default will search nested paths *ie foo.bar.baz*
179
- getFn: get,
180
- // When `true`, search will ignore `location` and `distance`, so it won't matter
181
- // where in the string the pattern appears.
182
- // More info: https://fusejs.io/concepts/scoring-theory.html#fuzziness-score
183
- ignoreLocation: false,
184
- // When `true`, the calculation for the relevance score (used for sorting) will
185
- // ignore the field-length norm.
186
- // More info: https://fusejs.io/concepts/scoring-theory.html#field-length-norm
187
- ignoreFieldNorm: false,
188
- // The weight to determine how much field length norm effects scoring.
189
- fieldNormWeight: 1
190
- };
191
- var Config = {
192
- ...BasicOptions,
193
- ...MatchOptions,
194
- ...FuzzyOptions,
195
- ...AdvancedOptions
196
- };
197
- const SPACE = /[^ ]+/g;
198
- function norm(weight = 1, mantissa = 3) {
199
- const cache = /* @__PURE__ */ new Map();
200
- const m = Math.pow(10, mantissa);
201
- return {
202
- get(value) {
203
- const numTokens = value.match(SPACE).length;
204
- if (cache.has(numTokens)) {
205
- return cache.get(numTokens);
206
- }
207
- const norm2 = 1 / Math.pow(numTokens, 0.5 * weight);
208
- const n = parseFloat(Math.round(norm2 * m) / m);
209
- cache.set(numTokens, n);
210
- return n;
211
- },
212
- clear() {
213
- cache.clear();
214
- }
215
- };
216
- }
217
- class FuseIndex {
218
- constructor({
219
- getFn = Config.getFn,
220
- fieldNormWeight = Config.fieldNormWeight
221
- } = {}) {
222
- this.norm = norm(fieldNormWeight, 3);
223
- this.getFn = getFn;
224
- this.isCreated = false;
225
- this.setIndexRecords();
226
- }
227
- setSources(docs = []) {
228
- this.docs = docs;
229
- }
230
- setIndexRecords(records = []) {
231
- this.records = records;
232
- }
233
- setKeys(keys = []) {
234
- this.keys = keys;
235
- this._keysMap = {};
236
- keys.forEach((key, idx) => {
237
- this._keysMap[key.id] = idx;
238
- });
239
- }
240
- create() {
241
- if (this.isCreated || !this.docs.length) {
242
- return;
243
- }
244
- this.isCreated = true;
245
- if (isString(this.docs[0])) {
246
- this.docs.forEach((doc, docIndex) => {
247
- this._addString(doc, docIndex);
248
- });
249
- } else {
250
- this.docs.forEach((doc, docIndex) => {
251
- this._addObject(doc, docIndex);
252
- });
253
- }
254
- this.norm.clear();
255
- }
256
- // Adds a doc to the end of the index
257
- add(doc) {
258
- const idx = this.size();
259
- if (isString(doc)) {
260
- this._addString(doc, idx);
261
- } else {
262
- this._addObject(doc, idx);
263
- }
264
- }
265
- // Removes the doc at the specified index of the index
266
- removeAt(idx) {
267
- this.records.splice(idx, 1);
268
- for (let i = idx, len = this.size(); i < len; i += 1) {
269
- this.records[i].i -= 1;
270
- }
271
- }
272
- getValueForItemAtKeyId(item, keyId) {
273
- return item[this._keysMap[keyId]];
274
- }
275
- size() {
276
- return this.records.length;
277
- }
278
- _addString(doc, docIndex) {
279
- if (!isDefined(doc) || isBlank(doc)) {
280
- return;
281
- }
282
- let record = {
283
- v: doc,
284
- i: docIndex,
285
- n: this.norm.get(doc)
286
- };
287
- this.records.push(record);
288
- }
289
- _addObject(doc, docIndex) {
290
- let record = { i: docIndex, $: {} };
291
- this.keys.forEach((key, keyIndex) => {
292
- let value = key.getFn ? key.getFn(doc) : this.getFn(doc, key.path);
293
- if (!isDefined(value)) {
294
- return;
295
- }
296
- if (isArray(value)) {
297
- let subRecords = [];
298
- const stack = [{ nestedArrIndex: -1, value }];
299
- while (stack.length) {
300
- const { nestedArrIndex, value: value2 } = stack.pop();
301
- if (!isDefined(value2)) {
302
- continue;
303
- }
304
- if (isString(value2) && !isBlank(value2)) {
305
- let subRecord = {
306
- v: value2,
307
- i: nestedArrIndex,
308
- n: this.norm.get(value2)
309
- };
310
- subRecords.push(subRecord);
311
- } else if (isArray(value2)) {
312
- value2.forEach((item, k) => {
313
- stack.push({
314
- nestedArrIndex: k,
315
- value: item
316
- });
317
- });
318
- } else ;
319
- }
320
- record.$[keyIndex] = subRecords;
321
- } else if (isString(value) && !isBlank(value)) {
322
- let subRecord = {
323
- v: value,
324
- n: this.norm.get(value)
325
- };
326
- record.$[keyIndex] = subRecord;
327
- }
328
- });
329
- this.records.push(record);
330
- }
331
- toJSON() {
332
- return {
333
- keys: this.keys,
334
- records: this.records
335
- };
336
- }
337
- }
338
- function createIndex(keys, docs, { getFn = Config.getFn, fieldNormWeight = Config.fieldNormWeight } = {}) {
339
- const myIndex = new FuseIndex({ getFn, fieldNormWeight });
340
- myIndex.setKeys(keys.map(createKey));
341
- myIndex.setSources(docs);
342
- myIndex.create();
343
- return myIndex;
344
- }
345
- function parseIndex(data, { getFn = Config.getFn, fieldNormWeight = Config.fieldNormWeight } = {}) {
346
- const { keys, records } = data;
347
- const myIndex = new FuseIndex({ getFn, fieldNormWeight });
348
- myIndex.setKeys(keys);
349
- myIndex.setIndexRecords(records);
350
- return myIndex;
351
- }
352
- function computeScore$1(pattern, {
353
- errors = 0,
354
- currentLocation = 0,
355
- expectedLocation = 0,
356
- distance = Config.distance,
357
- ignoreLocation = Config.ignoreLocation
358
- } = {}) {
359
- const accuracy = errors / pattern.length;
360
- if (ignoreLocation) {
361
- return accuracy;
362
- }
363
- const proximity = Math.abs(expectedLocation - currentLocation);
364
- if (!distance) {
365
- return proximity ? 1 : accuracy;
366
- }
367
- return accuracy + proximity / distance;
368
- }
369
- function convertMaskToIndices(matchmask = [], minMatchCharLength = Config.minMatchCharLength) {
370
- let indices = [];
371
- let start = -1;
372
- let end = -1;
373
- let i = 0;
374
- for (let len = matchmask.length; i < len; i += 1) {
375
- let match = matchmask[i];
376
- if (match && start === -1) {
377
- start = i;
378
- } else if (!match && start !== -1) {
379
- end = i - 1;
380
- if (end - start + 1 >= minMatchCharLength) {
381
- indices.push([start, end]);
382
- }
383
- start = -1;
384
- }
385
- }
386
- if (matchmask[i - 1] && i - start >= minMatchCharLength) {
387
- indices.push([start, i - 1]);
388
- }
389
- return indices;
390
- }
391
- const MAX_BITS = 32;
392
- function search(text, pattern, patternAlphabet, {
393
- location = Config.location,
394
- distance = Config.distance,
395
- threshold = Config.threshold,
396
- findAllMatches = Config.findAllMatches,
397
- minMatchCharLength = Config.minMatchCharLength,
398
- includeMatches = Config.includeMatches,
399
- ignoreLocation = Config.ignoreLocation
400
- } = {}) {
401
- if (pattern.length > MAX_BITS) {
402
- throw new Error(PATTERN_LENGTH_TOO_LARGE(MAX_BITS));
403
- }
404
- const patternLen = pattern.length;
405
- const textLen = text.length;
406
- const expectedLocation = Math.max(0, Math.min(location, textLen));
407
- let currentThreshold = threshold;
408
- let bestLocation = expectedLocation;
409
- const computeMatches = minMatchCharLength > 1 || includeMatches;
410
- const matchMask = computeMatches ? Array(textLen) : [];
411
- let index;
412
- while ((index = text.indexOf(pattern, bestLocation)) > -1) {
413
- let score = computeScore$1(pattern, {
414
- currentLocation: index,
415
- expectedLocation,
416
- distance,
417
- ignoreLocation
418
- });
419
- currentThreshold = Math.min(score, currentThreshold);
420
- bestLocation = index + patternLen;
421
- if (computeMatches) {
422
- let i = 0;
423
- while (i < patternLen) {
424
- matchMask[index + i] = 1;
425
- i += 1;
426
- }
427
- }
428
- }
429
- bestLocation = -1;
430
- let lastBitArr = [];
431
- let finalScore = 1;
432
- let binMax = patternLen + textLen;
433
- const mask = 1 << patternLen - 1;
434
- for (let i = 0; i < patternLen; i += 1) {
435
- let binMin = 0;
436
- let binMid = binMax;
437
- while (binMin < binMid) {
438
- const score2 = computeScore$1(pattern, {
439
- errors: i,
440
- currentLocation: expectedLocation + binMid,
441
- expectedLocation,
442
- distance,
443
- ignoreLocation
444
- });
445
- if (score2 <= currentThreshold) {
446
- binMin = binMid;
447
- } else {
448
- binMax = binMid;
449
- }
450
- binMid = Math.floor((binMax - binMin) / 2 + binMin);
451
- }
452
- binMax = binMid;
453
- let start = Math.max(1, expectedLocation - binMid + 1);
454
- let finish = findAllMatches ? textLen : Math.min(expectedLocation + binMid, textLen) + patternLen;
455
- let bitArr = Array(finish + 2);
456
- bitArr[finish + 1] = (1 << i) - 1;
457
- for (let j = finish; j >= start; j -= 1) {
458
- let currentLocation = j - 1;
459
- let charMatch = patternAlphabet[text.charAt(currentLocation)];
460
- if (computeMatches) {
461
- matchMask[currentLocation] = +!!charMatch;
462
- }
463
- bitArr[j] = (bitArr[j + 1] << 1 | 1) & charMatch;
464
- if (i) {
465
- bitArr[j] |= (lastBitArr[j + 1] | lastBitArr[j]) << 1 | 1 | lastBitArr[j + 1];
466
- }
467
- if (bitArr[j] & mask) {
468
- finalScore = computeScore$1(pattern, {
469
- errors: i,
470
- currentLocation,
471
- expectedLocation,
472
- distance,
473
- ignoreLocation
474
- });
475
- if (finalScore <= currentThreshold) {
476
- currentThreshold = finalScore;
477
- bestLocation = currentLocation;
478
- if (bestLocation <= expectedLocation) {
479
- break;
480
- }
481
- start = Math.max(1, 2 * expectedLocation - bestLocation);
482
- }
483
- }
484
- }
485
- const score = computeScore$1(pattern, {
486
- errors: i + 1,
487
- currentLocation: expectedLocation,
488
- expectedLocation,
489
- distance,
490
- ignoreLocation
491
- });
492
- if (score > currentThreshold) {
493
- break;
494
- }
495
- lastBitArr = bitArr;
496
- }
497
- const result = {
498
- isMatch: bestLocation >= 0,
499
- // Count exact matches (those with a score of 0) to be "almost" exact
500
- score: Math.max(1e-3, finalScore)
501
- };
502
- if (computeMatches) {
503
- const indices = convertMaskToIndices(matchMask, minMatchCharLength);
504
- if (!indices.length) {
505
- result.isMatch = false;
506
- } else if (includeMatches) {
507
- result.indices = indices;
508
- }
509
- }
510
- return result;
511
- }
512
- function createPatternAlphabet(pattern) {
513
- let mask = {};
514
- for (let i = 0, len = pattern.length; i < len; i += 1) {
515
- const char = pattern.charAt(i);
516
- mask[char] = (mask[char] || 0) | 1 << len - i - 1;
517
- }
518
- return mask;
519
- }
520
- const stripDiacritics = String.prototype.normalize ? (str) => str.normalize("NFD").replace(/[\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D3-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u09FE\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C00-\u0C04\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0D00-\u0D03\u0D3B\u0D3C\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u180B-\u180D\u1885\u1886\u18A9\u1920-\u192B\u1930-\u193B\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2-\u1CF4\u1CF7-\u1CF9\u1DC0-\u1DF9\u1DFB-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9E5\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F]/g, "") : (str) => str;
521
- class BitapSearch {
522
- constructor(pattern, {
523
- location = Config.location,
524
- threshold = Config.threshold,
525
- distance = Config.distance,
526
- includeMatches = Config.includeMatches,
527
- findAllMatches = Config.findAllMatches,
528
- minMatchCharLength = Config.minMatchCharLength,
529
- isCaseSensitive = Config.isCaseSensitive,
530
- ignoreDiacritics = Config.ignoreDiacritics,
531
- ignoreLocation = Config.ignoreLocation
532
- } = {}) {
533
- this.options = {
534
- location,
535
- threshold,
536
- distance,
537
- includeMatches,
538
- findAllMatches,
539
- minMatchCharLength,
540
- isCaseSensitive,
541
- ignoreDiacritics,
542
- ignoreLocation
543
- };
544
- pattern = isCaseSensitive ? pattern : pattern.toLowerCase();
545
- pattern = ignoreDiacritics ? stripDiacritics(pattern) : pattern;
546
- this.pattern = pattern;
547
- this.chunks = [];
548
- if (!this.pattern.length) {
549
- return;
550
- }
551
- const addChunk = (pattern2, startIndex) => {
552
- this.chunks.push({
553
- pattern: pattern2,
554
- alphabet: createPatternAlphabet(pattern2),
555
- startIndex
556
- });
557
- };
558
- const len = this.pattern.length;
559
- if (len > MAX_BITS) {
560
- let i = 0;
561
- const remainder = len % MAX_BITS;
562
- const end = len - remainder;
563
- while (i < end) {
564
- addChunk(this.pattern.substr(i, MAX_BITS), i);
565
- i += MAX_BITS;
566
- }
567
- if (remainder) {
568
- const startIndex = len - MAX_BITS;
569
- addChunk(this.pattern.substr(startIndex), startIndex);
570
- }
571
- } else {
572
- addChunk(this.pattern, 0);
573
- }
574
- }
575
- searchIn(text) {
576
- const { isCaseSensitive, ignoreDiacritics, includeMatches } = this.options;
577
- text = isCaseSensitive ? text : text.toLowerCase();
578
- text = ignoreDiacritics ? stripDiacritics(text) : text;
579
- if (this.pattern === text) {
580
- let result2 = {
581
- isMatch: true,
582
- score: 0
583
- };
584
- if (includeMatches) {
585
- result2.indices = [[0, text.length - 1]];
586
- }
587
- return result2;
588
- }
589
- const {
590
- location,
591
- distance,
592
- threshold,
593
- findAllMatches,
594
- minMatchCharLength,
595
- ignoreLocation
596
- } = this.options;
597
- let allIndices = [];
598
- let totalScore = 0;
599
- let hasMatches = false;
600
- this.chunks.forEach(({ pattern, alphabet, startIndex }) => {
601
- const { isMatch, score, indices } = search(text, pattern, alphabet, {
602
- location: location + startIndex,
603
- distance,
604
- threshold,
605
- findAllMatches,
606
- minMatchCharLength,
607
- includeMatches,
608
- ignoreLocation
609
- });
610
- if (isMatch) {
611
- hasMatches = true;
612
- }
613
- totalScore += score;
614
- if (isMatch && indices) {
615
- allIndices = [...allIndices, ...indices];
616
- }
617
- });
618
- let result = {
619
- isMatch: hasMatches,
620
- score: hasMatches ? totalScore / this.chunks.length : 1
621
- };
622
- if (hasMatches && includeMatches) {
623
- result.indices = allIndices;
624
- }
625
- return result;
626
- }
627
- }
628
- class BaseMatch {
629
- constructor(pattern) {
630
- this.pattern = pattern;
631
- }
632
- static isMultiMatch(pattern) {
633
- return getMatch(pattern, this.multiRegex);
634
- }
635
- static isSingleMatch(pattern) {
636
- return getMatch(pattern, this.singleRegex);
637
- }
638
- search() {
639
- }
640
- }
641
- function getMatch(pattern, exp) {
642
- const matches = pattern.match(exp);
643
- return matches ? matches[1] : null;
644
- }
645
- class ExactMatch extends BaseMatch {
646
- constructor(pattern) {
647
- super(pattern);
648
- }
649
- static get type() {
650
- return "exact";
651
- }
652
- static get multiRegex() {
653
- return /^="(.*)"$/;
654
- }
655
- static get singleRegex() {
656
- return /^=(.*)$/;
657
- }
658
- search(text) {
659
- const isMatch = text === this.pattern;
660
- return {
661
- isMatch,
662
- score: isMatch ? 0 : 1,
663
- indices: [0, this.pattern.length - 1]
664
- };
665
- }
666
- }
667
- class InverseExactMatch extends BaseMatch {
668
- constructor(pattern) {
669
- super(pattern);
670
- }
671
- static get type() {
672
- return "inverse-exact";
673
- }
674
- static get multiRegex() {
675
- return /^!"(.*)"$/;
676
- }
677
- static get singleRegex() {
678
- return /^!(.*)$/;
679
- }
680
- search(text) {
681
- const index = text.indexOf(this.pattern);
682
- const isMatch = index === -1;
683
- return {
684
- isMatch,
685
- score: isMatch ? 0 : 1,
686
- indices: [0, text.length - 1]
687
- };
688
- }
689
- }
690
- class PrefixExactMatch extends BaseMatch {
691
- constructor(pattern) {
692
- super(pattern);
693
- }
694
- static get type() {
695
- return "prefix-exact";
696
- }
697
- static get multiRegex() {
698
- return /^\^"(.*)"$/;
699
- }
700
- static get singleRegex() {
701
- return /^\^(.*)$/;
702
- }
703
- search(text) {
704
- const isMatch = text.startsWith(this.pattern);
705
- return {
706
- isMatch,
707
- score: isMatch ? 0 : 1,
708
- indices: [0, this.pattern.length - 1]
709
- };
710
- }
711
- }
712
- class InversePrefixExactMatch extends BaseMatch {
713
- constructor(pattern) {
714
- super(pattern);
715
- }
716
- static get type() {
717
- return "inverse-prefix-exact";
718
- }
719
- static get multiRegex() {
720
- return /^!\^"(.*)"$/;
721
- }
722
- static get singleRegex() {
723
- return /^!\^(.*)$/;
724
- }
725
- search(text) {
726
- const isMatch = !text.startsWith(this.pattern);
727
- return {
728
- isMatch,
729
- score: isMatch ? 0 : 1,
730
- indices: [0, text.length - 1]
731
- };
732
- }
733
- }
734
- class SuffixExactMatch extends BaseMatch {
735
- constructor(pattern) {
736
- super(pattern);
737
- }
738
- static get type() {
739
- return "suffix-exact";
740
- }
741
- static get multiRegex() {
742
- return /^"(.*)"\$$/;
743
- }
744
- static get singleRegex() {
745
- return /^(.*)\$$/;
746
- }
747
- search(text) {
748
- const isMatch = text.endsWith(this.pattern);
749
- return {
750
- isMatch,
751
- score: isMatch ? 0 : 1,
752
- indices: [text.length - this.pattern.length, text.length - 1]
753
- };
754
- }
755
- }
756
- class InverseSuffixExactMatch extends BaseMatch {
757
- constructor(pattern) {
758
- super(pattern);
759
- }
760
- static get type() {
761
- return "inverse-suffix-exact";
762
- }
763
- static get multiRegex() {
764
- return /^!"(.*)"\$$/;
765
- }
766
- static get singleRegex() {
767
- return /^!(.*)\$$/;
768
- }
769
- search(text) {
770
- const isMatch = !text.endsWith(this.pattern);
771
- return {
772
- isMatch,
773
- score: isMatch ? 0 : 1,
774
- indices: [0, text.length - 1]
775
- };
776
- }
777
- }
778
- class FuzzyMatch extends BaseMatch {
779
- constructor(pattern, {
780
- location = Config.location,
781
- threshold = Config.threshold,
782
- distance = Config.distance,
783
- includeMatches = Config.includeMatches,
784
- findAllMatches = Config.findAllMatches,
785
- minMatchCharLength = Config.minMatchCharLength,
786
- isCaseSensitive = Config.isCaseSensitive,
787
- ignoreDiacritics = Config.ignoreDiacritics,
788
- ignoreLocation = Config.ignoreLocation
789
- } = {}) {
790
- super(pattern);
791
- this._bitapSearch = new BitapSearch(pattern, {
792
- location,
793
- threshold,
794
- distance,
795
- includeMatches,
796
- findAllMatches,
797
- minMatchCharLength,
798
- isCaseSensitive,
799
- ignoreDiacritics,
800
- ignoreLocation
801
- });
802
- }
803
- static get type() {
804
- return "fuzzy";
805
- }
806
- static get multiRegex() {
807
- return /^"(.*)"$/;
808
- }
809
- static get singleRegex() {
810
- return /^(.*)$/;
811
- }
812
- search(text) {
813
- return this._bitapSearch.searchIn(text);
814
- }
815
- }
816
- class IncludeMatch extends BaseMatch {
817
- constructor(pattern) {
818
- super(pattern);
819
- }
820
- static get type() {
821
- return "include";
822
- }
823
- static get multiRegex() {
824
- return /^'"(.*)"$/;
825
- }
826
- static get singleRegex() {
827
- return /^'(.*)$/;
828
- }
829
- search(text) {
830
- let location = 0;
831
- let index;
832
- const indices = [];
833
- const patternLen = this.pattern.length;
834
- while ((index = text.indexOf(this.pattern, location)) > -1) {
835
- location = index + patternLen;
836
- indices.push([index, location - 1]);
837
- }
838
- const isMatch = !!indices.length;
839
- return {
840
- isMatch,
841
- score: isMatch ? 0 : 1,
842
- indices
843
- };
844
- }
845
- }
846
- const searchers = [
847
- ExactMatch,
848
- IncludeMatch,
849
- PrefixExactMatch,
850
- InversePrefixExactMatch,
851
- InverseSuffixExactMatch,
852
- SuffixExactMatch,
853
- InverseExactMatch,
854
- FuzzyMatch
855
- ];
856
- const searchersLen = searchers.length;
857
- const SPACE_RE = / +(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/;
858
- const OR_TOKEN = "|";
859
- function parseQuery(pattern, options = {}) {
860
- return pattern.split(OR_TOKEN).map((item) => {
861
- let query = item.trim().split(SPACE_RE).filter((item2) => item2 && !!item2.trim());
862
- let results = [];
863
- for (let i = 0, len = query.length; i < len; i += 1) {
864
- const queryItem = query[i];
865
- let found = false;
866
- let idx = -1;
867
- while (!found && ++idx < searchersLen) {
868
- const searcher = searchers[idx];
869
- let token = searcher.isMultiMatch(queryItem);
870
- if (token) {
871
- results.push(new searcher(token, options));
872
- found = true;
873
- }
874
- }
875
- if (found) {
876
- continue;
877
- }
878
- idx = -1;
879
- while (++idx < searchersLen) {
880
- const searcher = searchers[idx];
881
- let token = searcher.isSingleMatch(queryItem);
882
- if (token) {
883
- results.push(new searcher(token, options));
884
- break;
885
- }
886
- }
887
- }
888
- return results;
889
- });
890
- }
891
- const MultiMatchSet = /* @__PURE__ */ new Set([FuzzyMatch.type, IncludeMatch.type]);
892
- class ExtendedSearch {
893
- constructor(pattern, {
894
- isCaseSensitive = Config.isCaseSensitive,
895
- ignoreDiacritics = Config.ignoreDiacritics,
896
- includeMatches = Config.includeMatches,
897
- minMatchCharLength = Config.minMatchCharLength,
898
- ignoreLocation = Config.ignoreLocation,
899
- findAllMatches = Config.findAllMatches,
900
- location = Config.location,
901
- threshold = Config.threshold,
902
- distance = Config.distance
903
- } = {}) {
904
- this.query = null;
905
- this.options = {
906
- isCaseSensitive,
907
- ignoreDiacritics,
908
- includeMatches,
909
- minMatchCharLength,
910
- findAllMatches,
911
- ignoreLocation,
912
- location,
913
- threshold,
914
- distance
915
- };
916
- pattern = isCaseSensitive ? pattern : pattern.toLowerCase();
917
- pattern = ignoreDiacritics ? stripDiacritics(pattern) : pattern;
918
- this.pattern = pattern;
919
- this.query = parseQuery(this.pattern, this.options);
920
- }
921
- static condition(_, options) {
922
- return options.useExtendedSearch;
923
- }
924
- searchIn(text) {
925
- const query = this.query;
926
- if (!query) {
927
- return {
928
- isMatch: false,
929
- score: 1
930
- };
931
- }
932
- const { includeMatches, isCaseSensitive, ignoreDiacritics } = this.options;
933
- text = isCaseSensitive ? text : text.toLowerCase();
934
- text = ignoreDiacritics ? stripDiacritics(text) : text;
935
- let numMatches = 0;
936
- let allIndices = [];
937
- let totalScore = 0;
938
- for (let i = 0, qLen = query.length; i < qLen; i += 1) {
939
- const searchers2 = query[i];
940
- allIndices.length = 0;
941
- numMatches = 0;
942
- for (let j = 0, pLen = searchers2.length; j < pLen; j += 1) {
943
- const searcher = searchers2[j];
944
- const { isMatch, indices, score } = searcher.search(text);
945
- if (isMatch) {
946
- numMatches += 1;
947
- totalScore += score;
948
- if (includeMatches) {
949
- const type = searcher.constructor.type;
950
- if (MultiMatchSet.has(type)) {
951
- allIndices = [...allIndices, ...indices];
952
- } else {
953
- allIndices.push(indices);
954
- }
955
- }
956
- } else {
957
- totalScore = 0;
958
- numMatches = 0;
959
- allIndices.length = 0;
960
- break;
961
- }
962
- }
963
- if (numMatches) {
964
- let result = {
965
- isMatch: true,
966
- score: totalScore / numMatches
967
- };
968
- if (includeMatches) {
969
- result.indices = allIndices;
970
- }
971
- return result;
972
- }
973
- }
974
- return {
975
- isMatch: false,
976
- score: 1
977
- };
978
- }
979
- }
980
- const registeredSearchers = [];
981
- function register(...args) {
982
- registeredSearchers.push(...args);
983
- }
984
- function createSearcher(pattern, options) {
985
- for (let i = 0, len = registeredSearchers.length; i < len; i += 1) {
986
- let searcherClass = registeredSearchers[i];
987
- if (searcherClass.condition(pattern, options)) {
988
- return new searcherClass(pattern, options);
989
- }
990
- }
991
- return new BitapSearch(pattern, options);
992
- }
993
- const LogicalOperator = {
994
- AND: "$and",
995
- OR: "$or"
996
- };
997
- const KeyType = {
998
- PATH: "$path",
999
- PATTERN: "$val"
1000
- };
1001
- const isExpression = (query) => !!(query[LogicalOperator.AND] || query[LogicalOperator.OR]);
1002
- const isPath = (query) => !!query[KeyType.PATH];
1003
- const isLeaf = (query) => !isArray(query) && isObject(query) && !isExpression(query);
1004
- const convertToExplicit = (query) => ({
1005
- [LogicalOperator.AND]: Object.keys(query).map((key) => ({
1006
- [key]: query[key]
1007
- }))
1008
- });
1009
- function parse(query, options, { auto = true } = {}) {
1010
- const next = (query2) => {
1011
- let keys = Object.keys(query2);
1012
- const isQueryPath = isPath(query2);
1013
- if (!isQueryPath && keys.length > 1 && !isExpression(query2)) {
1014
- return next(convertToExplicit(query2));
1015
- }
1016
- if (isLeaf(query2)) {
1017
- const key = isQueryPath ? query2[KeyType.PATH] : keys[0];
1018
- const pattern = isQueryPath ? query2[KeyType.PATTERN] : query2[key];
1019
- if (!isString(pattern)) {
1020
- throw new Error(LOGICAL_SEARCH_INVALID_QUERY_FOR_KEY(key));
1021
- }
1022
- const obj = {
1023
- keyId: createKeyId(key),
1024
- pattern
1025
- };
1026
- if (auto) {
1027
- obj.searcher = createSearcher(pattern, options);
1028
- }
1029
- return obj;
1030
- }
1031
- let node = {
1032
- children: [],
1033
- operator: keys[0]
1034
- };
1035
- keys.forEach((key) => {
1036
- const value = query2[key];
1037
- if (isArray(value)) {
1038
- value.forEach((item) => {
1039
- node.children.push(next(item));
1040
- });
1041
- }
1042
- });
1043
- return node;
1044
- };
1045
- if (!isExpression(query)) {
1046
- query = convertToExplicit(query);
1047
- }
1048
- return next(query);
1049
- }
1050
- function computeScore(results, { ignoreFieldNorm = Config.ignoreFieldNorm }) {
1051
- results.forEach((result) => {
1052
- let totalScore = 1;
1053
- result.matches.forEach(({ key, norm: norm2, score }) => {
1054
- const weight = key ? key.weight : null;
1055
- totalScore *= Math.pow(
1056
- score === 0 && weight ? Number.EPSILON : score,
1057
- (weight || 1) * (ignoreFieldNorm ? 1 : norm2)
1058
- );
1059
- });
1060
- result.score = totalScore;
1061
- });
1062
- }
1063
- function transformMatches(result, data) {
1064
- const matches = result.matches;
1065
- data.matches = [];
1066
- if (!isDefined(matches)) {
1067
- return;
1068
- }
1069
- matches.forEach((match) => {
1070
- if (!isDefined(match.indices) || !match.indices.length) {
1071
- return;
1072
- }
1073
- const { indices, value } = match;
1074
- let obj = {
1075
- indices,
1076
- value
1077
- };
1078
- if (match.key) {
1079
- obj.key = match.key.src;
1080
- }
1081
- if (match.idx > -1) {
1082
- obj.refIndex = match.idx;
1083
- }
1084
- data.matches.push(obj);
1085
- });
1086
- }
1087
- function transformScore(result, data) {
1088
- data.score = result.score;
1089
- }
1090
- function format(results, docs, {
1091
- includeMatches = Config.includeMatches,
1092
- includeScore = Config.includeScore
1093
- } = {}) {
1094
- const transformers = [];
1095
- if (includeMatches) transformers.push(transformMatches);
1096
- if (includeScore) transformers.push(transformScore);
1097
- return results.map((result) => {
1098
- const { idx } = result;
1099
- const data = {
1100
- item: docs[idx],
1101
- refIndex: idx
1102
- };
1103
- if (transformers.length) {
1104
- transformers.forEach((transformer) => {
1105
- transformer(result, data);
1106
- });
1107
- }
1108
- return data;
1109
- });
1110
- }
1111
- class Fuse {
1112
- constructor(docs, options = {}, index) {
1113
- this.options = { ...Config, ...options };
1114
- if (this.options.useExtendedSearch && false) ;
1115
- this._keyStore = new KeyStore(this.options.keys);
1116
- this.setCollection(docs, index);
1117
- }
1118
- setCollection(docs, index) {
1119
- this._docs = docs;
1120
- if (index && !(index instanceof FuseIndex)) {
1121
- throw new Error(INCORRECT_INDEX_TYPE);
1122
- }
1123
- this._myIndex = index || createIndex(this.options.keys, this._docs, {
1124
- getFn: this.options.getFn,
1125
- fieldNormWeight: this.options.fieldNormWeight
1126
- });
1127
- }
1128
- add(doc) {
1129
- if (!isDefined(doc)) {
1130
- return;
1131
- }
1132
- this._docs.push(doc);
1133
- this._myIndex.add(doc);
1134
- }
1135
- remove(predicate = () => false) {
1136
- const results = [];
1137
- for (let i = 0, len = this._docs.length; i < len; i += 1) {
1138
- const doc = this._docs[i];
1139
- if (predicate(doc, i)) {
1140
- this.removeAt(i);
1141
- i -= 1;
1142
- len -= 1;
1143
- results.push(doc);
1144
- }
1145
- }
1146
- return results;
1147
- }
1148
- removeAt(idx) {
1149
- this._docs.splice(idx, 1);
1150
- this._myIndex.removeAt(idx);
1151
- }
1152
- getIndex() {
1153
- return this._myIndex;
1154
- }
1155
- search(query, { limit = -1 } = {}) {
1156
- const {
1157
- includeMatches,
1158
- includeScore,
1159
- shouldSort,
1160
- sortFn,
1161
- ignoreFieldNorm
1162
- } = this.options;
1163
- let results = isString(query) ? isString(this._docs[0]) ? this._searchStringList(query) : this._searchObjectList(query) : this._searchLogical(query);
1164
- computeScore(results, { ignoreFieldNorm });
1165
- if (shouldSort) {
1166
- results.sort(sortFn);
1167
- }
1168
- if (isNumber(limit) && limit > -1) {
1169
- results = results.slice(0, limit);
1170
- }
1171
- return format(results, this._docs, {
1172
- includeMatches,
1173
- includeScore
1174
- });
1175
- }
1176
- _searchStringList(query) {
1177
- const searcher = createSearcher(query, this.options);
1178
- const { records } = this._myIndex;
1179
- const results = [];
1180
- records.forEach(({ v: text, i: idx, n: norm2 }) => {
1181
- if (!isDefined(text)) {
1182
- return;
1183
- }
1184
- const { isMatch, score, indices } = searcher.searchIn(text);
1185
- if (isMatch) {
1186
- results.push({
1187
- item: text,
1188
- idx,
1189
- matches: [{ score, value: text, norm: norm2, indices }]
1190
- });
1191
- }
1192
- });
1193
- return results;
1194
- }
1195
- _searchLogical(query) {
1196
- const expression = parse(query, this.options);
1197
- const evaluate = (node, item, idx) => {
1198
- if (!node.children) {
1199
- const { keyId, searcher } = node;
1200
- const matches = this._findMatches({
1201
- key: this._keyStore.get(keyId),
1202
- value: this._myIndex.getValueForItemAtKeyId(item, keyId),
1203
- searcher
1204
- });
1205
- if (matches && matches.length) {
1206
- return [
1207
- {
1208
- idx,
1209
- item,
1210
- matches
1211
- }
1212
- ];
1213
- }
1214
- return [];
1215
- }
1216
- const res = [];
1217
- for (let i = 0, len = node.children.length; i < len; i += 1) {
1218
- const child = node.children[i];
1219
- const result = evaluate(child, item, idx);
1220
- if (result.length) {
1221
- res.push(...result);
1222
- } else if (node.operator === LogicalOperator.AND) {
1223
- return [];
1224
- }
1225
- }
1226
- return res;
1227
- };
1228
- const records = this._myIndex.records;
1229
- const resultMap = {};
1230
- const results = [];
1231
- records.forEach(({ $: item, i: idx }) => {
1232
- if (isDefined(item)) {
1233
- let expResults = evaluate(expression, item, idx);
1234
- if (expResults.length) {
1235
- if (!resultMap[idx]) {
1236
- resultMap[idx] = { idx, item, matches: [] };
1237
- results.push(resultMap[idx]);
1238
- }
1239
- expResults.forEach(({ matches }) => {
1240
- resultMap[idx].matches.push(...matches);
1241
- });
1242
- }
1243
- }
1244
- });
1245
- return results;
1246
- }
1247
- _searchObjectList(query) {
1248
- const searcher = createSearcher(query, this.options);
1249
- const { keys, records } = this._myIndex;
1250
- const results = [];
1251
- records.forEach(({ $: item, i: idx }) => {
1252
- if (!isDefined(item)) {
1253
- return;
1254
- }
1255
- let matches = [];
1256
- keys.forEach((key, keyIndex) => {
1257
- matches.push(
1258
- ...this._findMatches({
1259
- key,
1260
- value: item[keyIndex],
1261
- searcher
1262
- })
1263
- );
1264
- });
1265
- if (matches.length) {
1266
- results.push({
1267
- idx,
1268
- item,
1269
- matches
1270
- });
1271
- }
1272
- });
1273
- return results;
1274
- }
1275
- _findMatches({ key, value, searcher }) {
1276
- if (!isDefined(value)) {
1277
- return [];
1278
- }
1279
- let matches = [];
1280
- if (isArray(value)) {
1281
- value.forEach(({ v: text, i: idx, n: norm2 }) => {
1282
- if (!isDefined(text)) {
1283
- return;
1284
- }
1285
- const { isMatch, score, indices } = searcher.searchIn(text);
1286
- if (isMatch) {
1287
- matches.push({
1288
- score,
1289
- key,
1290
- value: text,
1291
- idx,
1292
- norm: norm2,
1293
- indices
1294
- });
1295
- }
1296
- });
1297
- } else {
1298
- const { v: text, n: norm2 } = value;
1299
- const { isMatch, score, indices } = searcher.searchIn(text);
1300
- if (isMatch) {
1301
- matches.push({ score, key, value: text, norm: norm2, indices });
1302
- }
1303
- }
1304
- return matches;
1305
- }
1306
- }
1307
- Fuse.version = "7.1.0";
1308
- Fuse.createIndex = createIndex;
1309
- Fuse.parseIndex = parseIndex;
1310
- Fuse.config = Config;
1311
- {
1312
- Fuse.parseQuery = parse;
1313
- }
1314
- {
1315
- register(ExtendedSearch);
1316
- }
1317
- const version = "0.3.5";
1318
- const packageJson = {
1319
- version
1320
- };
1321
- function instantiateCachedURL(dbVersion, url, importObject) {
1322
- const dbName = "wasm-cache";
1323
- const storeName = "wasm-cache";
1324
- function openDatabase() {
1325
- return new Promise((resolve, reject) => {
1326
- const request = indexedDB.open(dbName, dbVersion);
1327
- request.onerror = reject.bind(null, "Error opening wasm cache database");
1328
- request.onsuccess = () => {
1329
- resolve(request.result);
1330
- };
1331
- request.onupgradeneeded = (event) => {
1332
- const db = request.result;
1333
- if (db.objectStoreNames.contains(storeName)) {
1334
- console.log(`Clearing out version ${event.oldVersion} wasm cache`);
1335
- db.deleteObjectStore(storeName);
1336
- }
1337
- console.log(`Creating version ${event.newVersion} wasm cache`);
1338
- db.createObjectStore(storeName);
1339
- };
1340
- });
1341
- }
1342
- function lookupInDatabase(db) {
1343
- return new Promise((resolve, reject) => {
1344
- const store = db.transaction([storeName]).objectStore(storeName);
1345
- const request = store.get(url);
1346
- request.onerror = reject.bind(null, `Error getting wasm module ${url}`);
1347
- request.onsuccess = () => {
1348
- if (request.result) {
1349
- resolve(request.result);
1350
- } else {
1351
- reject(`Module ${url} was not found in wasm cache`);
1352
- }
1353
- };
1354
- });
1355
- }
1356
- function storeInDatabase(db, module) {
1357
- const store = db.transaction([storeName], "readwrite").objectStore(storeName);
1358
- try {
1359
- const request = store.put(module, url);
1360
- request.onerror = (err) => {
1361
- console.log(`Failed to store in wasm cache: ${err}`);
1362
- };
1363
- request.onsuccess = () => {
1364
- console.log(`Successfully stored ${url} in wasm cache`);
1365
- };
1366
- } catch (e) {
1367
- console.warn("An error was thrown... in storing wasm cache...");
1368
- console.warn(e);
1369
- }
1370
- }
1371
- async function fetchAndInstantiate() {
1372
- const response = await fetch(url);
1373
- const buffer = await response.arrayBuffer();
1374
- return await WebAssembly.instantiate(buffer, importObject);
1375
- }
1376
- return openDatabase().then(
1377
- (db) => {
1378
- return lookupInDatabase(db).then(
1379
- (module) => {
1380
- console.log(`Found ${url} in wasm cache`);
1381
- return WebAssembly.instantiate(module, importObject);
1382
- },
1383
- (errMsg) => {
1384
- console.log(errMsg);
1385
- return fetchAndInstantiate().then((results) => {
1386
- setTimeout(() => storeInDatabase(db, results.module), 0);
1387
- return results.instance;
1388
- });
1389
- }
1390
- );
1391
- },
1392
- (errMsg) => {
1393
- console.log(errMsg);
1394
- return fetchAndInstantiate().then((results) => results.instance);
1395
- }
1396
- );
1397
- }
1398
- class ModuleClass {
1399
- constructor({ init, version: version2, wasmUrl }) {
1400
- this._init = init;
1401
- this._version = version2;
1402
- this._wasmUrl = wasmUrl;
1403
- }
1404
- locateFile(baseName) {
1405
- return self.location.pathname.replace(/\[^\/]*$/, "/") + baseName;
1406
- }
1407
- instantiateWasm(imports, callback) {
1408
- instantiateCachedURL(this._version, this._wasmUrl, imports).then(
1409
- (instance) => callback(instance)
1410
- );
1411
- return {};
1412
- }
1413
- onInit(callback) {
1414
- this._init = callback;
1415
- }
1416
- onRuntimeInitialized() {
1417
- if (this._init) {
1418
- return this._init(this);
1419
- }
1420
- }
1421
- }
1422
- var WorkerEventType = /* @__PURE__ */ ((WorkerEventType2) => {
1423
- WorkerEventType2["INIT_CALC"] = "init";
1424
- WorkerEventType2["REQUEST_CALC"] = "req_calc";
1425
- WorkerEventType2["RESULT_CALC"] = "res_calc";
1426
- WorkerEventType2["INIT_FILTER"] = "init_filter";
1427
- WorkerEventType2["REQUEST_FILTER"] = "req_filter";
1428
- WorkerEventType2["RESULT_FILTER"] = "res_filter";
1429
- return WorkerEventType2;
1430
- })(WorkerEventType || {});
1431
- const ximgdiffVersionString = packageJson.version;
1432
- const _self = self;
1433
- function version2number(version2) {
1434
- const [, major, minor, patch] = version2.match(/^(\d*)\.(\d*)\.(\d*)/);
1435
- return +major * 1e4 + +minor * 100 + +patch;
1436
- }
1437
- let loaded = false;
1438
- let lastCalcData = null;
1439
- const cachedEntity = {
1440
- new: [],
1441
- passed: [],
1442
- failed: [],
1443
- deleted: []
1444
- };
1445
- const calc = ({
1446
- payload: { raw, img1, img2, actualSrc, expectedSrc, seq }
1447
- }) => {
1448
- const diffResult = _self.Module.detectDiff(_self.Module, img1, img2, {});
1449
- _self.postMessage({
1450
- type: WorkerEventType.RESULT_CALC,
1451
- payload: {
1452
- seq,
1453
- raw,
1454
- actualSrc,
1455
- expectedSrc,
1456
- result: {
1457
- ...diffResult,
1458
- images: [
1459
- { width: img1.width, height: img1.height },
1460
- { width: img2.width, height: img2.height }
1461
- ]
1462
- }
1463
- }
1464
- });
1465
- };
1466
- const filter = ({
1467
- payload: { input }
1468
- }) => {
1469
- if (!input) {
1470
- return _self.postMessage({
1471
- type: WorkerEventType.RESULT_FILTER,
1472
- payload: {
1473
- newItems: cachedEntity.new,
1474
- passedItems: cachedEntity.passed,
1475
- failedItems: cachedEntity.failed,
1476
- deletedItems: cachedEntity.deleted
1477
- }
1478
- });
1479
- }
1480
- const search2 = (entities) => {
1481
- const fuse = new Fuse(entities, {
1482
- shouldSort: false,
1483
- isCaseSensitive: false,
1484
- findAllMatches: true,
1485
- location: 0,
1486
- distance: 100,
1487
- minMatchCharLength: 1,
1488
- threshold: 0.2,
1489
- keys: ["name"]
1490
- });
1491
- return fuse.search(input).map(({ item }) => item);
1492
- };
1493
- _self.postMessage({
1494
- type: WorkerEventType.RESULT_FILTER,
1495
- payload: {
1496
- newItems: search2(cachedEntity.new),
1497
- passedItems: search2(cachedEntity.passed),
1498
- failedItems: search2(cachedEntity.failed),
1499
- deletedItems: search2(cachedEntity.deleted)
1500
- }
1501
- });
1502
- };
1503
- _self.Module = new ModuleClass({
1504
- version: version2number(ximgdiffVersionString),
1505
- wasmUrl: _self.wasmUrl,
1506
- init: () => {
1507
- loaded = true;
1508
- if (lastCalcData != null) {
1509
- calc(lastCalcData);
1510
- }
1511
- _self.postMessage({ type: WorkerEventType.INIT_CALC });
1512
- }
1513
- });
1514
- _self.addEventListener("message", ({ data }) => {
1515
- console.log("Received: ", data);
1516
- switch (data.type) {
1517
- case WorkerEventType.REQUEST_CALC:
1518
- if (loaded) {
1519
- calc(data);
1520
- } else {
1521
- lastCalcData = data;
1522
- }
1523
- break;
1524
- case WorkerEventType.INIT_FILTER:
1525
- cachedEntity.new = data.payload.newItems;
1526
- cachedEntity.passed = data.payload.passedItems;
1527
- cachedEntity.failed = data.payload.failedItems;
1528
- cachedEntity.deleted = data.payload.deletedItems;
1529
- break;
1530
- case WorkerEventType.REQUEST_FILTER:
1531
- filter(data);
1532
- break;
1533
- }
1534
- });
1535
- })();