cspell-lib 8.7.0 → 8.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/dist/esm/Document/resolveDocument.js +1 -1
  2. package/dist/esm/LanguageIds.js +1 -1
  3. package/dist/esm/Models/TextDocument.js +1 -1
  4. package/dist/esm/Settings/CSpellSettingsServer.js +3 -3
  5. package/dist/esm/Settings/Controller/configLoader/configLoader.js +10 -14
  6. package/dist/esm/Settings/Controller/configLoader/configLocations.js +1 -1
  7. package/dist/esm/Settings/Controller/configLoader/configSearch.js +3 -3
  8. package/dist/esm/Settings/Controller/configLoader/normalizeRawSettings.js +1 -1
  9. package/dist/esm/Settings/Controller/pnpLoader.js +2 -2
  10. package/dist/esm/Settings/DictionarySettings.js +2 -2
  11. package/dist/esm/Settings/GlobalSettings.js +2 -2
  12. package/dist/esm/Settings/InDocSettings.js +6 -8
  13. package/dist/esm/Settings/LanguageSettings.js +3 -3
  14. package/dist/esm/Settings/checkFilenameMatchesGlob.d.ts +1 -2
  15. package/dist/esm/Settings/checkFilenameMatchesGlob.js +1 -2
  16. package/dist/esm/Settings/link.js +4 -4
  17. package/dist/esm/Settings/mergeList.js +1 -1
  18. package/dist/esm/SpellingDictionary/DictionaryController/DictionaryLoader.js +8 -7
  19. package/dist/esm/SpellingDictionary/SuggestExperimental/SuggestionCollector.js +1 -1
  20. package/dist/esm/SpellingDictionary/SuggestExperimental/helpers.js +3 -3
  21. package/dist/esm/clearCachedFiles.js +1 -1
  22. package/dist/esm/events/events.d.ts +40 -12
  23. package/dist/esm/events/events.js +51 -15
  24. package/dist/esm/events/index.d.ts +2 -2
  25. package/dist/esm/events/index.js +1 -1
  26. package/dist/esm/index.d.ts +10 -12
  27. package/dist/esm/index.js +7 -9
  28. package/dist/esm/suggestions.js +1 -1
  29. package/dist/esm/textValidation/checkText.js +2 -3
  30. package/dist/esm/textValidation/determineTextDocumentSettings.js +1 -1
  31. package/dist/esm/textValidation/docValidator.js +5 -3
  32. package/dist/esm/textValidation/isWordValid.js +1 -1
  33. package/dist/esm/textValidation/traceWord.js +1 -1
  34. package/dist/esm/textValidation/validator.js +1 -1
  35. package/dist/esm/trace.js +4 -3
  36. package/dist/esm/util/AutoResolveLRUCache.js +1 -1
  37. package/dist/esm/util/MinHeapQueue.d.ts +1 -1
  38. package/dist/esm/util/MinHeapQueue.js +4 -6
  39. package/dist/esm/util/PairingHeap.d.ts +1 -1
  40. package/dist/esm/util/PairingHeap.js +1 -1
  41. package/dist/esm/util/TextMap.js +2 -2
  42. package/dist/esm/util/Uri.js +3 -3
  43. package/dist/esm/util/errors.js +1 -1
  44. package/dist/esm/util/fileReader.js +3 -8
  45. package/dist/esm/util/findUp.js +2 -2
  46. package/dist/esm/util/regexHelper.js +1 -1
  47. package/dist/esm/util/repMap.js +2 -2
  48. package/dist/esm/util/resolveFile.js +11 -9
  49. package/dist/esm/util/text.js +5 -5
  50. package/dist/esm/util/textRegex.js +2 -2
  51. package/dist/esm/util/url.js +2 -2
  52. package/dist/esm/util/wordSplitter.js +4 -4
  53. package/dist/esm/wordListHelper.js +1 -1
  54. package/package.json +14 -14
@@ -1,4 +1,4 @@
1
- import { readFile } from 'fs/promises';
1
+ import { readFile } from 'node:fs/promises';
2
2
  import { createTextDocument } from '../Models/TextDocument.js';
3
3
  import * as Uri from '../util/Uri.js';
4
4
  import { clean } from '../util/util.js';
@@ -240,7 +240,7 @@ export const languageExtensionDefinitions = [
240
240
  { id: 'trie', extensions: ['.trie'], format: 'Binary', description: 'CSpell dictionary file.' },
241
241
  ];
242
242
  const binaryFormatIds = languageExtensionDefinitions.filter((d) => d.format === 'Binary').map((d) => d.id);
243
- export const binaryLanguages = new Set(['binary', 'image', 'video', 'fonts'].concat(binaryFormatIds));
243
+ export const binaryLanguages = new Set(['binary', 'image', 'video', 'fonts', ...binaryFormatIds]);
244
244
  export const generatedFiles = new Set([...binaryLanguages, 'map', 'lock', 'pdf', 'cache_files', 'rsa', 'pem', 'trie']);
245
245
  export const languageIds = languageExtensionDefinitions.map(({ id }) => id);
246
246
  const mapExtensionToSetOfLanguageIds = buildLanguageExtensionMapSet(languageExtensionDefinitions);
@@ -1,4 +1,4 @@
1
- import assert from 'assert';
1
+ import assert from 'node:assert';
2
2
  import { TextDocument as VsTextDocument } from 'vscode-languageserver-textdocument';
3
3
  import { getFileSystem } from '../fileSystem.js';
4
4
  import { getLanguagesForBasename } from '../LanguageIds.js';
@@ -1,5 +1,5 @@
1
- import assert from 'assert';
2
- import { pathToFileURL } from 'url';
1
+ import assert from 'node:assert';
2
+ import { pathToFileURL } from 'node:url';
3
3
  import { onClearCache } from '../events/index.js';
4
4
  import { cleanCSpellSettingsInternal as csi, isCSpellSettingsInternal } from '../Models/CSpellSettingsInternalDef.js';
5
5
  import { autoResolveWeak, AutoResolveWeakCache } from '../util/AutoResolve.js';
@@ -26,7 +26,7 @@ onClearCache(() => {
26
26
  });
27
27
  function _mergeWordsCached(left, right) {
28
28
  const map = autoResolveWeak(cachedMerges, left, () => new WeakMap());
29
- return autoResolveWeak(map, right, () => left.concat(right));
29
+ return autoResolveWeak(map, right, () => [...left, ...right]);
30
30
  }
31
31
  function mergeWordsCached(left, right) {
32
32
  if (!Array.isArray(left) || !left.length) {
@@ -1,8 +1,8 @@
1
- import assert from 'assert';
1
+ import assert from 'node:assert';
2
+ import path from 'node:path';
3
+ import { fileURLToPath, pathToFileURL } from 'node:url';
2
4
  import { createReaderWriter, CSpellConfigFileInMemory } from 'cspell-config-lib';
3
5
  import { isUrlLike, toFileURL } from 'cspell-io';
4
- import path from 'path';
5
- import { fileURLToPath, pathToFileURL } from 'url';
6
6
  import { URI, Utils as UriUtils } from 'vscode-uri';
7
7
  import { srcDirectory } from '../../../../lib-cjs/index.cjs';
8
8
  import { onClearCache } from '../../../events/index.js';
@@ -99,11 +99,11 @@ export class ConfigLoader {
99
99
  }
100
100
  async searchForConfigFileLocation(searchFrom) {
101
101
  const url = toFileURL(searchFrom || cwdURL(), cwdURL());
102
- if (typeof searchFrom === 'string' && !isUrlLike(searchFrom) && url.protocol === 'file:') {
103
- // check to see if it is a directory
104
- if (await isDirectory(this.fs, url)) {
105
- return this.configSearch.searchForConfig(addTrailingSlash(url));
106
- }
102
+ if (typeof searchFrom === 'string' &&
103
+ !isUrlLike(searchFrom) &&
104
+ url.protocol === 'file:' && // check to see if it is a directory
105
+ (await isDirectory(this.fs, url))) {
106
+ return this.configSearch.searchForConfig(addTrailingSlash(url));
107
107
  }
108
108
  return this.configSearch.searchForConfig(url);
109
109
  }
@@ -450,7 +450,7 @@ async function isDirectory(fs, path) {
450
450
  try {
451
451
  return (await fs.stat(path)).isDirectory();
452
452
  }
453
- catch (e) {
453
+ catch {
454
454
  return false;
455
455
  }
456
456
  }
@@ -494,11 +494,7 @@ function relativeToCwd(file) {
494
494
  const segments = cwdPath.length - i;
495
495
  if (segments > 3)
496
496
  return toFilePathOrHref(file);
497
- const prefix = '.'
498
- .repeat(segments)
499
- .split('')
500
- .map(() => '..')
501
- .join('/');
497
+ const prefix = [...'.'.repeat(segments)].map(() => '..').join('/');
502
498
  return [prefix || '.', ...urlPath.slice(i)].join('/');
503
499
  }
504
500
  export const __testing__ = {
@@ -50,7 +50,7 @@ const setOfLocations = new Set([
50
50
  '.config/cspell.yml',
51
51
  ]);
52
52
  export const searchPlaces = Object.freeze([...setOfLocations]);
53
- export const defaultConfigFilenames = Object.freeze(searchPlaces.concat());
53
+ export const defaultConfigFilenames = Object.freeze([...searchPlaces]);
54
54
  function genCfgLoc(filename, extensions) {
55
55
  return extensions.map((ext) => filename + ext);
56
56
  }
@@ -43,7 +43,7 @@ export class ConfigSearch {
43
43
  const result = searchCache.get(searchHref) || pFoundUrl;
44
44
  searchCache.set(searchHref, result);
45
45
  }
46
- catch (e) {
46
+ catch {
47
47
  // ignore
48
48
  }
49
49
  };
@@ -100,7 +100,7 @@ export class ConfigSearch {
100
100
  const dirInfo = await this.fs.readDirectory(dir);
101
101
  return new Map(dirInfo.map((ent) => [ent.name, ent]));
102
102
  }
103
- catch (e) {
103
+ catch {
104
104
  return new Map();
105
105
  }
106
106
  }
@@ -141,7 +141,7 @@ async function checkPackageJson(fs, filename) {
141
141
  const pkg = JSON.parse(file.getText());
142
142
  return typeof pkg.cspell === 'object';
143
143
  }
144
- catch (e) {
144
+ catch {
145
145
  return false;
146
146
  }
147
147
  }
@@ -1,5 +1,5 @@
1
1
  import { homedir } from 'node:os';
2
- import { fileURLToPath } from 'url';
2
+ import { fileURLToPath } from 'node:url';
3
3
  import { resolveFile } from '../../../util/resolveFile.js';
4
4
  import { resolveFileWithURL, toFilePathOrHref } from '../../../util/url.js';
5
5
  import * as util from '../../../util/util.js';
@@ -1,9 +1,9 @@
1
1
  /**
2
2
  * Handles loading of `.pnp.js` and `.pnp.js` files.
3
3
  */
4
+ import { fileURLToPath } from 'node:url';
4
5
  import clearModule from 'clear-module';
5
6
  import importFresh from 'import-fresh';
6
- import { fileURLToPath } from 'url';
7
7
  import { findUp } from '../../util/findUp.js';
8
8
  import { toFileUrl } from '../../util/url.js';
9
9
  import { UnsupportedPnpFile } from './ImportError.js';
@@ -18,7 +18,7 @@ export class PnpLoader {
18
18
  cacheKeySuffix;
19
19
  constructor(pnpFiles = defaultPnpFiles) {
20
20
  this.pnpFiles = pnpFiles;
21
- this.cacheKeySuffix = ':' + pnpFiles.join();
21
+ this.cacheKeySuffix = ':' + pnpFiles.join(',');
22
22
  }
23
23
  /**
24
24
  * Request that the nearest .pnp file gets loaded
@@ -1,5 +1,5 @@
1
+ import * as path from 'node:path';
1
2
  import { mapDictionaryInformationToWeightMap } from 'cspell-trie-lib';
2
- import * as path from 'path';
3
3
  import { isDictionaryDefinitionInlineInternal } from '../Models/CSpellSettingsInternalDef.js';
4
4
  import { createAutoResolveWeakWeakCache } from '../util/AutoResolve.js';
5
5
  import { resolveRelativeTo } from '../util/resolveFile.js';
@@ -60,7 +60,7 @@ function determineName(filename, options) {
60
60
  export function calcDictionaryDefsToLoad(settings) {
61
61
  const { dictionaries = [], dictionaryDefinitions = [], noSuggestDictionaries = [] } = settings;
62
62
  const colNoSug = createDictionaryReferenceCollection(noSuggestDictionaries);
63
- const colDicts = createDictionaryReferenceCollection(dictionaries.concat(colNoSug.enabled()));
63
+ const colDicts = createDictionaryReferenceCollection([...dictionaries, ...colNoSug.enabled()]);
64
64
  const modDefs = dictionaryDefinitions.map((def) => {
65
65
  const enabled = colNoSug.isEnabled(def.name);
66
66
  if (enabled === undefined)
@@ -1,5 +1,5 @@
1
+ import { pathToFileURL } from 'node:url';
1
2
  import { CSpellConfigFileInMemory, CSpellConfigFileJson } from 'cspell-config-lib';
2
- import { pathToFileURL } from 'url';
3
3
  import { isErrnoException } from '../util/errors.js';
4
4
  import { logError } from '../util/logger.js';
5
5
  import { getSourceDirectoryUrl, toFilePathOrHref } from '../util/url.js';
@@ -55,7 +55,7 @@ export function getGlobalConfigPath() {
55
55
  const cfgStore = new ConfigStore(packageName);
56
56
  return cfgStore.path;
57
57
  }
58
- catch (e) {
58
+ catch {
59
59
  return undefined;
60
60
  }
61
61
  }
@@ -57,7 +57,7 @@ const preferredDirectives = [
57
57
  'enableCaseSensitive',
58
58
  'disableCaseSensitive',
59
59
  ];
60
- const allDirectives = new Set(preferredDirectives.concat(officialDirectives));
60
+ const allDirectives = new Set([...preferredDirectives, ...officialDirectives]);
61
61
  const allDirectiveSuggestions = [
62
62
  ...pipeSync(allDirectives, opMap((word) => ({ word }))),
63
63
  ];
@@ -84,8 +84,8 @@ export function getInDocumentSettings(text) {
84
84
  });
85
85
  const dictSettings = dict
86
86
  ? {
87
- dictionaries: dictionaries.concat(staticInDocumentDictionaryName),
88
- dictionaryDefinitions: dictionaryDefinitions.concat(dict),
87
+ dictionaries: [...dictionaries, staticInDocumentDictionaryName],
88
+ dictionaryDefinitions: [...dictionaryDefinitions, dict],
89
89
  }
90
90
  : clean({
91
91
  dictionaries: dictionaries.length ? dictionaries : undefined,
@@ -114,7 +114,7 @@ const settingParsers = [
114
114
  [/^locale?\b(?!-)/i, parseLocale],
115
115
  [/^language\s\b(?!-)/i, parseLocale],
116
116
  [/^dictionar(?:y|ies)\b(?!-)/i, parseDictionaries], // cspell:disable-line
117
- [/^LocalWords:/, (w) => parseWords(w.replace(/^LocalWords:?/gi, ' '))],
117
+ [/^LocalWords:/, (w) => parseWords(w.replaceAll(/^LocalWords:?/gi, ' '))],
118
118
  ];
119
119
  export const regExSpellingGuardBlock = /(\bc?spell(?:-?checker)?::?)\s*disable(?!-line|-next)\b[\s\S]*?((?:\1\s*enable\b)|$)/gi;
120
120
  export const regExSpellingGuardNext = /\bc?spell(?:-?checker)?::?\s*disable-next\b.*\s\s?.*/gi;
@@ -161,10 +161,8 @@ function* filterUniqueSuggestions(sugs) {
161
161
  const map = new Map();
162
162
  for (const sug of sugs) {
163
163
  const existing = map.get(sug.word);
164
- if (existing) {
165
- if (sug.isPreferred) {
166
- existing.isPreferred = true;
167
- }
164
+ if (existing && sug.isPreferred) {
165
+ existing.isPreferred = true;
168
166
  }
169
167
  yield sug;
170
168
  }
@@ -7,11 +7,11 @@ export function getDefaultLanguageSettings() {
7
7
  return defaultLanguageSettings;
8
8
  }
9
9
  function localesToList(locales) {
10
- return stringToList(locales.replace(/\s+/g, ','));
10
+ return stringToList(locales.replaceAll(/\s+/g, ','));
11
11
  }
12
12
  function stringToList(sList) {
13
13
  return sList
14
- .replace(/[|;]/g, ',')
14
+ .replaceAll(/[|;]/g, ',')
15
15
  .split(',')
16
16
  .map((s) => s.trim())
17
17
  .filter((s) => !!s);
@@ -31,7 +31,7 @@ export function normalizeLanguageId(langId) {
31
31
  const _normalizeLocale = memorizer(__normalizeLocale);
32
32
  function __normalizeLocale(locale) {
33
33
  const locales = localesToList(locale);
34
- return new Set(locales.map((locale) => locale.toLowerCase().replace(/[^a-z]/g, '')));
34
+ return new Set(locales.map((locale) => locale.toLowerCase().replaceAll(/[^a-z]/g, '')));
35
35
  }
36
36
  export function normalizeLocale(locale) {
37
37
  locale = typeof locale === 'string' ? locale : locale.join(',');
@@ -1,4 +1,3 @@
1
- import { checkFilenameMatchesExcludeGlob } from '../globs/checkFilenameMatchesGlob.js';
2
1
  /**
3
2
  * @param filename - filename
4
3
  * @param globs - globs
@@ -6,5 +5,5 @@ import { checkFilenameMatchesExcludeGlob } from '../globs/checkFilenameMatchesGl
6
5
  * @deprecated true
7
6
  * @deprecationMessage No longer actively supported. Use package: `cspell-glob`.
8
7
  */
9
- export declare const checkFilenameMatchesGlob: typeof checkFilenameMatchesExcludeGlob;
8
+ export { checkFilenameMatchesExcludeGlob as checkFilenameMatchesGlob } from '../globs/checkFilenameMatchesGlob.js';
10
9
  //# sourceMappingURL=checkFilenameMatchesGlob.d.ts.map
@@ -1,4 +1,3 @@
1
- import { checkFilenameMatchesExcludeGlob } from '../globs/checkFilenameMatchesGlob.js';
2
1
  /**
3
2
  * @param filename - filename
4
3
  * @param globs - globs
@@ -6,5 +5,5 @@ import { checkFilenameMatchesExcludeGlob } from '../globs/checkFilenameMatchesGl
6
5
  * @deprecated true
7
6
  * @deprecationMessage No longer actively supported. Use package: `cspell-glob`.
8
7
  */
9
- export const checkFilenameMatchesGlob = checkFilenameMatchesExcludeGlob;
8
+ export { checkFilenameMatchesExcludeGlob as checkFilenameMatchesGlob } from '../globs/checkFilenameMatchesGlob.js';
10
9
  //# sourceMappingURL=checkFilenameMatchesGlob.js.map
@@ -1,5 +1,5 @@
1
- import * as fs from 'fs';
2
- import * as Path from 'path';
1
+ import * as fs from 'node:fs';
2
+ import * as Path from 'node:path';
3
3
  import { toError } from '../util/errors.js';
4
4
  import { clean } from '../util/util.js';
5
5
  import { readRawSettings } from './Controller/configLoader/index.js';
@@ -25,7 +25,7 @@ function isString(s) {
25
25
  }
26
26
  export async function addPathsToGlobalImports(paths) {
27
27
  const resolvedSettings = await Promise.all(paths.map(resolveSettings));
28
- const hasError = resolvedSettings.filter((r) => !!r.error).length > 0;
28
+ const hasError = resolvedSettings.some((r) => !!r.error);
29
29
  if (hasError) {
30
30
  return {
31
31
  success: false,
@@ -134,7 +134,7 @@ function findPackageForCSpellConfig(pathToConfig) {
134
134
  name: pkg['name'],
135
135
  };
136
136
  }
137
- catch (e) {
137
+ catch {
138
138
  return undefined;
139
139
  }
140
140
  }
@@ -25,7 +25,7 @@ export function mergeList(left, right) {
25
25
  return right;
26
26
  if (!right.length)
27
27
  return left;
28
- const result = cacheMergeLists.get(left, right, (left, right) => left.concat(right));
28
+ const result = cacheMergeLists.get(left, right, (left, right) => [...left, ...right]);
29
29
  Object.freeze(left);
30
30
  Object.freeze(right);
31
31
  Object.freeze(result);
@@ -7,7 +7,7 @@ import { AutoResolveWeakCache, AutoResolveWeakWeakCache } from '../../util/AutoR
7
7
  import { toError } from '../../util/errors.js';
8
8
  import { SimpleCache } from '../../util/simpleCache.js';
9
9
  import { SpellingDictionaryLoadError } from '../SpellingDictionaryError.js';
10
- const MAX_AGE = 10000;
10
+ const MAX_AGE = 10_000;
11
11
  const loaders = {
12
12
  S: loadSimpleWordList,
13
13
  C: legacyWordList,
@@ -109,13 +109,14 @@ export class DictionaryLoader {
109
109
  loadingState: LoadingState.Loading,
110
110
  sig,
111
111
  };
112
- // eslint-disable-next-line promise/catch-or-return
113
- pending.then(([dictionary, stat]) => {
112
+ pending
113
+ .then(([dictionary, stat]) => {
114
114
  entry.stat = stat;
115
115
  entry.dictionary = dictionary;
116
116
  entry.loadingState = LoadingState.Loaded;
117
117
  return;
118
- });
118
+ })
119
+ .catch(() => undefined);
119
120
  return entry;
120
121
  }
121
122
  getStat(uri) {
@@ -141,7 +142,7 @@ export class DictionaryLoader {
141
142
  const path = def.path;
142
143
  const loaderType = determineType(toFileURL(path), def);
143
144
  const optValues = importantOptionKeys.map((k) => def[k]?.toString() || '');
144
- const parts = [path, loaderType].concat(optValues);
145
+ const parts = [path, loaderType, ...optValues];
145
146
  return parts.join('|');
146
147
  }
147
148
  }
@@ -178,7 +179,7 @@ async function legacyWordList(reader, filename, options) {
178
179
  function _legacyWordListSync(lines, filename, options) {
179
180
  const words = pipe(lines,
180
181
  // Remove comments
181
- opMap((line) => line.replace(/#.*/g, '')),
182
+ opMap((line) => line.replaceAll(/#.*/g, '')),
182
183
  // Split on everything else
183
184
  opConcatMap((line) => line.split(/[^\w\p{L}\p{M}'’]+/gu)), opFilter((word) => !!word));
184
185
  return createSpellingDictionary(words, options.name, filename.toString(), options);
@@ -190,7 +191,7 @@ async function wordsPerLineWordList(reader, filename, options) {
190
191
  function _wordsPerLineWordList(lines, filename, options) {
191
192
  const words = pipe(lines,
192
193
  // Remove comments
193
- opMap((line) => line.replace(/#.*/g, '')),
194
+ opMap((line) => line.replaceAll(/#.*/g, '')),
194
195
  // Split on everything else
195
196
  opConcatMap((line) => line.split(/\s+/gu)), opFilter((word) => !!word));
196
197
  return createSpellingDictionary(words, options.name, filename, options);
@@ -8,7 +8,7 @@ export class SuggestionCollector {
8
8
  this.minScore = minScore;
9
9
  }
10
10
  get collection() {
11
- return this.results.concat();
11
+ return [...this.results];
12
12
  }
13
13
  get sortedCollection() {
14
14
  return this.collection.sort(compareResults);
@@ -16,16 +16,16 @@ export function mergeFeatures(map, features) {
16
16
  map.append(features);
17
17
  }
18
18
  export function wordToSingleLetterFeatures(word) {
19
- return word.split('').map((a) => [a, 1]);
19
+ return [...word].map((a) => [a, 1]);
20
20
  }
21
21
  export function wordToTwoLetterFeatures(word) {
22
22
  return segmentString(word, 2).map((s) => [s, 1]);
23
23
  }
24
24
  export function segmentString(s, segLen) {
25
25
  const count = Math.max(0, s.length - segLen + 1);
26
- const result = new Array(count);
26
+ const result = [];
27
27
  for (let i = 0; i < count; ++i) {
28
- result[i] = s.substr(i, segLen);
28
+ result[i] = s.slice(i, i + segLen);
29
29
  }
30
30
  return result;
31
31
  }
@@ -18,7 +18,7 @@ export function clearCachedFiles() {
18
18
  function _clearCachedFiles() {
19
19
  // We want to dispatch immediately.
20
20
  dispatchClearCache();
21
- return Promise.all([refreshDictionaryCache(0)]).then(() => undefined);
21
+ return refreshDictionaryCache(0).then(() => undefined);
22
22
  }
23
23
  /**
24
24
  * Sends and event to clear the caches.
@@ -1,17 +1,45 @@
1
- /**
2
- * Event indicating that the cache should be cleared.
3
- */
4
- export declare class ClearCacheEvent extends Event {
5
- constructor();
6
- static eventName: "clear-cache";
7
- }
8
- export type EventNames = typeof ClearCacheEvent.eventName;
9
- export type EventTypes = ClearCacheEvent;
10
- export interface DisposableListener {
1
+ export interface Disposable {
11
2
  dispose(): void;
12
3
  }
13
- export declare function addEventListener(event: EventNames, listener: (event: ClearCacheEvent) => void): DisposableListener;
14
- export declare function dispatchEvent(event: EventTypes): void;
4
+ type EventListener<T, U = unknown> = (e: T) => U;
5
+ export interface EventFn<T, U = unknown> {
6
+ /**
7
+ * A function that represents an event to which you subscribe by calling it with
8
+ * a listener function as argument.
9
+ *
10
+ * @param listener The listener function will be called when the event happens.
11
+ * @returns A disposable which unsubscribes the event listener.
12
+ */
13
+ (listener: (e: T) => U): Disposable;
14
+ }
15
+ export type DisposableListener = Disposable;
16
+ export interface IEventEmitter<T> extends Disposable {
17
+ readonly name: string;
18
+ readonly on: EventFn<T>;
19
+ fire(event: T): Error[] | undefined | void;
20
+ }
21
+ export declare function createEmitter<T>(name: string): IEventEmitter<T>;
22
+ export declare class EventEmitter<T> implements IEventEmitter<T> {
23
+ #private;
24
+ readonly name: string;
25
+ constructor(name: string);
26
+ /**
27
+ * The event listeners can subscribe to.
28
+ */
29
+ readonly on: (listener: EventListener<T>) => Disposable;
30
+ /**
31
+ * Notify all subscribers of the {@link EventEmitter.on event}. Failure
32
+ * of one or more listener will not fail this function call.
33
+ *
34
+ * @param data The event object.
35
+ */
36
+ fire(event: T): undefined | Error[];
37
+ /**
38
+ * Dispose this object and free resources.
39
+ */
40
+ readonly dispose: () => void;
41
+ }
15
42
  export declare function onClearCache(listener: () => void): DisposableListener;
16
43
  export declare function dispatchClearCache(): void;
44
+ export {};
17
45
  //# sourceMappingURL=events.d.ts.map
@@ -1,28 +1,64 @@
1
+ import { toError } from '../util/errors.js';
2
+ export function createEmitter(name) {
3
+ return new EventEmitter(name);
4
+ }
5
+ export class EventEmitter {
6
+ name;
7
+ #listeners = new Set();
8
+ constructor(name) {
9
+ this.name = name;
10
+ }
11
+ /**
12
+ * The event listeners can subscribe to.
13
+ */
14
+ on = (listener) => {
15
+ this.#listeners.add(listener);
16
+ return {
17
+ dispose: () => {
18
+ this.#listeners.delete(listener);
19
+ },
20
+ };
21
+ };
22
+ /**
23
+ * Notify all subscribers of the {@link EventEmitter.on event}. Failure
24
+ * of one or more listener will not fail this function call.
25
+ *
26
+ * @param data The event object.
27
+ */
28
+ fire(event) {
29
+ let errors;
30
+ for (const listener of this.#listeners) {
31
+ try {
32
+ listener(event);
33
+ }
34
+ catch (e) {
35
+ errors = errors ?? [];
36
+ errors.push(toError(e));
37
+ }
38
+ }
39
+ return errors;
40
+ }
41
+ /**
42
+ * Dispose this object and free resources.
43
+ */
44
+ dispose = () => {
45
+ this.#listeners.clear();
46
+ };
47
+ }
1
48
  /**
2
49
  * Event indicating that the cache should be cleared.
3
50
  */
4
- export class ClearCacheEvent extends Event {
51
+ class ClearCacheEvent extends EventEmitter {
5
52
  constructor() {
6
53
  super(ClearCacheEvent.eventName);
7
54
  }
8
55
  static eventName = 'clear-cache';
9
56
  }
10
- const eventEmitter = new EventTarget();
11
- export function addEventListener(event, listener) {
12
- eventEmitter.addEventListener(event, listener);
13
- return {
14
- dispose() {
15
- eventEmitter.removeEventListener(event, listener);
16
- },
17
- };
18
- }
19
- export function dispatchEvent(event) {
20
- eventEmitter.dispatchEvent(event);
21
- }
57
+ const clearCacheEvent = new ClearCacheEvent();
22
58
  export function onClearCache(listener) {
23
- return addEventListener(ClearCacheEvent.eventName, listener);
59
+ return clearCacheEvent.on(listener);
24
60
  }
25
61
  export function dispatchClearCache() {
26
- dispatchEvent(new ClearCacheEvent());
62
+ clearCacheEvent.fire(undefined);
27
63
  }
28
64
  //# sourceMappingURL=events.js.map
@@ -1,3 +1,3 @@
1
- export type { DisposableListener, EventNames, EventTypes } from './events.js';
2
- export { addEventListener, ClearCacheEvent, dispatchClearCache, dispatchEvent, onClearCache } from './events.js';
1
+ export type { DisposableListener } from './events.js';
2
+ export { dispatchClearCache, onClearCache } from './events.js';
3
3
  //# sourceMappingURL=index.d.ts.map
@@ -1,2 +1,2 @@
1
- export { addEventListener, ClearCacheEvent, dispatchClearCache, dispatchEvent, onClearCache } from './events.js';
1
+ export { dispatchClearCache, onClearCache } from './events.js';
2
2
  //# sourceMappingURL=index.js.map
@@ -1,17 +1,22 @@
1
- import * as ExclusionHelper from './exclusionHelper.js';
2
- import * as Link from './Settings/index.link.js';
3
- import * as Text from './util/text.js';
1
+ export { clearCachedFiles, clearCaches } from './clearCachedFiles.js';
4
2
  export type { Document } from './Document/index.js';
5
3
  export { fileToDocument, fileToTextDocument, isBinaryFile } from './Document/index.js';
6
4
  export { ExcludeFilesGlobMap, ExclusionFunction } from './exclusionHelper.js';
5
+ export * as ExclusionHelper from './exclusionHelper.js';
7
6
  export { FeatureFlag, FeatureFlags, getSystemFeatureFlags, UnknownFeatureFlagError } from './FeatureFlags/index.js';
7
+ export type { VFileSystemProvider, VirtualFS } from './fileSystem.js';
8
+ export { FSCapabilityFlags, getVirtualFS } from './fileSystem.js';
9
+ export { getDictionary } from './getDictionary.js';
8
10
  export { getLanguagesForBasename as getLanguageIdsForBaseFilename, getLanguagesForExt } from './LanguageIds.js';
9
11
  export type { CreateTextDocumentParams, TextDocument, TextDocumentLine, TextDocumentRef, } from './Models/TextDocument.js';
10
12
  export { createTextDocument, updateTextDocument } from './Models/TextDocument.js';
13
+ export type { PerfTimer } from './perf/index.js';
14
+ export { createPerfTimer } from './perf/index.js';
11
15
  export { calcOverrideSettings, checkFilenameMatchesGlob, type ConfigurationDependencies, createConfigLoader, currentSettingsFileVersion, defaultConfigFilenames, defaultFileName, ENV_CSPELL_GLOB_ROOT, extractDependencies, extractImportErrors, finalizeSettings, getCachedFileSize, getDefaultBundledSettingsAsync, getDefaultConfigLoader, getDefaultSettings, getGlobalSettings, getGlobalSettingsAsync, getSources, ImportError, type ImportFileRefWithError, loadConfig, loadPnP, mergeInDocSettings, mergeSettings, readRawSettings, readSettings, readSettingsFiles, searchForConfig, sectionCSpell, } from './Settings/index.js';
12
16
  export { defaultFileName as defaultSettingsFilename } from './Settings/index.js';
17
+ export * as Link from './Settings/index.link.js';
13
18
  export { combineTextAndLanguageSettings, combineTextAndLanguageSettings as constructSettingsForText, } from './Settings/TextDocumentSettings.js';
14
- export { determineFinalDocumentSettings, DetermineFinalDocumentSettingsResult, spellCheckDocument, spellCheckFile, SpellCheckFileOptions, SpellCheckFileResult, } from './spellCheckFile.js';
19
+ export { determineFinalDocumentSettings, DetermineFinalDocumentSettingsResult, spellCheckDocument, spellCheckFile, SpellCheckFileOptions, SpellCheckFilePerf, SpellCheckFileResult, } from './spellCheckFile.js';
15
20
  export { CompoundWordsMethod, createSpellingDictionary, createCollection as createSpellingDictionaryCollection, isSpellingDictionaryLoadError, refreshDictionaryCache, SpellingDictionary, SpellingDictionaryCollection, SpellingDictionaryLoadError, SuggestionCollector, SuggestionResult, SuggestOptions, } from './SpellingDictionary/index.js';
16
21
  export type { SuggestedWord, SuggestionOptions, SuggestionsForWordResult } from './suggestions.js';
17
22
  export { SuggestionError, suggestionsForWord, suggestionsForWords } from './suggestions.js';
@@ -20,15 +25,8 @@ export type { TraceOptions, TraceResult, TraceWordResult } from './trace.js';
20
25
  export { traceWords, traceWordsAsync } from './trace.js';
21
26
  export { getLogger, Logger, setLogger } from './util/logger.js';
22
27
  export { resolveFile } from './util/resolveFile.js';
28
+ export * as Text from './util/text.js';
23
29
  export { checkText, checkTextDocument, CheckTextInfo, IncludeExcludeFlag, IncludeExcludeOptions, TextInfoItem, validateText, ValidationIssue, } from './validator.js';
24
30
  export * from '@cspell/cspell-types';
25
31
  export { asyncIterableToArray, readFileText as readFile, readFileTextSync as readFileSync, writeToFile, writeToFileIterable, writeToFileIterableP, } from 'cspell-io';
26
- export { Link, Text };
27
- export { ExclusionHelper };
28
- export { clearCachedFiles, clearCaches } from './clearCachedFiles.js';
29
- export type { VFileSystemProvider, VirtualFS } from './fileSystem.js';
30
- export { FSCapabilityFlags, getVirtualFS } from './fileSystem.js';
31
- export { getDictionary } from './getDictionary.js';
32
- export type { PerfTimer } from './perf/index.js';
33
- export { createPerfTimer } from './perf/index.js';
34
32
  //# sourceMappingURL=index.d.ts.map
package/dist/esm/index.js CHANGED
@@ -1,12 +1,15 @@
1
- import * as ExclusionHelper from './exclusionHelper.js';
2
- import * as Link from './Settings/index.link.js';
3
- import * as Text from './util/text.js';
1
+ export { clearCachedFiles, clearCaches } from './clearCachedFiles.js';
4
2
  export { fileToDocument, fileToTextDocument, isBinaryFile } from './Document/index.js';
3
+ export * as ExclusionHelper from './exclusionHelper.js';
5
4
  export { FeatureFlags, getSystemFeatureFlags, UnknownFeatureFlagError } from './FeatureFlags/index.js';
5
+ export { FSCapabilityFlags, getVirtualFS } from './fileSystem.js';
6
+ export { getDictionary } from './getDictionary.js';
6
7
  export { getLanguagesForBasename as getLanguageIdsForBaseFilename, getLanguagesForExt } from './LanguageIds.js';
7
8
  export { createTextDocument, updateTextDocument } from './Models/TextDocument.js';
9
+ export { createPerfTimer } from './perf/index.js';
8
10
  export { calcOverrideSettings, checkFilenameMatchesGlob, createConfigLoader, currentSettingsFileVersion, defaultConfigFilenames, defaultFileName, ENV_CSPELL_GLOB_ROOT, extractDependencies, extractImportErrors, finalizeSettings, getCachedFileSize, getDefaultBundledSettingsAsync, getDefaultConfigLoader, getDefaultSettings, getGlobalSettings, getGlobalSettingsAsync, getSources, ImportError, loadConfig, loadPnP, mergeInDocSettings, mergeSettings, readRawSettings, readSettings, readSettingsFiles, searchForConfig, sectionCSpell, } from './Settings/index.js';
9
11
  export { defaultFileName as defaultSettingsFilename } from './Settings/index.js';
12
+ export * as Link from './Settings/index.link.js';
10
13
  export { combineTextAndLanguageSettings, combineTextAndLanguageSettings as constructSettingsForText, } from './Settings/TextDocumentSettings.js';
11
14
  export { determineFinalDocumentSettings, spellCheckDocument, spellCheckFile, } from './spellCheckFile.js';
12
15
  export { CompoundWordsMethod, createSpellingDictionary, createCollection as createSpellingDictionaryCollection, isSpellingDictionaryLoadError, refreshDictionaryCache, SpellingDictionaryLoadError, } from './SpellingDictionary/index.js';
@@ -15,13 +18,8 @@ export { DocumentValidator, shouldCheckDocument } from './textValidation/index.j
15
18
  export { traceWords, traceWordsAsync } from './trace.js';
16
19
  export { getLogger, setLogger } from './util/logger.js';
17
20
  export { resolveFile } from './util/resolveFile.js';
21
+ export * as Text from './util/text.js';
18
22
  export { checkText, checkTextDocument, IncludeExcludeFlag, validateText, } from './validator.js';
19
23
  export * from '@cspell/cspell-types';
20
24
  export { asyncIterableToArray, readFileText as readFile, readFileTextSync as readFileSync, writeToFile, writeToFileIterable, writeToFileIterableP, } from 'cspell-io';
21
- export { Link, Text };
22
- export { ExclusionHelper };
23
- export { clearCachedFiles, clearCaches } from './clearCachedFiles.js';
24
- export { FSCapabilityFlags, getVirtualFS } from './fileSystem.js';
25
- export { getDictionary } from './getDictionary.js';
26
- export { createPerfTimer } from './perf/index.js';
27
25
  //# sourceMappingURL=index.js.map
@@ -1,4 +1,4 @@
1
- import assert from 'assert';
1
+ import assert from 'node:assert';
2
2
  import { finalizeSettings, getDefaultSettings, getGlobalSettingsAsync, mergeSettings } from './Settings/index.js';
3
3
  import { calcSettingsForLanguageId, isValidLocaleIntlFormat, normalizeLocaleIntl, } from './Settings/LanguageSettings.js';
4
4
  import { getDictionaryInternal, refreshDictionaryCache } from './SpellingDictionary/index.js';
@@ -1,4 +1,4 @@
1
- import assert from 'assert';
1
+ import assert from 'node:assert';
2
2
  import { resolveDocumentToTextDocument } from '../Document/resolveDocument.js';
3
3
  import { isTextDocument } from '../Models/TextDocument.js';
4
4
  import * as Settings from '../Settings/index.js';
@@ -69,8 +69,7 @@ function genResult(text, issues, includeRanges) {
69
69
  startPos: lastPos,
70
70
  endPos: startPos,
71
71
  flagIE: IncludeExcludeFlag.EXCLUDE,
72
- });
73
- result.push({
72
+ }, {
74
73
  text: text.slice(startPos, endPos),
75
74
  startPos,
76
75
  endPos,
@@ -1,4 +1,4 @@
1
- import * as path from 'path';
1
+ import * as path from 'node:path';
2
2
  import { getLanguagesForBasename } from '../LanguageIds.js';
3
3
  import { calcOverrideSettings, getDefaultSettings, getGlobalSettings, mergeSettings } from '../Settings/index.js';
4
4
  import { combineTextAndLanguageSettings } from '../Settings/TextDocumentSettings.js';
@@ -1,6 +1,6 @@
1
+ import assert from 'node:assert';
1
2
  import { opConcatMap, opMap, pipeSync } from '@cspell/cspell-pipe/sync';
2
3
  import { IssueType } from '@cspell/cspell-types';
3
- import assert from 'assert';
4
4
  import { getGlobMatcherForExcluding } from '../globs/getGlobMatcher.js';
5
5
  import { updateTextDocument } from '../Models/TextDocument.js';
6
6
  import { createPerfTimer } from '../perf/index.js';
@@ -78,6 +78,7 @@ export class DocumentValidator {
78
78
  const uri = this._document.uri;
79
79
  recGlobMatcherTime();
80
80
  const recShouldCheckTime = recordPerfTime(this.perfTiming, '_shouldCheck');
81
+ // eslint-disable-next-line unicorn/prefer-regexp-test
81
82
  const shouldCheck = !matcher.match(uriToFilePath(uri)) && (docSettings.enabled ?? true);
82
83
  recShouldCheckTime();
83
84
  const recFinalizeTime = recordPerfTime(this.perfTiming, '_finalizeSettings');
@@ -206,7 +207,7 @@ export class DocumentValidator {
206
207
  const spellingIssues = forceCheck || this.shouldCheckDocument() ? [...this._checkParsedText(this._parse())] : [];
207
208
  const directiveIssues = this.checkDocumentDirectives();
208
209
  // console.log('Stats: %o', this._preparations.textValidator.lineValidator.dict.stats());
209
- const allIssues = spellingIssues.concat(directiveIssues).sort((a, b) => a.offset - b.offset);
210
+ const allIssues = [...spellingIssues, ...directiveIssues].sort((a, b) => a.offset - b.offset);
210
211
  return allIssues;
211
212
  }
212
213
  finally {
@@ -350,7 +351,7 @@ function sanitizeSuggestion(sug) {
350
351
  async function searchForDocumentConfig(document, defaultConfig, pnpSettings) {
351
352
  const { uri } = document;
352
353
  if (uri.scheme !== 'file')
353
- return Promise.resolve(defaultConfig);
354
+ return defaultConfig;
354
355
  return searchForConfig(uri.toString(), pnpSettings).then((s) => s || defaultConfig);
355
356
  }
356
357
  function mapSug(sug) {
@@ -377,6 +378,7 @@ export async function shouldCheckDocument(doc, options, settings) {
377
378
  const matcher = getGlobMatcherForExcluding(localConfig?.ignorePaths);
378
379
  const docSettings = await determineTextDocumentSettings(doc, config);
379
380
  const uri = doc.uri;
381
+ // eslint-disable-next-line unicorn/prefer-regexp-test
380
382
  return !matcher.match(uriToFilePath(uri)) && (docSettings.enabled ?? true);
381
383
  }
382
384
  return { errors, shouldCheck: await shouldCheck() };
@@ -1,5 +1,5 @@
1
1
  function hasWordCheck(dict, word) {
2
- word = word.includes('\\') ? word.replace(/\\/g, '') : word;
2
+ word = word.includes('\\') ? word.replaceAll('\\', '') : word;
3
3
  return dict.has(word);
4
4
  }
5
5
  export function isWordValidWithEscapeRetry(dict, wo, line) {
@@ -12,7 +12,7 @@ export function traceWord(word, dictCollection, config) {
12
12
  const wfSplits = splits.words.map((s) => ({ word: s.text, found: s.isFound }));
13
13
  const unique = uniqueFn((w) => w.word + '|' + w.found);
14
14
  const wsFound = { word, found: dictCollection.has(word, opts) };
15
- const wordSplits = wfSplits.find((s) => s.word === word) ? wfSplits : [wsFound, ...wfSplits];
15
+ const wordSplits = wfSplits.some((s) => s.word === word) ? wfSplits : [wsFound, ...wfSplits];
16
16
  const traces = wordSplits
17
17
  .filter(unique)
18
18
  .map((s) => s.word)
@@ -17,7 +17,7 @@ export async function validateText(text, settings, options = {}) {
17
17
  const validationIssues = options.validateDirectives || finalSettings.validateDirectives
18
18
  ? validateInDocumentSettings(text, settings)
19
19
  : [];
20
- const issues = spellingIssues.concat(mapValidationIssues(text, validationIssues));
20
+ const issues = [...spellingIssues, ...mapValidationIssues(text, validationIssues)];
21
21
  if (!options.generateSuggestions) {
22
22
  return issues;
23
23
  }
package/dist/esm/trace.js CHANGED
@@ -22,9 +22,10 @@ export async function* traceWordsAsync(words, settings, options) {
22
22
  }));
23
23
  const withLanguageId = calcSettingsForLanguageId(withLocale, languageId ?? withLocale.languageId ?? 'plaintext');
24
24
  const settings = finalizeSettings(withLanguageId);
25
- const dictionaries = (settings.dictionaries || [])
26
- .concat((settings.dictionaryDefinitions || []).map((d) => d.name))
27
- .filter(util.uniqueFn);
25
+ const dictionaries = [
26
+ ...(settings.dictionaries || []),
27
+ ...(settings.dictionaryDefinitions || []).map((d) => d.name),
28
+ ].filter(util.uniqueFn);
28
29
  const dictSettings = toInternalSettings({ ...settings, dictionaries });
29
30
  const dictBase = await getDictionaryInternal(settings);
30
31
  const dicts = await getDictionaryInternal(dictSettings);
@@ -1,4 +1,4 @@
1
- import assert from 'assert';
1
+ import assert from 'node:assert';
2
2
  import { isArrayEqual } from './util.js';
3
3
  export class AutoResolveLRUCache {
4
4
  maxSize;
@@ -10,7 +10,7 @@ export declare class MinHeapQueue<T> implements IterableIterator<T> {
10
10
  add(t: T): MinHeapQueue<T>;
11
11
  get length(): number;
12
12
  dequeue(): T | undefined;
13
- concat(i: Iterable<T>): MinHeapQueue<T>;
13
+ append(i: Iterable<T>): MinHeapQueue<T>;
14
14
  next(): IteratorResult<T>;
15
15
  [Symbol.iterator](): IterableIterator<T>;
16
16
  clone(): MinHeapQueue<T>;
@@ -35,10 +35,8 @@ function takeFromHeap(t, compare) {
35
35
  i = k;
36
36
  j = i * 2 + 1;
37
37
  }
38
- if (j === m) {
39
- if (compare(t[i], t[j]) > 0) {
40
- swap(t, i, j);
41
- }
38
+ if (j === m && compare(t[i], t[j]) > 0) {
39
+ swap(t, i, j);
42
40
  }
43
41
  return result;
44
42
  }
@@ -61,7 +59,7 @@ export class MinHeapQueue {
61
59
  dequeue() {
62
60
  return takeFromHeap(this.values, this.compare);
63
61
  }
64
- concat(i) {
62
+ append(i) {
65
63
  for (const v of i) {
66
64
  this.add(v);
67
65
  }
@@ -83,7 +81,7 @@ export class MinHeapQueue {
83
81
  }
84
82
  clone() {
85
83
  const clone = new MinHeapQueue(this.compare);
86
- clone.values = this.values.concat();
84
+ clone.values = [...this.values];
87
85
  return clone;
88
86
  }
89
87
  }
@@ -14,7 +14,7 @@ export declare class PairingHeap<T> implements IterableIterator<T> {
14
14
  constructor(compare: CompareFn<T>);
15
15
  add(v: T): this;
16
16
  dequeue(): T | undefined;
17
- concat(i: Iterable<T>): this;
17
+ append(i: Iterable<T>): this;
18
18
  next(): IteratorResult<T>;
19
19
  peek(): T | undefined;
20
20
  [Symbol.iterator](): IterableIterator<T>;
@@ -16,7 +16,7 @@ export class PairingHeap {
16
16
  return undefined;
17
17
  return n.value;
18
18
  }
19
- concat(i) {
19
+ append(i) {
20
20
  for (const v of i) {
21
21
  this.add(v);
22
22
  }
@@ -1,4 +1,4 @@
1
- import assert from 'assert';
1
+ import assert from 'node:assert';
2
2
  /**
3
3
  * Extract a substring from a TextMap.
4
4
  * @param textMap - A text range with an optional map
@@ -24,7 +24,7 @@ export function extractTextMapRangeOrigin(textMap, extractRange) {
24
24
  const endDiff = srcTxt.length - mapEndDst;
25
25
  const head = !srcMap[0] && !srcMap[1] ? [] : [0, 0];
26
26
  const tail = [mapEndSrc + endDiff, mapEndDst + endDiff];
27
- const sMap = head.concat(srcMap).concat(tail);
27
+ const sMap = [...head, ...srcMap, ...tail];
28
28
  let idx = 0;
29
29
  for (; idx < sMap.length && a >= sMap[idx]; idx += 2) {
30
30
  // empty
@@ -1,4 +1,4 @@
1
- import assert from 'assert';
1
+ import assert from 'node:assert';
2
2
  import { URI, Utils } from 'vscode-uri';
3
3
  const isFile = /^(?:[a-zA-Z]:|[/\\])/;
4
4
  const isPossibleUri = /\w:\/\//;
@@ -77,7 +77,7 @@ class UriImpl extends URI {
77
77
  }
78
78
  toString() {
79
79
  // if (this.scheme !== 'stdin') return super.toString(true);
80
- const path = encodeURI(this.path || '').replace(/[#?]/g, (c) => `%${c.charCodeAt(0).toString(16)}`);
80
+ const path = encodeURI(this.path || '').replaceAll(/[#?]/g, (c) => `%${(c.codePointAt(0) || 0).toString(16)}`);
81
81
  const base = `${this.scheme}://${this.authority || ''}${path}`;
82
82
  const query = (this.query && `?${this.query}`) || '';
83
83
  const fragment = (this.fragment && `#${this.fragment}`) || '';
@@ -123,7 +123,7 @@ class UriImpl extends URI {
123
123
  }
124
124
  }
125
125
  function normalizeFilePath(path) {
126
- return normalizeDriveLetter(path.replace(/\\/g, '/'));
126
+ return normalizeDriveLetter(path.replaceAll('\\', '/'));
127
127
  }
128
128
  function parseStdinUri(uri) {
129
129
  assert(uri.startsWith(STDIN_PROTOCOL));
@@ -1,4 +1,4 @@
1
- import { format } from 'util';
1
+ import { format } from 'node:util';
2
2
  function getTypeOf(t) {
3
3
  return typeof t;
4
4
  }
@@ -2,13 +2,8 @@ import { toFileURL } from 'cspell-io';
2
2
  import { readTextFile } from '../fileSystem.js';
3
3
  import { toIterableIterator } from './iterableIteratorLib.js';
4
4
  export async function readLines(url, encoding = 'utf8') {
5
- try {
6
- url = toFileURL(url);
7
- const content = await readTextFile(url, encoding);
8
- return toIterableIterator(content.split(/\r?\n/g));
9
- }
10
- catch (e) {
11
- return Promise.reject(e);
12
- }
5
+ url = toFileURL(url);
6
+ const content = await readTextFile(url, encoding);
7
+ return toIterableIterator(content.split(/\r?\n/g));
13
8
  }
14
9
  //# sourceMappingURL=fileReader.js.map
@@ -1,6 +1,6 @@
1
1
  import { stat } from 'node:fs/promises';
2
- import path from 'path';
3
- import { fileURLToPath } from 'url';
2
+ import path from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
4
  export async function findUp(name, options = {}) {
5
5
  const { cwd = process.cwd(), type: entryType = 'file', stopAt } = options;
6
6
  let dir = path.resolve(toDirPath(cwd));
@@ -4,6 +4,6 @@
4
4
  * @returns - the escaped string.
5
5
  */
6
6
  export function escapeRegEx(s) {
7
- return s.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&').replace(/-/g, '\\x2d');
7
+ return s.replaceAll(/[|\\{}()[\]^$+*?.]/g, '\\$&').replaceAll('-', '\\x2d');
8
8
  }
9
9
  //# sourceMappingURL=regexHelper.js.map
@@ -10,11 +10,11 @@ export function createMapper(repMap) {
10
10
  .map((s) => {
11
11
  try {
12
12
  // fix up any nested ()
13
- const r = s.match(/\(/) ? s.replace(/\((?=.*\))/g, '(?:').replace(/\(\?:\?/g, '(?') : s;
13
+ const r = /\(/.test(s) ? s.replaceAll(/\((?=.*\))/g, '(?:').replaceAll('(?:?', '(?') : s;
14
14
  new RegExp(r);
15
15
  s = r;
16
16
  }
17
- catch (err) {
17
+ catch {
18
18
  return escapeRegEx(s);
19
19
  }
20
20
  return s;
@@ -1,11 +1,11 @@
1
1
  import { createRequire } from 'node:module';
2
+ import * as os from 'node:os';
3
+ import * as path from 'node:path';
2
4
  import { pathToFileURL } from 'node:url';
5
+ import { fileURLToPath } from 'node:url';
3
6
  import { resolveGlobal } from '@cspell/cspell-resolver';
4
7
  import { importResolveModuleName } from '@cspell/dynamic-import';
5
- import * as os from 'os';
6
- import * as path from 'path';
7
8
  import resolveFrom from 'resolve-from';
8
- import { fileURLToPath } from 'url';
9
9
  import { srcDirectory } from '../../lib-cjs/pkg-info.cjs';
10
10
  import { getFileSystem } from '../fileSystem.js';
11
11
  import { envToTemplateVars, replaceTemplate } from './templates.js';
@@ -73,7 +73,7 @@ export class FileResolver {
73
73
  const s = await this.fs.stat(file);
74
74
  return s.isFile() || s.isUnknown();
75
75
  }
76
- catch (error) {
76
+ catch {
77
77
  return false;
78
78
  }
79
79
  }
@@ -135,16 +135,17 @@ export class FileResolver {
135
135
  const r = require.resolve(filename);
136
136
  return { filename: r, relativeTo: rel.toString(), found: true, method: 'tryCreateRequire' };
137
137
  }
138
- catch (_) {
138
+ catch {
139
139
  return undefined;
140
140
  }
141
141
  };
142
142
  tryNodeResolveDefaultPaths = (filename) => {
143
143
  try {
144
+ // eslint-disable-next-line unicorn/prefer-module
144
145
  const r = require.resolve(filename);
145
146
  return { filename: r, relativeTo: undefined, found: true, method: 'tryNodeResolveDefaultPaths' };
146
147
  }
147
- catch (_) {
148
+ catch {
148
149
  return undefined;
149
150
  }
150
151
  };
@@ -167,10 +168,11 @@ export class FileResolver {
167
168
  }
168
169
  const paths = calcPaths(path.resolve(relativeToPath));
169
170
  try {
171
+ // eslint-disable-next-line unicorn/prefer-module
170
172
  const r = require.resolve(filename, { paths });
171
173
  return { filename: r, relativeTo: relativeToPath, found: true, method: 'tryNodeRequireResolve' };
172
174
  }
173
- catch (_) {
175
+ catch {
174
176
  return undefined;
175
177
  }
176
178
  };
@@ -180,7 +182,7 @@ export class FileResolver {
180
182
  const resolved = fileURLToPath(importResolveModuleName(filename, paths));
181
183
  return { filename: resolved, relativeTo: relativeTo.toString(), found: true, method: 'tryImportResolve' };
182
184
  }
183
- catch (_) {
185
+ catch {
184
186
  return undefined;
185
187
  }
186
188
  };
@@ -218,7 +220,7 @@ export class FileResolver {
218
220
  method: 'tryResolveFrom',
219
221
  };
220
222
  }
221
- catch (error) {
223
+ catch {
222
224
  // Failed to resolve a relative module request
223
225
  return undefined;
224
226
  }
@@ -83,10 +83,10 @@ export function extractWordsFromCodeTextOffset(textOffset) {
83
83
  return pipe(extractWordsFromTextOffset(textOffset), opConcatMap(splitCamelCaseWordWithOffset));
84
84
  }
85
85
  export function isUpperCase(word) {
86
- return !!word.match(regExAllUpper);
86
+ return regExAllUpper.test(word);
87
87
  }
88
88
  export function isLowerCase(word) {
89
- return !!word.match(regExAllLower);
89
+ return regExAllLower.test(word);
90
90
  }
91
91
  export function isFirstCharacterUpper(word) {
92
92
  return isUpperCase(word.slice(0, 1));
@@ -107,13 +107,13 @@ export function camelToSnake(word) {
107
107
  return splitCamelCaseWord(word).join('_').toLowerCase();
108
108
  }
109
109
  export function matchCase(example, word) {
110
- if (example.match(regExFirstUpper)) {
110
+ if (regExFirstUpper.test(example)) {
111
111
  return word.slice(0, 1).toUpperCase() + word.slice(1).toLowerCase();
112
112
  }
113
- if (example.match(regExAllLower)) {
113
+ if (regExAllLower.test(example)) {
114
114
  return word.toLowerCase();
115
115
  }
116
- if (example.match(regExAllUpper)) {
116
+ if (regExAllUpper.test(example)) {
117
117
  return word.toUpperCase();
118
118
  }
119
119
  if (isFirstCharacterUpper(example)) {
@@ -30,12 +30,12 @@ export function stringToRegExp(pattern, defaultFlags = 'gimu', forceFlags = 'g')
30
30
  if (pat) {
31
31
  const regPattern = flag.includes('x') ? removeVerboseFromRegExp(pat) : pat;
32
32
  // Make sure the flags are unique.
33
- const flags = [...new Set(forceFlags + flag)].join('').replace(/[^gimuy]/g, '');
33
+ const flags = [...new Set(forceFlags + flag)].join('').replaceAll(/[^gimuy]/g, '');
34
34
  const regex = new RegExp(regPattern, flags);
35
35
  return regex;
36
36
  }
37
37
  }
38
- catch (e) {
38
+ catch {
39
39
  /* empty */
40
40
  }
41
41
  return undefined;
@@ -1,5 +1,5 @@
1
- import path from 'path';
2
- import { fileURLToPath, pathToFileURL } from 'url';
1
+ import path from 'node:path';
2
+ import { fileURLToPath, pathToFileURL } from 'node:url';
3
3
  import { srcDirectory } from '../../lib-cjs/pkg-info.cjs';
4
4
  const isUrlRegExp = /^(?:[\w][\w-]+:\/|data:|untitled:)/i;
5
5
  /**
@@ -268,7 +268,7 @@ function splitIntoWords(lineSeg, breaks, has) {
268
268
  let maxCost = lineSeg.relEnd - lineSeg.relStart;
269
269
  const candidates = new PairingHeap(compare);
270
270
  const text = lineSeg.line.text;
271
- candidates.concat(makeCandidates(undefined, lineSeg.relStart, 0, 0));
271
+ candidates.append(makeCandidates(undefined, lineSeg.relStart, 0, 0));
272
272
  let attempts = 0;
273
273
  let bestPath;
274
274
  while (maxCost && candidates.length && attempts++ < maxAttempts) {
@@ -296,13 +296,13 @@ function splitIntoWords(lineSeg, breaks, has) {
296
296
  }
297
297
  else if (best.c < maxCost) {
298
298
  const c = makeCandidates(t ? best : best.p, j, best.bi + 1, best.c);
299
- candidates.concat(c);
299
+ candidates.append(c);
300
300
  }
301
301
  }
302
302
  else {
303
303
  // It is a pass through
304
304
  const c = makeCandidates(best.p, best.i, best.bi + 1, best.c);
305
- candidates.concat(c);
305
+ candidates.append(c);
306
306
  if (!c.length) {
307
307
  const t = maxIndex > best.i ? toTextOffset(text.slice(best.i, maxIndex), best.i) : undefined;
308
308
  const cost = !t || t.isFound ? 0 : t.text.length;
@@ -322,7 +322,7 @@ function splitIntoWords(lineSeg, breaks, has) {
322
322
  return pathToWords(bestPath);
323
323
  }
324
324
  function mergeSortedBreaks(...maps) {
325
- return [].concat(...maps).sort((a, b) => a.offset - b.offset);
325
+ return maps.flat().sort((a, b) => a.offset - b.offset);
326
326
  }
327
327
  export const __testing__ = {
328
328
  generateWordBreaks,
@@ -17,7 +17,7 @@ export function splitLine(line) {
17
17
  return [...Text.extractWordsFromText(line)].map(({ text }) => text);
18
18
  }
19
19
  export function splitCodeWords(words) {
20
- return words.map(Text.splitCamelCaseWord).flatMap((a) => a);
20
+ return words.flatMap(Text.splitCamelCaseWord);
21
21
  }
22
22
  export function splitLineIntoCodeWords(line) {
23
23
  const asMultiWord = regExpWordsWithSpaces.test(line) ? [line] : [];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cspell-lib",
3
- "version": "8.7.0",
3
+ "version": "8.8.0",
4
4
  "description": "A library of useful functions used across various cspell tools.",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -59,21 +59,21 @@
59
59
  },
60
60
  "homepage": "https://github.com/streetsidesoftware/cspell#readme",
61
61
  "dependencies": {
62
- "@cspell/cspell-bundled-dicts": "8.7.0",
63
- "@cspell/cspell-pipe": "8.7.0",
64
- "@cspell/cspell-resolver": "8.7.0",
65
- "@cspell/cspell-types": "8.7.0",
66
- "@cspell/dynamic-import": "8.7.0",
67
- "@cspell/strong-weak-map": "8.7.0",
62
+ "@cspell/cspell-bundled-dicts": "8.8.0",
63
+ "@cspell/cspell-pipe": "8.8.0",
64
+ "@cspell/cspell-resolver": "8.8.0",
65
+ "@cspell/cspell-types": "8.8.0",
66
+ "@cspell/dynamic-import": "8.8.0",
67
+ "@cspell/strong-weak-map": "8.8.0",
68
68
  "clear-module": "^4.1.2",
69
69
  "comment-json": "^4.2.3",
70
70
  "configstore": "^6.0.0",
71
- "cspell-config-lib": "8.7.0",
72
- "cspell-dictionary": "8.7.0",
73
- "cspell-glob": "8.7.0",
74
- "cspell-grammar": "8.7.0",
75
- "cspell-io": "8.7.0",
76
- "cspell-trie-lib": "8.7.0",
71
+ "cspell-config-lib": "8.8.0",
72
+ "cspell-dictionary": "8.8.0",
73
+ "cspell-glob": "8.8.0",
74
+ "cspell-grammar": "8.8.0",
75
+ "cspell-io": "8.8.0",
76
+ "cspell-trie-lib": "8.8.0",
77
77
  "fast-equals": "^5.0.1",
78
78
  "gensequence": "^7.0.0",
79
79
  "import-fresh": "^3.3.0",
@@ -98,5 +98,5 @@
98
98
  "leaked-handles": "^5.2.0",
99
99
  "lorem-ipsum": "^2.0.8"
100
100
  },
101
- "gitHead": "5318079ed11fe77e981287ecf1c40d6f28dd91ed"
101
+ "gitHead": "a42bce675c00cb2d51809b3ae3894119ea4f5ce7"
102
102
  }